From 185c59507abfa0262c13211b37a1b358bf54c3d5 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 22 Oct 2026 02:32:53 +0000 Subject: [PATCH 01/15] feat(nodelab): author pinned host-admitted workflows --- .../examples/nodelab_host.rs | 187 ++++++++++++ .../src/custom_nodes.rs | 2 + .../src/custom_nodes/authoring.rs | 37 +++ .../src/graph/connection_insert.rs | 7 + .../src/graph/connection_intent.rs | 1 + .../src/graph/session.rs | 16 +- .../src/graph/session_connection_api.rs | 21 +- .../src/graph/session_contract.rs | 22 +- .../src/graph/session_node_api.rs | 45 +++ .../src/graph/session_state.rs | 18 +- .../src/workflow.rs | 1 + .../src/workflow/custom_node_authoring_api.rs | 112 ++++++++ .../src/workflow/service_config.rs | 20 +- .../src/workflow/tests/custom_nodes.rs | 269 ++++++++++++++++++ docs/custom-nodes.md | 48 +++- .../evidence/nodelab-authoring/browser.log.gz | Bin 0 -> 441 bytes .../native-unavailable.log.gz | Bin 0 -> 2190 bytes .../nodelab-authoring/qualification.json | 54 ++++ .../execution-ledger.md | 33 +++ .../issues.md | 4 +- .../plan.md | 58 ++++ scripts/README.md | 17 ++ scripts/check-nodelab-browser.mjs | 172 +++++++++++ src-tauri/src/app_setup.rs | 3 + src-tauri/src/workflow/commands.rs | 34 +++ src/components/workbench/NodeLabPage.svelte | 89 +++++- src/components/workbench/nodeLabController.ts | 86 ++++++ .../workbench/nodeLabPresenters.test.ts | 15 +- src/components/workbench/nodeLabPresenters.ts | 15 +- .../workflow/customNodeAuthoring.test.ts | 143 ++++++++++ src/services/workflow/customNodeAuthoring.ts | 184 ++++++++++++ 31 files changed, 1647 insertions(+), 66 deletions(-) create mode 100644 crates/pantograph-workflow-service/examples/nodelab_host.rs create mode 100644 crates/pantograph-workflow-service/src/custom_nodes/authoring.rs create mode 100644 crates/pantograph-workflow-service/src/workflow/custom_node_authoring_api.rs create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/native-unavailable.log.gz create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json create mode 100644 scripts/check-nodelab-browser.mjs create mode 100644 src/components/workbench/nodeLabController.ts create mode 100644 src/services/workflow/customNodeAuthoring.test.ts create mode 100644 src/services/workflow/customNodeAuthoring.ts diff --git a/crates/pantograph-workflow-service/examples/nodelab_host.rs b/crates/pantograph-workflow-service/examples/nodelab_host.rs new file mode 100644 index 000000000..c1b4d82c1 --- /dev/null +++ b/crates/pantograph-workflow-service/examples/nodelab_host.rs @@ -0,0 +1,187 @@ +//! Isolated stdio host for NodeLab authoring qualification. No runtime code loader. +//! A verifier supplies the loopback HTTP transport; EOF drops the temporary store. +use async_trait::async_trait; +use node_engine::{Context, ExecutorExtensions, NodeExecutor}; +use pantograph_node_contracts::{ + NodeAuthoringMetadata, NodeCategory, NodeExecutionSemantics, NodeTypeContract, PortContract, + PortRequirement, PortValueType, +}; +use pantograph_workflow_service::{ + custom_nodes::{authoring::CustomNodeDraftRequest, CustomNodeCatalog, TrustedCustomNode}, + *, +}; +use serde::{de::DeserializeOwned, Serialize}; +use serde_json::{json, Value}; +use std::{ + collections::HashMap, + io::{BufRead, Write}, + sync::Arc, +}; + +struct Uppercase; +#[async_trait] +impl NodeExecutor for Uppercase { + async fn execute( + &self, + _: &str, + inputs: HashMap, + _: &Context, + _: &ExecutorExtensions, + ) -> node_engine::Result> { + Ok(HashMap::from([( + "output".into(), + json!(inputs["input"] + .as_str() + .ok_or_else(|| node_engine::NodeEngineError::ExecutionFailed( + "string input required".into() + ))? + .to_uppercase()), + )])) + } +} +fn catalog() -> Result, Box> { + let mut output = PortContract::output("output".parse()?, "Output", PortValueType::String); + output.requirement = PortRequirement::Required; + let contract = NodeTypeContract { + node_type: "host-uppercase".parse()?, + category: NodeCategory::Processing, + label: "Host uppercase".into(), + description: "Pure string transform compiled into this isolated Rust host".into(), + inputs: vec![PortContract::input( + "input".parse()?, + "Input", + PortValueType::String, + PortRequirement::Required, + )], + outputs: vec![output], + execution_semantics: NodeExecutionSemantics::Batch, + capability_requirements: vec![], + inference_tasks: vec![], + authoring: NodeAuthoringMetadata::default(), + contract_version: Some("1.0.0".into()), + contract_digest: None, + }; + let digest = |text: &str| format!("blake3:{}", blake3::hash(text.as_bytes())); + Ok(Arc::new(CustomNodeCatalog::try_new(vec![ + TrustedCustomNode::admit( + contract, + digest("nodelab_host.rs uppercase v1"), + digest("isolated Rust authoring host v1"), + Arc::new(Uppercase), + )?, + ])?)) +} +fn decode(value: Value) -> Result { + serde_json::from_value(value).map_err(|e| WorkflowServiceError::InvalidRequest(e.to_string())) +} +fn encode(value: impl Serialize) -> Result { + serde_json::to_value(value).map_err(|e| WorkflowServiceError::Internal(e.to_string())) +} +fn string(args: &Value, name: &str) -> Result { + args[name] + .as_str() + .map(str::to_owned) + .ok_or_else(|| WorkflowServiceError::InvalidRequest(format!("{name} is required"))) +} +async fn dispatch( + service: &WorkflowService, + store: &FileSystemWorkflowGraphStore, + command: &str, + args: Value, +) -> Result { + let edit = || -> Result { + Ok(WorkflowGraphEditSessionGraphRequest { + session_id: string(&args, "executionId")?, + }) + }; + match command { + "get_custom_node_authoring_catalog" => encode(service.custom_node_authoring_catalog()), + "create_custom_node_draft" => encode( + service + .create_custom_node_draft(decode::( + args["request"].clone(), + )?) + .await?, + ), + "get_node_lab_draft" => encode( + service + .workflow_graph_get_edit_session_graph(edit()?) + .await?, + ), + "create_workflow_execution_session" => encode( + service + .workflow_graph_create_edit_session(WorkflowGraphEditSessionCreateRequest { + graph: decode(args["graph"].clone())?, + workflow_id: args["workflowId"].as_str().map(str::to_owned), + }) + .await?, + ), + "update_node_data" => encode( + service + .workflow_graph_update_node_data(WorkflowGraphUpdateNodeDataRequest { + session_id: string(&args, "executionId")?, + node_id: string(&args, "nodeId")?, + data: args["data"].clone(), + }) + .await?, + ), + "save_workflow" => encode( + service + .workflow_graph_save( + store, + WorkflowGraphSaveRequest { + name: string(&args, "name")?, + graph: decode(args["graph"].clone())?, + }, + )? + .path, + ), + "load_workflow" => encode(service.workflow_graph_load( + store, + WorkflowGraphLoadRequest { + path: string(&args, "path")?, + }, + )?), + "remove_execution" => { + service + .workflow_graph_close_edit_session(WorkflowGraphEditSessionCloseRequest { + session_id: edit()?.session_id, + }) + .await?; + Ok(Value::Null) + } + _ => Err(WorkflowServiceError::CapabilityViolation( + "unsupported authoring host command".into(), + )), + } +} +#[tokio::main] +async fn main() -> Result<(), Box> { + let directory = tempfile::tempdir()?; + let store = FileSystemWorkflowGraphStore::new(directory.path()); + let service = if std::env::args().any(|arg| arg == "--empty-catalog") { + WorkflowService::new() + } else { + WorkflowService::with_trusted_custom_nodes(catalog()?) + }; + for line in std::io::stdin().lock().lines() { + let result = match serde_json::from_str::(&line?) { + Ok(request) => match request["command"].as_str() { + Some(command) => dispatch(&service, &store, command, request["args"].clone()).await, + None => Err(WorkflowServiceError::InvalidRequest( + "command is required".into(), + )), + }, + Err(error) => Err(WorkflowServiceError::InvalidRequest(error.to_string())), + }; + let response = match result { + Ok(value) => json!({"ok": true, "value": value}), + Err(error) => { + json!({"ok": false, "error": serde_json::from_str::(&error.to_envelope_json())?}) + } + }; + println!("{}", serde_json::to_string(&response)?); + std::io::stdout().flush()?; + } + Ok(()) +} diff --git a/crates/pantograph-workflow-service/src/custom_nodes.rs b/crates/pantograph-workflow-service/src/custom_nodes.rs index a6f8bfca3..90b245b5e 100644 --- a/crates/pantograph-workflow-service/src/custom_nodes.rs +++ b/crates/pantograph-workflow-service/src/custom_nodes.rs @@ -355,3 +355,5 @@ pub(crate) fn validate_payload( #[cfg(test)] pub(crate) mod tests; + +pub mod authoring; diff --git a/crates/pantograph-workflow-service/src/custom_nodes/authoring.rs b/crates/pantograph-workflow-service/src/custom_nodes/authoring.rs new file mode 100644 index 000000000..8dc69b4b2 --- /dev/null +++ b/crates/pantograph-workflow-service/src/custom_nodes/authoring.rs @@ -0,0 +1,37 @@ +//! Read-only host catalog and exactly pinned graph authoring. No execution/loading API. +use super::CustomNodeIdentity; +use serde::{Deserialize, Serialize}; + +/// Version 1 is a deliberately narrow projection of admitted string-port contracts. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct CustomNodeAuthoringCatalog { + pub contract_version: u16, + pub nodes: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct CustomNodeAuthoringEntry { + pub identity: CustomNodeIdentity, + pub label: String, + pub description: String, + pub trust: CustomNodeAuthoringTrust, + pub inputs: Vec, + pub outputs: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CustomNodeAuthoringTrust { + TrustedInProcess, +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct CustomNodeAuthoringPort { + pub id: String, + pub label: String, +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct CustomNodeDraftRequest { + pub identity: CustomNodeIdentity, +} diff --git a/crates/pantograph-workflow-service/src/graph/connection_insert.rs b/crates/pantograph-workflow-service/src/graph/connection_insert.rs index bd49a8b39..f267b7cd3 100644 --- a/crates/pantograph-workflow-service/src/graph/connection_insert.rs +++ b/crates/pantograph-workflow-service/src/graph/connection_insert.rs @@ -41,6 +41,13 @@ fn resolve_insert_definition<'a>( registry: &'a NodeRegistry, node_type: &str, ) -> Result<&'a NodeDefinition, ConnectionRejection> { + if registry.custom_nodes.get(node_type).is_some() { + return Err(ConnectionRejection { + reason: ConnectionRejectionReason::UnknownInsertNodeType, + message: "custom-node insertion by name is unsupported; add an exactly pinned node and connect its endpoints".into(), + contract_diagnostic: None, + }); + } registry .get_definition(node_type) .ok_or_else(|| ConnectionRejection { diff --git a/crates/pantograph-workflow-service/src/graph/connection_intent.rs b/crates/pantograph-workflow-service/src/graph/connection_intent.rs index 1360f02c0..a0c2caf1e 100644 --- a/crates/pantograph-workflow-service/src/graph/connection_intent.rs +++ b/crates/pantograph-workflow-service/src/graph/connection_intent.rs @@ -506,6 +506,7 @@ pub fn connection_candidates_with_surfaces( let mut insertable_node_types = registry .all_definitions() .into_iter() + .filter(|definition| registry.custom_nodes.get(&definition.node_type).is_none()) .filter_map(|definition| { let mut matching_input_port_ids = definition .inputs diff --git a/crates/pantograph-workflow-service/src/graph/session.rs b/crates/pantograph-workflow-service/src/graph/session.rs index d09eaa2a6..3d940e3bf 100644 --- a/crates/pantograph-workflow-service/src/graph/session.rs +++ b/crates/pantograph-workflow-service/src/graph/session.rs @@ -75,6 +75,7 @@ fn dirty_tasks_from_seed_nodes_unique(graph: &WorkflowGraph, node_ids: &[String] } pub struct GraphSessionStore { + node_registry: Arc, sessions: RwLock>, validation_state: Arc, validation_lifecycle: Arc, @@ -136,6 +137,7 @@ impl GraphSessionStore { dependency_provider: SharedDependencyEnvironmentProvider, ) -> Self { Self { + node_registry: Arc::new(super::registry::NodeRegistry::new()), sessions: RwLock::new(HashMap::new()), validation_state: Arc::new(CurrentInferenceValidationStateStore::new()), validation_lifecycle: Arc::new(WorkflowGraphValidationLifecycleOwner::new()), @@ -146,6 +148,14 @@ impl GraphSessionStore { } } + pub(crate) fn with_node_registry( + mut self, + registry: Arc, + ) -> Self { + self.node_registry = registry; + self + } + pub async fn set_validation_lifecycle_event_sink( &self, event_sink: Option>, @@ -159,7 +169,11 @@ impl GraphSessionStore { workflow_id: Option, ) -> WorkflowGraphEditSessionCreateResponse { let session_id = Uuid::new_v4().to_string(); - let session = Arc::new(Mutex::new(GraphEditSession::new(graph, workflow_id))); + let session = Arc::new(Mutex::new(GraphEditSession::new( + graph, + workflow_id, + self.node_registry.clone(), + ))); let graph_revision = { let state = session.lock().await; state.graph.compute_fingerprint() diff --git a/crates/pantograph-workflow-service/src/graph/session_connection_api.rs b/crates/pantograph-workflow-service/src/graph/session_connection_api.rs index 22a97ae4e..97f717675 100644 --- a/crates/pantograph-workflow-service/src/graph/session_connection_api.rs +++ b/crates/pantograph-workflow-service/src/graph/session_connection_api.rs @@ -13,7 +13,6 @@ use super::super::inference_validation_state::{ WorkflowGraphCurrentConnectionSurfacesStateRequest, }; use super::super::memory_impact::graph_memory_impact_from_graph_change; -use super::super::registry::NodeRegistry; use super::super::session_event::{dirty_tasks_from_seed_nodes, graph_modified_event}; use super::super::session_graph::sync_embedding_emit_metadata_flags; use super::super::session_types::{ @@ -39,10 +38,10 @@ impl GraphSessionStore { request.graph_revision.as_deref(), ) .await?; - let registry = NodeRegistry::new(); + let registry = self.node_registry.as_ref(); connection_candidates_with_surfaces( &graph, - ®istry, + registry, InferenceConnectionSurfaceView::new(&connection_surfaces.surfaces), request.source_anchor, request.graph_revision.as_deref(), @@ -65,10 +64,10 @@ impl GraphSessionStore { let mut state = handle.lock().await; state.touch(); let before_graph = state.graph.clone(); - let registry = NodeRegistry::new(); + let registry = self.node_registry.as_ref(); if let Err(rejection) = commit_connection_with_surfaces( &state.graph, - ®istry, + registry, InferenceConnectionSurfaceView::new(&connection_surfaces.surfaces), &request.graph_revision, &request.source_anchor, @@ -191,10 +190,10 @@ impl GraphSessionStore { let mut state = handle.lock().await; state.touch(); let before_graph = state.graph.clone(); - let registry = NodeRegistry::new(); + let registry = self.node_registry.as_ref(); let (inserted_node, inserted_edge) = match insert_node_and_connect( &state.graph, - ®istry, + registry, &request.graph_revision, &request.source_anchor, &request.node_type, @@ -252,11 +251,11 @@ impl GraphSessionStore { let handle = self.get_session_handle(&request.session_id).await?; let mut state = handle.lock().await; state.touch(); - let registry = NodeRegistry::new(); + let registry = self.node_registry.as_ref(); match preview_node_insert_on_edge( &state.graph, - ®istry, + registry, &request.graph_revision, &request.edge_id, &request.node_type, @@ -283,11 +282,11 @@ impl GraphSessionStore { let mut state = handle.lock().await; state.touch(); let before_graph = state.graph.clone(); - let registry = NodeRegistry::new(); + let registry = self.node_registry.as_ref(); let (inserted_node, incoming_edge, outgoing_edge, bridge) = match insert_node_on_edge( &state.graph, - ®istry, + registry, &request.graph_revision, &request.edge_id, &request.node_type, diff --git a/crates/pantograph-workflow-service/src/graph/session_contract.rs b/crates/pantograph-workflow-service/src/graph/session_contract.rs index ee8d764fc..d62215fc5 100644 --- a/crates/pantograph-workflow-service/src/graph/session_contract.rs +++ b/crates/pantograph-workflow-service/src/graph/session_contract.rs @@ -88,11 +88,28 @@ fn build_graph_session_response( build_graph_session_response_with_state(session_id, graph, workflow_event, None) } +#[cfg(test)] pub(crate) fn build_graph_session_response_with_state( session_id: &str, graph: &super::types::WorkflowGraph, workflow_event: Option, projection: Option<&WorkflowGraphSessionStateProjection>, +) -> WorkflowGraphEditSessionGraphResponse { + build_graph_session_response_with_registry( + session_id, + graph, + &NodeRegistry::new(), + workflow_event, + projection, + ) +} + +pub(crate) fn build_graph_session_response_with_registry( + session_id: &str, + graph: &super::types::WorkflowGraph, + registry: &NodeRegistry, + workflow_event: Option, + projection: Option<&WorkflowGraphSessionStateProjection>, ) -> WorkflowGraphEditSessionGraphResponse { let graph_revision = graph.compute_fingerprint(); WorkflowGraphEditSessionGraphResponse { @@ -106,10 +123,7 @@ pub(crate) fn build_graph_session_response_with_state( workflow_event.as_ref(), projection, )), - graph_diagnostics: validate_workflow_graph_contract_diagnostics( - graph, - &NodeRegistry::new(), - ), + graph_diagnostics: validate_workflow_graph_contract_diagnostics(graph, registry), } } diff --git a/crates/pantograph-workflow-service/src/graph/session_node_api.rs b/crates/pantograph-workflow-service/src/graph/session_node_api.rs index aa63ed567..4f2e3ba19 100644 --- a/crates/pantograph-workflow-service/src/graph/session_node_api.rs +++ b/crates/pantograph-workflow-service/src/graph/session_node_api.rs @@ -40,6 +40,33 @@ impl GraphSessionStore { request.node_id ))); } + let original = state + .graph + .find_node(&request.node_id) + .expect("checked node"); + if self + .node_registry + .custom_nodes + .get(&original.node_type) + .is_some() + || original + .data + .get(crate::custom_nodes::CUSTOM_NODE_IDENTITY_FIELD) + .is_some() + { + let mut candidate = original.clone(); + merge_node_data(&mut candidate.data, request.data.clone()); + if candidate + .data + .get(crate::custom_nodes::CUSTOM_NODE_IDENTITY_FIELD) + != original + .data + .get(crate::custom_nodes::CUSTOM_NODE_IDENTITY_FIELD) + || candidate.data.get("definition") != original.data.get("definition") + { + return Err(WorkflowServiceError::InvalidRequest("custom-node identity/definition cannot be patched; explicitly remove and recreate from the admitted catalog".into())); + } + } state.push_undo_snapshot(); let node = state.graph.find_node_mut(&request.node_id).ok_or_else(|| { WorkflowServiceError::InvalidRequest(format!( @@ -110,6 +137,24 @@ impl GraphSessionStore { let mut state = handle.lock().await; state.touch(); let before_graph = state.graph.clone(); + self.node_registry + .validate_custom_node_identity(&request.node) + .map_err(|error| WorkflowServiceError::InvalidRequest(error.to_string()))?; + if request + .node + .data + .get(crate::custom_nodes::CUSTOM_NODE_IDENTITY_FIELD) + .is_some() + && self + .node_registry + .custom_nodes + .get(&request.node.node_type) + .is_none() + { + return Err(WorkflowServiceError::InvalidRequest( + "custom-node implementation is unavailable".into(), + )); + } state.push_undo_snapshot(); let node_id = request.node.id.clone(); state.graph.nodes.push(request.node); diff --git a/crates/pantograph-workflow-service/src/graph/session_state.rs b/crates/pantograph-workflow-service/src/graph/session_state.rs index d44bda6b0..f4ff2e920 100644 --- a/crates/pantograph-workflow-service/src/graph/session_state.rs +++ b/crates/pantograph-workflow-service/src/graph/session_state.rs @@ -20,9 +20,10 @@ use super::types::WorkflowGraph; const DEFAULT_MAX_UNDO_SNAPSHOTS: usize = 64; -#[derive(Debug, Clone)] +#[derive(Clone)] pub(super) struct GraphEditSession { pub(super) graph: WorkflowGraph, + node_registry: std::sync::Arc, workflow_id: Option, undo_stack: Vec, redo_stack: Vec, @@ -31,10 +32,15 @@ pub(super) struct GraphEditSession { } impl GraphEditSession { - pub(super) fn new(mut graph: WorkflowGraph, workflow_id: Option) -> Self { + pub(super) fn new( + mut graph: WorkflowGraph, + workflow_id: Option, + node_registry: std::sync::Arc, + ) -> Self { graph = hydrate_embedding_emit_metadata_flags(graph); let mut session = Self { graph, + node_registry, workflow_id: workflow_id.and_then(normalize_optional_session_text), undo_stack: Vec::new(), redo_stack: Vec::new(), @@ -70,6 +76,7 @@ impl GraphEditSession { build_graph_session_response_with_projection( session_id, &self.graph, + &self.node_registry, None, phase6_memory_impact_projection(self.last_memory_impact.clone()), ) @@ -94,6 +101,7 @@ impl GraphEditSession { build_graph_session_response_with_projection( session_id, &self.graph, + &self.node_registry, workflow_event, projection, ) @@ -191,7 +199,7 @@ impl GraphEditSession { pub(super) fn canonicalize_graph(&mut self) { let graph = std::mem::take(&mut self.graph); - self.graph = canonicalize_workflow_graph(graph, &NodeRegistry::new()); + self.graph = canonicalize_workflow_graph(graph, &self.node_registry); self.graph.refresh_derived_graph(); } } @@ -199,12 +207,14 @@ impl GraphEditSession { pub(super) fn build_graph_session_response_with_projection( session_id: &str, graph: &WorkflowGraph, + registry: &NodeRegistry, workflow_event: Option, projection: Option, ) -> WorkflowGraphEditSessionGraphResponse { - super::session_contract::build_graph_session_response_with_state( + super::session_contract::build_graph_session_response_with_registry( session_id, graph, + registry, workflow_event, projection.as_ref(), ) diff --git a/crates/pantograph-workflow-service/src/workflow.rs b/crates/pantograph-workflow-service/src/workflow.rs index 24ee52b89..cf742ae05 100644 --- a/crates/pantograph-workflow-service/src/workflow.rs +++ b/crates/pantograph-workflow-service/src/workflow.rs @@ -1,3 +1,4 @@ +mod custom_node_authoring_api; #[cfg(test)] use async_trait::async_trait; use std::path::PathBuf; diff --git a/crates/pantograph-workflow-service/src/workflow/custom_node_authoring_api.rs b/crates/pantograph-workflow-service/src/workflow/custom_node_authoring_api.rs new file mode 100644 index 000000000..1992eadd9 --- /dev/null +++ b/crates/pantograph-workflow-service/src/workflow/custom_node_authoring_api.rs @@ -0,0 +1,112 @@ +use super::{WorkflowService, WorkflowServiceError}; +use crate::custom_nodes::{authoring::*, CUSTOM_NODE_IDENTITY_FIELD}; +use crate::{GraphEdge, GraphNode, Position, WorkflowGraph, WorkflowGraphEditSessionGraphResponse}; +use serde_json::json; + +impl WorkflowService { + /// Empty means no host registrations; transport failure is a separate outcome. + pub fn custom_node_authoring_catalog(&self) -> CustomNodeAuthoringCatalog { + CustomNodeAuthoringCatalog { + contract_version: 1, + nodes: self + .node_registry + .custom_nodes + .nodes() + .map(|node| { + let ports = |ports: &[pantograph_node_contracts::PortContract]| { + ports + .iter() + .map(|port| CustomNodeAuthoringPort { + id: port.id.as_str().into(), + label: port.label.clone(), + }) + .collect() + }; + CustomNodeAuthoringEntry { + identity: node.identity().clone(), + label: node.contract().label.clone(), + description: node.contract().description.clone(), + trust: CustomNodeAuthoringTrust::TrustedInProcess, + inputs: ports(&node.contract().inputs), + outputs: ports(&node.contract().outputs), + } + }) + .collect(), + } + } + + /// Resolve the user's complete selection before creating any session. Imported pins + /// never pass through this operation, and are never silently updated. + pub async fn create_custom_node_draft( + &self, + request: CustomNodeDraftRequest, + ) -> Result { + let custom = self + .node_registry + .custom_nodes + .get(&request.identity.node_type) + .ok_or_else(|| { + WorkflowServiceError::InvalidRequest( + crate::custom_nodes::CustomNodeError::Unavailable.to_string(), + ) + })?; + if custom.identity() != &request.identity { + return Err(WorkflowServiceError::InvalidRequest( + crate::custom_nodes::CustomNodeError::IdentityMismatch.to_string(), + )); + } + let mut graph = WorkflowGraph { + nodes: vec![GraphNode { + id: "custom".into(), + node_type: request.identity.node_type.clone(), + position: Position { x: 320.0, y: 0.0 }, + data: json!({"label": custom.contract().label, CUSTOM_NODE_IDENTITY_FIELD: custom.identity()}), + }], + edges: vec![], + derived_graph: None, + }; + for (direction, ports, node_type) in [ + ("input", &custom.contract().inputs, "text-input"), + ("output", &custom.contract().outputs, "text-output"), + ] { + let definition = self + .node_registry + .get_definition(node_type) + .ok_or_else(|| { + WorkflowServiceError::Internal("text authoring contract is unavailable".into()) + })?; + for (index, port) in ports.iter().enumerate() { + let id = format!("{direction}-{index}"); + let input = direction == "input"; + graph.nodes.push(GraphNode { + id: id.clone(), + node_type: node_type.into(), + position: Position { + x: if input { 0.0 } else { 640.0 }, + y: index as f64 * 160.0, + }, + data: json!({"label": port.label, "text": "", "definition": definition}), + }); + graph.edges.push(GraphEdge { + id: format!("edge-{id}"), + source: if input { id.clone() } else { "custom".into() }, + source_handle: if input { + "text".into() + } else { + port.id.as_str().into() + }, + target: if input { "custom".into() } else { id }, + target_handle: if input { + port.id.as_str().into() + } else { + "text".into() + }, + }); + } + } + let session = self.graph_session_store.create_session(graph, None).await; + self.graph_session_store + .get_session_graph(&session.session_id) + .await + } +} diff --git a/crates/pantograph-workflow-service/src/workflow/service_config.rs b/crates/pantograph-workflow-service/src/workflow/service_config.rs index 919c487c1..01a5c7a4e 100644 --- a/crates/pantograph-workflow-service/src/workflow/service_config.rs +++ b/crates/pantograph-workflow-service/src/workflow/service_config.rs @@ -92,7 +92,9 @@ impl WorkflowService { runtime_dispatch_assignment_repository: Arc::new(Mutex::new( InMemoryWorkflowRuntimeDispatchAssignmentRepository::new(), )), - graph_session_store: Arc::new(GraphSessionStore::new()), + graph_session_store: Arc::new( + GraphSessionStore::new().with_node_registry(node_registry.clone()), + ), artifact_writer: None, artifact_format_settings: Arc::new(Mutex::new(ArtifactFormatSettings::default())), artifact_format_settings_path: None, @@ -190,7 +192,8 @@ impl WorkflowService { provider: Arc, ) -> Self { self.graph_session_store = Arc::new( - GraphSessionStore::with_inference_interface_facts_provider(provider), + GraphSessionStore::with_inference_interface_facts_provider(provider) + .with_node_registry(self.node_registry.clone()), ); self } @@ -201,11 +204,14 @@ impl WorkflowService { inference_provider: Arc, provider: SharedDependencyEnvironmentProvider, ) -> Self { - self.graph_session_store = Arc::new(GraphSessionStore::with_timeout_and_providers( - std::time::Duration::from_secs(5 * 60), - inference_provider, - provider.clone(), - )); + self.graph_session_store = Arc::new( + GraphSessionStore::with_timeout_and_providers( + std::time::Duration::from_secs(5 * 60), + inference_provider, + provider.clone(), + ) + .with_node_registry(self.node_registry.clone()), + ); self.dependency_readiness_provider = Arc::new(DependencyEnvironmentService::new(provider)); self } diff --git a/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs b/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs index 6e16c03d5..9226d62a0 100644 --- a/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs +++ b/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs @@ -362,3 +362,272 @@ async fn custom_nodes_callback_failures_are_terminal_without_publishing_outputs( .is_err()); } } + +async fn authored_draft(service: &WorkflowService) -> crate::WorkflowGraphEditSessionGraphResponse { + let identity = service.custom_node_authoring_catalog().nodes[0] + .identity + .clone(); + service + .create_custom_node_draft(crate::custom_nodes::authoring::CustomNodeDraftRequest { + identity, + }) + .await + .unwrap() +} + +#[tokio::test] +async fn custom_node_authoring_registry_survives_provider_builders_and_undo_redo() { + for mode in 0..3 { + let service = WorkflowService::with_trusted_custom_nodes(catalog(Arc::new(Executor::new( + Behavior::Uppercase, + )))); + let service = match mode { + 1 => service.with_inference_interface_facts_provider(Arc::new(crate::graph::UnavailableInferenceInterfaceFactsProvider)), + 2 => service.with_graph_session_fact_providers(Arc::new(crate::graph::UnavailableInferenceInterfaceFactsProvider), Arc::new(pantograph_dependency_environment_service::NotImplementedDependencyEnvironmentProvider)), + _ => service, + }; + let draft = authored_draft(&service).await; + assert!( + draft + .graph_diagnostics + .iter() + .all(|d| !d.blocking_submission), + "{:?}", + draft.graph_diagnostics + ); + let pin = draft.graph.nodes[0].data[CUSTOM_NODE_IDENTITY_FIELD].clone(); + let updated = service + .workflow_graph_update_node_data(crate::WorkflowGraphUpdateNodeDataRequest { + session_id: draft.session_id.clone(), + node_id: "input-0".into(), + data: serde_json::json!({"text": "authored"}), + }) + .await + .unwrap(); + assert_eq!( + updated.graph.find_node("input-0").unwrap().data["text"], + "authored" + ); + let request = crate::WorkflowGraphEditSessionGraphRequest { + session_id: draft.session_id, + }; + let undo = service.workflow_graph_undo(request.clone()).await.unwrap(); + let redo = service.workflow_graph_redo(request).await.unwrap(); + for snapshot in [undo, redo] { + assert_eq!( + snapshot.graph.find_node("custom").unwrap().data[CUSTOM_NODE_IDENTITY_FIELD], + pin + ); + assert!(snapshot + .graph_diagnostics + .iter() + .all(|d| !d.blocking_submission)); + } + } +} + +#[tokio::test] +async fn custom_node_authoring_refuses_stale_selection_and_identity_patches_without_mutation() { + let service = WorkflowService::with_trusted_custom_nodes(catalog(Arc::new(Executor::new( + Behavior::Uppercase, + )))); + let entry = service.custom_node_authoring_catalog().nodes[0].clone(); + let mut stale = entry.identity.clone(); + stale.environment_digest = crate::custom_nodes::tests::digest("changed environment"); + let error = service + .create_custom_node_draft(crate::custom_nodes::authoring::CustomNodeDraftRequest { + identity: stale.clone(), + }) + .await + .unwrap_err(); + assert!(error.to_string().contains("identity does not match")); + assert!( + serde_json::from_value::( + serde_json::json!({"identity": entry.identity, "definition": {}}) + ) + .is_err() + ); + let draft = authored_draft(&service).await; + for patch in [ + serde_json::json!({CUSTOM_NODE_IDENTITY_FIELD: stale}), + serde_json::json!({"definition": {}}), + serde_json::json!({CUSTOM_NODE_IDENTITY_FIELD: null}), + ] { + let error = service + .workflow_graph_update_node_data(crate::WorkflowGraphUpdateNodeDataRequest { + session_id: draft.session_id.clone(), + node_id: "custom".into(), + data: patch, + }) + .await + .unwrap_err(); + assert!(error.to_string().contains("cannot be patched")); + let after = service + .workflow_graph_get_edit_session_graph(crate::WorkflowGraphEditSessionGraphRequest { + session_id: draft.session_id.clone(), + }) + .await + .unwrap(); + assert_eq!(after.graph_revision, draft.graph_revision); + assert_eq!(after.graph, draft.graph); + } + let mut unpinned = draft.graph.find_node("custom").unwrap().clone(); + unpinned.id = "bad".into(); + unpinned.data = serde_json::json!({}); + assert!(service + .workflow_graph_add_node(crate::WorkflowGraphAddNodeRequest { + session_id: draft.session_id, + node: unpinned + }) + .await + .unwrap_err() + .to_string() + .contains("identity does not match")); +} + +#[tokio::test] +async fn custom_node_authoring_candidates_and_commit_share_exact_registry() { + let service = WorkflowService::with_trusted_custom_nodes(catalog(Arc::new(Executor::new( + Behavior::Uppercase, + )))); + let draft = authored_draft(&service).await; + let removed = service + .workflow_graph_remove_edge(crate::WorkflowGraphRemoveEdgeRequest { + session_id: draft.session_id.clone(), + edge_id: "edge-input-0".into(), + }) + .await + .unwrap(); + let source = crate::ConnectionAnchor { + node_id: "input-0".into(), + port_id: "text".into(), + }; + let candidates = service + .workflow_graph_get_connection_candidates( + crate::WorkflowGraphGetConnectionCandidatesRequest { + session_id: draft.session_id.clone(), + source_anchor: source.clone(), + graph_revision: Some(removed.graph_revision.clone()), + }, + ) + .await + .unwrap(); + assert!(candidates + .compatible_nodes + .iter() + .any(|node| node.node_id == "custom")); + assert!(!candidates + .insertable_node_types + .iter() + .any(|node| node.node_type == "custom-uppercase")); + let rejected = service + .workflow_graph_preview_node_insert_on_edge( + crate::WorkflowGraphPreviewNodeInsertOnEdgeRequest { + session_id: draft.session_id.clone(), + edge_id: "edge-output-0".into(), + node_type: "custom-uppercase".into(), + graph_revision: removed.graph_revision.clone(), + }, + ) + .await + .unwrap(); + assert!(!rejected.accepted); + assert!(rejected + .rejection + .unwrap() + .message + .contains("insertion by name is unsupported")); + let committed = service + .workflow_graph_connect(crate::WorkflowGraphConnectRequest { + session_id: draft.session_id.clone(), + source_anchor: source, + target_anchor: crate::ConnectionAnchor { + node_id: "custom".into(), + port_id: "input".into(), + }, + graph_revision: removed.graph_revision, + }) + .await + .unwrap(); + assert!(committed.accepted); + let snapshot = service + .workflow_graph_get_edit_session_graph(crate::WorkflowGraphEditSessionGraphRequest { + session_id: draft.session_id, + }) + .await + .unwrap(); + assert!(snapshot + .graph_diagnostics + .iter() + .all(|d| !d.blocking_submission)); +} + +#[tokio::test] +async fn custom_node_authoring_saved_reopen_preserves_pin_and_scheduler_execution() { + let root = tempfile::tempdir().unwrap(); + let catalog = catalog(Arc::new(Executor::new(Behavior::Uppercase))); + let service = WorkflowService::with_trusted_custom_nodes(catalog.clone()); + let draft = authored_draft(&service).await; + let store = FileSystemWorkflowGraphStore::new(root.path()); + let saved = service + .workflow_graph_save( + &store, + crate::WorkflowGraphSaveRequest { + name: "custom-workflow".into(), + graph: draft.graph.clone(), + }, + ) + .unwrap(); + let reopened = WorkflowService::with_trusted_custom_nodes(catalog); + let graph = reopened + .workflow_graph_load( + &store, + crate::WorkflowGraphLoadRequest { + path: saved.path.clone(), + }, + ) + .unwrap() + .graph; + assert_eq!( + graph.find_node("custom").unwrap().data[CUSTOM_NODE_IDENTITY_FIELD], + draft.graph.find_node("custom").unwrap().data[CUSTOM_NODE_IDENTITY_FIELD] + ); + for (service, blocking) in [(&reopened, false), (&WorkflowService::new(), true)] { + let edit = service + .workflow_graph_create_edit_session(crate::WorkflowGraphEditSessionCreateRequest { + graph: graph.clone(), + workflow_id: Some(saved.path.clone()), + }) + .await + .unwrap(); + let snapshot = service + .workflow_graph_get_edit_session_graph(crate::WorkflowGraphEditSessionGraphRequest { + session_id: edit.session_id, + }) + .await + .unwrap(); + assert_eq!( + snapshot.graph.find_node("custom").unwrap().data, + graph.find_node("custom").unwrap().data + ); + assert_eq!( + snapshot + .graph_diagnostics + .iter() + .any(|d| d.blocking_submission), + blocking + ); + } + let host = SavedGraphHost { + root: root.path().into(), + }; + let session_id = session(&reopened, &host).await; + let mut request = run_request(&session_id); + request.inputs[0].node_id = "input-0".into(); + request.output_targets.as_mut().unwrap()[0].node_id = "output-0".into(); + let result = reopened + .run_workflow_execution_session(&host, request) + .await + .unwrap(); + assert_eq!(result.outputs[0].value, "MIXED CASE"); +} diff --git a/docs/custom-nodes.md b/docs/custom-nodes.md index 9ed1bcb6e..543552b93 100644 --- a/docs/custom-nodes.md +++ b/docs/custom-nodes.md @@ -82,13 +82,47 @@ adds the `custom_node` non-runtime template; identity adapter version 1 owns thi bounded contract. Coordinated Rust producers/consumers are updated together; older implementations cannot execute that template. -NodeLab authoring, Local Agent and runtime publishing remain unavailable. -Graph edit-session authoring and connection APIs still use built-in discovery; -they are not custom-node authoring surfaces. Before exposing custom nodes there, -NodeLab must install host-authorized registrations and exact graph pins, use the -same registry for edit validation/connection previews, and expose trust, version -mismatch and unavailable implementation outcomes. Publishing arbitrary code -needs its own artifact verification, isolation and lifecycle contract. +## NodeLab graph authoring + +NodeLab authors workflows from implementations already admitted by its host. It +reads `custom_node_authoring_catalog` (wire version 1), a narrow projection of +canonical labels, required string port IDs and complete immutable identities. +The projection's `trusted_in_process` profile carries the trust obligations above; +it is not an installation or execution permission. Default desktop composition +has an empty catalog and says so. Host maintainers register implementations in +Rust before service construction; browser clients cannot register or load code. +The legacy generic palette remains built-in-only. + +`create_custom_node_draft` requires the complete selected identity. The service +resolves exact equality before creating a session, then builds one text source +per required input, the pinned custom node, and one text sink per output. Custom +nodes never receive `node.data.definition`. NodeLab owns a separate edit session, +allows text source edits, displays backend contract diagnostics, and saves/reopens +through existing graph persistence. It provides no execution button; saved graphs +use scheduler sessions. Input text is authored configuration, not tool authority. + +The same admitted registry reaches edit-session canonicalization, diagnostics, +connection candidates and commits, including provider-builder construction. New +custom additions require exact pins. General custom data patches cannot change +identity or definitions. Imported/reopened missing or stale pins remain unchanged +and produce blocking diagnostics; explicit new authoring is the recovery path. +Name-only insert-and-connect/insert-on-edge APIs cannot express a selected complete +identity, so custom insertion there is explicitly unsupported and omitted from +creation suggestions. Adding a pinned node and connecting existing endpoints is +supported. + +Failed create/reopen preserves the current draft. Replacement and page teardown +close owned sessions, including late creation completion. Transport failures during +close retain exact session IDs in the app-scoped NodeLab service. Pending cleanup +is visible on the next NodeLab mount, blocks new creation/reopening and has an +explicit retry action. No automatic graph-session reap is assumed. A process or +host restart ends these ephemeral sessions; saved files retain their exact pins. + +The desktop commands are `get_custom_node_authoring_catalog`, +`create_custom_node_draft` and `get_node_lab_draft`; mutations/persistence reuse +existing commands. Local Agent and runtime publishing remain unavailable or +unsupported. Arbitrary packages still need independently admitted artifact +verification, isolation and lifecycle contracts. A scheduler-managed tool loop must consume this exact admission and invocation identity, plus its own typed tool authority, bounded iterations, cancellation, diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz new file mode 100644 index 0000000000000000000000000000000000000000..ec6e6c01c5b6d92e7d5f711e3f8f19252feaee63 GIT binary patch literal 441 zcmV;q0Y?5GiwFP!0000216@+hZWA#OzVB0v_8gpSNQ=~CLE?rGlmkK>9D9;X*ME5I zRZ_%-SAZi=*C%0|Ra&XO`TLpqX6%Uy!gQ@RYJhDeXDRGq7c-%ang zq1*lO-yax;4R{ebWO(AysxD)&m|G!psA1%0Fwv)48n%C+1WXUuU`t$Q~9^t0(A9`Uq|I$JPOuC18OT#7~V=ePt`Bl9#Ul8yz-%1(glPFEQPl5xPbQ`zcft~ j%o+M19VfigHB+k@Vu2r3JKB*bx?kOYkqj1t@9th3OC literal 0 HcmV?d00001 diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/native-unavailable.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/native-unavailable.log.gz new file mode 100644 index 0000000000000000000000000000000000000000..3080c4fbb6a61d170f1146064ebdb28df58b9529 GIT binary patch literal 2190 zcmV;92yyoxiwFP!000021FczYZ``;M{_bC)Z)wq!yxJFeZ6Jr{++Gq~8XqnOihhzQ zidr$2NQI=lyZ-eZzGy9xvYVU>1X^X`laFcp0ZuEM^x$0ii@bC4T&@% z;w&n9+LTdA1;L7o;~5;f=50qC%`J&2NshT7(LK~>eD9moZ#i)1mSHhiZQu9Kyw@R10P zd3V&*ZL(TTsa3CfL1e6uyw@D7WR=cy^olm~932w+GjF(ZFcXL8{!;p=Mk9;m}1vAB~7@vYgTcVr7nN1pjO%J>MuR$)QD^sl$~|1)W%b zTCdlkXe-kzj^e0D+v9s}IDIg7L5X{Y4NS(PwXayaR0-Z%&0e^V{GQkb@bgPMT{%OF z)0qsPD*qx$Js1#!r$F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ZPeljez`r3ixpI<@QgQ``uRk{_gg}>wOzZd8LC! z)DP+XZf3~;KR*8PdS@qcUhA$E_Jg{=oBhjwzWi}>bDRHP{0@b^*7=ddKV!w|jKjaT z8ldiXfSs(OI|EJtTzfrxEMi1@36J#l@^ds2`R>!Fn}2J;xBvWCe*NpGckjQvO~;aA zh*lxt1KV#-3}yk8L~l+%{romsCKro0XCVBxChlQFf59V=I67bj#yh=!_f!}}g$bfx zYfh+p7wwUZ7*_zsJu4F@%Z$F0grviF5hDbaV1V<2M3jMdjfQs(;|dOV9TGt(so<<7 z`rQbIv021g7y|ksS0TzG{XLU@qydK0cUgn_?~+EX-IAz8hv37<&$m|*t)e6EqZ&Po zt<)B}xcn3;2o4-FU#|Izz&*`-GH9??^G?D6Do-QO4mCUPewuu5$IVwIUwL5ySAiT^ QCrNVlUq8znCg~dh0L8mLwEzGB literal 0 HcmV?d00001 diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json new file mode 100644 index 000000000..5d259bf2c --- /dev/null +++ b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json @@ -0,0 +1,54 @@ +{ + "base": "285c48989a95caef1bcaac92eac9ff3b1be0a9ad", + "environment": { + "os": "Linux x86_64", + "rust": "1.92.0", + "node": "24.12.0", + "chromium": "Chromium 151.0.7922.173 built on Debian GNU/Linux 13 (trixie)", + "mode": "headless; disposable profile/store; GPU disabled; container verification no-sandbox only" + }, + "claims": { + "browser_user_workflow": "passed: actual NodeLab -> loopback -> Rust service -> filesystem create/edit/save/reopen; keyboard/pointer and focus; missing implementation blocking; exact pin retained", + "service_tests": "1068 library +65 integration passed, zero failures/ignored", + "frontend_tests": "740 passed, zero failures/ignored; 10 focused decoding/controller/presenter tests included", + "native_tauri": "unavailable: cargo check --locked -p pantograph --bin pantograph --no-default-features fails at glib-sys: missing glib-2.0.pc; pkg-config also lacks GTK/WebKit; no native startup claim", + "not_claimed": [ + "installed custom nodes in default desktop", + "arbitrary code loading", + "trained model T3", + "GPU", + "inference-backed/effectful tool loops", + "release qualification" + ] + }, + "source_sha256": { + "crates/pantograph-workflow-service/examples/nodelab_host.rs": "1c9a33092e0bac9560247b8c1e158bc0405527cad7b0a280d79dc61334eed8c8", + "crates/pantograph-workflow-service/src/custom_nodes.rs": "1d413febbad16689c864e7945191c7bb83079530ece13fda73541178bd86f774", + "crates/pantograph-workflow-service/src/custom_nodes/authoring.rs": "ab2e37ca4a68b846e8f23897891eea064730a1376c8597eb5ce00e1bf5f909ed", + "crates/pantograph-workflow-service/src/graph/connection_insert.rs": "881afe99675e681a2bd1208f69e55f82afa881adec9ead9a6863089dd3a6f2af", + "crates/pantograph-workflow-service/src/graph/connection_intent.rs": "d5832d05d88dd0d2dc10cb367038a0a6d5973e1275fe19e888fb411c13057199", + "crates/pantograph-workflow-service/src/graph/session.rs": "e9248df745093b0ff078691a04036017fed894bdd073d922b0f628920a1efcac", + "crates/pantograph-workflow-service/src/graph/session_connection_api.rs": "f29f061031b4c70f829cfbd603108857ed7d093245ae3cdeb8d63797b9c5fefe", + "crates/pantograph-workflow-service/src/graph/session_contract.rs": "844733c80c5f5a372844637a104e901b9cd46433e1ef73662ff314f4b8e134b0", + "crates/pantograph-workflow-service/src/graph/session_node_api.rs": "61505593be43e6bc58e9c9c8f1b991cfd75949a55da8351278ca45a25015ecd3", + "crates/pantograph-workflow-service/src/graph/session_state.rs": "c19150bbf4b61dd506ad6bb618593c40f59a8fde43f554025eb940e8c75b1d17", + "crates/pantograph-workflow-service/src/workflow.rs": "47e42061802abc91ebe6b3babf8c578116d2e0fecf51d86fa53148cbed613886", + "crates/pantograph-workflow-service/src/workflow/custom_node_authoring_api.rs": "5bf54f01b2db4ec2ffc21b6af41291c695ff91a3b274deb80838c32020b9941d", + "crates/pantograph-workflow-service/src/workflow/service_config.rs": "257edc58a50b37e8dee265b971e91084b0f77b0ce4031f8d105b604f33cea513", + "crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs": "aa080d798774771aa419db01d83cd26401684ab06333770a74e209c601e5952f", + "scripts/README.md": "03bed3d3d157a4d7e4a9f2a291f4a2ab37efa2e81f87c83e3d5710a38220119a", + "scripts/check-nodelab-browser.mjs": "30a619d382ddb242c19b50c51ec97fda8a6c20973fe51f94c7c0fcf5658d24d4", + "src-tauri/src/app_setup.rs": "b14c996956638c5a708156aaf8f110ce6f1fa3a175f6b03bb9ff0284bd392a50", + "src-tauri/src/workflow/commands.rs": "24834569833ec6509300b9c8c795b9eb8be233f0c6d9c37c5d67f82b63d24b6c", + "src/components/workbench/NodeLabPage.svelte": "b9206ed693d2a18f065c547752622cbb48a96a3599d1867d166e45f39fc7424f", + "src/components/workbench/nodeLabController.ts": "3b3806dcf0aedf191fd7ad91ce3ac746a08c6962b1c0b292f54d9ba6e9145716", + "src/components/workbench/nodeLabPresenters.test.ts": "5debffcdba6ddc86d4b4093dceb08dbf691b7659b73a483abd8d991616faa02e", + "src/components/workbench/nodeLabPresenters.ts": "4792bedc18bf6b55173a892e0f15bc7900b4c36fd84bfc508da3dac9c0bbb075", + "src/services/workflow/customNodeAuthoring.test.ts": "73d776ffb40ddcafcfb0e69f7434f98aa19bd037484a36ccdef7d9eff290d250", + "src/services/workflow/customNodeAuthoring.ts": "f4a11c2fa37816819db79176b2af584199c946a5e3c533482cc595362092dc08" + }, + "evidence_sha256": { + "browser.log.gz": "39a0549788107cc92c66b172a0810f2f81b40de30458af58e660a67fa1b45287", + "native-unavailable.log.gz": "f72bc764c185d785964c3ac95e9a0d6f24a1d999aefbd349dc143eed28d261b3" + } +} diff --git a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md index 7b4348f1e..e6a6f09de 100644 --- a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md +++ b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md @@ -813,3 +813,36 @@ Accepted stop-string/PR60 and all seed/precision/repair/paused histories remain separate. Controlled package/readiness/dispatch/session facts and untrained CPU models do not qualify live Pumas, pretrained quality, GPU, desktop or native batching/throughput. Full plan acceptance and parent publication remain separate. + +## 2026-10-22 — NodeLab trusted-node authoring + +Continued the admitted CN-02 slice on main `285c4898` after CN-01/README merges. +The [consumer contract](../../custom-nodes.md#nodelab-graph-authoring) owns the +read-only versioned catalog, exact-selection server-built drafts, shared edit +registry, pin-preserving mutations and saved/reopened behavior. Default desktop +has no custom registrations; the separate real Rust qualification host supplies +one compiled pure transform. No code loader, execution UI or tool grant is added. +Independent GPT-6.1 Sol High review accepted after repairing failed replacement +loss, explicit-null diagnostic decoding and close-failure ownership/recovery. + +[Qualification](evidence/nodelab-authoring/qualification.json) retains source +bindings, actual Chromium→Rust→filesystem user-workflow evidence and the native +failure. Service tests pass 1,068 library +65 integration, zero failures/ignored; +740 frontend tests pass including ten focused parser/controller/presenter cases. +Formatting, typecheck, production frontend build, lint, critical/a11y gates, +scheduler-only guard and traceability tests pass. All-target package Clippy +retains only the existing inference dead-field warning. Initial new fixtures used +an unexported provider and a nonexistent response field; corrected against the +actual owning APIs, preserving the assertions. The first browser Enter simulation +omitted character text and did not activate the button; proper CDP key events +then passed the same workflow assertions, with no pointer fallback for that gate. + +Native `cargo check --locked -p pantograph --bin pantograph --no-default-features` +is unavailable at glib-sys because this environment lacks `glib-2.0.pc`; GTK and +WebKit development packages are also absent. No native/desktop startup claim or +persistent access change is made. PR92 `afe33029` remains open with its unique +trained-text source/evidence and missing T3 gate unchanged. CN-03 PR94 integrates +first by parent instruction; CN-02 must then reconcile current main, preserve its +registry/loop validations, rerun combined affected tests and pass exact-head CI +before merge. The local/remote feature branch and worktree are retained pending +that disposition, with source and evidence preserved. diff --git a/docs/plans/domain-architecture-and-multimodal/issues.md b/docs/plans/domain-architecture-and-multimodal/issues.md index 78a0af760..5b5a43ac5 100644 --- a/docs/plans/domain-architecture-and-multimodal/issues.md +++ b/docs/plans/domain-architecture-and-multimodal/issues.md @@ -76,5 +76,5 @@ authorize the historical resident-accounting next-slice text. | ID | Issue | Owner | Disposition / next evidence | | --- | --- | --- | --- | | CN-01 | Palette/callback registration does not establish canonical executable admission or implementation/environment identity. | Custom-node lead | Closed for the bounded trusted string adapter after independent GPT-6.1 Sol High review and 1,129 passing service tests. Exact admission, saved/reopened scheduler execution, cancellation/commit arbitration and inspection share the immutable catalog. Arbitrary executable loading remains outside this contract. | -| CN-02 | NodeLab authoring, Local Agent and runtime publishing remain unavailable. | NodeLab follow-on | Deferred. Consume the [custom-node contract](../../custom-nodes.md): host-authorized registrations and exact graph pins, same registry for edit-session validation/connection previews, trust/version/unavailable outcomes. Untrusted package publishing additionally needs independently admitted artifact verification and isolation. A palette entry cannot enable execution. | -| CN-03 | Scheduler-managed tool-loop exposure needs a safe node invocation contract and explicit tool authority. | Tool-loop follow-on | Deferred. Depend on CN-01 exact identity/admission and scheduler-owned run/attempt/cancellation/result commitment; separately admit typed tool capabilities, bounded iteration and side-effect/idempotency behavior. The string adapter grants no tool capability. Do not restore the retired static loop. | +| CN-02 | NodeLab graph authoring requires the same admission identity and registry as execution. | NodeLab lead | Implemented, verifying: service-owned exact-selection draft creation, NodeLab source editing/save/reopen, shared edit registry and blocking stale/unavailable diagnostics. Default desktop is honestly empty; nonempty host-composed browser flow is qualified separately. Local Agent/code publishing, generic name-only custom insertion and arbitrary loading remain unsupported. See [contract](../../custom-nodes.md#nodelab-graph-authoring). | +| CN-03 | Scheduler-managed tool-loop exposure needs a safe node invocation contract and explicit tool authority. | Tool-loop follow-on | Separate worker task `01a1615c-5be4-74a5-bf4c-c3f3b3136000`. Depend on CN-01 exact identity/admission and scheduler-owned run/attempt/cancellation/result commitment; separately admit typed tool capabilities, bounded iteration and side-effect/idempotency behavior. The string adapter grants no tool capability. Do not restore the retired static loop. | diff --git a/docs/plans/domain-architecture-and-multimodal/plan.md b/docs/plans/domain-architecture-and-multimodal/plan.md index fdd0a90e6..2a0b0c92a 100644 --- a/docs/plans/domain-architecture-and-multimodal/plan.md +++ b/docs/plans/domain-architecture-and-multimodal/plan.md @@ -298,6 +298,64 @@ Development Proportionality, Commit, Documentation, Architecture/Code Design, Contracts, Security, Concurrency/Resilience and Library/Rust API/Async guidance. The rest of this plan retains its historical standards baseline. +## Admitted NodeLab/edit-session slice (2026-10-22) + +**Admission:** `continue` this Active plan under the delegated unfinished-path +instruction. CN-01 is integrated in `2e517f58`, README PR79 in current main +`285c4898`. Independent GPT-6.1 Sol High design review admits a bounded NodeLab +graph-authoring surface before implementation. This does not author or install +executable code. PR92's unique trained-text source/evidence and missing T3 gate +remain separate and protected; CN-03 has its own worker and integration gate. + +**Outcome and contract:** NodeLab reads a versioned service-owned projection of +host-admitted custom definitions and complete identities. The default desktop +catalog is honestly empty; a composed host supplies nonempty registrations. +Selecting an admitted node creates a separate edit-session draft with one text +source per required input and one text sink per output, derived from host ports. +Users edit source values, inspect backend diagnostics, save and reopen through +existing graph APIs. Saved pins are never silently refreshed. Missing/stale +implementations remain visible and blocking; recovery requires explicit new +authoring. No direct edit-session execution, Local Agent, runtime publishing, +arbitrary loader, new capability grant or static tool loop is enabled. + +The draft is constructed by the service from the exact selected identity, not +from a client-supplied custom definition. The same immutable registry must reach +graph-session construction, provider +builders, canonicalization, response diagnostics and connection candidate/commit +validation. Add requires the exact selected identity; custom data patches cannot +change identity or add dynamic definitions. Imported invalid graphs remain +inspectable without healing. Name-only custom insert-on-edge/insert-and-connect +is explicitly unsupported; use pinned add plus explicit connections. The +legacy generic palette stays built-in-only. CN-03 consumes saved graph pins and +CN-01 scheduler invocation, not NodeLab state or a second execution route. + +**Composition and write set:** registry/catalog owns admitted facts; graph +sessions own authored state, undo and validation; NodeLab owns local interaction +and observes service responses; existing store owns persistence. Stable +interfaces are the versioned read projection and existing pinned graph/mutation +contracts. This avoids duplicating admission or execution in the frontend. +Change service `custom_nodes`, `graph`, graph API/config and related tests; +NodeLab presenters/controller/page and narrow workflow transport projections; +desktop command wiring; a bounded real-host example/browser probe and affected +documentation. No scheduler-loop core, text runtime/readiness, root README or +PR92 edits. Branch `feat/nodelab-trusted-catalog`, worktree +`/workspace/pantograph-nodelab`, base `285c4898`, target `main`. Preserve source, +branches and evidence; parent coordinates serial integration if CN-03 intersects. + +**Acceptance:** focused admission/edit-session refusal tests, real save/reopen +and connection candidate/commit tests, provider-builder registry retention, +frontend decoder/lifecycle tests, and real-browser pointer/keyboard draft → +edit → save → reopen interaction through an injected Rust host. Browser evidence +does not qualify native Tauri startup. Native compile/smoke is attempted only +where available and its actual limits recorded. Required CI, independent source +review and current-main recheck precede merge under the later cleanup authority; +no gate waiver, evidence-weakening rerun or persistent access expansion. Status +`Verifying`; next slice complete independent review, current-main/CI gates and +serial integration. Failed replacement preserves the current draft; failed close +transfers exact session IDs to an app-scoped, user-retryable cleanup owner. Standards baseline `0fc92a2` +continues, adding routed Frontend, TypeScript/Async, Accessibility, IPC, +Persistence, protocol/evolution and GUI verification detail to the CN-01 routes. + ## Standards And Plan Authority Standards source: diff --git a/scripts/README.md b/scripts/README.md index 968852740..15d8c1291 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -257,3 +257,20 @@ it preserves the existing expression-evidence policy rather than proving its runtime value. Native-button rules and reviewed-ignore rules are unchanged. Runtime accessibility and dynamically empty/hidden content still require UI validation. + +## NodeLab authoring browser qualification + +Build `cargo build --locked -p pantograph-workflow-service --example nodelab_host`, +then run `NODELAB_HOST_BINARY= node +scripts/check-nodelab-browser.mjs`. The isolated stdio Rust host registers one +compiled pure transform and owns a temporary workflow store; the verifier exposes +only a temporary loopback transport. It exercises the actual NodeLab component, +strict catalog decoding, keyboard focus/creation, pointer edits, filesystem +save/reopen, pin retention, session replacement cleanup and missing-implementation +blocking. A second real empty host proves the empty catalog and stale reopen; +a deliberately failed transport proves the distinct unavailable state. Browser +arguments select headless Chromium, disposable profile, GPU disabled and the +verification-only no-sandbox mode required by this container. They do not alter +normal startup. This is browser/host evidence, not native Tauri, package, model, +GPU or scheduler tool-loop qualification. EOF and verifier teardown release the +host/store/browser resources. See [custom-node authoring](../docs/custom-nodes.md#nodelab-graph-authoring). diff --git a/scripts/check-nodelab-browser.mjs b/scripts/check-nodelab-browser.mjs new file mode 100644 index 000000000..76cd26290 --- /dev/null +++ b/scripts/check-nodelab-browser.mjs @@ -0,0 +1,172 @@ +/* global document, getComputedStyle */ +// Real NodeLab component -> loopback transport -> isolated Rust service -> filesystem. +// No Tauri startup, installed node, model or GPU claim. Build nodelab_host first. +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { createServer } from 'node:http'; +import { createInterface } from 'node:readline'; +import { mkdtemp, readFile, writeFile, symlink, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { evaluateBrowserFunction } from './cdp-browser-function.mjs'; + +const repo = fileURLToPath(new URL('../', import.meta.url)); +const fixture = await mkdtemp(path.join(tmpdir(), 'pantograph-nodelab-browser-')); +const hostBinary = process.env.NODELAB_HOST_BINARY; +assert.ok(hostBinary, 'NODELAB_HOST_BINARY must name the built nodelab_host example'); +const hosts = []; +const servers = []; +let browser; +let socket; +const commands = []; +const sessions = []; +try { + await symlink(path.join(repo, 'node_modules'), path.join(fixture, 'node_modules')); + await writeFile(path.join(fixture, 'index.html'), '
'); + await writeFile(path.join(fixture, 'main.js'), `import { mount } from 'svelte'; import Page from ${JSON.stringify(path.join(repo, 'src/components/workbench/NodeLabPage.svelte'))}; mount(Page, { target: document.getElementById('app') });`); + await build({ configFile: false, root: fixture, plugins: [svelte()], build: { outDir: 'dist', emptyOutDir: true } }); + function rustHost(empty) { + const child = spawn(hostBinary, empty ? ['--empty-catalog'] : [], { stdio: ['pipe', 'pipe', 'inherit'] }); + hosts.push(child); + const lines = createInterface({ input: child.stdout }); + let tail = Promise.resolve(); + return (command, args) => { + const result = tail.then(() => new Promise((resolve, reject) => { + const timeout = setTimeout(() => { lines.removeListener('line', received); reject(new Error('Rust host command timeout')); }, 10000); + const received = line => { clearTimeout(timeout); try { resolve(JSON.parse(line)); } catch (error) { reject(error); } }; + lines.once('line', received); + child.stdin.write(JSON.stringify({ command, args }) + '\n'); + })); + tail = result.catch(() => {}); + return result; + }; + } + const realHost = rustHost(false); + const emptyHost = rustHost(true); + async function startServer(mode) { + const server = createServer(async (request, response) => { + try { + const url = new URL(request.url, 'http://127.0.0.1'); + if (url.pathname.startsWith('/api/workflow/commands/')) { + if (request.method !== 'POST') { response.writeHead(405).end(); return; } + let body = ''; for await (const chunk of request) { body += chunk; if (body.length > 100000) throw new Error('request too large'); } + const command = decodeURIComponent(url.pathname.split('/').at(-1)); + const args = JSON.parse(body); + commands.push(command); + const result = mode === 'error' ? { ok: false, error: { code: 'runtime_not_ready', message: 'Qualification host unavailable' } } : await (mode === 'empty' ? emptyHost : realHost)(command, args); + if (result.ok && command === 'create_custom_node_draft') sessions.push(result.value.session_id); + response.writeHead(result.ok ? 200 : 400, { 'Content-Type': 'application/json' }).end(JSON.stringify(result.ok ? result.value : result.error)); + return; + } + const relative = url.pathname === '/' ? 'index.html' : url.pathname.slice(1); + const file = path.resolve(fixture, 'dist', relative); + if (!file.startsWith(path.resolve(fixture, 'dist') + path.sep)) { response.writeHead(403).end(); return; } + response.setHeader('Content-Type', file.endsWith('.js') ? 'application/javascript' : 'text/html'); + response.end(await readFile(file)); + } catch (error) { response.writeHead(500, { 'Content-Type': 'application/json' }).end(JSON.stringify({ code: 'internal_error', message: String(error) })); } + }); + servers.push(server); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + return `http://127.0.0.1:${server.address().port}`; + } + const realOrigin = await startServer('real'); + const emptyOrigin = await startServer('empty'); + const errorOrigin = await startServer('error'); + const profile = path.join(fixture, 'profile'); + // This disposable container cannot provide the Chromium user-namespace sandbox. + // These verification flags do not modify the normal application launcher. + browser = spawn(process.env.CHROMIUM_BINARY || 'chromium', ['--headless=new', '--no-sandbox', '--disable-gpu', '--disable-background-networking', '--no-first-run', '--no-default-browser-check', '--user-data-dir=' + profile, '--remote-debugging-port=0', 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, XDG_CONFIG_HOME: path.join(fixture, 'config'), XDG_CACHE_HOME: path.join(fixture, 'cache') } }); + let diagnostics = ''; browser.stderr.on('data', chunk => { diagnostics = (diagnostics + chunk).slice(-16384); }); + let port; + const deadline = Date.now() + 10000; + while (!port && Date.now() < deadline) { + try { port = (await readFile(path.join(profile, 'DevToolsActivePort'), 'utf8')).split('\n')[0]; } + catch { await new Promise(resolve => setTimeout(resolve, 50)); } + } + assert.ok(port, 'Chromium startup unavailable: ' + diagnostics); + const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); + socket = new WebSocket(pages.find(page => page.type === 'page').webSocketDebuggerUrl); + await new Promise((resolve, reject) => { socket.addEventListener('open', resolve, { once: true }); socket.addEventListener('error', reject, { once: true }); }); + let sequence = 0; const pending = new Map(); + socket.addEventListener('message', event => { + const message = JSON.parse(event.data); const item = pending.get(message.id); if (!item) return; + pending.delete(message.id); clearTimeout(item.timer); + if (message.error) item.reject(new Error(JSON.stringify(message.error))); else item.resolve(message.result); + }); + const call = (method, params = {}) => new Promise((resolve, reject) => { + const id = ++sequence; + const timer = setTimeout(() => { pending.delete(id); reject(new Error(method + ' timeout')); }, 15000); + pending.set(id, { resolve, reject, timer }); socket.send(JSON.stringify({ id, method, params })); + }); + const evaluate = (callback, args) => evaluateBrowserFunction(call, callback, args); + const text = () => evaluate(() => document.body.innerText); + async function waitText(expected) { + const deadline = Date.now() + 10000; + while (Date.now() < deadline) { if ((await text()).includes(expected)) return; await new Promise(resolve => setTimeout(resolve, 30)); } + assert.fail(`Missing UI text: ${expected}\n${await text()}\nCommands: ${JSON.stringify(commands)}`); + } + async function navigate(origin) { + await call('Page.navigate', { url: `${origin}/?workflowHost=${encodeURIComponent(origin)}` }); + await waitText('NodeLab'); + } + async function clickButton(label) { + const rect = await evaluate(label => { + const button = [...document.querySelectorAll('button')].find(item => item.textContent.trim() === label); + if (!button || button.disabled) throw new Error('Button unavailable: ' + label); + button.scrollIntoView(); const rect = button.getBoundingClientRect(); return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; + }, [label]); + await call('Input.dispatchMouseEvent', { type: 'mousePressed', button: 'left', clickCount: 1, ...rect }); + await call('Input.dispatchMouseEvent', { type: 'mouseReleased', button: 'left', clickCount: 1, ...rect }); + } + async function enter(selector, value) { + await evaluate(selector => { const input = document.querySelector(selector); input.focus(); }, [selector]); + await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'a', code: 'KeyA', modifiers: 2, windowsVirtualKeyCode: 65 }); + await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', modifiers: 2, windowsVirtualKeyCode: 65 }); + await call('Input.insertText', { text: value }); + } + await navigate(emptyOrigin); await waitText('This host has no admitted custom nodes'); + assert.equal(await evaluate(() => [...document.querySelectorAll('button')].some(button => button.textContent.startsWith('Create '))), false); + await navigate(errorOrigin); await waitText('Qualification host unavailable'); + assert.equal(await evaluate(() => document.querySelector('[role="alert"]')?.textContent), 'Qualification host unavailable'); + await navigate(realOrigin); await waitText('Create Host uppercase draft'); + // Tab/Enter activation proves keyboard access to creation, followed by real pointer actions. + await evaluate(() => document.activeElement?.blur()); + for (let count = 0; count < 10; count++) { + await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }); + await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }); + if (await evaluate(() => document.activeElement?.textContent === 'Create Host uppercase draft')) break; + } + assert.equal(await evaluate(() => document.activeElement?.textContent), 'Create Host uppercase draft'); + assert.equal(await evaluate(() => getComputedStyle(document.activeElement).outlineStyle !== 'none'), true); + await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r', unmodifiedText: '\r' }); + await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }); + await waitText('Graph contract valid'); + await enter('textarea', 'Saved Mixed case'); await clickButton('Apply input'); await waitText('Input saved in draft'); + await clickButton('Save workflow'); await waitText('Workflow saved'); + const savedPath = await evaluate(() => document.querySelector('code')?.textContent); + assert.ok(savedPath); + const file = (await realHost('load_workflow', { path: savedPath })).value; + assert.equal(file.graph.nodes.find(node => node.node_type === 'text-input').data.text, 'Saved Mixed case'); + const pin = file.graph.nodes.find(node => node.id === 'custom').data.custom_node_identity; + await enter('input', savedPath); await clickButton('Reopen saved workflow'); await waitText('Graph contract valid'); + assert.equal(await evaluate(() => document.querySelector('textarea')?.value), 'Saved Mixed case'); + const reloaded = (await realHost('load_workflow', { path: savedPath })).value; + assert.deepEqual(reloaded.graph.nodes.find(node => node.id === 'custom').data.custom_node_identity, pin); + assert.equal((await realHost('get_node_lab_draft', { executionId: sessions[0] })).error.code, 'session_not_found'); + // Same saved graph opened on a host without its implementation stays visible and blocked. + await emptyHost('save_workflow', { name: 'stale', graph: file.graph }); + await navigate(emptyOrigin); await waitText('This host has no admitted custom nodes'); + await enter('input', '.pantograph/workflows/stale.json'); await clickButton('Reopen saved workflow'); await waitText('Blocks execution:'); + assert.ok((await text()).includes('host-uppercase')); + assert.ok(!commands.some(command => command.includes('run_execution') || command.includes('register') || command.includes('publish'))); + console.log(JSON.stringify({ ok: true, claims: ['real empty catalog', 'transport failure distinct from empty', 'keyboard creation and visible focus', 'pointer edit/save/reopen through Rust filesystem', 'exact pin preserved', 'replaced session closed', 'missing implementation visible and blocking'], mode: 'headless Chromium, disposable profile, no sandbox, GPU disabled', nativeTauri: 'not qualified' }, null, 2)); +} finally { + socket?.close(); + if (browser && browser.exitCode === null) { browser.kill('SIGTERM'); await new Promise(resolve => { browser.once('exit', resolve); setTimeout(resolve, 2000).unref(); }); } + for (const server of servers) await new Promise(resolve => server.close(resolve)); + for (const host of hosts) { host.stdin.end(); if (host.exitCode === null) await new Promise(resolve => { host.once('exit', resolve); setTimeout(() => { host.kill('SIGTERM'); resolve(); }, 2000).unref(); }); } + await rm(fixture, { recursive: true, force: true }); +} diff --git a/src-tauri/src/app_setup.rs b/src-tauri/src/app_setup.rs index 2aa8cee7f..10472587b 100644 --- a/src-tauri/src/app_setup.rs +++ b/src-tauri/src/app_setup.rs @@ -461,6 +461,9 @@ pub fn run_app() -> AppStartupResult<()> { crate::llm::reset_recovery_state, // Workflow commands crate::workflow::commands::validate_workflow_connection, + crate::workflow::commands::get_custom_node_authoring_catalog, + crate::workflow::commands::create_custom_node_draft, + crate::workflow::commands::get_node_lab_draft, crate::workflow::commands::get_node_definitions, crate::workflow::commands::get_node_definitions_by_category, crate::workflow::commands::get_node_definition, diff --git a/src-tauri/src/workflow/commands.rs b/src-tauri/src/workflow/commands.rs index 6b2b64548..8b5550b93 100644 --- a/src-tauri/src/workflow/commands.rs +++ b/src-tauri/src/workflow/commands.rs @@ -49,6 +49,40 @@ pub fn validate_workflow_connection(source_type: PortDataType, target_type: Port super::workflow_definition_commands::validate_workflow_connection(source_type, target_type) } +/// Read-only host admissions; no registration or code upload command. +#[command] +pub fn get_custom_node_authoring_catalog( + workflow_service: State<'_, SharedWorkflowService>, +) -> pantograph_workflow_service::custom_nodes::authoring::CustomNodeAuthoringCatalog { + workflow_service.custom_node_authoring_catalog() +} + +#[command] +pub async fn create_custom_node_draft( + request: pantograph_workflow_service::custom_nodes::authoring::CustomNodeDraftRequest, + workflow_service: State<'_, SharedWorkflowService>, +) -> Result { + workflow_service + .create_custom_node_draft(request) + .await + .map_err(|error| error.to_envelope_json()) +} + +#[command] +pub async fn get_node_lab_draft( + execution_id: String, + workflow_service: State<'_, SharedWorkflowService>, +) -> Result { + workflow_service + .workflow_graph_get_edit_session_graph( + pantograph_workflow_service::WorkflowGraphEditSessionGraphRequest { + session_id: execution_id, + }, + ) + .await + .map_err(|error| error.to_envelope_json()) +} + #[command] pub fn get_node_definitions() -> Vec { super::workflow_definition_commands::get_node_definitions() diff --git a/src/components/workbench/NodeLabPage.svelte b/src/components/workbench/NodeLabPage.svelte index ffb8f1863..dea945294 100644 --- a/src/components/workbench/NodeLabPage.svelte +++ b/src/components/workbench/NodeLabPage.svelte @@ -1,23 +1,90 @@ -
-

Node Editor

-
- {nodeLabUnavailableMessage()} -
-
+
+

NodeLab

+

{nodeLabTrustMessage()}

+
{#each statusRows as row (row.label)}
-
{row.label}
+
{row.label}
{row.value}
{/each}
+ {#if view.error}{/if} +

{view.busy ? 'Working…' : view.notice}

+ {#if view.pendingCleanup} + + + {/if} +

Admitted nodes

+ + {#if view.catalog?.length === 0} +

This host has no admitted custom nodes. A host maintainer must register a trusted implementation before creating a new draft.

+ {:else if view.catalog} +
    + {#each view.catalog as entry (entry.identity.node_type)} +
  • +

    {entry.label}

    +

    {entry.description}

    +

    {entry.inputs.length} string inputs · {entry.outputs.length} string outputs · Trusted in-process

    +
    + Implementation identity +
    {JSON.stringify(entry.identity, null, 2)}
    +
    + +
  • + {/each} +
+ {/if} +
{ event.preventDefault(); void controller.reopen(path); }}> + + +
+ {#if view.savedPath}

Saved: {view.savedPath}

{/if} + {#if view.draft} +
+

Workflow draft

+

{view.draft.graph.nodes.length} nodes · {view.draft.graph.edges.length} connections. Saving preserves the selected implementation identity. Run saved workflows from Scheduler.

+ {#if view.draft.graph_diagnostics.length} +
    + {#each view.draft.graph_diagnostics as diagnostic} +
  • {diagnostic.blocking_submission ? 'Blocks execution: ' : ''}{diagnostic.message}
  • + {/each} +
+ {:else}

Graph contract valid

{/if} + {#each view.draft.graph.nodes.filter(node => node.node_type === 'text-input') as node (node.id)} +
{ event.preventDefault(); const input = new FormData(event.currentTarget).get('text'); if (typeof input === 'string') void controller.update(node, input); }}> + + +
+ {/each} +
{ event.preventDefault(); void controller.save(name); }}> + + +
+
+ {/if}
diff --git a/src/components/workbench/nodeLabController.ts b/src/components/workbench/nodeLabController.ts new file mode 100644 index 000000000..122609ce6 --- /dev/null +++ b/src/components/workbench/nodeLabController.ts @@ -0,0 +1,86 @@ +import { NodeLabService, type CustomNodeAuthoringEntry, type NodeLabDraft } from '../../services/workflow/customNodeAuthoring.ts'; +import type { GraphNode } from '../../services/workflow/types.ts'; + +export interface NodeLabView { + catalog: CustomNodeAuthoringEntry[] | null; + draft: NodeLabDraft | null; + savedPath: string; + busy: boolean; + error: string | null; + notice: string; + pendingCleanup: number; +} +/** One page owns one separate edit session and observes all in-flight completion. */ +export class NodeLabController { + private disposed = false; + private operation: Promise | null = null; + private readonly ownedSessions = new Set(); + cleanupError: unknown = null; + readonly view: NodeLabView = { catalog: null, draft: null, savedPath: '', busy: false, error: null, notice: '', pendingCleanup: 0 }; + private readonly service: NodeLabService; + private readonly changed: (view: NodeLabView) => void; + constructor(service: NodeLabService, changed: (view: NodeLabView) => void) { this.service = service; this.changed = changed; this.view.pendingCleanup = service.pendingCleanupCount; } + private publish(): void { if (!this.disposed) this.changed({ ...this.view }); } + private perform(action: () => Promise): Promise { + if (this.disposed || this.operation) return Promise.resolve(); + this.view.busy = true; this.view.error = null; this.view.notice = ''; this.publish(); + const operation = (async () => { + try { await action(); } + catch (error) { this.view.error = error instanceof Error ? error.message : 'NodeLab operation failed'; } + finally { this.view.busy = false; this.operation = null; this.view.pendingCleanup = this.service.pendingCleanupCount; this.publish(); } + })(); + this.operation = operation; + return operation; + } + retryCleanup(): Promise { return this.perform(() => this.service.retryCleanup()); } + loadCatalog(): Promise { + return this.perform(async () => { this.view.catalog = await this.service.catalog(); }); + } + private async replace(create: () => Promise): Promise { + const next = await create(); + this.ownedSessions.add(next.session_id); + if (this.view.draft) { + try { + await this.service.close(this.view.draft.session_id); + this.ownedSessions.delete(this.view.draft.session_id); + } catch (error) { + this.service.retainActiveSession(this.view.draft.session_id); + try { await this.service.close(next.session_id); this.ownedSessions.delete(next.session_id); } + catch (cleanupError) { this.cleanupError = cleanupError; throw new AggregateError([error, cleanupError], 'Draft replacement and cleanup failed; previous draft retained'); } + throw error; + } + } + this.view.draft = next; + this.view.savedPath = ''; + } + create(entry: CustomNodeAuthoringEntry): Promise { + return this.perform(() => this.replace(() => this.service.create(entry.identity))); + } + reopen(path: string): Promise { + return this.perform(async () => { await this.replace(() => this.service.reopen(path)); this.view.savedPath = path; }); + } + update(node: GraphNode, text: string): Promise { + return this.perform(async () => { + if (!this.view.draft) throw new Error('No NodeLab draft'); + this.view.draft = await this.service.update(this.view.draft.session_id, node, text); + this.view.notice = 'Input saved in draft'; + }); + } + save(name: string): Promise { + return this.perform(async () => { + if (!this.view.draft) throw new Error('No NodeLab draft'); + const result = await this.service.save(this.view.draft.session_id, name); + this.view.draft = result.draft; this.view.savedPath = result.path; this.view.notice = 'Workflow saved'; + }); + } + async dispose(): Promise { + this.disposed = true; + await this.operation; + for (const id of this.ownedSessions) { + try { + await this.service.close(id); this.ownedSessions.delete(id); + if (this.view.draft?.session_id === id) this.view.draft = null; + } catch (error) { this.cleanupError = error; } + } + } +} diff --git a/src/components/workbench/nodeLabPresenters.test.ts b/src/components/workbench/nodeLabPresenters.test.ts index a83fd6967..c279c61d0 100644 --- a/src/components/workbench/nodeLabPresenters.test.ts +++ b/src/components/workbench/nodeLabPresenters.test.ts @@ -1,16 +1,13 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { buildNodeLabStatusRows, nodeLabTrustMessage } from './nodeLabPresenters.ts'; -import { - buildNodeLabStatusRows, - nodeLabUnavailableMessage, -} from './nodeLabPresenters.ts'; - -test('node lab presenters expose a disabled state without authoring affordances', () => { - assert.equal(nodeLabUnavailableMessage(), 'Node authoring is unavailable in this build'); +test('NodeLab distinguishes admitted graph authoring from unsupported code publishing', () => { + assert.match(nodeLabTrustMessage(), /trusted in-process/); + assert.match(nodeLabTrustMessage(), /cannot install or publish code/); assert.deepEqual(buildNodeLabStatusRows(), [ - { label: 'Authoring API', value: 'Unavailable' }, + { label: 'Graph authoring', value: 'Host-admitted nodes' }, { label: 'Local Agent', value: 'Unavailable' }, - { label: 'Runtime Publishing', value: 'Unavailable' }, + { label: 'Runtime Publishing', value: 'Unsupported' }, ]); }); diff --git a/src/components/workbench/nodeLabPresenters.ts b/src/components/workbench/nodeLabPresenters.ts index 530bb2dd5..abea6cb53 100644 --- a/src/components/workbench/nodeLabPresenters.ts +++ b/src/components/workbench/nodeLabPresenters.ts @@ -1,16 +1,11 @@ -export interface NodeLabStatusRow { - label: string; - value: string; -} - +export interface NodeLabStatusRow { label: string; value: string } export function buildNodeLabStatusRows(): NodeLabStatusRow[] { return [ - { label: 'Authoring API', value: 'Unavailable' }, + { label: 'Graph authoring', value: 'Host-admitted nodes' }, { label: 'Local Agent', value: 'Unavailable' }, - { label: 'Runtime Publishing', value: 'Unavailable' }, + { label: 'Runtime Publishing', value: 'Unsupported' }, ]; } - -export function nodeLabUnavailableMessage(): string { - return 'Node authoring is unavailable in this build'; +export function nodeLabTrustMessage(): string { + return 'These nodes are supplied by this host and run as trusted in-process code. NodeLab creates workflows; it cannot install or publish code.'; } diff --git a/src/services/workflow/customNodeAuthoring.test.ts b/src/services/workflow/customNodeAuthoring.test.ts new file mode 100644 index 000000000..88d976738 --- /dev/null +++ b/src/services/workflow/customNodeAuthoring.test.ts @@ -0,0 +1,143 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { NodeLabService, parseCustomNodeCatalog, parseNodeLabDraft } from './customNodeAuthoring.ts'; +import { NodeLabController } from '../../components/workbench/nodeLabController.ts'; + +const identity = { node_type: 'custom-uppercase', contract_version: '1.0.0', contract_digest: `contract-blake3:${'c'.repeat(64)}`, implementation_digest: `blake3:${'a'.repeat(64)}`, environment_digest: `blake3:${'b'.repeat(64)}`, adapter_version: 1 }; +const entry = { identity, label: 'Uppercase', description: 'Host transform', trust: 'trusted_in_process', inputs: [{ id: 'input', label: 'Input' }], outputs: [{ id: 'output', label: 'Output' }] }; +const catalog = () => ({ contract_version: 1, nodes: [structuredClone(entry)] }); +const snapshot = (id = 'edit-1') => ({ session_id: id, graph_revision: 'revision-1', graph: { nodes: [{ id: 'source', node_type: 'text-input', position: { x: 0, y: 0 }, data: { text: 'draft' } }], edges: [] }, graph_diagnostics: [] }); + +test('catalog decoder requires complete v1 identity, trust, ports and extra-field policy', () => { + assert.equal(parseCustomNodeCatalog(catalog())[0].identity.environment_digest, identity.environment_digest); + assert.deepEqual(parseCustomNodeCatalog({ contract_version: 1, nodes: [] }), []); + const invalid: unknown[] = [null, [], { ...catalog(), contract_version: 2 }, { ...catalog(), extra: true }, { ...catalog(), nodes: {} }]; + for (const patch of [ + { trust: 'sandbox' }, { inputs: [] }, { outputs: [{ id: 'output', label: 1 }] }, + { identity: { ...identity, adapter_version: 2 } }, { identity: { ...identity, implementation_digest: 'unverified' } }, + { identity: { ...identity, extra: true } }, { identity: { ...identity, contract_digest: 'bad' } }, { identity: { ...identity, contract_version: 'not-semver' } }, { identity: { ...identity, node_type: 'bad type' } }, { inputs: [{ id: 'x', label: 'X' }, { id: 'x', label: 'Again' }] }, + ]) invalid.push({ contract_version: 1, nodes: [{ ...entry, ...patch }] }); + for (const value of invalid) assert.throws(() => parseCustomNodeCatalog(value)); + assert.throws(() => parseCustomNodeCatalog({ contract_version: 1, nodes: [entry, entry] })); +}); + +test('draft decoder refuses malformed graph and diagnostics before exposing state', () => { + assert.equal(parseNodeLabDraft(snapshot()).graph.nodes[0].data.text, 'draft'); + for (const value of [{ ...snapshot(), graph: { nodes: [{}], edges: [] } }, { ...snapshot(), graph_diagnostics: [{ message: 'invalid' }] }, { ...snapshot(), session_id: '' }, { ...snapshot(), graph_diagnostics: null }]) assert.throws(() => parseNodeLabDraft(value)); +}); + +test('service forwards exact selection and refuses changed-session response', async () => { + const calls: [string, Record | undefined][] = []; + const service = new NodeLabService(async (command, args) => { calls.push([command, args]); return snapshot(); }); + await service.create(identity); + assert.deepEqual(calls[0], ['create_custom_node_draft', { request: { identity } }]); + await assert.rejects(service.snapshot('other-session'), /correlation mismatch/); +}); + +test('invalid newly created response closes its session instead of leaking it', async () => { + const closed: string[] = []; + const service = new NodeLabService(async (command, args) => { + if (command === 'remove_execution') { closed.push(String(args?.executionId)); return null; } + return { session_id: 'created', graph: 'broken' }; + }); + await assert.rejects(service.create(identity), /Invalid NodeLab text/); + assert.deepEqual(closed, ['created']); +}); + +test('controller distinguishes empty catalog from failure and closes superseded drafts', async () => { + let fail = false; + let counter = 0; + const closed: string[] = []; + const service = new NodeLabService(async (command, args) => { + if (command === 'get_custom_node_authoring_catalog') { + if (fail) throw new Error('host unavailable'); + return { contract_version: 1, nodes: [] }; + } + if (command === 'remove_execution') { closed.push(String(args?.executionId)); return null; } + return snapshot(`edit-${++counter}`); + }); + const controller = new NodeLabController(service, () => {}); + await controller.loadCatalog(); assert.deepEqual(controller.view.catalog, []); assert.equal(controller.view.error, null); + fail = true; await controller.loadCatalog(); assert.equal(controller.view.error, 'host unavailable'); + const selected = parseCustomNodeCatalog(catalog())[0]; + await controller.create(selected); await controller.create(selected); + assert.deepEqual(closed, ['edit-1']); + await controller.dispose(); assert.deepEqual(closed, ['edit-1', 'edit-2']); +}); + +test('dispose observes in-flight creation, prevents obsolete publication and releases the late session', async () => { + let complete!: (value: unknown) => void; + const pending = new Promise(resolve => { complete = resolve; }); + const closed: string[] = []; + let published = 0; + const service = new NodeLabService(async (command, args) => { + if (command === 'remove_execution') { closed.push(String(args?.executionId)); return null; } + return pending; + }); + const controller = new NodeLabController(service, () => { published++; }); + const create = controller.create(parseCustomNodeCatalog(catalog())[0]); + const before = published; + const disposed = controller.dispose(); + complete(snapshot('late')); + await Promise.all([create, disposed]); + assert.equal(published, before); assert.deepEqual(closed, ['late']); assert.equal(controller.cleanupError, null); +}); + +test('close failure compensates the new session and retains the old draft', async () => { + let created = 0; + const closed: unknown[] = []; + const service = new NodeLabService(async (command, args) => { + if (command === 'remove_execution') { + closed.push(args?.executionId); + if (args?.executionId === 'edit-1') throw new Error('close refused'); + return null; + } + return snapshot(`edit-${++created}`); + }); + const controller = new NodeLabController(service, () => {}); + const selected = parseCustomNodeCatalog(catalog())[0]; + await controller.create(selected); await controller.create(selected); + assert.equal(created, 2); assert.equal(controller.view.error, 'close refused'); + assert.equal(controller.view.draft?.session_id, 'edit-1'); + assert.deepEqual(closed, ['edit-1', 'edit-2']); + await controller.dispose(); assert.match(String(controller.cleanupError), /close refused/); +}); + +test('failed stale selection or reopen retains current edited draft and save path', async () => { + let refuse = false; + const closed: unknown[] = []; + const service = new NodeLabService(async (command, args) => { + if (command === 'remove_execution') { closed.push(args?.executionId); return null; } + if (refuse) throw new Error('selection/path unavailable'); + return snapshot('current'); + }); + const controller = new NodeLabController(service, () => {}); + const selected = parseCustomNodeCatalog(catalog())[0]; + await controller.create(selected); + controller.view.savedPath = 'existing.json'; + const before = structuredClone(controller.view.draft); + refuse = true; + await controller.create(selected); + assert.deepEqual(controller.view.draft, before); assert.equal(controller.view.savedPath, 'existing.json'); + await controller.reopen('missing.json'); + assert.deepEqual(controller.view.draft, before); assert.equal(controller.view.savedPath, 'existing.json'); + assert.deepEqual(closed, []); + await controller.dispose(); assert.deepEqual(closed, ['current']); +}); + +test('app service retains failed malformed-response cleanup across page owners until explicit recovery', async () => { + let closeFails = true; + const service = new NodeLabService(async command => { + if (command === 'remove_execution') { if (closeFails) throw new Error('offline'); return null; } + return { session_id: 'known-created', graph_revision: 'revision', graph: null }; + }); + await assert.rejects(service.create(identity), /offline/); + assert.equal(service.pendingCleanupCount, 1); + const nextPage = new NodeLabController(service, () => {}); + assert.equal(nextPage.view.pendingCleanup, 1); + await assert.rejects(service.create(identity), /Close previous/); + closeFails = false; + await nextPage.retryCleanup(); + assert.equal(nextPage.view.pendingCleanup, 0); assert.equal(service.pendingCleanupCount, 0); + await nextPage.dispose(); +}); diff --git a/src/services/workflow/customNodeAuthoring.ts b/src/services/workflow/customNodeAuthoring.ts new file mode 100644 index 000000000..995ea61e0 --- /dev/null +++ b/src/services/workflow/customNodeAuthoring.ts @@ -0,0 +1,184 @@ +// Wire authority: custom_nodes/authoring.rs (catalog v1) and graph/session_contract.rs. +import type { GraphNode, WorkflowGraph } from './types.ts'; +import { invokeWorkflowCommand } from './workflowServiceErrors.ts'; + +export interface CustomNodeIdentity { + node_type: string; + contract_version: string; + contract_digest: string; + implementation_digest: string; + environment_digest: string; + adapter_version: number; +} +export interface CustomNodeAuthoringEntry { + identity: CustomNodeIdentity; + label: string; + description: string; + trust: 'trusted_in_process'; + inputs: { id: string; label: string }[]; + outputs: { id: string; label: string }[]; +} +export interface NodeLabDraft { + session_id: string; + graph_revision: string; + graph: WorkflowGraph; + graph_diagnostics: { message: string; blocking_submission: boolean }[]; +} +function record(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid NodeLab object'); + return value as Record; +} +function exact(value: unknown, keys: string[]): Record { + const item = record(value); + if (Object.keys(item).length !== keys.length || keys.some(key => !(key in item))) throw new Error('Invalid NodeLab fields'); + return item; +} +function text(value: unknown): string { + if (typeof value !== 'string') throw new Error('Invalid NodeLab text'); + return value; +} +function identifier(value: unknown): string { + const id = text(value); + if (!id.trim()) throw new Error('Invalid NodeLab identifier'); + return id; +} +function contractId(value: unknown): string { + const id = identifier(value); + // NodeTypeId/PortId grammar in pantograph-node-contracts; do not normalize pins. + if (id.length > 128 || !/^[A-Za-z0-9_.:-]+$/.test(id)) throw new Error('Invalid custom-node contract identifier'); + return id; +} +export function parseCustomNodeIdentity(value: unknown): CustomNodeIdentity { + const item = exact(value, ['node_type', 'contract_version', 'contract_digest', 'implementation_digest', 'environment_digest', 'adapter_version']); + if (item.adapter_version !== 1) throw new Error('Unsupported custom-node adapter version'); + for (const key of ['implementation_digest', 'environment_digest']) { + if (!/^blake3:[0-9a-f]{64}$/.test(text(item[key]))) throw new Error('Invalid custom-node attestation'); + } + if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(text(item.contract_version)) || !/^contract-blake3:[0-9a-f]{64}$/.test(text(item.contract_digest))) throw new Error('Invalid custom-node contract identity'); + return { + node_type: contractId(item.node_type), contract_version: text(item.contract_version), + contract_digest: identifier(item.contract_digest), implementation_digest: text(item.implementation_digest), + environment_digest: text(item.environment_digest), adapter_version: 1, + }; +} +export function parseCustomNodeCatalog(value: unknown): CustomNodeAuthoringEntry[] { + const catalog = exact(value, ['contract_version', 'nodes']); + if (catalog.contract_version !== 1) throw new Error('Unsupported NodeLab catalog version'); + if (!Array.isArray(catalog.nodes)) throw new Error('Invalid NodeLab catalog'); + const seen = new Set(); + return catalog.nodes.map(value => { + const item = exact(value, ['identity', 'label', 'description', 'trust', 'inputs', 'outputs']); + const identity = parseCustomNodeIdentity(item.identity); + if (seen.has(identity.node_type)) throw new Error('Duplicate NodeLab type'); + seen.add(identity.node_type); + if (item.trust !== 'trusted_in_process') throw new Error('Unsupported custom-node trust profile'); + const ports = (value: unknown) => { + if (!Array.isArray(value) || value.length < 1 || value.length > 8) throw new Error('Invalid NodeLab ports'); + const seen = new Set(); + return value.map(value => { + const port = exact(value, ['id', 'label']); + const id = contractId(port.id); + if (id.startsWith('_')) throw new Error('Invalid reserved custom-node port'); + if (seen.has(id)) throw new Error('Duplicate NodeLab port'); + seen.add(id); + return { id, label: text(port.label) }; + }); + }; + return { identity, label: text(item.label), description: text(item.description), trust: 'trusted_in_process', inputs: ports(item.inputs), outputs: ports(item.outputs) }; + }); +} +function parseGraph(value: unknown): WorkflowGraph { + const graph = record(value); + if (!Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) throw new Error('Invalid NodeLab graph'); + const nodes = graph.nodes.map(value => { + const node = record(value); + const position = record(node.position); + if (typeof position.x !== 'number' || !Number.isFinite(position.x) || typeof position.y !== 'number' || !Number.isFinite(position.y)) throw new Error('Invalid NodeLab position'); + return { id: identifier(node.id), node_type: identifier(node.node_type), position: { x: position.x, y: position.y }, data: record(node.data) }; + }); + const edges = graph.edges.map(value => { + const edge = record(value); + return { id: identifier(edge.id), source: identifier(edge.source), source_handle: identifier(edge.source_handle), target: identifier(edge.target), target_handle: identifier(edge.target_handle) }; + }); + return { nodes, edges }; +} +export function parseNodeLabDraft(value: unknown): NodeLabDraft { + const draft = record(value); + const diagnostics = draft.graph_diagnostics === undefined ? [] : draft.graph_diagnostics; + if (!Array.isArray(diagnostics)) throw new Error('Invalid NodeLab diagnostics'); + return { + session_id: identifier(draft.session_id), graph_revision: identifier(draft.graph_revision), graph: parseGraph(draft.graph), + graph_diagnostics: diagnostics.map(value => { + const item = record(value); + if (typeof item.blocking_submission !== 'boolean') throw new Error('Invalid NodeLab diagnostic'); + return { message: text(item.message), blocking_submission: item.blocking_submission }; + }), + }; +} + +export class NodeLabService { + // App-scoped recovery ownership for transport/close failures, never an execution registry. + private readonly pendingCloses = new Set(); + get pendingCleanupCount(): number { return this.pendingCloses.size; } + // A failed replacement keeps the old draft under its still-active controller. + retainActiveSession(id: string): void { this.pendingCloses.delete(id); } + async retryCleanup(): Promise { + const errors: unknown[] = []; + for (const id of [...this.pendingCloses]) { try { await this.close(id); } catch (error) { errors.push(error); } } + if (errors.length) throw new AggregateError(errors, 'Some NodeLab sessions could not be closed'); + } + private requireCleanupResolved(): void { + if (this.pendingCloses.size) throw new Error('Close previous NodeLab sessions before creating or reopening a draft'); + } + private readonly invoke: (command: string, args?: Record) => Promise; + constructor(invoke: (command: string, args?: Record) => Promise = invokeWorkflowCommand) { this.invoke = invoke; } + async catalog(): Promise { + return parseCustomNodeCatalog(await this.invoke('get_custom_node_authoring_catalog')); + } + private async ownedDraft(response: unknown): Promise { + const id = identifier(record(response).session_id); + try { return parseNodeLabDraft(response); } + catch (error) { await this.close(id); throw error; } + } + async create(identity: CustomNodeIdentity): Promise { + this.requireCleanupResolved(); + return this.ownedDraft(await this.invoke('create_custom_node_draft', { request: { identity } })); + } + async reopen(path: string): Promise { + this.requireCleanupResolved(); + const saved = record(await this.invoke('load_workflow', { path })); + const graph = parseGraph(saved.graph); + const session = record(await this.invoke('create_workflow_execution_session', { graph, workflowId: path })); + const id = identifier(session.session_id); + try { return await this.snapshot(id); } + catch (error) { await this.close(id); throw error; } + } + async snapshot(id: string): Promise { + const draft = parseNodeLabDraft(await this.invoke('get_node_lab_draft', { executionId: id })); + if (draft.session_id !== id) throw new Error('NodeLab session correlation mismatch'); + return draft; + } + async update(id: string, node: GraphNode, value: string): Promise { + // Source values are authored text; custom identities/definitions never use this path. + if (node.node_type !== 'text-input') throw new Error('NodeLab only edits text sources'); + const draft = parseNodeLabDraft(await this.invoke('update_node_data', { executionId: id, nodeId: node.id, data: { text: value } })); + if (draft.session_id !== id) throw new Error('NodeLab session correlation mismatch'); + return draft; + } + async save(id: string, name: string): Promise<{ draft: NodeLabDraft; path: string }> { + const draft = await this.snapshot(id); + const path = identifier(await this.invoke('save_workflow', { name, graph: draft.graph })); + return { draft, path }; + } + async close(id: string): Promise { + try { await this.invoke('remove_execution', { executionId: id }); this.pendingCloses.delete(id); } + catch (error) { + // Already absent is a terminal close outcome; other failures retain exact ownership. + if (error && typeof error === 'object' && 'code' in error && error.code === 'session_not_found') { this.pendingCloses.delete(id); return; } + this.pendingCloses.add(id); throw error; + } + } +} + +// Workbench lifetime owner: failed closes survive NodeLab page navigation. +export const nodeLabService = new NodeLabService(); From d503ed305448e9e36b8a54f2bc393d263803fe58 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 22 Oct 2026 02:35:34 +0000 Subject: [PATCH 02/15] fix(nodelab): key projected graph diagnostics --- .../evidence/nodelab-authoring/browser.log.gz | Bin 441 -> 441 bytes .../nodelab-authoring/qualification.json | 4 ++-- src/components/workbench/NodeLabPage.svelte | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz index ec6e6c01c5b6d92e7d5f711e3f8f19252feaee63..685a06aa6d63b9419d3576a7161c5a2a3d99454b 100644 GIT binary patch delta 318 zcmV-E0m1&c1Gxi`8GqCi)FUAERv{<{gg7|%B$=-N@Yt)QhzqX(N1m=v!Z@oGslNI9 znfYeyi3-AWt*+Dn+e*$-*uySnNIBYS3dNw5>Ppsu1@=O>`_tdwFbr4VMdXm-nMbR- zjKN}Vh0LLbk(fdMwJ)%6SOdZjjJYfImTEkFU*YV(G>A00p+$Nok}skmr2 z<1~2|l1$fsc|qx(q#SKEgiUIsy;4_aYfImTEkFU*YV(@ApB+FS$Nok}skmr2 z<1~2|{view.draft.graph.nodes.length} nodes · {view.draft.graph.edges.length} connections. Saving preserves the selected implementation identity. Run saved workflows from Scheduler.

{#if view.draft.graph_diagnostics.length}
    - {#each view.draft.graph_diagnostics as diagnostic} + {#each view.draft.graph_diagnostics as diagnostic, index (index)}
  • {diagnostic.blocking_submission ? 'Blocks execution: ' : ''}{diagnostic.message}
  • {/each}
From 802544a0ed5f523d2ce7a54f7859b8ed0187e63f Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 22 Oct 2026 02:40:26 +0000 Subject: [PATCH 03/15] test(nodelab): qualify browser with application styles --- .../evidence/nodelab-authoring/browser.log.gz | Bin 441 -> 584 bytes .../nodelab-authoring/qualification.json | 7 ++++--- .../execution-ledger.md | 2 ++ scripts/check-nodelab-browser.mjs | 8 ++++---- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser.log.gz index 685a06aa6d63b9419d3576a7161c5a2a3d99454b..07f9f0f9027ca4ed6844bfd1846afd03d511f9e3 100644 GIT binary patch literal 584 zcmV-O0=NAiiwFP!0000218q~wZWBQeyzf`E%mpNSY-8+zPbdL#LW&R(LWslcPRHBv zyqKPG>>w`u0v!3ed6E-ABr_#0#Js8t73JsyCw8FM_!J{E6ROoRTtd& zzSj6o-?R@BYU8lE{qYT^)4A9(#UjJ6{?MogkjJb5AGdFVMZdP**~Q`H5Og{^UNMsQI*VYwvZ{8OXyz&1c+vmKhJida#s16dcx9 zXEiw%>Y7|7r(po@72oov~L)nIst>}MB4%5bU4mV{8k1!JV<4X~0UF9<)*Bor3=uu#K83RC;Z0#FL9)LcXLLs%Zncz- z(p*d^C$K?t3?+=Ry0zpCgz<4dC^;dN zF%5dTEV06HCiWZ^H>`7rfpz7|?^K-*!3SUwYQuI2ug))OPE9y?7etgDr7clE{zhP`rbe zXQhS}jBnxT&#$xb<_rx2%~s8fh35*d-rs+E__8*4>VW|^uhsPn>w2X&XKPE}hAlt= z)@t*HyB{4uAIJViMya@HH{&#U7UXN!qVyTH1N5n!!04h~-1m!_IZvNrF0j+&YDQ?` zC>Q~9^t0(A9`Uq|I$JPOuE>^cc#V@RF`2 z-MVN-(e&c@c3zZx0+coN2h>)gFuap^o~mE8J*3FGdF4a3qzecUSPE_9aRIjt@9dEeVj diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json index 75b65155d..1d75ffd22 100644 --- a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json +++ b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/qualification.json @@ -5,7 +5,8 @@ "rust": "1.92.0", "node": "24.12.0", "chromium": "Chromium 151.0.7922.173 built on Debian GNU/Linux 13 (trixie)", - "mode": "headless; disposable profile/store; GPU disabled; container verification no-sandbox only" + "mode": "headless; disposable profile/store; GPU disabled; container verification no-sandbox only", + "application_styles": true }, "claims": { "browser_user_workflow": "passed: actual NodeLab -> loopback -> Rust service -> filesystem create/edit/save/reopen; keyboard/pointer and focus; missing implementation blocking; exact pin retained", @@ -37,7 +38,7 @@ "crates/pantograph-workflow-service/src/workflow/service_config.rs": "257edc58a50b37e8dee265b971e91084b0f77b0ce4031f8d105b604f33cea513", "crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs": "aa080d798774771aa419db01d83cd26401684ab06333770a74e209c601e5952f", "scripts/README.md": "03bed3d3d157a4d7e4a9f2a291f4a2ab37efa2e81f87c83e3d5710a38220119a", - "scripts/check-nodelab-browser.mjs": "30a619d382ddb242c19b50c51ec97fda8a6c20973fe51f94c7c0fcf5658d24d4", + "scripts/check-nodelab-browser.mjs": "91505dbfa49defa836a246fcff7317bc6dae795fd257da1ee8747146cebe3357", "src-tauri/src/app_setup.rs": "b14c996956638c5a708156aaf8f110ce6f1fa3a175f6b03bb9ff0284bd392a50", "src-tauri/src/workflow/commands.rs": "24834569833ec6509300b9c8c795b9eb8be233f0c6d9c37c5d67f82b63d24b6c", "src/components/workbench/NodeLabPage.svelte": "ab23063b86e78e3dc919602df48d027f0e736bee678b8e5609eedc41d0da25d2", @@ -48,7 +49,7 @@ "src/services/workflow/customNodeAuthoring.ts": "f4a11c2fa37816819db79176b2af584199c946a5e3c533482cc595362092dc08" }, "evidence_sha256": { - "browser.log.gz": "6a1c002a0a7a2aa962249b01f31b98f5f33e5643f43472cb07b390d8d75c0f74", + "browser.log.gz": "6c2a15df9371220e78251fd39f27631010da2e63d41f45843e9c9dba0c3bc97e", "native-unavailable.log.gz": "f72bc764c185d785964c3ac95e9a0d6f24a1d999aefbd349dc143eed28d261b3" } } diff --git a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md index e6a6f09de..1f3defa2e 100644 --- a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md +++ b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md @@ -836,6 +836,8 @@ an unexported provider and a nonexistent response field; corrected against the actual owning APIs, preserving the assertions. The first browser Enter simulation omitted character text and did not activate the button; proper CDP key events then passed the same workflow assertions, with no pointer fallback for that gate. +Full lint required keys on stateless diagnostic rows; repaired. Final browser +evidence loads the actual application stylesheet and checks nonzero focus outline. Native `cargo check --locked -p pantograph --bin pantograph --no-default-features` is unavailable at glib-sys because this environment lacks `glib-2.0.pc`; GTK and diff --git a/scripts/check-nodelab-browser.mjs b/scripts/check-nodelab-browser.mjs index 76cd26290..76e5496a5 100644 --- a/scripts/check-nodelab-browser.mjs +++ b/scripts/check-nodelab-browser.mjs @@ -26,8 +26,8 @@ const sessions = []; try { await symlink(path.join(repo, 'node_modules'), path.join(fixture, 'node_modules')); await writeFile(path.join(fixture, 'index.html'), '
'); - await writeFile(path.join(fixture, 'main.js'), `import { mount } from 'svelte'; import Page from ${JSON.stringify(path.join(repo, 'src/components/workbench/NodeLabPage.svelte'))}; mount(Page, { target: document.getElementById('app') });`); - await build({ configFile: false, root: fixture, plugins: [svelte()], build: { outDir: 'dist', emptyOutDir: true } }); + await writeFile(path.join(fixture, 'main.js'), `import ${JSON.stringify(path.join(repo, 'src/styles.css'))}; import { mount } from 'svelte'; import Page from ${JSON.stringify(path.join(repo, 'src/components/workbench/NodeLabPage.svelte'))}; mount(Page, { target: document.getElementById('app') });`); + await build({ configFile: false, root: fixture, css: { postcss: repo }, plugins: [svelte()], build: { outDir: 'dist', emptyOutDir: true } }); function rustHost(empty) { const child = spawn(hostBinary, empty ? ['--empty-catalog'] : [], { stdio: ['pipe', 'pipe', 'inherit'] }); hosts.push(child); @@ -64,7 +64,7 @@ try { const relative = url.pathname === '/' ? 'index.html' : url.pathname.slice(1); const file = path.resolve(fixture, 'dist', relative); if (!file.startsWith(path.resolve(fixture, 'dist') + path.sep)) { response.writeHead(403).end(); return; } - response.setHeader('Content-Type', file.endsWith('.js') ? 'application/javascript' : 'text/html'); + response.setHeader('Content-Type', file.endsWith('.js') ? 'application/javascript' : file.endsWith('.css') ? 'text/css' : 'text/html'); response.end(await readFile(file)); } catch (error) { response.writeHead(500, { 'Content-Type': 'application/json' }).end(JSON.stringify({ code: 'internal_error', message: String(error) })); } }); @@ -140,7 +140,7 @@ try { if (await evaluate(() => document.activeElement?.textContent === 'Create Host uppercase draft')) break; } assert.equal(await evaluate(() => document.activeElement?.textContent), 'Create Host uppercase draft'); - assert.equal(await evaluate(() => getComputedStyle(document.activeElement).outlineStyle !== 'none'), true); + assert.equal(await evaluate(() => getComputedStyle(document.activeElement).outlineStyle !== 'none' && parseFloat(getComputedStyle(document.activeElement).outlineWidth) > 0), true); await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r', unmodifiedText: '\r' }); await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }); await waitText('Graph contract valid'); From ff4e4de05d884f05338e70745db2400df0134926 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 22 Oct 2026 04:10:18 +0000 Subject: [PATCH 04/15] fix(nodelab): hide stale catalog choices after refresh failure --- .../nodelab-authoring/browser-refresh.log.gz | Bin 0 -> 617 bytes .../catalog-refresh-red.log.gz | Bin 0 -> 1146 bytes .../nodelab-authoring/qualification.json | 15 ++++++---- .../execution-ledger.md | 18 ++++++++++++ scripts/check-nodelab-browser.mjs | 27 ++++++++++++++++-- src/components/workbench/nodeLabController.ts | 6 +++- .../workflow/customNodeAuthoring.test.ts | 17 +++++++---- 7 files changed, 68 insertions(+), 15 deletions(-) create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser-refresh.log.gz create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/catalog-refresh-red.log.gz diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser-refresh.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser-refresh.log.gz new file mode 100644 index 0000000000000000000000000000000000000000..391ed64af588415c6df5b84da9b76f650b9e8068 GIT binary patch literal 617 zcmV-v0+#(BiwFP!0000219ekPZxb;Pz3;CWg$qcDleA3=IiXgF3x^7U5JCuf*OTlt z{=#FY35W}S0gn8-{u0JX0|mt1{5Wr{_HU;fajCZRW&Y7kvt{FRPBUJ6H3wKe;CpH9M)?>b*X72J$dh^9eVfCF4O@4;B(c!C^gh zR+D2v-Zj<7K!US?F6JF{^2#=>2E)V6KD!uFhNUK35<;Dhd?!E(?m#*guW{D~oeXp$ zShowbH?Se5)}kz4SNK>O1Nn>z&`=(;-rzW4i0C2rDU?+YFAGZxlK0zjMt9`lR!i$B z=3+uwfeo7DRl;a>hXxp#YxB+q{(bF8PRl%D*<`ku zZQZ-h7x>_o75>CSQ8_r+GF2G66`a`I)J(*y+>IB0S5%36d% zf=l0|B|36!hp?F6P;U%LE=EUiR+g=D8k~c}R+od5Y73^Tl2~qybAVif`IAN=s6u0? zAX4NG<+c#{PS}0OQJPLhi&{{>{6WYDvV9rXu96`+qxhp_fK1~uFraZ<=1k{81wQpH z_bAJ<{pAfehb6CUtl4twXqu+UWOOl4XPv0EfERQaeP^9c_$G$tu=(&1y&FCm`&cOR zG|bW3X8Qq6dR6(2v9L^nMFQK|MK=B)wqyt=!)zWwTGBW&ZG^Z;=5pnV%36al#Z4+AxuDjh5Gr5DH?=&K~92WHy+%_PomF4 zxs_#r$f)}rW)fx}(=JG(+i$NmlQBCnC6HmI7j_9sE&`1EC#Nxmpt9t0jr0P(*%_=9 zdlb_wf8*1A(Ot`?J5EN)=bTcy@C1+^!#v z7R~J+TRO)xQ~7_zqQ3VxG;Zp{*LcL&Ij+ZV!Ix4mOKZ?Bt}(669`HFJT`5&}Occ4N zkEq?ZkQe?0BwsUa^nPn9_YL(5G-);*#@XUZmWyG@v^ViZKL}+3&*6WcLW@N<9=$vI zXKt_a$Re>7-b(>Fli*`DQ^R1j#6IS9Txa9)c$!_jY<~#*2cbDU-c_r5UcUx;k)}Y5 z loopback -> Rust service -> filesystem create/edit/save/reopen; keyboard/pointer and focus; missing implementation blocking; exact pin retained", + "browser_user_workflow": "passed: actual NodeLab -> loopback -> Rust service -> filesystem create/edit/save/reopen; keyboard/pointer and focus; missing implementation blocking; exact pin retained; latest repaired-source run in browser-refresh.log.gz; original browser.log.gz retained as baseline evidence", "service_tests": "1068 library +65 integration passed, zero failures/ignored", "frontend_tests": "740 passed, zero failures/ignored; 10 focused decoding/controller/presenter tests included", "native_tauri": "unavailable: cargo check --locked -p pantograph --bin pantograph --no-default-features fails at glib-sys: missing glib-2.0.pc; pkg-config also lacks GTK/WebKit; no native startup claim", @@ -20,7 +20,8 @@ "GPU", "inference-backed/effectful tool loops", "release qualification" - ] + ], + "catalog_refresh": "failed refresh after successful load removes stale choices while preserving draft and saved path; focused red on baseline 802544a0, green after repair; same mounted real-browser flow passed" }, "source_sha256": { "crates/pantograph-workflow-service/examples/nodelab_host.rs": "1c9a33092e0bac9560247b8c1e158bc0405527cad7b0a280d79dc61334eed8c8", @@ -38,18 +39,20 @@ "crates/pantograph-workflow-service/src/workflow/service_config.rs": "257edc58a50b37e8dee265b971e91084b0f77b0ce4031f8d105b604f33cea513", "crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs": "aa080d798774771aa419db01d83cd26401684ab06333770a74e209c601e5952f", "scripts/README.md": "03bed3d3d157a4d7e4a9f2a291f4a2ab37efa2e81f87c83e3d5710a38220119a", - "scripts/check-nodelab-browser.mjs": "91505dbfa49defa836a246fcff7317bc6dae795fd257da1ee8747146cebe3357", + "scripts/check-nodelab-browser.mjs": "82f884c2fb04394168c06ba09b0432345aad059e67bc54efdc281a759b68c88f", "src-tauri/src/app_setup.rs": "b14c996956638c5a708156aaf8f110ce6f1fa3a175f6b03bb9ff0284bd392a50", "src-tauri/src/workflow/commands.rs": "24834569833ec6509300b9c8c795b9eb8be233f0c6d9c37c5d67f82b63d24b6c", "src/components/workbench/NodeLabPage.svelte": "ab23063b86e78e3dc919602df48d027f0e736bee678b8e5609eedc41d0da25d2", - "src/components/workbench/nodeLabController.ts": "3b3806dcf0aedf191fd7ad91ce3ac746a08c6962b1c0b292f54d9ba6e9145716", + "src/components/workbench/nodeLabController.ts": "0389ac2397e253926162195a1b41bddf1e07568f65afd568e1673b4fe44c0d1f", "src/components/workbench/nodeLabPresenters.test.ts": "5debffcdba6ddc86d4b4093dceb08dbf691b7659b73a483abd8d991616faa02e", "src/components/workbench/nodeLabPresenters.ts": "4792bedc18bf6b55173a892e0f15bc7900b4c36fd84bfc508da3dac9c0bbb075", - "src/services/workflow/customNodeAuthoring.test.ts": "73d776ffb40ddcafcfb0e69f7434f98aa19bd037484a36ccdef7d9eff290d250", + "src/services/workflow/customNodeAuthoring.test.ts": "97aa21f8487984832d03efac4f81d694b214ed065087099aca4a9b87433083dd", "src/services/workflow/customNodeAuthoring.ts": "f4a11c2fa37816819db79176b2af584199c946a5e3c533482cc595362092dc08" }, "evidence_sha256": { "browser.log.gz": "6c2a15df9371220e78251fd39f27631010da2e63d41f45843e9c9dba0c3bc97e", - "native-unavailable.log.gz": "f72bc764c185d785964c3ac95e9a0d6f24a1d999aefbd349dc143eed28d261b3" + "native-unavailable.log.gz": "f72bc764c185d785964c3ac95e9a0d6f24a1d999aefbd349dc143eed28d261b3", + "catalog-refresh-red.log.gz": "c849e1ead56e2b00b0f7fc3c7e04a4cf867a99fe176476aa9b0d9658613bf720", + "browser-refresh.log.gz": "2ddc4d6339e12a6c43cff584156c871b94352780d060b6ee4aa49495975884e2" } } diff --git a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md index 1f3defa2e..9cae9a29c 100644 --- a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md +++ b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md @@ -848,3 +848,21 @@ first by parent instruction; CN-02 must then reconcile current main, preserve it registry/loop validations, rerun combined affected tests and pass exact-head CI before merge. The local/remote feature branch and worktree are retained pending that disposition, with source and evidence preserved. + +While dependency integration was pending, a reachable catalog-refresh failure +left earlier Create choices visible. The focused regression failed on `802544a0` +and passes after clearing/publishing the catalog before transport; authored draft +and saved path remain unchanged. The same mounted real-browser flow passes +failed refresh and recovery. Its first probe inspected old-session closure before +Reopen completed; bounded observation now waits for replacement completion and +retains the original closure assertion. Original browser/native receipts remain; +the qualification manifest binds the repaired source and additional receipts. +No backend, scheduler or audit behavior changed. This repair remains local until +the required PR94 integration/current-main qualification. + +Hosted PR95 source/build/native-IPC checks passed on `802544a0`; the required +audit failed with an actual advisory-bulk HTTP 503. PR94 likewise remains blocked +on audit service failures. No audit retries or gate changes were requested here. +Local native provisioning inspection stopped when `apt-cache policy` was denied +reading `/etc/apt/apt.conf.d/80-applied-apt-retries`; no package installation or +privileged retry was attempted. This does not qualify native startup/interaction. diff --git a/scripts/check-nodelab-browser.mjs b/scripts/check-nodelab-browser.mjs index 76e5496a5..55ae40d26 100644 --- a/scripts/check-nodelab-browser.mjs +++ b/scripts/check-nodelab-browser.mjs @@ -23,6 +23,7 @@ let browser; let socket; const commands = []; const sessions = []; +let failRealCatalog = false; try { await symlink(path.join(repo, 'node_modules'), path.join(fixture, 'node_modules')); await writeFile(path.join(fixture, 'index.html'), '
'); @@ -56,7 +57,7 @@ try { const command = decodeURIComponent(url.pathname.split('/').at(-1)); const args = JSON.parse(body); commands.push(command); - const result = mode === 'error' ? { ok: false, error: { code: 'runtime_not_ready', message: 'Qualification host unavailable' } } : await (mode === 'empty' ? emptyHost : realHost)(command, args); + const result = (mode === 'error' || (mode === 'real' && failRealCatalog && command === 'get_custom_node_authoring_catalog')) ? { ok: false, error: { code: 'runtime_not_ready', message: 'Qualification host unavailable' } } : await (mode === 'empty' ? emptyHost : realHost)(command, args); if (result.ok && command === 'create_custom_node_draft') sessions.push(result.value.session_id); response.writeHead(result.ok ? 200 : 400, { 'Content-Type': 'application/json' }).end(JSON.stringify(result.ok ? result.value : result.error)); return; @@ -151,18 +152,38 @@ try { const file = (await realHost('load_workflow', { path: savedPath })).value; assert.equal(file.graph.nodes.find(node => node.node_type === 'text-input').data.text, 'Saved Mixed case'); const pin = file.graph.nodes.find(node => node.id === 'custom').data.custom_node_identity; - await enter('input', savedPath); await clickButton('Reopen saved workflow'); await waitText('Graph contract valid'); + await enter('input', savedPath); await clickButton('Reopen saved workflow'); + const reopenDeadline = Date.now() + 10000; + while ((await realHost('get_node_lab_draft', { executionId: sessions[0] })).ok && Date.now() < reopenDeadline) { + await new Promise(resolve => setTimeout(resolve, 30)); + } + while (await evaluate(() => document.querySelector('[aria-label="NodeLab authoring"]')?.getAttribute('aria-busy') === 'true')) { + assert.ok(Date.now() < reopenDeadline, 'Reopen must finish before inspecting the replacement'); + await new Promise(resolve => setTimeout(resolve, 30)); + } + await waitText('Graph contract valid'); assert.equal(await evaluate(() => document.querySelector('textarea')?.value), 'Saved Mixed case'); const reloaded = (await realHost('load_workflow', { path: savedPath })).value; assert.deepEqual(reloaded.graph.nodes.find(node => node.id === 'custom').data.custom_node_identity, pin); assert.equal((await realHost('get_node_lab_draft', { executionId: sessions[0] })).error.code, 'session_not_found'); + // A failed refresh cannot advertise stale implementations or discard the authored draft. + failRealCatalog = true; + await clickButton('Refresh catalog'); await waitText('Qualification host unavailable'); + assert.equal(await evaluate(() => [...document.querySelectorAll('button')].some(button => button.textContent.startsWith('Create '))), false); + assert.equal(await evaluate(() => document.querySelector('textarea')?.value), 'Saved Mixed case'); + assert.equal(await evaluate(() => document.querySelector('code')?.textContent), savedPath); + assert.equal((await text()).includes('This host has no admitted custom nodes'), false); + failRealCatalog = false; + await clickButton('Refresh catalog'); await waitText('Create Host uppercase draft'); + assert.equal(await evaluate(() => document.querySelector('textarea')?.value), 'Saved Mixed case'); + assert.equal(await evaluate(() => document.querySelector('code')?.textContent), savedPath); // Same saved graph opened on a host without its implementation stays visible and blocked. await emptyHost('save_workflow', { name: 'stale', graph: file.graph }); await navigate(emptyOrigin); await waitText('This host has no admitted custom nodes'); await enter('input', '.pantograph/workflows/stale.json'); await clickButton('Reopen saved workflow'); await waitText('Blocks execution:'); assert.ok((await text()).includes('host-uppercase')); assert.ok(!commands.some(command => command.includes('run_execution') || command.includes('register') || command.includes('publish'))); - console.log(JSON.stringify({ ok: true, claims: ['real empty catalog', 'transport failure distinct from empty', 'keyboard creation and visible focus', 'pointer edit/save/reopen through Rust filesystem', 'exact pin preserved', 'replaced session closed', 'missing implementation visible and blocking'], mode: 'headless Chromium, disposable profile, no sandbox, GPU disabled', nativeTauri: 'not qualified' }, null, 2)); + console.log(JSON.stringify({ ok: true, claims: ['real empty catalog', 'transport failure distinct from empty', 'keyboard creation and visible focus', 'pointer edit/save/reopen through Rust filesystem', 'exact pin preserved', 'replaced session closed', 'missing implementation visible and blocking', 'failed catalog refresh hides stale choices and preserves draft'], mode: 'headless Chromium, disposable profile, no sandbox, GPU disabled', nativeTauri: 'not qualified' }, null, 2)); } finally { socket?.close(); if (browser && browser.exitCode === null) { browser.kill('SIGTERM'); await new Promise(resolve => { browser.once('exit', resolve); setTimeout(resolve, 2000).unref(); }); } diff --git a/src/components/workbench/nodeLabController.ts b/src/components/workbench/nodeLabController.ts index 122609ce6..575872ffb 100644 --- a/src/components/workbench/nodeLabController.ts +++ b/src/components/workbench/nodeLabController.ts @@ -34,7 +34,11 @@ export class NodeLabController { } retryCleanup(): Promise { return this.perform(() => this.service.retryCleanup()); } loadCatalog(): Promise { - return this.perform(async () => { this.view.catalog = await this.service.catalog(); }); + return this.perform(async () => { + this.view.catalog = null; + this.publish(); + this.view.catalog = await this.service.catalog(); + }); } private async replace(create: () => Promise): Promise { const next = await create(); diff --git a/src/services/workflow/customNodeAuthoring.test.ts b/src/services/workflow/customNodeAuthoring.test.ts index 88d976738..30a1f1ace 100644 --- a/src/services/workflow/customNodeAuthoring.test.ts +++ b/src/services/workflow/customNodeAuthoring.test.ts @@ -45,22 +45,29 @@ test('invalid newly created response closes its session instead of leaking it', }); test('controller distinguishes empty catalog from failure and closes superseded drafts', async () => { - let fail = false; + let mode: 'empty' | 'full' | 'failed' = 'empty'; let counter = 0; const closed: string[] = []; const service = new NodeLabService(async (command, args) => { if (command === 'get_custom_node_authoring_catalog') { - if (fail) throw new Error('host unavailable'); - return { contract_version: 1, nodes: [] }; + if (mode === 'failed') throw new Error('host unavailable'); + return mode === 'empty' ? { contract_version: 1, nodes: [] } : catalog(); } if (command === 'remove_execution') { closed.push(String(args?.executionId)); return null; } return snapshot(`edit-${++counter}`); }); const controller = new NodeLabController(service, () => {}); await controller.loadCatalog(); assert.deepEqual(controller.view.catalog, []); assert.equal(controller.view.error, null); - fail = true; await controller.loadCatalog(); assert.equal(controller.view.error, 'host unavailable'); + mode = 'full'; await controller.loadCatalog(); assert.equal(controller.view.catalog?.length, 1); const selected = parseCustomNodeCatalog(catalog())[0]; - await controller.create(selected); await controller.create(selected); + await controller.create(selected); + controller.view.savedPath = 'saved-current.json'; + const before = structuredClone(controller.view.draft); + mode = 'failed'; await controller.loadCatalog(); assert.equal(controller.view.error, 'host unavailable'); + assert.equal(controller.view.catalog, null, 'failed refresh must not advertise stale creation choices'); + assert.deepEqual(controller.view.draft, before, 'catalog failure must preserve the current draft'); + assert.equal(controller.view.savedPath, 'saved-current.json'); + await controller.create(selected); assert.deepEqual(closed, ['edit-1']); await controller.dispose(); assert.deepEqual(closed, ['edit-1', 'edit-2']); }); From b4854d8d62bb58ef2917694ffcd8355733c252d7 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 22 Oct 2026 04:28:19 +0000 Subject: [PATCH 05/15] test(nodelab): qualify edit sessions with integrated loop admission --- .github/workflows/quality-gates.yml | 6 ++ .../src/workflow/tests/custom_nodes.rs | 90 ++++++++++++++++++ docs/custom-nodes.md | 8 ++ .../nodelab-authoring/browser-combined.log.gz | Bin 0 -> 618 bytes .../nodelab-authoring/ci-discovery.log.gz | Bin 0 -> 1531 bytes .../nodelab-authoring/qualification.json | 38 ++++++-- .../nodelab-authoring/service-combined.log.gz | Bin 0 -> 20631 bytes .../execution-ledger.md | 41 +++++++- .../plan.md | 14 +++ 9 files changed, 186 insertions(+), 11 deletions(-) create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser-combined.log.gz create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/ci-discovery.log.gz create mode 100644 docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/service-combined.log.gz diff --git a/.github/workflows/quality-gates.yml b/.github/workflows/quality-gates.yml index 4b002a144..815184f09 100644 --- a/.github/workflows/quality-gates.yml +++ b/.github/workflows/quality-gates.yml @@ -434,6 +434,12 @@ jobs: python3 -c 'import pathlib, sys; names = [line for line in pathlib.Path(sys.argv[1]).read_text().splitlines() if "tool_loop" in line and line.endswith(": test")]; print("Tool-loop tests discovered:", len(names)); sys.exit(0 if len(names) == 15 else 1)' "$RUNNER_TEMP/tool-loop-tests.list" cargo test --locked -p pantograph-workflow-service --lib tool_loop + - name: Run exact-head custom-node authoring and admission regression suite + run: | + cargo test --locked -p pantograph-workflow-service --lib workflow::tests::custom_nodes:: -- --list > "$RUNNER_TEMP/custom-node-tests.list" + python3 -c 'import pathlib, sys; names = [line for line in pathlib.Path(sys.argv[1]).read_text().splitlines() if line.startswith("workflow::tests::custom_nodes::") and line.endswith(": test")]; print("Custom-node tests discovered:", len(names)); sys.exit(0 if len(names) == 10 else 1)' "$RUNNER_TEMP/custom-node-tests.list" + cargo test --locked -p pantograph-workflow-service --lib workflow::tests::custom_nodes:: + - name: Run complete session execution regression suite run: | cargo test -p pantograph-workflow-service --lib workflow::tests::session_execution:: -- --list > "$RUNNER_TEMP/session-execution-tests.list" diff --git a/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs b/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs index 9226d62a0..76584515d 100644 --- a/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs +++ b/crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs @@ -631,3 +631,93 @@ async fn custom_node_authoring_saved_reopen_preserves_pin_and_scheduler_executio .unwrap(); assert_eq!(result.outputs[0].value, "MIXED CASE"); } + +#[tokio::test] +async fn custom_node_edit_sessions_preserve_integrated_loop_admission() { + use crate::tool_loops::tests::{catalog as loop_catalog, Executor as LoopExecutor, Mode}; + use crate::tool_loops::TOOL_LOOP_IDENTITY_FIELD; + + let controller = LoopExecutor::new(Mode::RoundTrip); + let tool = LoopExecutor::new(Mode::Uppercase); + let catalog = loop_catalog(controller.clone(), tool.clone(), 3); + let mut graph = custom_graph(catalog.get("loop-controller").unwrap().identity()); + let node = graph.find_node_mut("custom").unwrap(); + node.node_type = "tool-loop".into(); + node.data = serde_json::json!({TOOL_LOOP_IDENTITY_FIELD: catalog.tool_loop_identity("pure-loop").unwrap()}); + graph.edges[0].target_handle = "prompt".into(); + graph.edges[1].source_handle = "response".into(); + let root = tempfile::tempdir().unwrap(); + let store = FileSystemWorkflowGraphStore::new(root.path()); + let service = WorkflowService::with_trusted_custom_nodes(catalog.clone()); + let saved = service + .workflow_graph_save( + &store, + crate::WorkflowGraphSaveRequest { + name: "integrated-loop".into(), + graph, + }, + ) + .unwrap(); + let graph = service + .workflow_graph_load( + &store, + crate::WorkflowGraphLoadRequest { + path: saved.path.clone(), + }, + ) + .unwrap() + .graph; + let pin = graph.find_node("custom").unwrap().data[TOOL_LOOP_IDENTITY_FIELD].clone(); + let changed = loop_catalog(controller.clone(), tool.clone(), 4); + for (service, blocking) in [ + (service, false), + (WorkflowService::with_trusted_custom_nodes(changed), true), + (WorkflowService::new(), true), + ] { + let edit = service + .workflow_graph_create_edit_session(crate::WorkflowGraphEditSessionCreateRequest { + graph: graph.clone(), + workflow_id: Some(saved.path.clone()), + }) + .await + .unwrap(); + let request = crate::WorkflowGraphEditSessionGraphRequest { + session_id: edit.session_id.clone(), + }; + let snapshot = service + .workflow_graph_get_edit_session_graph(request.clone()) + .await + .unwrap(); + assert_eq!( + snapshot.graph.find_node("custom").unwrap().data[TOOL_LOOP_IDENTITY_FIELD], + pin + ); + assert_eq!( + snapshot + .graph_diagnostics + .iter() + .any(|d| d.blocking_submission), + blocking, + "{:?}", + snapshot.graph_diagnostics + ); + let mut invalid = snapshot.graph.find_node("custom").unwrap().clone(); + invalid.id = "invalid-new-loop".into(); + invalid.data[TOOL_LOOP_IDENTITY_FIELD]["max_turns"] = serde_json::json!(5); + assert!(service + .workflow_graph_add_node(crate::WorkflowGraphAddNodeRequest { + session_id: edit.session_id, + node: invalid, + }) + .await + .is_err()); + let after = service + .workflow_graph_get_edit_session_graph(request) + .await + .unwrap(); + assert_eq!(after.graph_revision, snapshot.graph_revision); + assert_eq!(after.graph, snapshot.graph); + } + assert!(controller.calls.lock().is_empty()); + assert!(tool.calls.lock().is_empty()); +} diff --git a/docs/custom-nodes.md b/docs/custom-nodes.md index 6eebe7fe5..20ce7362f 100644 --- a/docs/custom-nodes.md +++ b/docs/custom-nodes.md @@ -132,5 +132,13 @@ retired. Inference-backed controllers, side-effectful tools, external workers, Wasm, Python, package discovery, automatic updates, streaming and inference ports require follow-on admission; none are inferred from a palette entry. +NodeLab's creation catalog projects individual CN-01 registrations, not loop +templates or tool grants. Existing host-pinned loop graphs can be reopened using +the same registry; their pins remain unchanged and unavailable/stale grants are +blocking. A future loop-authoring surface must select a complete host-admitted +`ToolLoopIdentity` and produce exactly one prompt binding under the +[CN-03 contract](tool-loops.md); optional authoring ports and new grants remain +unsupported. No scheduler or loop authority is owned by NodeLab. + See [ADR-018](adr/ADR-018-trusted-custom-node-adapter.md) and the [admitted implementation slice](plans/domain-architecture-and-multimodal/plan.md#admitted-custom-node-adapter-slice-2026-10-21). diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser-combined.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/browser-combined.log.gz new file mode 100644 index 0000000000000000000000000000000000000000..a137fef0cf1f89dac4cd954458a0a0685ec949cc GIT binary patch literal 618 zcmV-w0+szAiwFP!0000219el&ZWBQeyzf`E%mpNS94B!eKA}X23x^1S5JCve?zFuf z&x`39#}3McUw|WDmoK5mjv;{9+thSbch&T+C?l*+)UldCTgV#n3z&xlF$Gh)Ou;Lq znw+#}ft_5}^F<0bjEOCAoKj@qGNkVNLHupci!DKR(u}rbZ@XH?>)g<%=Qw^f)i(hgzERwP0iY;y_0@E#4 z*i?0r^0n%-v+&P%peCoVyny@fU$@NJ7CIJa$JNZ3c_%Tte1A=&n-@o_V+NQWsgt9> zxaaEZKio)k^XikkR@Xv>>8Uz7{*!xnpr(hFTfNt(&Ojc{)af}lUnJu}SPo_qM8RP_ zbykyOK|VCq$3TL!fG*|@bn?nJEC$2f%{IFjQii!ETM|N@j(jIT3T{W*7cX(s2AvFa zB3QQzv^TIKrq-e?URQWu8Uy)^3D8g;vtHpiVTkA<_bHS`53dVL3zGNSa7MT1;aW@U zDCS~9S%DRr{Z+zfb%zERnQQaT2L65RNKkoVa?zqgpLY}Pr>m2;Hgrp=*;A@z(R+wQ zc5*H~d+5o?RE`Gl3yk1c^-(!$8FrQh$vwXdf87g#BeDl9ThjMX~w|1 zP9Q&J^*aO~fJLtj>mj_ndRuF1!OqFR%iJq`qf4Ty=|hIkMO&JaR5W+ZPnj3L%Jl;P E0G*>FyZ`_I literal 0 HcmV?d00001 diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/ci-discovery.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/ci-discovery.log.gz new file mode 100644 index 0000000000000000000000000000000000000000..f81bcbc8b299786b4c6a46ee848ef39efcc048ea GIT binary patch literal 1531 zcmVTU%F3A=ljOhHlcizR zYCbn&iGSvLK6hFdG>oEg)c%81tk_0sLnRl=Nq0?+a7-#o-Ad4mDXnD23d)7ejI10+ za=8S`oCK`IW-GycAq+s7T~lrF0IUon@#rQU05efgmOEi6Hc%D9Nv&vQ#0LB}JS(N6 zOmQrv5X=fonRBA7TE;Dyy#=4~Qd%1jjrbELv(&4#(wB-_#|lBYuL|tPiOAqps=eZZ zQ|8@D8*IN5Nj>;)%rjv=b+Am>f)!?i^;Sk=4{}qJRLo#!6l)O1u4L7PfeXe9_?AWu zzyd`-m-N8F4>hVeThkWiS=5#V!=f6FCUx@7RhUl)-V|43t)7> zh5@$z1%gyGFXVFN+J}&IrLBmT;57HxP^UGwo@7~&iVdD@{3otf43QJueJSA+@9+rP zqjB=3HtRn4B{nK)rOlpAgZOr$>VoE2S%t8rL9<0z={B-p2c;bhv(am8;K*}f!Fi!C zk5Lchmql%DBd@V9xPl>Sam3M4eQjV_sn-2?U`~LygQ=6H2o`SKcvI$0wuy`A$79(B z=88#c=Zj!)wQQm`*Jc@lG={A8Rq)X*LEDSZ2we%aBlaP zAOr|ZT1v%g=WtDfAdqnp+aXani8nBE<+mZ1pnyc8r({Y}p|VxU%-Y^k29Aoz@lxv{ zG)z7G*KQpqhnl$L5N^HmCL!BZSiQJ{_~^E<++mO|EJox$h^Th3MXHa{U1yFqU@GQ9 zHQ5Gt>D|5h>PB2Io?34pI`~6w(V$QyM1DGAwKW;}-Mw z;AsWXumw{eMok~CHrJrF$yQ7)#bGjQ({}A5v7fF6klmVm8tBk-p`lo=_WG_}f7PGs zICUTUD?^W^ZnjtnTF!1cC#JpF7+*4@V8uDfr6{;1iwYEMDHc!3!ZGA;hhJbM3obS? z6AJ>55{2qyh(WuP5HcFQCRvcIok*3Vh(cr&YqCk59%4Njr?NA~Hh%zxCMWOjCpTU)P&edkMNe@30iffaW1A-=p1 zG!&2{%-RPv=G)fRzr=@c`Mqe-)cE>|ASi&a`0itH{Yhw9Q7pJP{j?w_p_UPyZ{K=_ zY|ruPlxRiLYb+pV=(m!cZWddgV}2piQ?f*e#0*Aeq!|{N$s4Icih-1ZNEZYNJeP$a zAHC8Qv>pohr^ak2_B8lzHl97RaWZ-DRX`%>dR-Jb2@(S#1zSkJFyrX_#d&&`J4AHjyO4L?{8VSD(oZ#ZlJ!`~pThaLf2(wenSP;)#OhYC_Li<0^Z9a=!If61lN zrv6zXyZHEfHobU>Hl}d#HWART@UN+$D2>zc>?K;eyUvr}n!9h!-B;e+O~)56zoO=D zy5HPA@)gYeY3b1~VjfQ4|Au5B=YwxChVHfR{mlR2(w loopback -> Rust service -> filesystem create/edit/save/reopen; keyboard/pointer and focus; missing implementation blocking; exact pin retained; latest repaired-source run in browser-refresh.log.gz; original browser.log.gz retained as baseline evidence", - "service_tests": "1068 library +65 integration passed, zero failures/ignored", + "browser_user_workflow": "passed on combined source: actual styled NodeLab -> loopback -> rebuilt Rust service -> filesystem create/edit/save/reopen; keyboard/pointer and focus; exact pin retained; missing implementation blocking; failed catalog refresh/recovery preserves draft/path. Latest receipt browser-combined.log.gz", + "service_tests": "1084 library +65 integration passed, zero failures/ignored; both custom-node and pure-loop suites included", "frontend_tests": "740 passed, zero failures/ignored; 10 focused decoding/controller/presenter tests included", "native_tauri": "unavailable: cargo check --locked -p pantograph --bin pantograph --no-default-features fails at glib-sys: missing glib-2.0.pc; pkg-config also lacks GTK/WebKit; no native startup claim", "not_claimed": [ @@ -21,11 +21,12 @@ "inference-backed/effectful tool loops", "release qualification" ], - "catalog_refresh": "failed refresh after successful load removes stale choices while preserving draft and saved path; focused red on baseline 802544a0, green after repair; same mounted real-browser flow passed" + "catalog_refresh": "focused red on 802544a0, green after repair; same mounted combined-source browser flow removes stale choices and preserves draft and saved path", + "hosted_test_discovery": "local exact CI commands discovered and passed 15 tool_loop tests and 10 workflow::tests::custom_nodes:: tests; original loop gate unchanged" }, "source_sha256": { "crates/pantograph-workflow-service/examples/nodelab_host.rs": "1c9a33092e0bac9560247b8c1e158bc0405527cad7b0a280d79dc61334eed8c8", - "crates/pantograph-workflow-service/src/custom_nodes.rs": "1d413febbad16689c864e7945191c7bb83079530ece13fda73541178bd86f774", + "crates/pantograph-workflow-service/src/custom_nodes.rs": "93b016626ce454091fe6092807442184556f90b6f4ae65125af9c12a1e9c52aa", "crates/pantograph-workflow-service/src/custom_nodes/authoring.rs": "ab2e37ca4a68b846e8f23897891eea064730a1376c8597eb5ce00e1bf5f909ed", "crates/pantograph-workflow-service/src/graph/connection_insert.rs": "881afe99675e681a2bd1208f69e55f82afa881adec9ead9a6863089dd3a6f2af", "crates/pantograph-workflow-service/src/graph/connection_intent.rs": "d5832d05d88dd0d2dc10cb367038a0a6d5973e1275fe19e888fb411c13057199", @@ -37,8 +38,8 @@ "crates/pantograph-workflow-service/src/workflow.rs": "47e42061802abc91ebe6b3babf8c578116d2e0fecf51d86fa53148cbed613886", "crates/pantograph-workflow-service/src/workflow/custom_node_authoring_api.rs": "5bf54f01b2db4ec2ffc21b6af41291c695ff91a3b274deb80838c32020b9941d", "crates/pantograph-workflow-service/src/workflow/service_config.rs": "257edc58a50b37e8dee265b971e91084b0f77b0ce4031f8d105b604f33cea513", - "crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs": "aa080d798774771aa419db01d83cd26401684ab06333770a74e209c601e5952f", - "scripts/README.md": "03bed3d3d157a4d7e4a9f2a291f4a2ab37efa2e81f87c83e3d5710a38220119a", + "crates/pantograph-workflow-service/src/workflow/tests/custom_nodes.rs": "39ea2a0a726a4a93e6199f6cf72d22914db7d43e4edc8d750178acc5084c55ec", + "scripts/README.md": "a1b99bbc7b161a5842b49b4a97e08c8042121a2b034848c35c53e22e3dbd881c", "scripts/check-nodelab-browser.mjs": "82f884c2fb04394168c06ba09b0432345aad059e67bc54efdc281a759b68c88f", "src-tauri/src/app_setup.rs": "b14c996956638c5a708156aaf8f110ce6f1fa3a175f6b03bb9ff0284bd392a50", "src-tauri/src/workflow/commands.rs": "24834569833ec6509300b9c8c795b9eb8be233f0c6d9c37c5d67f82b63d24b6c", @@ -47,12 +48,31 @@ "src/components/workbench/nodeLabPresenters.test.ts": "5debffcdba6ddc86d4b4093dceb08dbf691b7659b73a483abd8d991616faa02e", "src/components/workbench/nodeLabPresenters.ts": "4792bedc18bf6b55173a892e0f15bc7900b4c36fd84bfc508da3dac9c0bbb075", "src/services/workflow/customNodeAuthoring.test.ts": "97aa21f8487984832d03efac4f81d694b214ed065087099aca4a9b87433083dd", - "src/services/workflow/customNodeAuthoring.ts": "f4a11c2fa37816819db79176b2af584199c946a5e3c533482cc595362092dc08" + "src/services/workflow/customNodeAuthoring.ts": "f4a11c2fa37816819db79176b2af584199c946a5e3c533482cc595362092dc08", + ".github/workflows/quality-gates.yml": "030e50d32426e0abaa17990e683e67a29b9cdb704a2a146908c78817e5369d2f", + "crates/pantograph-workflow-service/src/graph/registry.rs": "ad7cfd660e85e264a0c8f9e2ddd78fa3d4fd3074ee2275a13ee33c3f998434c7", + "crates/pantograph-workflow-service/src/tool_loops.rs": "3dee015aefb679de08564a02ed4175d902c9836c520c1b0de072cc5a036aaa09", + "crates/pantograph-workflow-service/src/scheduler/tool_loop.rs": "3af80db2ce8f4a621e2e1778e1c4dede603068fc12457c8a550d752d9a0bf362" }, "evidence_sha256": { "browser.log.gz": "6c2a15df9371220e78251fd39f27631010da2e63d41f45843e9c9dba0c3bc97e", "native-unavailable.log.gz": "f72bc764c185d785964c3ac95e9a0d6f24a1d999aefbd349dc143eed28d261b3", "catalog-refresh-red.log.gz": "c849e1ead56e2b00b0f7fc3c7e04a4cf867a99fe176476aa9b0d9658613bf720", - "browser-refresh.log.gz": "2ddc4d6339e12a6c43cff584156c871b94352780d060b6ee4aa49495975884e2" + "browser-refresh.log.gz": "2ddc4d6339e12a6c43cff584156c871b94352780d060b6ee4aa49495975884e2", + "browser-combined.log.gz": "a8ef7d653ecfa27ad28d01cf055ee112c4c83b03ee1d3b251e25671b37e7d598", + "service-combined.log.gz": "6cd931f20b55b2fc5bfd846b74e7ac0dfbcd4d61e4d175da0228192ec7374029", + "ci-discovery.log.gz": "272c0cad07fac982061e125acd110df89918e2147a478a2f30b9051fed19223a" + }, + "integrated_dependency": { + "pull_request": 94, + "head": "fcb2d7f618f32000ed1992569d7eabf3c77cf873", + "merge": "46aad5841ca8f2185e639da44f73474af045bc13", + "production_loop_core": "unchanged from merged main; NodeLab consumes the same immutable registry without authoring loop grants" + }, + "historical_evidence": { + "browser.log.gz": "802544a0ed5f523d2ce7a54f7859b8ed0187e63f; initial styled flow", + "browser-refresh.log.gz": "ff4e4de05d884f05338e70745db2400df0134926; refresh repair", + "catalog-refresh-red.log.gz": "regression failed on 802544a0 before repair", + "native-unavailable.log.gz": "original missing-GLib failure; retained unchanged" } } diff --git a/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/service-combined.log.gz b/docs/plans/domain-architecture-and-multimodal/evidence/nodelab-authoring/service-combined.log.gz new file mode 100644 index 0000000000000000000000000000000000000000..ca5b09ba36c795fed8ef60905417d7326d6131d4 GIT binary patch literal 20631 zcmV(sK<&RDiwFP!000021I>L|k1NS?-uwKD1`Jqt0L^md%r0Ai0YQKP8xUl@2{Nb1 zN|JTESVh&+efnBI-Wh8~t*n(-7tm;iO=jd085!#r?@^H@+2!|_bK=steEH)ZonE7h z`{Qq4{-~nj;wt}dQ5L`a5xckKzkfLuQRT|-lI-jX zmz~^qWpVnhbg4U4ELowxU+b(cUF`q#^-G?;96$U7&QYCKUw!p1eDjB%x&M8d z9KU|KxXi(Hc-7{Kdup#@qI% z@@qJ|Pv3t3xx^p8{BxbbNH2AkRPcL$rk=$-LC;PvfBNn{FJ4Q3lK zPSNS=zM~Ppi`}ul_Q}F-ockJWfvbUtjvzyB*`QG8xeY|}8?YA%a>nbXGEIRPbRZ$#O(cwL*u6gZ$ zTxWjUo&V~+uBOwx!QD92rN0{G0X}*y51Ie0Ja{>ADDu>mTPz^+Uksnawv>lFJJi{0 zmcM62aSJ+ke>V>-1eBV;QgA|U3j&3!@DH-x*CeYpnYkVC@D`=@x()Gz-lEjs!ty{{ z?EfPw*Ny4L2b@~^VfeAZc891uT%#hE-@;W`K+u2SveG{;o(W@5_x0_7m;Z3i3oqWX zj20Z;La+kKGxIHM>^u? zX(xKf3GT~1O-@P0E1Wy_&E0apA^ty-n}1+DjX(RjmxsT&BIm(M&%g5rN=lV0?^g%H z1qXr&CuOyKVqs2)DzBpSkbAueo}2kY;{Jv4N}A~1AK|1ML&pr?_ty}PY)w zy>v?A3FF7Nq=ZYRJ6LCBeTO^iKuyVzx9FisG91*iPx*M@Q{*L2nns|19^xXu;{%x{ zmuq!6*Hv9Odc2rw>Cei4;uVeCy?Q*la4;PbOcNe-81R@^*TXe0D;&%Z3lo?--=p&~ z2IS>iexgrM|Mv1HO-t6R^J2=NX$q40;5onxEt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*Y$Kw~TR(}5Ww;#)|zIuWG{WEu##Z`Q#1tH=l{kAAy{`4KJ z1eM6|?*2~YxR!4)ed{}VPQHuXvA+0!-h0OQ=9eG7cfb64azFj*j-P)1@%Z&uUr9sT zUx+ZRHlVE&-lzI%@%^Tx691f*Ej3GjMl2dyhux%+?!_HGeQH>+{R2qbZ>DRanv7yk z`FrBK7@dX6R~=2uFY`=<2i7+a@>q9a>OSECg2{{qUFK>}D&@Q%H!wlteAcUfxY5@TyKe#x!b*zYiduy1_f7yn~zyJ38PY;-! zw-tKa`M;KHc)c~$H@}?X)35HA^Doio)9LiXXT$P8_Og6y0AXT^p4;ucaXArdc*5+X zjH9EHNL5`B(>%t1+Mq4T+62Z?W5q`--Zo*$X*0RQw@c|nYq4^=9P#639Pvo(K^Jnj zh7WLnZ$AGLpPWDU@1yvaPtoU}&FO#o+|;GJj}@k`LuH1VRC`Al_+v658acGK;4zum%J@j+75x zCQyE6ZxF9F9M`P^`)A47G2@86LxKsMger9*bzp2j|HOcLL-`?{jn<_f>)0Rl_{ke+M#}aG6obGKw4DpYlsx;qj*VuJny-MptID~*fv5|W z*JRpxQ1Tj#Q$zDBToxBzHD)W*D?{GVNUf34D_{Z^qILVF& z2vdX|#7iKQ#)s)*{!-G7St+V^+|VT9+XW7<9%!B(-R|>dBJPJNB91kk)sl|K`Q|tG z`4<=ca{leNpQG=8`*bz}?RjSQ$zum$g)V-xW>2&Bss1st#7gsP#Q8gx;2O(R&pkjK zW07xZ%4htx z0m(k`cMTh61}y{JJ>yrL-l2`!^{2tTG@xws0l&5f8K?g!OJ>$$2ElzN{=OOTSa#tAV zF%4PNIDuLS!g(A%wjZ`WwtvV^-{6#A!a*F`EEl%*d*0UW%)Z~$6#4%(HWOB70RjN1 CXg`_& literal 0 HcmV?d00001 diff --git a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md index c01ec945f..074037ad1 100644 --- a/docs/plans/domain-architecture-and-multimodal/execution-ledger.md +++ b/docs/plans/domain-architecture-and-multimodal/execution-ledger.md @@ -920,8 +920,45 @@ No backend, scheduler or audit behavior changed. This repair remains local until the required PR94 integration/current-main qualification. Hosted PR95 source/build/native-IPC checks passed on `802544a0`; the required -audit failed with an actual advisory-bulk HTTP 503. PR94 likewise remains blocked -on audit service failures. No audit retries or gate changes were requested here. +audit failed with an actual advisory-bulk HTTP 503. PR94 was likewise blocked +on audit service failures at that stage. No audit retries or gate changes were requested here. Local native provisioning inspection stopped when `apt-cache policy` was denied reading `/etc/apt/apt.conf.d/80-applied-apt-retries`; no package installation or privileged retry was attempted. This does not qualify native startup/interaction. + + +## 2026-10-22 — Serial CN-02/CN-03 reconciliation + +PR94 passed its required exact-head checks and merged as `46aad584`. A normal +merge (`0acae31f`) incorporates that current main into the retained NodeLab branch; +only plan/issue conflicts required resolution, preserving both admitted slices. +CN-03 production registry/loop/scheduler code remains unchanged. The NodeLab +[handoff](../../custom-nodes.md#nodelab-graph-authoring) distinguishes individual +CN-01 authoring from future host-pinned loop-template authoring: no UI tool grants, +optional loop ports or second execution route are introduced. + +The combined edit-session regression saves/reopens an exact loop pin, accepts its +admitted catalog, preserves it with blocking diagnostics under changed/missing +catalogs, and refuses invalid new pins without snapshot/revision mutation or +callback invocation. Hosted coverage now explicitly discovers/runs all ten +custom-node workflow tests. The new regression is named outside the existing +`tool_loop` substring filter; that original fifteen-test discovery/execution gate +is unchanged. Local exact commands discover and pass both 15 and 10 tests. + +The [combined qualification](evidence/nodelab-authoring/qualification.json) binds +28 source files and retains seven receipts, including fresh 1,084 library +65 +integration tests (1,149 total, zero failed/ignored), both CI discovery/run filters +and styled Chromium → rebuilt Rust host → filesystem interaction. All eight +browser claims pass, including failed catalog refresh/recovery without losing +saved draft/path. The final frontend suite passes 740 tests; formatting, +typecheck, full/critical/a11y lint, production frontend build, scheduler-only guard +and 28 traceability tests pass. Original browser, refresh-red and missing-GLib +receipts remain preserved. Final package all-target Clippy passes with only the +existing inference dead-field warning. Local native startup/interaction remains unqualified; +the recorded APT read denial was not retried or bypassed. + +At this qualification stage, PR94 post-merge workflows and PR95 final independent +review/fresh exact-head CI/current-main rechecks still gate normal integration. +No old-head audit retry, dependency suppression, lockfile change, text-readiness +edit or branch deletion was performed. PR92's unique trained-text source/evidence +and missing T3 gate remain separate. diff --git a/docs/plans/domain-architecture-and-multimodal/plan.md b/docs/plans/domain-architecture-and-multimodal/plan.md index 782bb67f8..96591c6cd 100644 --- a/docs/plans/domain-architecture-and-multimodal/plan.md +++ b/docs/plans/domain-architecture-and-multimodal/plan.md @@ -360,6 +360,20 @@ transfers exact session IDs to an app-scoped, user-retryable cleanup owner. Stan continues, adding routed Frontend, TypeScript/Async, Accessibility, IPC, Persistence, protocol/evolution and GUI verification detail to the CN-01 routes. +**Serial reconciliation (2026-10-22):** CN-03 PR94 is integrated as `46aad584`. +Continue CN-02 on that current-main base with the same production contract. +Preserve both admitted slices and CN-03 source unchanged. Add one edit-session +integration regression for a saved/reopened exact loop pin: its admitted catalog +accepts it, changed/missing catalogs retain it with blocking diagnostics, and an +invalid new pin is rejected without mutation. This tests the shared-registry +handoff rather than adding loop authoring or execution. Rerun both service suites, +frontend/static gates and the real-host browser flow; bind fresh combined-source +evidence, obtain independent review, then pass fresh exact-head CI and current-main +rechecks. PR94 post-merge CI must also pass before PR95 merges normally. +Add explicit hosted discovery/execution of all ten custom-node service tests; +keep CN-03's existing fifteen-test loop gate unchanged and name the new +edit-session regression outside that substring filter. + ## Admitted CN-03 pure tool-loop slice (2026-10-22) **Authority and status:** The user authorized unfinished Pantograph paths and From 4352fce1beb98e9519f8665aa452352fc33ca895 Mon Sep 17 00:00:00 2001 From: MrScripty Date: Tue, 3 Nov 2026 06:29:48 -0700 Subject: [PATCH 06/15] docs(design): add workbench redesign mockups and implementation spec Interactive mockups of the calm workbench redesign (rounds 1 to 3, one artboard per tab plus a new Sessions tab), the shared run-context picker snippets, a local viewer that renders the artboards without the cloud canvas, and the implementation contract (tokens, glyph vocabulary, shell, picker and clipboard behaviour, shared parts, page mappings, accessibility contract, evidence). Co-Authored-By: Claude Fable 5.1 --- docs/design/mockups/README.md | 19 + docs/design/mockups/boards/Current.dc.html | 28 ++ docs/design/mockups/boards/Dark.dc.html | 335 +++++++++++++ .../design/mockups/boards/Diagnostics.dc.html | 408 +++++++++++++++ docs/design/mockups/boards/Graph.dc.html | 437 ++++++++++++++++ docs/design/mockups/boards/Instrument.dc.html | 292 +++++++++++ .../design/mockups/boards/IoInspector.dc.html | 408 +++++++++++++++ docs/design/mockups/boards/Library.dc.html | 387 ++++++++++++++ docs/design/mockups/boards/Main.dc.html | 273 ++++++++++ docs/design/mockups/boards/Network.dc.html | 373 ++++++++++++++ docs/design/mockups/boards/NodeEditor.dc.html | 358 +++++++++++++ docs/design/mockups/boards/Revised.dc.html | 474 ++++++++++++++++++ docs/design/mockups/boards/Sessions.dc.html | 370 ++++++++++++++ docs/design/mockups/boards/Studio.dc.html | 305 +++++++++++ docs/design/mockups/boards/shell.css | 186 +++++++ docs/design/mockups/ctx-markup.html | 38 ++ docs/design/mockups/ctx-mixin.js | 121 +++++ docs/design/mockups/inject.py | 20 + docs/design/mockups/viewer/.gitignore | 1 + docs/design/mockups/viewer/build.sh | 32 ++ docs/design/mockups/viewer/cdp.js | 30 ++ .../mockups/viewer/current-scheduler.png | Bin 0 -> 78281 bytes docs/design/mockups/viewer/support.js | 169 +++++++ docs/design/workbench-redesign-spec.md | 359 +++++++++++++ 24 files changed, 5423 insertions(+) create mode 100644 docs/design/mockups/README.md create mode 100644 docs/design/mockups/boards/Current.dc.html create mode 100644 docs/design/mockups/boards/Dark.dc.html create mode 100644 docs/design/mockups/boards/Diagnostics.dc.html create mode 100644 docs/design/mockups/boards/Graph.dc.html create mode 100644 docs/design/mockups/boards/Instrument.dc.html create mode 100644 docs/design/mockups/boards/IoInspector.dc.html create mode 100644 docs/design/mockups/boards/Library.dc.html create mode 100644 docs/design/mockups/boards/Main.dc.html create mode 100644 docs/design/mockups/boards/Network.dc.html create mode 100644 docs/design/mockups/boards/NodeEditor.dc.html create mode 100644 docs/design/mockups/boards/Revised.dc.html create mode 100644 docs/design/mockups/boards/Sessions.dc.html create mode 100644 docs/design/mockups/boards/Studio.dc.html create mode 100644 docs/design/mockups/boards/shell.css create mode 100644 docs/design/mockups/ctx-markup.html create mode 100644 docs/design/mockups/ctx-mixin.js create mode 100644 docs/design/mockups/inject.py create mode 100644 docs/design/mockups/viewer/.gitignore create mode 100755 docs/design/mockups/viewer/build.sh create mode 100644 docs/design/mockups/viewer/cdp.js create mode 100644 docs/design/mockups/viewer/current-scheduler.png create mode 100644 docs/design/mockups/viewer/support.js create mode 100644 docs/design/workbench-redesign-spec.md diff --git a/docs/design/mockups/README.md b/docs/design/mockups/README.md new file mode 100644 index 000000000..dad133178 --- /dev/null +++ b/docs/design/mockups/README.md @@ -0,0 +1,19 @@ +# Workbench mockups + +Interactive mockups of the redesigned workbench, authored for the Claude +Design canvas and viewable locally. + +- `boards/*.dc.html`: one artboard per tab (`Revised` is the Scheduler) plus + the earlier rounds (`Main`, `Studio`, `Instrument`, `Dark`) and the + `Current` baseline screenshot. `boards/shell.css` holds the shared tokens + and primitives for the round-3 boards. +- `ctx-markup.html`, `ctx-mixin.js`, `inject.py`: the shared run-context + picker, expanded into every board by `python3 inject.py` (idempotent). +- `viewer/`: `support.js` is a local stand-in for the canvas runtime; + `build.sh --serve` builds the boards into `viewer/site/` and serves them on + http://127.0.0.1:8765/; `cdp.js` drives headless Chromium for scripted + walkthroughs and screenshots. + +The implementation contract derived from these boards is +`../workbench-redesign-spec.md`; the plan is +`../../plans/workbench-redesign/plan.md`. diff --git a/docs/design/mockups/boards/Current.dc.html b/docs/design/mockups/boards/Current.dc.html new file mode 100644 index 000000000..246f07bb1 --- /dev/null +++ b/docs/design/mockups/boards/Current.dc.html @@ -0,0 +1,28 @@ + + + + +Current Scheduler build + + + + + + + +

+ Screenshot of the current Pantograph Scheduler page: icon-only left rail, fourteen filter dropdowns, a wide empty run table, a transport error banner, and a timeline side panel +
+ + + + diff --git a/docs/design/mockups/boards/Dark.dc.html b/docs/design/mockups/boards/Dark.dc.html new file mode 100644 index 000000000..45b6e7d69 --- /dev/null +++ b/docs/design/mockups/boards/Dark.dc.html @@ -0,0 +1,335 @@ + + + + +Scheduler, dark drafting paper with inbox + + + + + + + + +
+ +
+
Pantograph
+ +
+
Local engine, updated 20:05:51
+ Assistant +
+ +
+
+ +
+ + +
+ Engine unreachable since 20:03. Showing the last projection; runs keep executing on the engine. + +
+
+ + +
+ +
+
{{lane.name}}
+
+ +
{{b.label}}
+
+
+
+
+
+
+ +
+ +
+
+
+ + + +
+
+ + + +
+ +
+ + + + + + + + + + + +
+
+
+
+ + + +
+ +
+
Selected: {{sel.wf}}
+
+ + + +
+
+
+
+ +
+ +
+
+
{{sel.wf}} v{{sel.ver}}
+
{{sel.id}}
+
+ {{sel.statusLabel}} + {{sel.runtime}} on {{sel.device}} + priority {{sel.prio}} + queue {{sel.queue}} +
+
+ +
+ + + +
+
+
+
+
+

Estimate

+
{{sel.est}}
+
Based on 14 earlier runs of this version
+
+
+

Retention

+
Keep artifacts 7 days, 212 MB on disk
+
Expires 2026-11-09
+
+
+

Placement

+
{{sel.reasonOrPlaced}}
+
Policy fair-share, bucket default
+
+
+
+

Timeline

+
+ + {{e.t}}{{e.text}} + +
+
+ +
+ +
Select a run to see its timeline, estimate and retention.
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Diagnostics.dc.html b/docs/design/mockups/boards/Diagnostics.dc.html new file mode 100644 index 000000000..cf733cf74 --- /dev/null +++ b/docs/design/mockups/boards/Diagnostics.dc.html @@ -0,0 +1,408 @@ + + + + +Diagnostics tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+ +
+
+
+
Which run do you want to look into?
+
Diagnostics shows the events, errors and placement of one run. Pick one here, select it in the Scheduler, or paste a run id.
+ +
+
+
+ + +
+ +
+ +
+
+
+
{{sel.wf}} v{{sel.ver}}
+
{{sel.id}}
+
+ {{sel.statusLabel}} + {{sel.placement}} + from {{sel.client}}, session {{sel.session}} +
+
+
+

Timing

+
+ {{t.k}}{{t.v}} +
+
+
+

Placement

+
+ Runtime{{sel.runtime}}, cuda backend + Device{{sel.placementLong}} + Model{{sel.model}} + Policyfair-share, bucket default + Reason{{reason}} + Retention7 days, {{retention}} +
+
+ + +
+ + {{f.label}}{{f.n}} + +
+
+ + +
+
+
{{cmp.failed}}
runs of v{{sel.ver}} failed
+
{{cmp.median}}
median duration when it succeeds
+
+
{{cmp.note}}
+
+
+
+
+

Projection

+
Current at seq 1 842. Run list and node status rebuilt 20:05:50.
+
+
+
+ +
+
+
+ + + +
+
+ + + +
+ + + +
+ + +
+ +
+
{{err.title}} {{err.code}}
+
{{err.text}}
+
{{err.hint}}
+
+ +
+
+ +
+ +
+ {{e.t}} + + {{e.kind}} {{e.msg}} {{e.src}} +
+
+
{{lineCount}} of {{lineTotal}} events shown. Payload bodies for this run are in I/O Inspector.
+
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Graph.dc.html b/docs/design/mockups/boards/Graph.dc.html new file mode 100644 index 000000000..5aa2a701c --- /dev/null +++ b/docs/design/mockups/boards/Graph.dc.html @@ -0,0 +1,437 @@ + + + + +Graph tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+
+
+ + +
+
+ + +
+
Saved workflows
+ + + +
Picking a workflow switches to editing it. To see a workflow as a run used it, pick the run instead.
+
+
+
+ {{saveLine}} + read-only, as it ran + + + + + + + + + + + + + +
+ + +
Submit will save v{{version}} first. {{dirtyNote}}
+
+ +
The selected run is of {{sel.wf}}, not {{wfName}}. or keep editing {{wfName}}.
+
+ +
+ +
+
+ + +
+
+ + + + + + + + +
+
Drag onto the canvas, or double-click to add.
+
+
+ +
+ + +
+
{{n.label}}{{n.type}}
+
{{p}}
+
{{p}}
+
{{n.note}}
+
+
+
+ +
running now done in this run failed not reached
+
+ +
+ + +
+ +
+
+
{{node.label}}
+
{{node.type}} · {{node.id}}
+
{{node.stateLabel}}
+
+
+

Settings

+ + + +
Values as they were when the run started. Switch to Edit workflow to change them.
+
+
+

Ports

+
+ {{p.dir}}{{p.name}} {{p.type}} +
+
+ +
+

In this run

+
{{node.runNote}}
+ +
+
+
+
+
+ +
Select a node to see its settings.
+
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Instrument.dc.html b/docs/design/mockups/boards/Instrument.dc.html new file mode 100644 index 000000000..49488e3e2 --- /dev/null +++ b/docs/design/mockups/boards/Instrument.dc.html @@ -0,0 +1,292 @@ + + + + +Scheduler, night instrument direction + + + + + + + + +
+ + + +
+
+

Scheduler

+
{{summary}}
+
Local engine, updated 20:05:51
+
+ + +
+ Engine unreachable since 20:03. Showing the last projection; runs keep executing on the engine. + +
+
+ +
+ + + +
+
+ + +
+ + + +
+ +
+ + +
+ + + + + + + + + + + +
+
+ +
+ + + + +
+
+ + +
+
+
+
+ + + diff --git a/docs/design/mockups/boards/IoInspector.dc.html b/docs/design/mockups/boards/IoInspector.dc.html new file mode 100644 index 000000000..c6dea27ff --- /dev/null +++ b/docs/design/mockups/boards/IoInspector.dc.html @@ -0,0 +1,408 @@ + + + + +I/O Inspector tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+ +
+
+
+
Whose inputs and outputs?
+
The inspector shows what passed through each port of one run. Pick a run here, select it in the Scheduler, or paste a run id.
+ +
+
+
+ + +
+ +
+ +
+
+
+ + +
+
+ + + +
+
+
+ + + + + + + + +
+
Payloads kept 7 days. Retention settings
+
+ +
+ +
+
+
+
{{art.node}}:{{art.port}}
+
{{art.id}}
+
+ {{art.role}}{{art.kind}}{{art.retention}}{{art.media}}, {{art.size}} +
+
+
+ + + +
+
+
+ + + + +
{{art.body}}
+
{{art.bodyNote}}
+
+ + + +
+
+
+

Where it came from

+
+ Producer{{art.producer}} + Consumer{{art.consumer}} + Observed{{art.observed}} + Provenance{{art.prov}} +
+
+
+

How it was made

+
+ Runtime{{art.runtime}} + Backend{{art.backend}} + Model{{art.model}} + Format{{art.format}} +
+
+
+
+

Storage

+
+ Lifecycle{{art.lifecycle}} + Read handle{{art.handle}} + Content hash{{art.hash}} + Expires2026-11-09, with the run's other artifacts +
+
+
+
+ +
{{noArtText}}
+
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Library.dc.html b/docs/design/mockups/boards/Library.dc.html new file mode 100644 index 000000000..55b289ee0 --- /dev/null +++ b/docs/design/mockups/boards/Library.dc.html @@ -0,0 +1,387 @@ + + + + +Library tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+
+ +
+ +
+
+
+ + + +
+ +
+ + + +
+
+ +
Searching Hugging Face. Results download into the Pumas library on this machine.
+
+
+ +
+ + +
{{grp.title}} {{grp.n}}
+ + + +
+
+ + +
+ {{r.id}}{{r.sub}} + {{r.size}} + +
+
+
8 of 240 results. Narrow the search to see more specific models.
+
+
+
+ Cache on device on disk + {{diskLine}} +
+
+ +
+
+
+
+
{{sel.name}} {{sel.family}}
+
{{sel.id}}
+
+ {{c}} +
+
+
+ + + +
+
+ +
+
+

Where it lives

+
+ On disk{{sel.size}}, {{sel.path}} + On device{{sel.onDevice}} + Format{{sel.format}} +
+
+
+

How it is used

+
+ Runs{{sel.runs}} + Last used{{sel.lastLong}} + Read from network{{sel.net}} +
+
+
+ +
+

Workflows that use it

+ + + + +
WorkflowNodeRunsLast run
{{u.wf}} v{{u.ver}}{{u.node}}{{u.n}}{{u.last}}
+
+
+

Source

+
+ Repository{{sel.repo}} + Downloaded{{sel.downloaded}} + Licence{{sel.licence}} +
+
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Main.dc.html b/docs/design/mockups/boards/Main.dc.html new file mode 100644 index 000000000..db43b535c --- /dev/null +++ b/docs/design/mockups/boards/Main.dc.html @@ -0,0 +1,273 @@ + + + + +Scheduler, drafting paper direction + + + + + + + + +
+ + + +
+
+

Scheduler

+
Updated 20:05:51, live
+
+ + + + +
+ Engine unreachable since 20:03. Showing the last projection; runs keep executing on the engine. + +
+
+ +
+ + +
+ + + +
+ + + +
+ + +
+ + + + + + + + + + +
+
+ +
+
+ + + + + + + + + + + + + + + +
RunStatusPlacementQueueStartedDurationUpdated
{{run.id}} · v{{run.ver}}
{{run.statusLabel}}
{{run.reason}}
{{run.runtime}}
{{run.device}}
{{run.queue}}{{run.started}}{{run.dur}}{{run.updated}}
+
+ + +
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Network.dc.html b/docs/design/mockups/boards/Network.dc.html new file mode 100644 index 000000000..a1f6adc04 --- /dev/null +++ b/docs/design/mockups/boards/Network.dc.html @@ -0,0 +1,373 @@ + + + + +Network tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+
+ +
+ +
+
+
+ + + +
+
+
+ +
{{grp.title}} {{grp.n}}
+ + + +
+
+
Trusted peers only
+
+ +
+
+
+
+
{{host.name}} {{host.id}}
+
{{host.os}}, captured {{host.captured}}
+
+ {{host.transport}} + {{c}} +
+
+
+ + +
+
+ +
+
{{host.cpu}}
{{host.cores}} cores
+
{{host.mem}}
of {{host.memTotal}} memory in use
+
{{host.sched}}
running / queued here
+
{{host.sessions}}
runtime sessions loaded
+
+ + +
+

Devices

+
+ +
+
{{lane.name}}{{lane.meta}}
+
+ +
{{b.label}}
+
+
+
+
+
+
+
+ +

Devices

{{host.gpuNote}}
+
+ + +
+

{{sel.wf}} on this node

+
+ Run{{sel.id}} + State{{runState}} + Runtime session{{runSession}} + Assets read{{runAssets}} +
+
+
+ +
+

{{sel.wf}}

+
{{elsewhereText}}
+
+
+ +
+
+

Disks

+ + +
MountFreeTotal
{{d.mount}}{{d.free}}{{d.total}}
+
+
+

Interfaces

+ + +
NameReceivedSent
{{i.name}}{{i.rx}}{{i.tx}}
+
+
+
+

Identity

+
+ Node id{{host.id}} + Hostname{{host.host}} + Kernel{{host.kernel}} +
+
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/NodeEditor.dc.html b/docs/design/mockups/boards/NodeEditor.dc.html new file mode 100644 index 000000000..c403328d0 --- /dev/null +++ b/docs/design/mockups/boards/NodeEditor.dc.html @@ -0,0 +1,358 @@ + + + + +Node Editor tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+
+ + +
Node authoring is not available in this build. You can read your node definitions, but Save and Publish are off until the authoring API and the local agent are enabled in Settings.
+
+ +
+ +
+
+
+ + + +
+
+
+ +
{{grp.title}} {{grp.n}}
+ + + +
+
+
Built-in nodes are read-only. Duplicate one to start from it.
+
+ +
+
+
+
+
{{sel.label}}
+
{{sel.type}} v{{sel.ver}}
+
+
+ + +
+
+
+ + + + + +
+
+

Inputs

+ + + + +
NameTypeDefault
+ +
+
+

Outputs

+ + + + +
NameTypeRetained
+ +
+
+

Implementation

+
{{sel.code}}
+
+
+
+ +
+
On the canvaslive preview
+
+
+
{{sel.label}}{{sel.type}}
+
{{p.name}}
+
{{p.name}}
+
+
+
+

Checks

+
+ {{c.text}} +
+
+
+

Try it

+
Runs the node once with sample inputs on the local engine, outside any workflow.
+
{{tryNote}}
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Revised.dc.html b/docs/design/mockups/boards/Revised.dc.html new file mode 100644 index 000000000..a45ddcdf1 --- /dev/null +++ b/docs/design/mockups/boards/Revised.dc.html @@ -0,0 +1,474 @@ + + + + +Scheduler, dark drafting paper revised + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ + +
Local engine
+
+ +
Engine unreachable since 20:03, showing last projection
+
+ Settings + +
+ +
+
+ + +
+
local
+
+ +
+
{{lane.name}}{{lane.meta}}
+
+ +
{{b.label}}
+
+
+
+
+
+
running waiting for memory next
+
+
+ +
+ +
+
+
+ + + +
+
+ + + +
+ +
+ + {{c.label}} + +
+
+ +
+ + + + + + + + + + + +
+
+
+ +
+ + + + + + + + +
+ +
+ + + + + + + {{sel.wf}} has finished. No actions available. + + + Select a run to act on it. The other tabs follow this selection. + +
+
+ +
+ +
+
+
+
{{sel.wf}} v{{sel.ver}}
+
{{sel.id}}
+
+ {{sel.statusLabel}} + {{c.text}} +
+
+ +
+
+
+

Progress

+
{{sel.progress}}
+
{{sel.est}}, based on 14 earlier runs of this version
+
+
+

Placement

+
{{sel.placementLong}}
+
Policy fair-share, bucket default, {{sel.vram}} GB requested
+
+
+

Retention

+
Keep artifacts 7 days, 212 MB on disk
+
Expires 2026-11-09
+
+
+
+

Scheduler timeline

+
+ {{e.t}}{{e.text}} +
+
Node-level events for this run are in Diagnostics.
+
+
+
+ +
Select a run to see its progress, placement and timeline.
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Sessions.dc.html b/docs/design/mockups/boards/Sessions.dc.html new file mode 100644 index 000000000..219425bde --- /dev/null +++ b/docs/design/mockups/boards/Sessions.dc.html @@ -0,0 +1,370 @@ + + + + +Sessions tab + + + + + + + + + +
+
+
Pantograph
+ +
+ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
+ +
Local engine
+ Settings + +
+ +
+
+ +
+ +
+
+
+ + + +
+
+ + + +
+
+
+ +
{{grp.title}} {{grp.n}}
+ + + +
+
+
Sessions are saved in .pantograph/sessions. Runs stay in the Scheduler history after a session closes.
+
+ +
+ +
+
+
+
{{sel.name}}
+
{{sel.id}}
+
+ {{sel.stateLabel}} + {{c}} +
+
+
+ + + + + + + + + + +
+
+ +
+
+

Activity

+
+ Opened{{sel.opened}} + Last activity{{sel.lastAct}} + Client{{sel.clientLong}} +
+
+
+

Runs from this session

+
+ Total{{sel.runsLong}} + Live now{{sel.live}} + Artifacts kept{{sel.disk}} +
+ +
+
+ +
+

Open in this session

+
+ +
{{o.name}} {{o.meta}}{{o.sub}}{{o.action}}
+
+
+
+ +
+

What resumes

+
Open graphs and their unsaved edits, the selected run context, the loaded runtime sessions when memory allows, and the last workbench tab. Finished runs are not re-run.
+
+
+
+ +
Select a session to see what it has open and what it ran.
+
+
+
+
+
+
+ + + diff --git a/docs/design/mockups/boards/Studio.dc.html b/docs/design/mockups/boards/Studio.dc.html new file mode 100644 index 000000000..306b6b690 --- /dev/null +++ b/docs/design/mockups/boards/Studio.dc.html @@ -0,0 +1,305 @@ + + + + +Scheduler, grey studio direction + + + + + + + + +
+ +
+
Pantograph
+ +
+
Local engine, 2 GPUs
+ Assistant +
+ +
+
+

Scheduler

+
{{summary}}. Updated 20:05:51, live
+
+ + +
+ Engine unreachable since 20:03. Showing the last projection; runs keep executing on the engine. + +
+
+ + +
+ +
+
{{lane.name}}
{{lane.meta}}
+
+ +
{{b.label}}
+
+
+
+
+
+
+ +
+ + +
+ + + +
+ + + +
+ + +
+ + + + + + + + + + +
+
+ +
+
+ + + + + + + + + + + + + + + +
RunStatusPlacementQueueStartedDurationUpdated
{{run.id}} · v{{run.ver}}
{{run.statusLabel}}
{{run.reason}}
{{run.runtime}}
{{run.device}}
{{run.queue}}{{run.started}}{{run.dur}}{{run.updated}}
+
+ + +
+
+
+
+ + + diff --git a/docs/design/mockups/boards/shell.css b/docs/design/mockups/boards/shell.css new file mode 100644 index 000000000..4cf3ed8d9 --- /dev/null +++ b/docs/design/mockups/boards/shell.css @@ -0,0 +1,186 @@ +/* Pantograph workbench shell, direction E (dark drafting paper). Shared by the tab artboards. */ +body{margin:0;background:#2A2E35;color:#E4E6EA;font-family:'Atkinson Hyperlegible',system-ui,sans-serif;font-size:14px;line-height:1.45} +a{color:#E4E6EA}a:hover{color:#fff} +*,*::before,*::after{box-sizing:border-box} +button,input,select,textarea{font:inherit;color:inherit} +*{scrollbar-width:thin;scrollbar-color:#5A6069 transparent} +::-webkit-scrollbar{width:10px;height:10px} +::-webkit-scrollbar-track{background:transparent} +::-webkit-scrollbar-thumb{background:#5A6069;border-radius:5px;border:2px solid #33383F} +::-webkit-scrollbar-thumb:hover{background:#7A818C} +::-webkit-scrollbar-corner{background:transparent} +.serif{font-family:Newsreader,Georgia,serif} +.mono{font-family:'JetBrains Mono',ui-monospace,monospace;font-size:12.5px} +.muted{color:#A3A9B4} +.small{font-size:12.5px} +.root{height:100vh;display:flex;flex-direction:column;background:#2A2E35;overflow:hidden} +.hdr{display:flex;align-items:center;gap:4px;padding:0 14px;border-bottom:1px solid #1F2227;background:#23272D;flex:none} +.brand{font-family:Newsreader,Georgia,serif;font-size:18px;font-weight:500;padding-right:14px;letter-spacing:-0.01em} +.tab{display:flex;align-items:center;height:40px;padding:0 11px;text-decoration:none;color:#B8BDC6;border-bottom:2px solid transparent;font-size:13.5px;white-space:nowrap} +.tab:hover{color:#fff;background:rgba(255,255,255,.04)} +.tab[aria-current="page"]{color:#fff;border-bottom-color:#E4E6EA} +.vdiv{width:1px;height:18px;background:#4A5059;margin:0 10px;flex:none} +.tgl{height:26px;padding:0 10px;border:1px solid #4A5059;border-radius:4px;background:transparent;color:#B8BDC6;cursor:pointer;display:inline-flex;align-items:center;gap:6px;font-size:12.5px;white-space:nowrap} +.tgl:hover{color:#fff;border-color:#8A909A} +.tgl[aria-pressed="true"]{background:#E4E6EA;color:#1F2227;border-color:#E4E6EA} +.ctx{display:inline-flex;align-items:center;gap:8px;height:26px;padding:0 4px 0 10px;border:1px solid #4A5059;border-radius:4px;background:#2E333A;font-size:12.5px;max-width:320px} +.ctx .x{width:20px;height:20px;border:0;border-radius:3px;background:transparent;color:#A3A9B4;cursor:pointer;display:inline-flex;align-items:center;justify-content:center} +.ctx .x:hover{background:#4A5059;color:#fff} +.eng{display:inline-block;width:7px;height:7px;background:#A7C4A0;border-radius:1px} +.eng.off{background:#E39A9A} +.engine{font-size:12.5px;display:flex;align-items:center;gap:8px;margin:0 10px 0 12px;white-space:nowrap} +.main{flex:1;min-height:0;padding:10px 22px 16px;display:flex;flex-direction:column;gap:10px} +.dimrow{display:flex;align-items:center;padding:8px 0 4px;flex:none} +.dim{position:relative;flex:1;height:1px;background:#8A909A;align-self:center;margin:0 6px} +.dim::before,.dim::after{content:"";position:absolute;top:-5px;width:1px;height:11px;background:#8A909A} +.dim::before{left:0}.dim::after{right:0} +.dim-label{position:absolute;left:50%;top:-9px;transform:translateX(-50%);padding:0 12px;background:#2A2E35;font-family:'JetBrains Mono',monospace;font-size:12px;color:#C9CDD4;white-space:nowrap} +.field{height:30px;padding:0 10px;border:1px solid #4A5059;border-radius:4px;background:#23272D;color:#E4E6EA} +.field:focus{outline:2px solid var(--accent);outline-offset:1px} +.seg{display:flex;flex-wrap:wrap;border:1px solid #4A5059;border-radius:4px;overflow:hidden;background:#23272D} +.seg button{height:30px;padding:0 7px;border:0;background:transparent;cursor:pointer;display:flex;gap:4px;align-items:center;justify-content:center;color:#B8BDC6;font-size:12.5px;white-space:nowrap;min-width:0;flex:1} +.seg button+button{border-left:1px solid #3B4048} +.seg button:hover{background:#33383F;color:#fff} +.seg button[aria-pressed="true"]{background:#E4E6EA;color:#1F2227} +.seg .n{font-family:'JetBrains Mono',monospace;font-size:11px;opacity:.8} +.btn{height:30px;padding:0 11px;border:1px solid #4A5059;border-radius:4px;background:#33383F;cursor:pointer;display:inline-flex;align-items:center;gap:6px;color:#E4E6EA;text-decoration:none;font-size:13px;white-space:nowrap} +.btn:hover{border-color:#8A909A} +.btn.sm{height:28px} +.btn.primary{background:#E4E6EA;color:#1F2227;border-color:#E4E6EA;font-weight:700} +.btn.danger{background:transparent;color:#E39A9A;border-color:#5A4247} +.btn.danger:hover{border-color:#E39A9A} +.btn.confirm{background:#E39A9A;color:#1F2227;border-color:#E39A9A;font-weight:700} +.btn:focus-visible,.seg button:focus-visible,.item:focus-visible,.tgl:focus-visible,.ghead:focus-visible,.fchip button:focus-visible,.row:focus-visible,.pill:focus-visible{outline:2px solid var(--accent);outline-offset:1px} +.panel{background:#33383F;border:1px solid #4A5059;border-radius:4px} +.col{display:flex;flex-direction:column;overflow:hidden;min-width:0} +.scroll{flex:1;min-height:0;overflow:auto} +.ptop{padding:10px 12px;display:flex;flex-direction:column;gap:8px;flex:none;border-bottom:1px solid #4A5059} +.pfoot{padding:8px 12px;border-top:1px solid #4A5059;background:#2E333A;display:flex;gap:8px;align-items:center;flex:none;min-height:48px} +.ghead{display:flex;align-items:center;gap:8px;width:100%;padding:7px 12px;border:0;border-top:1px solid #3B4048;background:#2E333A;color:#C9CDD4;font-size:12px;font-weight:700;text-align:left;cursor:pointer;position:sticky;top:0;z-index:1} +.ghead .n{font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:400;color:#A3A9B4} +.ghead .chev{margin-left:auto;font-size:10px;color:#8A909A} +.item{display:grid;grid-template-columns:14px 1fr auto;gap:10px;align-items:start;width:100%;padding:8px 12px;border:0;border-top:1px solid #3B4048;background:transparent;text-align:left;cursor:pointer;color:#E4E6EA} +.item:hover{background:#3A3F47} +.item[aria-current="true"]{background:#434A54;box-shadow:inset 3px 0 0 #E4E6EA} +.item .name{font-weight:700;color:#fff} +.item .ver{font-family:'JetBrains Mono',monospace;font-size:11px;color:#A3A9B4;margin-left:6px} +.item .time{font-family:'JetBrains Mono',monospace;font-size:11.5px;color:#A3A9B4;padding-top:2px;white-space:nowrap} +.item .sub{display:block;font-size:12.5px;color:#A3A9B4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.g{display:inline-block;width:10px;height:10px;border-radius:50%;border:1.5px solid #A3A9B4;margin-top:4px;flex:none} +.g-running{background:var(--accent);border-color:var(--accent)} +.g-waiting{background:linear-gradient(90deg,var(--accent) 50%,transparent 50%);border-color:var(--accent)} +.g-queued{background:transparent} +.g-succeeded{background:#A3A9B4;border-color:#A3A9B4} +.g-failed{background:#E39A9A;border-color:#E39A9A;border-radius:1px;transform:rotate(45deg) scale(.9)} +.g-cancelled{border-style:dashed} +.g-idle{border-color:#6B717B} +.g-warn{background:#D9B06A;border-color:#D9B06A;border-radius:1px;transform:rotate(45deg) scale(.9)} +.g-dark{border-color:#1F2227} +.g-dark.g-running{background:#1F2227} +.st-failed{color:#E39A9A} +.sec{padding:14px 18px;border-top:1px solid #4A5059} +.sec h3{margin:0 0 8px;font-size:13px;font-weight:700;color:#fff} +.ev{display:grid;grid-template-columns:66px 1fr;gap:5px 14px;font-size:13.5px} +.ev .t{font-family:'JetBrains Mono',monospace;font-size:12px;color:#A3A9B4} +.kv{display:grid;grid-template-columns:max-content 1fr;gap:5px 16px;font-size:13.5px} +.kv .k{color:#A3A9B4} +.chip{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 8px;border:1px solid #4A5059;border-radius:11px;font-size:12px;background:#23272D;white-space:nowrap} +.chip .g{margin-top:0} +.fchip{display:inline-flex;align-items:center;gap:4px;height:24px;padding:0 4px 0 8px;border:1px solid #6B717B;border-radius:12px;font-size:12px;background:#2E333A;color:#E4E6EA} +.fchip button{width:18px;height:18px;border:0;border-radius:9px;background:transparent;color:#A3A9B4;cursor:pointer} +.fchip button:hover{background:#4A5059;color:#fff} +.fl{font-size:12px;color:#A3A9B4} +.fl .field{display:block;width:100%;margin-top:3px;height:28px} +.title{font-family:Newsreader,Georgia,serif;font-size:24px;font-weight:500;letter-spacing:-0.01em;color:#fff} +.title .muted{font-size:16px} +.empty{padding:32px 24px;color:#A3A9B4} +/* table rows */ +.tbl{width:100%;border-collapse:collapse;font-size:13px} +.tbl th{position:sticky;top:0;z-index:1;background:#2E333A;color:#A3A9B4;font-weight:700;font-size:12px;text-align:left;padding:7px 12px;border-bottom:1px solid #4A5059;white-space:nowrap} +.tbl td{padding:7px 12px;border-top:1px solid #3B4048;vertical-align:top} +.tbl tr.row{cursor:pointer} +.tbl tr.row:hover td{background:#3A3F47} +.tbl tr[aria-current="true"] td{background:#434A54} +.tbl tr[aria-current="true"] td:first-child{box-shadow:inset 3px 0 0 #E4E6EA} +.num{font-family:'JetBrains Mono',monospace;font-size:12px;text-align:right;white-space:nowrap} +/* log lines */ +.log{font-family:'JetBrains Mono',monospace;font-size:12px;line-height:1.55} +.log .ln{display:grid;grid-template-columns:96px 14px 1fr;gap:10px;padding:3px 12px;border-top:1px solid #30353C;align-items:start} +.log .ln:hover{background:#3A3F47} +.log .ln .t{color:#8A909A} +.log .ln .g{margin-top:5px;width:8px;height:8px} +.log .ln.err{background:rgba(227,154,154,.06)} +.log .ln .m{white-space:pre-wrap;word-break:break-word;color:#D5D9DF} +.log .ln .m b{color:#fff;font-weight:500} +/* lanes */ +.lane{display:grid;grid-template-columns:118px 1fr;gap:8px;align-items:center} +.lane-name{font-family:'JetBrains Mono',monospace;font-size:11.5px;color:#C9CDD4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.3} +.lane-track{display:flex;gap:2px;height:20px;border-radius:3px;overflow:hidden;background:#23272D} +.blk{display:flex;align-items:center;gap:6px;padding:0 6px;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;border:1px solid transparent;border-radius:2px} +.blk-running{background:var(--accent);color:#1F2227;font-weight:700} +.blk-waiting{border-color:var(--accent);color:#E4E6EA;background:repeating-linear-gradient(135deg,transparent 0 4px,rgba(217,176,106,.25) 4px 6px)} +.blk-queued{border-color:#6B717B;color:#C9CDD4} +.blk-free{border:0} +.legend{display:flex;gap:14px;align-items:center;font-size:11.5px;color:#A3A9B4;white-space:nowrap} +.legend .g{margin-top:0} +/* meters */ +.meter{height:6px;border-radius:3px;background:#23272D;overflow:hidden} +.meter i{display:block;height:100%;background:#8A909A;border-radius:3px} +.meter i.acc{background:var(--accent)} +/* graph canvas */ +.canvas{position:relative;flex:1;min-width:0;overflow:hidden;border:1px solid #4A5059;border-radius:4px;background-color:#2E333A;background-image:radial-gradient(#4A5059 1px,transparent 1px);background-size:22px 22px} +.gnode{position:absolute;width:168px;background:#33383F;border:1px solid #5A6069;border-radius:4px;box-shadow:0 1px 0 rgba(0,0,0,.25)} +.gnode .nh{display:flex;align-items:center;gap:7px;padding:6px 9px;border-bottom:1px solid #4A5059;font-size:12.5px;font-weight:700;color:#fff} +.gnode .nh .g{margin-top:0;width:8px;height:8px} +.gnode .nh .mono{font-weight:400;color:#A3A9B4;font-size:11px;margin-left:auto} +.gnode .pt{display:flex;justify-content:space-between;padding:3px 9px;font-size:11.5px;color:#C9CDD4;position:relative} +.gnode .pt::before,.gnode .pt::after{content:"";position:absolute;top:50%;width:7px;height:7px;border-radius:50%;background:#2E333A;border:1.5px solid #8A909A;transform:translateY(-50%)} +.gnode .pt.in::after{display:none}.gnode .pt.in::before{left:-4px} +.gnode .pt.out::before{display:none}.gnode .pt.out::after{right:-4px} +.gnode .pt.out{justify-content:flex-end} +.gnode[aria-current="true"]{border-color:#E4E6EA;box-shadow:0 0 0 1px #E4E6EA} +.gnode.dim{opacity:.55} +.wire{fill:none;stroke:#8A909A;stroke-width:1.5} +.wire.live{stroke:var(--accent);stroke-width:2} +.wire.err{stroke:#E39A9A;stroke-dasharray:4 3} +.pill{height:26px;padding:0 9px;border:1px solid #4A5059;border-radius:4px;background:#33383F;color:#C9CDD4;cursor:pointer;display:inline-flex;align-items:center;gap:6px;font-size:12px;white-space:nowrap} +.pill:hover{border-color:#8A909A;color:#fff} +.fab{position:absolute;display:flex;gap:6px;padding:6px;background:rgba(35,39,45,.9);border:1px solid #4A5059;border-radius:4px;backdrop-filter:blur(4px)} +.minimap{position:absolute;right:12px;bottom:12px;width:140px;height:84px;border:1px solid #4A5059;border-radius:3px;background:rgba(35,39,45,.9)} +.minimap i{position:absolute;width:12px;height:7px;background:#6B717B;border-radius:1px} +.minimap .view{position:absolute;border:1px solid #C9CDD4;background:transparent} +/* tree */ +.tree button{display:flex;align-items:center;gap:8px;width:100%;padding:5px 12px;border:0;background:transparent;color:#E4E6EA;text-align:left;cursor:pointer;font-size:13px} +.tree button:hover{background:#3A3F47} +.tree button[aria-current="true"]{background:#434A54;box-shadow:inset 3px 0 0 #E4E6EA} +.tree .lvl1{padding-left:28px} +.tree .lvl2{padding-left:46px;color:#C9CDD4} +.tree .typ{font-family:'JetBrains Mono',monospace;font-size:11px;color:#8A909A;margin-left:auto} +.code{font-family:'JetBrains Mono',monospace;font-size:12px;line-height:1.55;white-space:pre;overflow:auto;padding:12px 14px;background:#23272D;border-radius:4px;border:1px solid #4A5059;color:#D5D9DF} +.code .k{color:#C9CDD4}.code .s{color:#D9B06A}.code .n{color:#9FB7D9} +/* cards */ +.card{background:#33383F;border:1px solid #4A5059;border-radius:4px;padding:12px 14px} +.card h4{margin:0 0 6px;font-size:13px;font-weight:700;color:#fff} +.grid-auto{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px} +/* run-context picker */ +.ctxwrap{position:relative;display:flex;align-items:center} +.ctxbtn{display:inline-flex;align-items:center;gap:8px;height:24px;border:0;background:transparent;color:#E4E6EA;cursor:pointer;padding:0;max-width:280px;font-size:12.5px} +.ctxbtn .ctxname{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.ctxbtn:hover .ctxname{color:#fff} +.ctx.ctxempty{padding:0 10px;color:#B8BDC6;border-style:dashed} +.ctx.ctxempty:hover{color:#fff;border-color:#8A909A} +.ctxbtn:focus-visible,.ctx .x:focus-visible,.poprow:focus-visible{outline:2px solid var(--accent);outline-offset:1px} +.pop{position:absolute;right:0;top:32px;width:400px;z-index:60;background:#23272D;border:1px solid #4A5059;border-radius:4px;box-shadow:0 10px 28px rgba(0,0,0,.45);display:flex;flex-direction:column;max-height:70vh} +.poplist{overflow:auto;min-height:0;flex:1} +.pophead{padding:6px 12px;border-top:1px solid #3B4048;background:#2E333A;color:#C9CDD4;font-size:12px;font-weight:700;position:sticky;top:0;display:flex;gap:8px;align-items:center} +.pophead .n{font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:400;color:#A3A9B4} +.poprow{display:grid;grid-template-columns:14px 1fr auto;gap:10px;align-items:start;width:100%;padding:7px 12px;border:0;border-top:1px solid #3B4048;background:transparent;text-align:left;cursor:pointer;color:#E4E6EA;font-size:13px} +.poprow:hover{background:#3A3F47} +.poprow[aria-current="true"]{background:#434A54;box-shadow:inset 3px 0 0 #E4E6EA} +.poprow b{color:#fff} +.poprow .ver{font-family:'JetBrains Mono',monospace;font-size:11px;color:#A3A9B4} +.poprow .sub{display:block;font-size:12px;color:#A3A9B4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.poprow .time{font-family:'JetBrains Mono',monospace;font-size:11px;color:#A3A9B4;padding-top:3px} +.popfoot{padding:8px 12px;border-top:1px solid #3B4048;font-size:11.5px;color:#8A909A;line-height:1.4} +.toast{position:fixed;left:50%;bottom:22px;transform:translateX(-50%);z-index:70;padding:7px 12px;border:1px solid #4A5059;border-radius:4px;background:#23272D;color:#E4E6EA;font-size:12.5px;font-family:'JetBrains Mono',monospace;box-shadow:0 6px 18px rgba(0,0,0,.4)} +.btn[aria-disabled="true"],.tgl[aria-disabled="true"]{opacity:.45;cursor:default} diff --git a/docs/design/mockups/ctx-markup.html b/docs/design/mockups/ctx-markup.html new file mode 100644 index 000000000..781766f5f --- /dev/null +++ b/docs/design/mockups/ctx-markup.html @@ -0,0 +1,38 @@ +
+ +
+ + +
+
+ + + + + + +
+
Copied {{copiedId}}
diff --git a/docs/design/mockups/ctx-mixin.js b/docs/design/mockups/ctx-mixin.js new file mode 100644 index 000000000..d36c11c61 --- /dev/null +++ b/docs/design/mockups/ctx-mixin.js @@ -0,0 +1,121 @@ + catalog() { + return [ + { id: 'run_01JB2K7Q3M', wf: 'ingest-docs-rag', ver: '1.4.0', status: 'running', runtime: 'llama.cpp', device: 'cuda:0', deviceName: 'RTX 4090', vram: 17.2, queue: 0, prio: 0, est: 'About 2 min left', node: 'embed_chunks', pct: '61%', reason: '', started: '20:01:40', dur: '4m 12s', updated: '20:05:51', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2K9F0A', wf: 'image-gen-sdxl', ver: '0.9.2', status: 'running', runtime: 'diffusers', device: 'cuda:1', deviceName: 'RTX 3090', vram: 9.8, queue: 0, prio: 0, est: 'About 40 s left', node: 'sample', pct: 'step 18 of 30', reason: '', started: '20:04:02', dur: '1m 49s', updated: '20:05:50', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2KB4ZT', wf: 'transcribe-meeting', ver: '2.1.0', status: 'waiting', runtime: 'whisper', device: 'cuda:0', deviceName: 'RTX 4090', vram: 8, queue: 1, prio: 5, est: 'Starts after ingest-docs-rag', node: '', pct: '', reason: 'needs 8 GB on cuda:0, 6.8 GB free', started: '—', dur: '—', updated: '20:05:12', client: 'cli', session: 's-9c01' }, + { id: 'run_01JB2KC1PX', wf: 'summarize-daily', ver: '1.0.3', status: 'queued', runtime: 'llama.cpp', device: 'cuda:1', deviceName: 'RTX 3090', vram: 6, queue: 2, prio: 0, est: 'About 6 min', node: '', pct: '', reason: 'next on cuda:1, model cached', started: '—', dur: '—', updated: '20:04:40', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2KD8RN', wf: 'embed-corpus', ver: '1.4.0', status: 'queued', runtime: 'llama.cpp', device: '', deviceName: '', vram: 7, queue: 3, prio: 0, est: 'About 9 min', node: '', pct: '', reason: 'cold load, 12 s', started: '—', dur: '—', updated: '20:04:41', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2KE2QW', wf: 'image-gen-sdxl', ver: '0.9.2', status: 'queued', runtime: 'diffusers', device: '', deviceName: '', vram: 9.8, queue: 4, prio: 0, est: 'About 2 min', node: '', pct: '', reason: 'model cached', started: '—', dur: '—', updated: '20:04:55', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2JZ0MT', wf: 'summarize-daily', ver: '1.0.3', status: 'succeeded', runtime: 'llama.cpp', device: 'cuda:0', deviceName: 'RTX 4090', vram: 6, queue: 0, prio: 0, est: 'Finished in 38 s', node: '', pct: '', reason: '', started: '19:52:10', dur: '38 s', updated: '19:52:48', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2JV7KD', wf: 'embed-corpus', ver: '1.3.9', status: 'succeeded', runtime: 'llama.cpp', device: 'cuda:0', deviceName: 'RTX 4090', vram: 7, queue: 0, prio: 0, est: 'Finished in 11m 03s', node: '', pct: '', reason: '', started: '19:38:01', dur: '11m 03s', updated: '19:49:04', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2JT3HB', wf: 'image-gen-sdxl', ver: '0.9.1', status: 'failed', runtime: 'diffusers', device: 'cuda:1', deviceName: 'RTX 3090', vram: 14.2, queue: 0, prio: 0, est: 'Stopped after 22 s', node: 'load_model', pct: '', reason: 'out of memory, needed 14.2 GB', started: '19:35:20', dur: '22 s', updated: '19:35:42', client: 'gui', session: 's-4f2a' }, + { id: 'run_01JB2JQ9XA', wf: 'transcribe-meeting', ver: '2.0.0', status: 'cancelled', runtime: 'whisper', device: 'cuda:0', deviceName: 'RTX 4090', vram: 8, queue: 0, prio: 0, est: 'Stopped after 1m 10s', node: 'transcribe', pct: '', reason: 'cancelled from the GUI', started: '19:30:05', dur: '1m 10s', updated: '19:31:15', client: 'gui', session: 's-4f2a' } + ]; + } + wfMap() { + return { + 'ingest-docs-rag': { model: 'pumas://models/bge-m3', nodes: [['read_docs', 'read-file', 'text'], ['chunking', 'expand-settings', 'settings'], ['split', 'processing', 'chunks'], ['embed_chunks', 'embedding', 'embedding'], ['index', 'vector-output', ''], ['manifest', 'write-file', '']] }, + 'image-gen-sdxl': { model: 'pumas://models/sdxl-base-1.0', nodes: [['prompt', 'text-input', 'text'], ['load_model', 'puma-lib', 'model_path'], ['sample', 'pytorch-inference', 'latents'], ['decode', 'image-output', 'image'], ['unload', 'unload-model', '']] }, + 'transcribe-meeting': { model: 'pumas://models/whisper-large-v3', nodes: [['audio', 'audio-input', 'audio'], ['transcribe', 'onnx-inference', 'transcript'], ['notes', 'text-output', 'text']] }, + 'summarize-daily': { model: 'pumas://models/qwen3-8b-instruct', nodes: [['fetch', 'read-file', 'text'], ['summarize', 'llm-inference', 'response'], ['write', 'write-file', '']] }, + 'embed-corpus': { model: 'pumas://models/bge-m3', nodes: [['read', 'read-file', 'text'], ['embed', 'embedding', 'embedding'], ['index', 'vector-output', '']] } + }; + } + nodeStates(run) { + const wf = this.wfMap()[run.wf] || { nodes: [['start', 'processing', 'out'], ['end', 'text-output', '']] }; + const idx = wf.nodes.findIndex((n) => n[0] === run.node); + return wf.nodes.map(([id, type, port], i) => { + let state = 'queued'; + if (run.status === 'succeeded') state = 'succeeded'; + else if (run.status === 'running') state = i < idx ? 'succeeded' : i === idx ? 'running' : 'queued'; + else if (run.status === 'failed') state = i < idx ? 'succeeded' : i === idx ? 'failed' : 'skipped'; + else if (run.status === 'cancelled') state = i < idx ? 'succeeded' : i === idx ? 'cancelled' : 'skipped'; + const glyph = state === 'skipped' ? 'g-cancelled' : 'g-' + state; + return { id, type, port, state, glyph, label: state === 'skipped' ? 'skipped' : state }; + }); + } + decorateRun(r) { + const labels = { running: 'Running', waiting: 'Waiting', queued: 'Queued', succeeded: 'Succeeded', failed: 'Failed', cancelled: 'Cancelled' }; + const isLive = r.status === 'running' || r.status === 'waiting' || r.status === 'queued'; + let context = ''; + if (r.status === 'running') context = ', ' + r.node + (r.pct ? ' ' + r.pct : ''); + else if (r.status === 'waiting') context = ', ' + r.reason; + else if (r.status === 'queued') context = ', #' + r.queue + ' in queue'; + else if (r.reason) context = ', ' + r.reason; + else context = ', ' + r.dur; + const placement = r.device ? r.runtime + ' on ' + r.device : r.runtime + ', device not assigned yet'; + const placementLong = r.device ? r.runtime + ' on ' + r.device + ' (' + r.deviceName + ')' : 'Not assigned to a device yet'; + let progress = r.est; + if (r.status === 'running') progress = r.node + ', ' + r.pct; + else if (r.status === 'waiting') progress = 'Waiting: ' + r.reason; + else if (r.status === 'queued') progress = 'Queue position ' + r.queue + ', ' + r.reason; + else if (r.status === 'failed') progress = 'Failed in ' + r.node + ': ' + r.reason; + const chips = []; + if (r.device) chips.push({ text: r.runtime + ' on ' + r.device }); + if (r.prio) chips.push({ text: 'priority ' + r.prio }); + if (r.queue) chips.push({ text: '#' + r.queue + ' in queue' }); + return { ...r, glyph: 'g-' + r.status, stClass: r.status === 'failed' ? 'st-failed' : '', statusLabel: labels[r.status], contextSuffix: context, placement, placementLong, progress, chips, isLive, + model: (this.wfMap()[r.wf] || {}).model || 'none', hoverOn: () => { this._hoverRun = r.id; }, hoverOff: () => { if (this._hoverRun === r.id) this._hoverRun = null; } }; + } + ctxBind() { + if (this._ctxBound || typeof document === 'undefined') return; + this._ctxBound = true; + const isField = (t) => t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT'); + document.addEventListener('keydown', (e) => { + const k = (e.key || '').toLowerCase(); const mod = e.ctrlKey || e.metaKey; + if (e.key === 'Escape' && this.state && this.state.pickerOpen) { this.setState({ pickerOpen: false }); return; } + if (!mod || isField(e.target)) return; + if (k === 'c' && this._hoverRun) this.copyRun(this._hoverRun); + if (k === 'v' && this._hoverCtx) { e.preventDefault(); this.pasteRun(); } + }); + document.addEventListener('mousedown', (e) => { + if (this.state && this.state.pickerOpen && !(e.target.closest && e.target.closest('.ctxwrap'))) this.setState({ pickerOpen: false }); + }); + window.addEventListener('storage', (e) => { if (e.key === 'pg.run') this.setState({ run: e.newValue || null }); }); + } + copyRun(id) { + try { localStorage.setItem('pg.clip', id); } catch (_) {} + if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(id).catch(() => {}); + this.setState({ copied: id }); + clearTimeout(this._copyT); this._copyT = setTimeout(() => this.setState({ copied: null }), 1600); + } + pasteRun() { + const apply = (text) => { const id = (text || '').trim(); if (this.catalog().some((r) => r.id === id)) this.pickRun(id); else this.setState({ pickerOpen: true, pickerQuery: id }); }; + let fallback = ''; try { fallback = localStorage.getItem('pg.clip') || ''; } catch (_) {} + if (navigator.clipboard && navigator.clipboard.readText) navigator.clipboard.readText().then(apply, () => apply(fallback)); else apply(fallback); + } + pickRun(id) { + try { localStorage.setItem('pg.run', id || ''); } catch (_) {} + this.setState({ run: id || null, pickerOpen: false, pickerQuery: '', confirmCancel: false }); + } + ctxRunId(fallback) { + const st = this.state || {}; + if ('run' in st) return st.run; + try { const v = localStorage.getItem('pg.run'); if (v !== null) return v || null; } catch (_) {} + return fallback; + } + ctxVals(fallbackId) { + this.ctxBind(); + const st = this.state || {}; + const runId = this.ctxRunId(fallbackId); + const all = this.catalog(); + const selRaw = all.find((r) => r.id === runId); + const sel = this.decorateRun(selRaw || all[0]); + const qRaw = st.pickerQuery || ''; const q = qRaw.toLowerCase(); + const match = (r) => !q || r.wf.includes(q) || r.id.toLowerCase().includes(q) || ('v' + r.ver).includes(q); + const groups = [['Running', ['running']], ['Waiting for memory', ['waiting']], ['Queued', ['queued']], ['Finished today', ['succeeded', 'failed', 'cancelled']]] + .map(([title, keys]) => { const runs = all.filter((r) => keys.includes(r.status) && match(r)).map((r) => ({ ...this.decorateRun(r), selected: r.id === runId, pick: () => this.pickRun(r.id) })); return { title, n: runs.length, runs }; }) + .filter((g) => g.n); + const total = groups.reduce((n, g) => n + g.n, 0); + return { + runId, hasSel: !!selRaw, noSel: !selRaw, sel, ctxHas: !!selRaw, ctxNone: !selRaw, ctxRun: sel, + pickerOpen: !!st.pickerOpen, pickerQuery: qRaw, pickerGroups: groups, + pickerEmpty: total === 0, pickerEmptyText: q.startsWith('run_') ? 'No run with id ' + qRaw + ' in today\'s history.' : 'No runs match.', + togglePicker: () => this.setState({ pickerOpen: !st.pickerOpen }), + openPicker: () => this.setState({ pickerOpen: true }), + setQuery: (e) => { const v = e.target.value; if (all.some((r) => r.id === v.trim())) this.pickRun(v.trim()); else this.setState({ pickerQuery: v }); }, + clearSel: () => this.pickRun(null), + ctxHoverOn: () => { this._hoverCtx = true; }, ctxHoverOff: () => { this._hoverCtx = false; }, + copied: !!st.copied, copiedId: st.copied || '' + }; + } diff --git a/docs/design/mockups/inject.py b/docs/design/mockups/inject.py new file mode 100644 index 000000000..1db44af99 --- /dev/null +++ b/docs/design/mockups/inject.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Expands the shared run-context picker into every board. +Markup goes where a board has (or between ... ); +the mixin goes where the class has /*ctx*/ (or between /*ctx-start*/ ... /*ctx-end*/). Idempotent.""" +import pathlib, re, sys +here = pathlib.Path(__file__).parent +markup = (here / "ctx-markup.html").read_text().rstrip("\n") +mixin = (here / "ctx-mixin.js").read_text().rstrip("\n") +M0, M1 = "", "" +J0, J1 = "/*ctx-start*/", "/*ctx-end*/" +for f in sorted((here / "project").glob("*.dc.html")): + s = f.read_text() + if "" not in s and M0 not in s: + continue + s = s.replace("", f"{M0}\n{markup}\n {M1}") + s = re.sub(re.escape(M0) + r"[\s\S]*?" + re.escape(M1), lambda _: f"{M0}\n{markup}\n {M1}", s) + s = s.replace("/*ctx*/", f"{J0}\n{mixin}\n {J1}") + s = re.sub(re.escape(J0) + r"[\s\S]*?" + re.escape(J1), lambda _: f"{J0}\n{mixin}\n {J1}", s) + f.write_text(s) + print("injected", f.name) diff --git a/docs/design/mockups/viewer/.gitignore b/docs/design/mockups/viewer/.gitignore new file mode 100644 index 000000000..45ddf0ae3 --- /dev/null +++ b/docs/design/mockups/viewer/.gitignore @@ -0,0 +1 @@ +site/ diff --git a/docs/design/mockups/viewer/build.sh b/docs/design/mockups/viewer/build.sh new file mode 100755 index 000000000..2e0923223 --- /dev/null +++ b/docs/design/mockups/viewer/build.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Builds the local mockup site from ../boards into ./site and serves it on http://127.0.0.1:8765/ +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +src="$here/../boards" +out="$here/site" +mkdir -p "$out" +cp "$here/support.js" "$out/support.js" +cp "$src/shell.css" "$out/shell.css" +cp "$here/current-scheduler.png" "$out/current-scheduler.png" +for f in "$src"/*.dc.html; do + b="$(basename "$f" .dc.html)" + sed -e 's#src="/_blob/[0-9a-f]*"#src="./current-scheduler.png"#' "$f" > "$out/$b.html" +done +python3 - "$out/index.html" <<'PY' +import sys, pathlib +rows = [("Round 1: current build and three directions", ["Current", "Main", "Studio", "Instrument"]), + ("Round 2: D and E (Scheduler)", ["Dark", "Revised"]), + ("Round 3: every tab in E's language", ["Sessions", "Diagnostics", "IoInspector", "Network", "Graph", "NodeEditor", "Library"])] +cards = [] +for title, names in rows: + cards.append(f'

{title}

') + for n in names: + cards.append(f'{n}') + cards.append('
') +html = '''Pantograph GUI mockups + +

Pantograph GUI mockups

Click a board to open it full size. Boards share one run context; Ctrl+C over a run copies its id, Ctrl+V over the chip views it.

''' + ''.join(cards) + '' +pathlib.Path(sys.argv[1]).write_text(html) +PY +echo "built in $out" +if [ "${1:-}" = "--serve" ]; then exec python3 -m http.server 8765 --directory "$out"; fi diff --git a/docs/design/mockups/viewer/cdp.js b/docs/design/mockups/viewer/cdp.js new file mode 100644 index 000000000..bc1d58323 --- /dev/null +++ b/docs/design/mockups/viewer/cdp.js @@ -0,0 +1,30 @@ +// Drives headless Chrome over the DevTools protocol with Node's built-in WebSocket. +// Usage: node cdp.js steps.json where steps is [{goto:url}|{eval:js}|{wait:ms}|{shot:file}] +const { spawn } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const CH = os.homedir() + '/.cache/ms-playwright/chromium_headless_shell-1246/chrome-headless-shell-linux64/chrome-headless-shell'; +const PORT = 9333; +const steps = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +(async () => { + const chrome = spawn(CH, ['--headless', '--disable-gpu', '--hide-scrollbars=false', '--remote-debugging-port=' + PORT, '--window-size=1440,900', '--user-data-dir=' + fs.mkdtempSync(os.tmpdir() + '/cdp-'), 'about:blank'], { stdio: 'ignore' }); + let targets = null; + for (let i = 0; i < 50 && !targets; i++) { await sleep(200); try { targets = await (await fetch('http://127.0.0.1:' + PORT + '/json')).json(); } catch (_) {} } + const page = targets.find((t) => t.type === 'page'); + const ws = new WebSocket(page.webSocketDebuggerUrl); + await new Promise((r) => (ws.onopen = r)); + let id = 0; const pending = new Map(); + ws.onmessage = (m) => { const d = JSON.parse(m.data); if (d.id && pending.has(d.id)) { pending.get(d.id)(d); pending.delete(d.id); } }; + const send = (method, params = {}) => new Promise((r) => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); }); + await send('Page.enable'); await send('Runtime.enable'); + await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }); + for (const s of steps) { + if (s.goto) { await send('Page.navigate', { url: s.goto }); await sleep(s.settle || 1200); } + else if (s.eval) { const r = await send('Runtime.evaluate', { expression: s.eval, awaitPromise: true, returnByValue: true }); if (r.result && r.result.exceptionDetails) console.log('eval error:', r.result.exceptionDetails.text, s.eval.slice(0, 80)); else if (s.log) console.log(s.log + ':', JSON.stringify(r.result.result.value)); await sleep(s.settle || 250); } + else if (s.wait) await sleep(s.wait); + else if (s.shot) { const r = await send('Page.captureScreenshot', { format: 'png' }); fs.writeFileSync(s.shot, Buffer.from(r.result.data, 'base64')); console.log('shot', s.shot); } + } + ws.close(); chrome.kill(); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/docs/design/mockups/viewer/current-scheduler.png b/docs/design/mockups/viewer/current-scheduler.png new file mode 100644 index 0000000000000000000000000000000000000000..054584ef8f70d8fade33fa5466e4b7bfd15d573b GIT binary patch literal 78281 zcmce;XFS|p_c!WF6VX!j5{Z)NT|y89(IcYwUIwGLF-Sp_5WN!-L>Z%wZuH*EXoKjz zn;FK;IR5t?*YmtM=X}na^USMX-M_V0+iQK-+7tFpU6K3_-5nw#B66j-Z{8CT-Fi(# zbbaIYwaY6cw7KI%M0bgl-pG9LN#B_xHyZO?B0hi;rYOZ=0DcBaL7I;)vd_MTy}yfN zd)_;kKgLx>3>sD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nlw%3M#e)i_+zT(3RosxM&Z_hTnJE!A@&F}j+t|rX< zUR#*=BI;rInWM~&v!9-un_GSRyNUIejq88?(mR`S#`?#ar4jJntgk(>?=;)-f2HB+}zhGz4Pem*>m360#9l$d%FR6gvZMI zf5l(!?c2Bhd2#W=16z{v!+vl4yLI~Y)A8SHzlB=Vt}gh0#_dVh^t*4XuiTPaS6><% zo;y!c|Id}}&z2>hTJ~&j_3h}g9a@hTy6kji+4t>e{`H8HXY-eBd_uJhKZ|VzQ_3!xde&3te?KS7^ z8-AIm0K5J+ldudv+cZ7g4LYi|;&Qs3h3(fP>AH_Bm%s*$vFs1Nm8`1(-buy~7X!T8 zBfo}8!xr260q7tIq4UY9vb7j7B08*%`}6N&22WQ%mvv4FO#r;x((?cS literal 0 HcmV?d00001 diff --git a/docs/design/mockups/viewer/support.js b/docs/design/mockups/viewer/support.js new file mode 100644 index 000000000..fb3cbcbf8 --- /dev/null +++ b/docs/design/mockups/viewer/support.js @@ -0,0 +1,169 @@ +/* Local stand-in for the Design canvas runtime. Renders templates: + {{path}} interpolation, , , onClick/onChange handlers, + data-props defaults with a small tweak panel. Enough to view the mockups offline. */ +(function () { + class DCLogic { + constructor(props) { this.props = props; this.state = {}; } + setState(patch) { Object.assign(this.state, patch); scheduleRender(); } + } + window.DCLogic = DCLogic; + + let component, template, mount, propsSpec, renderQueued = false; + + function lit(s) { + s = s.trim(); + if (s === 'true') return true; + if (s === 'false') return false; + if (s === 'null') return null; + if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s); + if (/^'.*'$/.test(s) || /^".*"$/.test(s)) return s.slice(1, -1); + return undefined; + } + function lookup(path, scope, vals) { + const l = lit(path); + if (l !== undefined) return l; + const parts = path.split('.'); + let cur = Object.prototype.hasOwnProperty.call(scope, parts[0]) ? scope[parts[0]] : vals[parts[0]]; + for (let i = 1; i < parts.length && cur != null; i++) cur = cur[parts[i]]; + return cur; + } + const RE_ONE = /^\s*\{\{\s*([^}]*?)\s*\}\}\s*$/; + const RE_ALL = /\{\{\s*([^}]*?)\s*\}\}/g; + function evalExpr(str, scope, vals) { + const m = str.match(RE_ONE); + if (m) return lookup(m[1], scope, vals); + return interp(str, scope, vals); + } + function interp(str, scope, vals) { + if (!str.includes('{{')) return str; + return str.replace(RE_ALL, (_, p) => { const v = lookup(p, scope, vals); return v == null ? '' : String(v); }); + } + function parseAttrs(s) { + const out = {}; const re = /([\w-]+)="([^"]*)"/g; let m; + while ((m = re.exec(s))) out[m[1]] = m[2]; + return out; + } + + function renderChildren(src, scope, vals) { return renderList(Array.from(src.childNodes), scope, vals); } + function renderList(kids, scope, vals) { + const out = []; let i = 0; + while (i < kids.length) { + const k = kids[i]; + if (k.nodeType === 8) { + const m = k.data.match(/^\s*sc-(for|if)\s+([\s\S]*)$/); + if (m) { + let depth = 1, j = i + 1; + for (; j < kids.length; j++) { + if (kids[j].nodeType !== 8) continue; + if (/^\s*sc-(for|if)\b/.test(kids[j].data)) depth++; + else if (/^\s*\/sc-(for|if)/.test(kids[j].data)) { depth--; if (depth === 0) break; } + } + const body = kids.slice(i + 1, j); const attrs = parseAttrs(m[2]); + if (m[1] === 'for') { + const list = evalExpr(attrs.list || '', scope, vals) || []; + list.forEach((item) => { const sc = Object.assign({}, scope); sc[attrs.as] = item; out.push(...renderList(body, sc, vals)); }); + } else if (evalExpr(attrs.value || '', scope, vals)) { + out.push(...renderList(body, scope, vals)); + } + i = j + 1; continue; + } + i++; continue; + } + out.push(...renderNode(k, scope, vals)); i++; + } + return out; + } + function renderNode(n, scope, vals) { + if (n.nodeType === 3) { const t = document.createTextNode(interp(n.data, scope, vals)); return [t]; } + if (n.nodeType !== 1) return []; + const el = n.cloneNode(false); + for (const a of Array.from(el.attributes)) { + if (a.name.startsWith('hint-')) { el.removeAttribute(a.name); continue; } + if (!a.value.includes('{{')) continue; + if (a.name.startsWith('on')) { + const fn = evalExpr(a.value, scope, vals); + el.removeAttribute(a.name); + if (typeof fn === 'function') el.addEventListener(a.name.slice(2), fn); + continue; + } + const v = evalExpr(a.value, scope, vals); + el.setAttribute(a.name, v == null ? '' : String(v)); + } + if (el.hasAttribute('aria-disabled') && el.getAttribute('aria-disabled') === 'true') el.style.opacity = '.5'; + renderChildren(n, scope, vals).forEach((c) => el.appendChild(c)); + if ((el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA') && n.hasAttribute('value')) { + const v = el.getAttribute('value'); if (v != null) requestAnimationFrame(() => { el.value = v; }); + } + return [el]; + } + + function scheduleRender() { if (renderQueued) return; renderQueued = true; requestAnimationFrame(render); } + function render() { + renderQueued = false; + const vals = component.renderVals(); + const nodes = renderChildren(template, {}, vals); + const ae = document.activeElement; const key = ae && ae.dataset ? ae.dataset.key : null; + const pos = key && 'selectionStart' in ae ? ae.selectionStart : null; + mount.replaceChildren(...nodes); + if (key) { const again = mount.querySelector('[data-key="' + key + '"]'); if (again) { again.focus(); if (pos != null) try { again.setSelectionRange(pos, pos); } catch (_) {} } } + else { const af = mount.querySelector('[data-autofocus]'); if (af && !component._afDone) { component._afDone = true; af.focus(); } if (!af) component._afDone = false; } + relink(mount); + } + const PAGES = { sessions: 'Sessions.html', scheduler: 'Revised.html', diagnostics: 'Diagnostics.html', io: 'IoInspector.html', network: 'Network.html', graph: 'Graph.html', nodes: 'NodeEditor.html', library: 'Library.html' }; + function relink(root) { + if (!/^https?:$/.test(location.protocol)) return; + root.querySelectorAll('a[href^="#"]').forEach((a) => { const page = PAGES[a.getAttribute('href').slice(1)]; if (page) a.setAttribute('href', page); }); + } + + function readProps(spec) { + const props = {}; const q = new URLSearchParams(location.search); + for (const [k, d] of Object.entries(spec)) { + if (k.startsWith('$')) continue; + let v = d.default; + if (q.has(k)) { const raw = q.get(k); v = d.editor === 'boolean' ? raw === 'true' || raw === '1' : raw; } + props[k] = v; + } + return props; + } + function tweakPanel(spec, props) { + const keys = Object.keys(spec).filter((k) => !k.startsWith('$')); + if (!keys.length) return; + const box = document.createElement('div'); + box.setAttribute('aria-label', 'Tweaks'); + box.style.cssText = 'position:fixed;right:10px;bottom:10px;z-index:9999;font:12px system-ui,sans-serif;color:#E4E6EA;background:rgba(35,39,45,.95);border:1px solid #4A5059;border-radius:4px;padding:6px 8px;display:flex;gap:10px;align-items:center;opacity:.35;transition:opacity .15s'; + box.onmouseenter = () => (box.style.opacity = '1'); box.onmouseleave = () => (box.style.opacity = '.35'); + const home = document.createElement('a'); home.href = './index.html'; home.textContent = 'All boards'; home.style.cssText = 'color:#D9B06A;text-decoration:none;margin-right:4px'; box.appendChild(home); + keys.forEach((k) => { + const d = spec[k]; const lab = document.createElement('label'); lab.style.cssText = 'display:inline-flex;gap:4px;align-items:center'; + lab.appendChild(document.createTextNode(k)); + let input; + if (d.editor === 'boolean') { input = document.createElement('input'); input.type = 'checkbox'; input.checked = !!props[k]; input.onchange = () => { props[k] = input.checked; scheduleRender(); }; } + else if (d.options || d.editor === 'enum') { input = document.createElement('select'); (d.options || []).forEach((o) => { const op = document.createElement('option'); op.value = o; op.textContent = o; op.selected = o === props[k]; input.appendChild(op); }); input.onchange = () => { props[k] = input.value; scheduleRender(); }; } + else { input = document.createElement('input'); input.type = d.editor === 'color' ? 'color' : 'text'; input.value = props[k]; input.onchange = () => { props[k] = input.value; scheduleRender(); }; } + input.style.cssText = 'font:inherit;background:#23272D;color:inherit;border:1px solid #4A5059;border-radius:3px;height:22px'; + lab.appendChild(input); box.appendChild(lab); + }); + document.body.appendChild(box); + } + + async function boot() { + const src = await (await fetch(location.href, { cache: 'no-store' })).text(); + const xm = src.match(/([\s\S]*?)<\/x-dc>/); + if (!xm) return; + let body = xm[1]; + const hm = body.match(/([\s\S]*?)<\/helmet>/); + if (hm) { body = body.replace(hm[0], ''); const h = document.createElement('div'); h.innerHTML = hm[1]; Array.from(h.childNodes).forEach((n) => document.head.appendChild(n)); } + body = body.replace(/]*)>/g, '').replace(/<\/sc-(for|if)>/g, ''); + template = document.createElement('div'); template.innerHTML = body; + const scriptEl = document.querySelector('script[data-dc-script]'); + propsSpec = JSON.parse(scriptEl.getAttribute('data-props') || '{}'); + const props = readProps(propsSpec); + const Component = new Function('DCLogic', scriptEl.textContent + '\nreturn Component;')(DCLogic); + component = new Component(props); + const old = document.querySelector('x-dc'); mount = document.createElement('div'); mount.id = 'app'; + if (old) old.replaceWith(mount); else document.body.prepend(mount); + render(); + tweakPanel(propsSpec, props); + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot(); +})(); diff --git a/docs/design/workbench-redesign-spec.md b/docs/design/workbench-redesign-spec.md new file mode 100644 index 000000000..63d537cd8 --- /dev/null +++ b/docs/design/workbench-redesign-spec.md @@ -0,0 +1,359 @@ +# Workbench redesign: implementation spec + +This is the design contract for porting the approved mockups in +`docs/design/mockups/` into the Svelte workbench. The mockups are the visual +authority; this document states the tokens, shared parts, behaviours and +page-by-page mapping so that pages built in parallel come out as one system. +The plan that sequences the work is `docs/plans/workbench-redesign/plan.md`. + +To view the mockups locally: `bash docs/design/mockups/viewer/build.sh --serve` +then open http://127.0.0.1:8765/. Boards `Revised` (Scheduler), `Sessions`, +`Diagnostics`, `IoInspector`, `Network`, `Graph`, `NodeEditor`, `Library` are +the targets. Boards `Main`, `Studio`, `Instrument`, `Dark` are earlier rounds +and are not targets. + +## Design principles (from the Calm Tech review) + +- One place for attention: the selected run is the context for every tab, shown + once in the header chip. Pages do not repeat it in their own headers. +- Status is carried by a small glyph vocabulary, never by pulsing motion, bright + LED-like colour, or uppercase tracked labels. +- Errors are explained in sentences with a suggested next action, inside the + panel they belong to, not in page-wide red banners. +- Filters are progressive: a search field, one status segment, and a `Filters` + disclosure. Applied secondary filters appear as removable chips. +- Lists are grouped under sticky collapsible headers and scroll inside their + panel; the page itself never scrolls. +- Destructive actions are two-step (`Cancel run` → `Confirm cancel`) and reset + after four seconds. +- Engine unavailability is shown in place: the header line changes and content + dims to 72% opacity; pages keep showing the last projection. + +## Tokens + +Define these as CSS custom properties on `:root` in `src/styles.css` and expose +them to Tailwind through `tailwind.config.cjs` (`theme.extend.colors` keyed to +`var(--…)`). Replace the current `!important` neutral overrides; the new +palette is the only palette. + +| Token | Value | Use | +| --- | --- | --- | +| `--pg-ground` | `#2A2E35` | page background | +| `--pg-panel` | `#33383F` | panels, cards | +| `--pg-panel-raised` | `#3A3F47` | hover rows | +| `--pg-panel-selected` | `#434A54` | selected row (plus 3px inset left bar `--pg-text`) | +| `--pg-panel-sunken` | `#23272D` | inputs, popovers, lane tracks, header bar | +| `--pg-panel-head` | `#2E333A` | group headers, panel footers, device lane strip | +| `--pg-border` | `#4A5059` | panel borders, dividers | +| `--pg-border-soft` | `#3B4048` | row separators | +| `--pg-border-strong` | `#8A909A` | hover borders, dimension lines | +| `--pg-text` | `#E4E6EA` | primary text | +| `--pg-text-bright` | `#FFFFFF` | titles, selected | +| `--pg-text-muted` | `#A3A9B4` | secondary text | +| `--pg-text-soft` | `#C9CDD4` | labels, mono ids | +| `--pg-accent` | `#D9B06A` | running state, focus ring, live wire (brass) | +| `--pg-danger` | `#E39A9A` | failed state, destructive text | +| `--pg-ok` | `#A7C4A0` | engine online dot | +| `--pg-info` | `#9FB7D9` | numbers in code views | + +Fonts: `Newsreader` (serif, titles and the brand word), `Atkinson Hyperlegible` +(UI text), `JetBrains Mono` (ids, timestamps, code). Bundle them through +`@fontsource/*` packages so the desktop app works offline; if the packages +cannot be installed, fall back to the system stacks `Georgia, serif`, +`system-ui, sans-serif`, `ui-monospace, monospace` and record the gap in +`issues.md`. Base size 14px, line height 1.45. Titles 24px/500 serif, page +subtitles 20px. + +Scrollbars: `scrollbar-width: thin; scrollbar-color: #5A6069 transparent` plus +the WebKit equivalents (10px, thumb `#5A6069` with a 2px `--pg-panel` border, +hover `#7A818C`). Apply globally. + +Focus: `outline: 2px solid var(--pg-accent); outline-offset: 1px` on every +focusable control via `:focus-visible`. + +## Status glyph vocabulary + +One component, `StatusGlyph`, 10px circle, 1.5px border: + +| State | Rendering | +| --- | --- | +| running | filled accent | +| waiting | left half accent (`linear-gradient(90deg, accent 50%, transparent 50%)`), accent border | +| queued / next / not reached | hollow, muted border | +| succeeded / done | filled muted | +| failed | filled danger, 1px radius, rotated 45° (a small diamond) | +| cancelled / skipped | hollow, dashed border | +| idle (no run) | hollow, soft border | +| warn (log level) | filled accent diamond | + +Map backend statuses: `accepted`, `future`, `scheduled`, `queued`, `delayed` +→ queued; `running` → running; `completed` → succeeded; `failed` → failed; +`cancelled` → cancelled. Node statuses map the same way; `Waiting` → waiting. + +## Shell + +`WorkbenchShell.svelte` becomes a top bar, 40px tall, background +`--pg-panel-sunken`, with a 1px `#1F2227` bottom border: + +``` +Pantograph | Sessions | │ | Scheduler Diagnostics I/O Inspector Network | │ | Graph Node Editor Library | … | [run chip ▾ ×] [■ Local engine] Settings [Assistant] +``` + +- Tabs are text, 13.5px, 11px horizontal padding, 2px bottom border on the + current tab (`--pg-text`), hover tint `rgba(255,255,255,.04)`. Keyboard + reachable, `aria-current="page"` on the active one. The lucide icon rail and + the "Active Run" label block are removed. +- Vertical dividers (1px, 18px tall) separate the three groups. Settings is + pinned to the right as a tab. The Assistant toggle keeps its existing + behaviour; style it as a `tgl` (26px, bordered). +- Engine line: a 7px square dot, `--pg-ok` when online, `--pg-danger` when the + transport reports unavailable, followed by "Local engine" or "Engine + unreachable since HH:MM, showing last projection" and a small Retry. +- The run-context picker (below) sits between the tabs and the engine line. + +Page ids gain `sessions`. Order: sessions, scheduler, diagnostics, io_inspector, +network, graph, node_lab, library, settings. Scheduler stays the default page. + +## Run-context picker + +The run chip in the header is the single control for the shared selection +(ADR-014: transient frontend state shared across pages). + +- Source of runs: the scheduler run-list projection (`schedulerRunListStore`, + fed by `workflowService.queryRunList`). The picker never queries the ledger. +- Chip when a run is selected: glyph, workflow id, version (`v1.4.0`, mono, + muted), `▾`; a separate `×` button clears the selection. Chip when none: + "Pick a run ▾" with a dashed border. +- Clicking the chip opens a popover (400px, anchored right) with a search field + (placeholder "Search runs, or paste a run id") and the grouped list: + Running, Waiting for memory, Queued, Finished today. Rows: glyph, workflow + id + version, one-line status context, run id in mono on the right. + Selecting a row sets the active run and closes the popover. Escape and an + outside click close it. Focus goes to the search field on open and returns + to the chip on close. +- Search matches workflow id, run id and version. If the typed or pasted text + equals a known run id, select it immediately. If it looks like a run id but + is unknown, show "No run with id … in today's history." +- Clipboard: while the pointer is over a run row in the Scheduler list, a + picker row, or any element that renders a run id with `data-run-id`, Ctrl+C + (or Cmd+C) copies the run id and shows a 1.6s toast "Copied run_…". While + the pointer is over the chip, Ctrl+V reads the clipboard and selects that + run if known, otherwise opens the popover with the text in the search field. + Clipboard permission failures fall back to opening the popover. Keystrokes + inside inputs are ignored. +- Pages with no run selected show an empty state centred in the page: a short + serif question ("Which run do you want to look into?"), one sentence, and a + primary "Pick a run" button that opens the popover. + +## Shared parts (`src/components/workbench/ui/`) + +Build these once; pages compose them. Names are suggestions, the behaviour is +the contract. + +- `DimensionLine`: a 1px rule with tick ends and a centred mono label on the + page background. Used as the page summary line under the header. +- `Panel`: `--pg-panel` background, `--pg-border` border, 4px radius; a column + variant with a fixed top (`ptop`), scrolling middle (`scroll`) and fixed + footer (`pfoot`, `--pg-panel-head` background, 48px min height). +- `GroupHeader`: sticky, collapsible, label + mono count + chevron, `aria-expanded`. +- `ListRow`: grid `14px 1fr auto`, glyph, name (bold) + mono version, two + muted sub-lines, time on the right; `aria-current="true"` when selected. +- `SegmentedControl`: bordered group, each button with a label and mono count, + `aria-pressed` on the active one; wraps instead of clipping. +- `FilterChip`: pill with a `×` button; `Chip`: static pill. +- `DeviceLanes`: per device, name + "x of y GB in use" and a track of blocks + whose widths are proportional to GB: running (accent fill), waiting (accent + hatch), next (hollow), free (empty). Legend to the right. +- `KeyValue`: two-column grid of muted keys and values. +- `LogLine`: grid `96px 14px 1fr`, mono timestamp, level glyph, message with a + bold kind and a muted source suffix. Error lines get a 6% danger tint. +- `ErrorCard`: left 3px danger bar, bold title, muted code line, one sentence + of explanation, one sentence starting "Try:", and an action button. +- `TwoStepButton`: `danger` → `confirm` with a 4s reset. +- `EmptyState`: the centred question + sentence + primary button. +- `Toast`: fixed bottom centre, mono, 1.6s. + +## Pages + +Each page keeps its presenters and service calls. What changes is the +projection into the new layout. Every page: dimension line first, then the +two-panel inbox layout (fixed-width list left, detail right) unless noted. + +### Scheduler (`Revised` board) + +- Dimension line: "N runs waiting, about M min of queued work on D devices" + from the scheduler estimate projection; omit the minutes when no estimate. +- Device lanes strip (collapsible via a `showLanes` preference) from the + local Network status projection where device memory is available; hide the + strip when the projection has no device facts. +- Left panel 380px: search, status segment (All, Active, Queued, Done, Failed + with counts), `Filters` disclosure holding the remaining 11 selects from the + current page in a two-column grid, applied-filter chips, then the grouped + list (Running, Waiting for memory, Queued, Finished today). Footer: `Move to + front`, `Priority` number input, two-step `Cancel run` for live runs; "has + finished. No actions available." for finished ones; "Select a run to act on + it. The other tabs follow this selection." when none. +- Right panel: title (workflow id, version), run id (copyable), status chip + plus placement/priority/queue chips, buttons Diagnostics / Graph / I/O that + switch tabs; three cells Progress, Placement, Retention; then the scheduler + timeline (`querySchedulerTimeline`) as a time/event grid with the sentence + "Node-level events for this run are in Diagnostics." +- Selecting a row sets the active run (same store as the chip). + +### Diagnostics (`Diagnostics` board) + +- Dimension line: "run_id, failed 19:35:42 after 22 s, 1 error in load_model" + style sentence from run detail. +- Left panel 300px: title, run id, chips (status, placement, client/session); + Timing and Placement key-value sections; collapsible "Nodes by status" with + thin bars; collapsible "Compared with earlier runs" using the comparison + facets (two big serif numbers and a sentence); Projection freshness line. +- Right panel: level segment (All, Warnings, Errors with counts), source + segment (All sources, Scheduler, Runtime, Nodes), search, Follow toggle; + the ErrorCard when the run has a terminal error, with "Show in log" which + switches the level filter to Errors; then the timeline as LogLines; a + footer sentence "N of M events shown. Payload bodies for this run are in + I/O Inspector." +- The existing `diagnosticsFocus` behaviour (deep link to an event) is kept: + the focused event line gets the selected row treatment and is scrolled into + view. + +### I/O Inspector (`IoInspector` board) + +- Dimension line: "run_id, N nodes, M retained artifacts, X MB kept for 7 days". +- Left panel 340px: search, direction segment (All, Inputs, Outputs); a tree of + nodes (glyph, node id, mono type, "N retained ports") each expandable to its + artifacts ("→ port" for outputs, "← port" for inputs, size, kind and + retention). Footer: "Payloads kept 7 days. Retention settings" linking to + Settings as today. +- Right panel: title `node:port`, artifact id, chips (role, kind, retention, + media + size); buttons Read body / Download / Acknowledge with the existing + semantics; the preview region (image, text/JSON in a code block, or the + "Only metadata was kept for this port." panel); sections "Where it came + from", "How it was made", "Storage" from the artifact descriptor fields. +- The compact run graph strip is removed from this page; Graph owns graphs. +- Saved-graph mode (no run) becomes the empty state with "Pick a run". + +### Network (`Network` board) + +- Dimension line: "N nodes, c connected, d degraded, p waiting to be paired. + G GPUs, V GB VRAM reachable" from local status plus peers; omit parts that + the projection does not provide. +- Left panel 340px: segment (All nodes, Shared with me, Mine), groups Local + and Peers with rows (glyph by transport state, display name, node id, + two sub-lines, latency on the right). Footer "Pair a node" (disabled with + a title until pairing exists) and "Trusted peers only". +- Right panel: title, OS and captured time, chips; four stat cells (CPU with + meter, memory with meter, running/queued, runtime sessions); Devices as + DeviceLanes; the selected run's placement on this node (" on this + node": run id, state, runtime session, assets read) or a sentence that the + run is placed elsewhere; Disks and Interfaces as small tables; Identity. +- Degraded metrics render as muted text in their section, not an amber list. + +### Graph (`Graph` board) + +- Toolbar row (no dimension line of its own; the dimension line sits in the + toolbar between the status text and the panel toggles): a two-way mode + switch `Edit workflow` / `As run `; the workflow selector + (bold name, mono version, popover of saved workflows with "Picking a + workflow switches to editing it…" footer); "Saved HH:MM" or "Unsaved + changes" in edit mode, "read-only, as it ran" in run mode; `Nodes` and + `Properties` panel toggles; Save, Version input, `+patch`, `Submit run` in + edit mode; `Edit current vX` and `Save as new workflow` in run mode. +- Edit mode is the current editor (SvelteFlow canvas, palette, properties) + restyled: palette as a tree with category counts and `in:out` port counts, + dotted canvas background, node cards with the glyph in the header, a + bottom-left zoom/fit/snap pill group, minimap bottom right. +- Run mode renders the run graph projection in an isolated read-only surface + (ADR-014): node glyphs from node status, the live wire in accent, failed + wires dashed danger, a legend top right, and the properties panel showing + values "as they were when the run started" plus an "In this run" section + with I/O and Diagnostics buttons. Entering run mode never touches the + editable graph store. +- If the selected run belongs to a different workflow than the one being + edited, a one-line note offers "Show as run" or keeps editing. +- Submit disabled reasons stay as today but render as the button's title and + a muted sentence under the toolbar, not a banner. + +### Node Editor (`NodeEditor` board) + +Node authoring has no backend in this build. Keep the capability represented +at its owning boundary: the page shows the built-in node definitions read-only +(list left with "Built-in" group, definition form centre with inputs/outputs +tables and an implementation block reading "built-in, source not editable", +live canvas preview and Checks right). Authoring controls (`New node`, `Add +input`, `Save draft`, `Publish to runtime`, `Try with sample inputs`) render +with `aria-disabled` and a title, and the page opens with the in-place notice +"Node authoring is not available in this build…" naming Settings as the place +where it would be enabled. Do not advertise saving or publishing as working. +The "Your nodes" group is omitted until a definition store exists. + +### Library (`Library` board) + +- Dimension line: "N models, X GB on disk, L loaded on devices, U unused for + 30 days (Y GB)". Omit facts the projection lacks. +- Left panel 400px: search + `Find on Hugging Face` toggle, kind segment + (All, Text, Image, Audio) when the model kind is known; groups "Loaded on a + device", "On disk, used this month", "On disk, unused 30 days"; rows with + two cache squares (accent = loaded on that device, grey = disk only), name, + family, usage sub-line, size and last-used on the right. Footer legend and + free disk space. +- Search mode replaces the list with Hugging Face results (mono repo id, + sub-line, size, Download button that reads "Queued" once requested) using + the existing search/download service calls. +- Right panel: title, pumas id, chips; `Use in a new graph` (disabled until + supported), `Open folder` (disabled until supported), two-step `Delete from + disk` blocked with a title while a run uses the model; sections "Where it + lives", "How it is used", "Workflows that use it" (table from usage + projection), "Source". + +### Sessions (new, `Sessions` board) + +Sessions are a new tab over existing authority only: + +- Active: the client sessions the attribution projection exposes (this GUI + window's session, CLI sessions) with their runs. If no service lists client + sessions, show only the current window's session derived from the run list + (runs whose client session matches) and record the gap in `issues.md`. +- Saved: the saved workflows (`list_workflows`) and orchestrations, each shown + as a session card with created/modified dates and the runs of that workflow + from the run list. +- Rows: glyph (running if any live run, succeeded if active and idle, idle if + saved), name, client tag, sub-line, a thin outcome strip (accent running, + grey succeeded, danger failed, hollow queued), run count and last activity. +- Detail: title, id, chips; Activity and "Runs from this session" key-value + sections with "Show in Scheduler" (switches tab and applies the session + filter); "Open in this session" list with Open graph buttons (loads the + saved workflow into Graph edit mode); "What resumes" sentence. +- Actions: `Rename`, `Save a copy`, `Close session`, `Resume`, `Delete` only + where a service exists. Others render `aria-disabled` with a title. Do not + invent persistence. + +### Settings + +Not redesigned in this effort. It must still look right under the new tokens: +remove its dependence on the old `bg-neutral-*` overrides and use the shared +`Panel`, `KeyValue` and field styles for its existing sections. + +## Accessibility contract (selected for this change) + +Supported users operate the desktop app with pointer and keyboard; screen +reader semantics are preserved through native elements. Every control is a +`button`, `a`, `input`, `select` or `textarea` with a visible or hidden name. +Lists of selectable rows are buttons with `aria-current`. Toggles use +`aria-pressed`, disclosure uses `aria-expanded`, the picker popover is a +`role="dialog"` with a label, the log is `role="log"`. Decorative glyphs are +`aria-hidden` and the status is also in text. Focus is visible (accent +outline) and never depends on colour alone. `scripts/check-svelte-a11y.mjs` +must pass on every changed file. + +## Evidence + +- Deterministic: presenter and store tests under `src/**/*.test.ts` + (`npm run test:frontend`), `npm run typecheck`, `npm run lint:a11y`, + `npm run lint:critical`, `npx eslint --max-warnings 0`. +- Representative browser: `npx vite build` then a headless Chromium walkthrough + with `docs/design/mockups/viewer/cdp.js` against the built site, capturing a + screenshot per page with mocked services where a live engine is absent. +- Real desktop: `npm run dev:desktop` by the owner, checking each tab with the + local engine running. Recorded as manual evidence in the ledger. From cc2260d7647eba895f67c315ab198ff691825550 Mon Sep 17 00:00:00 2001 From: MrScripty Date: Tue, 3 Nov 2026 06:31:20 -0700 Subject: [PATCH 07/15] feat(workbench): replace the workbench GUI with the calm redesign Top-tab shell with a shared run-context picker (grouped, searchable run list; Ctrl+C over a run copies its id, Ctrl+V over the chip views it), design tokens with bundled fonts, themed scrollbars and focus rings, and fifteen shared parts (status glyph vocabulary, dimension line, panels, grouped lists, segmented controls, chips, log lines, error cards, two-step buttons, empty states). Every tab is rebuilt on its existing projection services: Scheduler (one run-list owner, grouped inbox list, progressive filters, two-step cancel), Diagnostics (run facts, filterable event log, explained error card, deep link kept), I/O Inspector (node and port tree, one artifact card, saved workflow inspection kept; fixes the pre-existing a11y and append/remove findings), Network (local node and peers, honest degraded text), Graph (Edit workflow and As run modes; run mode is the isolated read-only run graph per ADR-014), Node Editor (built-in definitions read-only with authoring controls disabled at the boundary), Library (usage-joined model list, Hugging Face search mode, two-step delete), and a new Sessions tab over saved workflows and orchestrations. Settings and its embedded panels and the graph node, edge and minimap components are restyled without behaviour change. Also: PumasHfModelSearchResult now mirrors its producer (Pumas HuggingFaceModel, camelCase); the Settings retention deep link targets the retention form; a Library delete confirmation no longer carries over to a different model; the last !important style overrides are removed. Plan: docs/plans/workbench-redesign/plan.md (ADR-014). Co-Authored-By: Claude Fable 5.1 --- index.html | 4 +- package-lock.json | 30 + package.json | 3 + packages/svelte-graph/src/README.md | 90 + .../svelte-graph/src/components/README.md | 79 + .../src/components/WorkflowGraph.css | 10 +- .../src/workflowGraphEdgeOptions.test.ts | 1 - .../src/workflowGraphEdgeOptions.ts | 1 - .../src/workflowGraphViewport.test.ts | 2 +- .../svelte-graph/src/workflowGraphViewport.ts | 2 +- src/README.md | 112 + src/components/BackendSelector.svelte | 30 +- src/components/DeviceConfig.svelte | 204 +- src/components/GraphSelector.svelte | 179 -- src/components/ModelConfig.svelte | 261 ++- src/components/NodeGroupEditor.svelte | 1 + src/components/NodePalette.svelte | 257 ++- src/components/README.md | 99 + src/components/RagStatus.svelte | 295 ++- src/components/SandboxSettings.svelte | 141 +- src/components/ServerStatus.svelte | 87 +- src/components/WorkflowGraph.css | 141 +- src/components/WorkflowGraphCanvas.svelte | 1 + .../WorkflowPersistenceControls.svelte | 437 +++- src/components/WorkflowToolbar.svelte | 292 ++- src/components/edges/README.md | 72 + src/components/edges/ReconnectableEdge.svelte | 97 +- src/components/nodes/BaseNode.svelte | 204 +- src/components/nodes/README.md | 96 + .../nodes/workflow/AgentToolsNode.svelte | 27 +- .../nodes/workflow/AudioInputNode.svelte | 40 +- .../nodes/workflow/AudioOutputNode.svelte | 74 +- .../nodes/workflow/BooleanInputNode.svelte | 35 +- .../DependencyEnvironmentActivityLog.svelte | 12 +- .../DependencyEnvironmentBindingsPanel.svelte | 62 +- .../DependencyEnvironmentModeControls.svelte | 10 +- .../workflow/DependencyEnvironmentNode.svelte | 11 - .../DependencyEnvironmentNodeHeader.svelte | 16 +- .../DependencyEnvironmentRefPanel.svelte | 8 +- .../DependencyEnvironmentStatusPanel.svelte | 15 +- .../nodes/workflow/EmbeddingNode.svelte | 30 +- .../nodes/workflow/GenericNode.svelte | 48 +- .../nodes/workflow/ImageOutputNode.svelte | 83 +- .../nodes/workflow/LLMInferenceNode.svelte | 88 +- .../nodes/workflow/LinkedInputNode.svelte | 49 +- .../nodes/workflow/MaskedTextInputNode.svelte | 84 +- .../nodes/workflow/ModelProviderNode.svelte | 31 +- .../nodes/workflow/NodeGroupNode.svelte | 97 +- .../nodes/workflow/NodeHeaderTitle.svelte | 28 + .../nodes/workflow/NumberInputNode.svelte | 37 +- .../workflow/PointCloudOutputNode.svelte | 61 +- .../nodes/workflow/PumaLibNode.svelte | 48 +- src/components/nodes/workflow/README.md | 96 + .../nodes/workflow/SelectionInputNode.svelte | 41 +- .../nodes/workflow/TextInputNode.svelte | 60 +- .../nodes/workflow/TextOutputNode.svelte | 34 +- .../nodes/workflow/VectorInputNode.svelte | 27 +- .../nodes/workflow/VectorOutputNode.svelte | 37 +- .../ManagedBinaryOverviewPanel.svelte | 73 +- .../ManagedRuntimeActivityPanel.svelte | 30 +- .../runtime-manager/ManagedRuntimeCard.svelte | 10 +- .../ManagedRuntimeCatalogPanel.svelte | 265 ++- .../ManagedRuntimeHeader.svelte | 26 +- .../ManagedRuntimeJobPanel.svelte | 45 +- .../ManagedRuntimePanel.svelte | 38 +- .../ManagedRuntimeSummaryGrid.svelte | 54 +- src/components/runtime-manager/README.md | 98 + .../managedRuntimePresenters.test.ts | 43 + .../managedRuntimePresenters.ts | 65 + .../BackendCapabilityBadges.svelte | 14 +- .../server-status/BackendOptionList.svelte | 21 +- .../server-status/ConnectionModeTabs.svelte | 37 +- .../ExternalConnectionPanel.svelte | 48 +- .../server-status/HealthStatusPanel.svelte | 90 +- src/components/server-status/README.md | 90 + .../server-status/RuntimeSnapshotGrid.svelte | 115 +- .../serverStatusPresenters.test.ts | 20 + .../server-status/serverStatusPresenters.ts | 32 + .../workbench/DiagnosticsPage.svelte | 1592 +++++++-------- src/components/workbench/GraphPage.svelte | 682 ++++++- .../workbench/IoInspectorPage.svelte | 1569 ++++++++------ src/components/workbench/LibraryPage.svelte | 1074 +++++++--- src/components/workbench/NetworkPage.svelte | 1008 +++++---- src/components/workbench/NodeLabPage.svelte | 649 +++++- src/components/workbench/README.md | 108 + .../workbench/RunGraphSnapshot.svelte | 738 +++---- .../SavedGraphInspectionSnapshot.svelte | 324 +-- src/components/workbench/SchedulerPage.svelte | 1798 ++++++++--------- src/components/workbench/SessionsPage.svelte | 632 ++++++ src/components/workbench/SettingsPage.svelte | 900 ++++----- .../workbench/WorkbenchShell.svelte | 341 +++- .../diagnosticsPagePresenters.test.ts | 483 ++++- .../workbench/diagnosticsPagePresenters.ts | 1034 +++++++++- .../graphInspectionPresenters.test.ts | 133 ++ .../workbench/graphInspectionPresenters.ts | 209 ++ .../workbench/ioInspectorPresenters.test.ts | 355 ++++ .../workbench/ioInspectorPresenters.ts | 667 ++++++ .../workbench/libraryUsagePresenters.test.ts | 312 +++ .../workbench/libraryUsagePresenters.ts | 556 +++++ .../workbench/networkPagePresenters.test.ts | 457 +++-- .../workbench/networkPagePresenters.ts | 748 +++++-- .../workbench/nodeLabPresenters.test.ts | 203 +- src/components/workbench/nodeLabPresenters.ts | 305 ++- .../workbench/runGraphPresenters.test.ts | 380 ++-- .../workbench/runGraphPresenters.ts | 848 +++++--- .../workbench/schedulerPagePresenters.test.ts | 527 +++-- .../workbench/schedulerPagePresenters.ts | 656 ++++-- .../workbench/sessionsPresenters.test.ts | 377 ++++ .../workbench/sessionsPresenters.ts | 800 ++++++++ .../workbench/settingsPagePresenters.test.ts | 91 +- .../workbench/settingsPagePresenters.ts | 168 +- src/components/workbench/shell/README.md | 102 + .../workbench/shell/RunContextPicker.svelte | 457 +++++ .../shell/runContextClipboard.test.ts | 227 +++ .../workbench/shell/runContextClipboard.ts | 207 ++ .../workbench/shell/runContextPicker.test.ts | 203 ++ .../workbench/shell/runContextPicker.ts | 359 ++++ .../workbench/shell/runContextRunList.test.ts | 174 ++ .../workbench/shell/runContextRunList.ts | 144 ++ .../workbench/shell/runContextStore.ts | 133 ++ src/components/workbench/ui/Chip.svelte | 19 + .../workbench/ui/DeviceLanes.svelte | 86 + .../workbench/ui/DimensionLine.svelte | 14 + src/components/workbench/ui/EmptyState.svelte | 59 + src/components/workbench/ui/ErrorCard.svelte | 57 + src/components/workbench/ui/FilterChip.svelte | 14 + .../workbench/ui/GroupHeader.svelte | 24 + src/components/workbench/ui/KeyValue.svelte | 18 + src/components/workbench/ui/ListRow.svelte | 79 + src/components/workbench/ui/LogLine.svelte | 34 + src/components/workbench/ui/Panel.svelte | 58 + src/components/workbench/ui/README.md | 117 ++ .../workbench/ui/SegmentedControl.svelte | 42 + .../workbench/ui/StatusGlyph.svelte | 22 + src/components/workbench/ui/Toast.svelte | 11 + .../workbench/ui/TwoStepButton.svelte | 64 + src/components/workbench/ui/index.ts | 32 + .../workbench/ui/statusGlyph.test.ts | 50 + src/components/workbench/ui/statusGlyph.ts | 102 + src/components/workbench/ui/types.ts | 42 + src/components/workflowMiniMap.test.ts | 31 +- src/components/workflowMiniMap.ts | 26 +- src/services/diagnostics/README.md | 79 + src/services/diagnostics/types.ts | 22 +- src/stores/README.md | 84 + src/stores/schedulerRunListStore.test.ts | 64 +- src/stores/schedulerRunListStore.ts | 141 +- src/stores/workbenchStore.test.ts | 43 +- src/stores/workbenchStore.ts | 36 +- src/styles.css | 1000 ++++++++- tailwind.config.cjs | 57 +- 151 files changed, 22846 insertions(+), 8142 deletions(-) create mode 100644 packages/svelte-graph/src/README.md create mode 100644 packages/svelte-graph/src/components/README.md create mode 100644 src/README.md delete mode 100644 src/components/GraphSelector.svelte create mode 100644 src/components/README.md create mode 100644 src/components/edges/README.md create mode 100644 src/components/nodes/README.md create mode 100644 src/components/nodes/workflow/NodeHeaderTitle.svelte create mode 100644 src/components/nodes/workflow/README.md create mode 100644 src/components/runtime-manager/README.md create mode 100644 src/components/runtime-manager/managedRuntimePresenters.test.ts create mode 100644 src/components/runtime-manager/managedRuntimePresenters.ts create mode 100644 src/components/server-status/README.md create mode 100644 src/components/server-status/serverStatusPresenters.test.ts create mode 100644 src/components/server-status/serverStatusPresenters.ts create mode 100644 src/components/workbench/README.md create mode 100644 src/components/workbench/SessionsPage.svelte create mode 100644 src/components/workbench/sessionsPresenters.test.ts create mode 100644 src/components/workbench/sessionsPresenters.ts create mode 100644 src/components/workbench/shell/README.md create mode 100644 src/components/workbench/shell/RunContextPicker.svelte create mode 100644 src/components/workbench/shell/runContextClipboard.test.ts create mode 100644 src/components/workbench/shell/runContextClipboard.ts create mode 100644 src/components/workbench/shell/runContextPicker.test.ts create mode 100644 src/components/workbench/shell/runContextPicker.ts create mode 100644 src/components/workbench/shell/runContextRunList.test.ts create mode 100644 src/components/workbench/shell/runContextRunList.ts create mode 100644 src/components/workbench/shell/runContextStore.ts create mode 100644 src/components/workbench/ui/Chip.svelte create mode 100644 src/components/workbench/ui/DeviceLanes.svelte create mode 100644 src/components/workbench/ui/DimensionLine.svelte create mode 100644 src/components/workbench/ui/EmptyState.svelte create mode 100644 src/components/workbench/ui/ErrorCard.svelte create mode 100644 src/components/workbench/ui/FilterChip.svelte create mode 100644 src/components/workbench/ui/GroupHeader.svelte create mode 100644 src/components/workbench/ui/KeyValue.svelte create mode 100644 src/components/workbench/ui/ListRow.svelte create mode 100644 src/components/workbench/ui/LogLine.svelte create mode 100644 src/components/workbench/ui/Panel.svelte create mode 100644 src/components/workbench/ui/README.md create mode 100644 src/components/workbench/ui/SegmentedControl.svelte create mode 100644 src/components/workbench/ui/StatusGlyph.svelte create mode 100644 src/components/workbench/ui/Toast.svelte create mode 100644 src/components/workbench/ui/TwoStepButton.svelte create mode 100644 src/components/workbench/ui/index.ts create mode 100644 src/components/workbench/ui/statusGlyph.test.ts create mode 100644 src/components/workbench/ui/statusGlyph.ts create mode 100644 src/components/workbench/ui/types.ts create mode 100644 src/services/diagnostics/README.md create mode 100644 src/stores/README.md diff --git a/index.html b/index.html index 8235c3ddc..4565f18b0 100644 --- a/index.html +++ b/index.html @@ -4,9 +4,9 @@ - Zenith Draw + Pantograph - +
diff --git a/package-lock.json b/package-lock.json index 61ac3ad64..5cee92db0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,9 @@ "packages/*" ], "dependencies": { + "@fontsource/atkinson-hyperlegible": "^5.3.0", + "@fontsource/jetbrains-mono": "^5.3.0", + "@fontsource/newsreader": "^5.3.0", "@tauri-apps/api": "^2.9.0", "@tauri-apps/plugin-dialog": "^2.6.0", "@tiptap/core": "^3.15.3", @@ -693,6 +696,33 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@fontsource/atkinson-hyperlegible": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/atkinson-hyperlegible/-/atkinson-hyperlegible-5.3.0.tgz", + "integrity": "sha512-Sp8Ve8+rQmENY2Lv02VH7sLpntzTTvnncnJMTbRE7DX6TLxGraN4ykZfzaUWIoCFmaomwkvNiqmlPkrKBuDoSA==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/jetbrains-mono": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz", + "integrity": "sha512-fqDfB5I9f1p1TV486aUgB9t8zP84P0O1FtQR5Ol9vjwPy+S+EIGlVYm1cvj2W5shcZMTg2nZFdVMoH5wFu8a1A==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/newsreader": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/newsreader/-/newsreader-5.3.0.tgz", + "integrity": "sha512-AFR6ZKY89GNL+9qBI2P2+66NhD5bhOj/v6fsLnFYLM4E0JnMB1yKb+Ro8cA64i1hwAWoBfTq5CHJGWH1toLDkw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", diff --git a/package.json b/package.json index 49032ab1e..833844391 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,9 @@ "hooks:install": "npx lefthook install" }, "dependencies": { + "@fontsource/atkinson-hyperlegible": "^5.3.0", + "@fontsource/jetbrains-mono": "^5.3.0", + "@fontsource/newsreader": "^5.3.0", "@tauri-apps/api": "^2.9.0", "@tauri-apps/plugin-dialog": "^2.6.0", "@tiptap/core": "^3.15.3", diff --git a/packages/svelte-graph/src/README.md b/packages/svelte-graph/src/README.md new file mode 100644 index 000000000..4d4c00ad2 --- /dev/null +++ b/packages/svelte-graph/src/README.md @@ -0,0 +1,90 @@ +# @pantograph/svelte-graph source + +## Purpose + +Source of the reusable graph editor package (see `../README.md` for the +package and dependency ownership). It holds the editor components, the +graph-context stores and the pure interaction helpers that both this package's +`WorkflowGraph` and the app's `src/components/WorkflowGraphCanvas.svelte` use. + +## Contents + +| Path | Responsibility | +| --- | --- | +| `index.ts` | Public exports of the package. | +| `components/` | Package editor components (`WorkflowGraph`, palette, toolbar, group editor, horseshoe selector, default node and edge components). | +| `stores/` | Session, view and workflow store factories and their pure graph queries. | +| `context/` | Graph context creation and lookup. | +| `backends/` | `MockWorkflowBackend` for tests and demos. | +| `types/`, `constants/`, `utils/` | Shared types, port colours, registry building and geometry. | +| `workflowGraphViewport.ts`, `workflowGraphEdgeOptions.ts` | SvelteFlow canvas constants shared by every editor mount (zoom limits, fit options, minimap mask colour, default edge options). | +| `workflow*.ts`, `horseshoe*.ts`, `connectionDragState.ts`, `cutInteraction.ts`, `reconnectInteraction.ts`, `portTypeCompatibility.ts`, `graphRevision.ts`, `paletteDragState.ts` + tests | Pure interaction and synchronisation helpers. | + +## Problem + +The Pantograph app and the package each mount SvelteFlow; canvas defaults +(zoom, fit, minimap, default edge options) must agree or the two editors +behave differently, and literal colours in those defaults override the app's +token styling. + +## Constraints + +- Constants are plain values passed as SvelteFlow props; the app styles the + canvas through the `--xy-*` CSS variables in + `src/components/WorkflowGraph.css`. +- A colour passed as a prop (for example `maskColor`) wins over the CSS + variable, so it must match the workbench token it stands for. +- Package tests run under the root `npm run test:frontend`. + +## Decision + +`WORKFLOW_GRAPH_MINIMAP_MASK_COLOR` is the workbench sunken panel at 60% +(`rgba(35, 39, 45, 0.6)`, `--pg-panel-sunken`). `WORKFLOW_GRAPH_DEFAULT_EDGE_OPTIONS` +carries no inline `style`, so edge colour follows `--xy-edge-stroke` and the +edge component's own styles. + +## Alternatives Rejected + +- Keeping a literal edge stroke in the default options: it bypassed the + canvas variables and the app's edge component ignored it anyway. +- Moving the constants into the app: the package's own `WorkflowGraph` mounts + SvelteFlow with the same values. + +## Invariants + +- Viewport and edge-option constants are shared, not copied; their tests pin + the values. +- No literal colour in a shared constant unless SvelteFlow requires a prop + value, and then it names the token it mirrors. + +## Revisit Triggers + +- The app stops passing `maskColor`, so the CSS variable can own the mask. +- The package gains its own theme tokens. + +## Dependencies + +**Internal:** consumed by `src/components/WorkflowGraphCanvas.svelte`, +`src/registry/pantographNodeTypes.ts` and the app stores. + +**External:** `svelte`, `@xyflow/svelte` (peer dependencies). + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```svelte + + + + + +``` diff --git a/packages/svelte-graph/src/components/README.md b/packages/svelte-graph/src/components/README.md new file mode 100644 index 000000000..a2fc1b6e2 --- /dev/null +++ b/packages/svelte-graph/src/components/README.md @@ -0,0 +1,79 @@ +# Graph editor components + +## Purpose + +Reusable Svelte components of the `@pantograph/svelte-graph` package: the +SvelteFlow-based workflow editor (`WorkflowGraph.svelte`), its toolbar, +palette, breadcrumb, group editor, cut tool, horseshoe insert selector and +the package's default node and edge components. + +## Contents + +- `WorkflowGraph.svelte` and `WorkflowGraph.css`: the editor surface and its + base stylesheet. The stylesheet is bundled into any app that imports the + editor, so its colour rules read the host's `--pg-*` tokens with the + package's original values as fallbacks. +- `WorkflowToolbar.svelte`, `NodePalette.svelte`, `NavigationBreadcrumb.svelte`, + `NodeGroupEditor.svelte`, `GroupPortMapper.svelte`, `ContainerBorder.svelte`, + `ZoomTransition.svelte`, `CutTool.svelte`, `WorkflowGraphHorseshoeLayer.svelte`, + `HorseshoeInsertSelector.svelte`, `WorkflowRunButton.svelte`. +- `nodes/`, `edges/`: the package's default node and edge components. The + Pantograph app mounts its own copies under `src/components/nodes` and + `src/components/edges`. +- `workflowGraphBackendActions.ts`: backend-facing actions the toolbar calls. + +## Problem + +The app's workbench redesign themes the editor through CSS custom properties, +but this package's stylesheet carried literal colours that painted over the +app's tokens (minimap ground, connecting-handle glow). + +## Constraints + +- The package stays host-agnostic: it must render without the host's tokens. +- Layout-affecting rules (node geometry, handle positions) do not change. + +## Decision + +Colour rules in `WorkflowGraph.css` use `var(--pg-…, )` so +a themed host overrides them and an unthemed host keeps the old appearance. +The heading set of this file is required by +`scripts/check-decision-traceability.sh` (plan issue WR-001). + +## Alternatives Rejected + +- Scoping the stylesheet under a host class: would require every consumer to + add the class and still leaves literal colours in the package. +- Removing the stylesheet from the package: breaks unthemed consumers. + +## Invariants + +- `WorkflowGraph.css` sets no node geometry that the app's node components + depend on; geometry lives in the node components. +- No rule in this directory uses the app's accent for anything but + connecting or live state. + +## Revisit Triggers + +- The host stops mounting its own node and edge copies (then the package's + `nodes/` and `edges/` need the token treatment too; plan issue WR-064). +- The package publishes independently and needs a documented theming API. + +## Dependencies + +- `@xyflow/svelte` for the canvas, minimap and controls. +- The host's `--pg-*` tokens are optional inputs. + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` (run-mode + graphs render in an isolated read-only surface, not through this editor). + +## Usage Examples + +```svelte + + +``` diff --git a/packages/svelte-graph/src/components/WorkflowGraph.css b/packages/svelte-graph/src/components/WorkflowGraph.css index 22f501040..f84b130b2 100644 --- a/packages/svelte-graph/src/components/WorkflowGraph.css +++ b/packages/svelte-graph/src/components/WorkflowGraph.css @@ -25,7 +25,7 @@ .svelte-flow__controls { background-color: #262626; - border: 1px solid #404040; + border: 1px solid var(--pg-border, #404040); border-radius: 8px; } @@ -40,8 +40,8 @@ } .svelte-flow__minimap { - background-color: #171717; - border: 1px solid #404040; + background-color: var(--pg-panel-sunken, #171717); + border: 1px solid var(--pg-border, #404040); border-radius: 8px; } @@ -56,8 +56,8 @@ } .svelte-flow__handle.connecting { - background: #60a5fa !important; - box-shadow: 0 0 10px rgba(96, 165, 250, 0.8); + background: var(--pg-accent, #60a5fa) !important; + box-shadow: 0 0 0 3px color-mix(in srgb, var(--pg-accent, #60a5fa) 35%, transparent); } .svelte-flow__connection-line { diff --git a/packages/svelte-graph/src/workflowGraphEdgeOptions.test.ts b/packages/svelte-graph/src/workflowGraphEdgeOptions.test.ts index 50a5a355b..b24149640 100644 --- a/packages/svelte-graph/src/workflowGraphEdgeOptions.test.ts +++ b/packages/svelte-graph/src/workflowGraphEdgeOptions.test.ts @@ -7,7 +7,6 @@ test('WORKFLOW_GRAPH_DEFAULT_EDGE_OPTIONS preserves shared reconnectable edge de assert.deepEqual(WORKFLOW_GRAPH_DEFAULT_EDGE_OPTIONS, { type: 'reconnectable', animated: false, - style: 'stroke: #525252; stroke-width: 2px;', interactionWidth: 20, selectable: true, focusable: true, diff --git a/packages/svelte-graph/src/workflowGraphEdgeOptions.ts b/packages/svelte-graph/src/workflowGraphEdgeOptions.ts index 9a1db751a..7528fb6e4 100644 --- a/packages/svelte-graph/src/workflowGraphEdgeOptions.ts +++ b/packages/svelte-graph/src/workflowGraphEdgeOptions.ts @@ -1,7 +1,6 @@ export const WORKFLOW_GRAPH_DEFAULT_EDGE_OPTIONS = { type: 'reconnectable', animated: false, - style: 'stroke: #525252; stroke-width: 2px;', interactionWidth: 20, selectable: true, focusable: true, diff --git a/packages/svelte-graph/src/workflowGraphViewport.test.ts b/packages/svelte-graph/src/workflowGraphViewport.test.ts index cbb5fe969..03c7dcfb2 100644 --- a/packages/svelte-graph/src/workflowGraphViewport.test.ts +++ b/packages/svelte-graph/src/workflowGraphViewport.test.ts @@ -13,6 +13,6 @@ test('workflow graph viewport constants preserve shared SvelteFlow canvas defaul assert.deepEqual(WORKFLOW_GRAPH_FIT_VIEW_OPTIONS, { maxZoom: 1 }); assert.equal(WORKFLOW_GRAPH_MIN_ZOOM, 0.25); assert.equal(WORKFLOW_GRAPH_MAX_ZOOM, 2); - assert.equal(WORKFLOW_GRAPH_MINIMAP_MASK_COLOR, 'rgba(0, 0, 0, 0.8)'); + assert.equal(WORKFLOW_GRAPH_MINIMAP_MASK_COLOR, 'rgba(35, 39, 45, 0.6)'); assert.equal(WORKFLOW_GRAPH_PAN_ACTIVATION_KEY, null); }); diff --git a/packages/svelte-graph/src/workflowGraphViewport.ts b/packages/svelte-graph/src/workflowGraphViewport.ts index 8267f820c..dd1d137d4 100644 --- a/packages/svelte-graph/src/workflowGraphViewport.ts +++ b/packages/svelte-graph/src/workflowGraphViewport.ts @@ -4,5 +4,5 @@ export const WORKFLOW_GRAPH_FIT_VIEW_OPTIONS = { export const WORKFLOW_GRAPH_MIN_ZOOM = 0.25; export const WORKFLOW_GRAPH_MAX_ZOOM = 2; -export const WORKFLOW_GRAPH_MINIMAP_MASK_COLOR = 'rgba(0, 0, 0, 0.8)'; +export const WORKFLOW_GRAPH_MINIMAP_MASK_COLOR = 'rgba(35, 39, 45, 0.6)'; export const WORKFLOW_GRAPH_PAN_ACTIVATION_KEY = null; diff --git a/src/README.md b/src/README.md new file mode 100644 index 000000000..bcef8071d --- /dev/null +++ b/src/README.md @@ -0,0 +1,112 @@ +# Frontend source root + +## Purpose + +The Svelte 5 frontend of the Pantograph desktop app (Tauri 2 webview). This +root holds the mount point, the global stylesheet with the workbench design +tokens, and the directories for components, stores, services and generated UI. + +## Contents + +| Path | Responsibility | +| --- | --- | +| `main.ts`, `App.svelte` | Mount the app; `App.svelte` renders the workbench shell, the Assistant side panel and global overlays. | +| `styles.css` | Fonts, `--pg-*` design tokens, global scrollbar and focus styles, and the `pg-*` component classes the workbench parts use. | +| `components/` | UI components; `components/workbench/` is the run-centric workbench (see its README). | +| `stores/` | Svelte stores for frontend-owned state (see `stores/README.md`). | +| `services/` | Typed clients for Tauri commands and events, including the workflow projection services. | +| `generated/` | Runtime-authored components; excluded from tests and lint rules that target hand-written code. | + +## Problem + +The webview needs one place that defines how the app looks (tokens, fonts, +focus and scrollbars) and one boundary through which it talks to the Rust +host, so pages can be rebuilt independently without forking either. + +## Constraints + +- The desktop app must render the same offline, so fonts are bundled from + `@fontsource/*` (SIL OFL 1.1) rather than loaded from a CDN. +- Colours come from the `--pg-*` tokens in `styles.css`; Tailwind exposes them + as `pg-*` colours (`tailwind.config.cjs`). The `neutral` scale stays only for + pages not yet restyled and is tuned to the same greys; no `!important` + colour overrides. +- Host access goes through `services/`; components do not call `invoke` + directly for workflow facts. + +## Decision + +Global styling lives in `styles.css` only: tokens on `:root`, element +baselines, and `pg-*` primitives in `@layer components` ported from +`docs/design/mockups/boards/shell.css`. The heading set of this README is +required by `scripts/check-decision-traceability.sh` (issue WR-001 in +`docs/plans/workbench-redesign/issues.md`). + +## Alternatives Rejected + +- Keeping the `!important` neutral overrides: they fought every new class and + hid which palette a page was using. +- System font stacks only: they render differently per machine; they remain + the fallback in each `font-family` stack. + +## Invariants + +- `:focus-visible` draws a 2px accent outline on every focusable element. +- Scrollbars are thin and themed everywhere. +- The `body` background is `var(--pg-ground)`; there is no gradient body + background. +- One remaining `!important` block in `styles.css` targets package graph + components (`.svelte-flow`, `.base-node`, ...) until the Graph milestone + restyles them. + +## Revisit Triggers + +- A light theme or user-selectable accent is requested (tokens would need a + second set). +- The Graph milestone removes the literal darks in `packages/svelte-graph`, so + the remaining override block can go. + +## Dependencies + +**Internal:** `packages/svelte-graph` (graph editor components). + +**External:** `svelte`, `@tauri-apps/api`, `tailwindcss`, `lucide-svelte`, +`@fontsource/newsreader`, `@fontsource/atkinson-hyperlegible`, +`@fontsource/jetbrains-mono`. + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```svelte + +
+

ingest-docs-rag v1.4.0

+

Queued, #2 in queue

+ +
+``` + +## API Consumer Contract + +- The frontend consumes the Tauri commands and events of the Rust host through + `services/` (for example `workflow_run_list_query` via + `workflowService.queryRunList`) and treats their typed responses as the only + authority for workflow, scheduler and diagnostics facts (ADR-014). +- Failures arrive as `WorkflowServiceError`; code `transport_error` means the + host could not be reached, and the workbench then shows the engine as + unreachable and keeps the last projection on screen. +- Outside a Tauri host (plain browser) every command fails with + `transport_error`; the app still renders its shell and empty or error states. + +## Structured Producer Contract + +- The frontend produces typed command requests for the host + (`services/workflow/*`), shaped by the request types in + `services/diagnostics/types.ts` and `services/workflow/types.ts`; it never + writes ledger rows or projections itself. +- `styles.css` produces the `--pg-*` custom properties and `pg-*` classes that + components consume; renaming or removing one is a coordinated change across + `components/workbench/ui/` and the pages using it. diff --git a/src/components/BackendSelector.svelte b/src/components/BackendSelector.svelte index e8ae337eb..625264efb 100644 --- a/src/components/BackendSelector.svelte +++ b/src/components/BackendSelector.svelte @@ -205,18 +205,13 @@ ); -
-
- Built-in inference engine -
+
+
Built-in inference engine
{#if isLoading} -
-
- Loading backends... -
+
Loading backends
{:else if backends.length === 0} -
No backends available
+
No backends available
{:else} {#if activeBackend} -
{activeBackend.description}
+
{activeBackend.description}
{/if} {/if} {#if error} -
- {error} -
+ {/if}
+ + diff --git a/src/components/DeviceConfig.svelte b/src/components/DeviceConfig.svelte index 420b172c4..47be48b7b 100644 --- a/src/components/DeviceConfig.svelte +++ b/src/components/DeviceConfig.svelte @@ -4,6 +4,7 @@ import { LLMService } from '../services/LLMService'; import { RagService } from '../services/RagService'; import { expandedSection, toggleSection } from '../stores/accordionStore'; + import { StatusGlyph } from './workbench/ui'; import { createScopedDeviceRefresh, type DeviceRefreshScope } from './deviceConfigRefreshScope'; import { buildBackendConfirmedDeviceOptions, @@ -238,83 +239,73 @@ }); -
- - +
+
+

+ +

+ + + {isLoadingDevices + ? 'Detecting devices' + : deviceLoadError + ? 'Detection failed' + : `${deviceOptions.length} device${deviceOptions.length === 1 ? '' : 's'}`} + +
{#if $expandedSection === 'device'} -
- -
-
-
- Inference Device -
-
{#if deviceLoadError} -
- Failed to detect devices: {deviceLoadError} -
+ {/if} - -
- +
+ - {#if deviceOptions.length === 0} -
- No backend-confirmed devices available. -
- {:else} -
- Select a backend-confirmed device for inference. -
- {/if} +

+ {deviceOptions.length === 0 + ? 'No backend-confirmed devices available.' + : 'Select a backend-confirmed device for inference.'} +

- -
- +
+
- {getGpuLayersLabel(gpuLayers)} -
-
- -1 = all layers on GPU, 0 = CPU only + {getGpuLayersLabel(gpuLayers)}
+

-1 = all layers on GPU, 0 = CPU only

- -
- VRAM Usage +
+ VRAM usage {#if vramUsage} -
-
- {getSelectedDeviceName()} - +
+
+ {getSelectedDeviceName()} + {formatVramValue(vramUsage.used)} / {formatVramValue(vramUsage.total)} used
-
-
= 90 ? 'bg-red-500' : vramUsage.percent >= 75 ? 'bg-amber-500' : 'bg-blue-500'} - style="width: {vramUsage.percent}%" - >
+ -
+
{formatVramValue(vramUsage.free)} free - {vramUsage.percent}% + {vramUsage.percent}%
+ {#if oomFlash} +

+ + Out of memory reported +

+ {/if}
{:else} -
- Select a GPU device to see VRAM usage. -
+

Select a GPU device to see VRAM usage.

{/if}
- -
- +
+ -
- {getEmbeddingModeDescription(embeddingMemoryMode)} -
+

{getEmbeddingModeDescription(embeddingMemoryMode)}

- {#if hasChanges} - +
+ +
{/if} - -
- Server will restart automatically when you save changes. -
+

Server will restart automatically when you save changes.

{:else} - -
- {getSelectedDeviceName()} - | - {getGpuLayersLabel(gpuLayers)} - | - {getEmbeddingModeLabel(embeddingMemoryMode)} -
+

+ {getSelectedDeviceName()}, {getGpuLayersLabel(gpuLayers)}, {getEmbeddingModeLabel(embeddingMemoryMode)} +

{/if} -
+
diff --git a/src/components/GraphSelector.svelte b/src/components/GraphSelector.svelte deleted file mode 100644 index 7c673a121..000000000 --- a/src/components/GraphSelector.svelte +++ /dev/null @@ -1,179 +0,0 @@ - - -
- - - {#if isOpen} - - {/if} -
- - diff --git a/src/components/ModelConfig.svelte b/src/components/ModelConfig.svelte index 5ccd303b8..dcee77db0 100644 --- a/src/components/ModelConfig.svelte +++ b/src/components/ModelConfig.svelte @@ -2,6 +2,7 @@ import { onMount, onDestroy } from 'svelte'; import { ConfigService, type ConfigState, type ModelConfig } from '../services/ConfigService'; import { expandedSection, toggleSection } from '../stores/accordionStore'; + import { StatusGlyph } from './workbench/ui'; let state: ConfigState = $state(ConfigService.getState()); let unsubscribe: (() => void) | null = null; @@ -86,172 +87,138 @@ ); let isConfigured = $derived(vlmModelPath && vlmMmprojPath); + -
- - +
+
+

+ +

+ + + {isConfigured ? 'Configured' : 'Not configured'} + +
{#if $expandedSection === 'model'} -
- -
-
- Vision-Language Model (VLM) -
- - -
- -
- - -
- {#if vlmModelPath} -
{getFileName(vlmModelPath)}
- {/if} -
- - -
- -
- - -
- {#if vlmMmprojPath} -
{getFileName(vlmMmprojPath)}
- {/if} +
+
+

Vision-language model (VLM)

+ +
+ +
+ +
+ {#if vlmModelPath} +

{getFileName(vlmModelPath)}

+ {/if}
- -
-
- Embedding Model (for RAG) +
+ +
+ +
+ {#if vlmMmprojPath} +

{getFileName(vlmMmprojPath)}

+ {/if} +
+
- -
- -
- - -
- {#if embeddingModelPath} -
{getFileName(embeddingModelPath)}
- {/if} +
+

Embedding model (for RAG)

+ +
+ +
+ +
+ {#if embeddingModelPath} +

{getFileName(embeddingModelPath)}

+ {/if} +
- -
- -
- - -
- {#if candleEmbeddingModelPath} -
{getFileName(candleEmbeddingModelPath)}
- {/if} -
- Directory with config.json, tokenizer.json, and model.safetensors -
+
+ +
+ +
+ {#if candleEmbeddingModelPath} +

{getFileName(candleEmbeddingModelPath)}

+ {/if} +

Directory with config.json, tokenizer.json, and model.safetensors

+
- {#if hasChanges} - +
+ +
{/if} - -
+

Configure model paths for the built-in llama.cpp server. VLM models enable vision-language inference, embedding models enable RAG search. -

+

{:else} - -
- {#if isConfigured} - {getFileName(vlmModelPath)} - {:else} - Not configured - {/if} -
+

+ {isConfigured ? getFileName(vlmModelPath) : 'Not configured'} +

{/if} -
+
diff --git a/src/components/NodeGroupEditor.svelte b/src/components/NodeGroupEditor.svelte index 2dd662eb7..e08bd33ad 100644 --- a/src/components/NodeGroupEditor.svelte +++ b/src/components/NodeGroupEditor.svelte @@ -164,6 +164,7 @@
- import { SvelteMap, SvelteSet } from 'svelte/reactivity'; + import { SvelteSet } from 'svelte/reactivity'; import { dispatchWorkflowPaletteDragEnd, dispatchWorkflowPaletteDragStart, @@ -10,30 +10,17 @@ setActiveWorkflowPaletteDragDefinition, WORKFLOW_PALETTE_DRAG_DATA_TYPES, } from './workflowPaletteDrag'; + import { buildNodePaletteTree } from './workbench/graphInspectionPresenters'; import type { NodeDefinition } from '../services/workflow/types'; + /** Where a double-clicked (or Enter-activated) node lands on the canvas. */ + const DOUBLE_CLICK_ADD_POSITION = { x: 200, y: 200 }; + let searchQuery = $state(''); let expandedCategories = new SvelteSet(['input', 'processing', 'output']); - // Format category names for display (snake_case -> Title Case) - function formatCategoryName(category: string): string { - return category.charAt(0).toUpperCase() + category.slice(1); - } - - let filteredByCategory = $derived(() => { - const result = new SvelteMap(); - for (const [category, defs] of $nodeDefinitionsByCategory) { - const filtered = defs.filter( - (d) => - d.label.toLowerCase().includes(searchQuery.toLowerCase()) || - d.description.toLowerCase().includes(searchQuery.toLowerCase()) - ); - if (filtered.length > 0) { - result.set(category, filtered); - } - } - return result; - }); + let tree = $derived(buildNodePaletteTree($nodeDefinitionsByCategory, searchQuery, expandedCategories)); + let searching = $derived(searchQuery.trim().length > 0); function toggleCategory(category: string) { if (expandedCategories.has(category)) { @@ -62,9 +49,8 @@ clearActiveWorkflowPaletteDragDefinition(); } - function handleDoubleClick(definition: NodeDefinition) { - // Add node at center of viewport - addNode(definition, { x: 200, y: 200 }); + function addDefinition(definition: NodeDefinition) { + addNode(definition, DOUBLE_CLICK_ADD_POSITION); } function handleNodeKeyDown(event: KeyboardEvent, definition: NodeDefinition) { @@ -72,87 +58,174 @@ return; } event.preventDefault(); - handleDoubleClick(definition); - } - - const categoryIcons: Record = { - input: '[ ]', - processing: '[~]', - tool: '[#]', - output: '[>]', - control: '[?]', - }; - - const categoryColors: Record = { - input: 'text-blue-400', - processing: 'text-green-400', - tool: 'text-amber-400', - output: 'text-cyan-400', - control: 'text-purple-400', - }; + addDefinition(definition); + } -
-
-

Nodes

+
+
+
-
- {#each [...filteredByCategory()] as [category, definitions] (category)} -
- - - {#if expandedCategories.has(category)} -
- {#each definitions as definition (definition.node_type)} -
handleDragStart(e, definition)} - ondragend={handleDragEnd} - ondblclick={() => handleDoubleClick(definition)} - onkeydown={(event) => handleNodeKeyDown(event, definition)} - title={definition.description} - role="button" - tabindex="0" - > - {definition.label} - - {definition.inputs.length}:{definition.outputs.length} - -
- {/each} -
- {/if} -
+
+ {#each tree as category (category.key)} + + + {#if category.expanded} +
+ {#each category.items as item (item.definition.node_type)} + +
handleDragStart(event, item.definition)} + ondragend={handleDragEnd} + ondblclick={() => addDefinition(item.definition)} + onkeydown={(event) => handleNodeKeyDown(event, item.definition)} + title={item.definition.description} + role="button" + tabindex="0" + aria-label={`${item.label}, ${item.portsTitle}. Press Enter to add to the canvas.`} + > + {item.label} + {item.ports} +
+ {/each} +
+ {/if} + {:else} +

+ {searching ? 'No nodes match this search.' : 'Node definitions are not loaded yet.'} +

{/each}
-
- Drag or double-click to add -
-
+
Drag onto the canvas, or double-click to add.
+
diff --git a/src/components/README.md b/src/components/README.md new file mode 100644 index 000000000..896b715b8 --- /dev/null +++ b/src/components/README.md @@ -0,0 +1,99 @@ +# Components + +## Purpose + +Svelte components of the Pantograph desktop GUI that are not pages. The +workbench shell and its pages live in `workbench/`; this directory holds the +graph editor surface the Graph page embeds, the app settings panels the +Settings page embeds, the side panel, and the pure helpers those components +use. + +## Contents + +| Path | Responsibility | +| --- | --- | +| `workbench/` | Run-centric workbench shell, pages, presenters and shared `ui/` parts (ADR-014). See `workbench/README.md`. | +| `WorkflowGraph*.svelte`, `WorkflowGraph.css`, `workflow*.ts` + tests, `edgeInsertInteraction.ts`, `reconnectInteraction.ts`, `WorkflowContainerBoundary.svelte`, `WorkflowEdgeInsertPreviewMarker.svelte`, `WorkflowToolbar.svelte`, `WorkflowPersistenceControls.svelte`, `NodePalette.svelte` | Graph editor canvas and its controls, with pure interaction helpers. | +| `nodes/`, `edges/`, `orchestration/` | Node cards, the reconnectable edge, and orchestration graph nodes. See their READMEs. | +| `ServerStatus.svelte`, `BackendSelector.svelte`, `ModelConfig.svelte`, `DeviceConfig.svelte`, `RagStatus.svelte`, `SandboxSettings.svelte` | App settings panels the Settings page shows under "Runtime and app settings". Each is a collapsible `pg-card`; only one is open at a time (`src/stores/accordionStore.ts`). | +| `server-status/`, `runtime-manager/` | Parts of `ServerStatus` and the managed runtime and dependency panels. See their READMEs. | +| `deviceConfigPresenters.ts`, `deviceConfigRefreshScope.ts` + tests | Pure device option logic and the scoped device refresh owner for `DeviceConfig`. | +| `SidePanel.svelte`, `side-panel/`, `ChunkPreview.svelte` | Assistant side panel and the RAG chunk preview overlay mounted by `App.svelte`. | +| `Canvas.svelte`, `Toolbar.svelte`, `Rulers.svelte`, `ClearButton.svelte`, `TopBar.svelte`, `HotLoadContainer.svelte`, `ZoomTransition.svelte`, `UnifiedGraphView.svelte`, `NavigationBreadcrumb.svelte`, `NodeGroupEditor.svelte`, `GroupPortMapper.svelte`, `CommitTimeline.svelte` | Drawing, hot-load and graph navigation components from the pre-workbench app; several are only reachable through `src/features/*` barrels or `src/config/architecture.ts`. | + +## Problem + +The GUI started as a single canvas app with a side panel; the run-centric +workbench (ADR-014) became the root and pages were rebuilt on shared parts. +Components in this directory are reused by those pages, so they must follow +the workbench look and the pages' data rules without moving into +`workbench/`, which holds pages and their presenters only. + +## Constraints + +- Services own backend data: components call `src/services/*` and subscribe to + their state, and never rebuild backend truth (ADR-003 for managed runtimes, + ADR-014 for run projections). +- Workbench look: `pg-*` classes and `--pg-*` tokens from `src/styles.css` and + the parts in `workbench/ui`; status as text beside a glyph; no cyan, + uppercase tracked labels, pulsing or spinners in restyled components. +- Svelte 5 runes and snippets; native interactive elements with names + (`scripts/check-svelte-a11y.mjs`). +- Pure logic sits in `*.ts` modules with Node test runner tests. + +## Decision + +Keep shared non-page components here, grouped by subdirectory when a +component has several parts, and restyle them in place onto the workbench +parts rather than forking page-specific copies. The settings panels remain +self-contained (they load their own service state on mount) so the Settings +page embeds them without wiring. + +## Alternatives Rejected + +- Moving the settings panels into `workbench/`: they are not pages, and + `ServerStatus` and `ManagedRuntimePanel` are also exported through + `src/features/*` barrels. +- Forking restyled copies for the Settings page: two copies of each panel's + service wiring would drift. + +## Invariants + +- Each settings panel owns its subscriptions: it subscribes on mount and + unsubscribes on destroy. +- Settings panel element ids (`vlm-model-path`, `compute-device-select`, + `validation-mode-select`, ...) are stable; the a11y labels depend on them. +- Graph handle geometry is a contract with saved graphs (see `nodes/README.md`). + +## Revisit Triggers + +- A component here gains a second page consumer with different needs; give it + props instead of copying it. +- The pre-workbench drawing components lose their last consumer; remove them. + +## Dependencies + +**Internal:** `src/services/*`, `src/stores/*`, `workbench/ui`, +`src/styles.css`. + +**External:** `svelte`, `@xyflow/svelte` (graph editor), `@tauri-apps/api` +(services), `lucide-svelte` (side panel, architecture nodes, group editor). + +## Related ADRs + +- `docs/adr/ADR-003-runtime-redistributables-manager-boundary.md` +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```svelte + + + + + +``` diff --git a/src/components/RagStatus.svelte b/src/components/RagStatus.svelte index 7b0e7e996..1c9996056 100644 --- a/src/components/RagStatus.svelte +++ b/src/components/RagStatus.svelte @@ -6,6 +6,7 @@ import { LLMService } from '../services/LLMService'; import { openChunkPreview } from '../stores/chunkPreviewStore'; import { expandedSection, toggleSection } from '../stores/accordionStore'; + import { StatusGlyph, type GlyphState } from './workbench/ui'; let ragState: RagState = $state(RagService.getState()); let configState: ConfigState = $state(ConfigService.getState()); @@ -155,227 +156,191 @@ configState.serverMode.mode === 'sidecar_inference' && !ragState.status.vectorizer_available ); + + let indexing = $derived(ragState.isIndexing || isIndexingWithSwitch); + + let indexGlyph = $derived( + ragState.status.vectors_indexed ? 'succeeded' : indexing ? 'running' : 'idle' + ); + + let docsGlyph = $derived( + ragState.status.docs_available ? 'succeeded' : isDownloadingDocs ? 'running' : 'idle' + ); -
- - +
+
+

+ +

+ + + {ragState.status.vectors_indexed ? 'Indexed' : indexing ? 'Indexing' : 'Not indexed'} + +
{#if $expandedSection === 'rag'} -
- -
-
- - Svelte 5 Docs - {#if ragState.status.docs_available} - ({ragState.status.docs_count} files) - {:else if isDownloadingDocs} - Downloading... - {:else} - Not downloaded - {/if} -
+
+
+

+ + Svelte 5 docs + + {#if ragState.status.docs_available} + {ragState.status.docs_count} files + {:else if isDownloadingDocs} + Downloading... + {:else} + Not downloaded + {/if} + +

{#if !ragState.status.docs_available && !isDownloadingDocs} - + {/if}
- -
-
- - Vector Index - {#if ragState.status.vectors_indexed} - ({ragState.status.vectors_count} docs) - {:else if ragState.isIndexing || isIndexingWithSwitch} - Indexing... - {:else} - Not indexed - {/if} -
+
+

+ + Vector index + + {#if ragState.status.vectors_indexed} + {ragState.status.vectors_count} docs + {:else if indexing} + Indexing... + {:else} + Not indexed + {/if} + +

- - {#if (ragState.isIndexing || isIndexingWithSwitch) && ragState.indexingProgress} -
-
-
+ {#if indexing && ragState.indexingProgress} +
+ -
+
{ragState.indexingProgress.status} {#if ragState.indexingProgress.total > 0} - {ragState.indexingProgress.current}/{ragState.indexingProgress.total} + {ragState.indexingProgress.current}/{ragState.indexingProgress.total} {/if}
{/if}
- {#if needsModeSwitch && canIndexWithSwitch} -
+

+ Server will temporarily switch to embedding mode during indexing -

+

{/if} - {#if ragState.error} -
- {ragState.error} -
+ {/if} - -
+
{#if configState.config.models.embedding_model_path} - - +
+ +
{/if} - - {#if useExternalEmbedding} -
+
+
-
{#if ragState.status.vectorizer_available} -
- +

+ Connected +

+
+
- {/if}
{/if}
- - {#if ragState.status.vectors_indexed} - - {/if} - - - {#if ragState.status.docs_available} - + {#if ragState.status.vectors_indexed || ragState.status.docs_available} +
+ {#if ragState.status.vectors_indexed} + + {/if} + {#if ragState.status.docs_available} + + {/if} +
{/if} - {#if !configState.config.models.embedding_model_path && !ragState.status.vectorizer_available} -

- Configure an embedding model in Model Configuration, or connect to an external embedding +

+ Configure an embedding model in Model configuration, or connect to an external embedding server to enable RAG search.

{/if}
{:else} - -
-
- - Docs -
-
- - RAG -
- {#if ragState.status.vectors_indexed} - ({ragState.status.vectors_count}) - {/if} -
+

+ Docs {ragState.status.docs_available ? 'downloaded' : 'not downloaded'} + + RAG {ragState.status.vectors_indexed + ? `indexed (${ragState.status.vectors_count})` + : indexing + ? 'indexing' + : 'not indexed'} + +

{/if} -
+
diff --git a/src/components/SandboxSettings.svelte b/src/components/SandboxSettings.svelte index a4f68c481..39526481b 100644 --- a/src/components/SandboxSettings.svelte +++ b/src/components/SandboxSettings.svelte @@ -2,6 +2,7 @@ import { onMount } from 'svelte'; import { invoke } from '@tauri-apps/api/core'; import { expandedSection, toggleSection } from '../stores/accordionStore'; + import { StatusGlyph } from './workbench/ui'; // Types matching the Rust backend type ImportValidationMode = 'none' | 'import_resolve' | 'vite_integration' | 'esbuild_bundle'; @@ -104,71 +105,52 @@ ); -
- - +
+
+

+ +

+ + + {isLoading ? 'Loading' : loadError ? 'Unavailable' : 'Loaded'} + +
{#if $expandedSection === 'sandbox'} -
+
{#if loadError} -
- Failed to load config: {loadError} -
+ {/if} - -
- +
+ -
- {getModeDescription(validationMode)} -
+

{getModeDescription(validationMode)}

- -
- +
+
- {timeoutMs}ms -
-
- Maximum time to wait for validation script. + {timeoutMs}ms
+

Maximum time to wait for validation script.

- -
- +
+ -
+

One package per line. Added to package.json dependencies for validation. -

+

- {#if hasChanges} - +
+ +
{/if} - -
- Import validation catches errors before they reach the main app. - Settings apply to the next generated component. -
+

+ Import validation catches errors before they reach the main app. Settings apply to the next + generated component. +

{:else} - -
- {getModeLabel(validationMode)} - {#if validationMode !== 'none'} - | - {timeoutMs}ms timeout - {/if} -
+

+ {getModeLabel(validationMode)}{#if validationMode !== 'none'}, {timeoutMs}ms timeout{/if} +

{/if} -
+
diff --git a/src/components/ServerStatus.svelte b/src/components/ServerStatus.svelte index 4dc853edd..0b4196f46 100644 --- a/src/components/ServerStatus.svelte +++ b/src/components/ServerStatus.svelte @@ -17,6 +17,8 @@ import HealthStatusPanel from './server-status/HealthStatusPanel.svelte'; import RuntimeSnapshotGrid from './server-status/RuntimeSnapshotGrid.svelte'; import { expandedSection, toggleSection } from '../stores/accordionStore'; + import { StatusGlyph } from './workbench/ui'; + import { serverConnectionGlyph } from './server-status/serverStatusPresenters'; let { showManagedRuntimePanel = true }: { showManagedRuntimePanel?: boolean } = $props(); @@ -127,14 +129,12 @@ await HealthMonitorService.checkNow(); } - let statusColor = $derived( - llmState.status.ready - ? healthState.lastResult?.healthy === false - ? 'bg-red-500' - : 'bg-green-500' - : llmState.status.mode !== 'none' - ? 'bg-yellow-500 animate-pulse' - : 'bg-neutral-500' + let statusGlyph = $derived( + serverConnectionGlyph( + llmState.status.ready, + healthState.lastResult?.healthy, + llmState.status.mode, + ) ); let statusText = $derived( @@ -163,31 +163,30 @@ }); -
- +
+
+

+ +

+ + + {statusText} + +
{#if $expandedSection === 'server'} -
+
{#if connectionType === 'external'} @@ -200,7 +199,7 @@ onDisconnect={disconnectExternal} /> {:else} -
+
{#if showManagedRuntimePanel} @@ -209,12 +208,12 @@ {/if} {#if llmState.status.ready} -
- Status: {statusText} +

+ Mode {modeText} {#if llmState.status.url} - {llmState.status.url} + {llmState.status.url} {/if} -

+

+
+

{/if}
{:else} -
+

{#if llmState.status.ready} - {modeText} + {modeText} {#if llmState.status.url} - {llmState.status.url} + {llmState.status.url} {/if} {:else} - Not connected + Not connected {/if} -

+

{/if} -
+
diff --git a/src/components/WorkflowGraph.css b/src/components/WorkflowGraph.css index d7b442ec0..df36c1962 100644 --- a/src/components/WorkflowGraph.css +++ b/src/components/WorkflowGraph.css @@ -1,76 +1,115 @@ -.svelte-flow { - background-color: transparent !important; - background-image: none !important; -} - -.svelte-flow__background { - display: none !important; -} +/* + * Editor canvas styling through the xyflow CSS variables, so the workbench + * tokens reach SvelteFlow without overriding its rules. Values follow + * docs/design/mockups/boards/shell.css (.canvas, .wire, .fab, .minimap). + */ +.workflow-graph-container { + position: relative; + overflow: hidden; + border: 1px solid var(--pg-border); + border-radius: 4px; -.svelte-flow__renderer { - background-color: transparent !important; + --xy-background-color: transparent; + --xy-node-background-color: transparent; + --xy-node-border: none; + --xy-node-boxshadow-hover: none; + --xy-node-boxshadow-selected: none; + --xy-node-color: var(--pg-text); + --xy-edge-stroke: var(--pg-border-strong); + --xy-edge-stroke-width: 1.5; + --xy-edge-stroke-selected: var(--pg-text); + --xy-connectionline-stroke: var(--pg-accent); + --xy-connectionline-stroke-width: 2; + --xy-handle-background-color: var(--pg-panel-head); + --xy-handle-border-color: var(--pg-border-strong); + --xy-controls-button-background-color: var(--pg-panel); + --xy-controls-button-background-color-hover: var(--pg-panel-raised); + --xy-controls-button-color: var(--pg-text-soft); + --xy-controls-button-color-hover: var(--pg-text-bright); + --xy-controls-button-border-color: var(--pg-border); + --xy-controls-box-shadow: none; + --xy-minimap-background-color: var(--pg-panel-sunken); + --xy-minimap-mask-background-color: rgba(35, 39, 45, 0.6); + --xy-minimap-mask-stroke-color: var(--pg-text-soft); + --xy-minimap-mask-stroke-width: 1; + --xy-minimap-node-background-color: var(--pg-border-idle); + --xy-attribution-background-color: transparent; } -.svelte-flow__edge-path { - stroke: #60a5fa; - stroke-width: 2px; - filter: drop-shadow(0 0 3px rgba(96, 165, 250, 0.6)); +/* Dotted drafting-paper ground on the flow element itself. */ +.workflow-graph-container .svelte-flow { + background-color: var(--pg-panel-head); + background-image: radial-gradient(var(--pg-border) 1px, transparent 1px); + background-size: 22px 22px; } -.svelte-flow__edge.selected .svelte-flow__edge-path { - stroke: #93c5fd; - stroke-width: 3px; - filter: drop-shadow(0 0 6px rgba(147, 197, 253, 0.8)); +.workflow-graph-container.cutting { + cursor: crosshair; } -.svelte-flow__controls { - background-color: #262626; - border: 1px solid #404040; - border-radius: 8px; +.workflow-graph-container .svelte-flow__background { + display: none; } -.svelte-flow__controls-button { - background-color: #262626; - border-color: #404040; - color: #a3a3a3; +/* + * Wires are neutral on the board. CSS outranks the SVG presentation + * attributes ReconnectableEdge sets (type-coloured gradient and glow), so the + * main path follows the tokens here; its insert-preview and drift overlays + * keep their own colours (see the M5 report). + */ +.workflow-graph-container .svelte-flow__edge-path, +.workflow-graph-container .react-flow__edge-path { + stroke: var(--pg-border-strong); + stroke-width: 1.5px; + filter: none; } -.svelte-flow__controls-button:hover { - background-color: #404040; +.workflow-graph-container .svelte-flow__edge.selected .svelte-flow__edge-path, +.workflow-graph-container .svelte-flow__edge.selected .react-flow__edge-path { + stroke: var(--pg-text); + stroke-width: 2px; } -.svelte-flow__minimap { - background-color: #171717; - border: 1px solid #404040; - border-radius: 8px; +.workflow-graph-container .svelte-flow__connection-path { + stroke: var(--pg-accent); + stroke-width: 2px; } -.svelte-flow__node { - background-color: transparent !important; - border: none !important; - box-shadow: none !important; +.workflow-graph-container .svelte-flow__handle.connecting { + background: var(--pg-accent); + border-color: var(--pg-accent); } -.svelte-flow__handle { - border-radius: 50%; +/* Bottom-left pill group (zoom in, zoom out, fit, lock) as on the board. */ +.workflow-graph-container .svelte-flow__controls { + display: flex; + flex-direction: row; + gap: 6px; + padding: 6px; + margin: 12px; + background: var(--pg-panel-sunken); + border: 1px solid var(--pg-border); + border-radius: 4px; } -.svelte-flow__handle.connecting { - background: #60a5fa !important; - box-shadow: 0 0 10px rgba(96, 165, 250, 0.8); +.workflow-graph-container .svelte-flow__controls-button { + width: 26px; + height: 26px; + border: 1px solid var(--pg-border); + border-radius: 4px; } -.svelte-flow__connection-line { - stroke: #60a5fa; - stroke-width: 2px; - filter: drop-shadow(0 0 4px rgba(96, 165, 250, 0.7)); +.workflow-graph-container .svelte-flow__controls-button svg { + fill: currentColor; } -.workflow-graph-container { - position: relative; - overflow: hidden; +.workflow-graph-container .svelte-flow__minimap { + margin: 12px; + border: 1px solid var(--pg-border); + border-radius: 3px; } -.workflow-graph-container.cutting { - cursor: crosshair; -} +/* + * The canvas passes a literal mask colour as a MiniMap prop, which wins over + * the --xy variables; fill on the mask element follows the tokens instead. + */ diff --git a/src/components/WorkflowGraphCanvas.svelte b/src/components/WorkflowGraphCanvas.svelte index b74ac1be7..e9d92d817 100644 --- a/src/components/WorkflowGraphCanvas.svelte +++ b/src/components/WorkflowGraphCanvas.svelte @@ -197,6 +197,7 @@ - import { FilePlus2, Save, Trash2, X } from 'lucide-svelte'; + import type { Snippet } from 'svelte'; import { workflowGraph, isDirty, clearWorkflow } from '../stores/workflowStore'; import { isReadOnly, @@ -12,21 +12,68 @@ deleteWorkflowByName, refreshWorkflowList, saveLastGraph, + SYSTEM_GRAPHS, + switchGraph, + type GraphType, } from '../stores/graphSessionStore'; import { workflowService } from '../services/workflow/WorkflowService'; - import GraphSelector from './GraphSelector.svelte'; + import { + formatWorkflowModifiedShort, + type GraphPageMode, + } from './workbench/graphInspectionPresenters'; + + /** + * Workflow selector (with New, Clear and Delete in its popover) and Save. + * Renders without a wrapper so its parts sit in the toolbar row; `middle` + * is rendered between the selector and Save. + */ + interface Props { + mode: GraphPageMode; + /** Version shown next to the workflow name in edit mode. */ + editVersion: string; + /** In run mode the selector names the run's workflow and version instead. */ + runWorkflow?: { workflowId: string; version: string | null } | null; + middle?: Snippet; + /** Called after a picked workflow or system graph has loaded. */ + onworkflowpicked?: () => void; + /** Save, delete and switch failures, for the toolbar to explain under the row. */ + onactionerror?: (message: string | null) => void; + } + + let { + mode, + editVersion, + runWorkflow = null, + middle, + onworkflowpicked, + onactionerror, + }: Props = $props(); const WORKFLOW_FILE_EXTENSION = '.json'; let isSaving = $state(false); let isDeleting = $state(false); - let actionError = $state(null); + let isSwitching = $state(false); + let open = $state(false); + let selectorRoot: HTMLDivElement | null = $state(null); + let toggleButton: HTMLButtonElement | null = $state(null); + let nowMs = $state(Date.now()); let currentSavedWorkflow = $derived( $currentGraphType === 'workflow' ? $availableWorkflows.find((workflow) => (workflow.id ?? workflow.name) === $currentGraphId) : undefined, ); + let selectorName = $derived( + mode === 'run' && runWorkflow ? runWorkflow.workflowId : $currentGraphName, + ); + let selectorVersion = $derived( + mode === 'run' && runWorkflow + ? runWorkflow.version + : $currentGraphType === 'system' + ? null + : editVersion, + ); function normalizeError(error: unknown): string { if (error instanceof Error && error.message.trim().length > 0) { @@ -38,6 +85,10 @@ return String(error); } + function reportError(message: string | null): void { + onactionerror?.(message); + } + function workflowIdFromSavedPath(path: string, fallbackName: string): string { const filename = path.split(/[\\/]/).pop(); if (!filename?.endsWith(WORKFLOW_FILE_EXTENSION)) { @@ -46,13 +97,72 @@ return filename.slice(0, -WORKFLOW_FILE_EXTENSION.length); } + function closePopover(returnFocus: boolean): void { + open = false; + if (returnFocus) { + toggleButton?.focus(); + } + } + + function togglePopover(): void { + if (!open) { + reportError(null); + nowMs = Date.now(); + void refreshWorkflowList(); + } + open = !open; + } + + // Outside pointer and Escape close the popover; listeners live only while it is open. + $effect(() => { + if (!open) return; + const onPointerDown = (event: MouseEvent) => { + if (selectorRoot && !selectorRoot.contains(event.target as Node)) { + closePopover(false); + } + }; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + event.preventDefault(); + closePopover(true); + } + }; + document.addEventListener('mousedown', onPointerDown); + document.addEventListener('keydown', onKeyDown); + return () => { + document.removeEventListener('mousedown', onPointerDown); + document.removeEventListener('keydown', onKeyDown); + }; + }); + + async function handleSelect(id: string, type: GraphType) { + if (isSwitching) return; + + reportError(null); + isSwitching = true; + try { + const loaded = await switchGraph(id, type); + if (loaded) { + closePopover(true); + onworkflowpicked?.(); + return; + } + reportError($graphSessionError ?? `Failed to load ${type} "${id}".`); + } catch (error) { + reportError(`Failed to load ${type} "${id}": ${normalizeError(error)}`); + console.error('[WorkflowPersistenceControls] Failed to switch graph:', error); + } finally { + isSwitching = false; + } + } + async function handleSave() { if ($isReadOnly || isSaving) return; const name = prompt('Workflow name:', $currentGraphName || 'Untitled Workflow')?.trim(); if (!name) return; - actionError = null; + reportError(null); isSaving = true; try { const path = await workflowService.saveWorkflow(name, $workflowGraph); @@ -65,7 +175,7 @@ await refreshWorkflowList(); } catch (error) { console.error('Failed to save workflow:', error); - actionError = `Failed to save workflow: ${normalizeError(error)}`; + reportError(`Failed to save workflow: ${normalizeError(error)}`); } finally { isSaving = false; } @@ -74,14 +184,16 @@ function handleNew() { if ($isReadOnly) return; if ($isDirty && !confirm('Discard unsaved changes?')) return; - actionError = null; + reportError(null); + closePopover(true); createNewWorkflow(); } function handleClear() { if ($isReadOnly) return; if (!confirm('Clear all nodes?')) return; - actionError = null; + reportError(null); + closePopover(true); clearWorkflow(); } @@ -94,81 +206,266 @@ ); if (!confirmed) return; - actionError = null; + reportError(null); isDeleting = true; try { const deleted = await deleteWorkflowByName(workflowId); if (!deleted) { - actionError = $graphSessionError ?? `Failed to delete workflow "${currentSavedWorkflow.name}".`; + reportError($graphSessionError ?? `Failed to delete workflow "${currentSavedWorkflow.name}".`); } } catch (error) { console.error('Failed to delete workflow:', error); - actionError = `Failed to delete workflow: ${normalizeError(error)}`; + reportError(`Failed to delete workflow: ${normalizeError(error)}`); } finally { isDeleting = false; } } -
- - -
- -
- - - - -
- - {#if actionError} - - {actionError} - +
+ + + {#if open} + {/if}
+ +{@render middle?.()} + +{#if mode === 'edit'} + +{/if} + + diff --git a/src/components/WorkflowToolbar.svelte b/src/components/WorkflowToolbar.svelte index a561362cb..d29f0153d 100644 --- a/src/components/WorkflowToolbar.svelte +++ b/src/components/WorkflowToolbar.svelte @@ -1,5 +1,5 @@ -
-
- +
+
+ {@render modeSwitch()} -
- {#if $isReadOnly} - (read-only) - {/if} - {#if $isDirty && !$isReadOnly} - * - {/if} -
- -
-
+ {:else} + + + {/if}
- {#if submitDisabledReason && !$isExecuting} -
Submit unavailable: {submitDisabledReason} -
+

{/if} - {#if workflowErrorMessage} -
-
+ {#if mode === 'edit' && workflowErrorMessage} +
+ + Workflow submit failed: {workflowErrorMessage} -
+ {#if canOpenWorkflowErrorDiagnostics} {/if}
{/if} + + {#if persistenceError} +
+ + {persistenceError} +
+ {/if} + + {#if $graphSessionError && $graphSessionError !== persistenceError} +
+ + {$graphSessionError} +
+ {/if}
+ + diff --git a/src/components/edges/README.md b/src/components/edges/README.md new file mode 100644 index 000000000..ff4f0df41 --- /dev/null +++ b/src/components/edges/README.md @@ -0,0 +1,72 @@ +# Graph edge components + +## Purpose + +Custom SvelteFlow edge renderers for the Graph tab's editor canvas. + +## Contents + +| Path | Responsibility | +| --- | --- | +| `ReconnectableEdge.svelte` | The default workflow edge (`type: 'reconnectable'`): bezier wire, insert-preview and inference-drift overlays, a wide invisible interaction path and the two reconnect anchors. | + +## Problem + +Edges used a per-data-type gradient with a glow filter, a light-blue insert +preview and a saturated red drift overlay. The redesign board +(`docs/design/mockups/boards/shell.css`, `.wire`) draws wires neutral grey and +keeps the accent for live state, so the canvas read as busier than the rest of +the workbench. + +## Constraints + +- The edge id, the `react-flow__edge-path` and `react-flow__edge-interaction` + classes, the interaction width and the reconnect anchor positions + (`insetReconnectAnchorPosition`) are behaviour, not styling. +- Token colours only; SVG presentation attributes cannot read CSS variables, + so colours live in the component's scoped style. + +## Decision + +The main path is `--pg-border-strong` at 1.5px and `--pg-text` at 2px when +selected; the insert preview (a live drag interaction) uses the accent at 45% +opacity; inference drift is a dashed `--pg-danger` overlay with its title. +The edge no longer reads the node store to colour itself. + +## Alternatives Rejected + +- Keeping type colours at the wire ends: the data type is already in the port + label's `title`, and the hues competed with the status glyphs. +- Styling only from `WorkflowGraph.css`: other mounts of this edge (the node + group editor) would keep the old colours. + +## Invariants + +- Edges are neutral at rest; the accent appears only during a live + interaction. +- Drift is dashed as well as red, so it is not shown by colour alone. + +## Revisit Triggers + +- The edit canvas gets live run state per edge (the run-mode snapshot already + draws live wires in accent). + +## Dependencies + +**Internal:** `src/components/reconnectInteraction.ts`, +`src/components/workflowInferenceDriftEdgeOverlays.ts`; registered in +`src/components/workflowGraphTypes.ts` and `src/components/NodeGroupEditor.svelte`. + +**External:** `svelte`, `@xyflow/svelte` (`getBezierPath`, `EdgeReconnectAnchor`). + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```ts +import ReconnectableEdge from './edges/ReconnectableEdge.svelte'; + +export const workflowEdgeTypes = { reconnectable: ReconnectableEdge }; +``` diff --git a/src/components/edges/ReconnectableEdge.svelte b/src/components/edges/ReconnectableEdge.svelte index 33479e182..876d15be3 100644 --- a/src/components/edges/ReconnectableEdge.svelte +++ b/src/components/edges/ReconnectableEdge.svelte @@ -4,8 +4,6 @@ getBezierPath, type EdgeProps, } from '@xyflow/svelte'; - import { nodes } from '../../stores/workflowStore'; - import type { NodeDefinition } from '../../services/workflow/types'; import { insetReconnectAnchorPosition } from '../reconnectInteraction'; import { INFERENCE_INTERFACE_DRIFT_EDGE_ACTIVE_KEY, @@ -16,9 +14,7 @@ id, data, source, - target, sourceHandleId, - targetHandleId, sourceX, sourceY, targetX, @@ -29,44 +25,6 @@ selected, }: EdgeProps = $props(); - // Port type colors - brighter/more saturated versions for edges - const typeColors: Record = { - string: '#4ade80', - prompt: '#60a5fa', - number: '#fbbf24', - boolean: '#f87171', - image: '#a78bfa', - audio: '#f9a8d4', - audio_stream: '#38bdf8', - stream: '#22d3ee', - json: '#fb923c', - kv_cache: '#a3e635', - component: '#f472b6', - document: '#2dd4bf', - tools: '#fbbf24', - embedding: '#818cf8', - vector_db: '#c084fc', - any: '#9ca3af', - }; - - // Get source port color - const sourceColor = $derived.by(() => { - const sourceNode = $nodes.find(n => n.id === source); - if (!sourceNode?.data?.definition) return '#60a5fa'; - const def = sourceNode.data.definition as NodeDefinition; - const port = def.outputs.find(p => p.id === sourceHandleId); - return port ? (typeColors[port.data_type] || '#60a5fa') : '#60a5fa'; - }); - - // Get target port color - const targetColor = $derived.by(() => { - const targetNode = $nodes.find(n => n.id === target); - if (!targetNode?.data?.definition) return '#60a5fa'; - const def = targetNode.data.definition as NodeDefinition; - const port = def.inputs.find(p => p.id === targetHandleId); - return port ? (typeColors[port.data_type] || '#60a5fa') : '#60a5fa'; - }); - const [path] = $derived( getBezierPath({ sourceX, @@ -78,8 +36,6 @@ }) ); - // Unique gradient ID for this edge - const gradientId = $derived(`edge-gradient-${id}`); const sourceAnchorPosition = $derived( insetReconnectAnchorPosition( { @@ -117,31 +73,12 @@ ); - - - - - - - - - - - - - - - - - - - - - + {#if edgeInsertPreviewActive} {#if typeof inferenceInterfaceDriftTitle === 'string'} {inferenceInterfaceDriftTitle} @@ -189,3 +124,25 @@ + + diff --git a/src/components/nodes/BaseNode.svelte b/src/components/nodes/BaseNode.svelte index c64a1fd03..b84624669 100644 --- a/src/components/nodes/BaseNode.svelte +++ b/src/components/nodes/BaseNode.svelte @@ -1,9 +1,11 @@
- -
-
+ +
+ + + {executionGlyph.label} + +
{#if header} {@render header()} {:else} - {label} + {label} {/if}
- - {#if executionState !== 'idle'} -
- {/if}
- + {#if executionState === 'error' && errorMessage} -
+
{errorMessage}
{/if} @@ -138,7 +115,7 @@
{#each inputs as input (input.id)} - + {input.label} {/each} @@ -146,7 +123,7 @@
{#each outputs as output (output.id)} - + {output.label} {/each} @@ -156,7 +133,7 @@ {#if children} -
+
{@render children()}
{/if} @@ -164,108 +141,96 @@ {#each inputs as input, i (input.id)} {@const yPos = 52 + i * 20} - {@const color = getPortColor(input)} - {@const connected = isInputConnected(input.id)} {/each} {#each outputs as output, i (output.id)} {@const yPos = 52 + i * 20} - {@const color = getPortColor(output)} - {@const connected = isOutputConnected(output.id)} {/each}
diff --git a/src/components/nodes/README.md b/src/components/nodes/README.md new file mode 100644 index 000000000..665503efc --- /dev/null +++ b/src/components/nodes/README.md @@ -0,0 +1,96 @@ +# Graph node components + +## Purpose + +Svelte components that SvelteFlow renders as node cards on the Graph tab's +editor canvas (and on the architecture view). `BaseNode.svelte` is the shared +card every workflow node builds on; the subdirectories hold the typed cards. + +## Contents + +| Path | Responsibility | +| --- | --- | +| `BaseNode.svelte` | Shared workflow node card: status glyph header, port labels, absolutely positioned handles, error line, optional content slot, connection-intent and inference-drift handle classes. | +| `workflow/` | Typed workflow node cards built on `BaseNode` plus their pure state helpers. See `workflow/README.md`. | +| `architecture/` | Cards for the read-only App Architecture system graph (`ArchBaseNode` and its category wrappers). | + +## Problem + +Saved graphs store node positions, handle ids and edge endpoints. The cards +must keep handle geometry stable across restyles, while the workbench redesign +(`docs/design/workbench-redesign-spec.md`) asks for one token palette, a glyph +header and no per-category colour, glow or pulsing on the canvas. + +## Constraints + +- Handle ids equal the node definition's port ids; edges reference them. +- Handle geometry is a contract with saved graphs and with edge routing: the + header is 37px tall and the ports section padding places handle `i` at + `52 + 20·i` px from the card top. +- Colours come from the `--pg-*` tokens in `src/styles.css`; no literal + colours, cyan, glow or pulsing animation. +- Selection stays visible without relying on hue alone (border plus outline + ring). + +## Decision + +`BaseNode` owns the card chrome, the status glyph (from +`editNodeExecutionGlyph` in `workbench/graphInspectionPresenters.ts`) and the +handles. Typed cards pass a `header` snippet (a title only) and their custom +content as children; they never restyle the card border or header, so +selection, running and error treatments look the same on every card. + +## Alternatives Rejected + +- Category-coloured headers and borders per node type: they competed with the + status glyph and the accent reserved for live state, and overrode the + selection border. +- Type-coloured handles: the data type stays in the port label's `title`; the + handle shows only connected or not. + +## Invariants + +- Header height 37px and handle offsets `52 + 20·i` px never change without a + migration of saved layouts and edge anchors. +- Handle ids, types (`target` left, `source` right) and the classes + `port-connected`, `intent-*` and `inference-drift-affected` keep their names. +- The execution state is shown as a glyph with screen-reader text, never by + colour alone. + +## Revisit Triggers + +- Ports gain per-port rows of variable height (the fixed offset breaks). +- The spec adds a per-category marker to the node card. + +## Dependencies + +**Internal:** `src/stores/workflowStore.ts` (edges, execution states, +connection intent), `src/components/workflowInferenceDriftEdgeOverlays.ts`, +`src/components/workbench/ui/StatusGlyph.svelte`, +`src/components/workbench/graphInspectionPresenters.ts`. + +**External:** `svelte`, `@xyflow/svelte` (`Handle`, `Position`). + +## Related ADRs + +- `docs/adr/ADR-006-canonical-node-contract-ownership.md` (port definitions the + handles render) +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` (the Graph + tab's edit mode that mounts these cards) + +## Usage Examples + +```svelte + + + + {#snippet header()} + + {/snippet} +
No output yet
+
+``` diff --git a/src/components/nodes/workflow/AgentToolsNode.svelte b/src/components/nodes/workflow/AgentToolsNode.svelte index f0feed045..ffaa0a44d 100644 --- a/src/components/nodes/workflow/AgentToolsNode.svelte +++ b/src/components/nodes/workflow/AgentToolsNode.svelte @@ -1,5 +1,6 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Audio Input'} -
+ {/snippet}
@@ -183,16 +175,16 @@ onchange={handleFileSelected} /> {#if data.fileName} -
{data.fileName}
+
{data.fileName}
{/if} {#if loadError} -
{loadError}
+
{loadError}
{/if} {#if audioSrc}
@@ -224,18 +216,18 @@ max={duration > 0 ? duration : 1} step="0.01" value={currentTime} - class="w-full h-1.5 accent-pink-500 cursor-pointer" + class="w-full h-1.5 accent-pg-text-soft cursor-pointer" oninput={handleSeek} />
- Vol + Vol
@@ -245,13 +237,3 @@
- diff --git a/src/components/nodes/workflow/AudioOutputNode.svelte b/src/components/nodes/workflow/AudioOutputNode.svelte index f46417c68..24a7d8f5a 100644 --- a/src/components/nodes/workflow/AudioOutputNode.svelte +++ b/src/components/nodes/workflow/AudioOutputNode.svelte @@ -1,6 +1,7 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Audio Output'} - -
+ {/snippet} {#if hasAnyAudio} @@ -777,7 +761,7 @@
- + {formatTime(currentTime)} / {formatTime(displayedDuration)} {#if !finalAudioSrc} - Streaming + Streaming {/if}
0 ? displayedDuration : 1} step="0.01" value={currentTime} - class="nodrag nopan nowheel w-full h-1.5 accent-pink-500 cursor-pointer" + class="nodrag nopan nowheel w-full h-1.5 accent-pg-text-soft cursor-pointer" disabled={!canSeek} oninput={handleSeek} onmousedown={stopControlEvent} @@ -819,14 +803,14 @@ onclickcapture={stopControlEvent} />
- Vol + Vol
-
{#if activityLog.length === 0} -
No activity yet. Use Run/Resolve/Check/Install to capture logs.
+
No activity yet. Use Run/Resolve/Check/Install to capture logs.
{:else} {#each activityLog as line, i (`${i}:${line}`)}
{line}
diff --git a/src/components/nodes/workflow/DependencyEnvironmentBindingsPanel.svelte b/src/components/nodes/workflow/DependencyEnvironmentBindingsPanel.svelte index 3f7dbea61..20f8a22f6 100644 --- a/src/components/nodes/workflow/DependencyEnvironmentBindingsPanel.svelte +++ b/src/components/nodes/workflow/DependencyEnvironmentBindingsPanel.svelte @@ -92,25 +92,25 @@ {#if mode === 'manual'} -
+
- Structured Override Controls - + Structured Override Controls + {effectiveManualOverrides.length} effective patch(es)
-
+
Configure per binding and per requirement below. Overrides are applied immediately.
{#if upstreamManualOverrides.length > 0} -
+
{upstreamManualOverrides.length} patch(es) are provided by connected input. Local form edits override conflicts.
{/if}
{#if requirementPatchCount(binding.binding_id, requirement.name) > 0} - + {requirementPatchCount(binding.binding_id, requirement.name)} patch(es) {/if} diff --git a/src/components/nodes/workflow/DependencyEnvironmentModeControls.svelte b/src/components/nodes/workflow/DependencyEnvironmentModeControls.svelte index dc2fb0a37..213ea7234 100644 --- a/src/components/nodes/workflow/DependencyEnvironmentModeControls.svelte +++ b/src/components/nodes/workflow/DependencyEnvironmentModeControls.svelte @@ -11,8 +11,9 @@
- diff --git a/src/components/nodes/workflow/DependencyEnvironmentNodeHeader.svelte b/src/components/nodes/workflow/DependencyEnvironmentNodeHeader.svelte index d1aff160c..be68d591b 100644 --- a/src/components/nodes/workflow/DependencyEnvironmentNodeHeader.svelte +++ b/src/components/nodes/workflow/DependencyEnvironmentNodeHeader.svelte @@ -1,17 +1,7 @@ -
-
- - - -
- {label} -
+ diff --git a/src/components/nodes/workflow/DependencyEnvironmentRefPanel.svelte b/src/components/nodes/workflow/DependencyEnvironmentRefPanel.svelte index f6165146c..bc1599d08 100644 --- a/src/components/nodes/workflow/DependencyEnvironmentRefPanel.svelte +++ b/src/components/nodes/workflow/DependencyEnvironmentRefPanel.svelte @@ -8,15 +8,15 @@ let { environmentRef }: Props = $props(); -
-
environment state: {environmentRef.state}
+
+
environment state: {environmentRef.state}
{#if environmentRef.env_id} -
+
env: {environmentRef.env_id}
{/if} {#if environmentRef.python_executable} -
+
python: {environmentRef.python_executable}
{/if} diff --git a/src/components/nodes/workflow/DependencyEnvironmentStatusPanel.svelte b/src/components/nodes/workflow/DependencyEnvironmentStatusPanel.svelte index 438f6741f..63e659fe0 100644 --- a/src/components/nodes/workflow/DependencyEnvironmentStatusPanel.svelte +++ b/src/components/nodes/workflow/DependencyEnvironmentStatusPanel.svelte @@ -28,16 +28,17 @@ {#if !hasModelBinding} -
+
Connect this sidecar to an inference node.
{:else} -
+ +
{dependencyBadge.label}
{#if dependencyStatus?.message} -
+
{dependencyStatus.message}
{/if} {#if dependencyStatus?.code} -
+
code: {dependencyCodeLabel(dependencyStatus.code) ?? dependencyStatus.code}
{/if} diff --git a/src/components/nodes/workflow/EmbeddingNode.svelte b/src/components/nodes/workflow/EmbeddingNode.svelte index 9fae802d6..82d85412b 100644 --- a/src/components/nodes/workflow/EmbeddingNode.svelte +++ b/src/components/nodes/workflow/EmbeddingNode.svelte @@ -1,5 +1,6 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'LlamaCpp Embedding'} -
+ {/snippet}
-
{statusText}
+
{statusText}
{#if !hasTextInput} -
Connect text input
+
Connect text input
{/if} {#if executionState === 'error' && errorMessage} -
+
{errorMessage}
{/if}
- - diff --git a/src/components/nodes/workflow/GenericNode.svelte b/src/components/nodes/workflow/GenericNode.svelte index 3baf27f79..63dd13114 100644 --- a/src/components/nodes/workflow/GenericNode.svelte +++ b/src/components/nodes/workflow/GenericNode.svelte @@ -1,7 +1,6 @@ -
- -
- - {statusText} -
-
+ +
+
- - diff --git a/src/components/nodes/workflow/ImageOutputNode.svelte b/src/components/nodes/workflow/ImageOutputNode.svelte index fee5d54b7..0324ce3c7 100644 --- a/src/components/nodes/workflow/ImageOutputNode.svelte +++ b/src/components/nodes/workflow/ImageOutputNode.svelte @@ -1,13 +1,14 @@ -
+
{#snippet header()} -
-
- - - -
-
- {data.label || 'LLM Inference'} -
-
+ {/snippet}
-
- - {statusText} -
+
{statusText}
- Model: - {modelName} + Model: + {modelName}
{#if inferenceDisplay} -
+
{#if inferenceDisplay.tasks.length > 0}
{#each inferenceDisplay.tasks as task (task)} - + {task} {/each} @@ -150,8 +131,8 @@ {/if} {#each inferenceDisplay.rows as row (row.label)}
- {row.label}: - {row.value} + {row.label}: + {row.value}
{/each}
@@ -214,7 +195,7 @@ {/if} {/if} {#if streamContent} -
+
{streamContent}
{/if} @@ -223,49 +204,38 @@
diff --git a/src/components/nodes/workflow/LinkedInputNode.svelte b/src/components/nodes/workflow/LinkedInputNode.svelte index 3560a1ffd..2dca8cf29 100644 --- a/src/components/nodes/workflow/LinkedInputNode.svelte +++ b/src/components/nodes/workflow/LinkedInputNode.svelte @@ -1,5 +1,6 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Linked Input'} -
+ {/snippet}
{#if status === 'unlinked'}
diff --git a/src/components/nodes/workflow/ModelProviderNode.svelte b/src/components/nodes/workflow/ModelProviderNode.svelte index 01d8dd138..5141c6bcc 100644 --- a/src/components/nodes/workflow/ModelProviderNode.svelte +++ b/src/components/nodes/workflow/ModelProviderNode.svelte @@ -1,5 +1,6 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Model Provider'} -
+ {/snippet} {#if isModelConnected} -
+
Model from connection
{:else}
- +
- - diff --git a/src/components/nodes/workflow/NodeGroupNode.svelte b/src/components/nodes/workflow/NodeGroupNode.svelte index d8a37181f..b91117054 100644 --- a/src/components/nodes/workflow/NodeGroupNode.svelte +++ b/src/components/nodes/workflow/NodeGroupNode.svelte @@ -41,28 +41,6 @@ })) ); - const typeColors: Record = { - string: '#22c55e', - prompt: '#3b82f6', - number: '#f59e0b', - boolean: '#ef4444', - image: '#8b5cf6', - audio: '#f472b6', - audio_stream: '#0ea5e9', - stream: '#06b6d4', - json: '#f97316', - kv_cache: '#84cc16', - component: '#ec4899', - document: '#14b8a6', - tools: '#d97706', - embedding: '#6366f1', - vector_db: '#a855f7', - any: '#6b7280', - }; - - function getPortColor(port: PortDefinition): string { - return typeColors[port.data_type] || typeColors.any; - } function handleOpenGroup() { if (group) { @@ -72,17 +50,17 @@
-
- +
+ - {label} - {nodeCount} nodes + {label} + {nodeCount} nodes
@@ -91,7 +69,7 @@
{#each inputs as input (input.id)} - + {input.label} {/each} @@ -99,7 +77,7 @@
{#each outputs as output (output.id)} - + {output.label} {/each} @@ -108,8 +86,8 @@
-
- Open group to edit internals +
+ Open group to edit internals @@ -122,7 +100,7 @@ type="target" position={Position.Left} id={input.id} - style="top: {yPos}px; background: {getPortColor(input)}; width: 10px; height: 10px; border: 2px solid #262626;" + style="top: {yPos}px; width: 10px; height: 10px;" /> {/each} @@ -132,25 +110,54 @@ type="source" position={Position.Right} id={output.id} - style="top: {yPos}px; background: {getPortColor(output)}; width: 10px; height: 10px; border: 2px solid #262626;" + style="top: {yPos}px; width: 10px; height: 10px;" /> {/each}
diff --git a/src/components/nodes/workflow/NodeHeaderTitle.svelte b/src/components/nodes/workflow/NodeHeaderTitle.svelte new file mode 100644 index 000000000..c5834404e --- /dev/null +++ b/src/components/nodes/workflow/NodeHeaderTitle.svelte @@ -0,0 +1,28 @@ + + +{label} + + diff --git a/src/components/nodes/workflow/NumberInputNode.svelte b/src/components/nodes/workflow/NumberInputNode.svelte index db3e6c3c9..78a4933ab 100644 --- a/src/components/nodes/workflow/NumberInputNode.svelte +++ b/src/components/nodes/workflow/NumberInputNode.svelte @@ -1,5 +1,6 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Number Input'} -
+ {/snippet}
-
{#if targetPort?.description} -
{targetPort.description}
+
{targetPort.description}
{/if} {#if targetPort?.constraints?.min !== undefined || targetPort?.constraints?.max !== undefined} -
+
{#if targetPort?.constraints?.min !== undefined}min {targetPort.constraints.min}{/if} {#if targetPort?.constraints?.min !== undefined && targetPort?.constraints?.max !== undefined} · {/if} {#if targetPort?.constraints?.max !== undefined}max {targetPort.constraints.max}{/if} @@ -99,18 +91,3 @@
- - diff --git a/src/components/nodes/workflow/PointCloudOutputNode.svelte b/src/components/nodes/workflow/PointCloudOutputNode.svelte index b06547dbd..e21b89bdc 100644 --- a/src/components/nodes/workflow/PointCloudOutputNode.svelte +++ b/src/components/nodes/workflow/PointCloudOutputNode.svelte @@ -1,13 +1,14 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Point Cloud'} - -
+ {/snippet} {#if hasData} @@ -289,37 +270,37 @@ event.stopPropagation()} onwheel={(event) => event.stopPropagation()} > -
+
{pointCount.toLocaleString()} points
{#if renderError} -
+
3D preview unavailable
{/if}
{:else} -
+
No point cloud yet
{/if} -
+
- + {#if isUsingDefaultFormat && defaultFormat} - Default {defaultFormat.format_id} + Default {defaultFormat.format_id} {:else if formatOverride} - Override + Override {/if}
- - diff --git a/src/components/nodes/workflow/TextInputNode.svelte b/src/components/nodes/workflow/TextInputNode.svelte index 53ac25daf..117d097fe 100644 --- a/src/components/nodes/workflow/TextInputNode.svelte +++ b/src/components/nodes/workflow/TextInputNode.svelte @@ -1,5 +1,6 @@ -
+
{#snippet header()} -
-
- - - -
- {data.label || 'Text Input'} -
+ {/snippet} {#if isTextConnected} -
+
Connected to external input
{:else}
{#if targetPort} -
{targetPort.label}
+
{targetPort.label}
{/if} {#if parseError} -
{parseError}
+
{parseError}
{/if} {/if}
- - diff --git a/src/components/nodes/workflow/VectorOutputNode.svelte b/src/components/nodes/workflow/VectorOutputNode.svelte index eded7f725..0d0cd2a8c 100644 --- a/src/components/nodes/workflow/VectorOutputNode.svelte +++ b/src/components/nodes/workflow/VectorOutputNode.svelte @@ -1,7 +1,7 @@
{#snippet header()} -
-
- - - -
- {data.label || 'Vector Output'} - -
+ {/snippet} {#if vector} -
{vector.length} dimensions
-
+
{vector.length} dimensions
+
[{preview}{#if hasMore}, ...{/if}]
{:else} -
+
No vector yet
{/if} @@ -79,15 +61,6 @@
diff --git a/src/components/workbench/GraphPage.svelte b/src/components/workbench/GraphPage.svelte index 8b71a6266..27cadffc0 100644 --- a/src/components/workbench/GraphPage.svelte +++ b/src/components/workbench/GraphPage.svelte @@ -1,31 +1,673 @@ + + -
- - {#if $activeWorkflowRun} -
- Editing the current workflow. Selected run remains - {$activeWorkflowRun.workflow_run_id} - for Scheduler, Diagnostics, I/O Inspector, Library, and Network pages. -
+{#snippet modeSwitch()} + + + +{/snippet} + +{#snippet panelToggles()} + {#if mode === 'edit'} + {/if} - {#if $graphSessionError} -
- {$graphSessionError} -
+ +{/snippet} + +{#snippet portList(ports: { direction: string; id: string; label: string; dataType: string | null }[])} + {#if ports.length === 0} +

This node has no ports.

+ {:else} +
+ {#each ports as port (`${port.direction}:${port.id}`)} +
{port.direction}
+
{port.label}{#if port.dataType}{port.dataType}{/if}
+ {/each} +
+ {/if} +{/snippet} + +
+ void editCurrentVersion()} + /> + + {#if resolution.workflowMismatch && activeRun?.workflow_id} +

+ The selected run is of {activeRun.workflow_id}, not {$currentGraphName}. + + or keep editing {$currentGraphName}. +

{/if} -
- {#if !$isReadOnly} - + +
+ {#if mode === 'edit'} + {#if paletteOpen && !$isReadOnly} + + {/if} + +
+ +
+ + {#if propertiesOpen} +
+ {#if editNode} + {@const editNodeId = editNode.id} +
+
+
{editNodeLabel}
+
{editNode.type ?? ''} · {editNode.id}
+
+
+

Settings

+

Edit this node's settings on its card in the canvas.

+
+
+

Ports

+ {@render portList([ + ...(editDefinition?.inputs ?? []).map((port) => ({ direction: 'in', id: port.id, label: port.label, dataType: port.data_type })), + ...(editDefinition?.outputs ?? []).map((port) => ({ direction: 'out', id: port.id, label: port.label, dataType: port.data_type })), + ])} +
+
+
+ + removeEditNode(editNodeId)} + /> +
+ {:else} +

+ {$selectedNodeIds.length > 1 + ? `${$selectedNodeIds.length} nodes are selected. Select one node to see its ports.` + : 'Select a node to see its ports.'} +

+ {/if} +
+ {/if} + {:else} +
+ {#if runState.status === 'error' && runState.runId === runId} +
+ runId && void loadRunGraph(runId)} + /> +
+ {:else if runState.status === 'missing' && runState.runId === runId} + setMode('edit')} + /> + {:else if shownRunGraph} + (selectedRunNodeId = nodeId)} + /> + {:else} +
Loading the graph as this run used it…
+ {/if} +
+ + {#if propertiesOpen} +
+ {#if runFacts && shownRunGraph} +
+
+
{runFacts.label}
+
{runFacts.nodeType} · {runFacts.nodeId}
+
{runFacts.stateLabel}
+
+
+

Settings

+ {#if runFacts.settings.length > 0} + + {/if} + {#if runFacts.settingsNote} +

{runFacts.settingsNote}

+ {/if} +

+ Values as they were when the run started. Switch to Edit workflow to change them. +

+
+
+

Ports

+ {@render portList(runFacts.ports)} +
+
+

In this run

+

{runFacts.runSentence}

+ {#if runFacts.runRows.length > 0} + + {/if} + {#each runFacts.staleMessages as message, index (index)} +

Stale graph fact: {message}

+ {/each} +
+ + +
+
+
+

Snapshot

+

+ {shownRunGraph.workflow_run_id} +

+ + {#if runState.statusError} +

+ {runState.statusesAvailable ? 'Node status could not be refreshed' : 'Node status is unavailable'}: {runState.statusError} +

+ {:else if liveStatusUpdates === 'unavailable'} +

Node status updates arrive only when the run is opened again.

+ {/if} +
+
+ {:else} +

+ {shownRunGraph ? 'Select a node to see its facts in this run.' : 'Node facts appear once the run graph has loaded.'} +

+ {/if} +
+ {/if} {/if} -
- -
+ + diff --git a/src/components/workbench/IoInspectorPage.svelte b/src/components/workbench/IoInspectorPage.svelte index c3335f0f2..a3dfc0547 100644 --- a/src/components/workbench/IoInspectorPage.svelte +++ b/src/components/workbench/IoInspectorPage.svelte @@ -1,20 +1,11 @@ -
-
-
-

I/O Inspector

-
- {#if $activeWorkflowRun} - {$activeWorkflowRun.workflow_run_id} - {:else} - Select a workflow run in Scheduler to inspect node I/O - {/if} -
-
-
- - -
-
+ function toggleNode(nodeId: string): void { + collapsedNodes = { ...collapsedNodes, [nodeId]: !collapsedNodes[nodeId] }; + } - {#if inspectorError} -
{inspectorError}
- {/if} + function toggleSavedInspection(): void { + savedInspectionOpen = !savedInspectionOpen; + if (savedInspectionOpen && !activeRunId()) { + void refreshSavedGraphInspectionMode(); + } + } - {#if !$activeWorkflowRun} -
-
- -
- {savedWorkflowOptions.length} saved workflows with stable ids -
-
+ function readHintFor(entry: IoInspectorTreeEntry): string { + const family = buildIoArtifactRendererSummary(entry.artifact).family; + if (canReadIoArtifactBody(entry.artifact)) { + return family === 'image' + ? 'Read body loads the full image.' + : `Read body shows the first ${PREVIEW_LIMIT_LABEL}.`; + } + if (entry.artifact.stream_handle) { + return 'Read stream shows what has been written so far.'; + } + return ''; + } + - {#if loadingInspector && !savedGraphModel} -
- Loading saved graph inspection -
- {:else if savedGraphModel} - { - selectNode(nodeId); - }} +
+ {#if !$activeWorkflowRun} + +
+
+ openRunContextPicker()} /> - {:else if savedWorkflows.length === 0} -
- No saved workflows are available for inspection. -
- {:else} -
- Saved workflows need backend-listed stable ids before inspection. -
- {/if} -
- {:else} -
-
- {#if loadingInspector && !runGraph} -
Loading run snapshot
- {:else if !runGraph} -
- No versioned graph captured for this run +
+
+ + {#if savedInspectionOpen} +
+
+ + + {savedWorkflowOptions.length} + {savedWorkflowOptions.length === 1 ? 'saved workflow' : 'saved workflows'} with stable ids + + +
+
+ {#if savedGraphError} +
+ void refreshSavedGraphInspectionMode()} + /> +
+ {:else if loadingSavedGraph && !savedGraphModel} +
Loading the saved graph.
+ {:else if savedGraphModel} + { + savedSelectedNodeId = nodeId; + }} + /> + {:else if savedWorkflows.length === 0} +
No saved workflows are available for inspection.
+ {:else} +
Saved workflows need backend-listed stable ids before inspection.
+ {/if} +
- {:else} - { - selectNode(nodeId); - }} - /> {/if}
+
+ {:else} +
+ +
-
-
-
-
-

- {selectedNodeId ? `Node I/O: ${selectedNodeId}` : 'Node I/O'} -

-
- {formatProjectionFreshness(projectionState)} - {#if summarizedArtifactCount > 0} - · {summarizedArtifactCount} retained artifacts in run - {/if} -
-
-
-
+ + {#if downloadLink} + + {/if} +
+ + diff --git a/src/components/workbench/LibraryPage.svelte b/src/components/workbench/LibraryPage.svelte index 7985c8dc6..d1ba959c9 100644 --- a/src/components/workbench/LibraryPage.svelte +++ b/src/components/workbench/LibraryPage.svelte @@ -1,10 +1,9 @@ -
-
-
-

Library

-
- {#if $activeWorkflowRun} - {$activeWorkflowRun.workflow_run_id} +
+ + +
+ + {#snippet top()} +
+ {#if hfMode} + + + {:else} + + + {/if} + +
+ {#if hfMode} +
{ + event.preventDefault(); + void searchHfModels(); + }} + > + + + +
+
Searching Hugging Face. Results download into the Pumas library on this machine.
+ {:else if kindOptions} + (kindFilter = next)} /> + {/if} + {/snippet} + + {#if hfMode} +
+ + {#if downloadOptionsOpen} +
+ + + +
Applied to the next Download. A blank name uses the repository id.
+
+ {/if} +
+ + {#if !hfSearched} +

Search by name or task, then download a result into the Pumas library.

{:else} - No active run selected + {#each hfRows as result (result.repoId)} + {@const downloadId = requestedDownloads[result.repoId]} +
+ + {result.repoId} + {#if result.sub}{result.sub}{/if} + + {result.size ?? ''} + {#if downloadId} + + {:else} + + {/if} +
+ {/each} +

{formatHfResultCountLine(hfRows.length, hfSearchedLimit)}

+ {/if} + {:else} + {#if pumasError} +

The Pumas model list could not be read. {pumasError}

+ {/if} + {#if usageError} +

+ {projectionState ? 'Usage could not be read, so rows show the last usage projection.' : 'Usage could not be read.'} + {usageError} +

+ {/if} + {#if pumasLoading && modelRows.length === 0} +

Loading the Pumas model list.

+ {:else if modelRows.length === 0 && !pumasError} +
+

No models in the Pumas library on this machine yet.

+ +
+ {:else if visibleRows.length === 0 && modelRows.length > 0} +

No models match this search.

{/if} -
-
- -
-
- {formatLibraryProjectionFreshness(projectionState)} -
+ {#each groups as group (group.key)} + {@const expanded = !collapsedGroups[group.key]} + toggleGroup(group.key)} + /> + {#if expanded} +
+ {#each group.rows as row (row.modelId)} + {@const lastUsedByActive = row.usage !== null && isLibraryAssetLastUsedByRun(row.usage, activeRunId)} + + {/each} +
+ {/if} + {/each} + {/if} - {#if error} -
{error}
- {/if} - {#if pumasError} -
{pumasError}
- {/if} - -
-
-
- - - - -
- {#if hfSearchResults.length > 0} -
- {#each hfSearchResults.slice(0, 8) as model, index (model.id ?? index)} - - {modelLabel(model)} + {#snippet footer()} +
+
+ + + Usage {lowerFirst(freshness)}{liveUpdatesError ? ', not updating live' : ''} - {/each} +
+ {#if actionError || actionMessage} +
+ {actionError ?? actionMessage} +
+ {/if}
- {/if} -
- -
- - - - - -
- -
- - - {#if actionMessage || actionError} -
- {actionError ?? actionMessage} + {/snippet} + + + + {#if !selectedRow} +

+ {modelRows.length === 0 + ? 'Models appear here once the Pumas library lists them.' + : 'Pick a model to see where it lives and how it is used.'} +

+ {:else} + {@const row = selectedRow} + {@const usageRows = libraryModelUsageRows(row, nowMs)} + {@const sourceRows = libraryModelSourceRows(row, nowMs)} + {@const workflowRows = libraryWorkflowUseRows(row, activeRunId, nowMs)} + {@const chips = libraryModelChips(row, activeRunId)} +
+
+

{row.name}{#if row.modelType}{row.modelType}{/if}

+
{row.modelId}
+ {#if chips.length > 0} +
+ {#each chips as chip (chip)} + {chip} + {/each} +
+ {/if} +
+
+ + + + {#key row.modelId} + void deleteModel(row)} + /> + {/key} +
- {/if} -
-
-
-
-

Pumas Models

- {pumasModels.length} -
-
- - - - - - - - - - {#if pumasLoading} - - - - {:else if pumasModels.length === 0} - - - +
+
+

Where it lives

+ +
+
+

How it is used

+ {#if usageRows.length > 0} + + {:else if usageError} +
Usage could not be read. {usageError}
+ {:else} +
No usage recorded for this model.
+ {/if} +
+
+ +
+

Workflows that use it

+ {#if workflowRows.length > 0} +
ModelPathDetails
Loading Pumas models
No Pumas models found
+ + + + + + + + + + {#each workflowRows as use (use.key)} + + + + + + + {/each} + +
WorkflowLast runRunsLast used
+ {use.workflowId ?? 'Unknown workflow'}{#if use.version}v{use.version}{/if} + {#if use.isActiveRun}Last used by active run{/if} + + {#if use.runId} + {use.runId} + {:else} + Not recorded + {/if} + {use.runCount}{use.lastUsed}
+
The usage projection keeps the most recent workflow and run for each model.
+ {:else if usageError} +
Usage could not be read. {usageError}
{:else} - {#each pumasModels as model, index (`${model.value}-${index}`)} - - -
{model.label}
- - -
- {model.value} -
- - - {model.description ?? 'Unavailable'} - - - {/each} +
No workflow run has used this model yet.
{/if} - - -
-
- -
- - - - - - - - - - - - - - - - {#if loading} - - - - {:else if assets.length === 0} - - - - {:else} - {#each assets as asset (asset.asset_id)} - {@const activeRunMatch = isLibraryAssetLastUsedByRun(asset, $activeWorkflowRun?.workflow_run_id)} - - - - - - - - - - - - {/each} - {/if} - -
AssetCategoryOperationAccessesRunsNetworkLast WorkflowLast RunLast Accessed
Loading Library usage
No Library usage recorded
-
- {asset.asset_id} -
- {#if activeRunMatch} -
Last used by active run
- {/if} -
- {formatLibraryAssetCategory(asset.asset_id)} - {asset.last_operation}{asset.total_access_count}{asset.run_access_count}{formatLibraryBytes(asset.total_network_bytes)} - {asset.last_workflow_id ?? 'Unavailable'} - - {asset.last_workflow_run_id ?? 'Unavailable'} - {formatTimestamp(asset.last_accessed_at_ms)}
+
+ +
+

Source

+ {#if sourceRows.length > 0} + + {:else} +
The Pumas library records no source for this model.
+ {/if} +
+ {/if} +
-
+
+ + diff --git a/src/components/workbench/NetworkPage.svelte b/src/components/workbench/NetworkPage.svelte index 414b51ade..4ec730d5f 100644 --- a/src/components/workbench/NetworkPage.svelte +++ b/src/components/workbench/NetworkPage.svelte @@ -1,6 +1,5 @@ -
-
-
-

Network

-
- {localNode?.display_name ?? 'Local Pantograph'} -
-
- -
+{#snippet nodeRow(entry: NetworkNodeEntry)} + (requestedNodeId = entry.nodeId)} + /> +{/snippet} - {#if error} -
{error}
- {/if} - -
- {#if !status && loading} -
Loading local status
- {:else if localNode} -
-
-
-
- {localNode.display_name} -
-
- Captured {formatNetworkTimestamp(localNode.captured_at_ms)} -
+{#snippet degraded(lines: string[])} + {#each lines as line (line)} +

{line}

+ {/each} +{/snippet} + +{#snippet sectionStatus(loadingNow: boolean, failure: string | null, freshness: string)} + {loadingNow ? 'Refreshing' : freshness} + {#if failure}

{failure}

{/if} +{/snippet} + +
+ + +
+ + {#snippet top()} +
+ + + +
+ {/snippet} + + {#if groups} + (localExpanded = !localExpanded)} + /> + + (peersExpanded = !peersExpanded)} + /> + + {:else} +

+ {loading ? 'Reading the local status.' : 'Nodes appear here once the local status can be read.'} +

+ {/if} + + {#snippet footer()} + + Trusted peers only + {/snippet} +
+ + + {#if !localNode} +
+
+
Network
+

+ {statusFailure ?? 'Reading the local status.'} +

- {#if $activeWorkflowRun} -
- {$activeWorkflowRun.workflow_run_id} - {formatSelectedRunLocalState(localNode, $activeWorkflowRun.workflow_run_id)} +
+ +
+
+ {:else if peerDetail} +
+
+
{peerDetail.header.title} {peerDetail.header.nodeId}
+
{peerDetail.header.subtitle}
+
+ {peerDetail.header.transportLabel} + {#each peerDetail.header.chips as chip (chip)}{chip}{/each}
- {/if} +
+
+ + +
+ {#if statusFailure}

{statusFailure}

{/if} - {#if localNode.degradation_warnings.length > 0} -
-

Degraded Metrics

-
    - {#each localNode.degradation_warnings as warning (warning)} -
  • {warning}
  • - {/each} -
+
+

Details

+

{peerDetail.note}

+
+ + {#if selectedRunOnPeer} +
+

{selectedRunOnPeer.heading}

+

{selectedRunOnPeer.sentence}

{/if} -
-
-
Transport
-
- {formatTransportState(localNode.transport_state)} -
-
{status.peer_nodes.length} peers
-
-
-
CPU
-
- {localNode.system.cpu.logical_core_count} cores -
-
- {formatCpuUsage(localNode.system.cpu.average_usage_percent)} +
+

Identity

+ +
+ {:else if localHeader && degradations} +
+
+
{localHeader.title} {localHeader.nodeId}
+
{localHeader.subtitle}
+
+ {localHeader.transportLabel} + {#each localHeader.chips as chip (chip)}{chip}{/each}
-
-
Memory
-
- {formatNetworkBytes(localNode.system.memory.used_bytes)} -
-
- {formatNetworkBytes(localNode.system.memory.available_bytes)} available -
+
+
-
-
Scheduler
-
- {formatSchedulerLoad(localNode)} -
-
- {formatSessionLoad(localNode)} +
+ {#if statusFailure}

{statusFailure}

{/if} + {#if subscriptionError} +

+ Live updates for the selected run are off ({subscriptionError}). Use Refresh to update. +

+ {/if} + {#if degradations.node.length > 0} +
{@render degraded(degradations.node)}
+ {/if} + +
+ {#each statCells as cell (cell.id)} +
+
{cell.value}
+
{cell.label}
+ {#if cell.meterPercent !== null} + + {/if} + {#if cell.id === 'cpu'}{@render degraded(degradations.cpu)}{/if} + {#if cell.id === 'memory'}{@render degraded(degradations.memory)}{/if}
-
+ {/each}
-
-
-

Local Capabilities

-
- {#each factRows as row (row.label)} -
-
{row.label}
-
{row.value}
-
+
+

Devices

+ + +

{DEVICE_MEMORY_NOT_REPORTED}

+ {@render degraded(degradations.devices)} +
+ +
+ {#if !$activeWorkflowRun || !selectedRunOnNode} +

Selected run

+

+ No run selected. Pick one to see its placement, execution and resources on this node. +

+ + {:else} +

{selectedRunOnNode.heading}

+
+
Run
+
{selectedRunOnNode.runId}
+
State
+
{selectedRunOnNode.state}
+ {#each selectedRunOnNode.rows as row (row.key)} +
{row.key}
+
{row.value}
{/each}
-
- -
- {#if $activeWorkflowRun} -
-

Selected Run Placement

-
- {#each selectedRunPlacementRows as row (row.label)} -
-
{row.label}
-
- {row.value} -
-
- {/each} -
-
- -
-
-
-

Selected Run Execution

-
- {formatNetworkProjectionFreshness(selectedRunNodeStatusProjectionState)} -
-
- {#if nodeStatusLoading} -
- {#if nodeStatusError} -
{nodeStatusError}
- {/if} - {#if nodeStatusLoading && selectedRunExecutionRows.length === 0} -
Loading selected-run execution state
- {:else if selectedRunExecutionRows.length === 0} -
No selected-run node status projected
- {:else} -
- - - - - - - - - - - {#each selectedRunExecutionRows as row (row.nodeId)} - - - - - - - {/each} - -
NodeStatusRuntimeModel
-
{row.nodeId}
-
- - {row.status} - - -
{row.runtime}
-
-
{row.model}
-
-
- {/if} -
- -
-
-
-

Selected Run Resources

-
- {formatLibraryProjectionFreshness(selectedRunResourceProjectionState)} -
-
- {#if resourceLoading} -
- {#if resourceError} -
{resourceError}
- {/if} - {#if resourceLoading && selectedRunResourceRows.length === 0} -
Loading selected-run resources
- {:else if selectedRunResourceRows.length === 0} -
No selected-run Library usage projected
- {:else} -
- - - - - - - - - - - - {#each selectedRunResourceRows as resource (resource.assetId)} - - - - - - - - {/each} - -
AssetCategoryCacheNetworkRun Access
-
- {resource.assetId} -
-
{resource.category} - - {resource.cacheStatus} - - {resource.networkBytes}{resource.accessCount}
-
- {/if} -
+ {#if selectedRunOnNode.note} +

{selectedRunOnNode.note}

{/if} -
-
-

Disks

-
- {#if localNode.system.disks.length === 0} -
Disk metrics unavailable
- {:else} -
- - - - - - - - - - - {#each localNode.system.disks as disk (disk.name + disk.mount_point)} - - - - - - - {/each} - -
NameMountTotalAvailable
{disk.name}{disk.mount_point}{formatNetworkBytes(disk.total_bytes)}{formatNetworkBytes(disk.available_bytes)}
-
+
+

Execution

+ {@render sectionStatus( + nodeStatusLoading, + nodeStatusError ? describeRunProjectionFailure('node status for this run', nodeStatusError) : null, + formatNetworkProjectionFreshness(selectedRunNodeStatusProjectionState), + )} +
+ {#if executionRows.length === 0} + {#if !nodeStatusError} +

+ {nodeStatusLoading ? 'Reading node status.' : 'No node status is projected for this run yet.'} +

{/if} -
- -
-
-

Network Interfaces

-
- {#if localNode.system.network_interfaces.length === 0} -
Interface metrics unavailable
- {:else} -
- - - - - - + {:else} +
+
NameReceivedTransmitted
+ + + + + {#each executionRows as row (row.nodeId)} + + + + + - - - {#each localNode.system.network_interfaces as networkInterface (networkInterface.name)} - - - - - - {/each} - -
NodeStatusRuntimeModel
{row.nodeId}{row.status}{row.runtime}{row.model}
{networkInterface.name} - {formatNetworkBytes(networkInterface.total_received_bytes)} - - {formatNetworkBytes(networkInterface.total_transmitted_bytes)} -
-
+ {/each} + + +
+ {/if} + +
+

Resources

+ {@render sectionStatus( + resourceLoading, + resourceError ? describeRunProjectionFailure('library usage for this run', resourceError) : null, + formatNetworkProjectionFreshness(selectedRunResourceProjectionState), + )} +
+ {#if resourceRows.length === 0} + {#if !resourceError} +

+ {resourceLoading ? 'Reading library usage.' : 'No library usage is projected for this run yet.'} +

{/if} -
- -
-
-
-

Selected Run Events

-
- {formatSchedulerProjectionFreshness(timelineProjectionState)} -
-
- {#if timelineLoading} -
+ + {#if $activeWorkflowRun} +
+

+ + + {timelineLoading ? 'Refreshing' : formatNetworkProjectionFreshness(timelineProjectionState)} + +

+
+
+
+ {/if} -
-
-

Peers

-
- {#if status.peer_nodes.length === 0} -
No trusted peers connected
- {:else} -
- {#each status.peer_nodes as peer (peer.node_id)} -
-
{peer.node_id}
-
{formatTransportState(peer.transport_state)}
-
+
+
+

Disks

+ {#if diskRows.length === 0} +

Disk metrics are not reported.

+ {:else} + + + + {#each diskRows as disk (disk.key)} + + + + + {/each} - - {/if} - + +
MountFreeTotal
{disk.mount}{disk.free}{disk.total}
+ {/if} + {@render degraded(degradations.disks)} +
+
+

Interfaces

+ {#if interfaceRows.length === 0} +

Interface metrics are not reported.

+ {:else} + + + + {#each interfaceRows as networkInterface (networkInterface.name)} + + + + + + {/each} + +
NameReceivedSent
{networkInterface.name}{networkInterface.received}{networkInterface.sent}
+ {/if} + {@render degraded(degradations.interfaces)}
-
- {:else} -
Local status unavailable
- {/if} + +
+

Identity

+ +
+ {/if} +
-
+ + + diff --git a/src/components/workbench/NodeLabPage.svelte b/src/components/workbench/NodeLabPage.svelte index ffb8f1863..064c09885 100644 --- a/src/components/workbench/NodeLabPage.svelte +++ b/src/components/workbench/NodeLabPage.svelte @@ -1,23 +1,640 @@ -
-

Node Editor

-
- {nodeLabUnavailableMessage()} +
+ + + + +
+ + {#snippet top()} + + {/snippet} + + {#each list.groups as group (group.id)} + (builtInExpanded = !builtInExpanded)} + /> + + {/each} + {#if list.emptyText} +

{list.emptyText}

+ {/if} + + {#snippet footer()} + Built-in nodes are read-only. This is the list the Graph palette offers. + {/snippet} +
+ + {#if view} + +
+
+

{view.label}

+
{view.nodeType}
+
+
+ + +
+
+ +
+ + + + + +
+ +
+

Inputs

+ {#if view.inputs.length > 0} + + + + + + + + + + + + {#each view.inputs as port (port.id)} + + + + + + + + {/each} + +
NameTypeDefaultRequiredRemove
+ + {#if port.idNote || port.description} + + {#if port.idNote}{port.idNote}{/if}{#if port.idNote && port.description}, {/if}{port.description ?? ''} + + {/if} + {port.requirement} + +
+ {:else} +

This node has no inputs.

+ {/if} + +
+ +
+

Outputs

+ {#if view.outputs.length > 0} + + + + + + + + + + {#each view.outputs as port (port.id)} + + + + + + {/each} + +
NameTypeRemove
+ + {#if port.idNote || port.description} + + {#if port.idNote}{port.idNote}{/if}{#if port.idNote && port.description}, {/if}{port.description ?? ''} + + {/if} + + +
+ {:else} +

This node has no outputs.

+ {/if} + +
+ +
+

Implementation

+
{view.implementationText}
+
+
+ + + {#snippet top()} +
+

On the canvas

+ preview +
+ {/snippet} + +
+
+
+ + {view.label} + {view.nodeType} +
+
+
+ {#each view.inputs as port (port.id)} +
{port.label}
+ {/each} +
+
+ {#each view.outputs as port (port.id)} +
{port.label}
+ {/each} +
+
+
+
+ +
+

Checks

+
    + {#each view.checks as check (check.text)} +
  • {check.text}
  • + {/each} +
+
+ +
+

Try it

+

+ Runs the node once with sample inputs on the local engine, outside any workflow. +

+ +
+
+ {:else} + + {/if}
-
- {#each statusRows as row (row.label)} -
-
{row.label}
-
{row.value}
-
- {/each} -
-
+ + + diff --git a/src/components/workbench/README.md b/src/components/workbench/README.md new file mode 100644 index 000000000..03b5f4112 --- /dev/null +++ b/src/components/workbench/README.md @@ -0,0 +1,108 @@ +# Workbench + +## Purpose + +The run-centric workbench is the only root workspace of the Pantograph desktop +GUI (ADR-014). This directory holds the shell, the pages that hang off its tab +bar, and the pure presenters that turn backend projections into what each page +renders. + +## Contents + +| Path | Responsibility | +| --- | --- | +| `WorkbenchShell.svelte` | Header (brand, tab groups, run-context picker, engine line, Settings, Assistant toggle) and the page switch. | +| `*Page.svelte` | One page per tab. Each consumes typed projection services and its own presenters. | +| `*Presenters.ts` + `*.test.ts` | Pure projection-to-view logic for one page, tested with the Node test runner. | +| `shell/` | Run-context picker, its run-list source and the run-id clipboard shortcuts. See `shell/README.md`. | +| `ui/` | Shared presentation parts every page composes (panels, rows, glyphs, segments, lanes, log lines). See `ui/README.md`. | +| `GraphPage.svelte`, `RunGraphSnapshot.svelte`, `runGraphPresenters.ts`, `graphInspectionPresenters.ts` | Graph tab: edit mode over the editable graph stores, read-only run mode over the run graph and node status projections (ADR-014). | +| `SessionsPage.svelte` | Sessions tab: saved workflows and orchestrations shown as sessions with their runs from the run-context run list. No session service exists, so session actions are disabled (see `docs/plans/workbench-redesign/reports/m8-sessions.md`). | + +## Problem + +Pages used to repeat the active run in their own headers, style themselves +with per-page Tailwind greys and `!important` overrides, and each invent status +colours. The approved redesign (`docs/design/workbench-redesign-spec.md`) needs +one shell, one run selection control and one set of parts so pages built in +parallel come out as one system. + +## Constraints + +- ADR-014: the active run is transient frontend state in + `src/stores/workbenchStore.ts`; pages read typed projection services and + never query `diagnostic_events` or parse `payload_json` for primary facts. +- Historic run graphs render in an isolated read-only surface and never touch + the editable graph store. +- Svelte 5 runes and snippets; Tailwind 3 with the `pg-*` tokens from + `src/styles.css`; native interactive elements only + (`scripts/check-svelte-a11y.mjs`). + +## Decision + +The shell owns navigation and the run context; pages own their projection and +layout; `ui/` owns visual primitives. Pages compose `ui/` parts and call the +run-context actions in `shell/runContextStore.ts`; they do not build their own +selection controls or status colours. The heading set of this README is +required by `scripts/check-decision-traceability.sh` (issue WR-001 in +`docs/plans/workbench-redesign/issues.md`); its content is the boundary +description for this directory. + +## Alternatives Rejected + +- Keeping the icon rail and a per-page "Active Run" label: it showed the + selection twice and gave no grouping of tabs. +- Letting each page style its own rows and glyphs: the redesign mockups depend + on one glyph vocabulary and one row shape across tabs. + +## Invariants + +- Graph run mode never writes the editable graph store; it reads only the run graph and node status projections for the selected run. +- The Scheduler reads the shell's `runContextRunList` as its only run-list source; it never queries `workflow_run_list_query` itself (WR-005). Diagnostics, I/O Inspector, Network, Library and Sessions keep their own projection queries and never read the diagnostic ledger directly (ADR-014). + +- Scheduler is the default page; page ids and their order come from + `WORKBENCH_PAGES` in `src/stores/workbenchStore.ts`. +- Exactly one run-context picker is mounted (by the shell); pages open it with + `openRunContextPicker()` instead of rendering their own. +- While the engine is unreachable the page area dims to 72% opacity and pages + keep their last projection instead of blanking. +- Presenters stay pure: no services, stores, DOM or timers. + +## Revisit Triggers + +- A page needs a projection field the backend does not expose (record it in + the plan's `issues.md` before working around it). +- A second root workspace is proposed alongside the workbench. + +## Dependencies + +**Internal:** `src/stores/workbenchStore.ts`, `src/stores/panelStore.ts`, +`src/services/workflow/WorkflowService.ts` and the diagnostics projection types +in `src/services/diagnostics/types.ts`. + +**External:** `svelte`, `lucide-svelte`, `@xyflow/svelte` (Graph page only). + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```svelte + + +{#if $activeWorkflowRun} + +{:else} + openRunContextPicker()} + /> +{/if} +``` diff --git a/src/components/workbench/RunGraphSnapshot.svelte b/src/components/workbench/RunGraphSnapshot.svelte index cab6768c7..381a574c2 100644 --- a/src/components/workbench/RunGraphSnapshot.svelte +++ b/src/components/workbench/RunGraphSnapshot.svelte @@ -1,395 +1,435 @@ -
-
-
-
- {formatRunGraphCountLabel(counts)} - {presentationLabel} - Snapshot {formatRunGraphTimestamp(runGraph.snapshot_created_at_ms)} -
-
+{#snippet card(node: RunGraphSnapshotNode)} + + + {node.label} + {node.nodeType} + + + {#each node.inputs as port (port.id)} + {port.label} + {/each} + {#each node.outputs as port (port.id)} + {port.label} + {/each} + {#if node.hiddenPortCount > 0} + {node.hiddenPortCount === 1 ? '1 more port' : `${node.hiddenPortCount} more ports`} + {/if} + {#if node.note} + {node.note} + {/if} + +{/snippet} -
-
- {#if canvas.nodes.length === 0} -
No graph nodes captured
- {:else} - - - - - - - {#each canvas.edges as edge (edge.id)} - 0 ? '3' : '2'} - stroke-opacity={edge.staleDiagnosticCount > 0 ? '0.9' : '0.65'} - marker-end="url(#run-graph-arrow)" +
+
+ {#if layout.nodes.length === 0} +

This run captured no graph nodes.

+ {:else} +
+
+ - {/if} + {#each layout.nodes as node (node.id)} + {#if onSelectNode} + + {:else} +
+ {@render card(node)} +
+ {/if} + {/each} +
-
+ {/if}
- {#if !compact} - {/if}
+ + diff --git a/src/components/workbench/SavedGraphInspectionSnapshot.svelte b/src/components/workbench/SavedGraphInspectionSnapshot.svelte index e06974b60..b459ac0c5 100644 --- a/src/components/workbench/SavedGraphInspectionSnapshot.svelte +++ b/src/components/workbench/SavedGraphInspectionSnapshot.svelte @@ -1,12 +1,14 @@ -
-
- - {#each model.canvas.edges as edge (edge.id)} - 0 ? '3' : '2'} - stroke-opacity={edge.staleDiagnosticCount > 0 ? '0.9' : '0.65'} - /> - {/each} - +
+
+
+ {#each model.canvas.nodes as node (node.id)} - selectNode(node.id)} - onkeydown={(event) => handleNodeKeydown(event, node.id)} + onclick={() => onSelectNode?.(node.id)} > - 0 ? '2.5' : '1.5'} - /> - - {node.id} - - - {node.nodeType} - - {#if node.staleDiagnosticCount > 0} - - - ! - + {node.id} + {node.nodeType} + {#if node.staleBadgeLabel} + {node.staleBadgeLabel} {/if} - + {/each} - +
-
+ + diff --git a/src/components/workbench/SchedulerPage.svelte b/src/components/workbench/SchedulerPage.svelte index 812f79075..986534470 100644 --- a/src/components/workbench/SchedulerPage.svelte +++ b/src/components/workbench/SchedulerPage.svelte @@ -1,6 +1,6 @@ -
-
-
-

Scheduler

-
- Projection updated {projectionUpdatedAtMs ? formatSchedulerTimestamp(projectionUpdatedAtMs) : 'when runs are available'} -
-
- -
+
+ - {#if error} -
{error}
+ {#if $schedulerViewPreferences.showLanes} +
+ local + {DEVICE_MEMORY_UNAVAILABLE} +
{/if} -
-
- - setSchedulerRunFilters({ search: eventValue(event) })} - class="mt-2 w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-sm text-neutral-100 focus:border-cyan-500 focus:outline-none" - /> -
-
- - setSchedulerRunFilters({ search: eventValue(event) })} + /> + + +
+ setSchedulerRunFilters({ statusSegment: segment })} + /> + {#if filterChips.length > 0} +
+ {#each filterChips as chip (chip.key)} + setFilter(chip.key, DEFAULT_SCHEDULER_RUN_FILTERS[chip.key])} /> + {/each} + {#if filterChips.length > 1} + + {/if} +
+ {/if} + {#if filtersOpen} +
+ {#each filterFields as field (field.key)} + + {/each} +
+ {/if} + {#if liveUpdatesUnavailable} +
Live updates are unavailable here; use Refresh to update.
+ {/if} + {/snippet} + + {#if !listLoaded} + {#if $runContextRunList.errorMessage} +
+ void refreshRunContextRunList()} + /> +
+ {:else if listUnreachable} +
+

The run list is unavailable because the engine did not answer.

+ +
+ {:else} +
Loading runs…
+ {/if} + {:else} + {#if $runContextRunList.errorMessage} +
+ void refreshRunContextRunList()} + /> +
+ {/if} + {#if runs.length === 0} +
No runs yet. Runs appear here once a workflow is submitted.
+ {:else if runGroups.length === 0} +
+

No runs match the search and filters.

+ +
+ {:else} + {#each runGroups as group (group.id)} + {@const expanded = !collapsedGroups[group.id]} + toggleGroup(group.id)} + /> + {#if expanded} +
+ {#each group.rows as row (row.runId)} + selectRunContext(row.record)} + /> + {/each} +
+ {/if} {/each} - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
+ {/if} + {/if} -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - {#if loading} - - - - {:else if runs.length === 0} - - - - {:else if displayedRuns.length === 0} - - - + {#snippet footer()} +
+ {#if footerState.kind === 'none'} + {NO_SELECTION_FOOTER} + {:else if footerState.kind === 'missing'} + This run is not in the loaded run list, so no queue actions are offered. + {:else if footerState.kind === 'finished'} + {footerState.workflowId} has finished. No actions available. {:else} - {#each displayedRuns as run (run.workflow_run_id)} -
+ - - - - - - - - - - - - - - - - - - - - - - - {/each} + Dependency readiness + +
GUI admin, acts by run id across sessions
+
+ + + + +
+ + {/if} {/if} - -
RunWorkflowVersionStatusScheduler PolicyRetentionClientSessionBucketRuntimeDeviceNetwork NodeQueuePriorityEstimateCacheReasonQueuedStartedDurationUpdatedOpen
Loading runs
No workflow runs recorded
No matching workflow runs
+ Move to front + + + + +
+ + +
+ +
+ {actionFeedback ?? ''} +
+ {#if moreActionsOpen} +
+
-
- {run.workflow_id} - - {run.workflow_semantic_version ?? run.workflow_version_id ?? 'Unversioned'} - - - {formatSchedulerStatusLabel(run.status)} - - - {formatSchedulerPolicyLabel(run.scheduler_policy_id)} - - {formatSchedulerRetentionLabel(run.retention_policy_id)} - - {formatSchedulerScopeLabel(run.client_id)} - - {formatSchedulerScopeLabel(run.client_session_id)} - - {formatSchedulerScopeLabel(run.bucket_id)} - - {formatSchedulerRuntimePlacementLabel(run)} - - {formatSchedulerDevicePlacementLabel(run)} - - {formatSchedulerPlacementLabel(run.selected_network_node_id)} - {formatSchedulerQueuePosition(run.scheduler_queue_position)}{formatSchedulerPriority(run.scheduler_priority)} - {formatSchedulerEstimateLabel(run)} - - {formatSchedulerModelCacheState(run.model_cache_state)} - - {formatSchedulerReasonLabel(run.scheduler_reason)} - {formatSchedulerTimestamp(run.enqueued_at_ms ?? run.accepted_at_ms)}{formatSchedulerTimestamp(run.started_at_ms)}{formatSchedulerDuration(run.duration_ms, run.status)}{formatSchedulerTimestamp(run.last_updated_at_ms)} -
- - - - -
-
-
- - +
-
+
+ + diff --git a/src/components/workbench/SessionsPage.svelte b/src/components/workbench/SessionsPage.svelte new file mode 100644 index 000000000..82c80bfd8 --- /dev/null +++ b/src/components/workbench/SessionsPage.svelte @@ -0,0 +1,632 @@ + + +
+ + +
+ + {#snippet top()} +
+ + + +
+ (filter = next)} /> + {/snippet} + + {#each groups as group (group.id)} + {@const expanded = !collapsed[group.id]} + toggleGroup(group.id)} + controls={`sessions-group-${group.id}`} + /> + {#if expanded} +
+ {#if group.id === 'saved' && sourceFailure} +
+ void loadSavedSessions()} + /> +
+ {/if} + {#if group.id === 'saved' && loadingSaved} +

Loading saved workflows and orchestrations…

+ {:else} + {#each group.entries as entry (entry.key)} + + {/each} + {#if group.note && !(group.id === 'saved' && sourceFailure && saved.length === 0)} +

{group.note}

+ {/if} + {/if} +
+ {/if} + {/each} + + {#snippet footer()} + + Saved sessions are your saved workflows and orchestrations. Runs stay in the Scheduler history. + + {/snippet} +
+ + + {#if detail && selected} + {@const entry = selected} +
+
+
{detail.title}
+ {#if detail.id !== detail.title} +
{detail.id}
+ {/if} +
+ {detail.stateLabel} + {#each detail.chips as chip (chip)} + {chip} + {/each} +
+
+
+ {#each detail.actions as action (action.id)} + {#if action.id === 'delete' && action.disabledReason === null} + void deleteWorkflow(entry)} + /> + {:else} + + {/if} + {/each} +
+
+ {#if deleteState?.key === entry.key && deleteState.status === 'failed'} +
+ +
+ {/if} + +
+
+

Activity

+ +
+
+

Runs from this session

+ +
+ +
+
+
+ + {#if detail.recentRuns.length > 0} +
+

Recent runs

+
+ {#each detail.recentRuns as row (row.runId)} + selectRunContext(row.record)} + /> + {/each} +
+ {#if detail.moreRunCount > 0} +

+ {detail.moreRunCount} more in Scheduler. Selecting a run makes it the run every tab shows. +

+ {:else} +

Selecting a run makes it the run every tab shows.

+ {/if} +
+ {/if} + +
+

Open in this session

+ {#each detail.open as item (item.name)} +
+ + + {item.name} {item.meta} + {item.sub} + + {#if item.disabledReason} + + {:else} + {@const opening = openState?.key === entry.key && openState.status === 'busy'} + + {/if} +
+ {/each} + {#if openState?.key === entry.key && openState.status === 'failed'} +
+ void openGraph(entry)} + /> +
+ {/if} +
+ +
+

What resumes

+

{detail.resumeSentence}

+
+ {:else} +
+ {sessionDetailEmptyText({ + loading: loadingSaved, + failed: sourceFailure !== null, + savedCount: saved.length, + filter, + query, + })} +
+ {/if} +
+
+
+ + diff --git a/src/components/workbench/SettingsPage.svelte b/src/components/workbench/SettingsPage.svelte index 95c484ee2..b002513dd 100644 --- a/src/components/workbench/SettingsPage.svelte +++ b/src/components/workbench/SettingsPage.svelte @@ -1,6 +1,5 @@ -
-
-
-

Settings

-
- ArtifactStore policy, media artifact defaults, managed inference runtimes, and media dependencies -
-
- -
- - {#if pageError} - +{#snippet sectionNote(error: string | null, message: string | null)} + {#if error} + + {:else if message} +

{message}

{/if} - -
-
-
-
-

Runtime And App Settings

-
- Server connection, model paths, device policy, RAG, and sandbox configuration +{/snippet} + +
+
+ + {#snippet top()} +
+
+

Settings

+

+ ArtifactStore policy, media artifact defaults, managed inference runtimes, and media dependencies +

+
-
-
+ {#if pageError} + + {/if} + {/snippet} + +
+

Runtime and app settings

+

+ Server connection, model paths, device policy, RAG, and sandbox configuration +

+
+
-
+
@@ -776,292 +773,231 @@
{ event.preventDefault(); void saveArtifactPolicy(); }} > -
-
-

ArtifactStore Policy

-
- {policy ? `${policy.policy_id} v${policy.policy_version}` : 'Policy unavailable'} -
+
+
+

ArtifactStore policy

+

+ {#if policy} + {policy.policy_id} v{policy.policy_version} + {:else} + Policy unavailable + {/if} +

-
- {#if policyError} - - {:else if policyMessage} -
- {policyMessage} -
- {/if} + {@render sectionNote(policyError, policyMessage)} -
-
- +
+
-
- + +
-
- + +
-
- + +
-
- + +
- +
{ event.preventDefault(); void saveDiagnosticsRetentionPolicy(); }} > -
-
-

Diagnostics Retention Policy

-
- {diagnosticsRetentionPolicy ? `${diagnosticsRetentionPolicy.policy_id} v${diagnosticsRetentionPolicy.policy_version}` : 'Policy unavailable'} -
+
+
+

Diagnostics retention policy

+

+ {#if diagnosticsRetentionPolicy} + {diagnosticsRetentionPolicy.policy_id} v{diagnosticsRetentionPolicy.policy_version} + {:else} + Policy unavailable + {/if} +

- {#if diagnosticsRetentionError} - - {:else if diagnosticsRetentionMessage} -
- {diagnosticsRetentionMessage} -
- {/if} + {@render sectionNote(diagnosticsRetentionError, diagnosticsRetentionMessage)} -
-
- +
+
-
- + +
+
{#if diagnosticsRetentionSettingRows.length > 0} -
- {#each diagnosticsRetentionSettingRows as row (row.label)} -
-
{row.label}
-
- {row.value} -
-
- {/each} -
+
+ +
{/if} -
-
-
-

Retention Cleanup

-
+
+
+
+

Retention cleanup

+

Apply backend retention cleanup using the current diagnostics retention policy. -

+

{#if diagnosticsRetentionCleanupRows.length > 0} -
- {#each diagnosticsRetentionCleanupRows as row (row.label)} -
-
{row.label}
-
- {row.value} -
-
- {/each} -
+
+ +
{/if}
{ event.preventDefault(); void saveArtifactFormats(); }} > -
-
-

Artifact Format Defaults

-
- Image {capabilityCount(capabilities?.image_formats)} / Audio {capabilityCount(capabilities?.audio_formats)} / Video {capabilityCount(capabilities?.video_formats)} / 3D {capabilityCount(capabilities?.three_d_formats)} -
+
+
+

Artifact format defaults

+

{capabilitySummary}

-
- {#if formatError} - - {:else if formatMessage} -
- {formatMessage} -
- {/if} + {@render sectionNote(formatError, formatMessage)} -
-
-
-

Image

- {formatRangeLabel(selectedImageFormat?.quality_min_percent, selectedImageFormat?.quality_max_percent, '%')} +
+
+
+

Image

+ + {formatRangeLabel(selectedImageFormat?.quality_min_percent, selectedImageFormat?.quality_max_percent, '%')} +
-
-
- +
+
-
- + +
-
- - {#each imageColorProfileOptions as profile (profile)} {/each} -
+
-
-
-

Audio

- {formatRangeLabel(selectedAudioFormat?.bitrate_min_kbps, selectedAudioFormat?.bitrate_max_kbps, ' kbps')} +
+
+

Audio

+ + {formatRangeLabel(selectedAudioFormat?.bitrate_min_kbps, selectedAudioFormat?.bitrate_max_kbps, ' kbps')} +
-
-
- +
+
-
- - {#each audioCodecOptions as codec (codec)} {/each} -
-
- + +
+
-
-
-

Video

- {formatRangeLabel(selectedVideoFormat?.crf_min, selectedVideoFormat?.crf_max)} +
+
+

Video

+ + {formatRangeLabel(selectedVideoFormat?.crf_min, selectedVideoFormat?.crf_max)} +
-
-
- +
+
-
- - {#each videoCodecOptions as codec (codec)} {/each} -
-
- + +
-
- - {#each videoBitDepthOptions as bitDepth (bitDepth)} {/each} -
+
-
-

3D

-
-
-
-
-

Managed Inference Runtimes

-
- Install and select sidecar backends required by scheduler workflows, including llama.cpp. -
+
+

Managed inference runtimes

+

+ Install and select sidecar backends required by scheduler workflows, including llama.cpp. +

+
+ +
- -
-
-
-
-

Managed Media Dependencies

-
- FFmpeg, ocioconvert, oiiotool, and OpenColorIO status/actions from backend commands -
+
+
+
+

Managed media dependencies

+

+ FFmpeg, ocioconvert, oiiotool, and OpenColorIO status and actions from backend commands +

- {#if managedMediaError} - - {:else if managedMediaMessage} -
- {managedMediaMessage} -
- {/if} + {@render sectionNote(managedMediaError, managedMediaMessage)} -
+
{#each managedMediaDependencies as dependency (dependency.id)} {@const presentation = formatManagedMediaDependencyStatus(dependency)} {@const selectedVersionOptions = managedMediaVersionOptions(dependency)} {@const actionBusy = managedMediaActionInProgress(dependency.id)} -
-
-
-
-

{dependency.display_name}

- - {presentation.readinessLabel} - - - {presentation.categoryLabel} - -
-
- {dependency.catalog.source.owner}/{dependency.catalog.source.project} / {presentation.packageLabel} / {dependency.catalog.platform_key} + {@const dependencyRows = buildManagedMediaDependencyRows(dependency)} + {@const rowSplit = Math.ceil(dependencyRows.length / 2)} +
+
+
+
+

{dependency.display_name}

+ {presentation.readinessLabel} + {presentation.categoryLabel}
+

+ {dependency.catalog.source.owner}/{dependency.catalog.source.project}, {presentation.packageLabel}, + {dependency.catalog.platform_key} +

-
- {#each buildManagedMediaDependencyRows(dependency) as row (row.label)} -
-
{row.label}
-
- {row.value} -
-
- {/each} -
+
+ + +
{#if dependency.missing_files.length > 0} -
- Missing: {dependency.missing_files.join(', ')} -
+

Missing: {dependency.missing_files.join(', ')}

{/if} -
-
-
- - -
-
- - -
-
- -
- +
+ + +
+
-
+
{/each}
-
+ - +
-
+
+ + diff --git a/src/components/workbench/WorkbenchShell.svelte b/src/components/workbench/WorkbenchShell.svelte index b396dd9df..3e067ab60 100644 --- a/src/components/workbench/WorkbenchShell.svelte +++ b/src/components/workbench/WorkbenchShell.svelte @@ -1,23 +1,11 @@ -
- - -
-
-
-
Pantograph
-
- {WORKBENCH_PAGES.find((page) => page.id === $selectedWorkbenchPage)?.label ?? 'Scheduler'} -
-
- -
- - {#if $activeWorkflowRun} - - - {/if} -
-
- -
- {#if $selectedWorkbenchPage === 'scheduler'} - - {:else if $selectedWorkbenchPage === 'diagnostics'} - - {:else if $selectedWorkbenchPage === 'graph'} - - {:else if $selectedWorkbenchPage === 'io_inspector'} - - {:else if $selectedWorkbenchPage === 'library'} - - {:else if $selectedWorkbenchPage === 'network'} - - {:else if $selectedWorkbenchPage === 'node_lab'} - - {:else if $selectedWorkbenchPage === 'settings'} - {/if} -
+
+ + + + + + +
+ {#if $selectedWorkbenchPage === 'sessions'} + + {:else if $selectedWorkbenchPage === 'scheduler'} + + {:else if $selectedWorkbenchPage === 'diagnostics'} + + {:else if $selectedWorkbenchPage === 'io_inspector'} + + {:else if $selectedWorkbenchPage === 'network'} + + {:else if $selectedWorkbenchPage === 'graph'} + + {:else if $selectedWorkbenchPage === 'node_lab'} + + {:else if $selectedWorkbenchPage === 'library'} + + {:else if $selectedWorkbenchPage === 'settings'} + + {/if}
+ + diff --git a/src/components/workbench/diagnosticsPagePresenters.test.ts b/src/components/workbench/diagnosticsPagePresenters.test.ts index 68ee35969..7885baa21 100644 --- a/src/components/workbench/diagnosticsPagePresenters.test.ts +++ b/src/components/workbench/diagnosticsPagePresenters.test.ts @@ -11,6 +11,33 @@ import type { import { DEFAULT_DIAGNOSTICS_COMPARISON_FILTERS, DEFAULT_DIAGNOSTICS_EXECUTION_FILTERS, + buildDiagnosticsClientLabel, + buildDiagnosticsComparisonFilterChips, + buildDiagnosticsComparisonShortcuts, + buildDiagnosticsComparisonSummary, + buildDiagnosticsDimensionLine, + buildDiagnosticsErrorCard, + buildDiagnosticsExecutionFilterChips, + buildDiagnosticsFactSections, + buildDiagnosticsLevelOptions, + buildDiagnosticsLogLines, + buildDiagnosticsNodeErrorsOutsideTimeline, + buildDiagnosticsNodeStatusBars, + buildDiagnosticsPlacementLabel, + buildDiagnosticsProjectionRows, + buildDiagnosticsRetentionRows, + createDiagnosticsRefreshGate, + diagnosticsSentenceCase, + diagnosticsFactLayoutLabels, + diagnosticsFocusKey, + diagnosticsRecentFromDate, + explainDiagnosticsError, + filterDiagnosticsLogLines, + formatDiagnosticsClock, + formatDiagnosticsElapsed, + formatDiagnosticsLogTime, + groupDiagnosticsExecutionFacetRows, + resolveDiagnosticsFocus, buildDiagnosticsExecutionFacetRows, buildDiagnosticsExecutionFilterOptions, buildDiagnosticsFacetSummary, @@ -18,10 +45,6 @@ import { buildDiagnosticsRetentionSummaryRows, buildDiagnosticsComparisonFilterOptions, buildDiagnosticsRunErrorSummary, - diagnosticsErrorSeverityClass, - diagnosticsStatusClass, - diagnosticsTimelineRowClass, - filterDiagnosticsTimelineEvents, filterDiagnosticsExecutionNodes, filterDiagnosticsComparisonRuns, formatDiagnosticErrorPhase, @@ -180,14 +203,7 @@ test('formatDiagnosticsProjectionFreshness keeps projection cursor visible', () ); }); -test('diagnosticsStatusClass maps operational statuses to stable classes', () => { - assert.match(diagnosticsStatusClass('completed'), /emerald/); - assert.match(diagnosticsStatusClass('running'), /cyan/); - assert.match(diagnosticsStatusClass('future'), /amber/); - assert.match(diagnosticsStatusClass('scheduled'), /amber/); - assert.match(diagnosticsStatusClass('queued'), /amber/); - assert.match(diagnosticsStatusClass('failed'), /red/); - assert.match(diagnosticsStatusClass('cancelled'), /neutral/); +test('formatDiagnosticsStatusLabel names every run status', () => { assert.equal(formatDiagnosticsStatusLabel('future'), 'Future'); assert.equal(formatDiagnosticsStatusLabel('scheduled'), 'Scheduled'); assert.equal(formatDiagnosticsStatusLabel('cancelled'), 'Cancelled'); @@ -209,45 +225,9 @@ test('diagnostic error presenters expose severity and run summary fields', () => assert.equal(summary?.fatal, true); assert.equal(summary?.phase, 'runtime_model_load'); assert.equal(summary?.code, 'runtime_model_load_failed'); - assert.match(diagnosticsErrorSeverityClass('fatal'), /red/); - assert.match(diagnosticsErrorSeverityClass('error'), /orange/); - assert.match(diagnosticsErrorSeverityClass('warning'), /amber/); assert.equal(formatDiagnosticErrorSeverity('fatal'), 'Fatal'); assert.equal(formatDiagnosticErrorSeverity(null), 'Unknown'); - assert.equal(formatDiagnosticErrorPhase('runtime_model_load'), 'Runtime Model Load'); -}); - -test('diagnostics timeline row class marks error events without payload parsing', () => { - const errorEvent: SchedulerTimelineProjectionRecord = { - event_seq: 1, - event_id: 'event-1', - event_kind: 'diagnostic_error_occurred', - source_component: 'workflow_service', - occurred_at_ms: 1, - recorded_at_ms: 1, - workflow_run_id: 'run-1', - workflow_id: 'workflow-a', - summary: 'runtime load failed', - detail: null, - error_severity: 'fatal', - error_phase: 'runtime_model_load', - related_event_ids: [], - payload_json: '{}', - }; - const metadataEvent: SchedulerTimelineProjectionRecord = { - ...errorEvent, - event_id: 'event-2', - event_kind: 'scheduler_queue_placement', - error_severity: null, - error_phase: null, - }; - - assert.match( - diagnosticsTimelineRowClass(errorEvent), - /red/, - ); - assert.deepEqual(filterDiagnosticsTimelineEvents([metadataEvent, errorEvent], 'errors'), [errorEvent]); - assert.deepEqual(filterDiagnosticsTimelineEvents([metadataEvent, errorEvent], 'all'), [metadataEvent, errorEvent]); + assert.equal(formatDiagnosticErrorPhase('runtime_model_load'), 'Runtime model load'); }); test('buildDiagnosticsFactRows uses projection fields without ledger parsing', () => { @@ -616,12 +596,411 @@ test('diagnostics comparison filters support accepted date ranges', () => { }); test('timeline label helpers format typed projection enums and payload presence', () => { - assert.equal(formatDiagnosticEventKind('scheduler_queue_placement'), 'Scheduler Queue Placement'); + assert.equal(formatDiagnosticEventKind('scheduler_queue_placement'), 'scheduler queue placement'); assert.equal( formatDiagnosticEventKind('inference_execution_diagnostic_observed'), - 'Inference Execution Diagnostic Observed', + 'inference execution diagnostic observed', ); - assert.equal(formatDiagnosticSourceComponent('node_execution'), 'Node Execution'); + assert.equal(formatDiagnosticSourceComponent('node_execution'), 'node execution'); assert.equal(hasTimelinePayload({ payload_json: '{}' }), false); assert.equal(hasTimelinePayload({ payload_json: '{"decision":"delay"}' }), true); }); + +// --- Redesigned page presenters ---------------------------------------------- + +function createTimelineEvent(overrides: Partial): SchedulerTimelineProjectionRecord { + return { + event_seq: 1, + event_id: 'event-1', + event_kind: 'scheduler_queue_placement', + source_component: 'scheduler', + occurred_at_ms: new Date(2026, 10, 3, 19, 35, 2, 114).getTime(), + recorded_at_ms: 1, + workflow_run_id: 'run-1', + workflow_id: 'workflow-a', + summary: 'placed on cuda:1', + detail: null, + error_severity: null, + error_phase: null, + related_event_ids: [], + payload_json: '{}', + ...overrides, + }; +} + +function createFailedRun(overrides: Partial = {}): RunDetailProjectionRecord { + return { + ...createRunDetail(), + status: 'failed', + started_at_ms: new Date(2026, 10, 3, 19, 35, 20).getTime(), + completed_at_ms: new Date(2026, 10, 3, 19, 35, 42).getTime(), + duration_ms: 22_000, + latest_error_event_id: 'error-event-1', + latest_error_severity: 'fatal', + latest_error_phase: 'runtime_model_load', + latest_error_code: 'runtime_model_load_failed', + latest_error_message: 'CUDA out of memory on cuda:1', + fatal_error_event_id: 'error-event-1', + error_count: 1, + warning_count: 0, + ...overrides, + }; +} + +const NOW = new Date(2026, 10, 3, 20, 0, 0).getTime(); + +test('time presenters format clock, elapsed and log times', () => { + assert.equal(formatDiagnosticsClock(new Date(2026, 10, 3, 19, 35, 20).getTime(), NOW), '19:35:20'); + assert.equal(formatDiagnosticsClock(new Date(2026, 10, 1, 8, 5, 0).getTime(), NOW), '2026-11-01 08:05:00'); + assert.equal(formatDiagnosticsClock(null, NOW), 'Not recorded'); + assert.equal(formatDiagnosticsElapsed(640), '640 ms'); + assert.equal(formatDiagnosticsElapsed(2_500), '2.5 s'); + assert.equal(formatDiagnosticsElapsed(22_000), '22 s'); + assert.equal(formatDiagnosticsElapsed(109_000), '1m 49s'); + assert.equal(formatDiagnosticsElapsed(2 * 3_600_000 + 5 * 60_000), '2h 05m'); + assert.equal(formatDiagnosticsLogTime(new Date(2026, 10, 3, 19, 35, 2, 114).getTime()), '19:35:02.114'); +}); + +test('buildDiagnosticsDimensionLine summarises status, time and errors', () => { + const failedNode = createNodeStatus({ node_id: 'load_model', status: 'failed' }); + assert.equal( + buildDiagnosticsDimensionLine(createFailedRun(), [createNodeStatus({}), failedNode], NOW), + 'run-1, failed 19:35:42 after 22 s, 1 error in load_model', + ); + assert.equal( + buildDiagnosticsDimensionLine({ ...createRunDetail(), started_at_ms: new Date(2026, 10, 3, 19, 50, 0).getTime() }, [], NOW), + 'run-1, running since 19:50:00', + ); + assert.equal( + buildDiagnosticsDimensionLine({ ...createRunDetail(), status: 'queued', scheduler_queue_position: 2 }, [], NOW), + 'run-1, queued at position 2', + ); + assert.equal( + buildDiagnosticsDimensionLine( + { ...createRunDetail(), status: 'delayed', scheduler_reason: 'needs 8 GB on cuda:0', warning_count: 2 }, + [], + NOW, + ), + 'run-1, delayed: needs 8 GB on cuda:0, 2 warnings', + ); +}); + +test('placement and client labels say what is assigned', () => { + const run = createRunDetail(); + assert.equal(buildDiagnosticsPlacementLabel(run), 'runtime-a on device-a'); + assert.equal(buildDiagnosticsPlacementLabel({ ...run, selected_device_id: null }), 'runtime-a, device not assigned yet'); + assert.equal( + buildDiagnosticsPlacementLabel({ ...run, selected_device_id: null, selected_runtime_id: null }), + 'Not placed yet', + ); + assert.equal(buildDiagnosticsClientLabel(run), 'from client-a, session session-a'); + assert.equal(buildDiagnosticsClientLabel({ ...run, client_id: null, client_session_id: null }), null); +}); + +test('buildDiagnosticsFactSections places every run-detail fact exactly once', () => { + const run = createFailedRun({ terminal_error: 'worker exited with code 1' }); + const factLabels = buildDiagnosticsFactRows(run).map((row) => row.label); + assert.deepEqual([...diagnosticsFactLayoutLabels()].sort(), [...factLabels].sort()); + + const sections = buildDiagnosticsFactSections(run, NOW); + const placed = [...sections.timing, ...sections.placement, ...sections.retention, ...sections.more]; + const factValues = buildDiagnosticsFactRows(run).map((row) => row.value); + for (const value of factValues) { + assert.ok(placed.some((row) => row.value === value), `fact value ${value} is placed`); + } + // Timing leads with the lifecycle times; the five lifecycle rows plus three fact rows. + assert.deepEqual( + sections.timing.map((row) => row.key), + ['Accepted', 'Queued', 'Started', 'Finished', 'Duration', 'Estimated wait', 'Estimated duration', 'Estimate confidence'], + ); + assert.equal(sections.timing.find((row) => row.key === 'Duration')?.value, '22 s'); + assert.deepEqual( + sections.placement.map((row) => row.key), + ['Runtime', 'Backend', 'Device', 'Model', 'Model cache', 'Policy', 'Bucket', 'Queue position', 'Priority', 'Reason'], + ); + assert.equal(sections.placement.find((row) => row.key === 'Runtime')?.value, 'runtime-a'); + const running = { ...createRunDetail(), started_at_ms: NOW - 252_000 }; + assert.equal(buildDiagnosticsFactSections(running, NOW).timing.find((row) => row.key === 'Duration')?.value, 'Running for 4m 12s'); + assert.deepEqual(sections.retention, [{ key: 'Policy', value: 'retention-a', mono: true }]); + assert.equal(sections.more.find((row) => row.key === 'Latest error event')?.value, 'error-event-1'); + assert.equal(sections.more.find((row) => row.key === 'Terminal error')?.value, 'worker exited with code 1'); + assert.equal(sections.more.some((row) => row.key === 'Fatal error event'), false); + for (const section of Object.values(sections)) { + const keys = section.map((row: { key: string }) => row.key); + assert.equal(new Set(keys).size, keys.length, 'keys are unique within a section'); + } +}); + +test('retention and projection rows keep every count and cursor', () => { + assert.deepEqual( + buildDiagnosticsRetentionRows([ + { retention_state: 'metadata_only', artifact_count: 1 }, + { retention_state: 'retained', artifact_count: 3 }, + ]), + [ + { key: 'Payload retained', value: '3 artifacts' }, + { key: 'Metadata retained only', value: '1 artifact' }, + ], + ); + const state = { + projection_name: 'run_detail', + projection_version: 1, + last_applied_event_seq: 42, + status: 'current' as const, + rebuilt_at_ms: null, + updated_at_ms: 5, + }; + assert.deepEqual( + buildDiagnosticsProjectionRows({ runDetail: state, timeline: null, runList: state, nodeStatus: state, io: state }).map( + (row) => `${row.key}: ${row.value}`, + ), + [ + 'Run detail: Current at seq 42', + 'Scheduler timeline: Projection unavailable', + 'Run list: Current at seq 42', + 'Node status: Current at seq 42', + 'I/O retention: Current at seq 42', + ], + ); +}); + +test('node status bars and breakdown group the node projection', () => { + const nodes = [ + createNodeStatus({ node_id: 'a', status: 'completed' }), + createNodeStatus({ node_id: 'b', status: 'failed', runtime_id: 'runtime-b' }), + createNodeStatus({ node_id: 'c', status: 'queued' }), + createNodeStatus({ node_id: 'd', status: 'queued' }), + ]; + assert.deepEqual(buildDiagnosticsNodeStatusBars(nodes), [ + { status: 'queued', label: 'Queued', count: 2, percent: 50 }, + { status: 'completed', label: 'Completed', count: 1, percent: 25 }, + { status: 'failed', label: 'Failed', count: 1, percent: 25 }, + ]); + assert.deepEqual(buildDiagnosticsNodeStatusBars([]), []); + + const groups = groupDiagnosticsExecutionFacetRows(buildDiagnosticsExecutionFacetRows(nodes)); + assert.equal(groups.some((group) => group.label === 'Node status'), false); + assert.equal(diagnosticsSentenceCase('Selected Runtime Variant'), 'Selected runtime variant'); + assert.deepEqual( + groups.find((group) => group.label === 'Runtime')?.rows.map((row) => `${row.value}:${row.count}`), + ['runtime-a:3', 'runtime-b:1'], + ); +}); + +test('filter chips name each applied execution and comparison filter', () => { + assert.deepEqual(buildDiagnosticsExecutionFilterChips(DEFAULT_DIAGNOSTICS_EXECUTION_FILTERS), []); + assert.deepEqual( + buildDiagnosticsExecutionFilterChips({ ...DEFAULT_DIAGNOSTICS_EXECUTION_FILTERS, runtime: 'runtime-a', status: 'failed' }), + [ + { field: 'status', label: 'Node status failed' }, + { field: 'runtime', label: 'Runtime runtime-a' }, + ], + ); + assert.deepEqual( + buildDiagnosticsComparisonFilterChips({ + ...DEFAULT_DIAGNOSTICS_COMPARISON_FILTERS, + status: 'failed', + selectedDevice: 'cuda:1', + acceptedFromDate: '2026-11-01', + }), + [ + { field: 'status', label: 'Status Failed' }, + { field: 'selectedDevice', label: 'Device cuda:1' }, + { field: 'acceptedFromDate', label: 'Accepted from 2026-11-01' }, + ], + ); +}); + +test('comparison shortcuts toggle version, device and recent presets', () => { + const run = createRunDetail(); + const shortcuts = buildDiagnosticsComparisonShortcuts(run, DEFAULT_DIAGNOSTICS_COMPARISON_FILTERS, NOW); + assert.deepEqual( + shortcuts.map((shortcut) => [shortcut.label, shortcut.pressed]), + [ + ['Only v1.2.3', false], + ['Only device-a', false], + ['Last 7 days', false], + ], + ); + const versionOn = shortcuts[0].toggled; + assert.equal(versionOn.workflowVersion, '1.2.3'); + const again = buildDiagnosticsComparisonShortcuts(run, versionOn, NOW); + assert.equal(again[0].pressed, true); + assert.equal(again[0].toggled.workflowVersion, 'all'); + + const recentOn = shortcuts[2].toggled; + assert.equal(recentOn.acceptedFromDate, diagnosticsRecentFromDate(NOW)); + assert.equal(buildDiagnosticsComparisonShortcuts(run, recentOn, NOW)[2].pressed, true); + assert.equal( + buildDiagnosticsComparisonShortcuts({ ...run, selected_device_id: null }, DEFAULT_DIAGNOSTICS_COMPARISON_FILTERS, NOW).some( + (shortcut) => shortcut.id === 'device', + ), + false, + ); +}); + +test('buildDiagnosticsComparisonSummary compares failures and durations with peers', () => { + const run = createFailedRun(); + const peers = [ + createRunListPeer({ workflow_run_id: 'p1', status: 'failed', latest_error_code: 'runtime_model_load_failed' }), + createRunListPeer({ workflow_run_id: 'p2', status: 'completed', duration_ms: 100_000 }), + createRunListPeer({ workflow_run_id: 'p3', status: 'completed', duration_ms: 118_000 }), + createRunListPeer({ workflow_run_id: 'p4', status: 'completed', duration_ms: 109_000 }), + ]; + const failed = buildDiagnosticsComparisonSummary(run, [run, ...peers]); + assert.equal(failed.failed, '2 of 5'); + assert.equal(failed.median, '1m 49s'); + assert.equal(failed.note, '1 of the other 4 compared runs also failed, 1 with runtime_model_load_failed.'); + + const completed = { ...createRunDetail(), status: 'completed' as const, duration_ms: 90_000 }; + assert.equal( + buildDiagnosticsComparisonSummary(completed, [completed, ...peers]).note, + 'This run took 1m 30s; the median completed run took 1m 49s.', + ); + const alone = buildDiagnosticsComparisonSummary(createRunDetail(), [createRunDetail()]); + assert.equal(alone.median, 'None yet'); + assert.equal(alone.note, 'No other runs of workflow-a in the run list match these filters.'); +}); + +test('buildDiagnosticsLogLines turns timeline events and node errors into log lines', () => { + const events = [ + createTimelineEvent({ event_seq: 3, event_id: 'event-3', event_kind: 'diagnostic_error_occurred', source_component: 'node_execution', summary: 'failed', error_severity: null, error_phase: 'runtime_model_load' }), + createTimelineEvent({ event_seq: 1, event_id: 'event-1', payload_json: '{"decision":"place"}' }), + createTimelineEvent({ event_seq: 2, event_id: 'event-2', event_kind: 'run_started', source_component: 'runtime', summary: 'memory pressure', error_severity: 'warning' }), + ]; + const nodes = [ + createNodeStatus({ node_id: 'load_model', status: 'failed', canonical_error_event_id: 'event-3', error_code: 'runtime_model_load_failed', error_severity: 'fatal' }), + ]; + const lines = buildDiagnosticsLogLines(events, nodes); + assert.deepEqual(lines.map((line) => line.seq), [1, 2, 3]); + assert.equal(lines[0].kind, 'scheduler queue placement'); + assert.equal(lines[0].source, 'scheduler, seq 1, payload captured'); + assert.equal(lines[0].time, '19:35:02.114'); + assert.equal(lines[0].domId, 'diagnostics-event-1'); + assert.equal(lines[1].level, 'warn'); + assert.equal(lines[2].kind, 'load_model'); + assert.equal(lines[2].level, 'error'); + assert.equal(lines[2].nodeId, 'load_model'); + assert.equal(lines[2].message, 'failed, phase runtime model load, runtime_model_load_failed'); + + assert.deepEqual( + buildDiagnosticsLevelOptions(lines).map((option) => `${option.label} ${option.count}`), + ['All 3', 'Warnings 1', 'Errors 1'], + ); + const only = (level: 'all' | 'warn' | 'error', source: 'all' | 'scheduler' | 'runtime' | 'nodes', query = '') => + filterDiagnosticsLogLines(lines, { level, source, query }).map((line) => line.eventId); + assert.deepEqual(only('error', 'all'), ['event-3']); + assert.deepEqual(only('warn', 'all'), ['event-2']); + assert.deepEqual(only('all', 'nodes'), ['event-3']); + assert.deepEqual(only('all', 'runtime'), ['event-2']); + assert.deepEqual(only('all', 'all', 'MEMORY'), ['event-2']); + assert.deepEqual(only('all', 'all', 'event-1'), ['event-1']); +}); + +test('node errors stay reachable when the timeline lacks their event', () => { + const nodes = [ + createNodeStatus({ node_id: 'in-timeline', status: 'failed', error_event_id: 'event-1', error: 'boom' }), + createNodeStatus({ node_id: 'missing', status: 'failed', error_event_id: 'event-9', error: 'boom' }), + createNodeStatus({ node_id: 'unlinked', status: 'failed', error_severity: 'error' }), + createNodeStatus({ node_id: 'fine', status: 'completed' }), + ]; + assert.deepEqual( + buildDiagnosticsNodeErrorsOutsideTimeline(nodes, [createTimelineEvent({ event_id: 'event-1' })]).map((node) => node.node_id), + ['missing', 'unlinked'], + ); +}); + +test('resolveDiagnosticsFocus selects the focused line and the level that shows it', () => { + const events = [ + createTimelineEvent({ event_seq: 1, event_id: 'event-1' }), + createTimelineEvent({ event_seq: 2, event_id: 'event-2', error_severity: 'fatal' }), + ]; + const nodes = [createNodeStatus({ node_id: 'load_model', status: 'failed', error_event_id: 'event-2' })]; + const lines = buildDiagnosticsLogLines(events, nodes); + const focus = { workflow_run_id: 'run-1', diagnostic_event_id: 'event-2', node_id: null, requested_at_ms: 7 }; + + assert.deepEqual(resolveDiagnosticsFocus(focus, 'run-1', lines, nodes), { + eventId: 'event-2', + nodeId: 'load_model', + lineDomId: 'diagnostics-event-2', + level: 'error', + }); + assert.equal(resolveDiagnosticsFocus(focus, 'run-2', lines, nodes), null); + assert.equal(resolveDiagnosticsFocus(null, 'run-1', lines, nodes), null); + assert.deepEqual( + resolveDiagnosticsFocus({ ...focus, diagnostic_event_id: null, node_id: 'load_model' }, 'run-1', lines, nodes)?.lineDomId, + 'diagnostics-event-2', + ); + assert.equal(resolveDiagnosticsFocus({ ...focus, diagnostic_event_id: 'event-1' }, 'run-1', lines, nodes)?.level, 'all'); + assert.deepEqual(resolveDiagnosticsFocus({ ...focus, diagnostic_event_id: 'event-9' }, 'run-1', lines, nodes), { + eventId: 'event-9', + nodeId: null, + lineDomId: null, + level: 'all', + }); + assert.equal(diagnosticsFocusKey(focus), 'run-1:7'); + assert.notEqual(diagnosticsFocusKey({ ...focus, requested_at_ms: 8 }), diagnosticsFocusKey(focus)); +}); + +test('explainDiagnosticsError explains known codes and restates unknown ones', () => { + const known = explainDiagnosticsError({ + code: 'runtime_model_load_failed', + message: 'CUDA out of memory on cuda:1', + phase: 'runtime_model_load', + nodeId: 'load_model', + }); + assert.equal(known.title, 'Model failed to load in load_model'); + assert.equal(known.explanation, 'The runtime could not load the model for this run: CUDA out of memory on cuda:1.'); + assert.match(known.suggestion, /^Try: /); + + const unknown = explainDiagnosticsError({ code: 'something_new', message: 'disk quota exceeded.', phase: 'artifact' }); + assert.equal(unknown.title, 'Artifact failed'); + assert.equal(unknown.explanation, 'The run reported: disk quota exceeded.'); + assert.match(unknown.suggestion, /^Try: show the error in the log/); + + const bare = explainDiagnosticsError({ code: null, message: ' ', phase: 'unassigned' }); + assert.equal(bare.title, 'The run reported an error'); + assert.equal(bare.explanation, 'No error message was projected for this run.'); +}); + +test('buildDiagnosticsErrorCard covers fatal errors, warnings and terminal-only errors', () => { + const nodes = [createNodeStatus({ node_id: 'load_model', status: 'failed', canonical_error_event_id: 'error-event-1' })]; + const card = buildDiagnosticsErrorCard(createFailedRun(), nodes); + assert.equal(card?.kind, 'error'); + assert.equal(card?.title, 'Model failed to load in load_model'); + assert.equal(card?.codeLine, 'runtime_model_load_failed, phase runtime model load, fatal'); + assert.equal(card?.eventId, 'error-event-1'); + assert.equal(card?.nodeId, 'load_model'); + + const warning = buildDiagnosticsErrorCard( + { + ...createRunDetail(), + latest_error_event_id: 'warn-1', + latest_error_severity: 'warning', + latest_error_code: 'projection_failed', + latest_error_message: 'projection lagging', + }, + [], + ); + assert.equal(warning?.kind, 'warning'); + + const terminalOnly = buildDiagnosticsErrorCard({ ...createRunDetail(), status: 'failed', terminal_error: 'worker exited' }, []); + assert.equal(terminalOnly?.kind, 'error'); + assert.equal(terminalOnly?.eventId, null); + assert.equal(terminalOnly?.explanation, 'The run reported: worker exited.'); + assert.equal(buildDiagnosticsErrorCard(createRunDetail(), []), null); +}); + +test('createDiagnosticsRefreshGate applies only the newest refresh and nothing after close', () => { + const gate = createDiagnosticsRefreshGate(); + const first = gate.begin(); + const second = gate.begin(); + assert.equal(gate.isCurrent(first), false); + assert.equal(gate.isCurrent(second), true); + gate.close(); + assert.equal(gate.isCurrent(second), false); + assert.equal(gate.isCurrent(gate.begin()), false); + + const other = createDiagnosticsRefreshGate(); + assert.equal(other.isCurrent(other.begin()), true, 'gates are scoped to their owner'); +}); diff --git a/src/components/workbench/diagnosticsPagePresenters.ts b/src/components/workbench/diagnosticsPagePresenters.ts index 80c38f6ae..05b69c2f2 100644 --- a/src/components/workbench/diagnosticsPagePresenters.ts +++ b/src/components/workbench/diagnosticsPagePresenters.ts @@ -4,6 +4,7 @@ import type { DiagnosticEventSourceComponent, IoArtifactRetentionState, IoArtifactRetentionSummaryRecord, + NodeExecutionProjectionStatus, NodeStatusProjectionRecord, ProjectionStateRecord, RunDetailProjectionRecord, @@ -13,6 +14,8 @@ import type { SchedulerTimelineProjectionRecord, } from '../../services/diagnostics/types'; import { formatProjectionFreshnessState } from './projectionFreshness.ts'; +import type { LogLevel } from './ui/statusGlyph.ts'; +import type { KeyValueRow, SegmentOption } from './ui/types.ts'; export interface DiagnosticsFactRow { label: string; @@ -52,8 +55,6 @@ export interface DiagnosticsRunErrorSummary { fatal: boolean; } -export type DiagnosticsTimelineEventFilter = 'all' | 'errors'; - export interface DiagnosticsExecutionFilters { status: string; nodeVersion: string; @@ -164,13 +165,6 @@ export const EMPTY_DIAGNOSTICS_EXECUTION_FILTER_OPTIONS: DiagnosticsExecutionFil modelVersions: [], }; -export function formatDiagnosticsTimestamp(value: number | null | undefined): string { - if (!value) { - return 'Unavailable'; - } - return new Date(value).toLocaleString(); -} - export function formatDiagnosticsDuration( value: number | null | undefined, status: RunDetailProjectionRecord['status'], @@ -200,65 +194,6 @@ export function formatDiagnosticsProjectionFreshness(state: ProjectionStateRecor return formatProjectionFreshnessState(state); } -export function diagnosticsStatusClass(status: RunDetailProjectionRecord['status']): string { - switch (status) { - case 'completed': - return 'border-emerald-700 bg-emerald-950/60 text-emerald-200'; - case 'running': - return 'border-cyan-700 bg-cyan-950/60 text-cyan-200'; - case 'queued': - case 'accepted': - case 'future': - case 'scheduled': - return 'border-amber-700 bg-amber-950/60 text-amber-200'; - case 'delayed': - return 'border-orange-700 bg-orange-950/60 text-orange-200'; - case 'failed': - return 'border-red-700 bg-red-950/60 text-red-200'; - case 'cancelled': - return 'border-neutral-700 bg-neutral-900 text-neutral-300'; - } -} - -export function diagnosticsErrorSeverityClass(severity: DiagnosticErrorSeverity): string { - switch (severity) { - case 'fatal': - return 'border-red-700 bg-red-950/70 text-red-100'; - case 'error': - return 'border-orange-700 bg-orange-950/60 text-orange-100'; - case 'warning': - return 'border-amber-700 bg-amber-950/60 text-amber-100'; - } -} - -export function diagnosticsTimelineRowClass(event: SchedulerTimelineProjectionRecord): string { - switch (event.error_severity) { - case 'fatal': - return 'bg-red-950/30'; - case 'error': - return 'bg-orange-950/25'; - case 'warning': - return 'bg-amber-950/20'; - case null: - case undefined: - return ''; - } -} - -export function isDiagnosticErrorTimelineEvent(event: SchedulerTimelineProjectionRecord): boolean { - return Boolean(event.error_severity); -} - -export function filterDiagnosticsTimelineEvents( - events: SchedulerTimelineProjectionRecord[], - filter: DiagnosticsTimelineEventFilter, -): SchedulerTimelineProjectionRecord[] { - if (filter === 'errors') { - return events.filter(isDiagnosticErrorTimelineEvent); - } - return events; -} - export function formatDiagnosticsStatusLabel(status: RunDetailProjectionRecord['status']): string { switch (status) { case 'accepted': @@ -807,31 +742,970 @@ function dateInputEndMs(value: string): number | null { return Number.isFinite(parsed) ? parsed : null; } +/** Lower-case words for a projection enum, for example `node_execution` to "node execution". */ +export function diagnosticsWords(value: string): string { + return value.split('_').filter((part) => part.length > 0).join(' '); +} + export function formatDiagnosticEventKind(kind: DiagnosticEventKind): string { - return kind - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); + return diagnosticsWords(kind); } export function formatDiagnosticErrorPhase(phase: string | null | undefined): string { if (!phase || phase.trim().length === 0) { return 'Unassigned'; } - return phase - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); + const words = diagnosticsWords(phase.trim()); + return words.charAt(0).toUpperCase() + words.slice(1); } export function formatDiagnosticSourceComponent(source: DiagnosticEventSourceComponent): string { - return source - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); + return diagnosticsWords(source); } export function hasTimelinePayload(event: Pick): boolean { const payload = event.payload_json.trim(); return payload.length > 0 && payload !== '{}' && payload !== 'null'; } + +// --------------------------------------------------------------------------- +// Redesigned page projection (docs/design/workbench-redesign-spec.md, +// "Diagnostics"). Everything below is pure: it reads typed projection records +// and returns what the page renders. +// --------------------------------------------------------------------------- + +const MS_PER_SECOND = 1_000; +const MS_PER_MINUTE = 60 * MS_PER_SECOND; +const MS_PER_HOUR = 60 * MS_PER_MINUTE; +const MS_PER_DAY = 24 * MS_PER_HOUR; + +const NOT_RECORDED = 'Not recorded'; + +function pad2(value: number): string { + return String(value).padStart(2, '0'); +} + +function localDateKey(date: Date): string { + return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`; +} + +function localClock(date: Date): string { + return `${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; +} + +/** + * Local wall-clock time of a projection timestamp: `HH:MM:SS` on the same + * local day as `nowMs`, `YYYY-MM-DD HH:MM:SS` otherwise. + */ +export function formatDiagnosticsClock(value: number | null | undefined, nowMs: number): string { + if (!value) { + return NOT_RECORDED; + } + const date = new Date(value); + const clock = localClock(date); + return localDateKey(date) === localDateKey(new Date(nowMs)) ? clock : `${localDateKey(date)} ${clock}`; +} + +/** Log timestamp with milliseconds, `HH:MM:SS.mmm` local time. */ +export function formatDiagnosticsLogTime(value: number): string { + const date = new Date(value); + return `${localClock(date)}.${String(date.getMilliseconds()).padStart(3, '0')}`; +} + +/** Elapsed time in the words the page uses: "640 ms", "2.5 s", "22 s", "1m 49s", "2h 05m". */ +export function formatDiagnosticsElapsed(value: number): string { + const ms = Math.max(0, value); + if (ms < MS_PER_SECOND) { + return `${Math.round(ms)} ms`; + } + if (ms < 10 * MS_PER_SECOND) { + return `${(ms / MS_PER_SECOND).toFixed(1)} s`; + } + if (ms < MS_PER_MINUTE) { + return `${Math.round(ms / MS_PER_SECOND)} s`; + } + const totalSeconds = Math.round(ms / MS_PER_SECOND); + if (ms < MS_PER_HOUR) { + return `${Math.floor(totalSeconds / 60)}m ${pad2(totalSeconds % 60)}s`; + } + const totalMinutes = Math.floor(totalSeconds / 60); + return `${Math.floor(totalMinutes / 60)}h ${pad2(totalMinutes % 60)}m`; +} + +const RUN_STATUS_WORD: Record = { + accepted: 'accepted', + future: 'scheduled for later', + scheduled: 'scheduled', + queued: 'queued', + delayed: 'delayed', + running: 'running', + completed: 'completed', + failed: 'failed', + cancelled: 'cancelled', +}; + +function isTerminalRunStatus(status: RunListProjectionRecord['status']): boolean { + return status === 'completed' || status === 'failed' || status === 'cancelled'; +} + +function plural(count: number, noun: string): string { + return `${count} ${noun}${count === 1 ? '' : 's'}`; +} + +function nodeErrorEventId(node: NodeStatusProjectionRecord): string | null { + return node.canonical_error_event_id ?? node.error_event_id ?? null; +} + +/** Whether a node row carries a diagnostic error (the old "Node Errors" table criterion). */ +export function diagnosticsNodeHasError(node: NodeStatusProjectionRecord): boolean { + return Boolean(nodeErrorEventId(node) || node.error || node.error_severity); +} + +function firstFailedNodeId(nodes: NodeStatusProjectionRecord[]): string | null { + return nodes.find((node) => node.status === 'failed')?.node_id ?? null; +} + +/** + * The page summary line, for example + * "run_1, failed 19:35:42 after 22 s, 1 error in load_model". + */ +export function buildDiagnosticsDimensionLine( + run: RunDetailProjectionRecord, + nodes: NodeStatusProjectionRecord[], + nowMs: number, +): string { + const word = RUN_STATUS_WORD[run.status]; + let state: string; + if (isTerminalRunStatus(run.status)) { + const at = run.completed_at_ms ?? run.last_updated_at_ms; + const after = + run.duration_ms === null || run.duration_ms === undefined ? '' : ` after ${formatDiagnosticsElapsed(run.duration_ms)}`; + state = `${word} ${formatDiagnosticsClock(at, nowMs)}${after}`; + } else if (run.status === 'running') { + state = run.started_at_ms ? `${word} since ${formatDiagnosticsClock(run.started_at_ms, nowMs)}` : word; + } else if (run.status === 'delayed') { + state = run.scheduler_reason ? `${word}: ${run.scheduler_reason}` : word; + } else { + const position = run.scheduler_queue_position; + state = position === null || position === undefined ? word : `${word} at position ${position}`; + } + + const parts = [run.workflow_run_id, state]; + const errors = run.error_count ?? 0; + if (errors > 0) { + const failedNode = firstFailedNodeId(nodes); + parts.push(`${plural(errors, 'error')}${failedNode ? ` in ${failedNode}` : ''}`); + } + const warnings = run.warning_count ?? 0; + if (warnings > 0) { + parts.push(plural(warnings, 'warning')); + } + return parts.join(', '); +} + +/** Placement chip text: "diffusers on cuda:1", or what is still missing. */ +export function buildDiagnosticsPlacementLabel(run: RunListProjectionRecord): string { + const runtime = run.selected_runtime_id; + const device = run.selected_device_id; + if (runtime && device) { + return `${runtime} on ${device}`; + } + if (runtime) { + return `${runtime}, device not assigned yet`; + } + if (device) { + return `on ${device}, runtime not assigned yet`; + } + return 'Not placed yet'; +} + +/** Client chip text, or null when the run carries no client facts. */ +export function buildDiagnosticsClientLabel(run: RunDetailProjectionRecord): string | null { + if (run.client_id && run.client_session_id) { + return `from ${run.client_id}, session ${run.client_session_id}`; + } + if (run.client_id) { + return `from ${run.client_id}`; + } + if (run.client_session_id) { + return `session ${run.client_session_id}`; + } + return null; +} + +type DiagnosticsFactSection = 'timing' | 'placement' | 'retention' | 'more'; + +/** + * Where each `buildDiagnosticsFactRows` fact goes in the redesigned left + * panel, with its sentence-case key. Every fact row label must appear here + * exactly once (enforced by test) so no fact the page showed is lost. + */ +const DIAGNOSTICS_FACT_LAYOUT: Record = { + 'Estimated Queue Wait': { section: 'timing', key: 'Estimated wait' }, + 'Estimated Duration': { section: 'timing', key: 'Estimated duration' }, + 'Estimate Confidence': { section: 'timing', key: 'Estimate confidence' }, + 'Selected Runtime': { section: 'placement', key: 'Runtime' }, + 'Selected Backend': { section: 'placement', key: 'Backend' }, + 'Selected Device': { section: 'placement', key: 'Device' }, + 'Selected Model': { section: 'placement', key: 'Model' }, + 'Model Cache': { section: 'placement', key: 'Model cache' }, + 'Scheduler Policy': { section: 'placement', key: 'Policy' }, + Bucket: { section: 'placement', key: 'Bucket' }, + 'Queue Position': { section: 'placement', key: 'Queue position' }, + Priority: { section: 'placement', key: 'Priority' }, + 'Scheduler Reason': { section: 'placement', key: 'Reason' }, + 'Retention Policy': { section: 'retention', key: 'Policy' }, + Workflow: { section: 'more', key: 'Workflow' }, + 'Workflow Version': { section: 'more', key: 'Workflow version' }, + 'Run Snapshot': { section: 'more', key: 'Run snapshot' }, + 'Presentation Revision': { section: 'more', key: 'Presentation revision' }, + Client: { section: 'more', key: 'Client' }, + 'Client Session': { section: 'more', key: 'Client session' }, + 'Execution Session': { section: 'more', key: 'Execution session' }, + 'Selected Runtime Variant': { section: 'more', key: 'Runtime variant' }, + 'Selected Task': { section: 'more', key: 'Task' }, + 'Selected Device Class': { section: 'more', key: 'Device class' }, + 'Selected Network Node': { section: 'more', key: 'Network node' }, + 'Timeline Events': { section: 'more', key: 'Timeline events' }, + 'Last Event Seq': { section: 'more', key: 'Last event seq' }, +}; + +export function diagnosticsFactLayoutLabels(): string[] { + return Object.keys(DIAGNOSTICS_FACT_LAYOUT); +} + +export interface DiagnosticsFactSections { + timing: KeyValueRow[]; + placement: KeyValueRow[]; + retention: KeyValueRow[]; + more: KeyValueRow[]; +} + +/** + * The run facts split into the left panel's Timing, Placement, Retention and + * "More facts" key-value blocks. Timing leads with the lifecycle timestamps; + * "More facts" ends with the run's error identifiers when it has any. + */ +export function buildDiagnosticsFactSections(run: RunDetailProjectionRecord, nowMs: number): DiagnosticsFactSections { + const sections: DiagnosticsFactSections = { + timing: [ + { key: 'Accepted', value: formatDiagnosticsClock(run.accepted_at_ms, nowMs), mono: true }, + { key: 'Queued', value: formatDiagnosticsClock(run.enqueued_at_ms, nowMs), mono: true }, + { key: 'Started', value: formatDiagnosticsClock(run.started_at_ms, nowMs), mono: true }, + { key: 'Finished', value: formatDiagnosticsClock(run.completed_at_ms, nowMs), mono: true }, + { key: 'Duration', value: formatDiagnosticsRunDuration(run, nowMs) }, + ], + placement: [], + retention: [], + more: [], + }; + // Layout order, not fact-row order, so each block reads in a sensible sequence. + const factRows = new Map(buildDiagnosticsFactRows(run).map((row) => [row.label, row])); + for (const [label, layout] of Object.entries(DIAGNOSTICS_FACT_LAYOUT)) { + const row = factRows.get(label); + if (!row) continue; + factRows.delete(label); + sections[layout.section].push({ key: layout.key, value: row.value, mono: row.mono }); + } + for (const row of factRows.values()) { + sections.more.push({ key: row.label, value: row.value, mono: row.mono }); + } + const errorEventId = run.latest_error_event_id; + if (errorEventId) { + sections.more.push({ key: 'Latest error event', value: errorEventId, mono: true }); + } + if (run.fatal_error_event_id && run.fatal_error_event_id !== errorEventId) { + sections.more.push({ key: 'Fatal error event', value: run.fatal_error_event_id, mono: true }); + } + if (run.terminal_error && run.terminal_error !== run.latest_error_message) { + sections.more.push({ key: 'Terminal error', value: run.terminal_error }); + } + return sections; +} + +/** Duration of a finished run, or how long a running run has been running as of `nowMs`. */ +export function formatDiagnosticsRunDuration(run: RunListProjectionRecord, nowMs: number): string { + if (typeof run.duration_ms === 'number') { + return formatDiagnosticsElapsed(run.duration_ms); + } + if (run.status === 'running' && run.started_at_ms) { + return `Running for ${formatDiagnosticsElapsed(nowMs - run.started_at_ms)}`; + } + return formatDiagnosticsDuration(null, run.status); +} + +/** Sentence case for projection labels written in title case, for example "Selected Runtime" to "Selected runtime". */ +export function diagnosticsSentenceCase(label: string): string { + return label.charAt(0) + label.slice(1).toLowerCase(); +} + +export function buildDiagnosticsRetentionRows( + summary: IoArtifactRetentionSummaryRecord[], +): KeyValueRow[] { + return buildDiagnosticsRetentionSummaryRows(summary).map((row) => ({ + key: row.label, + value: plural(row.count, 'artifact'), + })); +} + +export interface DiagnosticsProjectionStates { + runDetail: ProjectionStateRecord | null; + timeline: ProjectionStateRecord | null; + runList: ProjectionStateRecord | null; + nodeStatus: ProjectionStateRecord | null; + io: ProjectionStateRecord | null; +} + +/** One freshness row per projection the page reads (ADR-014 guardrail). */ +export function buildDiagnosticsProjectionRows(states: DiagnosticsProjectionStates): KeyValueRow[] { + return [ + { key: 'Run detail', value: formatDiagnosticsProjectionFreshness(states.runDetail) }, + { key: 'Scheduler timeline', value: formatDiagnosticsProjectionFreshness(states.timeline) }, + { key: 'Run list', value: formatDiagnosticsProjectionFreshness(states.runList) }, + { key: 'Node status', value: formatDiagnosticsProjectionFreshness(states.nodeStatus) }, + { key: 'I/O retention', value: formatDiagnosticsProjectionFreshness(states.io) }, + ]; +} + +export interface DiagnosticsNodeStatusBar { + status: NodeExecutionProjectionStatus; + label: string; + count: number; + /** Share of all nodes, 0 to 100, rounded. */ + percent: number; +} + +const NODE_STATUS_BAR_ORDER: Array<[NodeExecutionProjectionStatus, string]> = [ + ['running', 'Running'], + ['waiting', 'Waiting'], + ['queued', 'Queued'], + ['completed', 'Completed'], + ['failed', 'Failed'], + ['cancelled', 'Cancelled'], +]; + +/** "Nodes by status" bars, in lifecycle order, omitting statuses with no nodes. */ +export function buildDiagnosticsNodeStatusBars(nodes: NodeStatusProjectionRecord[]): DiagnosticsNodeStatusBar[] { + const total = nodes.length; + return NODE_STATUS_BAR_ORDER.map(([status, label]) => { + const count = nodes.filter((node) => node.status === status).length; + return { status, label, count, percent: total > 0 ? Math.round((count / total) * 100) : 0 }; + }).filter((bar) => bar.count > 0); +} + +export interface DiagnosticsFacetGroup { + label: string; + rows: DiagnosticsExecutionFacetRow[]; +} + +/** + * Execution facet rows grouped by facet for the "Breakdown" disclosure. Node + * status is left out because the status bars already show it. + */ +export function groupDiagnosticsExecutionFacetRows(rows: DiagnosticsExecutionFacetRow[]): DiagnosticsFacetGroup[] { + const groups: DiagnosticsFacetGroup[] = []; + for (const row of rows) { + if (row.label === 'Node Status') continue; + const label = diagnosticsSentenceCase(row.label); + const group = groups.find((candidate) => candidate.label === label); + if (group) { + group.rows.push(row); + } else { + groups.push({ label, rows: [row] }); + } + } + return groups; +} + +// --- Filters: field descriptors and applied-filter chips -------------------- + +export interface DiagnosticsExecutionFilterField { + field: keyof DiagnosticsExecutionFilters; + label: string; + options: keyof DiagnosticsExecutionFilterOptions; +} + +export const DIAGNOSTICS_EXECUTION_FILTER_FIELDS: readonly DiagnosticsExecutionFilterField[] = [ + { field: 'status', label: 'Node status', options: 'statuses' }, + { field: 'nodeVersion', label: 'Node version', options: 'nodeVersions' }, + { field: 'runtime', label: 'Runtime', options: 'runtimes' }, + { field: 'runtimeVersion', label: 'Runtime version', options: 'runtimeVersions' }, + { field: 'model', label: 'Model', options: 'models' }, + { field: 'modelVersion', label: 'Model version', options: 'modelVersions' }, +]; + +type DiagnosticsComparisonSelectField = Exclude< + keyof DiagnosticsComparisonFilters, + 'acceptedFromDate' | 'acceptedToDate' +>; + +export type DiagnosticsComparisonFilterField = + | { input: 'select'; field: DiagnosticsComparisonSelectField; label: string; options: keyof DiagnosticsComparisonFilterOptions } + | { input: 'date'; field: 'acceptedFromDate' | 'acceptedToDate'; label: string }; + +export const DIAGNOSTICS_COMPARISON_FILTER_FIELDS: readonly DiagnosticsComparisonFilterField[] = [ + { input: 'select', field: 'workflowVersion', label: 'Version', options: 'workflowVersions' }, + { input: 'select', field: 'status', label: 'Status', options: 'statuses' }, + { input: 'select', field: 'schedulerPolicy', label: 'Scheduler policy', options: 'schedulerPolicies' }, + { input: 'select', field: 'retentionPolicy', label: 'Retention policy', options: 'retentionPolicies' }, + { input: 'select', field: 'client', label: 'Client', options: 'clients' }, + { input: 'select', field: 'clientSession', label: 'Session', options: 'clientSessions' }, + { input: 'select', field: 'selectedRuntime', label: 'Runtime', options: 'selectedRuntimes' }, + { input: 'select', field: 'selectedRuntimeVariant', label: 'Runtime variant', options: 'selectedRuntimeVariants' }, + { input: 'select', field: 'selectedBackend', label: 'Backend', options: 'selectedBackends' }, + { input: 'select', field: 'selectedDeviceClass', label: 'Device class', options: 'selectedDeviceClasses' }, + { input: 'select', field: 'selectedDevice', label: 'Device', options: 'selectedDevices' }, + { input: 'select', field: 'selectedNetworkNode', label: 'Network node', options: 'selectedNetworkNodes' }, + { input: 'select', field: 'bucket', label: 'Bucket', options: 'buckets' }, + { input: 'select', field: 'acceptedDate', label: 'Accepted on', options: 'acceptedDates' }, + { input: 'date', field: 'acceptedFromDate', label: 'Accepted from' }, + { input: 'date', field: 'acceptedToDate', label: 'Accepted to' }, +]; + +/** Display text of a comparison filter option; statuses read as words. */ +export function formatDiagnosticsComparisonOption(field: keyof DiagnosticsComparisonFilters, value: string): string { + if (field === 'status' && isRunListStatus(value)) { + return formatDiagnosticsStatusLabel(value); + } + return value; +} + +const RUN_LIST_STATUSES = new Set(Object.keys(RUN_STATUS_WORD)); + +function isRunListStatus(value: string): value is RunListProjectionRecord['status'] { + return RUN_LIST_STATUSES.has(value); +} + +export interface DiagnosticsFilterChip { + field: F; + /** Applied filter in words, for example "Device cuda:0". */ + label: string; +} + +export function buildDiagnosticsExecutionFilterChips( + filters: DiagnosticsExecutionFilters, +): DiagnosticsFilterChip[] { + return DIAGNOSTICS_EXECUTION_FILTER_FIELDS.filter(({ field }) => filters[field] !== DIAGNOSTICS_FILTER_ALL).map( + ({ field, label }) => ({ field, label: `${label} ${filters[field]}` }), + ); +} + +export function buildDiagnosticsComparisonFilterChips( + filters: DiagnosticsComparisonFilters, +): DiagnosticsFilterChip[] { + const chips: DiagnosticsFilterChip[] = []; + for (const descriptor of DIAGNOSTICS_COMPARISON_FILTER_FIELDS) { + const value = filters[descriptor.field]; + const applied = descriptor.input === 'date' ? value.trim().length > 0 : value !== DIAGNOSTICS_FILTER_ALL; + if (applied) { + chips.push({ + field: descriptor.field, + label: `${descriptor.label} ${formatDiagnosticsComparisonOption(descriptor.field, value)}`, + }); + } + } + return chips; +} + +/** The value a cleared filter field returns to. */ +export function defaultDiagnosticsComparisonFilterValue(field: keyof DiagnosticsComparisonFilters): string { + return DEFAULT_DIAGNOSTICS_COMPARISON_FILTERS[field]; +} + +export interface DiagnosticsComparisonShortcut { + id: 'version' | 'device' | 'recent'; + label: string; + pressed: boolean; + /** Filters after the shortcut is toggled. */ + toggled: DiagnosticsComparisonFilters; +} + +const RECENT_COMPARISON_DAYS = 7; + +/** UTC date (the comparison date filters compare in UTC) of the first day of the recent window. */ +export function diagnosticsRecentFromDate(nowMs: number): string { + return new Date(nowMs - (RECENT_COMPARISON_DAYS - 1) * MS_PER_DAY).toISOString().slice(0, 10); +} + +/** + * The board's quick pills ("Only v0.9.1", "Only cuda:1", "Last 7 days"), + * expressed as presets over the existing comparison filters. + */ +export function buildDiagnosticsComparisonShortcuts( + run: RunDetailProjectionRecord, + filters: DiagnosticsComparisonFilters, + nowMs: number, +): DiagnosticsComparisonShortcut[] { + const shortcuts: DiagnosticsComparisonShortcut[] = []; + const version = workflowVersionLabel(run); + const versionPressed = filters.workflowVersion === version; + shortcuts.push({ + id: 'version', + label: version === 'Unversioned' ? 'Only unversioned' : `Only v${version}`, + pressed: versionPressed, + toggled: { ...filters, workflowVersion: versionPressed ? DIAGNOSTICS_FILTER_ALL : version }, + }); + if (run.selected_device_id) { + const devicePressed = filters.selectedDevice === run.selected_device_id; + shortcuts.push({ + id: 'device', + label: `Only ${run.selected_device_id}`, + pressed: devicePressed, + toggled: { ...filters, selectedDevice: devicePressed ? DIAGNOSTICS_FILTER_ALL : run.selected_device_id }, + }); + } + const from = diagnosticsRecentFromDate(nowMs); + const recentPressed = filters.acceptedFromDate === from && filters.acceptedToDate.trim().length === 0; + shortcuts.push({ + id: 'recent', + label: `Last ${RECENT_COMPARISON_DAYS} days`, + pressed: recentPressed, + toggled: { ...filters, acceptedFromDate: recentPressed ? '' : from, acceptedToDate: '' }, + }); + return shortcuts; +} + +// --- "Compared with earlier runs" ------------------------------------------- + +export interface DiagnosticsComparisonSummary { + /** Big number, for example "3 of 14". */ + failed: string; + failedLabel: string; + /** Big number: median duration of the other completed runs, for example "1m 49s", or "None yet". */ + median: string; + medianLabel: string; + note: string; +} + +function median(values: number[]): number | null { + if (values.length === 0) return null; + const sorted = [...values].sort((left, right) => left - right); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; +} + +/** + * Comparison of the selected run with the run-list peers that pass the + * comparison filters. `comparedRuns` is `filterDiagnosticsComparisonRuns` + * output, so it starts with the selected run. + */ +export function buildDiagnosticsComparisonSummary( + run: RunDetailProjectionRecord, + comparedRuns: RunListProjectionRecord[], +): DiagnosticsComparisonSummary { + const total = comparedRuns.length; + const failedRuns = comparedRuns.filter((candidate) => candidate.status === 'failed'); + const peers = comparedRuns.filter((candidate) => candidate.workflow_run_id !== run.workflow_run_id); + // The median describes the other runs, so this run is compared against it rather than with itself. + const completedDurations = peers + .filter((candidate) => candidate.status === 'completed' && typeof candidate.duration_ms === 'number') + .map((candidate) => candidate.duration_ms as number); + const medianMs = median(completedDurations); + + let note: string; + if (peers.length === 0) { + note = `No other runs of ${run.workflow_id} in the run list match these filters.`; + } else if (run.status === 'failed') { + const failedPeers = peers.filter((candidate) => candidate.status === 'failed'); + const code = run.latest_error_code; + const sameCode = code ? failedPeers.filter((candidate) => candidate.latest_error_code === code).length : 0; + if (failedPeers.length === 0) { + note = `None of the other ${plural(peers.length, 'compared run')} failed.`; + } else { + note = + `${failedPeers.length} of the other ${plural(peers.length, 'compared run')} also failed` + + (sameCode > 0 ? `, ${sameCode} with ${code}.` : '.'); + } + } else if (medianMs !== null && typeof run.duration_ms === 'number') { + note = `This run took ${formatDiagnosticsElapsed(run.duration_ms)}; the median completed run took ${formatDiagnosticsElapsed(medianMs)}.`; + } else { + note = `${completedDurations.length} of the other ${plural(peers.length, 'compared run')} completed with a recorded duration.`; + } + + return { + failed: `${failedRuns.length} of ${total}`, + failedLabel: `runs of ${run.workflow_id} failed`, + median: medianMs === null ? 'None yet' : formatDiagnosticsElapsed(medianMs), + medianLabel: 'median duration of the other completed runs', + note, + }; +} + +// --- Event log ---------------------------------------------------------------- + +export type DiagnosticsLevelFilter = 'all' | 'warn' | 'error'; +export type DiagnosticsSourceFilter = 'all' | 'scheduler' | 'runtime' | 'nodes'; + +export const DIAGNOSTICS_SOURCE_OPTIONS: SegmentOption[] = [ + { value: 'all', label: 'All sources' }, + { value: 'scheduler', label: 'Scheduler' }, + { value: 'runtime', label: 'Runtime' }, + { value: 'nodes', label: 'Nodes' }, +]; + +const SOURCE_FILTER_COMPONENT: Record, DiagnosticEventSourceComponent> = { + scheduler: 'scheduler', + runtime: 'runtime', + nodes: 'node_execution', +}; + +/** Log level of a timeline event: error and fatal are errors, warning is a warning. */ +export function diagnosticsSeverityLevel(severity: DiagnosticErrorSeverity | null | undefined): LogLevel { + switch (severity) { + case 'fatal': + case 'error': + return 'error'; + case 'warning': + return 'warn'; + case null: + case undefined: + return 'info'; + } +} + +export interface DiagnosticsLogLine { + eventId: string; + /** DOM id of the rendered line, used to scroll a focused event into view. */ + domId: string; + seq: number; + time: string; + level: LogLevel; + kind: string; + message: string; + source: string; + sourceComponent: DiagnosticEventSourceComponent; + /** Node whose error this event is, when the node status projection links them. */ + nodeId: string | null; + searchText: string; +} + +export function diagnosticsLogLineDomId(eventSeq: number): string { + return `diagnostics-event-${eventSeq}`; +} + +/** + * Timeline events as log lines, in event order. A node's error appears as its + * own line: the event the node status row points at takes the node id as its + * kind, the node's error code in the message, and at least error level. + */ +export function buildDiagnosticsLogLines( + events: SchedulerTimelineProjectionRecord[], + nodes: NodeStatusProjectionRecord[], +): DiagnosticsLogLine[] { + const nodeByErrorEvent = new Map(); + for (const node of nodes) { + if (node.canonical_error_event_id) nodeByErrorEvent.set(node.canonical_error_event_id, node); + if (node.error_event_id && !nodeByErrorEvent.has(node.error_event_id)) nodeByErrorEvent.set(node.error_event_id, node); + } + return [...events] + .sort((left, right) => left.event_seq - right.event_seq) + .map((event) => { + const node = nodeByErrorEvent.get(event.event_id) ?? null; + const eventLevel = diagnosticsSeverityLevel(event.error_severity); + const level = node && eventLevel === 'info' ? diagnosticsSeverityLevel(node.error_severity ?? 'error') : eventLevel; + const phase = event.error_phase ?? node?.error_phase ?? null; + const message = [ + event.summary, + event.detail ?? null, + phase ? `phase ${diagnosticsWords(phase)}` : null, + node?.error_code ?? null, + ] + .filter((part): part is string => Boolean(part && part.trim().length > 0)) + .join(', '); + const source = [ + formatDiagnosticSourceComponent(event.source_component), + `seq ${event.event_seq}`, + hasTimelinePayload(event) ? 'payload captured' : null, + ] + .filter((part): part is string => part !== null) + .join(', '); + const kind = node ? node.node_id : formatDiagnosticEventKind(event.event_kind); + return { + eventId: event.event_id, + domId: diagnosticsLogLineDomId(event.event_seq), + seq: event.event_seq, + time: formatDiagnosticsLogTime(event.occurred_at_ms), + level, + kind, + message, + source, + sourceComponent: event.source_component, + nodeId: node?.node_id ?? null, + searchText: `${kind} ${message} ${source} ${event.event_id}`.toLowerCase(), + }; + }); +} + +export function buildDiagnosticsLevelOptions(lines: DiagnosticsLogLine[]): SegmentOption[] { + return [ + { value: 'all', label: 'All', count: lines.length }, + { value: 'warn', label: 'Warnings', count: lines.filter((line) => line.level === 'warn').length }, + { value: 'error', label: 'Errors', count: lines.filter((line) => line.level === 'error').length }, + ]; +} + +export interface DiagnosticsLogFilter { + level: DiagnosticsLevelFilter; + source: DiagnosticsSourceFilter; + query: string; +} + +export function filterDiagnosticsLogLines(lines: DiagnosticsLogLine[], filter: DiagnosticsLogFilter): DiagnosticsLogLine[] { + const query = filter.query.trim().toLowerCase(); + const component = filter.source === 'all' ? null : SOURCE_FILTER_COMPONENT[filter.source]; + return lines.filter( + (line) => + (filter.level === 'all' || line.level === filter.level) && + (component === null || line.sourceComponent === component) && + (query.length === 0 || line.searchText.includes(query)), + ); +} + +/** + * Nodes with an error whose error event is not in the timeline. These keep a + * compact table under the error card so no node error is unreachable. + */ +export function buildDiagnosticsNodeErrorsOutsideTimeline( + nodes: NodeStatusProjectionRecord[], + events: SchedulerTimelineProjectionRecord[], +): NodeStatusProjectionRecord[] { + const eventIds = new Set(events.map((event) => event.event_id)); + return nodes.filter((node) => { + if (!diagnosticsNodeHasError(node)) return false; + const ids = [node.canonical_error_event_id, node.error_event_id].filter((id): id is string => Boolean(id)); + return !ids.some((id) => eventIds.has(id)); + }); +} + +export function diagnosticsNodeErrorEventLabel(node: NodeStatusProjectionRecord): string { + return nodeErrorEventId(node) ?? 'Not linked'; +} + +// --- Deep-link focus ------------------------------------------------------------ + +/** Structural copy of `DiagnosticsFocusTarget` (workbenchStore) so presenters stay store-free. */ +export interface DiagnosticsFocusRequest { + workflow_run_id: string; + diagnostic_event_id?: string | null; + node_id?: string | null; + requested_at_ms: number; +} + +export interface DiagnosticsFocusResolution { + /** Event to mark selected; null when the focus names only a node with no linked event. */ + eventId: string | null; + nodeId: string | null; + /** DOM id of the line to scroll into view; null when the event is not in the timeline. */ + lineDomId: string | null; + /** Level filter that shows the focused line. */ + level: DiagnosticsLevelFilter; +} + +/** Identity of one focus request; the page applies each request once. */ +export function diagnosticsFocusKey(focus: DiagnosticsFocusRequest): string { + return `${focus.workflow_run_id}:${focus.requested_at_ms}`; +} + +/** + * Resolve the workbench diagnostics focus for the loaded run: which line to + * select and scroll to, and which level filter shows it. Returns null when + * there is no focus or it belongs to another run. + */ +export function resolveDiagnosticsFocus( + focus: DiagnosticsFocusRequest | null, + runId: string, + lines: DiagnosticsLogLine[], + nodes: NodeStatusProjectionRecord[], +): DiagnosticsFocusResolution | null { + if (!focus || focus.workflow_run_id !== runId) { + return null; + } + const focusedNode = focus.node_id ? nodes.find((node) => node.node_id === focus.node_id) : undefined; + const eventId = focus.diagnostic_event_id ?? (focusedNode ? nodeErrorEventId(focusedNode) : null); + const line = + (eventId ? lines.find((candidate) => candidate.eventId === eventId) : undefined) ?? + (focus.node_id ? lines.find((candidate) => candidate.nodeId === focus.node_id) : undefined); + return { + eventId: line?.eventId ?? eventId, + nodeId: focus.node_id ?? line?.nodeId ?? null, + lineDomId: line?.domId ?? null, + level: line && line.level !== 'info' ? line.level : 'all', + }; +} + +// --- Error card ----------------------------------------------------------------- + +export interface DiagnosticsErrorExplanation { + title: string; + explanation: string; + /** Starts with "Try:". */ + suggestion: string; +} + +interface KnownDiagnosticsError { + title: string; + /** What happened, completed by the projected message. */ + lead: string; + suggestion: string; +} + +/** + * Plain-language explanations for diagnostic error codes from the workflow + * service error registry (`crates/pantograph-workflow-service/src/workflow/diagnostic_errors.rs`). + * Codes not listed here use the neutral fallback, which restates the message. + */ +const KNOWN_DIAGNOSTICS_ERRORS: Record = { + runtime_model_load_failed: { + title: 'Model failed to load', + lead: 'The runtime could not load the model for this run', + suggestion: + 'Try: check free memory on the device the run was placed on (Network shows it), or choose a smaller model, then run the workflow again.', + }, + runtime_preflight_failed: { + title: 'Runtime check failed before start', + lead: 'The scheduler checked the runtime and model before starting and the check did not pass', + suggestion: 'Try: confirm the runtime and model the workflow asks for are installed, then run it again.', + }, + runtime_launch_failed: { + title: 'Runtime did not start', + lead: 'The runtime process for this run could not be started', + suggestion: 'Try: check the runtime installation in Settings, then run the workflow again.', + }, + scheduler_admission_failed: { + title: 'Scheduler did not admit the run', + lead: 'The scheduler could not admit this run', + suggestion: 'Try: check the placement and device memory in Scheduler and Network, then submit the run again.', + }, + model_dependency_failed: { + title: 'Model dependency unavailable', + lead: 'A dependency the model needs could not be resolved', + suggestion: 'Try: open the model in Library and resolve its dependencies, then run the workflow again.', + }, + node_execution_failed: { + title: 'Node failed', + lead: 'A node stopped with an error while the run executed', + suggestion: "Try: look at the node's inputs in I/O Inspector, fix the input or the node's settings, then run it again.", + }, + output_validation_failed: { + title: 'Output did not match its port', + lead: 'A node produced output that did not match its declared port type', + suggestion: "Try: compare the node's output in I/O Inspector with the type its port declares.", + }, + run_timeout: { + title: 'Run timed out', + lead: 'The run did not finish within its time limit', + suggestion: 'Try: run it again when the device is less busy, or with a longer time limit.', + }, +}; + +const FALLBACK_DIAGNOSTICS_SUGGESTION = 'Try: show the error in the log to see the events that led up to it.'; + +function asSentence(text: string): string { + const trimmed = text.trim(); + if (trimmed.length === 0) return trimmed; + return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`; +} + +/** + * Title, one-sentence explanation and "Try:" advice for a diagnostic error, + * from its code and message. Known codes get a specific explanation; any other + * code gets a neutral sentence that restates the message. + */ +export function explainDiagnosticsError(input: { + code: string | null | undefined; + message: string | null | undefined; + phase?: string | null; + nodeId?: string | null; +}): DiagnosticsErrorExplanation { + const message = input.message?.trim() ?? ''; + const where = input.nodeId ? ` in ${input.nodeId}` : ''; + const known = input.code ? KNOWN_DIAGNOSTICS_ERRORS[input.code] : undefined; + if (known) { + return { + title: `${known.title}${where}`, + explanation: asSentence(message.length > 0 ? `${known.lead}: ${message}` : known.lead), + suggestion: known.suggestion, + }; + } + const phase = input.phase && input.phase !== 'unassigned' ? formatDiagnosticErrorPhase(input.phase) : null; + return { + title: phase ? `${phase} failed${where}` : `The run reported an error${where}`, + explanation: message.length > 0 ? asSentence(`The run reported: ${message}`) : 'No error message was projected for this run.', + suggestion: FALLBACK_DIAGNOSTICS_SUGGESTION, + }; +} + +export interface DiagnosticsErrorCard extends DiagnosticsErrorExplanation { + /** `error` renders the danger card; `warning` renders a muted line instead. */ + kind: 'error' | 'warning'; + /** Muted machine detail: code, phase and severity. */ + codeLine: string; + eventId: string | null; + nodeId: string | null; +} + +/** + * The run's latest or terminal error as an error card, or null when the run + * has none. A warning on a run that did not fail is returned with kind + * `warning` so the page can mention it without the danger treatment. + */ +export function buildDiagnosticsErrorCard( + run: RunDetailProjectionRecord, + nodes: NodeStatusProjectionRecord[], +): DiagnosticsErrorCard | null { + const summary = buildDiagnosticsRunErrorSummary(run); + if (!summary && !run.terminal_error) { + return null; + } + const eventId = summary && summary.eventId !== 'unassigned' ? summary.eventId : null; + const code = summary?.code ?? 'unknown_error'; + const phase = summary?.phase ?? 'unassigned'; + const severity: DiagnosticErrorSeverity = summary?.severity ?? 'fatal'; + const message = summary?.message ?? run.terminal_error ?? null; + const node = + (eventId ? nodes.find((candidate) => nodeErrorEventId(candidate) === eventId) : undefined) ?? + nodes.find((candidate) => candidate.status === 'failed'); + const nodeId = node?.node_id ?? null; + const explanation = explainDiagnosticsError({ code, message, phase, nodeId }); + const codeParts = [code]; + if (phase !== 'unassigned') codeParts.push(`phase ${diagnosticsWords(phase)}`); + codeParts.push(formatDiagnosticErrorSeverity(severity).toLowerCase()); + return { + ...explanation, + kind: severity === 'warning' && run.status !== 'failed' ? 'warning' : 'error', + codeLine: codeParts.join(', '), + eventId, + nodeId, + }; +} + +// --- Refresh ownership ------------------------------------------------------------ + +/** + * Current-invocation authority for the page's projection refreshes. The page + * owns one gate: each refresh takes a token, and only the newest token may + * apply its results. `close()` (on destroy) makes every outstanding token stale. + */ +export interface DiagnosticsRefreshGate { + begin(): number; + isCurrent(token: number): boolean; + close(): void; +} + +export function createDiagnosticsRefreshGate(): DiagnosticsRefreshGate { + let generation = 0; + let closed = false; + return { + begin() { + generation += 1; + return generation; + }, + isCurrent(token) { + return !closed && token === generation; + }, + close() { + closed = true; + generation += 1; + }, + }; +} diff --git a/src/components/workbench/graphInspectionPresenters.test.ts b/src/components/workbench/graphInspectionPresenters.test.ts index e1db56e32..82c5f9e24 100644 --- a/src/components/workbench/graphInspectionPresenters.test.ts +++ b/src/components/workbench/graphInspectionPresenters.test.ts @@ -9,6 +9,16 @@ import { resolveSavedGraphSelectedNodeId, resolveSavedWorkflowInspectionPath, savedGraphNodeFocusDomId, + buildNodePaletteTree, + editNodeExecutionGlyph, + formatEditCurrentLabel, + formatEditDimensionLabel, + formatRunDimensionLabel, + formatRunModeLabel, + formatWorkflowModifiedShort, + formatWorkflowSaveLine, + resolveGraphPageMode, + runIdSuffix, } from './graphInspectionPresenters.ts'; import type { WorkflowGraphInspectionProjection } from '../../services/workflow/types.ts'; @@ -188,3 +198,126 @@ test('saved graph inspection selection helpers preserve valid frontend selection assert.equal(resolveSavedGraphSelectedNodeId('first', projection), 'first'); assert.equal(resolveSavedGraphSelectedNodeId('missing', projection), 'stale'); }); + +const RUN = { workflow_run_id: 'run_7c9e6679-7425-40de-944b-e07fc1f90ae7', workflow_id: 'ingest-docs-rag' }; + +test('graph page opens a run as run when its workflow is the one being edited', () => { + assert.deepEqual( + resolveGraphPageMode({ activeRun: RUN, loadedWorkflowId: 'ingest-docs-rag', request: null }), + { mode: 'run', runAvailable: true, workflowMismatch: false }, + ); +}); + +test('graph page stays in edit mode and offers the run when the run is of another workflow', () => { + assert.deepEqual( + resolveGraphPageMode({ activeRun: RUN, loadedWorkflowId: 'summarize-daily', request: null }), + { mode: 'edit', runAvailable: true, workflowMismatch: true }, + ); + assert.deepEqual( + resolveGraphPageMode({ activeRun: RUN, loadedWorkflowId: null, request: null }), + { mode: 'edit', runAvailable: true, workflowMismatch: true }, + 'a system graph or a loading editor is never the run workflow', + ); +}); + +test('graph page without a run is always the editor', () => { + assert.deepEqual( + resolveGraphPageMode({ + activeRun: null, + loadedWorkflowId: 'ingest-docs-rag', + request: { runId: null, mode: 'run' }, + }), + { mode: 'edit', runAvailable: false, workflowMismatch: false }, + ); +}); + +test('an explicit mode choice holds for its run and resets when another run is selected', () => { + const editRequest = { runId: RUN.workflow_run_id, mode: 'edit' as const }; + assert.equal( + resolveGraphPageMode({ activeRun: RUN, loadedWorkflowId: 'ingest-docs-rag', request: editRequest }).mode, + 'edit', + ); + const runRequest = { runId: RUN.workflow_run_id, mode: 'run' as const }; + const shown = resolveGraphPageMode({ activeRun: RUN, loadedWorkflowId: 'summarize-daily', request: runRequest }); + assert.equal(shown.mode, 'run'); + assert.equal(shown.workflowMismatch, false); + const otherRun = { workflow_run_id: 'run_other', workflow_id: 'ingest-docs-rag' }; + assert.equal( + resolveGraphPageMode({ activeRun: otherRun, loadedWorkflowId: 'ingest-docs-rag', request: editRequest }).mode, + 'run', + ); + const noWorkflow = { workflow_run_id: 'run_x', workflow_id: null }; + assert.deepEqual( + resolveGraphPageMode({ activeRun: noWorkflow, loadedWorkflowId: 'ingest-docs-rag', request: null }), + { mode: 'edit', runAvailable: true, workflowMismatch: false }, + ); +}); + +test('graph page labels use the last six characters of the run id', () => { + assert.equal(runIdSuffix(RUN.workflow_run_id), 'f90ae7'); + assert.equal(runIdSuffix('run_1'), 'run_1'); + assert.equal(formatRunModeLabel(RUN.workflow_run_id), 'As run f90ae7'); + assert.equal(formatRunModeLabel(null), 'As a run…'); + assert.equal(formatEditDimensionLabel('1.4.1', 6, 1), 'Editing v1.4.1, 6 nodes, 1 edge'); + assert.equal(formatEditDimensionLabel(null, 1, 0), 'Viewing, 1 node, 0 edges'); + assert.equal( + formatRunDimensionLabel(1, RUN.workflow_run_id, 'Running'), + '1 node as run f90ae7 ran them, running', + ); + assert.equal(formatEditCurrentLabel('1.4.1'), 'Edit current v1.4.1'); + assert.equal(formatEditCurrentLabel(null), 'Edit current version'); +}); + +test('save line prefers unsaved changes, then the saved time', () => { + assert.equal(formatWorkflowSaveLine({ isDirty: true, savedModifiedAt: '2026-11-03T10:00:00Z' }), 'Unsaved changes'); + assert.equal(formatWorkflowSaveLine({ isDirty: false, savedModifiedAt: null }), 'Not saved yet'); + assert.equal(formatWorkflowSaveLine({ isDirty: false, savedModifiedAt: 'not a date' }), 'Saved'); + const modified = new Date(2026, 10, 3, 20, 4).toISOString(); + assert.equal(formatWorkflowSaveLine({ isDirty: false, savedModifiedAt: modified }), 'Saved 20:04'); +}); + +test('editor execution states map to the shared glyphs', () => { + assert.deepEqual(editNodeExecutionGlyph('running'), { glyph: 'running', label: 'Running' }); + assert.deepEqual(editNodeExecutionGlyph('waiting'), { glyph: 'waiting', label: 'Waiting' }); + assert.deepEqual(editNodeExecutionGlyph('success'), { glyph: 'succeeded', label: 'Done' }); + assert.deepEqual(editNodeExecutionGlyph('error'), { glyph: 'failed', label: 'Failed' }); + assert.deepEqual(editNodeExecutionGlyph(undefined), { glyph: 'idle', label: 'Idle' }); +}); + +test('palette tree counts nodes per category, shows in:out ports and opens matches while searching', () => { + const def = (node_type: string, label: string, inputs: number, outputs: number, description = '') => ({ + node_type, + label, + description, + inputs: Array.from({ length: inputs }, () => ({})), + outputs: Array.from({ length: outputs }, () => ({})), + }); + const catalogue = new Map([ + ['input', [def('text-input', 'Text input', 0, 1), def('read-file', 'Read file', 0, 1, 'reads text')]], + ['processing', [def('llm-inference', 'LLM inference', 4, 3)]], + ['tool_kit', [def('unload-model', 'Unload model', 1, 0)]], + ]); + + const tree = buildNodePaletteTree(catalogue, '', new Set(['input'])); + assert.deepEqual( + tree.map((category) => [category.label, category.count, category.expanded]), + [['Input', 2, true], ['Processing', 1, false], ['Tool kit', 1, false]], + ); + assert.equal(tree[1].items[0].ports, '4:3'); + assert.equal(tree[1].items[0].portsTitle, '4 inputs, 3 outputs'); + + const searched = buildNodePaletteTree(catalogue, ' TEXT ', new Set()); + assert.deepEqual( + searched.map((category) => [category.key, category.count, category.expanded]), + [['input', 2, true]], + 'description matches count too', + ); + assert.deepEqual(buildNodePaletteTree(catalogue, 'nothing', new Set()), []); +}); + +test('workflow list shows the time for today and the date otherwise', () => { + const now = new Date(2026, 10, 3, 21, 0).getTime(); + assert.equal(formatWorkflowModifiedShort(new Date(2026, 10, 3, 20, 4).toISOString(), now), '20:04'); + assert.equal(formatWorkflowModifiedShort(new Date(2026, 9, 29, 9, 0).toISOString(), now), 'Oct 29'); + assert.equal(formatWorkflowModifiedShort('garbage', now), ''); +}); diff --git a/src/components/workbench/graphInspectionPresenters.ts b/src/components/workbench/graphInspectionPresenters.ts index a9317219f..ca2a90bfc 100644 --- a/src/components/workbench/graphInspectionPresenters.ts +++ b/src/components/workbench/graphInspectionPresenters.ts @@ -5,6 +5,7 @@ import type { WorkflowMetadata, } from '../../services/workflow/types'; import { buildRunGraphCanvasModel, type RunGraphCanvasModel } from './runGraphPresenters.ts'; +import type { GlyphState } from './ui/statusGlyph.ts'; const SAVED_WORKFLOW_INSPECTION_ROOT = '.pantograph/workflows'; const WORKFLOW_FILE_EXTENSION = '.json'; @@ -133,3 +134,211 @@ function diagnosticsForSelectedNode( } return projection.diagnostics.filter((diagnostic) => diagnostic.node_id === selectedNodeId); } + +// --- Graph page: edit and run modes --- + +export type GraphPageMode = 'edit' | 'run'; + +/** A mode the user picked explicitly; it holds only while the same run is selected. */ +export interface GraphPageModeRequest { + runId: string | null; + mode: GraphPageMode; +} + +export interface GraphPageModeInput { + /** The shared run context (workbenchStore), or null when no run is selected. */ + activeRun: { workflow_run_id: string; workflow_id?: string | null } | null; + /** Saved workflow open in the editor; null for system graphs or while loading. */ + loadedWorkflowId: string | null; + request: GraphPageModeRequest | null; +} + +export interface GraphPageModeResolution { + mode: GraphPageMode; + /** A run is selected, so run mode can be entered. */ + runAvailable: boolean; + /** Edit mode while the selected run belongs to another workflow: offer "Show as run". */ + workflowMismatch: boolean; +} + +/** + * Which mode the Graph page shows. Default: run mode when the selected run is + * of the workflow open in the editor, edit mode otherwise. An explicit choice + * made for the current run wins; selecting another run returns to the default. + */ +export function resolveGraphPageMode(input: GraphPageModeInput): GraphPageModeResolution { + const run = input.activeRun; + if (!run) { + return { mode: 'edit', runAvailable: false, workflowMismatch: false }; + } + const runWorkflowId = run.workflow_id?.trim() || null; + const sameWorkflow = runWorkflowId !== null && runWorkflowId === input.loadedWorkflowId; + const requested = + input.request && input.request.runId === run.workflow_run_id ? input.request.mode : null; + const mode: GraphPageMode = requested ?? (sameWorkflow ? 'run' : 'edit'); + return { + mode, + runAvailable: true, + workflowMismatch: mode === 'edit' && runWorkflowId !== null && !sameWorkflow, + }; +} + +/** Last characters of a run id, as shown in the mode switch. */ +export function runIdSuffix(runId: string, length = 6): string { + return runId.length <= length ? runId : runId.slice(-length); +} + +export function formatRunModeLabel(runId: string | null): string { + return runId ? `As run ${runIdSuffix(runId)}` : 'As a run…'; +} + +/** Edit-mode summary; `version` is null for read-only system graphs, which have none. */ +export function formatEditDimensionLabel( + version: string | null, + nodeCount: number, + edgeCount: number, +): string { + const counts = `${pluralize(nodeCount, 'node')}, ${pluralize(edgeCount, 'edge')}`; + return version ? `Editing v${version}, ${counts}` : `Viewing, ${counts}`; +} + +export function formatRunDimensionLabel( + nodeCount: number, + runId: string, + statusLabel: string, +): string { + return `${pluralize(nodeCount, 'node')} as run ${runIdSuffix(runId)} ran them, ${statusLabel.toLowerCase()}`; +} + +export function formatEditCurrentLabel(version: string | null): string { + return version ? `Edit current v${version}` : 'Edit current version'; +} + +/** "Saved 20:04", "Unsaved changes" or "Not saved yet" for the toolbar status. */ +export function formatWorkflowSaveLine(input: { + isDirty: boolean; + savedModifiedAt: string | null; +}): string { + if (input.isDirty) { + return 'Unsaved changes'; + } + if (!input.savedModifiedAt) { + return 'Not saved yet'; + } + const modified = new Date(input.savedModifiedAt); + if (Number.isNaN(modified.getTime())) { + return 'Saved'; + } + const hh = String(modified.getHours()).padStart(2, '0'); + const mm = String(modified.getMinutes()).padStart(2, '0'); + return `Saved ${hh}:${mm}`; +} + +const SHORT_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +/** Modified time in the workflow list: "20:04" today, "Oct 29" otherwise. */ +export function formatWorkflowModifiedShort(modifiedAt: string, nowMs: number): string { + const modified = new Date(modifiedAt); + if (Number.isNaN(modified.getTime())) { + return ''; + } + const now = new Date(nowMs); + const sameDay = + modified.getFullYear() === now.getFullYear() && + modified.getMonth() === now.getMonth() && + modified.getDate() === now.getDate(); + if (sameDay) { + return `${String(modified.getHours()).padStart(2, '0')}:${String(modified.getMinutes()).padStart(2, '0')}`; + } + return `${SHORT_MONTHS[modified.getMonth()]} ${modified.getDate()}`; +} + +/** Editor node execution state (svelte-graph) to the shared glyph and its words. */ +export function editNodeExecutionGlyph(state: string | null | undefined): { + glyph: GlyphState; + label: string; +} { + switch (state) { + case 'running': + return { glyph: 'running', label: 'Running' }; + case 'waiting': + return { glyph: 'waiting', label: 'Waiting' }; + case 'success': + return { glyph: 'succeeded', label: 'Done' }; + case 'error': + return { glyph: 'failed', label: 'Failed' }; + default: + return { glyph: 'idle', label: 'Idle' }; + } +} + +export interface PaletteDefinitionLike { + node_type: string; + label: string; + description: string; + inputs: unknown[]; + outputs: unknown[]; +} + +export interface NodePaletteItem { + definition: D; + label: string; + /** "in:out" port counts, for example "2:1". */ + ports: string; + portsTitle: string; +} + +export interface NodePaletteCategory { + key: string; + label: string; + count: number; + expanded: boolean; + items: NodePaletteItem[]; +} + +/** + * Palette tree: categories in catalogue order with their matching node count. + * While searching, every category with matches is open so results are visible. + */ +export function buildNodePaletteTree( + byCategory: ReadonlyMap, + query: string, + expandedCategories: ReadonlySet, +): NodePaletteCategory[] { + const needle = query.trim().toLowerCase(); + const categories: NodePaletteCategory[] = []; + for (const [category, definitions] of byCategory) { + const matches = needle + ? definitions.filter( + (definition) => + definition.label.toLowerCase().includes(needle) || + definition.description.toLowerCase().includes(needle), + ) + : [...definitions]; + if (matches.length === 0) { + continue; + } + categories.push({ + key: category, + label: formatPaletteCategoryLabel(category), + count: matches.length, + expanded: needle.length > 0 || expandedCategories.has(category), + items: matches.map((definition) => ({ + definition, + label: definition.label, + ports: `${definition.inputs.length}:${definition.outputs.length}`, + portsTitle: `${pluralize(definition.inputs.length, 'input')}, ${pluralize(definition.outputs.length, 'output')}`, + })), + }); + } + return categories; +} + +export function formatPaletteCategoryLabel(category: string): string { + const words = category.replaceAll('_', ' ').trim(); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +function pluralize(count: number, noun: string): string { + return count === 1 ? `1 ${noun}` : `${count} ${noun}s`; +} diff --git a/src/components/workbench/ioInspectorPresenters.test.ts b/src/components/workbench/ioInspectorPresenters.test.ts index 539bc3c02..b684da61f 100644 --- a/src/components/workbench/ioInspectorPresenters.test.ts +++ b/src/components/workbench/ioInspectorPresenters.test.ts @@ -1,6 +1,9 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import type { IoArtifactProjectionRecord, ResolvedNodeIoRecord } from '../../services/diagnostics/types'; +import type { WorkflowGraphDiagnostic } from '../../services/workflow/types'; + import { assertCompleteIoArtifactImageRead, buildIoArtifactDescriptorMetadataRows, @@ -36,6 +39,27 @@ import { isNormalResolvedNodeIoDisplayRow, isWorkflowInputArtifact, isWorkflowOutputArtifact, + IO_INSPECTOR_BOUNDARY_NODE_ID, + applyIoInspectorBackendFilter, + buildIoArtifactChipLabels, + buildIoArtifactDetailSections, + buildIoInspectorDimensionLabel, + buildIoInspectorNodeTree, + buildStaleGraphFactCards, + countIoInspectorEntriesByDirection, + createIoArtifactDownloadUrlOwner, + describeIoArtifactAcknowledgeUnavailable, + describeIoArtifactReadUnavailable, + describeIoArtifactStreamUnavailable, + filterIoInspectorNodeTree, + findIoInspectorEntry, + formatIoInspectorEntryDetail, + formatIoInspectorNodeSubLabel, + parseGraphCanvasViewBox, + partitionGraphDiagnosticsByNode, + resolveIoArtifactPreviewMode, + resolveIoInspectorSelectedEntryKey, + sentenceCaseLabel, } from './ioInspectorPresenters.ts'; test('classifyIoArtifactMedia groups common artifact media types', () => { @@ -794,3 +818,334 @@ test('retention cleanup detail rows expose backend cleanup status', () => { assert.equal(rows.find((row) => row.label === 'Last Event Seq')?.value, '44'); assert.deepEqual(buildRetentionCleanupDetailRows(null), []); }); + +// --- Node and port tree (workbench redesign M3) ----------------------------- + + +function treeArtifact(overrides: Partial & { artifact_id: string }): IoArtifactProjectionRecord { + return { + event_seq: 1, + event_id: `event-${overrides.artifact_id}`, + occurred_at_ms: 1_000, + recorded_at_ms: 1_000, + workflow_run_id: 'run-1', + workflow_id: 'wf', + artifact_role: 'node_output', + retention_state: 'retained', + ...overrides, + }; +} + +function resolved(overrides: Partial & Pick): ResolvedNodeIoRecord { + return { resolution: overrides.direction === 'input' ? 'derived_from_edge' : 'produced_output', ...overrides }; +} + +const promptText = treeArtifact({ + artifact_id: 'art-prompt', + producer_node_id: 'prompt', + producer_port_id: 'text', + consumer_node_id: 'sample', + consumer_port_id: 'prompt', + media_type: 'text/plain', + payload_kind: 'text', + size_bytes: 412, +}); +const decodedImage = treeArtifact({ + artifact_id: 'art-image', + producer_node_id: 'decode', + producer_port_id: 'image', + media_type: 'image/png', + payload_kind: 'image', + size_bytes: 4 * 1_048_576, + artifact_role: 'workflow_output', +}); +const latents = treeArtifact({ + artifact_id: 'art-latents', + producer_node_id: 'sample', + producer_port_id: 'latents', + media_type: 'application/octet-stream', + payload_kind: 'generic_binary', + retention_state: 'metadata_only', + size_bytes: 33 * 1_048_576, +}); + +function sampleTree() { + return buildIoInspectorNodeTree({ + graphNodes: [ + { id: 'prompt', node_type: 'text-input' }, + { id: 'sample', node_type: 'pytorch-inference' }, + { id: 'decode', node_type: 'image-output' }, + { id: 'unload', node_type: 'unload-model' }, + ], + nodeStatuses: [ + { node_id: 'prompt', status: 'completed' }, + { node_id: 'sample', status: 'running' }, + { node_id: 'unload', status: 'queued' }, + ], + resolvedNodeIo: [ + resolved({ node_id: 'prompt', port_id: 'text', direction: 'output', artifact_id: 'art-prompt' }), + resolved({ + node_id: 'sample', + port_id: 'prompt', + direction: 'input', + artifact_id: 'art-prompt', + upstream_node_id: 'prompt', + upstream_port_id: 'text', + }), + resolved({ node_id: 'sample', port_id: 'latents', direction: 'output', artifact_id: 'art-latents' }), + resolved({ node_id: 'sample', port_id: '_data', direction: 'output', artifact_id: 'art-latents' }), + ], + // decodedImage has no resolved row: it must come from its producer metadata. + artifacts: [promptText, latents, decodedImage], + }); +} + +test('node tree lists snapshot nodes in graph order with inputs before outputs', () => { + const tree = sampleTree(); + assert.deepEqual(tree.map((node) => node.nodeId), ['prompt', 'sample', 'decode', 'unload']); + const sample = tree[1]; + assert.equal(sample.nodeType, 'pytorch-inference'); + assert.equal(sample.status, 'running'); + assert.deepEqual( + sample.entries.map((entry) => [entry.direction, entry.portId, entry.artifact.artifact_id]), + [ + ['input', 'prompt', 'art-prompt'], + ['output', 'latents', 'art-latents'], + ], + 'the _data diagnostic port is not listed', + ); + const decode = tree[2]; + assert.deepEqual(decode.entries.map((entry) => [entry.direction, entry.portId, entry.nodeIo]), [['output', 'image', null]]); + assert.deepEqual(tree[3].entries, []); +}); + +test('node tree puts artifacts with no node under a trailing workflow boundary group', () => { + const tree = buildIoInspectorNodeTree({ + graphNodes: [{ id: 'a', node_type: 'x' }], + nodeStatuses: [], + resolvedNodeIo: [], + artifacts: [treeArtifact({ artifact_id: 'loose', artifact_role: 'workflow_input' })], + }); + assert.deepEqual(tree.map((node) => [node.nodeId, node.boundary]), [['a', false], [IO_INSPECTOR_BOUNDARY_NODE_ID, true]]); + assert.equal(tree[1].entries[0].direction, 'input'); + assert.equal(formatIoInspectorNodeSubLabel(tree[1]), '1 retained port'); +}); + +test('node tree does not duplicate an artifact the resolved rows already place', () => { + const tree = sampleTree(); + const promptEntries = tree.flatMap((node) => node.entries).filter((entry) => entry.artifact.artifact_id === 'art-prompt'); + assert.deepEqual(promptEntries.map((entry) => `${entry.nodeId}:${entry.portId}`), ['prompt:text', 'sample:prompt']); + assert.equal(new Set(tree.flatMap((node) => node.entries.map((entry) => entry.key))).size, 4); +}); + +test('direction and search filters narrow entries and count per direction', () => { + const tree = sampleTree(); + assert.deepEqual(countIoInspectorEntriesByDirection(tree), { all: 4, input: 1, output: 3 }); + + const inputs = filterIoInspectorNodeTree(tree, { direction: 'input', search: '' }); + assert.equal(inputs.length, 4, 'nodes stay listed without search text'); + assert.deepEqual(countIoInspectorEntriesByDirection(inputs), { all: 1, input: 1, output: 0 }); + + const byPort = filterIoInspectorNodeTree(tree, { direction: 'all', search: 'LATENT' }); + assert.deepEqual(byPort.map((node) => [node.nodeId, node.entries.map((entry) => entry.portId)]), [['sample', ['latents']]]); + + const byNodeType = filterIoInspectorNodeTree(tree, { direction: 'all', search: 'image-output' }); + assert.deepEqual(byNodeType.map((node) => node.nodeId), ['decode']); + + const byArtifactId = filterIoInspectorNodeTree(tree, { direction: 'output', search: 'art-prompt' }); + assert.deepEqual(byArtifactId.map((node) => node.nodeId), ['prompt']); +}); + +test('selection keeps the chosen entry and otherwise prefers an image output', () => { + const tree = sampleTree(); + const imageKey = resolveIoInspectorSelectedEntryKey(null, tree); + assert.equal(findIoInspectorEntry(tree, imageKey)?.artifact.artifact_id, 'art-image'); + + const latentsKey = tree[1].entries[1].key; + assert.equal(resolveIoInspectorSelectedEntryKey(latentsKey, tree), latentsKey); + assert.equal(resolveIoInspectorSelectedEntryKey('gone', tree), imageKey, 'a vanished entry falls back'); + + const noImage = buildIoInspectorNodeTree({ graphNodes: [], nodeStatuses: [], resolvedNodeIo: [], artifacts: [promptText] }); + assert.equal(findIoInspectorEntry(noImage, resolveIoInspectorSelectedEntryKey(null, noImage))?.direction, 'output'); + assert.equal(resolveIoInspectorSelectedEntryKey('x', []), null); + assert.equal(findIoInspectorEntry(tree, null), null); +}); + +test('node and entry labels read as sentences', () => { + const tree = sampleTree(); + assert.equal(formatIoInspectorNodeSubLabel(tree[0]), 'Succeeded, 1 retained port'); + assert.equal(formatIoInspectorNodeSubLabel(tree[1], 2), 'Running, 2 retained ports, 2 stale graph facts'); + assert.equal(formatIoInspectorNodeSubLabel(tree[2]), 'No status recorded, 1 retained port'); + assert.equal(formatIoInspectorNodeSubLabel(tree[3]), 'Queued, not reached yet'); + assert.equal(formatIoInspectorEntryDetail(decodedImage), 'Image, payload retained'); + assert.equal(formatIoInspectorEntryDetail(latents), 'Generic binary, metadata retained only'); + assert.equal(formatIoInspectorEntryDetail({ ...promptText, lifecycle_state: 'streaming' }), 'Text, streaming'); + assert.deepEqual(buildIoArtifactChipLabels(decodedImage), ['Workflow output', 'Image', 'Payload retained', 'image/png, 4.0 MiB']); +}); + +test('dimension line counts nodes, artifacts and kept payload bytes', () => { + assert.equal( + buildIoInspectorDimensionLabel({ runId: 'run-1', nodeCount: 4, artifacts: [promptText, latents, decodedImage] }), + 'run-1, 4 nodes, 3 retained artifacts, 4.0 MiB of payloads kept', + ); + assert.equal( + buildIoInspectorDimensionLabel({ runId: 'run-1', nodeCount: 1, artifacts: [] }), + 'run-1, 1 node, 0 retained artifacts, 0 B of payloads kept', + ); + assert.equal( + buildIoInspectorDimensionLabel({ runId: 'run-1', nodeCount: 1, artifacts: [], freshness: 'Current at seq 12' }), + 'run-1, 1 node, 0 retained artifacts, 0 B of payloads kept, projection current at seq 12', + ); +}); + +test('backend filter keeps matching artifacts and the resolved rows that point at them', () => { + const cuda = treeArtifact({ artifact_id: 'a', artifact_fact_id: 'fact-a', selected_backend_key: 'cuda' }); + const cpu = treeArtifact({ artifact_id: 'b', payload_artifact_id: 'payload-b', selected_backend_key: 'cpu' }); + const rows = [ + resolved({ node_id: 'n', port_id: 'p', direction: 'output', artifact_fact_id: 'fact-a' }), + resolved({ node_id: 'n', port_id: 'q', direction: 'output', payload_artifact_id: 'payload-b' }), + ]; + const unfiltered = applyIoInspectorBackendFilter([cuda, cpu], rows, ' '); + assert.equal(unfiltered.artifacts.length, 2); + assert.equal(unfiltered.resolvedNodeIo.length, 2); + const filtered = applyIoInspectorBackendFilter([cuda, cpu], rows, ' cuda '); + assert.deepEqual(filtered.artifacts.map((artifact) => artifact.artifact_id), ['a']); + assert.deepEqual(filtered.resolvedNodeIo.map((row) => row.port_id), ['p']); +}); + +test('detail sections split origin, making and storage facts', () => { + const sections = buildIoArtifactDetailSections( + { + artifact: { + ...decodedImage, + runtime_id: 'diffusers', + selected_backend_key: 'cuda', + read_handle: 'artifact-read://x', + lifecycle_state: 'retained', + access_modes: ['read', 'download'], + content_hash: 'sha256:abc', + format: { format_id: 'png', media_type: 'image/png', bit_depth: '8-bit' }, + }, + nodeIo: null, + direction: 'output', + portId: 'image', + }, + (ms) => `t${ms}`, + ); + assert.deepEqual(sections.origin.map((row) => [row.key, row.value]), [ + ['Producer', 'decode:image'], + ['Consumer', 'Unavailable'], + ['Direction', 'Output'], + ['Observed', 't1000'], + ['Provenance', 'From artifact metadata; no resolved node I/O row'], + ]); + assert.deepEqual(sections.making.map((row) => row.key), ['Runtime', 'Backend', 'Format', 'Format media', 'Bit depth']); + assert.deepEqual(sections.storage.map((row) => row.key), [ + 'Payload kind', + 'Lifecycle', + 'Access', + 'Read handle', + 'Retention', + 'Availability', + 'Size', + 'Payload ref', + 'Content hash', + ]); + const withRow = buildIoArtifactDetailSections( + { artifact: promptText, nodeIo: resolved({ node_id: 'sample', port_id: 'prompt', direction: 'input', upstream_node_id: 'prompt', upstream_port_id: 'text' }), direction: 'input', portId: 'prompt' }, + String, + ); + assert.equal(withRow.origin.find((row) => row.key === 'Provenance')?.value, 'From prompt:text'); + assert.equal(withRow.making[0].key, 'Backend', 'backend is always shown'); + assert.equal(sentenceCaseLabel('Conversion Command'), 'Conversion command'); + assert.equal(sentenceCaseLabel('CRF'), 'CRF'); +}); + +test('preview mode follows the media family and the loaded body', () => { + assert.equal(resolveIoArtifactPreviewMode('image', null), 'none'); + assert.equal(resolveIoArtifactPreviewMode('image', { text: null }), 'image'); + assert.equal(resolveIoArtifactPreviewMode('audio', { text: null }), 'audio'); + assert.equal(resolveIoArtifactPreviewMode('json', { text: '{}' }), 'text'); + assert.equal(resolveIoArtifactPreviewMode('text', { text: '' }), 'text'); + assert.equal(resolveIoArtifactPreviewMode('video', { text: null }), 'binary'); + assert.equal(resolveIoArtifactPreviewMode('file', {}), 'binary'); +}); + +test('disabled artifact actions explain why', () => { + assert.equal(describeIoArtifactReadUnavailable({ retention_state: 'retained', read_handle: 'h' }), null); + assert.equal( + describeIoArtifactReadUnavailable({ retention_state: 'metadata_only' }), + 'Metadata retained only, so there is no body to read.', + ); + assert.equal( + describeIoArtifactReadUnavailable({ retention_state: 'retained', read_handle: 'h', lifecycle_state: 'streaming' }), + 'The body is streaming; it can be read once it is retained.', + ); + assert.match(describeIoArtifactReadUnavailable({ retention_state: 'retained' }) ?? '', /did not grant/); + assert.equal(describeIoArtifactStreamUnavailable({ stream_handle: 's' }), null); + assert.equal(describeIoArtifactStreamUnavailable({}), 'This body was not written as a stream.'); + assert.equal(describeIoArtifactAcknowledgeUnavailable({ artifact_id: 'a', retention_state: 'retained' }), null); + assert.match(describeIoArtifactAcknowledgeUnavailable({ artifact_id: 'a', retention_state: 'expired' }) ?? '', /retained/); +}); + +test('stale graph facts become muted cards, grouped by node', () => { + const diagnostics: WorkflowGraphDiagnostic[] = [ + { code: 'unknown_node_type', severity: 'error', scope: 'node', node_id: 'sample', message: 'Node type is not registered.', blocking_submission: true }, + { code: 'unknown_node_type', severity: 'error', scope: 'node', node_id: 'sample', message: 'Node type is not registered.', blocking_submission: true }, + { code: 'duplicate_edge_id', severity: 'warning', scope: 'graph', message: 'Two edges share an id.', blocking_submission: false }, + ]; + const cards = buildStaleGraphFactCards(diagnostics); + assert.equal(cards.length, 2, 'duplicates collapse'); + assert.deepEqual(cards[0], { + key: cards[0].key, + title: 'Unknown node type', + code: 'Error, unknown_node_type', + explanation: 'Node type is not registered.', + suggestion: 'Try: open the workflow in Graph and fix this node before running it again.', + }); + assert.equal(cards[1].suggestion, null); + const parts = partitionGraphDiagnosticsByNode(diagnostics); + assert.equal(parts.graph.length, 1); + assert.equal(parts.byNodeId.get('sample')?.length, 2); +}); + +test('canvas view box parses strings and objects and falls back when malformed', () => { + assert.deepEqual(parseGraphCanvasViewBox('-96 -10 400 300'), { x: -96, y: -10, width: 400, height: 300 }); + assert.deepEqual(parseGraphCanvasViewBox({ x: 1, y: 2, width: 3, height: 4 }), { x: 1, y: 2, width: 3, height: 4 }); + assert.deepEqual(parseGraphCanvasViewBox('nope'), { x: 0, y: 0, width: 640, height: 360 }); + assert.deepEqual(parseGraphCanvasViewBox('0 0 0 10'), { x: 0, y: 0, width: 640, height: 360 }); + assert.deepEqual(parseGraphCanvasViewBox(undefined), { x: 0, y: 0, width: 640, height: 360 }); +}); + +test('download URL owner revokes after the delay or on dispose, exactly once', () => { + const revoked: string[] = []; + const timers = new Map void>(); + let nextHandle = 1; + const owner = createIoArtifactDownloadUrlOwner({ + delayMs: 30_000, + revoke: (url) => revoked.push(url), + schedule: (callback) => { + const handle = nextHandle++; + timers.set(handle, callback); + return handle; + }, + cancel: (handle) => timers.delete(handle), + }); + + owner.release('blob:a'); + owner.release('blob:b'); + assert.equal(owner.pendingCount(), 2); + timers.get(1)?.(); + timers.delete(1); + assert.deepEqual(revoked, ['blob:a']); + assert.equal(owner.pendingCount(), 1); + + owner.dispose(); + assert.deepEqual(revoked, ['blob:a', 'blob:b']); + assert.equal(timers.size, 0, 'pending timers are cancelled'); + assert.equal(owner.pendingCount(), 0); + + owner.release('blob:late'); + assert.deepEqual(revoked, ['blob:a', 'blob:b', 'blob:late'], 'a URL released after dispose is revoked at once'); + assert.equal(timers.size, 0); +}); diff --git a/src/components/workbench/ioInspectorPresenters.ts b/src/components/workbench/ioInspectorPresenters.ts index a2a437fc8..6eb922280 100644 --- a/src/components/workbench/ioInspectorPresenters.ts +++ b/src/components/workbench/ioInspectorPresenters.ts @@ -6,10 +6,15 @@ import type { IoArtifactPayloadKind, IoArtifactProjectionRecord, IoArtifactRetentionState, + NodeExecutionProjectionStatus, + NodeStatusProjectionRecord, ProjectionStateRecord, + ResolvedNodeIoDirection, ResolvedNodeIoRecord, WorkflowRetentionCleanupResult, } from '../../services/diagnostics/types'; +import type { GraphNode, WorkflowGraphDiagnostic } from '../../services/workflow/types'; +import type { KeyValueRow } from './ui/types'; import { formatProjectionFreshnessState } from './projectionFreshness.ts'; export type IoArtifactMediaFamily = @@ -1031,3 +1036,665 @@ export function formatIoRetentionTimestamp(value: number | null | undefined): st } return new Date(value).toLocaleString(); } + +// --------------------------------------------------------------------------- +// Node and port tree (I/O Inspector board, workbench redesign M3). +// +// The left panel lists the run snapshot's nodes, each expandable to the ports +// that have retained-artifact metadata. Entries come from the backend-resolved +// node I/O rows joined with the artifact projection; artifacts that no resolved +// row references fall back to their own producer/consumer metadata so nothing +// recorded for the run is hidden. Everything here is a pure projection of the +// `workflow_run_inspection_query` response. +// --------------------------------------------------------------------------- + +export type IoInspectorDirectionFilter = 'all' | ResolvedNodeIoDirection; + +export interface IoInspectorTreeEntry { + /** Stable row identity: direction, node, port and artifact. */ + key: string; + nodeId: string; + portId: string; + direction: ResolvedNodeIoDirection; + artifact: IoArtifactProjectionRecord; + /** The backend-resolved row, or null when the entry came from artifact metadata alone. */ + nodeIo: ResolvedNodeIoRecord | null; +} + +export interface IoInspectorTreeNode { + /** Node id; for the workflow boundary group this is `IO_INSPECTOR_BOUNDARY_NODE_ID`. */ + nodeId: string; + nodeType: string | null; + status: NodeExecutionProjectionStatus | null; + /** True for the synthetic group holding artifacts not attached to any node. */ + boundary: boolean; + /** Inputs first, then outputs, in backend order within each direction. */ + entries: IoInspectorTreeEntry[]; +} + +export interface IoInspectorTreeSource { + graphNodes: Pick[]; + nodeStatuses: Pick[]; + resolvedNodeIo: ResolvedNodeIoRecord[]; + artifacts: IoArtifactProjectionRecord[]; +} + +export interface IoInspectorDirectionCounts { + all: number; + input: number; + output: number; +} + +export const IO_INSPECTOR_BOUNDARY_NODE_ID = '\u0000workflow-boundary'; +const UNRECORDED_PORT_LABEL = 'port not recorded'; + +export function ioInspectorEntryKey( + direction: ResolvedNodeIoDirection, + nodeId: string, + portId: string, + artifactId: string, +): string { + return [direction, nodeId, portId, artifactId].join('\u001f'); +} + +export function buildIoInspectorNodeTree(source: IoInspectorTreeSource): IoInspectorTreeNode[] { + const nodes = new Map(); + const ensureNode = (nodeId: string): IoInspectorTreeNode => { + let node = nodes.get(nodeId); + if (!node) { + const boundary = nodeId === IO_INSPECTOR_BOUNDARY_NODE_ID; + node = { nodeId, nodeType: null, status: null, boundary, entries: [] }; + nodes.set(nodeId, node); + } + return node; + }; + + for (const graphNode of source.graphNodes) { + ensureNode(graphNode.id).nodeType = graphNode.node_type || null; + } + for (const status of source.nodeStatuses) { + const node = ensureNode(status.node_id); + node.status = status.status; + node.nodeType ??= status.node_type ?? null; + } + + const seenKeys = new Set(); + const referencedArtifactIds = new Set(); + const addEntry = (entry: Omit): void => { + const key = ioInspectorEntryKey(entry.direction, entry.nodeId, entry.portId, entry.artifact.artifact_id); + if (seenKeys.has(key)) { + return; + } + seenKeys.add(key); + const node = ensureNode(entry.nodeId); + if (!node.nodeType && entry.artifact.node_id === entry.nodeId && entry.artifact.node_type) { + node.nodeType = entry.artifact.node_type; + } + node.entries.push({ ...entry, key }); + }; + + for (const row of buildResolvedNodeIoDisplayRows(source.resolvedNodeIo, source.artifacts)) { + if (!row.artifact || !isNormalResolvedNodeIoDisplayRow(row)) { + continue; + } + referencedArtifactIds.add(row.artifact.artifact_id); + addEntry({ + nodeId: row.nodeIo.node_id, + portId: row.nodeIo.port_id, + direction: row.nodeIo.direction, + artifact: row.artifact, + nodeIo: row.nodeIo, + }); + } + + for (const artifact of source.artifacts) { + if (referencedArtifactIds.has(artifact.artifact_id) || isDiagnosticArtifact(artifact)) { + continue; + } + for (const entry of entriesFromArtifactMetadata(artifact)) { + addEntry(entry); + } + } + + const ordered = [...nodes.values()].map((node) => ({ + ...node, + entries: [ + ...node.entries.filter((entry) => entry.direction === 'input'), + ...node.entries.filter((entry) => entry.direction === 'output'), + ], + })); + // The boundary group only exists when an artifact needed it; keep it last. + return [...ordered.filter((node) => !node.boundary), ...ordered.filter((node) => node.boundary)]; +} + +function isDiagnosticArtifact(artifact: IoArtifactProjectionRecord): boolean { + return [artifact.producer_port_id, artifact.consumer_port_id].some(isDiagnosticDataPort); +} + +function entriesFromArtifactMetadata( + artifact: IoArtifactProjectionRecord, +): Omit[] { + const entries: Omit[] = []; + const producer = normalizeArtifactIdentity(artifact.producer_node_id); + const consumer = normalizeArtifactIdentity(artifact.consumer_node_id); + if (producer) { + entries.push({ + nodeId: producer, + portId: normalizeArtifactIdentity(artifact.producer_port_id) ?? UNRECORDED_PORT_LABEL, + direction: 'output', + artifact, + nodeIo: null, + }); + } + if (consumer) { + entries.push({ + nodeId: consumer, + portId: normalizeArtifactIdentity(artifact.consumer_port_id) ?? UNRECORDED_PORT_LABEL, + direction: 'input', + artifact, + nodeIo: null, + }); + } + if (entries.length > 0) { + return entries; + } + const direction: ResolvedNodeIoDirection = artifact.artifact_role.includes('input') ? 'input' : 'output'; + return [ + { + nodeId: normalizeArtifactIdentity(artifact.node_id) ?? IO_INSPECTOR_BOUNDARY_NODE_ID, + portId: UNRECORDED_PORT_LABEL, + direction, + artifact, + nodeIo: null, + }, + ]; +} + +/** + * Narrow the tree to one direction and a search text. With no search text + * every node stays listed (a node with no matching ports still shows its + * status); with search text a node stays when its id or type matches (all its + * ports in the direction) or when one of its ports or artifact ids matches. + */ +export function filterIoInspectorNodeTree( + nodes: IoInspectorTreeNode[], + filter: { direction: IoInspectorDirectionFilter; search: string }, +): IoInspectorTreeNode[] { + const query = filter.search.trim().toLowerCase(); + const inDirection = (entry: IoInspectorTreeEntry) => + filter.direction === 'all' || entry.direction === filter.direction; + return nodes.flatMap((node) => { + const directional = node.entries.filter(inDirection); + if (!query) { + return [{ ...node, entries: directional }]; + } + const nodeMatches = [formatIoInspectorNodeLabel(node), node.nodeType ?? ''] + .some((value) => value.toLowerCase().includes(query)); + const entries = nodeMatches + ? directional + : directional.filter((entry) => + [entry.portId, entry.artifact.artifact_id].some((value) => value.toLowerCase().includes(query)), + ); + return nodeMatches || entries.length > 0 ? [{ ...node, entries }] : []; + }); +} + +export function countIoInspectorEntriesByDirection(nodes: IoInspectorTreeNode[]): IoInspectorDirectionCounts { + const counts: IoInspectorDirectionCounts = { all: 0, input: 0, output: 0 }; + for (const entry of nodes.flatMap((node) => node.entries)) { + counts.all += 1; + counts[entry.direction] += 1; + } + return counts; +} + +export function findIoInspectorEntry( + nodes: IoInspectorTreeNode[], + key: string | null, +): IoInspectorTreeEntry | null { + if (!key) { + return null; + } + for (const node of nodes) { + const entry = node.entries.find((candidate) => candidate.key === key); + if (entry) { + return entry; + } + } + return null; +} + +/** + * Keep the chosen entry while it exists; otherwise open on the first image + * output (what most runs are inspected for), then the first output, then the + * first entry. Null when the run has no retained I/O. + */ +export function resolveIoInspectorSelectedEntryKey( + currentKey: string | null, + nodes: IoInspectorTreeNode[], +): string | null { + if (findIoInspectorEntry(nodes, currentKey)) { + return currentKey; + } + const entries = nodes.flatMap((node) => node.entries); + const outputs = entries.filter((entry) => entry.direction === 'output'); + const image = outputs.find( + (entry) => + classifyIoArtifactMedia(resolveIoArtifactMediaType(entry.artifact), entry.artifact.payload_kind) === 'image', + ); + return (image ?? outputs[0] ?? entries[0])?.key ?? null; +} + +export function formatIoInspectorNodeLabel(node: Pick): string { + return node.boundary ? 'Workflow boundary' : node.nodeId; +} + +export function formatIoInspectorNodeStatusLabel(status: NodeExecutionProjectionStatus | null): string { + switch (status) { + case 'queued': + return 'Queued'; + case 'running': + return 'Running'; + case 'waiting': + return 'Waiting'; + case 'completed': + return 'Succeeded'; + case 'failed': + return 'Failed'; + case 'cancelled': + return 'Cancelled'; + case null: + return 'No status recorded'; + } +} + +/** Second line of a node row, for example "Succeeded, 2 retained ports". */ +export function formatIoInspectorNodeSubLabel( + node: Pick, + staleFactCount = 0, +): string { + const parts: string[] = []; + if (!node.boundary) { + parts.push(formatIoInspectorNodeStatusLabel(node.status)); + } + const ports = node.entries.length; + if (ports > 0) { + parts.push(`${ports} retained ${ports === 1 ? 'port' : 'ports'}`); + } else if (node.status === 'queued' || node.status === 'waiting') { + parts.push('not reached yet'); + } else { + parts.push('no retained I/O'); + } + if (staleFactCount > 0) { + parts.push(`${staleFactCount} stale graph ${staleFactCount === 1 ? 'fact' : 'facts'}`); + } + return parts.join(', '); +} + +export function formatIoInspectorDirectionMark(direction: ResolvedNodeIoDirection): string { + return direction === 'input' ? '←' : '→'; +} + +/** Kind and retention of an entry, for example "Image, payload retained". */ +export function formatIoInspectorEntryDetail( + artifact: Pick & + Partial>, +): string { + return `${formatIoInspectorKindLabel(artifact)}, ${formatIoInspectorRetentionLabel(artifact).toLowerCase()}`; +} + +export function formatIoInspectorKindLabel( + artifact: Pick & + Partial>, +): string { + return artifact.payload_kind + ? formatIoArtifactPayloadKindLabel(artifact.payload_kind) + : formatIoArtifactMediaLabel(resolveIoArtifactMediaType(artifact)); +} + +/** Retention in words; a body still being written reads "Streaming". */ +export function formatIoInspectorRetentionLabel( + artifact: Pick & + Partial>, +): string { + if (artifact.lifecycle_state === 'streaming' || artifact.lifecycle_state === 'writing') { + return formatIoArtifactLifecycleStateLabel(artifact.lifecycle_state); + } + return formatIoArtifactRetentionStateLabel(artifact.retention_state); +} + +/** Static chips under the artifact title: role, kind, retention, media and size. */ +export function buildIoArtifactChipLabels(artifact: IoArtifactProjectionRecord): string[] { + const media = resolveIoArtifactMediaType(artifact)?.trim() || 'media type unknown'; + return [ + formatIoArtifactRoleLabel(artifact.artifact_role), + formatIoInspectorKindLabel(artifact), + formatIoInspectorRetentionLabel(artifact), + `${media}, ${formatIoArtifactBytes(artifact.size_bytes)}`, + ]; +} + +/** + * Dimension line: "run_x, 5 nodes, 6 retained artifacts, 4.1 MiB of payloads + * kept", followed by the I/O projection freshness when given (ADR-014 asks + * pages backed by cursor read models to show it). + */ +export function buildIoInspectorDimensionLabel(input: { + runId: string; + nodeCount: number; + artifacts: Pick[]; + freshness?: string | null; +}): string { + const keptBytes = input.artifacts + .filter((artifact) => artifact.retention_state === 'retained') + .reduce((total, artifact) => total + (artifact.size_bytes ?? 0), 0); + const nodes = `${input.nodeCount} ${input.nodeCount === 1 ? 'node' : 'nodes'}`; + const artifacts = `${input.artifacts.length} retained ${input.artifacts.length === 1 ? 'artifact' : 'artifacts'}`; + const base = `${input.runId}, ${nodes}, ${artifacts}, ${formatIoArtifactBytes(keptBytes)} of payloads kept`; + const freshness = input.freshness?.trim(); + return freshness ? `${base}, projection ${freshness.charAt(0).toLowerCase()}${freshness.slice(1)}` : base; +} + +export interface IoInspectorBackendFilterResult { + artifacts: IoArtifactProjectionRecord[]; + resolvedNodeIo: ResolvedNodeIoRecord[]; +} + +/** + * Apply the Backend filter: keep artifacts whose selected backend key equals + * the filter and the resolved rows that point at a kept artifact. An empty + * filter keeps everything. + */ +export function applyIoInspectorBackendFilter( + artifacts: IoArtifactProjectionRecord[], + resolvedNodeIo: ResolvedNodeIoRecord[], + backendKey: string, +): IoInspectorBackendFilterResult { + const key = backendKey.trim(); + if (key.length === 0) { + return { artifacts, resolvedNodeIo }; + } + const kept = artifacts.filter((artifact) => artifact.selected_backend_key === key); + const ids = (field: 'artifact_fact_id' | 'payload_artifact_id' | 'artifact_id') => + new Set(kept.map((artifact) => normalizeArtifactIdentity(artifact[field])).filter((id): id is string => id !== null)); + const factIds = ids('artifact_fact_id'); + const payloadIds = ids('payload_artifact_id'); + const artifactIds = ids('artifact_id'); + const has = (set: Set, value: string | null | undefined) => { + const normalized = normalizeArtifactIdentity(value); + return normalized !== null && set.has(normalized); + }; + return { + artifacts: kept, + resolvedNodeIo: resolvedNodeIo.filter( + (record) => + has(factIds, record.artifact_fact_id) || + has(payloadIds, record.payload_artifact_id) || + has(artifactIds, record.artifact_id), + ), + }; +} + +export interface IoArtifactDetailSections { + origin: KeyValueRow[]; + making: KeyValueRow[]; + storage: KeyValueRow[]; +} + +const STORAGE_DESCRIPTOR_LABELS = new Set(['Payload Kind', 'Lifecycle', 'Access', 'Read Handle', 'Stream Handle']); + +/** + * The "Where it came from", "How it was made" and "Storage" sections of the + * artifact detail. Descriptor rows keep their existing values; format and + * conversion rows go under "How it was made". `formatTimestamp` is injected so + * the caller owns locale formatting. + */ +export function buildIoArtifactDetailSections( + entry: Pick, + formatTimestamp: (ms: number) => string, +): IoArtifactDetailSections { + const { artifact, nodeIo } = entry; + const origin: KeyValueRow[] = [ + { key: 'Producer', value: formatIoArtifactEndpointValue(artifact.producer_node_id, artifact.producer_port_id), mono: true }, + { key: 'Consumer', value: formatIoArtifactEndpointValue(artifact.consumer_node_id, artifact.consumer_port_id), mono: true }, + { key: 'Direction', value: formatResolvedNodeIoDirectionLabel(entry.direction) }, + { key: 'Observed', value: formatTimestamp(artifact.occurred_at_ms) }, + ]; + if (nodeIo) { + origin.push( + { key: 'Resolution', value: formatResolvedNodeIoResolutionLabel(nodeIo.resolution) }, + { key: 'Provenance', value: formatResolvedNodeIoProvenance(nodeIo) }, + ); + } else { + origin.push({ key: 'Provenance', value: 'From artifact metadata; no resolved node I/O row' }); + } + + const making: KeyValueRow[] = []; + const storage: KeyValueRow[] = []; + for (const row of buildIoArtifactDescriptorMetadataRows(artifact)) { + const target = STORAGE_DESCRIPTOR_LABELS.has(row.label) ? storage : making; + target.push({ key: sentenceCaseLabel(row.label), value: row.value, mono: row.mono }); + } + if (!making.some((row) => row.key === 'Backend')) { + making.unshift({ key: 'Backend', value: formatIoArtifactDetailValue(artifact.selected_backend_key), mono: true }); + } + storage.push( + { key: 'Retention', value: formatIoArtifactRetentionStateLabel(artifact.retention_state) }, + { key: 'Availability', value: formatIoArtifactAvailabilityLabel(artifact) }, + ); + if (artifact.retention_reason?.trim()) { + storage.push({ key: 'Retention reason', value: artifact.retention_reason.trim() }); + } + storage.push( + { key: 'Size', value: formatIoArtifactBytes(artifact.size_bytes), mono: true }, + { key: 'Payload ref', value: formatIoArtifactDetailValue(artifact.payload_ref), mono: true }, + { key: 'Content hash', value: formatIoArtifactDetailValue(artifact.content_hash), mono: true }, + ); + return { origin, making, storage }; +} + +/** "Read Handle" → "Read handle"; all-caps words such as "CRF" stay as they are. */ +export function sentenceCaseLabel(label: string): string { + return label + .split(' ') + .map((word, index) => (index === 0 || /^[A-Z0-9]+$/.test(word) ? word : word.toLowerCase())) + .join(' '); +} + +export type IoArtifactPreviewMode = 'none' | 'image' | 'audio' | 'text' | 'binary'; + +/** + * How a loaded body renders. Images and audio play from the object URL; text, + * JSON and tables show the decoded bounded preview; everything else (video + * included, whose preview read is bounded to the first 64 KiB) gets the + * binary-body message pointing at Download. + */ +export function resolveIoArtifactPreviewMode( + family: IoArtifactMediaFamily, + preview: { text?: string | null } | null | undefined, +): IoArtifactPreviewMode { + if (!preview) { + return 'none'; + } + if (family === 'image') { + return 'image'; + } + if (family === 'audio') { + return 'audio'; + } + if (preview.text !== null && preview.text !== undefined) { + return 'text'; + } + return 'binary'; +} + +/** Why Read body and Download are disabled, or null when they are available. */ +export function describeIoArtifactReadUnavailable( + artifact: Pick & + Partial>, +): string | null { + if (canReadIoArtifactBody(artifact)) { + return null; + } + if (artifact.retention_state !== 'retained') { + return `${formatIoArtifactRetentionStateLabel(artifact.retention_state)}, so there is no body to read.`; + } + if (artifact.lifecycle_state && artifact.lifecycle_state !== 'retained') { + return `The body is ${formatIoArtifactLifecycleStateLabel(artifact.lifecycle_state).toLowerCase()}; it can be read once it is retained.`; + } + return 'The engine did not grant read or download access to this body.'; +} + +export function describeIoArtifactStreamUnavailable( + artifact: Partial>, +): string | null { + return artifact.stream_handle ? null : 'This body was not written as a stream.'; +} + +export function describeIoArtifactAcknowledgeUnavailable( + artifact: Pick, +): string | null { + return canAcknowledgeIoArtifactConsumed(artifact) + ? null + : 'Only retained payloads can be acknowledged as consumed.'; +} + +export interface StaleGraphFactCard { + key: string; + title: string; + code: string; + explanation: string; + suggestion: string | null; +} + +/** + * Muted, ErrorCard-shaped explanations of backend graph diagnostics ("stale + * graph facts"). They describe the captured graph, not a failure of this page, + * so they never use the danger colour. + */ +export function buildStaleGraphFactCards(diagnostics: WorkflowGraphDiagnostic[]): StaleGraphFactCard[] { + const seen = new Set(); + return diagnostics.flatMap((diagnostic) => { + const key = [diagnostic.scope, diagnostic.node_id ?? '', diagnostic.code, diagnostic.message].join('\u001f'); + if (seen.has(key)) { + return []; + } + seen.add(key); + return [ + { + key, + title: humanizeDiagnosticCode(diagnostic.code), + code: `${formatGraphDiagnosticSeverityLabel(diagnostic.severity)}, ${diagnostic.code}`, + explanation: diagnostic.message, + suggestion: diagnostic.blocking_submission + ? 'Try: open the workflow in Graph and fix this node before running it again.' + : null, + }, + ]; + }); +} + +export function formatGraphDiagnosticSeverityLabel(severity: WorkflowGraphDiagnostic['severity']): string { + switch (severity) { + case 'error': + return 'Error'; + case 'warning': + return 'Warning'; + case 'info': + return 'Note'; + } +} + +function humanizeDiagnosticCode(code: string): string { + const words = code.replaceAll('_', ' ').trim(); + return words.length > 0 ? words.charAt(0).toUpperCase() + words.slice(1) : 'Graph fact'; +} + +/** Split graph diagnostics into graph-scope facts and facts per node id. */ +export function partitionGraphDiagnosticsByNode(diagnostics: WorkflowGraphDiagnostic[]): { + graph: WorkflowGraphDiagnostic[]; + byNodeId: Map; +} { + const graph: WorkflowGraphDiagnostic[] = []; + const byNodeId = new Map(); + for (const diagnostic of diagnostics) { + const nodeId = normalizeArtifactIdentity(diagnostic.node_id); + if (!nodeId) { + graph.push(diagnostic); + continue; + } + byNodeId.set(nodeId, [...(byNodeId.get(nodeId) ?? []), diagnostic]); + } + return { graph, byNodeId }; +} + +export interface GraphCanvasViewBox { + x: number; + y: number; + width: number; + height: number; +} + +const FALLBACK_CANVAS_VIEWBOX: GraphCanvasViewBox = { x: 0, y: 0, width: 640, height: 360 }; + +/** + * Read a canvas view box given either as the SVG string "x y w h" or as an + * object. Malformed input falls back to the empty-canvas box so the saved + * graph surface still lays out. + */ +export function parseGraphCanvasViewBox(viewBox: string | GraphCanvasViewBox | null | undefined): GraphCanvasViewBox { + if (viewBox && typeof viewBox === 'object') { + return viewBox; + } + const parts = (viewBox ?? '').trim().split(/[\s,]+/).map(Number); + if (parts.length !== 4 || parts.some((part) => !Number.isFinite(part)) || parts[2] <= 0 || parts[3] <= 0) { + return { ...FALLBACK_CANVAS_VIEWBOX }; + } + const [x, y, width, height] = parts; + return { x, y, width, height }; +} + +export interface IoArtifactDownloadUrlOwner { + /** Revoke `objectUrl` after the delay; the owner keeps the timer. */ + release: (objectUrl: string) => void; + /** Cancel pending timers and revoke every URL still held. */ + dispose: () => void; + pendingCount: () => number; +} + +/** + * One owner for the object URLs handed to the browser for downloads. Each URL + * is revoked after `delayMs` (the browser needs it alive while the download + * starts) or when the page is destroyed, whichever comes first. + */ +export function createIoArtifactDownloadUrlOwner(options: { + delayMs: number; + revoke: (objectUrl: string) => void; + schedule: (callback: () => void, delayMs: number) => number; + cancel: (handle: number) => void; +}): IoArtifactDownloadUrlOwner { + const pending = new Map(); + let disposed = false; + return { + release(objectUrl) { + if (disposed) { + options.revoke(objectUrl); + return; + } + const handle = options.schedule(() => { + pending.delete(handle); + options.revoke(objectUrl); + }, options.delayMs); + pending.set(handle, objectUrl); + }, + dispose() { + disposed = true; + for (const [handle, objectUrl] of pending) { + options.cancel(handle); + options.revoke(objectUrl); + } + pending.clear(); + }, + pendingCount: () => pending.size, + }; +} diff --git a/src/components/workbench/libraryUsagePresenters.test.ts b/src/components/workbench/libraryUsagePresenters.test.ts index 519568aa8..90879042f 100644 --- a/src/components/workbench/libraryUsagePresenters.test.ts +++ b/src/components/workbench/libraryUsagePresenters.test.ts @@ -1,12 +1,39 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import type { LibraryUsageProjectionRecord } from '../../services/diagnostics/types'; +import type { PortOption } from '../../services/workflow/types'; import { + buildHfDownloadRequest, + buildHfSearchRequest, + buildLibraryModelRows, classifyLibraryAsset, + classifyLibraryModelKind, + createLibraryRequestGate, + filterLibraryModelRows, + filterLibraryModelRowsByKind, + formatHfDownloadStatus, + formatHfResultCountLine, + formatHfSearchStatus, formatLibraryAssetCategory, formatLibraryBytes, + formatLibraryDimensionLine, + formatLibraryModelSubline, formatLibraryProjectionFreshness, + formatLibraryTimeShort, + formatPumasDeleteStatus, + groupLibraryModelRows, isLibraryAssetLastUsedByRun, + libraryDeleteBlockReason, + libraryKindOptions, + libraryModelChips, + libraryModelIdFromOption, + libraryModelLocationRows, + libraryModelSourceRows, + libraryModelUsageRows, + libraryWorkflowUseRows, + normalizeHfSearchLimit, + projectHfSearchResults, } from './libraryUsagePresenters.ts'; test('classifyLibraryAsset uses explicit asset id prefixes only', () => { @@ -51,3 +78,288 @@ test('formatLibraryProjectionFreshness keeps projection status visible', () => { 'Current at seq 7', ); }); + +// --- Library list, detail and search projections --------------------------- + +const DAY_MS = 24 * 60 * 60 * 1000; +// Local-time construction keeps the time-of-day assertions independent of TZ. +const NOW = new Date(2026, 10, 3, 20, 5).getTime(); + +function option(id: string, metadata: Record = {}, extra: Partial = {}): PortOption { + return { + value: { model_id: id }, + label: id.split('/').pop() ?? id, + metadata: { id, ...metadata }, + ...extra, + }; +} + +function usage(assetId: string, extra: Partial = {}): LibraryUsageProjectionRecord { + return { + asset_id: assetId, + total_access_count: 3, + run_access_count: 2, + total_network_bytes: 0, + last_accessed_at_ms: NOW - 60_000, + last_operation: 'run_usage', + last_workflow_run_id: 'run_a', + last_workflow_id: 'ingest-docs-rag', + last_workflow_semantic_version: '1.4.0', + last_event_seq: 9, + last_updated_at_ms: NOW - 60_000, + ...extra, + }; +} + +test('buildLibraryModelRows joins usage by pumas asset id and leaves the rest unjoined', () => { + const rows = buildLibraryModelRows( + [ + option('llm/qwen/qwen3-8b', { model_type: 'llm', repo_id: 'Qwen/Qwen3-8B', recommended_backend: 'llama.cpp' }), + option('diffusion/sdxl', { model_type: 'diffusion', display_entry_path: '/models/sdxl' }), + option('llm/qwen/qwen3-8b'), + { value: null, label: 'no id' }, + ], + [ + usage('pumas://models/llm/qwen/qwen3-8b'), + usage('hf://models/Qwen/Qwen3-8B', { last_operation: 'download', last_workflow_id: null }), + usage('pumas://models/deleted-model'), + ], + ); + assert.deepEqual( + rows.map((row) => [row.modelId, row.assetId, row.usage?.asset_id ?? null]), + [ + ['llm/qwen/qwen3-8b', 'pumas://models/llm/qwen/qwen3-8b', 'pumas://models/llm/qwen/qwen3-8b'], + ['diffusion/sdxl', 'pumas://models/diffusion/sdxl', null], + ], + ); + assert.equal(rows[0].downloadUsage?.asset_id, 'hf://models/Qwen/Qwen3-8B'); + assert.equal(rows[0].backend, 'llama.cpp'); + assert.equal(rows[1].path, '/models/sdxl'); +}); + +test('libraryModelIdFromOption reads metadata id, then model_ref value, then a string value', () => { + assert.equal(libraryModelIdFromOption({ value: 'x', label: 'x', metadata: { id: 'meta-id' } }), 'meta-id'); + assert.equal(libraryModelIdFromOption({ value: { model_id: 'ref-id' }, label: 'x' }), 'ref-id'); + assert.equal(libraryModelIdFromOption({ value: 'plain-id', label: 'x' }), 'plain-id'); + assert.equal(libraryModelIdFromOption({ value: { other: 1 }, label: 'x' }), null); +}); + +test('classifyLibraryModelKind uses model type, then task, then pipeline tag, else no kind', () => { + assert.equal(classifyLibraryModelKind({ modelType: 'embedding', taskType: null, pipelineTag: null }), 'text'); + assert.equal(classifyLibraryModelKind({ modelType: 'unknown', taskType: 'image_generation', pipelineTag: null }), 'image'); + assert.equal( + classifyLibraryModelKind({ modelType: null, taskType: null, pipelineTag: 'automatic-speech-recognition' }), + 'audio', + ); + assert.equal(classifyLibraryModelKind({ modelType: 'vlm', taskType: null, pipelineTag: null }), null); +}); + +test('libraryKindOptions is hidden when no kind is known and counts kinds otherwise', () => { + const unknown = buildLibraryModelRows([option('a'), option('b')], []); + assert.equal(libraryKindOptions(unknown), null); + const known = buildLibraryModelRows( + [option('a', { model_type: 'llm' }), option('b', { model_type: 'diffusion' }), option('c')], + [], + ); + assert.deepEqual( + libraryKindOptions(known)?.map((segment) => [segment.value, segment.count]), + [['all', 3], ['text', 1], ['image', 1], ['audio', 0]], + ); + assert.deepEqual(filterLibraryModelRowsByKind(known, 'image').map((row) => row.modelId), ['b']); +}); + +test('filterLibraryModelRows matches name, id, repository and model type', () => { + const rows = buildLibraryModelRows( + [option('llm/qwen3', { repo_id: 'Qwen/Qwen3-8B', model_type: 'llm' }), option('audio/whisper')], + [], + ); + assert.deepEqual(filterLibraryModelRows(rows, 'QWEN/').map((row) => row.modelId), ['llm/qwen3']); + assert.deepEqual(filterLibraryModelRows(rows, 'whisper').map((row) => row.modelId), ['audio/whisper']); + assert.equal(filterLibraryModelRows(rows, ' ').length, 2); +}); + +test('groupLibraryModelRows groups by last access and falls back to one Models group', () => { + const noUsage = buildLibraryModelRows([option('a'), option('b')], []); + assert.deepEqual( + groupLibraryModelRows(noUsage, NOW).map((group) => [group.label, group.rows.length]), + [['Models', 2]], + ); + const rows = buildLibraryModelRows( + [option('recent'), option('old'), option('never')], + [ + usage('pumas://models/recent', { last_accessed_at_ms: NOW - 2 * DAY_MS }), + usage('pumas://models/old', { last_accessed_at_ms: NOW - 31 * DAY_MS }), + ], + ); + assert.deepEqual( + groupLibraryModelRows(rows, NOW).map((group) => [group.label, group.rows.map((row) => row.modelId)]), + [ + ['Used this month', ['recent']], + ['Unused for 30 days', ['old']], + ['No usage recorded', ['never']], + ], + ); + assert.equal(groupLibraryModelRows([], NOW).length, 0); + assert.equal( + formatLibraryDimensionLine(rows, NOW), + '3 models, 1 used this month, 1 unused for 30 days, 1 with no usage recorded', + ); + assert.equal(formatLibraryDimensionLine(noUsage, NOW), '2 models'); + assert.equal(formatLibraryDimensionLine([], NOW, true), 'Pumas model list unavailable'); + assert.equal(formatLibraryDimensionLine(noUsage, NOW, true), '2 models'); +}); + +test('formatLibraryModelSubline says "No usage recorded" when the projection has no row', () => { + const [withUsage, withoutUsage, noBackend] = buildLibraryModelRows( + [option('a', { recommended_backend: 'llama.cpp' }), option('b', { recommended_backend: 'diffusers' }), option('c')], + [usage('pumas://models/a')], + ); + assert.equal(formatLibraryModelSubline(withUsage), 'llama.cpp, last used by ingest-docs-rag'); + assert.equal(formatLibraryModelSubline(withoutUsage), 'diffusers, no usage recorded'); + assert.equal(formatLibraryModelSubline(noBackend), 'No usage recorded'); +}); + +test('formatLibraryTimeShort shows time today, month and day this year, and the year otherwise', () => { + assert.equal(formatLibraryTimeShort(new Date(2026, 10, 3, 9, 7).getTime(), NOW), '09:07'); + assert.equal(formatLibraryTimeShort(new Date(2026, 9, 29, 9, 7).getTime(), NOW), 'Oct 29'); + assert.equal(formatLibraryTimeShort(new Date(2025, 9, 29, 9, 7).getTime(), NOW), 'Oct 29, 2025'); +}); + +test('detail rows omit facts the projections lack', () => { + const [row] = buildLibraryModelRows([option('a')], []); + assert.deepEqual(libraryModelLocationRows(row), [{ key: 'Readiness', value: 'Ready to use in a graph' }]); + assert.deepEqual(libraryModelUsageRows(row, NOW), []); + assert.deepEqual(libraryModelSourceRows(row, NOW), []); + assert.deepEqual(libraryWorkflowUseRows(row, 'run_a', NOW), []); + + const [full] = buildLibraryModelRows( + [ + option( + 'b', + { repo_id: 'Org/B', model_type: 'llm', task_type_primary: 'text-generation', storage_kind: 'library_owned' }, + { disabled: true, unavailableReason: 'entry path is Missing' }, + ), + ], + [ + usage('pumas://models/b', { total_network_bytes: 2_048, last_cache_status: 'hit' }), + usage('hf://models/Org/B', { last_operation: 'download', last_accessed_at_ms: new Date(2026, 9, 1).getTime() }), + ], + ); + assert.deepEqual(libraryModelLocationRows(full), [ + { key: 'Storage', value: 'library_owned' }, + { key: 'Readiness', value: 'entry path is Missing' }, + ]); + assert.deepEqual( + libraryModelUsageRows(full, NOW).map((entry) => [entry.key, entry.value]), + [ + ['Runs', '2 runs'], + ['Accesses', '3'], + ['Last used', '20:04, by ingest-docs-rag v1.4.0'], + ['Last operation', 'run_usage'], + ['Read from network', '2.0 KiB'], + ['Cache', 'hit'], + ], + ); + assert.deepEqual( + libraryModelSourceRows(full, NOW).map((entry) => [entry.key, entry.value]), + [ + ['Repository', 'Org/B'], + ['Model type', 'llm'], + ['Task', 'text-generation'], + ['Download recorded', 'Oct 1'], + ], + ); + assert.deepEqual(libraryModelChips(full, 'run_a'), ['Last used by active run', 'Not ready', '2 runs']); +}); + +test('libraryWorkflowUseRows marks the active run and libraryDeleteBlockReason blocks delete', () => { + const [row] = buildLibraryModelRows([option('a')], [usage('pumas://models/a')]); + const [active] = libraryWorkflowUseRows(row, 'run_a', NOW); + assert.equal(active.isActiveRun, true); + assert.equal(active.workflowId, 'ingest-docs-rag'); + assert.equal(active.version, '1.4.0'); + assert.equal(active.runCount, 2); + assert.equal(libraryWorkflowUseRows(row, 'run_b', NOW)[0].isActiveRun, false); + + assert.match(libraryDeleteBlockReason(row, 'run_a', false) ?? '', /active run/); + assert.match(libraryDeleteBlockReason(row, 'run_b', true) ?? '', /current library action/); + assert.equal(libraryDeleteBlockReason(row, 'run_b', false), null); + assert.equal(libraryDeleteBlockReason(row, null, false), null); +}); + +test('buildHfSearchRequest trims inputs and clamps the limit to the host range', () => { + assert.deepEqual(buildHfSearchRequest({ query: ' qwen ', kind: ' ', limit: 25 }), { + query: 'qwen', + kind: null, + limit: 25, + hydrateLimit: 10, + }); + assert.equal(buildHfSearchRequest({ query: '', kind: 'text-generation', limit: 500 }).limit, 100); + assert.equal(normalizeHfSearchLimit(0), 1); + assert.equal(normalizeHfSearchLimit('7'), 7); + assert.equal(normalizeHfSearchLimit(Number.NaN), 25); + assert.equal(normalizeHfSearchLimit(null), 25); + assert.equal(normalizeHfSearchLimit(''), 25); + assert.equal(buildHfSearchRequest({ query: 'x', kind: '', limit: 4 }).hydrateLimit, 4); +}); + +test('buildHfDownloadRequest keeps the existing defaults for family and official name', () => { + assert.deepEqual(buildHfDownloadRequest('Org/Model', { officialName: '', family: ' ', modelType: '' }), { + repo_id: 'Org/Model', + family: 'model', + official_name: 'Org/Model', + model_type: null, + }); + assert.deepEqual( + buildHfDownloadRequest('Org/Model', { officialName: ' My model ', family: 'qwen', modelType: 'llm' }), + { repo_id: 'Org/Model', family: 'qwen', official_name: 'My model', model_type: 'llm' }, + ); +}); + +test('projectHfSearchResults reads the camelCase host fields and drops rows without a repository', () => { + const rows = projectHfSearchResults([ + { repoId: 'Qwen/Qwen3-14B-GGUF', kind: 'text-generation', formats: ['gguf'], downloads: 1_234, totalSizeBytes: 2_147_483_648 }, + { repoId: 'Qwen/Qwen3-14B-GGUF' }, + { name: 'no repo' }, + ]); + assert.deepEqual(rows, [ + { repoId: 'Qwen/Qwen3-14B-GGUF', sub: 'text-generation, gguf, 1.2k downloads', size: '2.0 GiB' }, + ]); + assert.equal(formatHfResultCountLine(0, 25), 'No Hugging Face models match. Try a shorter or different query.'); + assert.equal(formatHfResultCountLine(3, 25), '3 results'); + assert.match(formatHfResultCountLine(25, 25), /^Showing the first 25\./); +}); + +test('status sentences name the audit event when the host returns one', () => { + assert.equal(formatHfSearchStatus({ models: [], auditEventSeq: 12 }), 'Search recorded at event 12'); + assert.equal(formatHfSearchStatus({ models: [] }), 'Search finished'); + assert.equal( + formatHfDownloadStatus('Org/M', { downloadId: 'dl-1', auditEventSeq: 13 }), + 'Download dl-1 of Org/M recorded at event 13', + ); + assert.equal(formatHfDownloadStatus('Org/M', { downloadId: 'dl-1' }), 'Download dl-1 of Org/M started'); + assert.equal(formatPumasDeleteStatus({ success: true, auditEventSeq: 14 }), 'Delete recorded at event 14'); + assert.equal(formatPumasDeleteStatus({ success: false, error: 'busy' }), 'busy'); + assert.equal(formatPumasDeleteStatus({ success: false }), 'Delete did not complete'); +}); + +test('createLibraryRequestGate applies only the newest invocation and nothing after dispose', async () => { + const gate = createLibraryRequestGate(); + const applied: string[] = []; + const run = async (label: string, delayMs: number) => { + const token = gate.begin(); + await new Promise((resolve) => setTimeout(resolve, delayMs)); + if (gate.isCurrent(token)) applied.push(label); + }; + await Promise.all([run('slow-first', 20), run('fast-second', 1)]); + assert.deepEqual(applied, ['fast-second']); + + const token = gate.begin(); + assert.equal(gate.isCurrent(token), true); + gate.dispose(); + assert.equal(gate.isCurrent(token), false); + assert.equal(gate.isCurrent(gate.begin()), false); + + const other = createLibraryRequestGate(); + assert.equal(other.isCurrent(other.begin()), true, 'gates are scoped to their owner'); +}); diff --git a/src/components/workbench/libraryUsagePresenters.ts b/src/components/workbench/libraryUsagePresenters.ts index ab333660e..a4569b07f 100644 --- a/src/components/workbench/libraryUsagePresenters.ts +++ b/src/components/workbench/libraryUsagePresenters.ts @@ -1,7 +1,15 @@ import type { LibraryUsageProjectionRecord, ProjectionStateRecord, + PumasHfDownloadRequest, + PumasHfDownloadStartAuditResponse, + PumasHfModelSearchAuditRequest, + PumasHfModelSearchAuditResponse, + PumasHfModelSearchResult, + PumasModelDeleteAuditResponse, } from '../../services/diagnostics/types'; +import type { PortOption } from '../../services/workflow/types'; +import type { KeyValueRow, SegmentOption } from './ui/types'; import { formatProjectionFreshnessState } from './projectionFreshness.ts'; export type LibraryAssetCategory = @@ -93,3 +101,551 @@ export function formatLibraryBytes(bytes: number): string { export function formatLibraryProjectionFreshness(state: ProjectionStateRecord | null): string { return formatProjectionFreshnessState(state); } + +// --------------------------------------------------------------------------- +// Library list: Pumas models joined with the library usage projection. +// --------------------------------------------------------------------------- + +/** + * Asset id prefixes the host writes into `library.asset_accessed` events + * (`session_execution_api.rs::pumas_model_asset_id`, + * `puma_lib_commands.rs::record_*_audit`). The join below depends on them. + */ +export const PUMAS_MODEL_ASSET_PREFIX = 'pumas://models/'; +export const HF_MODEL_ASSET_PREFIX = 'hf://models/'; + +/** "Unused for 30 days" boundary. */ +export const LIBRARY_UNUSED_AFTER_MS = 30 * 24 * 60 * 60 * 1000; + +export type LibraryModelKind = 'text' | 'image' | 'audio'; +export type LibraryKindFilter = 'all' | LibraryModelKind; + +export interface LibraryModelRow { + /** Pumas model id (selector row `model_ref.model_id`). */ + modelId: string; + /** Usage-projection asset id for this model: `pumas://models/`. */ + assetId: string; + name: string; + modelType: string | null; + kind: LibraryModelKind | null; + repoId: string | null; + backend: string | null; + path: string | null; + storageKind: string | null; + validationState: string | null; + pipelineTag: string | null; + taskType: string | null; + /** Set when the selector reports the row as not executable. */ + unavailableReason: string | null; + /** Usage record for `assetId`, when one exists. */ + usage: LibraryUsageProjectionRecord | null; + /** Usage record for `hf://models/` (download audits), when one exists. */ + downloadUsage: LibraryUsageProjectionRecord | null; +} + +export function pumasModelAssetId(modelId: string): string { + return `${PUMAS_MODEL_ASSET_PREFIX}${modelId}`; +} + +function nonEmptyString(value: unknown): string | null { + if (typeof value !== 'string') return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +function metadataString(option: PortOption, key: string): string | null { + return nonEmptyString(option.metadata?.[key]); +} + +/** The Pumas model id of a selector option, or null when the option carries none. */ +export function libraryModelIdFromOption(option: PortOption): string | null { + const fromMetadata = metadataString(option, 'id'); + if (fromMetadata) return fromMetadata; + const value = option.value; + if (value && typeof value === 'object' && 'model_id' in value) { + return nonEmptyString((value as { model_id?: unknown }).model_id); + } + return nonEmptyString(value); +} + +const KIND_BY_MODEL_TYPE: Record = { + llm: 'text', + reranker: 'text', + embedding: 'text', + diffusion: 'image', + vision: 'image', + audio: 'audio', +}; + +const KIND_BY_TASK: Record = { + 'text-generation': 'text', + 'text2text-generation': 'text', + 'feature-extraction': 'text', + 'sentence-similarity': 'text', + 'fill-mask': 'text', + summarization: 'text', + translation: 'text', + 'text-classification': 'text', + 'token-classification': 'text', + 'question-answering': 'text', + 'text-ranking': 'text', + image_generation: 'image', + 'text-to-image': 'image', + 'image-to-image': 'image', + 'unconditional-image-generation': 'image', + 'text-to-speech': 'audio', + 'text-to-audio': 'audio', + 'automatic-speech-recognition': 'audio', + 'audio-classification': 'audio', + 'audio-to-audio': 'audio', +}; + +/** + * Kind for the Text / Image / Audio segment, from the facts the selector row + * provides: the Pumas model type first, then the task type, then the pipeline + * tag. Anything else (for example `vlm` or `unknown`) has no kind and only + * appears under All. + */ +export function classifyLibraryModelKind(facts: { + modelType: string | null; + taskType: string | null; + pipelineTag: string | null; +}): LibraryModelKind | null { + const byType = facts.modelType ? KIND_BY_MODEL_TYPE[facts.modelType.toLowerCase()] : undefined; + if (byType) return byType; + for (const task of [facts.taskType, facts.pipelineTag]) { + const byTask = task ? KIND_BY_TASK[task.toLowerCase()] : undefined; + if (byTask) return byTask; + } + return null; +} + +/** + * Joins the Pumas selector rows with the usage projection by asset id. Rows + * without a model id are dropped; duplicate model ids keep the first row. + */ +export function buildLibraryModelRows( + options: readonly PortOption[], + usage: readonly LibraryUsageProjectionRecord[], +): LibraryModelRow[] { + const usageByAsset = new Map(); + for (const record of usage) { + if (!usageByAsset.has(record.asset_id)) usageByAsset.set(record.asset_id, record); + } + const seen = new Set(); + const rows: LibraryModelRow[] = []; + for (const option of options) { + const modelId = libraryModelIdFromOption(option); + if (!modelId || seen.has(modelId)) continue; + seen.add(modelId); + const assetId = pumasModelAssetId(modelId); + const modelType = metadataString(option, 'model_type'); + const taskType = metadataString(option, 'task_type_primary'); + const pipelineTag = metadataString(option, 'pipeline_tag'); + const repoId = metadataString(option, 'repo_id'); + const hints = option.metadata?.runtime_engine_hints; + const firstHint = Array.isArray(hints) ? nonEmptyString(hints[0]) : null; + rows.push({ + modelId, + assetId, + name: nonEmptyString(option.label) ?? metadataString(option, 'cleaned_name') ?? modelId, + modelType: modelType && modelType.toLowerCase() !== 'unknown' ? modelType : null, + kind: classifyLibraryModelKind({ modelType, taskType, pipelineTag }), + repoId, + backend: metadataString(option, 'recommended_backend') ?? firstHint, + path: metadataString(option, 'display_entry_path') ?? metadataString(option, 'display_indexed_path'), + storageKind: metadataString(option, 'storage_kind'), + validationState: metadataString(option, 'validation_state'), + pipelineTag, + taskType, + unavailableReason: option.disabled + ? (nonEmptyString(option.unavailableReason) ?? 'The Pumas library reports this model as not ready') + : null, + usage: usageByAsset.get(assetId) ?? null, + downloadUsage: repoId ? (usageByAsset.get(`${HF_MODEL_ASSET_PREFIX}${repoId}`) ?? null) : null, + }); + } + return rows; +} + +/** Case-insensitive match on name, model id, repository and model type. */ +export function filterLibraryModelRows(rows: readonly LibraryModelRow[], query: string): LibraryModelRow[] { + const needle = query.trim().toLowerCase(); + if (!needle) return [...rows]; + return rows.filter((row) => + [row.name, row.modelId, row.repoId, row.modelType].some( + (field) => field !== null && field.toLowerCase().includes(needle), + ), + ); +} + +const KIND_LABELS: Record = { + all: 'All', + text: 'Text', + image: 'Image', + audio: 'Audio', +}; + +/** Segment options with counts, or null when no row has a known kind. */ +export function libraryKindOptions(rows: readonly LibraryModelRow[]): SegmentOption[] | null { + if (!rows.some((row) => row.kind !== null)) return null; + return (['all', 'text', 'image', 'audio'] as const).map((value) => ({ + value, + label: KIND_LABELS[value], + count: value === 'all' ? rows.length : rows.filter((row) => row.kind === value).length, + })); +} + +export function filterLibraryModelRowsByKind( + rows: readonly LibraryModelRow[], + kind: LibraryKindFilter, +): LibraryModelRow[] { + return kind === 'all' ? [...rows] : rows.filter((row) => row.kind === kind); +} + +export type LibraryModelGroupKey = 'used_this_month' | 'unused_30_days' | 'no_usage' | 'models'; + +export interface LibraryModelGroup { + key: LibraryModelGroupKey; + label: string; + rows: LibraryModelRow[]; +} + +function usedWithinMonth(row: LibraryModelRow, nowMs: number): boolean { + return row.usage !== null && nowMs - row.usage.last_accessed_at_ms < LIBRARY_UNUSED_AFTER_MS; +} + +/** + * Groups by the only time fact the projections provide (last access). Device + * residency is not exposed, so there is no "Loaded on a device" group. When no + * row has usage at all, everything sits in one "Models" group. Rows keep their + * input order inside a group; empty groups are omitted. + */ +export function groupLibraryModelRows(rows: readonly LibraryModelRow[], nowMs: number): LibraryModelGroup[] { + if (!rows.some((row) => row.usage !== null)) { + return rows.length > 0 ? [{ key: 'models', label: 'Models', rows: [...rows] }] : []; + } + const groups: LibraryModelGroup[] = [ + { key: 'used_this_month', label: 'Used this month', rows: rows.filter((row) => usedWithinMonth(row, nowMs)) }, + { + key: 'unused_30_days', + label: 'Unused for 30 days', + rows: rows.filter((row) => row.usage !== null && !usedWithinMonth(row, nowMs)), + }, + { key: 'no_usage', label: 'No usage recorded', rows: rows.filter((row) => row.usage === null) }, + ]; + return groups.filter((group) => group.rows.length > 0); +} + +function plural(count: number, one: string, many = `${one}s`): string { + return `${count} ${count === 1 ? one : many}`; +} + +/** + * Page summary line. Sizes and device residency are not in the projections, so + * they are omitted. `listUnavailable` marks a model list that could not be read, + * so an empty list is not reported as "0 models". + */ +export function formatLibraryDimensionLine( + rows: readonly LibraryModelRow[], + nowMs: number, + listUnavailable = false, +): string { + if (listUnavailable && rows.length === 0) return 'Pumas model list unavailable'; + const parts = [plural(rows.length, 'model')]; + if (rows.some((row) => row.usage !== null)) { + const used = rows.filter((row) => usedWithinMonth(row, nowMs)).length; + const unused = rows.filter((row) => row.usage !== null && !usedWithinMonth(row, nowMs)).length; + const none = rows.filter((row) => row.usage === null).length; + parts.push(`${used} used this month`, `${unused} unused for 30 days`); + if (none > 0) parts.push(`${none} with no usage recorded`); + } + return parts.join(', '); +} + +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +function pad2(value: number): string { + return String(value).padStart(2, '0'); +} + +/** "20:01" for today (local time), "Oct 29" this year, "Oct 29, 2025" otherwise. */ +export function formatLibraryTimeShort(ms: number, nowMs: number): string { + const at = new Date(ms); + const now = new Date(nowMs); + if (at.toDateString() === now.toDateString()) return `${pad2(at.getHours())}:${pad2(at.getMinutes())}`; + const day = `${MONTHS[at.getMonth()]} ${at.getDate()}`; + return at.getFullYear() === now.getFullYear() ? day : `${day}, ${at.getFullYear()}`; +} + +function formatWorkflowRef(usage: LibraryUsageProjectionRecord): string | null { + if (!usage.last_workflow_id) return null; + return usage.last_workflow_semantic_version + ? `${usage.last_workflow_id} v${usage.last_workflow_semantic_version}` + : usage.last_workflow_id; +} + +/** List row sub-line: backend, then who used it last, or "No usage recorded". */ +export function formatLibraryModelSubline(row: LibraryModelRow): string { + let usagePart = 'No usage recorded'; + if (row.usage) { + usagePart = row.usage.last_workflow_id + ? `last used by ${row.usage.last_workflow_id}` + : `${plural(row.usage.total_access_count, 'access', 'accesses')} recorded`; + } + if (!row.backend) return usagePart.charAt(0).toUpperCase() + usagePart.slice(1); + return `${row.backend}, ${usagePart.charAt(0).toLowerCase()}${usagePart.slice(1)}`; +} + +export function libraryModelChips(row: LibraryModelRow, activeRunId: string | null | undefined): string[] { + const chips: string[] = []; + if (row.usage && isLibraryAssetLastUsedByRun(row.usage, activeRunId)) chips.push('Last used by active run'); + if (row.unavailableReason) chips.push('Not ready'); + if (row.backend) chips.push(row.backend); + if (row.usage) chips.push(plural(row.usage.run_access_count, 'run')); + return chips; +} + +export function libraryModelLocationRows(row: LibraryModelRow): KeyValueRow[] { + const rows: KeyValueRow[] = []; + if (row.path) rows.push({ key: 'Path', value: row.path, mono: true }); + if (row.storageKind) rows.push({ key: 'Storage', value: row.storageKind }); + if (row.validationState) rows.push({ key: 'Validation', value: row.validationState }); + rows.push({ key: 'Readiness', value: row.unavailableReason ?? 'Ready to use in a graph' }); + return rows; +} + +/** "How it is used" rows; empty when the projection has no record for the model. */ +export function libraryModelUsageRows(row: LibraryModelRow, nowMs: number): KeyValueRow[] { + const usage = row.usage; + if (!usage) return []; + const workflow = formatWorkflowRef(usage); + const rows: KeyValueRow[] = [ + { key: 'Runs', value: plural(usage.run_access_count, 'run') }, + { key: 'Accesses', value: String(usage.total_access_count) }, + { + key: 'Last used', + value: `${formatLibraryTimeShort(usage.last_accessed_at_ms, nowMs)}${workflow ? `, by ${workflow}` : ''}`, + }, + { key: 'Last operation', value: usage.last_operation }, + { key: 'Read from network', value: formatLibraryBytes(usage.total_network_bytes) }, + ]; + if (usage.last_cache_status) rows.push({ key: 'Cache', value: usage.last_cache_status }); + return rows; +} + +export function libraryModelSourceRows(row: LibraryModelRow, nowMs: number): KeyValueRow[] { + const rows: KeyValueRow[] = []; + if (row.repoId) rows.push({ key: 'Repository', value: row.repoId, mono: true }); + if (row.modelType) rows.push({ key: 'Model type', value: row.modelType }); + if (row.taskType) rows.push({ key: 'Task', value: row.taskType }); + if (row.pipelineTag && row.pipelineTag !== row.taskType) rows.push({ key: 'Pipeline', value: row.pipelineTag }); + if (row.downloadUsage && row.downloadUsage.last_operation === 'download') { + rows.push({ + key: 'Download recorded', + value: formatLibraryTimeShort(row.downloadUsage.last_accessed_at_ms, nowMs), + }); + } + return rows; +} + +export interface LibraryWorkflowUseRow { + key: string; + workflowId: string | null; + version: string | null; + runId: string | null; + runCount: number; + lastUsed: string; + isActiveRun: boolean; +} + +/** + * "Workflows that use it": the usage projection keeps one record per asset with + * its most recent workflow and run, so the table has at most one row. + */ +export function libraryWorkflowUseRows( + row: LibraryModelRow, + activeRunId: string | null | undefined, + nowMs: number, +): LibraryWorkflowUseRow[] { + const usage = row.usage; + if (!usage || (!usage.last_workflow_id && !usage.last_workflow_run_id)) return []; + return [ + { + key: `${usage.asset_id}:${usage.last_workflow_run_id ?? usage.last_workflow_id}`, + workflowId: usage.last_workflow_id ?? null, + version: usage.last_workflow_semantic_version ?? null, + runId: usage.last_workflow_run_id ?? null, + runCount: usage.run_access_count, + lastUsed: formatLibraryTimeShort(usage.last_accessed_at_ms, nowMs), + isActiveRun: isLibraryAssetLastUsedByRun(usage, activeRunId), + }, + ]; +} + +/** Why `Delete from disk` is blocked, or null when it is allowed. */ +export function libraryDeleteBlockReason( + row: LibraryModelRow, + activeRunId: string | null | undefined, + actionBusy: boolean, +): string | null { + if (row.usage && isLibraryAssetLastUsedByRun(row.usage, activeRunId)) { + return 'Cannot delete while the active run is the last one that used this model'; + } + if (actionBusy) return 'Wait for the current library action to finish'; + return null; +} + +export function formatPumasDeleteStatus(response: PumasModelDeleteAuditResponse): string { + if (!response.success) return response.error ?? 'Delete did not complete'; + return response.auditEventSeq ? `Delete recorded at event ${response.auditEventSeq}` : 'Delete finished'; +} + +// --------------------------------------------------------------------------- +// Hugging Face search mode. +// --------------------------------------------------------------------------- + +export const HF_SEARCH_DEFAULT_LIMIT = 25; +export const HF_SEARCH_MAX_LIMIT = 100; +/** Results hydrated with file sizes per search (bounded host work). */ +export const HF_SEARCH_MAX_HYDRATE = 10; + +/** Clamps the limit field to the host's accepted range (1 to 100); a blank field uses the default. */ +export function normalizeHfSearchLimit(value: unknown): number { + if (value === null || value === undefined || (typeof value === 'string' && value.trim() === '')) { + return HF_SEARCH_DEFAULT_LIMIT; + } + const numeric = typeof value === 'number' ? value : Number(value); + if (!Number.isFinite(numeric)) return HF_SEARCH_DEFAULT_LIMIT; + return Math.min(HF_SEARCH_MAX_LIMIT, Math.max(1, Math.trunc(numeric))); +} + +/** Trims the inputs: the host rejects padded queries and empty kinds. */ +export function buildHfSearchRequest(input: { + query: string; + kind: string; + limit: unknown; +}): PumasHfModelSearchAuditRequest { + const limit = normalizeHfSearchLimit(input.limit); + const kind = input.kind.trim(); + return { + query: input.query.trim(), + kind: kind.length > 0 ? kind : null, + limit, + hydrateLimit: Math.min(limit, HF_SEARCH_MAX_HYDRATE), + }; +} + +export interface HfDownloadOptions { + officialName: string; + family: string; + modelType: string; +} + +/** Download request with today's defaults: family "model", official name = repository id. */ +export function buildHfDownloadRequest(repoId: string, options: HfDownloadOptions): PumasHfDownloadRequest { + const repo = repoId.trim(); + const modelType = options.modelType.trim(); + return { + repo_id: repo, + family: options.family.trim() || 'model', + official_name: options.officialName.trim() || repo, + model_type: modelType.length > 0 ? modelType : null, + }; +} + +export interface LibraryHfResultRow { + repoId: string; + sub: string; + size: string | null; +} + +function compactCount(count: number): string { + if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`; + if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`; + return String(count); +} + +/** + * One search result row from the Pumas `HuggingFaceModel` projection (camelCase + * fields). Results without a repository id are dropped because they cannot be + * downloaded. + */ +export function projectHfSearchResult(result: PumasHfModelSearchResult): LibraryHfResultRow | null { + const repoId = nonEmptyString(result.repoId); + if (!repoId) return null; + const parts: string[] = []; + const kind = nonEmptyString(result.kind); + if (kind && kind !== 'unknown') parts.push(kind); + if (Array.isArray(result.formats)) { + const formats = result.formats.map(nonEmptyString).filter((format): format is string => format !== null); + if (formats.length > 0) parts.push(formats.join(', ')); + } + if (typeof result.downloads === 'number' && Number.isFinite(result.downloads)) { + parts.push(`${compactCount(result.downloads)} downloads`); + } + const size = result.totalSizeBytes; + return { + repoId, + sub: parts.join(', '), + size: typeof size === 'number' && Number.isFinite(size) && size > 0 ? formatLibraryBytes(size) : null, + }; +} + +export function projectHfSearchResults(results: readonly PumasHfModelSearchResult[]): LibraryHfResultRow[] { + const seen = new Set(); + const rows: LibraryHfResultRow[] = []; + for (const result of results) { + const row = projectHfSearchResult(result); + if (!row || seen.has(row.repoId)) continue; + seen.add(row.repoId); + rows.push(row); + } + return rows; +} + +export function formatHfResultCountLine(count: number, limit: number): string { + if (count === 0) return 'No Hugging Face models match. Try a shorter or different query.'; + if (count >= limit) return `Showing the first ${count}. Narrow the search or raise the limit to see others.`; + return plural(count, 'result'); +} + +export function formatHfSearchStatus(response: PumasHfModelSearchAuditResponse): string { + return response.auditEventSeq ? `Search recorded at event ${response.auditEventSeq}` : 'Search finished'; +} + +export function formatHfDownloadStatus(repoId: string, response: PumasHfDownloadStartAuditResponse): string { + return response.auditEventSeq + ? `Download ${response.downloadId} of ${repoId} recorded at event ${response.auditEventSeq}` + : `Download ${response.downloadId} of ${repoId} started`; +} + +// --------------------------------------------------------------------------- +// Request authority for the page's async work. +// --------------------------------------------------------------------------- + +export interface LibraryRequestGate { + /** Starts an invocation; earlier tokens from this gate stop being current. */ + begin(): number; + /** True while `token` is the newest invocation and the gate is not disposed. */ + isCurrent(token: number): boolean; + /** Owner teardown: no token is current afterwards and `begin` returns stale tokens. */ + dispose(): void; +} + +/** + * Generation token scoped to one owner (one page instance and one kind of + * request). A completion applies its result only while `isCurrent` holds, so a + * superseded or post-unmount completion never writes page state. + */ +export function createLibraryRequestGate(): LibraryRequestGate { + let generation = 0; + let disposed = false; + return { + begin: () => ++generation, + isCurrent: (token) => !disposed && token === generation, + dispose: () => { + disposed = true; + }, + }; +} diff --git a/src/components/workbench/networkPagePresenters.test.ts b/src/components/workbench/networkPagePresenters.test.ts index a2cd74635..4ae7a9a75 100644 --- a/src/components/workbench/networkPagePresenters.test.ts +++ b/src/components/workbench/networkPagePresenters.test.ts @@ -1,57 +1,77 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import type { NodeStatusProjectionRecord } from '../../services/diagnostics/types.ts'; -import type { WorkflowLocalNetworkNodeStatus } from '../../services/workflow/types.ts'; +import type { + NodeStatusProjectionRecord, + SchedulerTimelineProjectionRecord, +} from '../../services/diagnostics/types.ts'; +import type { + WorkflowLocalNetworkNodeStatus, + WorkflowPeerNetworkNodeStatus, +} from '../../services/workflow/types.ts'; import { - buildNetworkFactRows, + buildLocalDeviceRows, + buildLocalDiskRows, + buildLocalIdentityRows, + buildLocalInterfaceRows, + buildLocalNodeEntry, + buildLocalNodeHeader, + buildLocalStatCells, + buildNetworkDimensionLine, + buildNetworkNodeGroups, + buildPeerDetail, + buildPeerNodeEntry, + buildSelectedRunEventLines, buildSelectedRunExecutionRows, + buildSelectedRunOnLocalNode, buildSelectedRunResourceRows, - buildSelectedRunPlacementRows, - formatCpuUsage, - formatGpuAvailability, + describeLocalStatusFailure, + describeRunProjectionFailure, + describeSelectedRunForPeer, + findSelectedRunPlacement, formatNetworkBytes, + formatNetworkClock, formatNetworkProjectionFreshness, - formatSchedulerLoad, - findSelectedRunPlacement, - formatSelectedRunRequirementList, + formatSelectedRunLocalState, formatSelectedRunModelCacheState, - formatSelectedRunResourceCacheStatus, formatSelectedRunNodeStatus, - formatSelectedRunLocalState, - formatSelectedRunPlacementState, + formatSelectedRunRequirementList, + formatSelectedRunResourceCacheStatus, formatSelectedRunRuntimePosture, - selectedRunNodeStatusClass, - selectedRunResourceCacheClass, - formatSessionLoad, formatTransportState, + glyphStateForTransport, + groupDegradationWarnings, + logLevelForTimelineEvent, + resolveSelectedNodeId, } from './networkPagePresenters.ts'; -function createNode(): WorkflowLocalNetworkNodeStatus { +const GIB = 1_073_741_824; + +function createNode(overrides: Partial = {}): WorkflowLocalNetworkNodeStatus { return { - node_id: 'local-node', - display_name: 'Local Node', - captured_at_ms: 1_000, + node_id: 'local', + display_name: 'orangecream', + captured_at_ms: new Date(2026, 10, 3, 20, 5, 51).getTime(), transport_state: 'local_only', system: { - hostname: 'host-a', + hostname: 'orangecream', os_name: 'Linux', - os_version: '6', - kernel_version: '6.1', + os_version: '7.0', + kernel_version: '7.0.0-31-generic', cpu: { - logical_core_count: 8, - average_usage_percent: null, + logical_core_count: 16, + average_usage_percent: 12.4, }, memory: { - total_bytes: 16_000, - used_bytes: 8_000, - available_bytes: 8_000, + total_bytes: 64 * GIB, + used_bytes: 16 * GIB, + available_bytes: 48 * GIB, }, disks: [ { - name: 'disk-a', + name: 'nvme0n1p2', mount_point: '/', - total_bytes: 1_073_741_824, + total_bytes: GIB, available_bytes: 536_870_912, }, ], @@ -64,7 +84,7 @@ function createNode(): WorkflowLocalNetworkNodeStatus { ], gpu: { available: false, - reason: 'GPU probe unavailable', + reason: 'GPU metrics are not collected by the local system metrics provider', }, }, scheduler_load: { @@ -75,7 +95,7 @@ function createNode(): WorkflowLocalNetworkNodeStatus { active_run_count: 2, queued_run_count: 3, active_workflow_run_ids: ['run-active'], - queued_workflow_run_ids: ['run-queued'], + queued_workflow_run_ids: ['run-queued', 'run-queued-unplaced'], run_placements: [ { workflow_run_id: 'run-active', @@ -83,8 +103,8 @@ function createNode(): WorkflowLocalNetworkNodeStatus { workflow_id: 'workflow-a', state: 'running', runtime_loaded: true, - model_cache_state: 'unknown', - required_backends: ['python'], + model_cache_state: 'cache_hit', + required_backends: ['llama.cpp'], required_models: ['model-a'], }, { @@ -99,10 +119,19 @@ function createNode(): WorkflowLocalNetworkNodeStatus { }, ], }, - degradation_warnings: ['GPU probe unavailable'], + degradation_warnings: [], + ...overrides, }; } +function createPeers(): WorkflowPeerNetworkNodeStatus[] { + return [ + { node_id: 'node-studio', display_name: 'Studio', transport_state: 'connected', last_seen_at_ms: new Date(2026, 10, 3, 20, 5, 48).getTime() }, + { node_id: 'node-laptop', display_name: 'Laptop', transport_state: 'degraded', last_seen_at_ms: new Date(2026, 10, 3, 19, 48, 10).getTime() }, + { node_id: 'node-render', display_name: 'Render box', transport_state: 'pairing_required', last_seen_at_ms: null }, + ]; +} + function createNodeStatus(overrides: Partial): NodeStatusProjectionRecord { return { workflow_run_id: 'run-active', @@ -129,79 +158,241 @@ function createNodeStatus(overrides: Partial): NodeS }; } -test('network byte presenter keeps compact storage and traffic labels', () => { +function createTimelineEvent(overrides: Partial): SchedulerTimelineProjectionRecord { + return { + event_seq: 1, + event_id: 'evt-1', + event_kind: 'scheduler_queue_placement', + source_component: 'scheduler', + occurred_at_ms: new Date(2026, 10, 3, 20, 1, 40, 118).getTime(), + recorded_at_ms: 0, + workflow_run_id: 'run-active', + workflow_id: 'workflow-a', + summary: 'Run queued', + payload_json: '{}', + ...overrides, + } as SchedulerTimelineProjectionRecord; +} + +test('formatters keep compact byte and clock labels', () => { assert.equal(formatNetworkBytes(null), 'Unavailable'); assert.equal(formatNetworkBytes(512), '512 B'); assert.equal(formatNetworkBytes(2_048), '2.0 KiB'); assert.equal(formatNetworkBytes(2_097_152), '2.0 MiB'); + assert.equal(formatNetworkBytes(4096 * GIB), '4.0 TiB'); + const at = new Date(2026, 10, 3, 9, 4, 7, 5).getTime(); + assert.equal(formatNetworkClock(at), '09:04:07'); + assert.equal(formatNetworkClock(at, { millis: true }), '09:04:07.005'); + assert.equal(formatNetworkClock(at, { seconds: false }), '09:04'); + assert.equal(formatTransportState('pairing_required'), 'Pairing required'); }); -test('network state presenters avoid fake degraded metric values', () => { - const node = createNode(); +test('transport states map to the glyph vocabulary', () => { + assert.equal(glyphStateForTransport('connected'), 'succeeded'); + assert.equal(glyphStateForTransport('degraded'), 'cancelled'); + assert.equal(glyphStateForTransport('pairing_required'), 'queued'); + assert.equal(glyphStateForTransport('local_only'), 'running'); + assert.equal(glyphStateForTransport('peer_networking_unavailable'), 'idle'); +}); - assert.equal(formatTransportState('local_only'), 'Local only'); - assert.equal(formatTransportState('pairing_required'), 'Pairing required'); - assert.equal(formatCpuUsage(node.system.cpu.average_usage_percent), 'Usage unavailable'); - assert.equal(formatGpuAvailability(node), 'GPU probe unavailable'); +test('node list puts the local node first and keeps peers in projection order', () => { + const groups = buildNetworkNodeGroups(createNode({ transport_state: 'connected' }), createPeers()); + + assert.equal(groups.local.nodeId, 'local'); + assert.equal(groups.local.kind, 'local'); + // The local node reads as local whatever its transport state is. + assert.equal(groups.local.glyph, 'running'); + assert.equal(groups.local.line1, '2 running, 3 queued'); + assert.equal(groups.local.line2, '16 cores, 16.0 GiB of 64.0 GiB memory'); + assert.equal(groups.local.time, 'local'); + + assert.deepEqual( + groups.peers.map((peer) => [peer.nodeId, peer.glyph, peer.line1, peer.time]), + [ + ['node-studio', 'succeeded', 'Connected', '20:05'], + ['node-laptop', 'cancelled', 'Degraded', '19:48'], + ['node-render', 'queued', 'Pairing required', ''], + ], + ); + assert.equal(groups.peers[2].line2, 'Details hidden until paired'); + assert.equal(groups.peers[0].line2, 'Metrics not reported for peers'); + assert.equal(groups.peers[0].timeTitle, 'Last seen 20:05:48'); }); -test('network load presenters expose scheduler capacity', () => { - const node = createNode(); +test('selected node falls back to the local node when the peer is gone', () => { + const groups = buildNetworkNodeGroups(createNode(), createPeers()); - assert.equal(formatSchedulerLoad(node), '2 active / 3 queued'); - assert.equal(formatSessionLoad(node), '1/4 sessions, 1/2 loaded'); - assert.equal(formatSelectedRunLocalState(node, 'run-active'), 'Running locally'); - assert.equal(formatSelectedRunLocalState(node, 'run-queued'), 'Queued locally'); - assert.equal(formatSelectedRunLocalState(node, 'run-missing'), 'Not scheduled locally'); - assert.equal(formatSelectedRunLocalState(node, null), 'No selected run'); + assert.equal(resolveSelectedNodeId(groups, null), 'local'); + assert.equal(resolveSelectedNodeId(groups, 'node-laptop'), 'node-laptop'); + assert.equal(resolveSelectedNodeId(groups, 'node-forgotten'), 'local'); + assert.equal(resolveSelectedNodeId(groups, 'local'), 'local'); +}); - const placement = findSelectedRunPlacement(node, 'run-active'); - assert.equal(placement?.workflow_execution_session_id, 'session-active'); - assert.equal(formatSelectedRunRuntimePosture(placement), 'Runtime session loaded'); - assert.equal(formatSelectedRunRuntimePosture(findSelectedRunPlacement(node, 'run-queued')), 'Runtime session not loaded'); - assert.equal(formatSelectedRunRuntimePosture(null), 'Unavailable'); - assert.equal(formatSelectedRunModelCacheState(placement?.model_cache_state ?? 'unknown'), 'Cache state unknown'); +test('dimension line counts nodes by transport and omits unreported GPU totals', () => { assert.equal( - formatSelectedRunModelCacheState(findSelectedRunPlacement(node, 'run-queued')?.model_cache_state ?? 'unknown'), - 'Model not required', + buildNetworkDimensionLine(createNode(), createPeers(), false), + '4 nodes, 2 connected, 1 degraded, 1 waiting to be paired.', ); - assert.equal(formatSelectedRunPlacementState(placement), 'Running locally'); - assert.equal(formatSelectedRunPlacementState(findSelectedRunPlacement(node, 'run-queued')), 'Queued locally'); - assert.equal(formatSelectedRunPlacementState(null), 'Unavailable'); - assert.equal(formatSelectedRunRequirementList(placement?.required_backends ?? [], 'No backends'), 'python'); - assert.equal(formatSelectedRunRequirementList([], 'No models'), 'No models'); + assert.equal(buildNetworkDimensionLine(createNode(), [], false), '1 node, 1 connected.'); + assert.equal( + buildNetworkDimensionLine( + createNode({ transport_state: 'peer_networking_unavailable' }), + [{ node_id: 'p', display_name: 'P', transport_state: 'peer_networking_unavailable' }], + false, + ), + '2 nodes, 1 connected, 1 without peer networking.', + ); + assert.equal(buildNetworkDimensionLine(null, [], true), 'Reading local status'); + assert.equal(buildNetworkDimensionLine(null, [], false), 'Local status unavailable'); }); -test('formatNetworkProjectionFreshness keeps selected-run projection cursor visible', () => { - assert.equal(formatNetworkProjectionFreshness(null), 'Projection unavailable'); - assert.equal( - formatNetworkProjectionFreshness({ - projection_name: 'node_status', - projection_version: 5, - last_applied_event_seq: 42, - status: 'rebuilding', - rebuilt_at_ms: null, - updated_at_ms: 5, +test('degradation warnings go to the section they qualify', () => { + const node = createNode({ + degradation_warnings: [ + 'GPU metrics are not collected by the local system metrics provider', + 'CPU usage sample was too short', + 'Memory totals unavailable inside the sandbox', + 'Disk metrics skipped for network mounts', + 'Network interface counters unavailable', + 'Peer discovery is disabled', + 'Metrics captured late', + 'CPU usage sample was too short', + ], + }); + const grouped = groupDegradationWarnings(node); + + // The GPU reason already shows in Devices, so the duplicate warning is dropped. + assert.deepEqual(grouped.devices, []); + assert.deepEqual(grouped.cpu, ['CPU usage sample was too short']); + assert.deepEqual(grouped.memory, ['Memory totals unavailable inside the sandbox']); + assert.deepEqual(grouped.disks, ['Disk metrics skipped for network mounts']); + assert.deepEqual(grouped.interfaces, ['Network interface counters unavailable']); + assert.deepEqual(grouped.node, ['Peer discovery is disabled', 'Metrics captured late']); + assert.deepEqual(groupDegradationWarnings(createNode({ degradation_warnings: ['CUDA probe failed'] })).devices, [ + 'CUDA probe failed', + ]); +}); + +test('local detail presenters render reported facts and name what is missing', () => { + const node = createNode(); + const header = buildLocalNodeHeader(node, 0); + assert.equal(header.subtitle, 'Linux 7.0, captured 20:05:51'); + assert.equal(header.transportLabel, 'Local only'); + assert.deepEqual(header.chips, ['16 cores', 'No GPU reported']); + assert.deepEqual(buildLocalNodeHeader(createNode({ transport_state: 'connected' }), 3).chips, [ + '16 cores', + 'No GPU reported', + '3 peers', + ]); + + const cells = buildLocalStatCells(node); + assert.deepEqual( + cells.map((cell) => [cell.id, cell.value, cell.label, cell.meterPercent]), + [ + ['cpu', '12%', '16 cores', 12.4], + ['memory', '16.0 GiB', 'of 64.0 GiB memory in use', 25], + ['scheduler', '2 / 3', 'running / queued here', null], + ['sessions', '1 of 2', 'runtime sessions loaded, 1 of 4 active', null], + ], + ); + const unreported = buildLocalStatCells( + createNode({ + system: { ...node.system, cpu: { logical_core_count: 1, average_usage_percent: null }, memory: { total_bytes: 0, used_bytes: 0, available_bytes: 0 } }, }), - 'Rebuilding at seq 42', + ); + assert.deepEqual([unreported[0].value, unreported[0].label, unreported[0].meterPercent], ['Not reported', '1 core, usage not reported', null]); + assert.equal(unreported[1].meterPercent, null); + + assert.deepEqual(buildLocalDeviceRows(node), [ + { key: 'GPU', value: 'Not available' }, + { key: 'Reason', value: 'GPU metrics are not collected by the local system metrics provider' }, + ]); + assert.deepEqual( + buildLocalDeviceRows(createNode({ system: { ...node.system, gpu: { available: true, reason: null } } })), + [{ key: 'GPU', value: 'Available' }], + ); + assert.deepEqual(buildLocalDiskRows(node), [ + { key: 'nvme0n1p2\u{1f}/', mount: '/', name: 'nvme0n1p2', free: '512.0 MiB', total: '1.0 GiB' }, + ]); + assert.deepEqual(buildLocalInterfaceRows(node), [{ name: 'eth0', received: '2.0 KiB', sent: '4.0 KiB' }]); + assert.deepEqual( + buildLocalIdentityRows(createNode({ system: { ...node.system, hostname: null, kernel_version: null } })).map((row) => row.value), + ['local', 'Not reported', 'Linux 7.0', 'Not reported'], ); }); -test('buildSelectedRunPlacementRows exposes selected-run local relevance facts', () => { - const placement = findSelectedRunPlacement(createNode(), 'run-active'); - const rows = buildSelectedRunPlacementRows(placement); - - assert.equal(rows.find((row) => row.label === 'State')?.value, 'Running locally'); - assert.equal(rows.find((row) => row.label === 'Session')?.value, 'session-active'); - assert.equal(rows.find((row) => row.label === 'Workflow')?.value, 'workflow-a'); - assert.equal(rows.find((row) => row.label === 'Runtime')?.value, 'Runtime session loaded'); - assert.equal(rows.find((row) => row.label === 'Model Cache')?.value, 'Cache state unknown'); - assert.equal(rows.find((row) => row.label === 'Backends')?.value, 'python'); - assert.equal(rows.find((row) => row.label === 'Models')?.value, 'model-a'); - assert.equal(buildSelectedRunPlacementRows(null).find((row) => row.label === 'State')?.value, 'Not scheduled locally'); +test('peer detail reports only transport and last-seen facts', () => { + const [studio, , render] = createPeers(); + const detail = buildPeerDetail(studio); + assert.equal(detail.header.glyph, 'succeeded'); + assert.equal(detail.header.subtitle, 'Last seen 20:05:48'); + assert.match(detail.note, /reports only the transport state and last-seen time/); + assert.deepEqual(detail.identityRows.map((row) => row.value), ['node-studio', 'Connected', '20:05:48']); + + const pairing = buildPeerDetail(render); + assert.deepEqual(pairing.header.chips, []); + assert.equal(pairing.header.glyph, 'queued'); + assert.equal(pairing.header.subtitle, 'Not seen yet'); + assert.match(pairing.note, /not trusted yet/); + assert.equal(buildPeerNodeEntry(render).timeTitle, undefined); + assert.equal(buildLocalNodeEntry(createNode()).timeTitle, 'This node'); +}); + +test('selected run placement on the local node uses the placement record', () => { + const node = createNode(); + + const placed = buildSelectedRunOnLocalNode(node, { workflow_run_id: 'run-active', workflow_id: 'ingest-docs-rag' }); + assert.equal(placed.heading, 'ingest-docs-rag on this node'); + assert.equal(placed.state, 'Running locally'); + assert.equal(placed.placed, true); + assert.equal(placed.note, null); + assert.deepEqual(placed.rows, [ + { key: 'Runtime session', value: 'Runtime session loaded, model cache hit' }, + { key: 'Session id', value: 'session-active', mono: true }, + { key: 'Backends', value: 'llama.cpp' }, + { key: 'Models', value: 'model-a' }, + ]); + + const fromPlacement = buildSelectedRunOnLocalNode(node, { workflow_run_id: 'run-queued' }); + assert.equal(fromPlacement.heading, 'workflow-a on this node'); + assert.equal(fromPlacement.state, 'Queued locally'); + + const finished = buildSelectedRunOnLocalNode(node, { workflow_run_id: 'run-done', workflow_id: null }); + assert.equal(finished.heading, 'Selected run on this node'); + assert.equal(finished.state, 'Not running or queued here'); + assert.equal(finished.placed, false); + assert.deepEqual(finished.rows, []); + assert.match(finished.note ?? '', /lists only runs that are running or queued/); + + const listedWithoutPlacement = buildSelectedRunOnLocalNode(node, { workflow_run_id: 'run-queued-unplaced' }); + assert.equal(listedWithoutPlacement.state, 'Queued locally'); + assert.match(listedWithoutPlacement.note ?? '', /placement record is not in the local status yet/); }); -test('buildSelectedRunExecutionRows exposes selected-run node runtime and model facts', () => { +test('selected run with a peer open never claims peer placement', () => { + const node = createNode(); + assert.deepEqual(describeSelectedRunForPeer(node, { workflow_run_id: 'run-active', workflow_id: 'wf' }, 'Studio'), { + heading: 'wf', + sentence: 'wf is running on orangecream, not on Studio.', + }); + assert.match( + describeSelectedRunForPeer(node, { workflow_run_id: 'run-done', workflow_id: 'wf' }, 'Studio').sentence, + /does not report run placement on peers/, + ); +}); + +test('placement helpers keep their wording', () => { + const node = createNode(); + const placement = findSelectedRunPlacement(node, 'run-active'); + assert.equal(findSelectedRunPlacement(node, null), null); + assert.equal(formatSelectedRunLocalState(node, null), 'No selected run'); + assert.equal(formatSelectedRunRuntimePosture(placement), 'Runtime session loaded'); + assert.equal(formatSelectedRunRuntimePosture(null), 'Unavailable'); + assert.equal(formatSelectedRunModelCacheState('unknown'), 'Cache state unknown'); + assert.equal(formatSelectedRunRequirementList([], 'No models'), 'No models'); +}); + +test('execution rows carry the node status glyph', () => { const rows = buildSelectedRunExecutionRows([ createNodeStatus({ node_id: 'node-a', status: 'running' }), createNodeStatus({ @@ -212,30 +403,18 @@ test('buildSelectedRunExecutionRows exposes selected-run node runtime and model model_id: '', model_version: null, }), + createNodeStatus({ node_id: 'node-c', status: 'completed' }), ]); assert.deepEqual(rows, [ - { - nodeId: 'node-a', - status: 'Running', - statusClass: 'border-cyan-800 bg-cyan-950/50 text-cyan-200', - runtime: 'runtime-a@2.0.0', - model: 'model-a@3.0.0', - }, - { - nodeId: 'node-b', - status: 'Waiting', - statusClass: 'border-amber-800 bg-amber-950/50 text-amber-200', - runtime: 'Runtime unavailable', - model: 'Model unavailable', - }, + { nodeId: 'node-a', status: 'Running', glyph: 'running', runtime: 'runtime-a@2.0.0', model: 'model-a@3.0.0' }, + { nodeId: 'node-b', status: 'Waiting', glyph: 'waiting', runtime: 'Runtime unavailable', model: 'Model unavailable' }, + { nodeId: 'node-c', status: 'Completed', glyph: 'succeeded', runtime: 'runtime-a@2.0.0', model: 'model-a@3.0.0' }, ]); assert.equal(formatSelectedRunNodeStatus('cancelled'), 'Cancelled'); - assert.match(selectedRunNodeStatusClass('completed'), /emerald/); - assert.match(selectedRunNodeStatusClass('failed'), /red/); }); -test('buildSelectedRunResourceRows exposes selected-run Library usage facts', () => { +test('resource rows describe library usage in sentence case', () => { const rows = buildSelectedRunResourceRows([ { asset_id: 'model:llama', @@ -251,25 +430,67 @@ test('buildSelectedRunResourceRows exposes selected-run Library usage facts', () ]); assert.deepEqual(rows, [ + { assetId: 'model:llama', category: 'Model', cacheStatus: 'Cache hit', networkBytes: '2.0 KiB', accessCount: '2' }, + ]); + assert.equal(formatSelectedRunResourceCacheStatus(null), 'Not reported'); + assert.equal(formatSelectedRunResourceCacheStatus('load_requested'), 'Load requested'); +}); + +test('timeline events become log lines with a level from the error severity', () => { + const lines = buildSelectedRunEventLines([ + createTimelineEvent({}), + createTimelineEvent({ + event_id: 'evt-2', + event_kind: 'diagnostic_error_occurred', + source_component: 'runtime', + summary: 'Model load failed', + detail: 'out of memory', + error_severity: 'fatal', + }), + ]); + + assert.deepEqual(lines, [ + { id: 'evt-1', time: '20:01:40.118', level: 'info', kind: 'scheduler_queue_placement', message: 'Run queued', source: 'scheduler' }, { - assetId: 'model:llama', - category: 'Model', - cacheStatus: 'Cache Hit', - cacheClass: 'border-emerald-800 bg-emerald-950/50 text-emerald-200', - networkBytes: '2.0 KiB', - accessCount: '2', + id: 'evt-2', + time: '20:01:40.118', + level: 'error', + kind: 'diagnostic_error_occurred', + message: 'Model load failed. out of memory', + source: 'runtime', }, ]); - assert.equal(formatSelectedRunResourceCacheStatus(null), 'Cache status unavailable'); - assert.match(selectedRunResourceCacheClass('cache_miss'), /amber/); - assert.match(selectedRunResourceCacheClass('failed'), /red/); - assert.match(selectedRunResourceCacheClass(null), /neutral/); + assert.equal(logLevelForTimelineEvent('warning'), 'warn'); + assert.equal(logLevelForTimelineEvent('error'), 'error'); + assert.equal(logLevelForTimelineEvent(null), 'info'); }); -test('buildNetworkFactRows summarizes local node capabilities', () => { - const rows = buildNetworkFactRows(createNode()); +test('failures read as sentences and keep the last capture visible', () => { + assert.equal( + describeLocalStatusFailure('Transport error: host unreachable', null), + 'Pantograph could not read the local status. Transport error: host unreachable.', + ); + assert.equal( + describeLocalStatusFailure('Internal error: probe failed.', new Date(2026, 10, 3, 20, 5, 51).getTime()), + 'The last refresh failed, so this is the status captured at 20:05:51. Internal error: probe failed.', + ); + assert.equal( + describeRunProjectionFailure('node status for this run', 'Scheduler busy'), + 'Could not read node status for this run. Scheduler busy.', + ); +}); - assert.equal(rows.find((row) => row.label === 'Node ID')?.value, 'local-node'); - assert.equal(rows.find((row) => row.label === 'OS')?.value, 'Linux 6'); - assert.equal(rows.find((row) => row.label === 'Network Interfaces')?.value, '1'); +test('formatNetworkProjectionFreshness keeps the projection cursor visible', () => { + assert.equal(formatNetworkProjectionFreshness(null), 'Projection unavailable'); + assert.equal( + formatNetworkProjectionFreshness({ + projection_name: 'node_status', + projection_version: 5, + last_applied_event_seq: 42, + status: 'rebuilding', + rebuilt_at_ms: null, + updated_at_ms: 5, + }), + 'Rebuilding at seq 42', + ); }); diff --git a/src/components/workbench/networkPagePresenters.ts b/src/components/workbench/networkPagePresenters.ts index bac173461..f20c4e509 100644 --- a/src/components/workbench/networkPagePresenters.ts +++ b/src/components/workbench/networkPagePresenters.ts @@ -2,48 +2,41 @@ import type { LibraryUsageProjectionRecord, NodeStatusProjectionRecord, ProjectionStateRecord, + SchedulerTimelineProjectionRecord, } from '../../services/diagnostics/types'; import type { WorkflowLocalNetworkNodeStatus, WorkflowLocalRunPlacementRecord, - WorkflowSchedulerModelCacheState, WorkflowNetworkTransportState, + WorkflowPeerNetworkNodeStatus, + WorkflowSchedulerModelCacheState, } from '../../services/workflow/types'; import { formatLibraryAssetCategory, formatLibraryBytes, } from './libraryUsagePresenters.ts'; import { formatProjectionFreshnessState } from './projectionFreshness.ts'; +import { glyphStateForStatus, type GlyphState, type LogLevel } from './ui/statusGlyph.ts'; +import type { KeyValueRow } from './ui/types.ts'; -export interface NetworkFactRow { - label: string; - value: string; - mono?: boolean; -} +/* + * Network page projection. Everything here is derived from the local network + * status query, the selected run's node status, library usage and scheduler + * timeline projections. Nothing is invented: when the projection does not + * report a fact (peer metrics, per-device memory, latency), the presenters say + * so in a sentence instead of filling a number. + */ -export type NetworkSelectedRunPlacementRow = NetworkFactRow; - -export interface NetworkSelectedRunResourceRow { - assetId: string; - category: string; - cacheStatus: string; - cacheClass: string; - networkBytes: string; - accessCount: string; -} - -export interface NetworkSelectedRunExecutionRow { - nodeId: string; - status: string; - statusClass: string; - runtime: string; - model: string; -} +// --------------------------------------------------------------------------- +// Formatting export function formatNetworkBytes(bytes: number | null | undefined): string { if (bytes === null || bytes === undefined) { return 'Unavailable'; } + if (bytes >= 1_099_511_627_776) { + return `${(bytes / 1_099_511_627_776).toFixed(1)} TiB`; + } if (bytes >= 1_073_741_824) { return `${(bytes / 1_073_741_824).toFixed(1)} GiB`; } @@ -56,8 +49,19 @@ export function formatNetworkBytes(bytes: number | null | undefined): string { return `${bytes} B`; } -export function formatNetworkTimestamp(value: number): string { - return new Date(value).toLocaleString(); +function pad(value: number, width = 2): string { + return String(value).padStart(width, '0'); +} + +/** Local wall-clock time, `HH:MM:SS`, or `HH:MM:SS.mmm` with `millis`. */ +export function formatNetworkClock(valueMs: number, options: { millis?: boolean; seconds?: boolean } = {}): string { + const date = new Date(valueMs); + const base = `${pad(date.getHours())}:${pad(date.getMinutes())}`; + if (options.seconds === false) { + return base; + } + const withSeconds = `${base}:${pad(date.getSeconds())}`; + return options.millis ? `${withSeconds}.${pad(date.getMilliseconds(), 3)}` : withSeconds; } export function formatNetworkProjectionFreshness(state: ProjectionStateRecord | null): string { @@ -79,28 +83,381 @@ export function formatTransportState(state: WorkflowNetworkTransportState): stri } } -export function formatCpuUsage(value: number | null | undefined): string { - if (value === null || value === undefined) { - return 'Usage unavailable'; +/** + * Glyph for a node's transport state: connected → succeeded, degraded → + * cancelled, pairing required → queued, local → running. A peer whose host has + * no peer networking has no live link to show and renders idle. + */ +export function glyphStateForTransport(state: WorkflowNetworkTransportState): GlyphState { + switch (state) { + case 'connected': + return 'succeeded'; + case 'degraded': + return 'cancelled'; + case 'pairing_required': + return 'queued'; + case 'local_only': + return 'running'; + case 'peer_networking_unavailable': + return 'idle'; } - return `${value.toFixed(1)}% average`; } -export function formatGpuAvailability(node: WorkflowLocalNetworkNodeStatus): string { - if (node.system.gpu.available) { - return 'Available'; +/** The local node is the one this engine runs on; it always reads as local. */ +export const LOCAL_NODE_GLYPH: GlyphState = 'running'; + +function formatOsLabel(node: WorkflowLocalNetworkNodeStatus): string { + const name = node.system.os_name; + const version = node.system.os_version; + if (name && version) { + return `${name} ${version}`; } - return node.system.gpu.reason ?? 'Unavailable'; + return name ?? 'OS not reported'; +} + +function plural(count: number, singular: string, pluralForm = `${singular}s`): string { + return `${count} ${count === 1 ? singular : pluralForm}`; +} + +// --------------------------------------------------------------------------- +// Left list: local node first, then peers in projection order + +export type NetworkNodeKind = 'local' | 'peer'; + +export interface NetworkNodeEntry { + nodeId: string; + kind: NetworkNodeKind; + name: string; + glyph: GlyphState; + transportLabel: string; + /** First sub-line. */ + line1: string; + /** Second, smaller sub-line. */ + line2: string; + /** Mono text on the right of the row; empty when nothing is reported. */ + time: string; + timeTitle?: string; } -export function formatSchedulerLoad(node: WorkflowLocalNetworkNodeStatus): string { +export interface NetworkNodeGroups { + local: NetworkNodeEntry; + peers: NetworkNodeEntry[]; +} + +export function buildLocalNodeEntry(node: WorkflowLocalNetworkNodeStatus): NetworkNodeEntry { const load = node.scheduler_load; - return `${load.active_run_count} active / ${load.queued_run_count} queued`; + const memory = node.system.memory; + return { + nodeId: node.node_id, + kind: 'local', + name: node.display_name, + glyph: LOCAL_NODE_GLYPH, + transportLabel: formatTransportState(node.transport_state), + line1: `${load.active_run_count} running, ${load.queued_run_count} queued`, + line2: `${plural(node.system.cpu.logical_core_count, 'core')}, ${formatNetworkBytes(memory.used_bytes)} of ${formatNetworkBytes(memory.total_bytes)} memory`, + time: 'local', + timeTitle: 'This node', + }; +} + +export function buildPeerNodeEntry(peer: WorkflowPeerNetworkNodeStatus): NetworkNodeEntry { + const lastSeen = peer.last_seen_at_ms ?? null; + return { + nodeId: peer.node_id, + kind: 'peer', + name: peer.display_name, + glyph: glyphStateForTransport(peer.transport_state), + transportLabel: formatTransportState(peer.transport_state), + line1: formatTransportState(peer.transport_state), + line2: + peer.transport_state === 'pairing_required' + ? 'Details hidden until paired' + : 'Metrics not reported for peers', + time: lastSeen === null ? '' : formatNetworkClock(lastSeen, { seconds: false }), + timeTitle: lastSeen === null ? undefined : `Last seen ${formatNetworkClock(lastSeen)}`, + }; +} + +export function buildNetworkNodeGroups( + local: WorkflowLocalNetworkNodeStatus, + peers: WorkflowPeerNetworkNodeStatus[], +): NetworkNodeGroups { + return { + local: buildLocalNodeEntry(local), + peers: peers.map(buildPeerNodeEntry), + }; +} + +/** The requested node when it is still listed, otherwise the local node. */ +export function resolveSelectedNodeId(groups: NetworkNodeGroups, requestedId: string | null): string { + if (requestedId && groups.peers.some((peer) => peer.nodeId === requestedId)) { + return requestedId; + } + return groups.local.nodeId; +} + +// --------------------------------------------------------------------------- +// Dimension line + +type TransportClass = 'connected' | 'degraded' | 'pairing' | 'unreachable'; + +function classifyTransport(state: WorkflowNetworkTransportState, isLocal: boolean): TransportClass { + switch (state) { + case 'connected': + case 'local_only': + return 'connected'; + case 'degraded': + return 'degraded'; + case 'pairing_required': + return 'pairing'; + case 'peer_networking_unavailable': + // The local node answered this query, so it is reachable even without peers. + return isLocal ? 'connected' : 'unreachable'; + } +} + +/** + * "N nodes, c connected, d degraded, p waiting to be paired." GPU count and + * VRAM are not in the projection, so that part of the line is omitted. + */ +export function buildNetworkDimensionLine( + local: WorkflowLocalNetworkNodeStatus | null, + peers: WorkflowPeerNetworkNodeStatus[], + loading: boolean, +): string { + if (!local) { + return loading ? 'Reading local status' : 'Local status unavailable'; + } + const counts: Record = { connected: 0, degraded: 0, pairing: 0, unreachable: 0 }; + counts[classifyTransport(local.transport_state, true)] += 1; + for (const peer of peers) { + counts[classifyTransport(peer.transport_state, false)] += 1; + } + const parts = [plural(1 + peers.length, 'node'), `${counts.connected} connected`]; + if (counts.degraded > 0) parts.push(`${counts.degraded} degraded`); + if (counts.pairing > 0) parts.push(`${counts.pairing} waiting to be paired`); + if (counts.unreachable > 0) parts.push(`${counts.unreachable} without peer networking`); + return `${parts.join(', ')}.`; +} + +// --------------------------------------------------------------------------- +// Degraded metrics, routed to the section they affect + +export type NetworkMetricSection = 'cpu' | 'memory' | 'devices' | 'disks' | 'interfaces' | 'node'; + +export type NetworkDegradations = Record; + +const DEGRADATION_ROUTES: Array<[RegExp, NetworkMetricSection]> = [ + [/\b(gpu|cuda|vram|rocm|metal|device)/i, 'devices'], + [/\b(peer|transport|pairing)/i, 'node'], + [/\bcpu/i, 'cpu'], + [/\b(memory|ram|swap)\b/i, 'memory'], + [/\b(disk|mount|storage|volume)/i, 'disks'], + [/\b(network|interface|nic)/i, 'interfaces'], +]; + +/** + * Routes the projection's free-text degradation warnings to the section whose + * numbers they qualify. Unmatched warnings belong to the node as a whole. The + * GPU reason is already shown in Devices, so a warning repeating it is dropped. + */ +export function groupDegradationWarnings(node: WorkflowLocalNetworkNodeStatus): NetworkDegradations { + const groups: NetworkDegradations = { cpu: [], memory: [], devices: [], disks: [], interfaces: [], node: [] }; + const gpuReason = node.system.gpu.reason?.trim() ?? ''; + for (const raw of node.degradation_warnings) { + const warning = raw.trim(); + if (warning.length === 0 || warning === gpuReason) continue; + const section = DEGRADATION_ROUTES.find(([pattern]) => pattern.test(warning))?.[1] ?? 'node'; + if (!groups[section].includes(warning)) groups[section].push(warning); + } + return groups; +} + +// --------------------------------------------------------------------------- +// Local node detail + +export interface NetworkNodeHeader { + title: string; + nodeId: string; + subtitle: string; + glyph: GlyphState; + transportLabel: string; + chips: string[]; +} + +export function buildLocalNodeHeader( + node: WorkflowLocalNetworkNodeStatus, + peerCount: number, +): NetworkNodeHeader { + const chips = [ + plural(node.system.cpu.logical_core_count, 'core'), + node.system.gpu.available ? 'GPU available' : 'No GPU reported', + ]; + if (node.transport_state !== 'local_only') { + chips.push(plural(peerCount, 'peer')); + } + return { + title: node.display_name, + nodeId: node.node_id, + subtitle: `${formatOsLabel(node)}, captured ${formatNetworkClock(node.captured_at_ms)}`, + glyph: LOCAL_NODE_GLYPH, + transportLabel: formatTransportState(node.transport_state), + chips, + }; +} + +export interface NetworkStatCell { + id: 'cpu' | 'memory' | 'scheduler' | 'sessions'; + value: string; + label: string; + /** 0–100 when a meter is meaningful, null when the share is not reported. */ + meterPercent: number | null; +} + +function clampPercent(value: number): number { + if (!Number.isFinite(value)) return 0; + return Math.min(100, Math.max(0, value)); } -export function formatSessionLoad(node: WorkflowLocalNetworkNodeStatus): string { +export function buildLocalStatCells(node: WorkflowLocalNetworkNodeStatus): NetworkStatCell[] { + const cpu = node.system.cpu; + const memory = node.system.memory; const load = node.scheduler_load; - return `${load.active_session_count}/${load.max_sessions} sessions, ${load.loaded_session_count}/${load.max_loaded_sessions} loaded`; + const usage = cpu.average_usage_percent ?? null; + const cores = plural(cpu.logical_core_count, 'core'); + return [ + { + id: 'cpu', + value: usage === null ? 'Not reported' : `${Math.round(usage)}%`, + label: usage === null ? `${cores}, usage not reported` : `${cores}`, + meterPercent: usage === null ? null : clampPercent(usage), + }, + { + id: 'memory', + value: formatNetworkBytes(memory.used_bytes), + label: `of ${formatNetworkBytes(memory.total_bytes)} memory in use`, + meterPercent: memory.total_bytes > 0 ? clampPercent((memory.used_bytes / memory.total_bytes) * 100) : null, + }, + { + id: 'scheduler', + value: `${load.active_run_count} / ${load.queued_run_count}`, + label: 'running / queued here', + meterPercent: null, + }, + { + id: 'sessions', + value: `${load.loaded_session_count} of ${load.max_loaded_sessions}`, + label: `runtime sessions loaded, ${load.active_session_count} of ${load.max_sessions} active`, + meterPercent: null, + }, + ]; +} + +/** Shown under the GPU facts until the projection reports per-device memory (WR-006). */ +export const DEVICE_MEMORY_NOT_REPORTED = + 'Per-device memory is not reported by this engine build.'; + +export function buildLocalDeviceRows(node: WorkflowLocalNetworkNodeStatus): KeyValueRow[] { + const gpu = node.system.gpu; + const rows: KeyValueRow[] = [{ key: 'GPU', value: gpu.available ? 'Available' : 'Not available' }]; + const reason = gpu.reason?.trim(); + if (reason) { + rows.push({ key: 'Reason', value: reason }); + } + return rows; +} + +export interface NetworkDiskRow { + key: string; + mount: string; + name: string; + free: string; + total: string; +} + +export function buildLocalDiskRows(node: WorkflowLocalNetworkNodeStatus): NetworkDiskRow[] { + return node.system.disks.map((disk) => ({ + key: `${disk.name}\u{1f}${disk.mount_point}`, + mount: disk.mount_point, + name: disk.name, + free: formatNetworkBytes(disk.available_bytes), + total: formatNetworkBytes(disk.total_bytes), + })); +} + +export interface NetworkInterfaceRow { + name: string; + received: string; + sent: string; +} + +export function buildLocalInterfaceRows(node: WorkflowLocalNetworkNodeStatus): NetworkInterfaceRow[] { + return node.system.network_interfaces.map((networkInterface) => ({ + name: networkInterface.name, + received: formatNetworkBytes(networkInterface.total_received_bytes), + sent: formatNetworkBytes(networkInterface.total_transmitted_bytes), + })); +} + +export function buildLocalIdentityRows(node: WorkflowLocalNetworkNodeStatus): KeyValueRow[] { + return [ + { key: 'Node id', value: node.node_id, mono: true }, + { key: 'Hostname', value: node.system.hostname ?? 'Not reported', mono: Boolean(node.system.hostname) }, + { key: 'OS', value: formatOsLabel(node) }, + { key: 'Kernel', value: node.system.kernel_version ?? 'Not reported' }, + ]; +} + +// --------------------------------------------------------------------------- +// Peer detail + +export interface NetworkPeerDetail { + header: NetworkNodeHeader; + /** Why the metric sections are absent for this peer. */ + note: string; + identityRows: KeyValueRow[]; +} + +export function buildPeerDetail(peer: WorkflowPeerNetworkNodeStatus): NetworkPeerDetail { + const lastSeen = peer.last_seen_at_ms ?? null; + const lastSeenText = lastSeen === null ? 'Not seen yet' : formatNetworkClock(lastSeen); + const pairing = peer.transport_state === 'pairing_required'; + return { + header: { + title: peer.display_name, + nodeId: peer.node_id, + subtitle: lastSeen === null ? 'Not seen yet' : `Last seen ${lastSeenText}`, + glyph: glyphStateForTransport(peer.transport_state), + transportLabel: formatTransportState(peer.transport_state), + chips: [], + }, + note: pairing + ? 'This node was found on the network but is not trusted yet. Its details stay hidden until it is paired, and pairing is not available in this build.' + : 'This engine build reports only the transport state and last-seen time of peers. CPU, memory, devices, disks and interfaces appear here once peer metrics are reported.', + identityRows: [ + { key: 'Node id', value: peer.node_id, mono: true }, + { key: 'Transport', value: formatTransportState(peer.transport_state) }, + { key: 'Last seen', value: lastSeenText, mono: lastSeen !== null }, + ], + }; +} + +// --------------------------------------------------------------------------- +// Selected run + +export interface NetworkSelectedRunRef { + workflow_run_id: string; + workflow_id?: string | null; +} + +export function findSelectedRunPlacement( + node: WorkflowLocalNetworkNodeStatus, + workflowRunId: string | null | undefined, +): WorkflowLocalRunPlacementRecord | null { + if (!workflowRunId) { + return null; + } + return node.scheduler_load.run_placements.find((placement) => placement.workflow_run_id === workflowRunId) ?? null; } export function formatSelectedRunLocalState( @@ -123,17 +480,7 @@ export function formatSelectedRunLocalState( if (node.scheduler_load.queued_workflow_run_ids.includes(workflowRunId)) { return 'Queued locally'; } - return 'Not scheduled locally'; -} - -export function findSelectedRunPlacement( - node: WorkflowLocalNetworkNodeStatus, - workflowRunId: string | null | undefined, -): WorkflowLocalRunPlacementRecord | null { - if (!workflowRunId) { - return null; - } - return node.scheduler_load.run_placements.find((placement) => placement.workflow_run_id === workflowRunId) ?? null; + return 'Not running or queued here'; } export function formatSelectedRunRuntimePosture(placement: WorkflowLocalRunPlacementRecord | null): string { @@ -143,53 +490,6 @@ export function formatSelectedRunRuntimePosture(placement: WorkflowLocalRunPlace return placement.runtime_loaded ? 'Runtime session loaded' : 'Runtime session not loaded'; } -export function formatSelectedRunPlacementState(placement: WorkflowLocalRunPlacementRecord | null): string { - if (!placement) { - return 'Unavailable'; - } - switch (placement.state) { - case 'running': - return 'Running locally'; - case 'queued': - return 'Queued locally'; - } -} - -export function formatSelectedRunRequirementList(values: string[], emptyLabel: string): string { - return values.length > 0 ? values.join(', ') : emptyLabel; -} - -export function buildSelectedRunPlacementRows( - placement: WorkflowLocalRunPlacementRecord | null, -): NetworkSelectedRunPlacementRow[] { - if (!placement) { - return [ - { label: 'State', value: 'Not scheduled locally' }, - { label: 'Session', value: 'Unavailable', mono: true }, - { label: 'Workflow', value: 'Unavailable', mono: true }, - { label: 'Runtime', value: 'Unavailable' }, - { label: 'Model Cache', value: 'Unavailable' }, - { label: 'Backends', value: 'No backend requirements' }, - { label: 'Models', value: 'No model requirements' }, - ]; - } - return [ - { label: 'State', value: formatSelectedRunPlacementState(placement) }, - { label: 'Session', value: placement.workflow_execution_session_id, mono: true }, - { label: 'Workflow', value: placement.workflow_id, mono: true }, - { label: 'Runtime', value: formatSelectedRunRuntimePosture(placement) }, - { label: 'Model Cache', value: formatSelectedRunModelCacheState(placement.model_cache_state) }, - { - label: 'Backends', - value: formatSelectedRunRequirementList(placement.required_backends, 'No backend requirements'), - }, - { - label: 'Models', - value: formatSelectedRunRequirementList(placement.required_models, 'No model requirements'), - }, - ]; -} - export function formatSelectedRunModelCacheState(state: WorkflowSchedulerModelCacheState): string { switch (state) { case 'unknown': @@ -213,17 +513,115 @@ export function formatSelectedRunModelCacheState(state: WorkflowSchedulerModelCa } } -export function buildSelectedRunResourceRows( - assets: LibraryUsageProjectionRecord[], -): NetworkSelectedRunResourceRow[] { - return assets.map((asset) => ({ - assetId: asset.asset_id, - category: formatLibraryAssetCategory(asset.asset_id), - cacheStatus: formatSelectedRunResourceCacheStatus(asset.last_cache_status), - cacheClass: selectedRunResourceCacheClass(asset.last_cache_status), - networkBytes: formatLibraryBytes(asset.total_network_bytes), - accessCount: String(asset.run_access_count), - })); +export function formatSelectedRunRequirementList(values: string[], emptyLabel: string): string { + return values.length > 0 ? values.join(', ') : emptyLabel; +} + +export function selectedRunWorkflowLabel( + run: NetworkSelectedRunRef, + placement: WorkflowLocalRunPlacementRecord | null, +): string { + const workflowId = run.workflow_id?.trim() || placement?.workflow_id?.trim(); + return workflowId && workflowId.length > 0 ? workflowId : 'Selected run'; +} + +export interface NetworkSelectedRunOnNode { + /** " on this node". */ + heading: string; + runId: string; + state: string; + placed: boolean; + /** Placement facts after the run id and state; empty when not placed here. */ + rows: KeyValueRow[]; + /** Sentence shown when the run is not running or queued on this node. */ + note: string | null; +} + +/** + * The selected run's placement on the local node. The local status lists + * only running and queued runs, so a finished run is reported as "not running + * or queued here" rather than guessed. + */ +export function buildSelectedRunOnLocalNode( + node: WorkflowLocalNetworkNodeStatus, + run: NetworkSelectedRunRef, +): NetworkSelectedRunOnNode { + const placement = findSelectedRunPlacement(node, run.workflow_run_id); + const workflow = selectedRunWorkflowLabel(run, placement); + const state = formatSelectedRunLocalState(node, run.workflow_run_id); + if (!placement) { + return { + heading: `${workflow} on this node`, + runId: run.workflow_run_id, + state, + placed: false, + rows: [], + note: + state === 'Not running or queued here' + ? 'The local status lists only runs that are running or queued, so this run has no placement here right now. Its execution and resources below come from the run projections.' + : 'The scheduler lists this run here, but its placement record is not in the local status yet.', + }; + } + return { + heading: `${workflow} on this node`, + runId: run.workflow_run_id, + state, + placed: true, + rows: [ + { key: 'Runtime session', value: `${formatSelectedRunRuntimePosture(placement)}, ${formatSelectedRunModelCacheState(placement.model_cache_state).toLowerCase()}` }, + { key: 'Session id', value: placement.workflow_execution_session_id, mono: true }, + { key: 'Backends', value: formatSelectedRunRequirementList(placement.required_backends, 'No backend requirements') }, + { key: 'Models', value: formatSelectedRunRequirementList(placement.required_models, 'No model requirements') }, + ], + note: null, + }; +} + +export interface NetworkSelectedRunOnPeer { + heading: string; + sentence: string; +} + +/** The selected run while a peer is open: placement on peers is not reported. */ +export function describeSelectedRunForPeer( + local: WorkflowLocalNetworkNodeStatus, + run: NetworkSelectedRunRef, + peerName: string, +): NetworkSelectedRunOnPeer { + const placement = findSelectedRunPlacement(local, run.workflow_run_id); + const workflow = selectedRunWorkflowLabel(run, placement); + if (placement) { + const verb = placement.state === 'running' ? 'running' : 'queued'; + return { heading: workflow, sentence: `${workflow} is ${verb} on ${local.display_name}, not on ${peerName}.` }; + } + return { + heading: workflow, + sentence: `This engine build does not report run placement on peers, so it cannot say whether ${workflow} used ${peerName}.`, + }; +} + +export interface NetworkSelectedRunExecutionRow { + nodeId: string; + status: string; + glyph: GlyphState; + runtime: string; + model: string; +} + +export function formatSelectedRunNodeStatus(value: NodeStatusProjectionRecord['status']): string { + const text = value.replaceAll('_', ' '); + return text.charAt(0).toUpperCase() + text.slice(1); +} + +function formatSelectedRunVersionedLabel( + id: string | null | undefined, + version: string | null | undefined, + fallback: string, +): string { + if (!id || id.trim().length === 0) { + return fallback; + } + return version && version.trim().length > 0 ? `${id}@${version}` : id; } export function buildSelectedRunExecutionRows( @@ -232,93 +630,93 @@ export function buildSelectedRunExecutionRows( return nodes.map((node) => ({ nodeId: node.node_id, status: formatSelectedRunNodeStatus(node.status), - statusClass: selectedRunNodeStatusClass(node.status), + glyph: glyphStateForStatus(node.status), runtime: formatSelectedRunVersionedLabel(node.runtime_id, node.runtime_version, 'Runtime unavailable'), model: formatSelectedRunVersionedLabel(node.model_id, node.model_version, 'Model unavailable'), })); } -export function selectedRunResourceCacheClass(value: string | null | undefined): string { - if (value === 'cache_hit' || value === 'loaded') { - return 'border-emerald-800 bg-emerald-950/50 text-emerald-200'; - } - if (value === 'cache_miss' || value === 'load_requested') { - return 'border-amber-800 bg-amber-950/50 text-amber-200'; - } - if (value === 'failed') { - return 'border-red-800 bg-red-950/50 text-red-200'; - } - return 'border-neutral-800 bg-neutral-950 text-neutral-400'; +export interface NetworkSelectedRunResourceRow { + assetId: string; + category: string; + cacheStatus: string; + networkBytes: string; + accessCount: string; } export function formatSelectedRunResourceCacheStatus(value: string | null | undefined): string { if (!value || value.trim().length === 0) { - return 'Cache status unavailable'; + return 'Not reported'; } - return value - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); + const text = value.trim().replaceAll('_', ' '); + return text.charAt(0).toUpperCase() + text.slice(1); } -export function formatSelectedRunNodeStatus(value: NodeStatusProjectionRecord['status']): string { - return value - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); -} - -export function selectedRunNodeStatusClass(value: NodeStatusProjectionRecord['status']): string { - switch (value) { - case 'queued': - return 'border-amber-800 bg-amber-950/50 text-amber-200'; - case 'completed': - return 'border-emerald-800 bg-emerald-950/50 text-emerald-200'; - case 'running': - return 'border-cyan-800 bg-cyan-950/50 text-cyan-200'; - case 'waiting': - return 'border-amber-800 bg-amber-950/50 text-amber-200'; - case 'failed': - return 'border-red-800 bg-red-950/50 text-red-200'; - case 'cancelled': - return 'border-neutral-700 bg-neutral-900 text-neutral-300'; +export function buildSelectedRunResourceRows( + assets: LibraryUsageProjectionRecord[], +): NetworkSelectedRunResourceRow[] { + return assets.map((asset) => ({ + assetId: asset.asset_id, + category: formatLibraryAssetCategory(asset.asset_id), + cacheStatus: formatSelectedRunResourceCacheStatus(asset.last_cache_status), + networkBytes: formatLibraryBytes(asset.total_network_bytes), + accessCount: String(asset.run_access_count), + })); +} + +export interface NetworkEventLine { + id: string; + time: string; + level: LogLevel; + kind: string; + message: string; + source: string; +} + +export function logLevelForTimelineEvent( + severity: SchedulerTimelineProjectionRecord['error_severity'], +): LogLevel { + switch (severity) { + case 'warning': + return 'warn'; + case 'error': + case 'fatal': + return 'error'; + default: + return 'info'; } } -export function buildNetworkFactRows(node: WorkflowLocalNetworkNodeStatus): NetworkFactRow[] { - const memory = node.system.memory; - return [ - { label: 'Node ID', value: node.node_id }, - { label: 'Hostname', value: node.system.hostname ?? 'Unavailable' }, - { label: 'OS', value: formatOsLabel(node) }, - { label: 'Kernel', value: node.system.kernel_version ?? 'Unavailable' }, - { label: 'CPU', value: `${node.system.cpu.logical_core_count} logical cores` }, - { - label: 'Memory', - value: `${formatNetworkBytes(memory.used_bytes)} used / ${formatNetworkBytes(memory.total_bytes)} total`, - }, - { label: 'GPU', value: formatGpuAvailability(node) }, - { label: 'Disks', value: String(node.system.disks.length) }, - { label: 'Network Interfaces', value: String(node.system.network_interfaces.length) }, - ]; +export function buildSelectedRunEventLines(events: SchedulerTimelineProjectionRecord[]): NetworkEventLine[] { + return events.map((event) => ({ + id: event.event_id, + time: formatNetworkClock(event.occurred_at_ms, { millis: true }), + level: logLevelForTimelineEvent(event.error_severity), + kind: event.event_kind, + message: event.detail ? `${event.summary}. ${event.detail}` : event.summary, + source: event.source_component, + })); } -function formatSelectedRunVersionedLabel( - id: string | null | undefined, - version: string | null | undefined, - fallback: string, +// --------------------------------------------------------------------------- +// Query failures, as sentences for the panel they affect + +function asSentence(text: string): string { + const trimmed = text.trim(); + return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`; +} + +export function describeLocalStatusFailure( + errorText: string, + lastCapturedAtMs: number | null, ): string { - if (!id || id.trim().length === 0) { - return fallback; + if (lastCapturedAtMs === null) { + return `Pantograph could not read the local status. ${asSentence(errorText)}`; } - return version && version.trim().length > 0 ? `${id}@${version}` : id; + return `The last refresh failed, so this is the status captured at ${formatNetworkClock(lastCapturedAtMs)}. ${asSentence(errorText)}`; } -function formatOsLabel(node: WorkflowLocalNetworkNodeStatus): string { - const name = node.system.os_name; - const version = node.system.os_version; - if (name && version) { - return `${name} ${version}`; - } - return name ?? 'Unavailable'; +/** Sentence for a failed selected-run projection query, shown in its section. */ +export function describeRunProjectionFailure(what: string, errorText: string): string { + return `Could not read ${what}. ${asSentence(errorText)}`; } diff --git a/src/components/workbench/nodeLabPresenters.test.ts b/src/components/workbench/nodeLabPresenters.test.ts index a83fd6967..668b160da 100644 --- a/src/components/workbench/nodeLabPresenters.test.ts +++ b/src/components/workbench/nodeLabPresenters.test.ts @@ -1,16 +1,203 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import type { NodeDefinition, PortDefinition } from '../../services/workflow/types.ts'; import { - buildNodeLabStatusRows, - nodeLabUnavailableMessage, + NODE_LAB_IMPLEMENTATION_TEXT, + NODE_LAB_UNAVAILABLE_FACILITIES, + buildNodeLabList, + formatNodeLabDefault, + nodeLabAuthoringNotice, + nodeLabDisabledReason, + nodeLabSummaryLine, + projectNodeLabDefinition, + resolveNodeLabSelection, + sortNodeLabDefinitions, + type NodeLabAuthoringControl, } from './nodeLabPresenters.ts'; -test('node lab presenters expose a disabled state without authoring affordances', () => { - assert.equal(nodeLabUnavailableMessage(), 'Node authoring is unavailable in this build'); - assert.deepEqual(buildNodeLabStatusRows(), [ - { label: 'Authoring API', value: 'Unavailable' }, - { label: 'Local Agent', value: 'Unavailable' }, - { label: 'Runtime Publishing', value: 'Unavailable' }, +function port(id: string, data_type: PortDefinition['data_type'], extra: Partial = {}): PortDefinition { + return { id, label: id, data_type, required: false, multiple: false, ...extra }; +} + +function definition(node_type: string, extra: Partial = {}): NodeDefinition { + return { + node_type, + category: 'processing', + label: node_type, + description: '', + io_binding_origin: 'integrated', + inputs: [], + outputs: [], + execution_mode: 'reactive', + ...extra, + }; +} + +const llm = definition('llm-inference', { + label: 'LLM Inference', + description: ' Generates text with a local model. ', + inputs: [ + port('prompt', 'prompt', { label: 'Prompt', required: true }), + port('temperature', 'number', { label: 'Temperature', default_value: 0.7 }), + port('tools', 'tools', { label: 'Tools', multiple: true, description: ' Tool definitions ' }), + ], + outputs: [port('response', 'string', { label: 'Response' }), port('stream', 'stream', { label: '' })], + execution_mode: 'stream', +}); +const textInput = definition('text-input', { + category: 'input', + label: 'Text Input', + io_binding_origin: 'client_session', + outputs: [port('text', 'string', { label: 'Text' })], +}); +const textOutput = definition('text-output', { category: 'output', label: 'Text Output' }); +const embedding = definition('embedding', { label: 'Embedding', description: 'Embeds text into vectors' }); +const custom = definition('mystery', { category: 'experimental' as NodeDefinition['category'], label: 'Aardvark' }); + +const all = [textOutput, custom, llm, embedding, textInput]; + +test('the notice names the three unavailable facilities and Settings', () => { + assert.deepEqual([...NODE_LAB_UNAVAILABLE_FACILITIES], ['Authoring API', 'Local Agent', 'Runtime Publishing']); + const notice = nodeLabAuthoringNotice(); + assert.equal(notice.headline, 'Node authoring is not available in this build.'); + for (const facility of NODE_LAB_UNAVAILABLE_FACILITIES) { + assert.ok(notice.sentence.includes(facility), `notice names ${facility}`); + } + assert.ok(notice.sentence.includes('Settings')); +}); + +test('every authoring control has a non-empty reason naming why it is off', () => { + const controls: NodeLabAuthoringControl[] = [ + 'new_node', + 'save_draft', + 'publish', + 'try', + 'edit_field', + 'add_port', + 'remove_port', + ]; + for (const control of controls) { + assert.match(nodeLabDisabledReason(control), /this build (does not include|has no Authoring API)/); + } + assert.match(nodeLabDisabledReason('publish'), /Runtime Publishing/); + assert.match(nodeLabDisabledReason('try'), /Local Agent/); +}); + +test('definitions sort in palette category order, unknown categories last, then by label', () => { + const before = all.map((d) => d.node_type); + assert.deepEqual( + sortNodeLabDefinitions(all).map((d) => d.node_type), + ['text-input', 'embedding', 'llm-inference', 'text-output', 'mystery'], + ); + assert.deepEqual(all.map((d) => d.node_type), before, 'input order is untouched'); +}); + +test('the list has one Built-in group with category and port counts', () => { + const list = buildNodeLabList(all, ''); + assert.equal(list.total, 5); + assert.equal(list.matched, 5); + assert.equal(list.emptyText, null); + assert.deepEqual(list.groups.map((g) => g.label), ['Built-in']); + assert.deepEqual(list.groups[0].rows[0], { + nodeType: 'text-input', + label: 'Text Input', + categoryLabel: 'Input', + context: ', 0 inputs, 1 output', + }); + assert.equal(list.groups[0].rows[2].context, ', 3 inputs, 2 outputs'); + assert.equal(list.groups[0].rows[4].categoryLabel, 'Experimental'); +}); + +test('search matches label, type id, category and description, ignoring case and spaces', () => { + assert.deepEqual(buildNodeLabList(all, ' TEXT ').groups[0].rows.map((r) => r.nodeType), [ + 'text-input', + 'embedding', + 'llm-inference', + 'text-output', + ]); + assert.deepEqual(buildNodeLabList(all, 'llm-inf').groups[0].rows.map((r) => r.nodeType), ['llm-inference']); + assert.deepEqual(buildNodeLabList(all, 'output').groups[0].rows.map((r) => r.nodeType), ['text-output']); + const none = buildNodeLabList(all, 'zebra '); + assert.equal(none.matched, 0); + assert.deepEqual(none.groups, []); + assert.equal(none.emptyText, 'No built-in node matches “zebra”.'); +}); + +test('an empty registry yields an empty list sentence and summary, not fabricated rows', () => { + const list = buildNodeLabList([], ''); + assert.deepEqual(list.groups, []); + assert.equal(list.emptyText, 'No built-in node definitions are loaded.'); + assert.equal(nodeLabSummaryLine([]), 'No node definitions loaded'); + assert.equal(resolveNodeLabSelection([], 'llm-inference'), null); +}); + +test('summary counts nodes and categories', () => { + assert.equal(nodeLabSummaryLine(all), '5 built-in nodes in 4 categories, read-only'); + assert.equal(nodeLabSummaryLine([llm]), '1 built-in node in 1 category, read-only'); +}); + +test('selection keeps a reported type and falls back to the first row when it disappears', () => { + assert.equal(resolveNodeLabSelection(all, 'llm-inference'), llm); + assert.equal(resolveNodeLabSelection(all, null), textInput); + assert.equal(resolveNodeLabSelection(all, 'removed-type'), textInput); + // A search that hides the selected row does not change the detail. + assert.equal(buildNodeLabList(all, 'output').matched, 1); + assert.equal(resolveNodeLabSelection(all, 'llm-inference'), llm); +}); + +test('a definition projects to read-only form rows without invented fields', () => { + const view = projectNodeLabDefinition(llm); + assert.equal(view.nodeType, 'llm-inference'); + assert.equal(view.label, 'LLM Inference'); + assert.equal(view.categoryLabel, 'Processing'); + assert.equal(view.description, 'Generates text with a local model.'); + assert.equal(view.executionModeLabel, 'Stream'); + assert.equal(view.ioBindingLabel, 'Integrated'); + assert.equal(view.implementationText, NODE_LAB_IMPLEMENTATION_TEXT); + assert.equal(view.implementationText, 'built-in, source not editable'); + assert.deepEqual(view.checks, [{ glyph: 'succeeded', text: 'Built-in node, always valid' }]); + assert.deepEqual(view.inputs, [ + { id: 'prompt', label: 'Prompt', idNote: null, dataType: 'prompt', defaultText: '', requirement: 'required', description: null }, + { id: 'temperature', label: 'Temperature', idNote: null, dataType: 'number', defaultText: '0.7', requirement: 'optional', description: null }, + { id: 'tools', label: 'Tools', idNote: null, dataType: 'tools', defaultText: '', requirement: 'optional, accepts many', description: 'Tool definitions' }, ]); + assert.deepEqual(view.outputs.map((p) => [p.id, p.label, p.dataType]), [ + ['response', 'Response', 'string'], + ['stream', 'stream', 'stream'], + ]); + for (const key of ['version', 'runtime', 'device', 'retention']) { + assert.ok(!(key in view), `${key} is not projected`); + } + assert.equal(projectNodeLabDefinition(textInput).ioBindingLabel, 'Client session'); +}); + +test('the port id is noted only when it reads differently from the label', () => { + const view = projectNodeLabDefinition( + definition('ports', { + inputs: [ + port('system_prompt', 'string', { label: 'System Prompt' }), + port('kv-cache', 'kv_cache', { label: 'KV Cache' }), + port('pumas_model_ref', 'json', { label: 'Model' }), + ], + }), + ); + assert.deepEqual(view.inputs.map((p) => p.idNote), [null, null, 'pumas_model_ref']); +}); + +test('a definition missing port arrays projects as having no ports', () => { + const partial = { ...embedding, inputs: undefined, outputs: undefined } as unknown as NodeDefinition; + const view = projectNodeLabDefinition(partial); + assert.deepEqual(view.inputs, []); + assert.deepEqual(view.outputs, []); + assert.equal(buildNodeLabList([partial], '').groups[0].rows[0].context, ', 0 inputs, 0 outputs'); +}); + +test('defaults render as text, with structured values as JSON', () => { + assert.equal(formatNodeLabDefault(undefined), ''); + assert.equal(formatNodeLabDefault(null), ''); + assert.equal(formatNodeLabDefault('hello'), 'hello'); + assert.equal(formatNodeLabDefault(false), 'false'); + assert.equal(formatNodeLabDefault(8), '8'); + assert.equal(formatNodeLabDefault({ k: [1, 2] }), '{"k":[1,2]}'); }); diff --git a/src/components/workbench/nodeLabPresenters.ts b/src/components/workbench/nodeLabPresenters.ts index 530bb2dd5..463df157d 100644 --- a/src/components/workbench/nodeLabPresenters.ts +++ b/src/components/workbench/nodeLabPresenters.ts @@ -1,16 +1,301 @@ -export interface NodeLabStatusRow { +/** + * Node Editor projection (docs/design/workbench-redesign-spec.md, "Node Editor"). + * + * Node authoring has no backend in this build. The page reads the built-in node + * definitions the engine already reports (the `nodeDefinitions` store the Graph + * palette lists) and shows them read-only. Everything the mockup shows that the + * definitions do not carry (version, runtime, device, output retention) is + * omitted rather than invented. + */ +import type { + ExecutionMode, + IoBindingOrigin, + NodeCategory, + NodeDefinition, + PortDefinition, +} from '../../services/workflow/types'; + +/** The authoring facilities this build does not include. */ +export const NODE_LAB_UNAVAILABLE_FACILITIES = [ + 'Authoring API', + 'Local Agent', + 'Runtime Publishing', +] as const; + +export type NodeLabFacility = (typeof NODE_LAB_UNAVAILABLE_FACILITIES)[number]; + +export interface NodeLabNotice { + headline: string; + sentence: string; +} + +export function nodeLabAuthoringNotice(): NodeLabNotice { + return { + headline: 'Node authoring is not available in this build.', + sentence: + 'You can read the built-in node definitions, but the Authoring API, the Local Agent and ' + + 'Runtime Publishing are not included, so creating, saving, publishing and trying nodes ' + + 'are off. They would be enabled in Settings; this build has no setting for them yet.', + }; +} + +/** Every authoring control the board shows, each disabled with its own reason. */ +export type NodeLabAuthoringControl = + | 'new_node' + | 'save_draft' + | 'publish' + | 'try' + | 'edit_field' + | 'add_port' + | 'remove_port'; + +const DISABLED_REASON: Record = { + new_node: 'Creating nodes needs the Authoring API, which this build does not include.', + save_draft: 'Saving drafts needs the Authoring API, which this build does not include.', + publish: + 'Publishing needs Runtime Publishing, which this build does not include. Built-in nodes are already available in Graph.', + try: 'Trying a node outside a workflow needs the Local Agent, which this build does not include.', + edit_field: 'Built-in nodes are read-only, and this build has no Authoring API to edit definitions.', + add_port: 'Built-in nodes are read-only, and this build has no Authoring API to add ports.', + remove_port: 'Built-in nodes are read-only, and this build has no Authoring API to remove ports.', +}; + +export function nodeLabDisabledReason(control: NodeLabAuthoringControl): string { + return DISABLED_REASON[control]; +} + +/** Palette order (NodeCategory); categories the frontend does not know sort last. */ +export const NODE_LAB_CATEGORIES: readonly NodeCategory[] = [ + 'input', + 'processing', + 'tool', + 'output', + 'control', +]; + +export function nodeLabCategoryLabel(category: string): string { + return category.length === 0 ? 'Uncategorised' : category.charAt(0).toUpperCase() + category.slice(1); +} + +const EXECUTION_MODE_LABEL: Record = { + reactive: 'Reactive', + manual: 'Manual', + stream: 'Stream', +}; + +const IO_BINDING_LABEL: Record = { + client_session: 'Client session', + integrated: 'Integrated', +}; + +export const NODE_LAB_EXECUTION_MODES = Object.keys(EXECUTION_MODE_LABEL) as ExecutionMode[]; +export const NODE_LAB_IO_BINDINGS = Object.keys(IO_BINDING_LABEL) as IoBindingOrigin[]; + +export function nodeLabExecutionModeLabel(mode: string): string { + return EXECUTION_MODE_LABEL[mode as ExecutionMode] ?? mode; +} + +export function nodeLabIoBindingLabel(origin: string): string { + return IO_BINDING_LABEL[origin as IoBindingOrigin] ?? origin; +} + +export const NODE_LAB_IMPLEMENTATION_TEXT = 'built-in, source not editable'; + +function categoryRank(category: string): number { + const index = NODE_LAB_CATEGORIES.indexOf(category as NodeCategory); + return index === -1 ? NODE_LAB_CATEGORIES.length : index; +} + +/** Definitions in palette category order, then by label. Does not mutate the input. */ +export function sortNodeLabDefinitions(definitions: readonly NodeDefinition[]): NodeDefinition[] { + return [...definitions].sort( + (a, b) => + categoryRank(a.category) - categoryRank(b.category) || + a.category.localeCompare(b.category) || + a.label.localeCompare(b.label) || + a.node_type.localeCompare(b.node_type), + ); +} + +function portsOf(ports: readonly PortDefinition[] | undefined): readonly PortDefinition[] { + return Array.isArray(ports) ? ports : []; +} + +function countText(count: number, one: string, many: string): string { + return `${count} ${count === 1 ? one : many}`; +} + +export interface NodeLabListRow { + nodeType: string; label: string; - value: string; + categoryLabel: string; + /** Text after the category, for example ", 3 inputs, 2 outputs". */ + context: string; +} + +export interface NodeLabListGroup { + id: 'built_in'; + label: string; + rows: NodeLabListRow[]; +} + +export interface NodeLabList { + total: number; + matched: number; + /** One "Built-in" group; "Your nodes" waits for a definition store. */ + groups: NodeLabListGroup[]; + /** Muted sentence when the list is empty, otherwise null. */ + emptyText: string | null; } -export function buildNodeLabStatusRows(): NodeLabStatusRow[] { - return [ - { label: 'Authoring API', value: 'Unavailable' }, - { label: 'Local Agent', value: 'Unavailable' }, - { label: 'Runtime Publishing', value: 'Unavailable' }, - ]; +function matchesQuery(definition: NodeDefinition, query: string): boolean { + if (query.length === 0) { + return true; + } + return [definition.label, definition.node_type, definition.category, definition.description] + .some((value) => typeof value === 'string' && value.toLowerCase().includes(query)); +} + +export function buildNodeLabList(definitions: readonly NodeDefinition[], query: string): NodeLabList { + const normalized = query.trim().toLowerCase(); + const sorted = sortNodeLabDefinitions(definitions); + const rows = sorted + .filter((definition) => matchesQuery(definition, normalized)) + .map((definition) => ({ + nodeType: definition.node_type, + label: definition.label, + categoryLabel: nodeLabCategoryLabel(definition.category), + context: `, ${countText(portsOf(definition.inputs).length, 'input', 'inputs')}, ${countText( + portsOf(definition.outputs).length, + 'output', + 'outputs', + )}`, + })); + let emptyText: string | null = null; + if (definitions.length === 0) { + emptyText = 'No built-in node definitions are loaded.'; + } else if (rows.length === 0) { + emptyText = `No built-in node matches “${query.trim()}”.`; + } + return { + total: definitions.length, + matched: rows.length, + groups: rows.length > 0 ? [{ id: 'built_in', label: 'Built-in', rows }] : [], + emptyText, + }; +} + +/** + * The definition the centre and right columns show: the selected type when the + * engine still reports it, otherwise the first definition in list order, or + * null when there are none. Selection is resolved against all definitions, so a + * search that hides the selected row does not change the detail. + */ +export function resolveNodeLabSelection( + definitions: readonly NodeDefinition[], + selectedNodeType: string | null, +): NodeDefinition | null { + if (selectedNodeType !== null) { + const match = definitions.find((definition) => definition.node_type === selectedNodeType); + if (match) { + return match; + } + } + return sortNodeLabDefinitions(definitions)[0] ?? null; +} + +export function nodeLabSummaryLine(definitions: readonly NodeDefinition[]): string { + if (definitions.length === 0) { + return 'No node definitions loaded'; + } + const categories = new Set(definitions.map((definition) => definition.category)).size; + return `${countText(definitions.length, 'built-in node', 'built-in nodes')} in ${countText( + categories, + 'category', + 'categories', + )}, read-only`; +} + +/** Display text for a port default; empty when the definition declares none. */ +export function formatNodeLabDefault(value: unknown): string { + if (value === undefined || value === null) { + return ''; + } + if (typeof value === 'string') { + return value; + } + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +} + +export interface NodeLabPortRow { + id: string; + label: string; + /** The port id when it reads differently from the label (wires use the id), otherwise null. */ + idNote: string | null; + dataType: string; + /** Inputs only: the declared default, empty when none. */ + defaultText: string; + /** Inputs only: "required" or "optional", plus ", accepts many" for multi-connection ports. */ + requirement: string; + description: string | null; +} + +function comparable(text: string): string { + return text.toLowerCase().replace(/[\s_-]+/g, ''); +} + +function projectPort(port: PortDefinition): NodeLabPortRow { + const label = port.label || port.id; + return { + id: port.id, + label, + idNote: comparable(label) === comparable(port.id) ? null : port.id, + dataType: port.data_type, + defaultText: formatNodeLabDefault(port.default_value), + requirement: `${port.required ? 'required' : 'optional'}${port.multiple ? ', accepts many' : ''}`, + description: port.description?.trim() ? port.description.trim() : null, + }; +} + +export interface NodeLabCheck { + glyph: 'succeeded'; + text: string; +} + +export interface NodeLabDefinitionView { + nodeType: string; + label: string; + category: string; + categoryLabel: string; + description: string; + executionMode: string; + executionModeLabel: string; + ioBindingOrigin: string; + ioBindingLabel: string; + inputs: NodeLabPortRow[]; + outputs: NodeLabPortRow[]; + implementationText: string; + checks: NodeLabCheck[]; } -export function nodeLabUnavailableMessage(): string { - return 'Node authoring is unavailable in this build'; +export function projectNodeLabDefinition(definition: NodeDefinition): NodeLabDefinitionView { + return { + nodeType: definition.node_type, + label: definition.label, + category: definition.category, + categoryLabel: nodeLabCategoryLabel(definition.category), + description: definition.description?.trim() ?? '', + executionMode: definition.execution_mode, + executionModeLabel: nodeLabExecutionModeLabel(definition.execution_mode), + ioBindingOrigin: definition.io_binding_origin, + ioBindingLabel: nodeLabIoBindingLabel(definition.io_binding_origin), + inputs: portsOf(definition.inputs).map(projectPort), + outputs: portsOf(definition.outputs).map(projectPort), + implementationText: NODE_LAB_IMPLEMENTATION_TEXT, + checks: [{ glyph: 'succeeded', text: 'Built-in node, always valid' }], + }; } diff --git a/src/components/workbench/runGraphPresenters.test.ts b/src/components/workbench/runGraphPresenters.test.ts index 711a57222..4221c66d5 100644 --- a/src/components/workbench/runGraphPresenters.test.ts +++ b/src/components/workbench/runGraphPresenters.test.ts @@ -4,21 +4,26 @@ import assert from 'node:assert/strict'; import type { WorkflowRunGraphProjection } from '../../services/workflow/types.ts'; import { buildRunGraphCanvasModel, - buildRunGraphEdgeRows, - buildRunGraphNodeArtifactSummaries, - buildRunGraphNodeRows, buildRunGraphNodeStatusMap, - formatRunGraphArtifactDetail, - formatRunGraphArtifactSummary, formatRunGraphNodeCacheStatusLabel, formatRunGraphNodeStatusLabel, - formatRunGraphCountLabel, - runGraphNodeStatusClass, - runGraphNodeErrorClass, - runGraphStaleDiagnosticClass, - resolveRunGraphCounts, resolveRunGraphPresentationLabel, + buildRunGraphNodeFacts, + buildRunGraphSnapshotLayout, + createRunGraphRequestGate, + formatRunGraphDuration, + formatRunGraphNodeRunSentence, + resolveRunGraphSelectedNodeId, + runGraphNodeGlyph, + runGraphSettingRows, + runGraphWireKind, + clampRunGraphScale, + fitRunGraphScale, + RUN_GRAPH_CARD_HEADER, + RUN_GRAPH_CARD_ROW, + type RunGraphNodeStatusByNodeId, } from './runGraphPresenters.ts'; +import type { NodeStatusProjectionRecord } from '../../services/diagnostics/types.ts'; function createRunGraph(): WorkflowRunGraphProjection { return { @@ -107,43 +112,6 @@ function createRunGraph(): WorkflowRunGraphProjection { }; } -test('resolveRunGraphCounts and labels use the immutable graph snapshot', () => { - const runGraph = createRunGraph(); - - assert.deepEqual(resolveRunGraphCounts(runGraph.graph), { - nodeCount: 2, - edgeCount: 1, - }); - assert.equal(formatRunGraphCountLabel({ nodeCount: 2, edgeCount: 1 }), '2 nodes / 1 edges'); -}); - -test('buildRunGraphNodeRows joins topology versions without editor state', () => { - const rows = buildRunGraphNodeRows(createRunGraph()); - - assert.deepEqual(rows.map((row) => row.nodeId), ['input-1', 'output-1']); - assert.equal(rows[0].contractVersion, '1.0.0'); - assert.equal(rows[0].behaviorDigest, 'digest-input'); - assert.equal(rows[0].positionLabel, '10, 20'); - assert.equal(rows[0].settingsState, 'Run settings captured'); - assert.equal(rows[0].artifactSummaryLabel, 'No retained I/O'); - assert.equal(rows[0].statusLabel, 'No status'); -}); - -test('buildRunGraphEdgeRows renders captured graph edges before topology fallback', () => { - const rows = buildRunGraphEdgeRows(createRunGraph()); - - assert.deepEqual(rows, [ - { - edgeId: 'edge-1', - source: 'input-1:text', - target: 'output-1:value', - staleDiagnosticCount: 0, - staleSeverity: null, - staleDiagnosticMessages: [], - }, - ]); -}); - test('resolveRunGraphPresentationLabel distinguishes complete and fallback layouts', () => { const runGraph = createRunGraph(); assert.equal(resolveRunGraphPresentationLabel(runGraph), 'Presentation revision'); @@ -191,20 +159,6 @@ test('run graph presenters expose backend stale graph diagnostics', () => { }, ]; - const rows = buildRunGraphNodeRows(runGraph); - const outputRow = rows.find((row) => row.nodeId === 'output-1'); - assert.equal(outputRow?.staleDiagnosticCount, 1); - assert.equal(outputRow?.staleSeverity, 'error'); - assert.equal(outputRow?.staleBadgeLabel, '1 stale graph fact'); - assert.deepEqual(outputRow?.staleDiagnosticMessages, [ - 'node type diffusion-inference is retired', - ]); - assert.equal(runGraphStaleDiagnosticClass(outputRow?.staleSeverity), 'error'); - - const edgeRows = buildRunGraphEdgeRows(runGraph); - assert.equal(edgeRows[0].staleDiagnosticCount, 1); - assert.deepEqual(edgeRows[0].staleDiagnosticMessages, ['edge target node is missing']); - const canvas = buildRunGraphCanvasModel(runGraph.graph, {}, {}, runGraph.graph_diagnostics); const outputNode = canvas.nodes.find((node) => node.id === 'output-1'); assert.equal(outputNode?.staleDiagnosticCount, 1); @@ -213,91 +167,28 @@ test('run graph presenters expose backend stale graph diagnostics', () => { assert.equal(canvas.edges[0].staleSeverity, 'error'); }); -test('buildRunGraphNodeArtifactSummaries groups retained node io facts', () => { - const summaries = buildRunGraphNodeArtifactSummaries([ - { - node_id: 'input-1', - artifact_role: 'node_input', - event_seq: 10, - payload_ref: 'artifact://input', - media_type: 'text/plain', - }, - { - node_id: 'input-1', - artifact_role: 'node_output', - event_seq: 12, - payload_ref: null, - media_type: 'application/json', +test('buildRunGraphCanvasModel exposes artifact availability', () => { + const summaries = { + 'output-1': { + nodeId: 'output-1', + inputCount: 0, + outputCount: 1, + artifactCount: 1, + payloadRefCount: 1, + latestEventSeq: 14, + mediaTypes: ['image/png'], }, - { - node_id: 'output-1', - artifact_role: 'node_output', - event_seq: 14, - payload_ref: 'artifact://output', - media_type: 'image/png', - }, - { - node_id: null, - artifact_role: 'workflow_output', - event_seq: 15, - payload_ref: 'artifact://workflow-output', - media_type: 'text/plain', - }, - ]); - - assert.deepEqual(summaries['input-1'], { - nodeId: 'input-1', - inputCount: 1, - outputCount: 1, - artifactCount: 2, - payloadRefCount: 1, - latestEventSeq: 12, - mediaTypes: ['application/json', 'text/plain'], - }); - assert.equal(summaries['output-1'].outputCount, 1); - assert.equal(summaries['output-1'].payloadRefCount, 1); - assert.equal(Object.hasOwn(summaries, 'workflow-output'), false); -}); - -test('buildRunGraphNodeRows and canvas expose artifact availability labels', () => { - const summaries = buildRunGraphNodeArtifactSummaries([ - { - node_id: 'output-1', - artifact_role: 'node_output', - event_seq: 14, - payload_ref: 'artifact://output', - media_type: 'image/png', - }, - ]); - - const rows = buildRunGraphNodeRows(createRunGraph(), summaries); - const outputRow = rows.find((row) => row.nodeId === 'output-1'); - assert.equal(outputRow?.artifactSummaryLabel, '1 output / 0 inputs'); - assert.equal(outputRow?.artifactDetailLabel, '1 artifact, 1 payload reference, image/png'); - assert.equal(outputRow?.hasOutputArtifacts, true); + }; const canvas = buildRunGraphCanvasModel(createRunGraph().graph, summaries); const outputNode = canvas.nodes.find((node) => node.id === 'output-1'); assert.equal(outputNode?.artifactCount, 1); + assert.equal(outputNode?.artifactSummaryLabel, '1 output / 0 inputs'); + const inputNode = canvas.nodes.find((node) => node.id === 'input-1'); + assert.equal(inputNode?.artifactSummaryLabel, 'No retained I/O'); assert.equal(outputNode?.hasOutputArtifacts, true); }); -test('formatRunGraphArtifactSummary distinguishes metadata-only nodes', () => { - const summary = buildRunGraphNodeArtifactSummaries([ - { - node_id: 'input-1', - artifact_role: 'node_input', - event_seq: 10, - payload_ref: null, - media_type: null, - }, - ])['input-1']; - - assert.equal(formatRunGraphArtifactSummary(null), 'No retained I/O'); - assert.equal(formatRunGraphArtifactSummary(summary), '0 outputs / 1 input'); - assert.equal(formatRunGraphArtifactDetail(summary), '1 artifact, 0 payload references, media unknown'); -}); - test('buildRunGraphNodeStatusMap keeps the latest node status by event sequence', () => { const statuses = buildRunGraphNodeStatusMap([ { @@ -347,12 +238,6 @@ test('buildRunGraphNodeStatusMap keeps the latest node status by event sequence' assert.equal(statuses['output-1'].status, 'completed'); assert.equal(formatRunGraphNodeCacheStatusLabel(statuses['output-1'].execution_cache_status), 'Cache hit'); assert.equal(formatRunGraphNodeStatusLabel(statuses['output-1'].status), 'Completed'); - assert.equal(runGraphNodeStatusClass(statuses['output-1'].status), 'completed'); - - const rows = buildRunGraphNodeRows(createRunGraph(), {}, statuses); - const outputRow = rows.find((row) => row.nodeId === 'output-1'); - assert.equal(outputRow?.statusLabel, 'Completed'); - assert.equal(outputRow?.cacheStatusLabel, 'Cache hit'); const canvas = buildRunGraphCanvasModel(createRunGraph().graph, {}, statuses); const outputNode = canvas.nodes.find((node) => node.id === 'output-1'); @@ -388,13 +273,208 @@ test('run graph presenters expose node diagnostic error badges', () => { }, ]); - const rows = buildRunGraphNodeRows(createRunGraph(), {}, statuses); - const outputRow = rows.find((row) => row.nodeId === 'output-1'); - assert.equal(outputRow?.errorEventId, 'error-event-1'); - assert.equal(outputRow?.errorBadgeLabel, 'Fatal: node_execution_failed'); - assert.equal(runGraphNodeErrorClass(outputRow?.errorSeverity), 'fatal'); - const canvas = buildRunGraphCanvasModel(createRunGraph().graph, {}, statuses); const outputNode = canvas.nodes.find((node) => node.id === 'output-1'); assert.equal(outputNode?.errorBadgeLabel, 'Fatal: node_execution_failed'); }); + +function nodeStatus( + nodeId: string, + status: NodeStatusProjectionRecord['status'], + extra: Partial = {}, +): NodeStatusProjectionRecord { + return { + workflow_run_id: 'run-1', + workflow_id: 'workflow-a', + node_id: nodeId, + status, + last_event_seq: 1, + last_updated_at_ms: 1_000, + ...extra, + }; +} + +function createDefinedRunGraph(): WorkflowRunGraphProjection { + const runGraph = createRunGraph(); + runGraph.graph.nodes[0].data = { + label: 'Prompt', + definition: { + label: 'Text Input', + inputs: [], + outputs: [ + { id: 'text', label: 'Text', data_type: 'string' }, + { id: 'unused', label: 'Unused', data_type: 'string' }, + ], + }, + }; + runGraph.graph.nodes[1].data = { + definition: { + label: 'Text Output', + inputs: [{ id: 'value', label: 'Value', data_type: 'string' }], + outputs: [], + }, + }; + return runGraph; +} + +test('run node glyphs follow the status vocabulary and never guess without statuses', () => { + assert.deepEqual(runGraphNodeGlyph(nodeStatus('a', 'running'), true), { glyph: 'running', label: 'Running' }); + assert.deepEqual(runGraphNodeGlyph(nodeStatus('a', 'completed'), true), { glyph: 'succeeded', label: 'Completed' }); + assert.deepEqual(runGraphNodeGlyph(nodeStatus('a', 'failed'), true), { glyph: 'failed', label: 'Failed' }); + assert.deepEqual(runGraphNodeGlyph(nodeStatus('a', 'cancelled'), true), { glyph: 'cancelled', label: 'Cancelled' }); + assert.deepEqual(runGraphNodeGlyph(nodeStatus('a', 'waiting'), true), { glyph: 'waiting', label: 'Waiting' }); + assert.deepEqual(runGraphNodeGlyph(null, true), { glyph: 'queued', label: 'Not reached' }); + assert.deepEqual(runGraphNodeGlyph(null, false), { glyph: 'idle', label: 'No status' }); +}); + +test('wires leaving a running node are live and wires leaving a failed node are failed', () => { + assert.equal(runGraphWireKind('running', 0), 'live'); + assert.equal(runGraphWireKind('failed', 2), 'failed'); + assert.equal(runGraphWireKind('completed', 1), 'stale'); + assert.equal(runGraphWireKind(null, 0), 'idle'); +}); + +test('snapshot layout shifts positions, draws connected ports and anchors wires on them', () => { + const runGraph = createDefinedRunGraph(); + const statuses: RunGraphNodeStatusByNodeId = { 'input-1': nodeStatus('input-1', 'running') }; + const layout = buildRunGraphSnapshotLayout(runGraph.graph, statuses, [], true); + + const input = layout.nodes.find((node) => node.id === 'input-1'); + const output = layout.nodes.find((node) => node.id === 'output-1'); + assert.ok(input && output); + assert.equal(input.label, 'Prompt'); + assert.equal(output.label, 'Text Output'); + assert.equal(input.x, 48); + assert.equal(input.y, 48); + assert.equal(output.x, 338); + assert.deepEqual(input.outputs.map((port) => port.id), ['text']); + assert.equal(input.hiddenPortCount, 1); + assert.equal(input.glyph, 'running'); + assert.equal(output.glyph, 'queued'); + assert.equal(output.stateLabel, 'Not reached'); + + const [wire] = layout.wires; + assert.equal(wire.kind, 'live'); + const sourceY = input.y + RUN_GRAPH_CARD_HEADER + 6 + RUN_GRAPH_CARD_ROW / 2; + const targetY = output.y + RUN_GRAPH_CARD_HEADER + 6 + RUN_GRAPH_CARD_ROW / 2; + assert.ok(wire.d.startsWith(`M ${input.x + input.width} ${sourceY} `)); + assert.ok(wire.d.endsWith(`${output.x} ${targetY}`)); + assert.ok(layout.width >= output.x + output.width); +}); + +test('snapshot layout falls back to edge handles when nodes carry no definition', () => { + const runGraph = createRunGraph(); + const layout = buildRunGraphSnapshotLayout( + runGraph.graph, + { 'input-1': nodeStatus('input-1', 'failed', { error_code: 'oom', error_severity: 'fatal' }) }, + [], + true, + ); + const input = layout.nodes.find((node) => node.id === 'input-1'); + assert.deepEqual(input?.outputs, [{ id: 'text', label: 'text', dataType: null }]); + assert.equal(input?.note, 'Fatal: oom'); + assert.equal(input?.noteDanger, true); + assert.equal(layout.wires[0].kind, 'failed'); + assert.deepEqual(buildRunGraphSnapshotLayout({ nodes: [], edges: [] }), { + width: 0, + height: 0, + nodes: [], + wires: [], + }); +}); + +test('selected run node defaults to the running node, then the failed node, then the first', () => { + const graph = createRunGraph().graph; + assert.equal(resolveRunGraphSelectedNodeId('output-1', graph, {}), 'output-1'); + assert.equal(resolveRunGraphSelectedNodeId('missing', graph, {}), 'input-1'); + assert.equal( + resolveRunGraphSelectedNodeId(null, graph, { 'output-1': nodeStatus('output-1', 'failed') }), + 'output-1', + ); + assert.equal( + resolveRunGraphSelectedNodeId(null, graph, { + 'input-1': nodeStatus('input-1', 'failed'), + 'output-1': nodeStatus('output-1', 'running'), + }), + 'output-1', + ); + assert.equal(resolveRunGraphSelectedNodeId(null, { nodes: [], edges: [] }, {}), null); +}); + +test('run node facts read captured settings, ports, contract and run status', () => { + const runGraph = createDefinedRunGraph(); + runGraph.graph_settings.nodes[0].data = { prompt: 'hello', batch_size: 64, nested: { a: 1 } }; + const facts = buildRunGraphNodeFacts(runGraph, 'input-1', { + 'input-1': nodeStatus('input-1', 'completed', { duration_ms: 1_200, execution_cache_status: 'cache_hit' }), + }); + assert.ok(facts); + assert.equal(facts.label, 'Prompt'); + assert.equal(facts.glyph, 'succeeded'); + assert.deepEqual(facts.settings, [ + { key: 'Prompt', value: 'hello' }, + { key: 'Batch size', value: '64', mono: true }, + ]); + assert.equal(facts.settingsNote, null); + assert.deepEqual(facts.ports.map((port) => `${port.direction}:${port.id}`), ['out:text', 'out:unused']); + assert.equal(facts.contractRows[0].value, '1.0.0'); + assert.equal(facts.runSentence, 'Completed in 1.2 s.'); + assert.deepEqual(facts.runRows, [{ key: 'Cache', value: 'Cache hit' }]); + + const output = buildRunGraphNodeFacts(runGraph, 'output-1', {}); + assert.equal(output?.settingsNote, 'No plain settings were captured for this node.'); + assert.equal(output?.runSentence, 'Not reached in this run.'); + assert.equal(buildRunGraphNodeFacts(runGraph, 'missing', {}), null); + + runGraph.graph_settings.nodes = []; + assert.equal( + buildRunGraphNodeFacts(runGraph, 'input-1', {}, false)?.settingsNote, + 'This run did not capture settings for this node.', + ); +}); + +test('run sentences explain failures in words and durations read naturally', () => { + assert.equal( + formatRunGraphNodeRunSentence(nodeStatus('a', 'failed', { error: 'out of memory, needed 14.2 GB.' })), + 'Failed: out of memory, needed 14.2 GB.', + ); + assert.equal( + formatRunGraphNodeRunSentence(nodeStatus('a', 'failed', { error_code: 'oom' })), + 'Failed: Error: oom.', + ); + assert.equal(formatRunGraphNodeRunSentence(null, false), 'Node status is unavailable for this run.'); + assert.equal(formatRunGraphDuration(420), '420 ms'); + assert.equal(formatRunGraphDuration(38_000), '38.0 s'); + assert.equal(formatRunGraphDuration(663_000), '11m 03s'); +}); + +test('setting rows keep plain scalars and shorten long text', () => { + const long = 'x'.repeat(200); + const rows = runGraphSettingRows({ label: 'skip', definition: {}, empty: ' ', flag: true, text: long }); + assert.deepEqual(rows.map((row) => row.key), ['Flag', 'Text']); + assert.equal(rows[1].value.length, 120); + assert.ok(rows[1].value.endsWith('…')); + assert.deepEqual(runGraphSettingRows(null), []); + assert.deepEqual(runGraphSettingRows(['a']), []); +}); + +test('request gate applies only the newest load and nothing after invalidation', () => { + const gate = createRunGraphRequestGate(); + const first = gate.begin(); + const second = gate.begin(); + assert.equal(gate.isCurrent(first), false); + assert.equal(gate.isCurrent(second), true); + gate.invalidate(); + assert.equal(gate.isCurrent(second), false); + + const other = createRunGraphRequestGate(); + const otherToken = other.begin(); + assert.equal(other.isCurrent(otherToken), true, 'gates are scoped to their owner'); +}); + +test('fit scale shrinks large snapshots to the viewport and never enlarges small ones', () => { + assert.equal(fitRunGraphScale({ width: 1024, height: 524 }, { width: 2000, height: 500 }), 0.5); + assert.equal(fitRunGraphScale({ width: 1200, height: 800 }, { width: 400, height: 300 }), 1); + assert.equal(fitRunGraphScale({ width: 0, height: 0 }, { width: 400, height: 300 }), 1); + assert.equal(fitRunGraphScale({ width: 124, height: 124 }, { width: 10_000, height: 10_000 }), 0.35); + assert.equal(clampRunGraphScale(9), 1.5); +}); diff --git a/src/components/workbench/runGraphPresenters.ts b/src/components/workbench/runGraphPresenters.ts index 6f878e314..f33d034e9 100644 --- a/src/components/workbench/runGraphPresenters.ts +++ b/src/components/workbench/runGraphPresenters.ts @@ -7,48 +7,11 @@ import type { } from '../../services/workflow/types'; import type { DiagnosticErrorSeverity, - IoArtifactProjectionRecord, NodeExecutionProjectionStatus, NodeStatusProjectionRecord, } from '../../services/diagnostics/types'; - -export interface RunGraphCounts { - nodeCount: number; - edgeCount: number; -} - -export interface RunGraphNodeRow { - nodeId: string; - nodeType: string; - contractVersion: string; - behaviorDigest: string; - positionLabel: string; - settingsState: string; - artifactSummaryLabel: string; - artifactDetailLabel: string; - hasOutputArtifacts: boolean; - statusLabel: string; - statusClass: string; - cacheStatusLabel: string | null; - errorEventId: string | null; - errorSeverity: DiagnosticErrorSeverity | null; - errorPhase: string | null; - errorCode: string | null; - errorBadgeLabel: string | null; - staleDiagnosticCount: number; - staleSeverity: WorkflowGraphDiagnostic['severity'] | null; - staleBadgeLabel: string | null; - staleDiagnosticMessages: string[]; -} - -export interface RunGraphEdgeRow { - edgeId: string; - source: string; - target: string; - staleDiagnosticCount: number; - staleSeverity: WorkflowGraphDiagnostic['severity'] | null; - staleDiagnosticMessages: string[]; -} +import { glyphStateForStatus, type GlyphState } from './ui/statusGlyph.ts'; +import type { KeyValueRow } from './ui/types'; export interface RunGraphCanvasNode { id: string; @@ -116,17 +79,6 @@ const NODE_HEIGHT = 104; const CANVAS_PADDING = 96; const EMPTY_CANVAS_VIEWBOX = '0 0 640 360'; -export function resolveRunGraphCounts(graph: WorkflowGraph | null | undefined): RunGraphCounts { - return { - nodeCount: graph?.nodes.length ?? 0, - edgeCount: graph?.edges.length ?? 0, - }; -} - -export function formatRunGraphCountLabel(counts: RunGraphCounts): string { - return `${counts.nodeCount} nodes / ${counts.edgeCount} edges`; -} - export function formatRunGraphTimestamp(value: number): string { return new Date(value).toLocaleString(); } @@ -143,77 +95,6 @@ export function resolveRunGraphPresentationLabel(runGraph: WorkflowRunGraphProje return 'Generated layout fallback'; } -export function buildRunGraphNodeRows( - runGraph: WorkflowRunGraphProjection, - artifactSummaries: RunGraphNodeArtifactSummaryByNodeId = {}, - nodeStatuses: RunGraphNodeStatusByNodeId = {}, -): RunGraphNodeRow[] { - const diagnostics = indexRunGraphDiagnostics(runGraph.graph_diagnostics ?? []); - const topologyByNodeId = new Map( - runGraph.executable_topology.nodes.map((node) => [node.node_id, node]), - ); - const settingsByNodeId = new Map( - runGraph.graph_settings.nodes.map((node) => [node.node_id, node]), - ); - - return runGraph.graph.nodes.map((node) => { - const topology = topologyByNodeId.get(node.id); - const settings = settingsByNodeId.get(node.id); - const artifactSummary = artifactSummaries[node.id]; - const nodeStatus = nodeStatuses[node.id]; - const nodeDiagnostics = diagnostics.byNodeId.get(node.id) ?? []; - return { - nodeId: node.id, - nodeType: topology?.node_type ?? node.node_type, - contractVersion: topology?.contract_version || 'Unknown', - behaviorDigest: topology?.behavior_digest || 'Unknown', - positionLabel: formatNodePosition(node), - settingsState: settings ? 'Run settings captured' : 'Run settings unavailable', - artifactSummaryLabel: formatRunGraphArtifactSummary(artifactSummary), - artifactDetailLabel: formatRunGraphArtifactDetail(artifactSummary), - hasOutputArtifacts: (artifactSummary?.outputCount ?? 0) > 0, - statusLabel: formatRunGraphNodeStatusLabel(nodeStatus?.status), - statusClass: runGraphNodeStatusClass(nodeStatus?.status), - cacheStatusLabel: formatRunGraphNodeCacheStatusLabel(nodeStatus?.execution_cache_status), - errorEventId: nodeStatus?.canonical_error_event_id ?? nodeStatus?.error_event_id ?? null, - errorSeverity: nodeStatus?.error_severity ?? null, - errorPhase: nodeStatus?.error_phase ?? null, - errorCode: nodeStatus?.error_code ?? null, - errorBadgeLabel: formatRunGraphNodeErrorBadge(nodeStatus), - staleDiagnosticCount: nodeDiagnostics.length, - staleSeverity: strongestGraphDiagnosticSeverity(nodeDiagnostics), - staleBadgeLabel: formatRunGraphStaleBadge(nodeDiagnostics), - staleDiagnosticMessages: nodeDiagnostics.map((diagnostic) => diagnostic.message), - }; - }); -} - -export function buildRunGraphEdgeRows(runGraph: WorkflowRunGraphProjection): RunGraphEdgeRow[] { - const diagnostics = indexRunGraphDiagnostics(runGraph.graph_diagnostics ?? []); - if (runGraph.graph.edges.length > 0) { - return runGraph.graph.edges.map((edge) => { - const edgeDiagnostics = diagnostics.byEdgeId.get(edge.id) ?? []; - return { - edgeId: edge.id, - source: formatGraphEdgeEndpoint(edge.source, edge.source_handle), - target: formatGraphEdgeEndpoint(edge.target, edge.target_handle), - staleDiagnosticCount: edgeDiagnostics.length, - staleSeverity: strongestGraphDiagnosticSeverity(edgeDiagnostics), - staleDiagnosticMessages: edgeDiagnostics.map((diagnostic) => diagnostic.message), - }; - }); - } - - return runGraph.executable_topology.edges.map((edge, index) => ({ - edgeId: `topology-edge-${index + 1}`, - source: formatGraphEdgeEndpoint(edge.source_node_id, edge.source_port_id), - target: formatGraphEdgeEndpoint(edge.target_node_id, edge.target_port_id), - staleDiagnosticCount: 0, - staleSeverity: null, - staleDiagnosticMessages: [], - })); -} - export function buildRunGraphCanvasModel( graph: WorkflowGraph, artifactSummaries: RunGraphNodeArtifactSummaryByNodeId = {}, @@ -293,38 +174,6 @@ export function formatRunGraphNodeErrorBadge( return `${severity}: ${code}`; } -export function runGraphNodeErrorClass( - severity: DiagnosticErrorSeverity | null | undefined, -): string { - switch (severity) { - case 'fatal': - return 'fatal'; - case 'error': - return 'error'; - case 'warning': - return 'warning'; - case null: - case undefined: - return 'none'; - } -} - -export function runGraphStaleDiagnosticClass( - severity: WorkflowGraphDiagnostic['severity'] | null | undefined, -): string { - switch (severity) { - case 'error': - return 'error'; - case 'warning': - return 'warning'; - case 'info': - return 'info'; - case null: - case undefined: - return 'none'; - } -} - function formatRunGraphErrorSeverity(severity: DiagnosticErrorSeverity): string { switch (severity) { case 'fatal': @@ -370,27 +219,6 @@ export function formatRunGraphNodeStatusLabel( } } -export function runGraphNodeStatusClass( - status: NodeExecutionProjectionStatus | null | undefined, -): string { - switch (status) { - case 'running': - return 'running'; - case 'waiting': - return 'waiting'; - case 'completed': - return 'completed'; - case 'failed': - return 'failed'; - case 'cancelled': - return 'cancelled'; - case 'queued': - return 'queued'; - default: - return 'unknown'; - } -} - export function formatRunGraphNodeCacheStatusLabel( status: NodeStatusProjectionRecord['execution_cache_status'] | null | undefined, ): string | null { @@ -406,86 +234,6 @@ export function formatRunGraphNodeCacheStatusLabel( } } -export function buildRunGraphNodeArtifactSummaries( - artifacts: Pick< - IoArtifactProjectionRecord, - 'node_id' | 'artifact_role' | 'event_seq' | 'payload_ref' | 'media_type' - >[], -): RunGraphNodeArtifactSummaryByNodeId { - const summaries: RunGraphNodeArtifactSummaryByNodeId = {}; - const mediaTypesByNodeId = new Map>(); - - for (const artifact of artifacts) { - if (!artifact.node_id) { - continue; - } - - const summary = summaries[artifact.node_id] ?? { - nodeId: artifact.node_id, - inputCount: 0, - outputCount: 0, - artifactCount: 0, - payloadRefCount: 0, - latestEventSeq: artifact.event_seq, - mediaTypes: [], - }; - - summary.artifactCount += 1; - summary.latestEventSeq = Math.max(summary.latestEventSeq, artifact.event_seq); - if (artifact.artifact_role === 'node_input') { - summary.inputCount += 1; - } - if (artifact.artifact_role === 'node_output') { - summary.outputCount += 1; - } - if (artifact.payload_ref?.trim()) { - summary.payloadRefCount += 1; - } - if (artifact.media_type?.trim()) { - const mediaTypes = mediaTypesByNodeId.get(artifact.node_id) ?? new Set(); - mediaTypes.add(artifact.media_type); - mediaTypesByNodeId.set(artifact.node_id, mediaTypes); - } - - summaries[artifact.node_id] = summary; - } - - for (const [nodeId, mediaTypes] of mediaTypesByNodeId.entries()) { - summaries[nodeId].mediaTypes = [...mediaTypes].sort(); - } - - return summaries; -} - -export function formatRunGraphArtifactSummary( - summary: RunGraphNodeArtifactSummary | null | undefined, -): string { - if (!summary || summary.artifactCount === 0) { - return 'No retained I/O'; - } - return `${formatCount(summary.outputCount, 'output')} / ${formatCount(summary.inputCount, 'input')}`; -} - -export function formatRunGraphArtifactDetail( - summary: RunGraphNodeArtifactSummary | null | undefined, -): string { - if (!summary || summary.artifactCount === 0) { - return 'No retained artifact metadata for this node'; - } - - const payloadLabel = - summary.payloadRefCount === 1 - ? '1 payload reference' - : `${summary.payloadRefCount} payload references`; - const mediaLabel = - summary.mediaTypes.length === 0 ? 'media unknown' : summary.mediaTypes.join(', '); - return `${formatCount(summary.artifactCount, 'artifact')}, ${payloadLabel}, ${mediaLabel}`; -} - -function formatGraphEdgeEndpoint(nodeId: string, portId: string): string { - return `${nodeId}:${portId}`; -} - function indexRunGraphDiagnostics(diagnostics: WorkflowGraphDiagnostic[]): RunGraphDiagnosticIndex { const byNodeId = new Map(); const byEdgeId = new Map(); @@ -518,6 +266,41 @@ function appendDiagnostic( } } +// Used only by buildRunGraphCanvasModel; no longer exported (M9d). +function runGraphNodeStatusClass( + status: NodeExecutionProjectionStatus | null | undefined, +): string { + switch (status) { + case 'running': + return 'running'; + case 'waiting': + return 'waiting'; + case 'completed': + return 'completed'; + case 'failed': + return 'failed'; + case 'cancelled': + return 'cancelled'; + case 'queued': + return 'queued'; + default: + return 'unknown'; + } +} + +function formatRunGraphArtifactSummary( + summary: RunGraphNodeArtifactSummary | null | undefined, +): string { + if (!summary || summary.artifactCount === 0) { + return 'No retained I/O'; + } + return `${formatCount(summary.outputCount, 'output')} / ${formatCount(summary.inputCount, 'input')}`; +} + +function formatCount(count: number, noun: string): string { + return count === 1 ? `1 ${noun}` : `${count} ${noun}s`; +} + function strongestGraphDiagnosticSeverity( diagnostics: WorkflowGraphDiagnostic[], ): WorkflowGraphDiagnostic['severity'] | null { @@ -540,14 +323,6 @@ function formatRunGraphStaleBadge(diagnostics: WorkflowGraphDiagnostic[]): strin return diagnostics.length === 1 ? '1 stale graph fact' : `${diagnostics.length} stale graph facts`; } -function formatCount(count: number, noun: string): string { - return count === 1 ? `1 ${noun}` : `${count} ${noun}s`; -} - -function formatNodePosition(node: GraphNode): string { - return `${Math.round(node.position.x)}, ${Math.round(node.position.y)}`; -} - function buildRunGraphCanvasEdge( edge: GraphEdge, nodeById: Map, @@ -571,3 +346,552 @@ function buildRunGraphCanvasEdge( staleDiagnosticMessages: diagnostics.map((diagnostic) => diagnostic.message), }; } + +// --- Graph page run mode (read-only run graph surface, ADR-014) --- + +/** How a wire is drawn in the run snapshot. */ +export type RunGraphWireKind = 'idle' | 'live' | 'failed' | 'stale'; + +export interface RunGraphSnapshotPort { + id: string; + label: string; + dataType: string | null; +} + +export interface RunGraphSnapshotNode { + id: string; + label: string; + nodeType: string; + x: number; + y: number; + width: number; + height: number; + glyph: GlyphState; + stateLabel: string; + inputs: RunGraphSnapshotPort[]; + outputs: RunGraphSnapshotPort[]; + /** Ports of the node definition that no captured edge uses. */ + hiddenPortCount: number; + /** One short line under the ports: the error badge or the stale-fact badge. */ + note: string | null; + noteDanger: boolean; + errorEventId: string | null; +} + +export interface RunGraphSnapshotWire { + id: string; + d: string; + kind: RunGraphWireKind; + sourceNodeId: string; + targetNodeId: string; +} + +export interface RunGraphSnapshotLayout { + width: number; + height: number; + nodes: RunGraphSnapshotNode[]; + wires: RunGraphSnapshotWire[]; +} + +export interface RunGraphNodeGlyph { + glyph: GlyphState; + label: string; +} + +export interface RunGraphNodePortFact { + direction: 'in' | 'out'; + id: string; + label: string; + dataType: string | null; +} + +export interface RunGraphNodeFacts { + nodeId: string; + label: string; + nodeType: string; + glyph: GlyphState; + stateLabel: string; + /** Captured run settings as read-only rows; empty when none were captured. */ + settings: KeyValueRow[]; + settingsNote: string | null; + ports: RunGraphNodePortFact[]; + contractRows: KeyValueRow[]; + /** One sentence for the "In this run" section. */ + runSentence: string; + runRows: KeyValueRow[]; + errorEventId: string | null; + staleMessages: string[]; +} + +/** Card geometry, in canvas pixels. Port rows anchor the wires. */ +export const RUN_GRAPH_CARD_WIDTH = 184; +export const RUN_GRAPH_CARD_HEADER = 32; +export const RUN_GRAPH_CARD_ROW = 22; +const RUN_GRAPH_CARD_PADDING = 6; +const RUN_GRAPH_LAYOUT_MARGIN = 48; +const RUN_GRAPH_SETTING_MAX_LENGTH = 120; + +/** + * Glyph and words for a node in a run. Without a status record the node was + * not reached, unless the node-status projection itself was unavailable, in + * which case nothing is claimed. + */ +export function runGraphNodeGlyph( + status: NodeStatusProjectionRecord | null | undefined, + statusesAvailable: boolean, +): RunGraphNodeGlyph { + if (!status) { + return statusesAvailable + ? { glyph: 'queued', label: 'Not reached' } + : { glyph: 'idle', label: 'No status' }; + } + return { + glyph: glyphStateForStatus(status.status), + label: formatRunGraphNodeStatusLabel(status.status), + }; +} + +/** Wire treatment from the status of the node it leaves. */ +export function runGraphWireKind( + sourceStatus: NodeExecutionProjectionStatus | null | undefined, + staleDiagnosticCount: number, +): RunGraphWireKind { + if (sourceStatus === 'running') { + return 'live'; + } + if (sourceStatus === 'failed') { + return 'failed'; + } + return staleDiagnosticCount > 0 ? 'stale' : 'idle'; +} + +/** + * Lay out the captured run graph as cards and wires. Positions come from the + * snapshot and are shifted so the top-left card sits at the margin; nothing + * here reads or writes the editable graph. + */ +export function buildRunGraphSnapshotLayout( + graph: WorkflowGraph, + nodeStatuses: RunGraphNodeStatusByNodeId = {}, + graphDiagnostics: WorkflowGraphDiagnostic[] = [], + statusesAvailable = true, +): RunGraphSnapshotLayout { + if (graph.nodes.length === 0) { + return { width: 0, height: 0, nodes: [], wires: [] }; + } + + const diagnostics = indexRunGraphDiagnostics(graphDiagnostics); + const minX = Math.min(...graph.nodes.map((node) => node.position.x)); + const minY = Math.min(...graph.nodes.map((node) => node.position.y)); + const offsetX = RUN_GRAPH_LAYOUT_MARGIN - minX; + const offsetY = RUN_GRAPH_LAYOUT_MARGIN - minY; + + const nodes = graph.nodes.map((node) => { + const status = nodeStatuses[node.id]; + const { glyph, label: stateLabel } = runGraphNodeGlyph(status, statusesAvailable); + const ports = resolveSnapshotPorts(node, graph.edges); + const nodeDiagnostics = diagnostics.byNodeId.get(node.id) ?? []; + const errorBadge = formatRunGraphNodeErrorBadge(status); + const staleBadge = formatRunGraphStaleBadge(nodeDiagnostics); + const note = errorBadge ?? staleBadge; + const rowCount = + ports.inputs.length + ports.outputs.length + (ports.hiddenPortCount > 0 ? 1 : 0) + (note ? 1 : 0); + return { + id: node.id, + label: resolveNodeLabel(node), + nodeType: node.node_type, + x: Math.round(node.position.x + offsetX), + y: Math.round(node.position.y + offsetY), + width: RUN_GRAPH_CARD_WIDTH, + height: RUN_GRAPH_CARD_HEADER + RUN_GRAPH_CARD_PADDING * 2 + rowCount * RUN_GRAPH_CARD_ROW, + glyph, + stateLabel, + inputs: ports.inputs, + outputs: ports.outputs, + hiddenPortCount: ports.hiddenPortCount, + note, + noteDanger: errorBadge !== null, + errorEventId: status?.canonical_error_event_id ?? status?.error_event_id ?? null, + }; + }); + + const nodeById = new Map(nodes.map((node) => [node.id, node])); + const wires = graph.edges.flatMap((edge) => { + const source = nodeById.get(edge.source); + const target = nodeById.get(edge.target); + if (!source || !target) { + return []; + } + const sourceX = source.x + source.width; + const sourceY = outputAnchorY(source, edge.source_handle); + const targetX = target.x; + const targetY = inputAnchorY(target, edge.target_handle); + const bend = Math.max(40, Math.abs(targetX - sourceX) / 2); + return [ + { + id: edge.id, + d: `M ${sourceX} ${sourceY} C ${sourceX + bend} ${sourceY}, ${targetX - bend} ${targetY}, ${targetX} ${targetY}`, + kind: runGraphWireKind( + nodeStatuses[edge.source]?.status, + diagnostics.byEdgeId.get(edge.id)?.length ?? 0, + ), + sourceNodeId: edge.source, + targetNodeId: edge.target, + }, + ]; + }); + + return { + width: Math.max(...nodes.map((node) => node.x + node.width)) + RUN_GRAPH_LAYOUT_MARGIN, + height: Math.max(...nodes.map((node) => node.y + node.height)) + RUN_GRAPH_LAYOUT_MARGIN, + nodes, + wires, + }; +} + +/** + * The node the properties panel shows when nothing valid is selected: the + * running node, else the failed node, else the first node. + */ +export function resolveRunGraphSelectedNodeId( + currentNodeId: string | null, + graph: WorkflowGraph, + nodeStatuses: RunGraphNodeStatusByNodeId = {}, +): string | null { + const nodeIds = graph.nodes.map((node) => node.id); + if (currentNodeId && nodeIds.includes(currentNodeId)) { + return currentNodeId; + } + return ( + nodeIds.find((nodeId) => nodeStatuses[nodeId]?.status === 'running') ?? + nodeIds.find((nodeId) => nodeStatuses[nodeId]?.status === 'failed') ?? + nodeIds[0] ?? + null + ); +} + +/** Facts for the run-mode properties panel, all from the run snapshot and node status projection. */ +export function buildRunGraphNodeFacts( + runGraph: WorkflowRunGraphProjection, + nodeId: string, + nodeStatuses: RunGraphNodeStatusByNodeId = {}, + statusesAvailable = true, +): RunGraphNodeFacts | null { + const node = runGraph.graph.nodes.find((candidate) => candidate.id === nodeId); + if (!node) { + return null; + } + + const status = nodeStatuses[nodeId]; + const { glyph, label: stateLabel } = runGraphNodeGlyph(status, statusesAvailable); + const topology = runGraph.executable_topology.nodes.find((candidate) => candidate.node_id === nodeId); + const settingsRecord = runGraph.graph_settings.nodes.find((candidate) => candidate.node_id === nodeId); + const settings = settingsRecord ? runGraphSettingRows(settingsRecord.data) : []; + const ports = resolveSnapshotPorts(node, runGraph.graph.edges, true); + const staleMessages = (runGraph.graph_diagnostics ?? []) + .filter((diagnostic) => diagnostic.scope === 'node' && diagnostic.node_id === nodeId) + .map((diagnostic) => diagnostic.message); + + return { + nodeId, + label: resolveNodeLabel(node), + nodeType: topology?.node_type ?? node.node_type, + glyph, + stateLabel, + settings, + settingsNote: !settingsRecord + ? 'This run did not capture settings for this node.' + : settings.length === 0 + ? 'No plain settings were captured for this node.' + : null, + ports: [ + ...ports.inputs.map((port) => ({ direction: 'in' as const, ...port })), + ...ports.outputs.map((port) => ({ direction: 'out' as const, ...port })), + ], + contractRows: [ + { key: 'Contract', value: topology?.contract_version || 'Unknown' }, + { key: 'Behavior', value: topology?.behavior_digest || 'Unknown', mono: true }, + ], + runSentence: formatRunGraphNodeRunSentence(status, statusesAvailable), + runRows: buildRunGraphNodeRunRows(status), + errorEventId: status?.canonical_error_event_id ?? status?.error_event_id ?? null, + staleMessages, + }; +} + +export function formatRunGraphNodeRunSentence( + status: NodeStatusProjectionRecord | null | undefined, + statusesAvailable = true, +): string { + if (!status) { + return statusesAvailable + ? 'Not reached in this run.' + : 'Node status is unavailable for this run.'; + } + switch (status.status) { + case 'queued': + return 'Queued, not started yet.'; + case 'waiting': + return 'Waiting to start.'; + case 'running': + return status.started_at_ms ? `Running since ${formatClockTime(status.started_at_ms)}.` : 'Running.'; + case 'completed': + return status.duration_ms !== null && status.duration_ms !== undefined + ? `Completed in ${formatRunGraphDuration(status.duration_ms)}.` + : 'Completed.'; + case 'failed': { + const reason = status.error?.trim() || formatRunGraphNodeErrorBadge(status); + return reason ? `Failed: ${trimSentenceEnd(reason)}.` : 'Failed.'; + } + case 'cancelled': + return 'Cancelled.'; + } +} + +export function formatRunGraphDuration(durationMs: number): string { + if (durationMs < 1000) { + return `${Math.max(0, Math.round(durationMs))} ms`; + } + const seconds = durationMs / 1000; + if (seconds < 60) { + return `${seconds.toFixed(1)} s`; + } + const minutes = Math.floor(seconds / 60); + const rest = Math.round(seconds - minutes * 60); + return `${minutes}m ${String(rest).padStart(2, '0')}s`; +} + +/** Plain scalar settings as rows; structured values are left to I/O Inspector. */ +export function runGraphSettingRows(data: unknown): KeyValueRow[] { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return []; + } + const seenKeys = new Set(); + return Object.entries(data as Record).flatMap(([key, value]) => { + if (key === 'label' || key === 'definition') { + return []; + } + // Rows are keyed by their visible key; keep the first of any that read the same. + const visibleKey = humanizeSettingKey(key); + if (seenKeys.has(visibleKey)) { + return []; + } + seenKeys.add(visibleKey); + if (typeof value === 'string') { + if (value.trim().length === 0) { + return []; + } + const text = + value.length > RUN_GRAPH_SETTING_MAX_LENGTH + ? `${value.slice(0, RUN_GRAPH_SETTING_MAX_LENGTH - 1)}…` + : value; + return [{ key: visibleKey, value: text }]; + } + if (typeof value === 'number' || typeof value === 'boolean') { + return [{ key: visibleKey, value: String(value), mono: typeof value === 'number' }]; + } + return []; + }); +} + +/** + * Current-invocation authority for run graph loads: a load started for one run + * must not apply after a newer load (another run, or a refresh) began, or + * after the owner stopped. + */ +export interface RunGraphRequestGate { + begin(): number; + isCurrent(token: number): boolean; + /** Supersede every started request, for example on unmount or leaving run mode. */ + invalidate(): void; +} + +export function createRunGraphRequestGate(): RunGraphRequestGate { + let generation = 0; + return { + begin() { + generation += 1; + return generation; + }, + isCurrent(token) { + return token === generation; + }, + invalidate() { + generation += 1; + }, + }; +} + +function buildRunGraphNodeRunRows(status: NodeStatusProjectionRecord | null | undefined): KeyValueRow[] { + if (!status) { + return []; + } + const rows: KeyValueRow[] = []; + const cache = formatRunGraphNodeCacheStatusLabel(status.execution_cache_status); + if (cache) { + rows.push({ key: 'Cache', value: cache }); + } + if (status.runtime_id) { + rows.push({ + key: 'Runtime', + value: status.runtime_version ? `${status.runtime_id} ${status.runtime_version}` : status.runtime_id, + }); + } + if (status.selected_backend_key) { + rows.push({ key: 'Backend', value: status.selected_backend_key }); + } + if (status.model_id) { + rows.push({ key: 'Model', value: status.model_id, mono: true }); + } + // A running node's sentence already says when it started. + if (status.started_at_ms && status.status !== 'running') { + rows.push({ key: 'Started', value: formatClockTime(status.started_at_ms), mono: true }); + } + const errorBadge = formatRunGraphNodeErrorBadge(status); + if (errorBadge) { + rows.push({ + key: 'Error', + value: status.error_phase ? `${errorBadge} in ${status.error_phase}` : errorBadge, + }); + } + return rows; +} + +function resolveNodeLabel(node: GraphNode): string { + const data = node.data ?? {}; + const label = typeof data.label === 'string' ? data.label.trim() : ''; + if (label) { + return label; + } + const definition = readDefinition(node); + return definition?.label?.trim() || node.id; +} + +interface SnapshotDefinition { + label?: string; + inputs: RunGraphSnapshotPort[]; + outputs: RunGraphSnapshotPort[]; +} + +function readDefinition(node: GraphNode): SnapshotDefinition | null { + const definition = (node.data ?? {}).definition; + if (!definition || typeof definition !== 'object') { + return null; + } + const record = definition as Record; + return { + label: typeof record.label === 'string' ? record.label : undefined, + inputs: readPorts(record.inputs), + outputs: readPorts(record.outputs), + }; +} + +function readPorts(value: unknown): RunGraphSnapshotPort[] { + if (!Array.isArray(value)) { + return []; + } + return value.flatMap((port) => { + if (!port || typeof port !== 'object') { + return []; + } + const record = port as Record; + if (typeof record.id !== 'string') { + return []; + } + return [ + { + id: record.id, + label: typeof record.label === 'string' && record.label.trim() ? record.label : record.id, + dataType: typeof record.data_type === 'string' ? record.data_type : null, + }, + ]; + }); +} + +/** + * Ports to draw on a card: the connected ones in definition order, plus any + * port an edge names that the definition lacks. With `allPorts`, every + * definition port is returned (properties panel). + */ +function resolveSnapshotPorts( + node: GraphNode, + edges: GraphEdge[], + allPorts = false, +): { inputs: RunGraphSnapshotPort[]; outputs: RunGraphSnapshotPort[]; hiddenPortCount: number } { + const definition = readDefinition(node); + const connectedInputs = uniqueHandles(edges.filter((edge) => edge.target === node.id).map((edge) => edge.target_handle)); + const connectedOutputs = uniqueHandles(edges.filter((edge) => edge.source === node.id).map((edge) => edge.source_handle)); + const pick = (declared: RunGraphSnapshotPort[], connected: string[]) => { + const declaredIds = new Set(declared.map((port) => port.id)); + const shown = allPorts ? declared : declared.filter((port) => connected.includes(port.id)); + const undeclared = connected + .filter((id) => !declaredIds.has(id)) + .map((id) => ({ id, label: id, dataType: null })); + return { shown: [...shown, ...undeclared], hidden: declared.length - (allPorts ? declared.length : shown.length) }; + }; + const inputs = pick(definition?.inputs ?? [], connectedInputs); + const outputs = pick(definition?.outputs ?? [], connectedOutputs); + return { + inputs: inputs.shown, + outputs: outputs.shown, + hiddenPortCount: inputs.hidden + outputs.hidden, + }; +} + +function uniqueHandles(handles: string[]): string[] { + return [...new Set(handles)]; +} + +function rowCenterY(node: RunGraphSnapshotNode, rowIndex: number): number { + return node.y + RUN_GRAPH_CARD_HEADER + RUN_GRAPH_CARD_PADDING + rowIndex * RUN_GRAPH_CARD_ROW + RUN_GRAPH_CARD_ROW / 2; +} + +function inputAnchorY(node: RunGraphSnapshotNode, portId: string): number { + const index = node.inputs.findIndex((port) => port.id === portId); + return index < 0 ? node.y + RUN_GRAPH_CARD_HEADER / 2 : rowCenterY(node, index); +} + +function outputAnchorY(node: RunGraphSnapshotNode, portId: string): number { + const index = node.outputs.findIndex((port) => port.id === portId); + return index < 0 ? node.y + RUN_GRAPH_CARD_HEADER / 2 : rowCenterY(node, node.inputs.length + index); +} + +function humanizeSettingKey(key: string): string { + const words = key.replaceAll('_', ' ').replaceAll('-', ' ').trim(); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +function trimSentenceEnd(text: string): string { + return text.trim().replace(/[.\s]+$/, ''); +} + +function formatClockTime(ms: number): string { + const date = new Date(ms); + return [date.getHours(), date.getMinutes(), date.getSeconds()] + .map((part) => String(part).padStart(2, '0')) + .join(':'); +} + +export const RUN_GRAPH_MIN_SCALE = 0.35; +export const RUN_GRAPH_MAX_SCALE = 1.5; +const RUN_GRAPH_FIT_INSET = 24; + +/** Scale that fits the whole snapshot in the viewport, never enlarging it. */ +export function fitRunGraphScale( + viewport: { width: number; height: number }, + layout: Pick, +): number { + if (viewport.width <= 0 || viewport.height <= 0 || layout.width <= 0 || layout.height <= 0) { + return 1; + } + const fit = Math.min( + 1, + (viewport.width - RUN_GRAPH_FIT_INSET) / layout.width, + (viewport.height - RUN_GRAPH_FIT_INSET) / layout.height, + ); + return clampRunGraphScale(fit); +} + +export function clampRunGraphScale(scale: number): number { + return Math.min(RUN_GRAPH_MAX_SCALE, Math.max(RUN_GRAPH_MIN_SCALE, Math.round(scale * 100) / 100)); +} diff --git a/src/components/workbench/schedulerPagePresenters.test.ts b/src/components/workbench/schedulerPagePresenters.test.ts index 48305d2ac..a58e0889e 100644 --- a/src/components/workbench/schedulerPagePresenters.test.ts +++ b/src/components/workbench/schedulerPagePresenters.test.ts @@ -7,23 +7,16 @@ import type { SchedulerTimelineProjectionRecord, } from '../../services/diagnostics/types.ts'; import { - buildSchedulerEstimateRows, buildSchedulerRetentionSummaryRows, buildSchedulerTimelineAttemptRows, - buildSchedulerRunListQuery, filterSchedulerTimelineEvents, filterAndSortSchedulerRuns, formatSchedulerAcceptedDateLabel, formatSchedulerDevicePlacementLabel, - formatSchedulerEstimateDuration, formatSchedulerPlacementLabel, formatSchedulerModelCacheState, formatSchedulerPolicyLabel, - formatSchedulerPriority, - formatSchedulerQueuePosition, formatSchedulerProjectionFreshness, - formatSchedulerEstimateLabel, - formatSchedulerReasonLabel, formatSchedulerRetentionLabel, formatSchedulerRetentionStateLabel, formatSchedulerRuntimePlacementLabel, @@ -31,7 +24,6 @@ import { formatSchedulerStatusLabel, formatSchedulerTimelineKind, formatSchedulerTimelineSource, - formatSchedulerDuration, formatSchedulerTimestamp, schedulerAcceptedDateFilterOptions, schedulerBucketFilterOptions, @@ -51,8 +43,36 @@ import { schedulerTimelinePayloadLabel, schedulerTimelineKindFilterOptions, schedulerTimelineSourceFilterOptions, - schedulerStatusClass, + buildSchedulerFilterFields, + buildSchedulerQueueSummary, + buildSchedulerStatusSegments, + filterSchedulerRunsBySegment, + formatSchedulerClockTime, + formatSchedulerRowTime, + groupSchedulerRuns, + schedulerAdminControlsUnavailableReason, + schedulerAppliedFilterChips, + schedulerDetailFreshnessText, + schedulerEstimateSentence, + schedulerFooterState, + schedulerQueueControlsUnavailableReason, + schedulerResumeUnavailableReason, + schedulerRetentionPolicyText, + schedulerRetentionText, + schedulerRunDetailChips, + schedulerRunDetailLine, + schedulerRunPlacementText, + schedulerRunPolicyText, + schedulerRunProgressText, + schedulerStatusSegmentForRun, + schedulerTimelineAttemptText, } from './schedulerPagePresenters.ts'; +import { + DEFAULT_SCHEDULER_RUN_FILTERS, + SCHEDULER_SECONDARY_FILTER_KEYS, + withSchedulerRunFilters, +} from '../../stores/schedulerRunListStore.ts'; +import { groupRunsForContextPicker } from './shell/runContextPicker.ts'; function run(overrides: Partial): RunListProjectionRecord { return { @@ -114,29 +134,13 @@ function timelineEvent( }; } -test('scheduler timestamp and duration presenters keep pending states visible', () => { +test('scheduler timestamp and status presenters keep pending states visible', () => { assert.equal(formatSchedulerTimestamp(null), 'Unscheduled'); - assert.equal(formatSchedulerDuration(null, 'future'), 'Pending'); - assert.equal(formatSchedulerDuration(null, 'scheduled'), 'Pending'); - assert.equal(formatSchedulerDuration(null, 'queued'), 'Pending'); - assert.equal(formatSchedulerDuration(null, 'delayed'), 'Pending'); - assert.equal(formatSchedulerDuration(null, 'running'), 'Running'); - assert.equal(formatSchedulerDuration(500, 'completed'), '500 ms'); - assert.equal(formatSchedulerDuration(1_500, 'completed'), '1.5 s'); -}); - -test('schedulerStatusClass maps run statuses to stable classes', () => { - assert.match(schedulerStatusClass('completed'), /emerald/); - assert.match(schedulerStatusClass('running'), /cyan/); - assert.match(schedulerStatusClass('future'), /amber/); - assert.match(schedulerStatusClass('scheduled'), /amber/); - assert.match(schedulerStatusClass('queued'), /amber/); - assert.match(schedulerStatusClass('delayed'), /orange/); - assert.match(schedulerStatusClass('failed'), /red/); - assert.match(schedulerStatusClass('cancelled'), /neutral/); assert.equal(formatSchedulerStatusLabel('future'), 'Future'); assert.equal(formatSchedulerStatusLabel('scheduled'), 'Scheduled'); assert.equal(formatSchedulerStatusLabel('cancelled'), 'Cancelled'); + assert.equal(formatSchedulerModelCacheState('cache_miss'), 'Model cache miss'); + assert.equal(formatSchedulerModelCacheState(null), 'Unavailable'); }); test('scheduler policy presenters keep missing dense table facts explicit', () => { @@ -169,30 +173,6 @@ test('scheduler policy presenters keep missing dense table facts explicit', () = assert.equal(formatSchedulerAcceptedDateLabel(null), 'Unassigned'); }); -test('scheduler queue and estimate presenters keep unavailable facts explicit', () => { - assert.equal(formatSchedulerQueuePosition(0), '0'); - assert.equal(formatSchedulerQueuePosition(null), 'Unassigned'); - assert.equal(formatSchedulerPriority(5), '5'); - assert.equal(formatSchedulerPriority(undefined), 'Default'); - assert.equal( - formatSchedulerEstimateLabel( - run({ - estimate_confidence: 'low', - estimated_queue_wait_ms: 1_500, - estimated_duration_ms: 2_500, - }), - ), - 'wait 1.5 s / run 2.5 s (low)', - ); - assert.equal(formatSchedulerEstimateLabel(run({ estimate_confidence: 'low' })), 'low confidence'); - assert.equal(formatSchedulerEstimateLabel(run({})), 'Unavailable'); - assert.equal(formatSchedulerEstimateDuration(null), 'Unavailable'); - assert.equal(formatSchedulerEstimateDuration(750), '750 ms'); - assert.equal(formatSchedulerEstimateDuration(1_500), '1.5 s'); - assert.equal(formatSchedulerReasonLabel('warm_session_reused'), 'warm_session_reused'); - assert.equal(formatSchedulerReasonLabel(''), 'Unavailable'); -}); - test('scheduler dependency-readiness resume presenter uses backend typed state', () => { assert.equal( schedulerRunSupportsDependencyReadinessResume( @@ -225,41 +205,6 @@ test('scheduler dependency-readiness resume presenter uses backend typed state', ); }); -test('buildSchedulerEstimateRows exposes selected-run estimate projection facts', () => { - assert.deepEqual(buildSchedulerEstimateRows(null), [ - { label: 'Confidence', value: 'Unavailable' }, - { label: 'Queue Wait', value: 'Unavailable' }, - { label: 'Run Duration', value: 'Unavailable' }, - { label: 'Model Cache', value: 'Unavailable' }, - { label: 'Policy', value: 'Unassigned', mono: true }, - { label: 'Updated', value: 'Unavailable' }, - ]); - - const rows = buildSchedulerEstimateRows({ - workflow_run_id: 'run-a', - workflow_id: 'workflow-a', - workflow_version_id: 'wfver-a', - workflow_semantic_version: '1.0.0', - scheduler_policy_id: 'policy-a', - latest_estimate_json: '{}', - estimate_confidence: 'medium', - estimated_queue_wait_ms: 1_500, - estimated_duration_ms: 2_500, - model_cache_state: 'cache_hit', - last_event_seq: 7, - last_updated_at_ms: 86_400_000, - }); - - assert.equal(rows.find((row) => row.label === 'Confidence')?.value, 'medium'); - assert.equal(rows.find((row) => row.label === 'Queue Wait')?.value, '1.5 s'); - assert.equal(rows.find((row) => row.label === 'Run Duration')?.value, '2.5 s'); - assert.equal(rows.find((row) => row.label === 'Model Cache')?.value, 'Model cache hit'); - assert.equal(rows.find((row) => row.label === 'Policy')?.value, 'policy-a'); - assert.equal(rows.find((row) => row.label === 'Updated')?.value, new Date(86_400_000).toLocaleString()); - assert.equal(formatSchedulerModelCacheState('cache_miss'), 'Model cache miss'); - assert.equal(formatSchedulerModelCacheState(null), 'Unavailable'); -}); - test('buildSchedulerRetentionSummaryRows formats typed retention projection counts', () => { const rows = buildSchedulerRetentionSummaryRows([ { retention_state: 'expired', artifact_count: 2 }, @@ -306,6 +251,7 @@ test('filterAndSortSchedulerRuns filters by status and search text', () => { const filtered = filterAndSortSchedulerRuns(runs, { search: 'caption', + statusSegment: 'all', status: 'queued', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -339,6 +285,7 @@ test('filterAndSortSchedulerRuns searches client scope facts', () => { assert.deepEqual( filterAndSortSchedulerRuns(runs, { search: 'bucket-side', + statusSegment: 'all', status: 'all', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -367,6 +314,7 @@ test('filterAndSortSchedulerRuns searches selected runtime variant facts', () => assert.deepEqual( filterAndSortSchedulerRuns(runs, { search: 'llama_cpp.cuda', + statusSegment: 'all', status: 'all', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -396,6 +344,7 @@ test('filterAndSortSchedulerRuns sorts by operational fields', () => { assert.deepEqual( filterAndSortSchedulerRuns(runs, { search: '', + statusSegment: 'all', status: 'all', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -416,6 +365,7 @@ test('filterAndSortSchedulerRuns sorts by operational fields', () => { assert.deepEqual( filterAndSortSchedulerRuns(runs, { search: '', + statusSegment: 'all', status: 'all', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -498,6 +448,7 @@ test('scheduler policy filters use explicit projection labels', () => { assert.deepEqual( filterAndSortSchedulerRuns(runs, { search: '', + statusSegment: 'all', status: 'all', schedulerPolicy: 'policy-a', retentionPolicy: 'Unassigned', @@ -612,67 +563,355 @@ test('scheduler timeline filters use typed event kind and source fields', () => ); }); -test('buildSchedulerRunListQuery sends backend-supported filters only', () => { + +// --- Redesigned layout ------------------------------------------------------- + +const ALL_STATUSES: RunListProjectionRecord['status'][] = [ + 'accepted', + 'future', + 'scheduled', + 'queued', + 'delayed', + 'running', + 'completed', + 'failed', + 'cancelled', +]; + +function localMs(hours: number, minutes: number, seconds = 0, day = 3): number { + return new Date(2026, 10, day, hours, minutes, seconds).getTime(); +} + +test('status segments agree with the picker groups and have no memory-wait bucket (WR-004)', () => { + const nowMs = localMs(20, 0); + for (const status of ALL_STATUSES) { + const record = run({ workflow_run_id: `run-${status}`, status, completed_at_ms: localMs(19, 0) }); + const [group] = groupRunsForContextPicker([record], { query: '', selectedRunId: null, nowMs }); + const segment = schedulerStatusSegmentForRun(record); + if (group.id === 'running') assert.equal(segment, 'active', status); + else if (group.id === 'queued') assert.equal(segment, 'queued', status); + else assert.equal(segment, status === 'failed' ? 'failed' : 'done', status); + } + + const pool = ALL_STATUSES.map((status) => run({ workflow_run_id: `run-${status}`, status })); assert.deepEqual( - buildSchedulerRunListQuery( - { - search: 'caption', - status: 'queued', - schedulerPolicy: 'policy-a', - retentionPolicy: 'retention-a', - client: 'client-a', - clientSession: 'session-a', - bucket: 'bucket-a', - selectedRuntime: 'runtime-a', - selectedRuntimeVariant: 'runtime_a.cuda', - selectedBackend: 'llama_cpp', - selectedDeviceClass: 'cuda', - selectedDevice: 'device-a', - selectedNetworkNode: 'network-node-a', - acceptedDate: '1970-01-02', - sort: 'workflow_asc', - }, - 250, + buildSchedulerStatusSegments(pool).map((option) => [option.value, option.label, option.count]), + [ + ['all', 'All', 9], + ['active', 'Active', 1], + ['queued', 'Queued', 5], + ['done', 'Done', 2], + ['failed', 'Failed', 1], + ], + ); + assert.deepEqual( + filterSchedulerRunsBySegment(pool, 'done').map((record) => record.status), + ['completed', 'cancelled'], + ); + assert.equal(filterSchedulerRunsBySegment(pool, 'all').length, 9); +}); + +test('groupSchedulerRuns uses the picker grouping and keeps the Sort order inside groups', () => { + const nowMs = localMs(20, 0); + const sorted = [ + run({ workflow_run_id: 'run-q3', status: 'queued', scheduler_queue_position: 3, last_updated_at_ms: localMs(19, 59) }), + run({ + workflow_run_id: 'run-delayed', + status: 'delayed', + scheduler_reason: 'needs 8 GB on cuda:0', + selected_runtime_id: null, + selected_device_id: null, + last_updated_at_ms: localMs(19, 58), + }), + run({ + workflow_run_id: 'run-live', + status: 'running', + started_at_ms: localMs(19, 30), + last_updated_at_ms: localMs(19, 57), + }), + run({ workflow_run_id: 'run-q1', status: 'queued', scheduler_queue_position: 1, last_updated_at_ms: localMs(19, 56) }), + run({ + workflow_run_id: 'run-old', + status: 'completed', + completed_at_ms: localMs(18, 0, 0, 2), + last_updated_at_ms: localMs(18, 0, 0, 2), + }), + ]; + + const groups = groupSchedulerRuns(sorted, { selectedRunId: 'run-q1', nowMs }); + + assert.deepEqual( + groups.map((group) => [group.title, group.rows.map((row) => row.runId)]), + [ + ['Running', ['run-live']], + ['Queued', ['run-q3', 'run-delayed', 'run-q1']], + ['Finished earlier', ['run-old']], + ], + ); + const queued = groups[1].rows; + assert.equal(queued[1].contextSuffix, ', needs 8 GB on cuda:0'); + assert.equal(queued[1].detail, null); + assert.equal(queued[0].contextSuffix, ', #3 in queue'); + assert.equal(queued[0].detail, 'runtime-a on device-a'); + assert.equal(queued[0].time, '19:59'); + assert.equal(queued[2].selected, true); + assert.equal(queued[0].selected, false); + assert.equal(groups[0].rows[0].detail, 'Started 19:30'); + assert.equal(groups[2].rows[0].time, 'Nov 2'); +}); + +test('row time and detail presenters stay short', () => { + const startOfToday = localMs(0, 0); + assert.equal(formatSchedulerRowTime(localMs(9, 5), startOfToday), '09:05'); + assert.equal(formatSchedulerRowTime(localMs(9, 5, 0, 1), startOfToday), 'Nov 1'); + assert.equal(formatSchedulerClockTime(localMs(9, 5, 7)), '09:05:07'); + assert.equal(schedulerRunDetailLine(run({ status: 'running', started_at_ms: null })), null); + assert.equal( + schedulerRunDetailLine(run({ status: 'queued', selected_device_id: null })), + 'runtime-a, device not assigned yet', + ); + assert.equal( + schedulerRunDetailLine(run({ status: 'queued', selected_runtime_id: null, selected_device_id: null })), + null, + ); +}); + +test('buildSchedulerQueueSummary reads run-list estimates and degrades to a count', () => { + const loaded = { loaded: true, loading: false, unreachable: false }; + assert.equal( + buildSchedulerQueueSummary([run({ status: 'queued' }), run({ status: 'delayed' })], loaded), + '2 runs waiting', + ); + assert.equal( + buildSchedulerQueueSummary( + [ + run({ status: 'running', selected_device_id: 'cuda:0' }), + run({ status: 'queued', estimated_duration_ms: 600_000, selected_device_id: 'cuda:1' }), + run({ status: 'queued', estimated_duration_ms: 420_000, selected_device_id: null }), + run({ status: 'completed', estimated_duration_ms: 999_000, selected_device_id: 'cuda:9' }), + ], + loaded, ), - { - limit: 250, - status: 'queued', - scheduler_policy_id: 'policy-a', - retention_policy_id: 'retention-a', - client_id: 'client-a', - client_session_id: 'session-a', - bucket_id: 'bucket-a', - selected_runtime_id: 'runtime-a', - selected_runtime_variant_id: 'runtime_a.cuda', - selected_backend_key: 'llama_cpp', - selected_device_class: 'cuda', - selected_device_id: 'device-a', - selected_network_node_id: 'network-node-a', - accepted_at_from_ms: 86_400_000, - accepted_at_to_ms: 172_799_999, - }, + '2 runs waiting, about 17 min of queued work on 2 devices', + ); + assert.equal( + buildSchedulerQueueSummary( + [ + run({ status: 'queued', estimated_duration_ms: 30_000, selected_device_id: null }), + run({ status: 'queued', estimated_duration_ms: null, selected_device_id: null }), + ], + loaded, + ), + '2 runs waiting, under a minute of queued work (estimated for 1 of them)', + ); + assert.equal(buildSchedulerQueueSummary([run({ status: 'queued' })], loaded), '1 run waiting'); + assert.equal(buildSchedulerQueueSummary([run({ status: 'running' })], loaded), 'No runs waiting, 1 running'); + assert.equal(buildSchedulerQueueSummary([], loaded), 'No runs waiting'); + assert.equal( + buildSchedulerQueueSummary([], { loaded: false, loading: true, unreachable: false }), + 'Loading runs', ); + assert.equal( + buildSchedulerQueueSummary([], { loaded: false, loading: false, unreachable: true }), + 'Run list unavailable, the engine did not answer', + ); +}); + +test('buildSchedulerFilterFields lists the fourteen disclosure selects with stable options', () => { + const runs = [ + run({ workflow_run_id: 'run-a', scheduler_policy_id: 'fifo' }), + run({ workflow_run_id: 'run-b', scheduler_policy_id: null }), + ]; + const filters = withSchedulerRunFilters(DEFAULT_SCHEDULER_RUN_FILTERS, { + selectedDevice: 'cuda:7', + status: 'delayed', + }); + const fields = buildSchedulerFilterFields(runs, filters); + assert.deepEqual( - buildSchedulerRunListQuery( - { - search: 'caption', - status: 'all', - schedulerPolicy: 'Unassigned', - retentionPolicy: 'all', - client: 'Unassigned', - clientSession: 'all', - bucket: 'all', - selectedRuntime: 'Unassigned', - selectedRuntimeVariant: 'Unassigned', - selectedBackend: 'Unassigned', - selectedDeviceClass: 'Unassigned', - selectedDevice: 'all', - selectedNetworkNode: 'all', - acceptedDate: 'all', - sort: 'workflow_asc', - }, - 50, + fields.map((field) => field.key), + SCHEDULER_SECONDARY_FILTER_KEYS, + ); + assert.equal(new Set(fields.map((field) => field.id)).size, 14); + const status = fields.find((field) => field.key === 'status'); + assert.equal(status?.value, 'delayed'); + assert.deepEqual(status?.options.slice(0, 2), [ + { value: 'all', label: 'All' }, + { value: 'accepted', label: 'Accepted' }, + ]); + const sort = fields.find((field) => field.key === 'sort'); + assert.deepEqual(sort?.options.map((option) => option.label), ['Updated', 'Queued', 'Duration', 'Workflow', 'Status']); + const policy = fields.find((field) => field.key === 'schedulerPolicy'); + assert.deepEqual(policy?.options.map((option) => option.value), ['all', 'Unassigned', 'fifo']); + const device = fields.find((field) => field.key === 'selectedDevice'); + assert.deepEqual(device?.options.map((option) => option.value), ['all', 'device-a', 'cuda:7']); +}); + +test('schedulerAppliedFilterChips names each non-default disclosure filter', () => { + assert.deepEqual(schedulerAppliedFilterChips(DEFAULT_SCHEDULER_RUN_FILTERS), []); + const filters = withSchedulerRunFilters(DEFAULT_SCHEDULER_RUN_FILTERS, { + search: 'ignored', + statusSegment: 'failed', + status: 'failed', + sort: 'duration_desc', + selectedNetworkNode: 'local', + }); + assert.deepEqual(schedulerAppliedFilterChips(filters), [ + { key: 'status', label: 'Status: Failed' }, + { key: 'sort', label: 'Sort: Duration' }, + { key: 'selectedNetworkNode', label: 'Network node: local' }, + ]); +}); + +test('detail presenters describe progress, placement and retention from projection facts', () => { + assert.equal( + schedulerRunProgressText(run({ status: 'running', started_at_ms: localMs(20, 1, 40) })), + 'Running since 20:01:40', + ); + assert.equal( + schedulerRunProgressText(run({ status: 'queued', scheduler_queue_position: 2, scheduler_reason: 'model cached' })), + 'Queue position 2, model cached', + ); + assert.equal(schedulerRunProgressText(run({ status: 'scheduled' })), 'Scheduled'); + assert.equal(schedulerRunProgressText(run({ status: 'delayed', scheduler_reason: 'waiting on cuda:0' })), 'Delayed: waiting on cuda:0'); + assert.equal(schedulerRunProgressText(run({ status: 'completed', duration_ms: 38_000 })), 'Finished in 38 s'); + assert.equal( + schedulerRunProgressText(run({ status: 'failed', latest_error_message: 'out of memory' })), + 'Failed: out of memory', + ); + assert.equal(schedulerRunProgressText(run({ status: 'cancelled', duration_ms: 70_000 })), 'Cancelled after 1m 10s'); + + assert.equal(schedulerRunPlacementText(run({})), 'runtime-a / runtime_a.cuda on cuda / device-a'); + assert.equal( + schedulerRunPlacementText(run({ selected_device_id: null, selected_device_class: null })), + 'runtime-a / runtime_a.cuda, device not assigned yet', + ); + assert.equal( + schedulerRunPlacementText( + run({ + selected_runtime_id: null, + selected_runtime_variant_id: null, + selected_device_id: null, + selected_device_class: null, + }), + ), + 'Not assigned to a device yet', + ); + assert.equal( + schedulerRunPolicyText(run({})), + 'Policy policy-a, bucket bucket-a, backend llama_cpp, network node network-node-a', + ); + assert.equal( + schedulerRunPolicyText( + run({ scheduler_policy_id: null, bucket_id: 'default', selected_backend_key: null, selected_network_node_id: null }), + ), + 'Bucket default', + ); + assert.equal(schedulerRetentionPolicyText(run({})), 'Retention policy retention-a'); + assert.equal(schedulerRetentionPolicyText(run({ retention_policy_id: null })), 'No retention policy recorded'); + assert.equal( + schedulerRetentionText( + [ + { retention_state: 'metadata_only', artifact_count: 1 }, + { retention_state: 'retained', artifact_count: 3 }, + ], + { loading: false, error: null }, + ), + 'Payload retained: 3, Metadata retained only: 1', + ); + assert.equal(schedulerRetentionText([], { loading: false, error: null }), 'No retained artifacts projected'); + assert.equal(schedulerRetentionText([], { loading: true, error: null }), 'Loading the artifact summary'); + assert.equal( + schedulerRetentionText([], { loading: false, error: 'Transport error: down' }), + 'Artifact summary unavailable: Transport error: down', + ); + assert.deepEqual(schedulerRunDetailChips(run({ scheduler_priority: 5, scheduler_queue_position: 1 })), [ + 'runtime-a on device-a', + 'priority 5', + '#1 in queue', + ]); + assert.deepEqual( + schedulerRunDetailChips(run({ selected_runtime_id: null, selected_device_id: null, scheduler_priority: 0 })), + [], + ); +}); + +test('schedulerEstimateSentence reads the estimate query and says when it is missing', () => { + const estimate = { + workflow_run_id: 'run-a', + workflow_id: 'workflow-a', + estimate_confidence: 'high', + estimated_queue_wait_ms: 40_000, + estimated_duration_ms: 360_000, + model_cache_state: 'cache_hit' as const, + last_event_seq: 3, + last_updated_at_ms: 1, + }; + assert.equal( + schedulerEstimateSentence(estimate, { loading: false, error: null }), + 'About 40 s queue wait, about 6m 00s to run, high confidence. Model cache hit.', + ); + assert.equal( + schedulerEstimateSentence( + { ...estimate, estimated_queue_wait_ms: null, estimated_duration_ms: null, estimate_confidence: null, model_cache_state: 'unknown' }, + { loading: false, error: null }, ), - { limit: 50 }, + 'No duration estimate.', + ); + assert.equal(schedulerEstimateSentence(null, { loading: false, error: null }), 'No scheduler estimate for this run'); + assert.equal(schedulerEstimateSentence(null, { loading: true, error: null }), 'Loading the scheduler estimate'); + assert.equal( + schedulerEstimateSentence(estimate, { loading: false, error: 'Internal error: boom' }), + 'Estimate unavailable: Internal error: boom', + ); +}); + +test('footer state and unavailable reasons keep every action reachable but honest', () => { + assert.deepEqual(schedulerFooterState(null, null), { kind: 'none' }); + assert.deepEqual(schedulerFooterState('run-x', null), { kind: 'missing' }); + assert.deepEqual(schedulerFooterState('run-a', run({ status: 'failed' })), { + kind: 'finished', + workflowId: 'workflow-a', + }); + const queued = run({ status: 'queued' }); + assert.deepEqual(schedulerFooterState('run-a', queued), { kind: 'live', run: queued }); + assert.equal(schedulerFooterState('run-a', run({ status: 'running' })).kind, 'live'); + + assert.equal(schedulerQueueControlsUnavailableReason(queued), null); + assert.match(schedulerQueueControlsUnavailableReason(run({ status: 'running' })) ?? '', /only while a run is queued/); + assert.match( + schedulerQueueControlsUnavailableReason(run({ status: 'queued', workflow_execution_session_id: null })) ?? '', + /GUI admin actions under More actions/, + ); + assert.equal(schedulerAdminControlsUnavailableReason(run({ status: 'delayed', workflow_execution_session_id: null })), null); + assert.match(schedulerAdminControlsUnavailableReason(run({ status: 'running' })) ?? '', /queued or delayed/); + assert.equal( + schedulerResumeUnavailableReason(run({ workflow_execution_session_resume_state: 'dependency_readiness_pending' })), + null, + ); + assert.match(schedulerResumeUnavailableReason(run({})) ?? '', /dependency readiness/); +}); + +test('timeline helpers summarise attempts and projection freshness', () => { + assert.equal(schedulerTimelineAttemptText(timelineEvent({})), null); + assert.equal( + schedulerTimelineAttemptText( + timelineEvent({ scheduler_attempt_id: 'attempt-1', scheduler_attempt_device_id: 'cuda:0' }), + ), + 'Attempt attempt-1 · Device cuda:0', + ); + assert.equal( + schedulerDetailFreshnessText({ + timeline: { + projection_name: 'scheduler_timeline', + projection_version: 1, + last_applied_event_seq: 41, + status: 'current', + updated_at_ms: 1, + }, + estimate: null, + retention: null, + }), + 'Timeline current at seq 41; estimate projection unavailable; artifacts projection unavailable', ); }); diff --git a/src/components/workbench/schedulerPagePresenters.ts b/src/components/workbench/schedulerPagePresenters.ts index b00686b0c..5cb6cdafe 100644 --- a/src/components/workbench/schedulerPagePresenters.ts +++ b/src/components/workbench/schedulerPagePresenters.ts @@ -4,11 +4,29 @@ import type { ProjectionStateRecord, RunListProjectionRecord, WorkflowSchedulerEstimateRecord, - WorkflowRunListQueryRequest, SchedulerTimelineProjectionRecord, } from '../../services/diagnostics/types'; -import type { SchedulerRunFilters, SchedulerSortKey } from '../../stores/schedulerRunListStore'; +import { + DEFAULT_SCHEDULER_RUN_FILTERS, + SCHEDULER_SECONDARY_FILTER_KEYS, + SCHEDULER_SORT_OPTIONS, + SCHEDULER_STATUS_FILTERS, + SCHEDULER_STATUS_SEGMENTS, + type SchedulerRunFilters, + type SchedulerSecondaryFilterKey, + type SchedulerSortKey, + type SchedulerStatusSegment, +} from '../../stores/schedulerRunListStore.ts'; import { formatProjectionFreshnessState } from './projectionFreshness.ts'; +import { + formatClockTime, + formatRunDuration, + groupRunsForContextPicker, + startOfLocalDayMs, + type RunContextGroupId, + type RunContextRow, +} from './shell/runContextPicker.ts'; +import type { SegmentOption } from './ui/types.ts'; export function formatSchedulerTimestamp(value: number | null | undefined): string { if (!value) { @@ -17,61 +35,6 @@ export function formatSchedulerTimestamp(value: number | null | undefined): stri return new Date(value).toLocaleString(); } -export function formatSchedulerDuration( - value: number | null | undefined, - status: RunListProjectionRecord['status'], -): string { - if (value === null || value === undefined) { - if (status === 'running') { - return 'Running'; - } - if ( - status === 'future' || - status === 'scheduled' || - status === 'queued' || - status === 'accepted' || - status === 'delayed' - ) { - return 'Pending'; - } - return 'Unavailable'; - } - if (value < 1_000) { - return `${Math.round(value)} ms`; - } - return `${(value / 1_000).toFixed(1)} s`; -} - -export function formatSchedulerQueuePosition(value: number | null | undefined): string { - if (value === null || value === undefined) { - return 'Unassigned'; - } - return String(value); -} - -export function formatSchedulerPriority(value: number | null | undefined): string { - if (value === null || value === undefined) { - return 'Default'; - } - return String(value); -} - -export function formatSchedulerEstimateLabel(run: RunListProjectionRecord): string { - const parts = [ - run.estimated_queue_wait_ms === null || run.estimated_queue_wait_ms === undefined - ? null - : `wait ${formatSchedulerDuration(run.estimated_queue_wait_ms, run.status)}`, - run.estimated_duration_ms === null || run.estimated_duration_ms === undefined - ? null - : `run ${formatSchedulerDuration(run.estimated_duration_ms, run.status)}`, - ].filter((part): part is string => part !== null); - if (parts.length === 0) { - return run.estimate_confidence ? `${run.estimate_confidence} confidence` : 'Unavailable'; - } - const confidence = run.estimate_confidence ? ` (${run.estimate_confidence})` : ''; - return `${parts.join(' / ')}${confidence}`; -} - export function formatSchedulerModelCacheState( state: RunListProjectionRecord['model_cache_state'] | WorkflowSchedulerEstimateRecord['model_cache_state'], ): string { @@ -100,50 +63,11 @@ export function formatSchedulerModelCacheState( } } -export interface SchedulerEstimateFactRow { - label: string; - value: string; - mono?: boolean; -} - export interface SchedulerRetentionSummaryRow { label: string; count: number; } -export function buildSchedulerEstimateRows( - estimate: WorkflowSchedulerEstimateRecord | null | undefined, -): SchedulerEstimateFactRow[] { - if (!estimate) { - return [ - { label: 'Confidence', value: 'Unavailable' }, - { label: 'Queue Wait', value: 'Unavailable' }, - { label: 'Run Duration', value: 'Unavailable' }, - { label: 'Model Cache', value: 'Unavailable' }, - { label: 'Policy', value: 'Unassigned', mono: true }, - { label: 'Updated', value: 'Unavailable' }, - ]; - } - return [ - { label: 'Confidence', value: estimate.estimate_confidence ?? 'Unavailable' }, - { label: 'Queue Wait', value: formatSchedulerEstimateDuration(estimate.estimated_queue_wait_ms) }, - { label: 'Run Duration', value: formatSchedulerEstimateDuration(estimate.estimated_duration_ms) }, - { label: 'Model Cache', value: formatSchedulerModelCacheState(estimate.model_cache_state) }, - { label: 'Policy', value: formatSchedulerPolicyLabel(estimate.scheduler_policy_id), mono: true }, - { label: 'Updated', value: formatSchedulerTimestamp(estimate.last_updated_at_ms) }, - ]; -} - -export function formatSchedulerEstimateDuration(value: number | null | undefined): string { - if (value === null || value === undefined) { - return 'Unavailable'; - } - if (value < 1_000) { - return `${Math.round(value)} ms`; - } - return `${(value / 1_000).toFixed(1)} s`; -} - export function buildSchedulerRetentionSummaryRows( summary: IoArtifactRetentionSummaryRecord[], ): SchedulerRetentionSummaryRow[] { @@ -174,10 +98,6 @@ export function formatSchedulerRetentionStateLabel(retentionState: IoArtifactRet } } -export function formatSchedulerReasonLabel(value: string | null | undefined): string { - return value && value.trim().length > 0 ? value : 'Unavailable'; -} - export function formatSchedulerStatusLabel(status: RunListProjectionRecord['status']): string { switch (status) { case 'accepted': @@ -210,26 +130,6 @@ export function schedulerRunSupportsDependencyReadinessResume( ); } -export function schedulerStatusClass(status: RunListProjectionRecord['status']): string { - switch (status) { - case 'completed': - return 'border-emerald-700 bg-emerald-950/60 text-emerald-200'; - case 'running': - return 'border-cyan-700 bg-cyan-950/60 text-cyan-200'; - case 'queued': - case 'accepted': - case 'future': - case 'scheduled': - return 'border-amber-700 bg-amber-950/60 text-amber-200'; - case 'delayed': - return 'border-orange-700 bg-orange-950/60 text-orange-200'; - case 'failed': - return 'border-red-700 bg-red-950/60 text-red-200'; - case 'cancelled': - return 'border-neutral-700 bg-neutral-900 text-neutral-300'; - } -} - export function formatSchedulerProjectionFreshness(state: ProjectionStateRecord | null): string { return formatProjectionFreshnessState(state); } @@ -542,55 +442,6 @@ export function filterAndSortSchedulerRuns( return [...filtered].sort((left, right) => compareSchedulerRuns(left, right, filters.sort)); } -export function buildSchedulerRunListQuery( - filters: SchedulerRunFilters, - limit: number, -): WorkflowRunListQueryRequest { - const request: WorkflowRunListQueryRequest = { limit }; - if (filters.status !== 'all') { - request.status = filters.status; - } - if (isAssignedFilterValue(filters.schedulerPolicy)) { - request.scheduler_policy_id = filters.schedulerPolicy; - } - if (isAssignedFilterValue(filters.retentionPolicy)) { - request.retention_policy_id = filters.retentionPolicy; - } - if (isAssignedFilterValue(filters.client)) { - request.client_id = filters.client; - } - if (isAssignedFilterValue(filters.clientSession)) { - request.client_session_id = filters.clientSession; - } - if (isAssignedFilterValue(filters.bucket)) { - request.bucket_id = filters.bucket; - } - if (isAssignedFilterValue(filters.selectedRuntime)) { - request.selected_runtime_id = filters.selectedRuntime; - } - if (isAssignedFilterValue(filters.selectedRuntimeVariant)) { - request.selected_runtime_variant_id = filters.selectedRuntimeVariant; - } - if (isAssignedFilterValue(filters.selectedBackend)) { - request.selected_backend_key = filters.selectedBackend; - } - if (isAssignedFilterValue(filters.selectedDeviceClass)) { - request.selected_device_class = filters.selectedDeviceClass; - } - if (isAssignedFilterValue(filters.selectedDevice)) { - request.selected_device_id = filters.selectedDevice; - } - if (isAssignedFilterValue(filters.selectedNetworkNode)) { - request.selected_network_node_id = filters.selectedNetworkNode; - } - const acceptedRange = schedulerAcceptedDateRange(filters.acceptedDate); - if (acceptedRange) { - request.accepted_at_from_ms = acceptedRange.fromMs; - request.accepted_at_to_ms = acceptedRange.toMs; - } - return request; -} - function uniqueSortedOptions(values: string[]): string[] { return [...new Set(values)].sort(compareFilterOptions); } @@ -605,24 +456,6 @@ function compareFilterOptions(left: string, right: string): number { return compareStrings(left, right); } -function isAssignedFilterValue(value: string): boolean { - return value !== 'all' && value !== 'Unassigned'; -} - -function schedulerAcceptedDateRange(value: string): { fromMs: number; toMs: number } | null { - if (!isAssignedFilterValue(value)) { - return null; - } - const fromMs = Date.parse(`${value}T00:00:00.000Z`); - if (!Number.isFinite(fromMs)) { - return null; - } - return { - fromMs, - toMs: fromMs + 86_400_000 - 1, - }; -} - function schedulerRunMatchesSearch(run: RunListProjectionRecord, search: string): boolean { return [ run.workflow_run_id, @@ -667,3 +500,452 @@ function compareSchedulerRuns( function compareStrings(left: string, right: string): number { return left.localeCompare(right); } + +// --------------------------------------------------------------------------- +// Redesigned Scheduler layout (docs/design/workbench-redesign-spec.md, +// "Scheduler"). Input is the shell's run-list projection; grouping and row +// decoration come from the run-context picker helpers so the list and the +// header picker always agree (issues WR-004, WR-005). +// --------------------------------------------------------------------------- + +const SCHEDULER_STATUS_SEGMENT_LABELS: Record = { + all: 'All', + active: 'Active', + queued: 'Queued', + done: 'Done', + failed: 'Failed', +}; + +/** + * Status segment of a run. There is no memory-wait status in the run-list + * projection (WR-004), so Active holds running runs only and delayed runs + * count as Queued, matching the picker's Queued group. + */ +export function schedulerStatusSegmentForRun( + run: Pick, +): Exclude { + switch (run.status) { + case 'running': + return 'active'; + case 'accepted': + case 'future': + case 'scheduled': + case 'queued': + case 'delayed': + return 'queued'; + case 'completed': + case 'cancelled': + return 'done'; + case 'failed': + return 'failed'; + } +} + +export function filterSchedulerRunsBySegment( + runs: readonly RunListProjectionRecord[], + segment: SchedulerStatusSegment, +): RunListProjectionRecord[] { + return segment === 'all' ? [...runs] : runs.filter((run) => schedulerStatusSegmentForRun(run) === segment); +} + +/** Segment buttons with counts over `pool` (the runs left after every other filter). */ +export function buildSchedulerStatusSegments( + pool: readonly RunListProjectionRecord[], +): SegmentOption[] { + const counts: Record = { all: pool.length, active: 0, queued: 0, done: 0, failed: 0 }; + for (const run of pool) counts[schedulerStatusSegmentForRun(run)] += 1; + return SCHEDULER_STATUS_SEGMENTS.map((segment) => ({ + value: segment, + label: SCHEDULER_STATUS_SEGMENT_LABELS[segment], + count: counts[segment], + })); +} + +export interface SchedulerRunRow extends RunContextRow { + /** Right-hand time: HH:MM today, otherwise a short date. */ + time: string; + timeTitle: string; + /** Second sub-line: start time for running runs, placement otherwise. */ + detail: string | null; +} + +export interface SchedulerRunGroup { + id: RunContextGroupId; + title: string; + rows: SchedulerRunRow[]; +} + +const SHORT_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +export function formatSchedulerRowTime(ms: number, startOfTodayMs: number): string { + if (ms >= startOfTodayMs) return formatClockTime(ms); + const date = new Date(ms); + return `${SHORT_MONTHS[date.getMonth()]} ${date.getDate()}`; +} + +/** Local wall-clock time as HH:MM:SS, for timeline rows. */ +export function formatSchedulerClockTime(ms: number): string { + const date = new Date(ms); + return [date.getHours(), date.getMinutes(), date.getSeconds()] + .map((part) => String(part).padStart(2, '0')) + .join(':'); +} + +/** "llama.cpp on cuda:0", "llama.cpp, device not assigned yet", or null when nothing is placed. */ +export function schedulerRunPlacementSummary( + run: Pick, +): string | null { + const runtime = run.selected_runtime_id?.trim(); + const device = run.selected_device_id?.trim(); + if (runtime && device) return `${runtime} on ${device}`; + if (runtime) return `${runtime}, device not assigned yet`; + if (device) return `on ${device}`; + return null; +} + +export function schedulerRunDetailLine(run: RunListProjectionRecord): string | null { + if (run.status === 'running') { + // The picker's context for running runs is already the placement. + return typeof run.started_at_ms === 'number' ? `Started ${formatClockTime(run.started_at_ms)}` : null; + } + return schedulerRunPlacementSummary(run); +} + +/** + * Group already filtered and sorted runs the way the header picker does + * (Running, Queued, Finished today, Finished earlier). Inside each group the + * order of `sortedRuns` (the Sort filter) is kept. + */ +export function groupSchedulerRuns( + sortedRuns: readonly RunListProjectionRecord[], + options: { selectedRunId: string | null; nowMs: number }, +): SchedulerRunGroup[] { + const order = new Map(sortedRuns.map((run, index) => [run.workflow_run_id, index])); + const position = (row: RunContextRow) => order.get(row.runId) ?? Number.MAX_SAFE_INTEGER; + const startOfToday = startOfLocalDayMs(options.nowMs); + return groupRunsForContextPicker(sortedRuns, { + query: '', + selectedRunId: options.selectedRunId, + nowMs: options.nowMs, + }).map((group) => ({ + id: group.id, + title: group.title, + rows: [...group.rows] + .sort((left, right) => position(left) - position(right)) + .map((row) => ({ + ...row, + time: formatSchedulerRowTime(row.record.last_updated_at_ms, startOfToday), + timeTitle: `Updated ${formatSchedulerTimestamp(row.record.last_updated_at_ms)}`, + detail: schedulerRunDetailLine(row.record), + })), + })); +} + +function formatWorkMinutes(ms: number): string { + if (ms < 60_000) return 'under a minute'; + return `about ${Math.round(ms / 60_000)} min`; +} + +function plural(count: number, one: string, many: string): string { + return `${count} ${count === 1 ? one : many}`; +} + +/** + * The dimension line: "N runs waiting, about M min of queued work on D + * devices". Minutes come from the scheduler estimate facts carried on each + * run-list record (`estimated_duration_ms`); without any estimate the line is + * the count alone. + */ +export function buildSchedulerQueueSummary( + runs: readonly RunListProjectionRecord[], + list: { loaded: boolean; loading: boolean; unreachable: boolean }, +): string { + if (!list.loaded) { + if (list.unreachable) return 'Run list unavailable, the engine did not answer'; + return list.loading ? 'Loading runs' : 'Run list unavailable'; + } + const waiting = runs.filter((run) => schedulerStatusSegmentForRun(run) === 'queued'); + if (waiting.length === 0) { + const running = runs.filter((run) => run.status === 'running').length; + return running > 0 ? `No runs waiting, ${running} running` : 'No runs waiting'; + } + const count = plural(waiting.length, 'run waiting', 'runs waiting'); + const estimated = waiting.filter( + (run) => typeof run.estimated_duration_ms === 'number' && run.estimated_duration_ms >= 0, + ); + if (estimated.length === 0) return count; + const totalMs = estimated.reduce((sum, run) => sum + (run.estimated_duration_ms ?? 0), 0); + const coverage = estimated.length < waiting.length ? ` (estimated for ${estimated.length} of them)` : ''; + const devices = new Set( + runs + .filter((run) => run.status === 'running' || schedulerStatusSegmentForRun(run) === 'queued') + .map((run) => run.selected_device_id?.trim()) + .filter((device): device is string => Boolean(device)), + ); + const onDevices = devices.size > 0 ? ` on ${plural(devices.size, 'device', 'devices')}` : ''; + return `${count}, ${formatWorkMinutes(totalMs)} of queued work${onDevices}${coverage}`; +} + +// --- Filters disclosure ----------------------------------------------------- + +export interface SchedulerFilterOption { + value: string; + label: string; +} + +export interface SchedulerFilterField { + key: SchedulerSecondaryFilterKey; + /** DOM id of the select, stable across renders. */ + id: string; + label: string; + value: string; + options: SchedulerFilterOption[]; +} + +const SCHEDULER_FILTER_LABELS: Record = { + status: 'Status', + sort: 'Sort', + schedulerPolicy: 'Policy', + retentionPolicy: 'Retention', + client: 'Client', + clientSession: 'Session', + bucket: 'Bucket', + selectedRuntime: 'Runtime', + selectedRuntimeVariant: 'Runtime variant', + selectedBackend: 'Backend', + selectedDeviceClass: 'Device class', + selectedDevice: 'Device', + selectedNetworkNode: 'Network node', + acceptedDate: 'Accepted', +}; + +type SchedulerOptionFilterKey = Exclude; + +const SCHEDULER_FILTER_OPTION_SOURCES: Record string[]> = { + schedulerPolicy: schedulerPolicyFilterOptions, + retentionPolicy: schedulerRetentionFilterOptions, + client: schedulerClientFilterOptions, + clientSession: schedulerClientSessionFilterOptions, + bucket: schedulerBucketFilterOptions, + selectedRuntime: schedulerSelectedRuntimeFilterOptions, + selectedRuntimeVariant: schedulerSelectedRuntimeVariantFilterOptions, + selectedBackend: schedulerSelectedBackendFilterOptions, + selectedDeviceClass: schedulerSelectedDeviceClassFilterOptions, + selectedDevice: schedulerSelectedDeviceFilterOptions, + selectedNetworkNode: schedulerSelectedNetworkNodeFilterOptions, + acceptedDate: schedulerAcceptedDateFilterOptions, +}; + +function schedulerFilterValueLabel(key: SchedulerSecondaryFilterKey, value: string): string { + if (value === 'all') return 'All'; + if (key === 'status') return formatSchedulerStatusLabel(value as RunListProjectionRecord['status']); + if (key === 'sort') return SCHEDULER_SORT_OPTIONS.find((option) => option.value === value)?.label ?? value; + return value; +} + +/** + * The fourteen selects of the Filters disclosure, in display order. Options + * come from the loaded runs; an applied value that no loaded run carries any + * more stays listed so the select still shows it. + */ +export function buildSchedulerFilterFields( + runs: RunListProjectionRecord[], + filters: SchedulerRunFilters, +): SchedulerFilterField[] { + return SCHEDULER_SECONDARY_FILTER_KEYS.map((key) => { + const value = filters[key]; + let values: string[]; + if (key === 'status') values = [...SCHEDULER_STATUS_FILTERS]; + else if (key === 'sort') values = SCHEDULER_SORT_OPTIONS.map((option) => option.value); + else { + values = ['all', ...SCHEDULER_FILTER_OPTION_SOURCES[key](runs)]; + if (!values.includes(value)) values.push(value); + } + return { + key, + id: `scheduler-filter-${key}`, + label: SCHEDULER_FILTER_LABELS[key], + value, + options: values.map((option) => ({ value: option, label: schedulerFilterValueLabel(key, option) })), + }; + }); +} + +export interface SchedulerAppliedFilterChip { + key: SchedulerSecondaryFilterKey; + label: string; +} + +/** One chip per disclosure filter that differs from its default. */ +export function schedulerAppliedFilterChips(filters: SchedulerRunFilters): SchedulerAppliedFilterChip[] { + return SCHEDULER_SECONDARY_FILTER_KEYS.filter((key) => filters[key] !== DEFAULT_SCHEDULER_RUN_FILTERS[key]).map( + (key) => ({ key, label: `${SCHEDULER_FILTER_LABELS[key]}: ${schedulerFilterValueLabel(key, filters[key])}` }), + ); +} + +// --- Detail panel ------------------------------------------------------------- + +/** First line of the Progress cell, from run-list facts only. */ +export function schedulerRunProgressText(run: RunListProjectionRecord): string { + const reason = run.scheduler_reason?.trim(); + const duration = formatRunDuration(run.duration_ms); + switch (run.status) { + case 'running': + return typeof run.started_at_ms === 'number' + ? `Running since ${formatSchedulerClockTime(run.started_at_ms)}` + : 'Running'; + case 'accepted': + case 'future': + case 'scheduled': + case 'queued': { + const head = typeof run.scheduler_queue_position === 'number' + ? `Queue position ${run.scheduler_queue_position}` + : formatSchedulerStatusLabel(run.status); + return reason ? `${head}, ${reason}` : head; + } + case 'delayed': + return reason ? `Delayed: ${reason}` : 'Delayed by the scheduler'; + case 'completed': + return duration ? `Finished in ${duration}` : 'Finished'; + case 'failed': { + const error = run.latest_error_message?.trim() || run.latest_error_code?.trim(); + return error ? `Failed: ${error}` : 'Failed'; + } + case 'cancelled': + return duration ? `Cancelled after ${duration}` : 'Cancelled'; + } +} + +/** Second line of the Progress cell, from the selected run's scheduler estimate query. */ +export function schedulerEstimateSentence( + estimate: WorkflowSchedulerEstimateRecord | null, + state: { loading: boolean; error: string | null }, +): string { + if (state.error) return `Estimate unavailable: ${state.error}`; + if (!estimate) return state.loading ? 'Loading the scheduler estimate' : 'No scheduler estimate for this run'; + const wait = formatRunDuration(estimate.estimated_queue_wait_ms); + const run = formatRunDuration(estimate.estimated_duration_ms); + const parts = [wait ? `about ${wait} queue wait` : null, run ? `about ${run} to run` : null].filter( + (part): part is string => part !== null, + ); + let sentence = parts.length > 0 ? parts.join(', ') : 'no duration estimate'; + if (estimate.estimate_confidence) sentence += `, ${estimate.estimate_confidence} confidence`; + sentence = `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}.`; + if (estimate.model_cache_state && estimate.model_cache_state !== 'unknown') { + sentence += ` ${formatSchedulerModelCacheState(estimate.model_cache_state)}.`; + } + return sentence; +} + +export function schedulerRunPlacementText(run: RunListProjectionRecord): string { + const runtime = formatSchedulerRuntimePlacementLabel(run); + const device = formatSchedulerDevicePlacementLabel(run); + if (runtime === 'Unassigned' && device === 'Unassigned') return 'Not assigned to a device yet'; + if (device === 'Unassigned') return `${runtime}, device not assigned yet`; + if (runtime === 'Unassigned') return `On ${device}`; + return `${runtime} on ${device}`; +} + +export function schedulerRunPolicyText(run: RunListProjectionRecord): string { + const parts = [ + run.scheduler_policy_id ? `Policy ${run.scheduler_policy_id}` : null, + run.bucket_id ? `bucket ${run.bucket_id}` : null, + run.selected_backend_key ? `backend ${run.selected_backend_key}` : null, + run.selected_network_node_id ? `network node ${run.selected_network_node_id}` : null, + ].filter((part): part is string => part !== null); + if (parts.length === 0) return 'No policy, bucket or backend recorded'; + const text = parts.join(', '); + return `${text.charAt(0).toUpperCase()}${text.slice(1)}`; +} + +export function schedulerRetentionText( + summary: IoArtifactRetentionSummaryRecord[], + state: { loading: boolean; error: string | null }, +): string { + if (state.error) return `Artifact summary unavailable: ${state.error}`; + const rows = buildSchedulerRetentionSummaryRows(summary); + if (rows.length === 0) return state.loading ? 'Loading the artifact summary' : 'No retained artifacts projected'; + return rows.map((row) => `${row.label}: ${row.count}`).join(', '); +} + +export function schedulerRetentionPolicyText(run: Pick): string { + return run.retention_policy_id ? `Retention policy ${run.retention_policy_id}` : 'No retention policy recorded'; +} + +/** Chips after the status chip: placement, priority, queue position. */ +export function schedulerRunDetailChips(run: RunListProjectionRecord): string[] { + const chips: string[] = []; + const placement = schedulerRunPlacementSummary(run); + if (placement) chips.push(placement); + if (typeof run.scheduler_priority === 'number' && run.scheduler_priority !== 0) { + chips.push(`priority ${run.scheduler_priority}`); + } + if (typeof run.scheduler_queue_position === 'number') chips.push(`#${run.scheduler_queue_position} in queue`); + return chips; +} + +export function schedulerTimelineAttemptText( + event: Parameters[0], +): string | null { + const rows = buildSchedulerTimelineAttemptRows(event); + return rows.length > 0 ? rows.map((row) => `${row.label} ${row.value}`).join(' · ') : null; +} + +function lowerFirst(text: string): string { + return `${text.charAt(0).toLowerCase()}${text.slice(1)}`; +} + +/** One muted line naming how fresh each detail projection is (ADR-014 guardrail). */ +export function schedulerDetailFreshnessText(states: { + timeline: ProjectionStateRecord | null; + estimate: ProjectionStateRecord | null; + retention: ProjectionStateRecord | null; +}): string { + return [ + `Timeline ${lowerFirst(formatProjectionFreshnessState(states.timeline))}`, + `estimate ${lowerFirst(formatProjectionFreshnessState(states.estimate))}`, + `artifacts ${lowerFirst(formatProjectionFreshnessState(states.retention))}`, + ].join('; '); +} + +// --- Footer ----------------------------------------------------------------- + +export type SchedulerFooterState = + | { kind: 'none' } + | { kind: 'missing' } + | { kind: 'finished'; workflowId: string } + | { kind: 'live'; run: RunListProjectionRecord }; + +/** + * What the run panel footer offers. `missing` is an active run that is not in + * the loaded run list (selected elsewhere, or older than the list window). + */ +export function schedulerFooterState( + activeRunId: string | null, + run: RunListProjectionRecord | null, +): SchedulerFooterState { + if (!activeRunId) return { kind: 'none' }; + if (!run) return { kind: 'missing' }; + const segment = schedulerStatusSegmentForRun(run); + if (segment === 'done' || segment === 'failed') return { kind: 'finished', workflowId: run.workflow_id }; + return { kind: 'live', run }; +} + +/** Why the session queue actions (Cancel, Front, Priority) are unavailable, or null when they apply. */ +export function schedulerQueueControlsUnavailableReason(run: RunListProjectionRecord | null): string | null { + if (schedulerRunSupportsQueueControls(run)) return null; + if (!run || (run.status !== 'queued' && run.status !== 'delayed')) { + return 'The scheduler accepts cancel, front and priority changes only while a run is queued or delayed.'; + } + return 'This run has no workflow execution session. The GUI admin actions under More actions act on it by run id.'; +} + +export function schedulerAdminControlsUnavailableReason(run: RunListProjectionRecord | null): string | null { + if (schedulerRunSupportsAdminQueueControls(run)) return null; + return 'GUI admin actions apply only while a run is queued or delayed.'; +} + +export function schedulerResumeUnavailableReason(run: RunListProjectionRecord | null): string | null { + if (schedulerRunSupportsDependencyReadinessResume(run)) return null; + return 'Resume applies only to a session run waiting on runtime dependency readiness.'; +} diff --git a/src/components/workbench/sessionsPresenters.test.ts b/src/components/workbench/sessionsPresenters.test.ts new file mode 100644 index 000000000..dc03b8911 --- /dev/null +++ b/src/components/workbench/sessionsPresenters.test.ts @@ -0,0 +1,377 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import type { RunListProjectionRecord, RunListProjectionStatus } from '../../services/diagnostics/types'; +import type { WorkflowMetadata } from '../../services/workflow/types'; +import type { OrchestrationGraphMetadata } from '../../stores/orchestrationStore'; +import { + ACTIVE_SESSIONS_UNAVAILABLE_NOTE, + SESSION_RECENT_RUN_LIMIT, + buildSavedSessions, + createLatestOnlyGate, + buildSessionDetail, + countRunOutcomes, + formatLastActivityShort, + formatSessionDateTime, + formatSessionDay, + groupSessions, + lastActivityOf, + outcomeStrip, + outcomeSummaryText, + parseMetadataDate, + runOutcomeKind, + runsForWorkflow, + savedWorkflowId, + schedulerSearchForSession, + sessionFilterOptions, + sessionSourceFromResult, + sessionsDimensionLine, + sessionDetailEmptyText, + savedSourceFailure, + workflowSessionEntry, + orchestrationSessionEntry, + type SessionSourceState, +} from './sessionsPresenters.ts'; + +// Local-time constructors keep the date wording independent of the test machine's zone. +const NOW = new Date(2026, 10, 3, 20, 6, 0).getTime(); +const TODAY_1928 = new Date(2026, 10, 3, 19, 28, 0).getTime(); +const OCT_31_1402 = new Date(2026, 9, 31, 14, 2, 0).getTime(); +const JAN_31_2025 = new Date(2025, 0, 31, 9, 5, 0).getTime(); + +function run( + id: string, + workflowId: string, + status: RunListProjectionStatus, + updatedMs: number, + extra: Partial = {}, +): RunListProjectionRecord { + return { + workflow_run_id: id, + workflow_id: workflowId, + status, + last_event_seq: 1, + last_updated_at_ms: updatedMs, + ...extra, + }; +} + +function workflow(id: string, extra: Partial = {}): WorkflowMetadata { + return { + id, + name: id, + created: new Date(OCT_31_1402).toISOString(), + modified: new Date(OCT_31_1402).toISOString(), + ...extra, + }; +} + +function ready(items: T[]): SessionSourceState { + return { status: 'ready', items }; +} + +const RUNS: RunListProjectionRecord[] = [ + run('run_a1', 'ingest-docs-rag', 'running', NOW - 10_000, { client_id: 'client_gui', client_session_id: 'cs_1', workflow_semantic_version: '1.4.0', selected_device_id: 'cuda:0' }), + run('run_a2', 'ingest-docs-rag', 'queued', NOW - 20_000, { scheduler_queue_position: 2, client_id: 'client_gui', client_session_id: 'cs_2', workflow_semantic_version: '1.4.0' }), + run('run_a3', 'ingest-docs-rag', 'completed', NOW - 600_000, { client_id: 'client_cli', workflow_semantic_version: '1.3.9' }), + run('run_a4', 'ingest-docs-rag', 'failed', NOW - 900_000, { workflow_semantic_version: '1.3.9' }), + run('run_b1', 'summarize-daily', 'completed', TODAY_1928), + run('run_b2', 'summarize-daily', 'cancelled', TODAY_1928 - 60_000), + run('run_x1', 'not-saved-anywhere', 'delayed', NOW - 5_000), +]; + +test('runOutcomeKind folds projection statuses into the five strip kinds', () => { + assert.equal(runOutcomeKind('running'), 'running'); + for (const status of ['accepted', 'future', 'scheduled', 'queued', 'delayed'] as const) { + assert.equal(runOutcomeKind(status), 'queued', status); + } + assert.equal(runOutcomeKind('completed'), 'succeeded'); + assert.equal(runOutcomeKind('failed'), 'failed'); + assert.equal(runOutcomeKind('cancelled'), 'cancelled'); +}); + +test('outcome strip keeps board order, omits empty kinds and sums to the total', () => { + const counts = countRunOutcomes([ + { status: 'completed' }, + { status: 'failed' }, + { status: 'running' }, + { status: 'delayed' }, + { status: 'completed' }, + { status: 'running' }, + ]); + assert.deepEqual(counts, { running: 2, queued: 1, succeeded: 2, failed: 1, cancelled: 0, total: 6 }); + assert.deepEqual(outcomeStrip(counts), [ + { kind: 'running', count: 2 }, + { kind: 'queued', count: 1 }, + { kind: 'succeeded', count: 2 }, + { kind: 'failed', count: 1 }, + ]); + assert.equal(outcomeSummaryText(counts), '2 running, 1 queued, 2 succeeded, 1 failed'); + assert.deepEqual(outcomeStrip(countRunOutcomes([])), []); + assert.equal(outcomeSummaryText(countRunOutcomes([])), 'no runs'); +}); + +test('runsForWorkflow matches the exact workflow id and orders newest first', () => { + const rows = runsForWorkflow([...RUNS, run('run_a0', 'ingest-docs-rag-v2', 'completed', NOW)], 'ingest-docs-rag'); + assert.deepEqual(rows.map((row) => row.workflow_run_id), ['run_a1', 'run_a2', 'run_a3', 'run_a4']); +}); + +test('metadata dates parse RFC 3339 and reject junk', () => { + assert.equal(parseMetadataDate('2026-10-31T14:02:00Z'), Date.UTC(2026, 9, 31, 14, 2, 0)); + assert.equal(parseMetadataDate('not a date'), null); + assert.equal(parseMetadataDate(''), null); + assert.equal(parseMetadataDate(undefined), null); +}); + +test('date wording: today, this year, other years', () => { + assert.equal(formatSessionDateTime(TODAY_1928, NOW), 'Today 19:28'); + assert.equal(formatSessionDateTime(OCT_31_1402, NOW), 'Oct 31, 14:02'); + assert.equal(formatSessionDateTime(JAN_31_2025, NOW), 'Jan 31, 2025, 09:05'); + assert.equal(formatSessionDay(OCT_31_1402, NOW), 'Oct 31'); + assert.equal(formatSessionDay(JAN_31_2025, NOW), 'Jan 31, 2025'); +}); + +test('last-activity short wording: now while live, time today, day otherwise, never', () => { + assert.equal(formatLastActivityShort(TODAY_1928, NOW, true), 'now'); + assert.equal(formatLastActivityShort(TODAY_1928, NOW, false), '19:28'); + assert.equal(formatLastActivityShort(OCT_31_1402, NOW, false), 'Oct 31'); + assert.equal(formatLastActivityShort(JAN_31_2025, NOW, false), 'Jan 31, 2025'); + assert.equal(formatLastActivityShort(null, NOW, false), 'never'); +}); + +test('last activity is the newer of the latest run update and the saved modified time', () => { + const runs = [run('r1', 'w', 'completed', TODAY_1928), run('r2', 'w', 'failed', TODAY_1928 - 1000)]; + assert.deepEqual(lastActivityOf(runs, OCT_31_1402), { ms: TODAY_1928, what: 'run completed' }); + assert.deepEqual(lastActivityOf(runs, NOW), { ms: NOW, what: 'workflow saved' }); + assert.deepEqual(lastActivityOf([], OCT_31_1402), { ms: OCT_31_1402, what: 'workflow saved' }); + assert.deepEqual(lastActivityOf([], null), { ms: null, what: null }); +}); + +test('workflow entry projects glyph, strip, counts and when from its runs', () => { + const live = workflowSessionEntry(workflow('ingest-docs-rag', { description: 'Index the handbook' }), RUNS, NOW); + assert.equal(live.key, 'workflow:ingest-docs-rag'); + assert.equal(live.glyph, 'running'); + assert.equal(live.stateLabel, 'Saved workflow, 2 live runs'); + assert.equal(live.runCountLabel, '4 runs'); + assert.equal(live.whenLabel, 'now'); + assert.equal(live.sub, '2 live runs, 1 running, 1 queued, 1 succeeded, 1 failed'); + assert.equal(live.stripLabel, 'Runs in recent history: 1 running, 1 queued, 1 succeeded, 1 failed'); + assert.equal(live.lastActivityLabel, 'Today 20:05, run in progress'); + + const idle = workflowSessionEntry(workflow('maid', { created: new Date(JAN_31_2025).toISOString() }), RUNS, NOW); + assert.equal(idle.glyph, 'idle'); + assert.equal(idle.stateLabel, 'Saved workflow'); + assert.equal(idle.runCountLabel, '0 runs'); + assert.equal(idle.sub, 'Created Jan 31, 2025'); + assert.equal(idle.whenLabel, 'Oct 31'); + assert.deepEqual(idle.strip, []); +}); + +test('saved workflow id is the file stem from list_workflows, else the name', () => { + assert.equal(savedWorkflowId({ id: 'coding-agent', name: 'Coding Agent' }), 'coding-agent'); + assert.equal(savedWorkflowId({ id: ' ', name: 'Coding Agent' }), 'Coding Agent'); + assert.equal(savedWorkflowId({ name: 'Coding Agent' }), 'Coding Agent'); +}); + +test('orchestration entry has no dates and says so in the detail', () => { + const orchestration: OrchestrationGraphMetadata = { id: 'coding-agent-orch', name: 'Coding Agent Orchestration', description: '', nodeCount: 4 }; + const entry = orchestrationSessionEntry(orchestration, RUNS, NOW); + assert.equal(entry.tag, 'orchestration'); + assert.equal(entry.sub, 'Orchestration, 4 nodes'); + assert.equal(entry.whenLabel, 'never'); + assert.equal(entry.stateLabel, 'Saved orchestration'); + const detail = buildSessionDetail(entry, null, NOW); + assert.equal(detail.activity.find((row) => row.key === 'Created')?.value, 'Not recorded for orchestrations'); + assert.ok(detail.open[0].disabledReason, 'orchestrations cannot be opened in Graph'); + assert.ok(detail.actions.find((action) => action.id === 'delete')?.disabledReason); +}); + +test('saved sessions sort live first, then by last activity, then by name', () => { + const sessions = buildSavedSessions( + ready([workflow('maid'), workflow('summarize-daily'), workflow('ingest-docs-rag'), workflow('alpha')]), + ready([]), + RUNS, + NOW, + ); + assert.deepEqual(sessions.map((entry) => entry.id), ['ingest-docs-rag', 'summarize-daily', 'alpha', 'maid']); +}); + +test('a source that failed or is loading contributes no entries', () => { + const sessions = buildSavedSessions( + { status: 'failed', message: 'unreachable' }, + { status: 'loading' }, + RUNS, + NOW, + ); + assert.deepEqual(sessions, []); +}); + +test('grouping: Active carries the explanation, Saved filters by query', () => { + const saved = buildSavedSessions(ready([workflow('ingest-docs-rag'), workflow('maid')]), ready([]), RUNS, NOW); + + const all = groupSessions(saved, 'all', ''); + assert.deepEqual(all.map((group) => group.id), ['active', 'saved']); + assert.equal(all[0].note, ACTIVE_SESSIONS_UNAVAILABLE_NOTE); + assert.equal(all[0].count, undefined); + assert.equal(all[1].count, 2); + assert.equal(all[1].note, null); + + assert.deepEqual(groupSessions(saved, 'active', '').map((group) => group.id), ['active']); + assert.deepEqual(groupSessions(saved, 'saved', '').map((group) => group.id), ['saved']); + + const searched = groupSessions(saved, 'saved', 'MAID'); + assert.deepEqual(searched[0].entries.map((entry) => entry.id), ['maid']); + + const none = groupSessions(saved, 'saved', 'zzz'); + assert.equal(none[0].entries.length, 0); + assert.equal(none[0].note, 'No saved sessions match "zzz".'); + + const empty = groupSessions([], 'saved', ''); + assert.match(empty[0].note ?? '', /No saved workflows or orchestrations yet/); +}); + +test('filter options never claim a count of active sessions', () => { + const saved = buildSavedSessions(ready([workflow('a'), workflow('b')]), ready([]), [], NOW); + assert.deepEqual(sessionFilterOptions(saved), [ + { value: 'all', label: 'All', count: 2 }, + { value: 'active', label: 'Active' }, + { value: 'saved', label: 'Saved', count: 2 }, + ]); +}); + +test('dimension line states sources, run totals and runs of unsaved workflows', () => { + const workflows = ready([workflow('ingest-docs-rag'), workflow('summarize-daily')]); + const orchestrations = ready([]); + const saved = buildSavedSessions(workflows, orchestrations, RUNS, NOW); + assert.equal( + sessionsDimensionLine({ workflows, orchestrations, saved, runs: RUNS, runsLoaded: true }), + '2 saved workflows, 0 orchestrations. 7 runs in recent history, 3 live, 1 from workflows not saved here', + ); + assert.equal( + sessionsDimensionLine({ workflows: { status: 'loading' }, orchestrations, saved: [], runs: [], runsLoaded: false }), + 'Loading saved workflows. Run history not loaded', + ); + assert.equal( + sessionsDimensionLine({ workflows: { status: 'failed', message: 'x' }, orchestrations: { status: 'failed', message: 'y' }, saved: [], runs: RUNS, runsLoaded: true }), + 'Saved workflows unavailable, orchestrations unavailable. 7 runs in recent history, 3 live', + ); +}); + +test('detail lists activity, run summary, recent runs and the open item', () => { + const runs = [ + ...RUNS, + ...Array.from({ length: 6 }, (_, index) => run(`run_old${index}`, 'ingest-docs-rag', 'completed', OCT_31_1402 - index)), + ]; + const entry = workflowSessionEntry(workflow('ingest-docs-rag'), runs, NOW); + const detail = buildSessionDetail(entry, 'run_a2', NOW); + + assert.equal(detail.title, 'ingest-docs-rag'); + assert.deepEqual(detail.chips, ['latest v1.4.0', 'cuda:0']); + assert.deepEqual(detail.activity, [ + { key: 'Created', value: 'Oct 31, 14:02' }, + { key: 'Modified', value: 'Oct 31, 14:02' }, + { key: 'Last activity', value: 'Today 20:05, run in progress' }, + { key: 'Clients', value: 'client_gui, client_cli, 2 client sessions', mono: true }, + ]); + assert.deepEqual(detail.runSummary, [ + { key: 'Total', value: '10 in recent history: 1 running, 1 queued, 7 succeeded, 1 failed' }, + { key: 'Live now', value: 'run_a1 running, run_a2 queued #2' }, + { key: 'Versions run', value: 'v1.4.0, v1.3.9' }, + ]); + assert.equal(detail.recentRuns.length, SESSION_RECENT_RUN_LIMIT); + assert.equal(detail.moreRunCount, 5); + assert.equal(detail.recentRuns.find((row) => row.runId === 'run_a2')?.selected, true); + assert.equal(detail.open[0].actionLabel, 'Open graph'); + assert.equal(detail.open[0].disabledReason, null); + assert.equal(detail.open[0].sub, 'Graph, .pantograph/workflows/ingest-docs-rag.json'); +}); + +test('detail actions: only Delete workflow is backed by a service', () => { + const detail = buildSessionDetail(workflowSessionEntry(workflow('maid'), [], NOW), null, NOW); + const byId = Object.fromEntries(detail.actions.map((action) => [action.id, action])); + assert.equal(byId.delete.label, 'Delete workflow'); + assert.equal(byId.delete.disabledReason, null); + for (const id of ['resume', 'rename', 'save_copy']) { + assert.ok(byId[id].disabledReason, `${id} is disabled with a reason`); + } + assert.equal(byId.close, undefined, 'saved sessions have no Close action'); + assert.deepEqual(detail.runSummary[0], { key: 'Total', value: 'None in recent history' }); + assert.equal(detail.activity[3].value, 'None recorded on its runs'); +}); + +test('listing outcomes classify into ready or failed with a reason', () => { + assert.deepEqual(sessionSourceFromResult({ status: 'fulfilled', value: [1, 2] }), { status: 'ready', items: [1, 2] }); + assert.deepEqual(sessionSourceFromResult({ status: 'rejected', reason: new Error(' no host ') }), { status: 'failed', message: 'no host' }); + assert.deepEqual(sessionSourceFromResult({ status: 'rejected', reason: 'Failed to read workflows directory' }), { + status: 'failed', + message: 'Failed to read workflows directory', + }); + assert.deepEqual(sessionSourceFromResult({ status: 'rejected', reason: {} }), { status: 'failed', message: 'the engine gave no reason' }); + assert.equal(sessionSourceFromResult({ status: 'fulfilled', value: null as unknown as number[] }).status, 'failed'); +}); + +test('Show in Scheduler searches by the saved workflow id', () => { + assert.equal(schedulerSearchForSession({ id: 'ingest-docs-rag' }), 'ingest-docs-rag'); +}); + +test('failed listings collapse into one explanation when they share a reason', () => { + const okWorkflows = ready([workflow('a')]); + const okOrchestrations = ready([]); + assert.equal(savedSourceFailure(okWorkflows, okOrchestrations), null); + assert.equal(savedSourceFailure({ status: 'loading' }, { status: 'loading' }), null); + + const both = savedSourceFailure({ status: 'failed', message: 'no host' }, { status: 'failed', message: 'no host' }); + assert.equal(both?.title, 'Saved workflows and orchestrations could not be listed'); + assert.equal(both?.explanation, 'The engine did not return them: no host.'); + + const different = savedSourceFailure({ status: 'failed', message: 'a' }, { status: 'failed', message: 'b' }); + assert.equal(different?.explanation, 'Workflows: a. Orchestrations: b.'); + + assert.equal(savedSourceFailure({ status: 'failed', message: 'a' }, okOrchestrations)?.code, 'list_workflows'); + assert.equal( + savedSourceFailure({ status: 'failed', message: 'Failed to read workflows directory.' }, okOrchestrations)?.explanation, + 'The engine did not return them: Failed to read workflows directory.', + ); + assert.equal(savedSourceFailure(okWorkflows, { status: 'failed', message: 'b' })?.code, 'list_orchestrations'); +}); + +test('latest-only gate: newest call applies, older ones are superseded, close ends all', () => { + const gate = createLatestOnlyGate(); + const beforeOpen = gate.begin(); + assert.equal(gate.classify(beforeOpen), 'closed', 'nothing applies before the page mounts'); + + gate.open(); + const first = gate.begin(); + const second = gate.begin(); + assert.equal(gate.classify(first), 'superseded'); + assert.equal(gate.classify(second), 'current'); + + gate.close(); + assert.equal(gate.classify(second), 'closed', 'a call finishing after destroy never applies'); + + gate.open(); + assert.equal(gate.classify(second), 'superseded', 'reopening does not revive an old call'); + const third = gate.begin(); + assert.equal(gate.classify(third), 'current'); +}); + +test('latest-only gates are independent per operation', () => { + const load = createLatestOnlyGate(); + const open = createLatestOnlyGate(); + load.open(); + open.open(); + const loadToken = load.begin(); + open.begin(); + open.begin(); + assert.equal(load.classify(loadToken), 'current'); +}); + +test('detail empty text follows loading, filter, failure, emptiness and search', () => { + const base = { loading: false, failed: false, savedCount: 3, filter: 'all' as const, query: '' }; + assert.equal(sessionDetailEmptyText({ ...base, loading: true }), 'Loading saved sessions…'); + assert.match(sessionDetailEmptyText({ ...base, filter: 'active' }), /No live sessions/); + assert.match(sessionDetailEmptyText({ ...base, failed: true, savedCount: 0 }), /cannot be listed/); + assert.match(sessionDetailEmptyText({ ...base, savedCount: 0 }), /Nothing to show yet/); + assert.equal(sessionDetailEmptyText({ ...base, query: 'zzz' }), 'No session matches the search.'); + assert.match(sessionDetailEmptyText(base), /Select a session/); +}); diff --git a/src/components/workbench/sessionsPresenters.ts b/src/components/workbench/sessionsPresenters.ts new file mode 100644 index 000000000..d1b754cb2 --- /dev/null +++ b/src/components/workbench/sessionsPresenters.ts @@ -0,0 +1,800 @@ +/** + * Pure projection for the Sessions tab. + * + * Sessions are a view over existing authority only (plan M8, spec "Sessions"): + * - saved sessions are the saved workflows (`list_workflows`, `WorkflowMetadata`) + * and orchestrations (`list_orchestrations`, `OrchestrationGraphMetadata`); + * - their runs are the rows of the scheduler run-list projection whose + * `workflow_id` equals the saved workflow's id (the file stem); + * - live client sessions are not listed by any frontend service, so the Active + * group carries an explanation instead of rows (issue in the M8 report). + * + * Nothing here calls services, reads stores, the DOM or timers; the page passes + * `nowMs` in so wording is deterministic. The one stateful helper, + * `createLatestOnlyGate`, is the page's invocation authority, kept here so its + * deterministic behaviour is tested. + */ +import type { + RunListProjectionRecord, + RunListProjectionStatus, +} from '../../services/diagnostics/types'; +import type { WorkflowMetadata } from '../../services/workflow/types'; +import type { OrchestrationGraphMetadata } from '../../stores/orchestrationStore'; +import type { KeyValueRow, SegmentOption } from './ui/types'; +import type { GlyphState } from './ui/statusGlyph.ts'; +import { decorateRunContextRow, formatRunVersion, shortRunId, type RunContextRow } from './shell/runContextPicker.ts'; + +/** Rows the detail panel lists under "Recent runs". */ +export const SESSION_RECENT_RUN_LIMIT = 5; + +export type SessionKind = 'workflow' | 'orchestration'; +export type SessionsFilter = 'all' | 'active' | 'saved'; +export type RunOutcomeKind = 'running' | 'queued' | 'succeeded' | 'failed' | 'cancelled'; + +/** One saved source the page loaded, or why it could not be loaded. */ +export type SessionSourceState = + | { status: 'loading' } + | { status: 'ready'; items: T[] } + | { status: 'failed'; message: string }; + +export interface OutcomeCounts { + running: number; + queued: number; + succeeded: number; + failed: number; + cancelled: number; + total: number; +} + +export interface OutcomeStripSegment { + kind: RunOutcomeKind; + count: number; +} + +export interface SessionEntry { + /** Unique across kinds, for keyed lists and selection. */ + key: string; + kind: SessionKind; + /** Workflow file stem or orchestration id. */ + id: string; + name: string; + description: string | null; + /** Short tag after the name, in place of the board's client tag. */ + tag: string; + glyph: GlyphState; + /** Sentence-case state for the detail chip. */ + stateLabel: string; + sub: string; + strip: OutcomeStripSegment[]; + /** The strip's content in words, for assistive technology and titles. */ + stripLabel: string; + runCountLabel: string; + whenLabel: string; + createdMs: number | null; + modifiedMs: number | null; + lastActivityMs: number | null; + lastActivityLabel: string; + counts: OutcomeCounts; + /** This session's runs from the run list, newest update first. */ + runs: RunListProjectionRecord[]; + nodeCount: number | null; +} + +export interface SessionGroup { + id: 'active' | 'saved'; + label: string; + /** Omitted for Active, whose sessions are not listed by this build. */ + count?: number; + entries: SessionEntry[]; + /** Muted sentence shown in place of rows; null when rows explain themselves. */ + note: string | null; +} + +export interface SessionOpenItem { + name: string; + meta: string; + glyph: GlyphState; + sub: string; + actionLabel: string; + /** Null when the action works; otherwise why it is unavailable (button title). */ + disabledReason: string | null; +} + +export interface SessionAction { + id: 'rename' | 'save_copy' | 'resume' | 'close' | 'delete'; + label: string; + /** Null when the action is backed by a service. */ + disabledReason: string | null; +} + +export interface SessionDetail { + key: string; + kind: SessionKind; + title: string; + id: string; + glyph: GlyphState; + stateLabel: string; + chips: string[]; + activity: KeyValueRow[]; + runSummary: KeyValueRow[]; + recentRuns: RunContextRow[]; + /** Runs beyond the recent list, for a "and N more in Scheduler" line. */ + moreRunCount: number; + open: SessionOpenItem[]; + resumeSentence: string; + actions: SessionAction[]; +} + +export const ACTIVE_SESSIONS_UNAVAILABLE_NOTE = + 'Live client sessions are not listed by this engine build. Runs still show their client session in the Scheduler.'; + +export const NO_SESSION_SERVICE_REASON = + 'Not available: this engine build has no session service. Sessions here are your saved workflows.'; + +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +const OUTCOME_ORDER: RunOutcomeKind[] = ['running', 'queued', 'succeeded', 'failed', 'cancelled']; + +const OUTCOME_WORDS: Record = { + running: 'running', + queued: 'queued', + succeeded: 'succeeded', + failed: 'failed', + cancelled: 'cancelled', +}; + +const RUN_ACTIVITY_WORDS: Record = { + accepted: 'run accepted', + future: 'run scheduled', + scheduled: 'run scheduled', + queued: 'run queued', + delayed: 'run delayed', + running: 'run in progress', + completed: 'run completed', + failed: 'run failed', + cancelled: 'run cancelled', +}; + +// --------------------------------------------------------------------------- +// Invocation authority +// --------------------------------------------------------------------------- + +/** How a finished async call relates to its owner when it completes. */ +export type InvocationOutcome = 'current' | 'superseded' | 'closed'; + +/** + * Latest-call-wins authority for one operation of one page instance. The page + * opens it on mount and closes it on destroy; each call takes a token with + * `begin()` and may apply its result only when `classify(token)` is `current`. + * A newer `begin()` supersedes older tokens; `close()` supersedes all of them. + */ +export interface LatestOnlyGate { + open(): void; + close(): void; + begin(): number; + classify(token: number): InvocationOutcome; +} + +export function createLatestOnlyGate(): LatestOnlyGate { + let generation = 0; + let isOpen = false; + return { + open() { + isOpen = true; + }, + close() { + isOpen = false; + generation += 1; + }, + begin() { + generation += 1; + return generation; + }, + classify(token) { + if (!isOpen) return 'closed'; + return token === generation ? 'current' : 'superseded'; + }, + }; +} + +// --------------------------------------------------------------------------- +// Source loading outcomes +// --------------------------------------------------------------------------- + +function errorText(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) return error.message.trim(); + if (typeof error === 'string' && error.trim().length > 0) return error.trim(); + return 'the engine gave no reason'; +} + +/** Classify one settled listing call into the source state the page renders. */ +export function sessionSourceFromResult(result: PromiseSettledResult): SessionSourceState { + if (result.status === 'fulfilled') { + return Array.isArray(result.value) + ? { status: 'ready', items: result.value } + : { status: 'failed', message: 'the engine answered with something other than a list' }; + } + return { status: 'failed', message: errorText(result.reason) }; +} + +// --------------------------------------------------------------------------- +// Runs and outcomes +// --------------------------------------------------------------------------- + +export function runOutcomeKind(status: RunListProjectionStatus): RunOutcomeKind { + switch (status) { + case 'running': + return 'running'; + case 'accepted': + case 'future': + case 'scheduled': + case 'queued': + case 'delayed': + return 'queued'; + case 'completed': + return 'succeeded'; + case 'failed': + return 'failed'; + case 'cancelled': + return 'cancelled'; + } +} + +export function isLiveOutcome(kind: RunOutcomeKind): boolean { + return kind === 'running' || kind === 'queued'; +} + +export function countRunOutcomes(runs: readonly Pick[]): OutcomeCounts { + const counts: OutcomeCounts = { running: 0, queued: 0, succeeded: 0, failed: 0, cancelled: 0, total: 0 }; + for (const run of runs) { + counts[runOutcomeKind(run.status)] += 1; + counts.total += 1; + } + return counts; +} + +/** Strip segments in board order (running, queued, succeeded, failed, cancelled), empty kinds omitted. */ +export function outcomeStrip(counts: OutcomeCounts): OutcomeStripSegment[] { + return OUTCOME_ORDER.filter((kind) => counts[kind] > 0).map((kind) => ({ kind, count: counts[kind] })); +} + +/** "2 running, 1 queued, 2 succeeded, 1 failed", or "no runs". */ +export function outcomeSummaryText(counts: OutcomeCounts): string { + const parts = outcomeStrip(counts).map((segment) => `${segment.count} ${OUTCOME_WORDS[segment.kind]}`); + return parts.length > 0 ? parts.join(', ') : 'no runs'; +} + +export function liveRunCount(counts: OutcomeCounts): number { + return counts.running + counts.queued; +} + +export function pluralize(count: number, singular: string, plural = `${singular}s`): string { + return `${count} ${count === 1 ? singular : plural}`; +} + +/** Runs of one workflow id, newest update first (ties by run id for stable order). */ +export function runsForWorkflow( + runs: readonly RunListProjectionRecord[], + workflowId: string, +): RunListProjectionRecord[] { + return runs + .filter((run) => run.workflow_id === workflowId) + .sort( + (left, right) => + right.last_updated_at_ms - left.last_updated_at_ms || + left.workflow_run_id.localeCompare(right.workflow_run_id), + ); +} + +// --------------------------------------------------------------------------- +// Dates +// --------------------------------------------------------------------------- + +/** Workflow metadata dates are RFC 3339 strings; anything unparsable is null. */ +export function parseMetadataDate(value: string | null | undefined): number | null { + if (typeof value !== 'string' || value.trim().length === 0) return null; + const ms = Date.parse(value); + return Number.isFinite(ms) ? ms : null; +} + +function pad2(value: number): string { + return String(value).padStart(2, '0'); +} + +function sameLocalDay(left: Date, right: Date): boolean { + return ( + left.getFullYear() === right.getFullYear() && + left.getMonth() === right.getMonth() && + left.getDate() === right.getDate() + ); +} + +/** "Oct 31" in the current year, "Jan 31, 2025" otherwise (local time). */ +export function formatSessionDay(ms: number, nowMs: number): string { + const date = new Date(ms); + const now = new Date(nowMs); + const day = `${MONTHS[date.getMonth()]} ${date.getDate()}`; + return date.getFullYear() === now.getFullYear() ? day : `${day}, ${date.getFullYear()}`; +} + +/** "Today 19:28", "Oct 31, 14:02", or "Jan 31, 2025, 14:02" (local time). */ +export function formatSessionDateTime(ms: number, nowMs: number): string { + const date = new Date(ms); + const time = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`; + if (sameLocalDay(date, new Date(nowMs))) return `Today ${time}`; + return `${formatSessionDay(ms, nowMs)}, ${time}`; +} + +/** + * Right-hand "when" of a row: "now" while a run is live, the time today, + * otherwise the day. "never" when nothing has happened that the sources record. + */ +export function formatLastActivityShort(ms: number | null, nowMs: number, live: boolean): string { + if (live) return 'now'; + if (ms === null) return 'never'; + const date = new Date(ms); + if (sameLocalDay(date, new Date(nowMs))) return `${pad2(date.getHours())}:${pad2(date.getMinutes())}`; + return formatSessionDay(ms, nowMs); +} + +export interface LastActivity { + ms: number | null; + /** What happened at `ms`, for example "run completed" or "workflow saved". */ + what: string | null; +} + +/** The newer of the latest run update and the saved file's modified time. */ +export function lastActivityOf(runs: readonly RunListProjectionRecord[], modifiedMs: number | null): LastActivity { + const latestRun = runs.reduce( + (latest, run) => (latest === null || run.last_updated_at_ms > latest.last_updated_at_ms ? run : latest), + null, + ); + if (latestRun && (modifiedMs === null || latestRun.last_updated_at_ms >= modifiedMs)) { + return { ms: latestRun.last_updated_at_ms, what: RUN_ACTIVITY_WORDS[latestRun.status] }; + } + if (modifiedMs !== null) return { ms: modifiedMs, what: 'workflow saved' }; + return { ms: null, what: null }; +} + +export function formatLastActivityLong(activity: LastActivity, nowMs: number): string { + if (activity.ms === null) return 'Nothing recorded yet'; + const when = formatSessionDateTime(activity.ms, nowMs); + return activity.what ? `${when}, ${activity.what}` : when; +} + +// --------------------------------------------------------------------------- +// Entries +// --------------------------------------------------------------------------- + +function trimmedOrNull(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed ? trimmed : null; +} + +function kindLabel(kind: SessionKind): string { + return kind === 'workflow' ? 'Saved workflow' : 'Saved orchestration'; +} + +function entryGlyph(counts: OutcomeCounts): GlyphState { + // Spec: running if any live run; saved sessions are otherwise idle. + return liveRunCount(counts) > 0 ? 'running' : 'idle'; +} + +function entrySub( + counts: OutcomeCounts, + description: string | null, + fallback: string, +): string { + const live = liveRunCount(counts); + if (live > 0) return `${pluralize(live, 'live run')}, ${outcomeSummaryText(counts)}`; + return description ?? fallback; +} + +function finishEntry( + base: Pick, + runs: RunListProjectionRecord[], + fallbackSub: string, + nowMs: number, +): SessionEntry { + const counts = countRunOutcomes(runs); + const live = liveRunCount(counts) > 0; + const activity = lastActivityOf(runs, base.modifiedMs); + return { + ...base, + glyph: entryGlyph(counts), + stateLabel: live ? `${kindLabel(base.kind)}, ${pluralize(liveRunCount(counts), 'live run')}` : kindLabel(base.kind), + sub: entrySub(counts, base.description, fallbackSub), + strip: outcomeStrip(counts), + stripLabel: `Runs in recent history: ${outcomeSummaryText(counts)}`, + runCountLabel: pluralize(counts.total, 'run'), + whenLabel: formatLastActivityShort(activity.ms, nowMs, live), + lastActivityMs: activity.ms, + lastActivityLabel: formatLastActivityLong(activity, nowMs), + counts, + runs, + }; +} + +/** The id `list_workflows` gives a saved workflow (file stem), else its name. */ +export function savedWorkflowId(workflow: Pick): string { + return trimmedOrNull(workflow.id) ?? workflow.name; +} + +export function workflowSessionEntry( + workflow: WorkflowMetadata, + runs: readonly RunListProjectionRecord[], + nowMs: number, +): SessionEntry { + const id = savedWorkflowId(workflow); + const createdMs = parseMetadataDate(workflow.created); + const fallback = createdMs === null ? 'Saved workflow' : `Created ${formatSessionDay(createdMs, nowMs)}`; + return finishEntry( + { + key: `workflow:${id}`, + kind: 'workflow', + id, + name: trimmedOrNull(workflow.name) ?? id, + description: trimmedOrNull(workflow.description), + tag: 'workflow', + createdMs, + modifiedMs: parseMetadataDate(workflow.modified), + nodeCount: null, + }, + runsForWorkflow(runs, id), + fallback, + nowMs, + ); +} + +export function orchestrationSessionEntry( + orchestration: OrchestrationGraphMetadata, + runs: readonly RunListProjectionRecord[], + nowMs: number, +): SessionEntry { + const nodeCount = Number.isFinite(orchestration.nodeCount) ? orchestration.nodeCount : null; + return finishEntry( + { + key: `orchestration:${orchestration.id}`, + kind: 'orchestration', + id: orchestration.id, + name: trimmedOrNull(orchestration.name) ?? orchestration.id, + description: trimmedOrNull(orchestration.description), + tag: 'orchestration', + createdMs: null, + modifiedMs: null, + nodeCount, + }, + runsForWorkflow(runs, orchestration.id), + nodeCount === null ? 'Orchestration' : `Orchestration, ${pluralize(nodeCount, 'node')}`, + nowMs, + ); +} + +/** + * Saved sessions from both sources, most recent activity first, never-active + * ones last by name. A source that is not ready contributes no entries; the + * page explains it in place. + */ +export function buildSavedSessions( + workflows: SessionSourceState, + orchestrations: SessionSourceState, + runs: readonly RunListProjectionRecord[], + nowMs: number, +): SessionEntry[] { + const entries = [ + ...(workflows.status === 'ready' ? workflows.items.map((item) => workflowSessionEntry(item, runs, nowMs)) : []), + ...(orchestrations.status === 'ready' + ? orchestrations.items.map((item) => orchestrationSessionEntry(item, runs, nowMs)) + : []), + ]; + return entries.sort((left, right) => { + const leftLive = liveRunCount(left.counts) > 0 ? 1 : 0; + const rightLive = liveRunCount(right.counts) > 0 ? 1 : 0; + if (leftLive !== rightLive) return rightLive - leftLive; + const leftMs = left.lastActivityMs ?? Number.NEGATIVE_INFINITY; + const rightMs = right.lastActivityMs ?? Number.NEGATIVE_INFINITY; + if (leftMs !== rightMs) return rightMs - leftMs; + return left.name.localeCompare(right.name); + }); +} + +// --------------------------------------------------------------------------- +// Filtering, grouping, summary +// --------------------------------------------------------------------------- + +export function sessionMatchesQuery(entry: SessionEntry, query: string): boolean { + const needle = query.trim().toLowerCase(); + if (!needle) return true; + return [entry.name, entry.id, entry.description, entry.tag].some( + (value) => typeof value === 'string' && value.toLowerCase().includes(needle), + ); +} + +export function sessionFilterOptions(saved: readonly SessionEntry[]): SegmentOption[] { + return [ + { value: 'all', label: 'All', count: saved.length }, + // No count: live sessions are not listed by this build, and 0 would claim there are none. + { value: 'active', label: 'Active' }, + { value: 'saved', label: 'Saved', count: saved.length }, + ]; +} + +/** + * List groups for the left panel. Active is always present for the `all` and + * `active` filters and carries the explanation; Saved carries the entries that + * match the query, or a sentence when there are none. + */ +export function groupSessions( + saved: readonly SessionEntry[], + filter: SessionsFilter, + query: string, +): SessionGroup[] { + const groups: SessionGroup[] = []; + if (filter !== 'saved') { + groups.push({ id: 'active', label: 'Active', entries: [], note: ACTIVE_SESSIONS_UNAVAILABLE_NOTE }); + } + if (filter !== 'active') { + const entries = saved.filter((entry) => sessionMatchesQuery(entry, query)); + let note: string | null = null; + if (entries.length === 0) { + note = saved.length === 0 + ? 'No saved workflows or orchestrations yet. Save a workflow from the Graph tab and it appears here.' + : `No saved sessions match "${query.trim()}".`; + } + groups.push({ id: 'saved', label: 'Saved', count: entries.length, entries, note }); + } + return groups; +} + +/** Runs in the run list whose workflow is not one of the saved sessions. */ +export function unsavedWorkflowRunCount( + runs: readonly RunListProjectionRecord[], + saved: readonly SessionEntry[], +): number { + const ids = new Set(saved.map((entry) => entry.id)); + return runs.filter((run) => !ids.has(run.workflow_id)).length; +} + +export interface SessionsSummaryInput { + workflows: SessionSourceState; + orchestrations: SessionSourceState; + saved: readonly SessionEntry[]; + runs: readonly RunListProjectionRecord[]; + runsLoaded: boolean; +} + +/** The dimension line under the header. */ +export function sessionsDimensionLine(input: SessionsSummaryInput): string { + const parts: string[] = []; + if (input.workflows.status === 'loading' || input.orchestrations.status === 'loading') { + parts.push('Loading saved workflows'); + } else { + const workflows = input.workflows.status === 'ready' ? pluralize(input.workflows.items.length, 'saved workflow') : 'saved workflows unavailable'; + const orchestrations = input.orchestrations.status === 'ready' + ? pluralize(input.orchestrations.items.length, 'orchestration') + : 'orchestrations unavailable'; + parts.push(`${workflows}, ${orchestrations}`); + } + if (!input.runsLoaded) { + parts.push('run history not loaded'); + } else { + const counts = countRunOutcomes(input.runs); + let runs = `${pluralize(counts.total, 'run')} in recent history, ${liveRunCount(counts)} live`; + const elsewhere = input.workflows.status === 'ready' ? unsavedWorkflowRunCount(input.runs, input.saved) : 0; + if (elsewhere > 0) runs += `, ${elsewhere} from workflows not saved here`; + parts.push(runs); + } + return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('. '); +} + +export interface SavedSourceFailure { + title: string; + /** The listing command(s) that failed, shown as the muted code line. */ + code: string; + explanation: string; +} + +/** + * One in-place explanation for failed listings. Both sources usually fail for + * the same reason (engine unreachable), so a shared message gives one card. + */ +function endSentence(text: string): string { + return /[.!?]$/.test(text) ? text : `${text}.`; +} + +export function savedSourceFailure( + workflows: SessionSourceState, + orchestrations: SessionSourceState, +): SavedSourceFailure | null { + const workflowFailure = workflows.status === 'failed' ? workflows.message : null; + const orchestrationFailure = orchestrations.status === 'failed' ? orchestrations.message : null; + if (workflowFailure !== null && orchestrationFailure !== null) { + const same = workflowFailure === orchestrationFailure; + return { + title: 'Saved workflows and orchestrations could not be listed', + code: 'list_workflows, list_orchestrations', + explanation: same + ? `The engine did not return them: ${endSentence(workflowFailure)}` + : `Workflows: ${endSentence(workflowFailure)} Orchestrations: ${endSentence(orchestrationFailure)}`, + }; + } + if (workflowFailure !== null) { + return { + title: 'Saved workflows could not be listed', + code: 'list_workflows', + explanation: `The engine did not return them: ${endSentence(workflowFailure)}`, + }; + } + if (orchestrationFailure !== null) { + return { + title: 'Orchestrations could not be listed', + code: 'list_orchestrations', + explanation: `Saved workflows are shown; orchestrations are missing: ${endSentence(orchestrationFailure)}`, + }; + } + return null; +} + +export interface DetailEmptyInput { + loading: boolean; + failed: boolean; + savedCount: number; + filter: SessionsFilter; + query: string; +} + +/** What the detail panel says when no session is selected. */ +export function sessionDetailEmptyText(input: DetailEmptyInput): string { + if (input.loading) return 'Loading saved sessions…'; + if (input.filter === 'active') return 'No live sessions to show here. Choose Saved to see your saved workflows.'; + if (input.failed && input.savedCount === 0) return 'Nothing to show while saved workflows cannot be listed.'; + if (input.savedCount === 0) return 'Nothing to show yet. Saved workflows appear here with the runs they produced.'; + if (input.query.trim()) return 'No session matches the search.'; + return 'Select a session to see what it ran and open its graph.'; +} + +// --------------------------------------------------------------------------- +// Detail +// --------------------------------------------------------------------------- + +function distinctValues(values: readonly (string | null | undefined)[]): string[] { + const seen: string[] = []; + for (const value of values) { + const trimmed = value?.trim(); + if (trimmed && !seen.includes(trimmed)) seen.push(trimmed); + } + return seen; +} + +function listWithMore(values: string[], max: number): string { + if (values.length <= max) return values.join(', '); + return `${values.slice(0, max).join(', ')} and ${values.length - max} more`; +} + +function liveNowText(runs: readonly RunListProjectionRecord[]): string { + const live = runs.filter((run) => isLiveOutcome(runOutcomeKind(run.status))); + if (live.length === 0) return 'none'; + return listWithMore( + live.map((run) => { + const word = run.status === 'running' ? 'running' : run.status === 'delayed' ? 'delayed' : 'queued'; + const position = typeof run.scheduler_queue_position === 'number' && word !== 'running' + ? ` #${run.scheduler_queue_position}` + : ''; + return `${shortRunId(run.workflow_run_id)} ${word}${position}`; + }), + 3, + ); +} + +const NOT_RECORDED_ORCHESTRATION = 'Not recorded for orchestrations'; + +export function buildSessionDetail( + entry: SessionEntry, + selectedRunId: string | null, + nowMs: number, +): SessionDetail { + const isWorkflow = entry.kind === 'workflow'; + const versions = distinctValues(entry.runs.map((run) => formatRunVersion(run.workflow_semantic_version))); + const clients = distinctValues(entry.runs.map((run) => run.client_id)); + const clientSessions = distinctValues(entry.runs.map((run) => run.client_session_id)); + const devices = distinctValues(entry.runs.map((run) => run.selected_device_id)); + + // The kind is already in the state chip (`stateLabel`). + const chips: string[] = []; + if (versions.length > 0) chips.push(`latest ${versions[0]}`); + if (devices.length > 0) chips.push(listWithMore(devices, 2)); + if (!isWorkflow && entry.nodeCount !== null) chips.push(pluralize(entry.nodeCount, 'node')); + + const dateOrMissing = (ms: number | null): string => { + if (ms !== null) return formatSessionDateTime(ms, nowMs); + return isWorkflow ? 'Not recorded' : NOT_RECORDED_ORCHESTRATION; + }; + + const activity: KeyValueRow[] = [ + { key: 'Created', value: dateOrMissing(entry.createdMs) }, + { key: 'Modified', value: dateOrMissing(entry.modifiedMs) }, + { key: 'Last activity', value: entry.lastActivityLabel }, + { + key: 'Clients', + value: clients.length > 0 + ? `${listWithMore(clients, 2)}${clientSessions.length > 0 ? `, ${pluralize(clientSessions.length, 'client session')}` : ''}` + : 'None recorded on its runs', + mono: clients.length > 0, + }, + ]; + + const runSummary: KeyValueRow[] = [ + { + key: 'Total', + value: entry.counts.total > 0 + ? `${entry.counts.total} in recent history: ${outcomeSummaryText(entry.counts)}` + : 'None in recent history', + }, + { key: 'Live now', value: liveNowText(entry.runs) }, + { key: 'Versions run', value: versions.length > 0 ? listWithMore(versions, 4) : 'none' }, + ]; + + const recentRuns = entry.runs + .slice(0, SESSION_RECENT_RUN_LIMIT) + .map((run) => decorateRunContextRow(run, selectedRunId)); + + const open: SessionOpenItem[] = [ + isWorkflow + ? { + name: entry.name, + meta: versions[0] ?? 'saved', + glyph: entry.glyph, + sub: `Graph, .pantograph/workflows/${entry.id}.json`, + actionLabel: 'Open graph', + disabledReason: null, + } + : { + name: entry.name, + meta: 'orchestration', + glyph: entry.glyph, + sub: entry.description ?? 'Orchestration graph', + actionLabel: 'Open graph', + disabledReason: 'Not available: the Graph tab does not open orchestrations in this build.', + }, + ]; + + const actions: SessionAction[] = [ + { id: 'resume', label: 'Resume', disabledReason: NO_SESSION_SERVICE_REASON }, + { id: 'rename', label: 'Rename', disabledReason: 'Not available: there is no rename command for saved workflows.' }, + { id: 'save_copy', label: 'Save a copy', disabledReason: 'Not available here: open the graph and save it under a new name.' }, + { + id: 'delete', + label: isWorkflow ? 'Delete workflow' : 'Delete', + disabledReason: isWorkflow ? null : 'Not available: orchestrations are deleted from their own editor.', + }, + ]; + + return { + key: entry.key, + kind: entry.kind, + title: entry.name, + id: entry.id, + glyph: entry.glyph, + stateLabel: entry.stateLabel, + chips, + activity, + runSummary, + recentRuns, + moreRunCount: Math.max(0, entry.runs.length - recentRuns.length), + open, + resumeSentence: isWorkflow + ? 'This engine build keeps no session state, so nothing resumes on its own. Open graph loads the saved workflow into a new edit session; finished runs stay in the Scheduler history and are not re-run.' + : 'This engine build keeps no session state for orchestrations; their runs, if any, stay in the Scheduler history.', + actions, + }; +} + +/** + * Text for the Scheduler search when "Show in Scheduler" is used. The scheduler + * filter store has no exact workflow filter; its search matches the workflow id + * as a substring (and other run fields), so the result can include workflows + * whose id contains this one. + */ +export function schedulerSearchForSession(entry: Pick): string { + return entry.id; +} diff --git a/src/components/workbench/settingsPagePresenters.test.ts b/src/components/workbench/settingsPagePresenters.test.ts index acd6a97c6..ef2681aea 100644 --- a/src/components/workbench/settingsPagePresenters.test.ts +++ b/src/components/workbench/settingsPagePresenters.test.ts @@ -2,17 +2,21 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { + buildCapabilityRows, buildDiagnosticsRetentionCleanupRows, buildDiagnosticsRetentionPolicyRows, buildDiagnosticsRetentionSettingRows, buildManagedMediaDependencyRows, buildArtifactPolicyRows, findFormatOption, + formatCapabilityCount, + formatCapabilitySummary, formatManagedMediaDependencyStatus, formatOptionItems, formatRangeLabel, formatSettingsBytes, formatSettingsSeconds, + managedMediaDependencyGlyph, managedMediaVersionOptions, managedMediaVersionStatusLabel, optionValuesWithCurrent, @@ -83,26 +87,26 @@ test('artifact policy rows preserve backend ids and nullable budgets', () => { delete_on_consume: true, }); - assert.equal(rows.find((row) => row.label === 'Policy')?.value, 'artifact-policy-v1'); - assert.equal(rows.find((row) => row.label === 'Version')?.value, '3'); - assert.equal(rows.find((row) => row.label === 'TTL')?.value, '7 days'); - assert.equal(rows.find((row) => row.label === 'Disk Budget')?.value, 'Unlimited'); - assert.equal(rows.find((row) => row.label === 'Memory Budget')?.value, '4.0 KiB'); - assert.equal(rows.find((row) => row.label === 'Delete On Consume')?.value, 'Enabled'); + assert.equal(rows.find((row) => row.key === 'Policy')?.value, 'artifact-policy-v1'); + assert.equal(rows.find((row) => row.key === 'Version')?.value, '3'); + assert.equal(rows.find((row) => row.key === 'TTL')?.value, '7 days'); + assert.equal(rows.find((row) => row.key === 'Disk budget')?.value, 'Unlimited'); + assert.equal(rows.find((row) => row.key === 'Memory budget')?.value, '4.0 KiB'); + assert.equal(rows.find((row) => row.key === 'Delete on consume')?.value, 'Enabled'); }); test('diagnostics retention policy rows expose global retention settings', () => { const policy = diagnosticsRetentionPolicy(); const rows = buildDiagnosticsRetentionPolicyRows(policy); - assert.equal(rows.find((row) => row.label === 'Policy')?.value, 'standard-local-v1'); - assert.equal(rows.find((row) => row.label === 'Version')?.value, '3'); - assert.equal(rows.find((row) => row.label === 'Days')?.value, '30'); + assert.equal(rows.find((row) => row.key === 'Policy')?.value, 'standard-local-v1'); + assert.equal(rows.find((row) => row.key === 'Version')?.value, '3'); + assert.equal(rows.find((row) => row.key === 'Days')?.value, '30'); const settingRows = buildDiagnosticsRetentionSettingRows(policy); - assert.equal(settingRows.find((row) => row.label === 'Final Outputs')?.value, '30 days, Retain Payload Reference'); - assert.equal(settingRows.find((row) => row.label === 'Intermediate Node I/O')?.value, '14 days, Metadata Only'); - assert.equal(settingRows.find((row) => row.label === 'Cleanup Trigger')?.value, 'Manual Or Maintenance'); + assert.equal(settingRows.find((row) => row.key === 'Final outputs')?.value, '30 days, Retain payload reference'); + assert.equal(settingRows.find((row) => row.key === 'Intermediate node I/O')?.value, '14 days, Metadata only'); + assert.equal(settingRows.find((row) => row.key === 'Cleanup trigger')?.value, 'Manual or maintenance'); }); test('diagnostics retention cleanup rows expose backend cleanup result', () => { @@ -115,11 +119,11 @@ test('diagnostics retention cleanup rows expose backend cleanup result', () => { last_event_seq: 44, }); - assert.equal(rows.find((row) => row.label === 'Policy')?.value, 'standard-local-v1'); - assert.equal(rows.find((row) => row.label === 'Version')?.value, '4'); - assert.match(rows.find((row) => row.label === 'Cutoff')?.value ?? '', /1970/); - assert.equal(rows.find((row) => row.label === 'Expired')?.value, '12'); - assert.equal(rows.find((row) => row.label === 'Last Event Seq')?.value, '44'); + assert.equal(rows.find((row) => row.key === 'Policy')?.value, 'standard-local-v1'); + assert.equal(rows.find((row) => row.key === 'Version')?.value, '4'); + assert.match(rows.find((row) => row.key === 'Cutoff')?.value ?? '', /1970/); + assert.equal(rows.find((row) => row.key === 'Expired')?.value, '12'); + assert.equal(rows.find((row) => row.key === 'Last event seq')?.value, '44'); assert.deepEqual(buildDiagnosticsRetentionCleanupRows(null), []); }); @@ -177,21 +181,62 @@ test('managed media dependency presenters expose backend status and version fact assert.deepEqual(formatManagedMediaDependencyStatus(dependency), { installLabel: 'Installed', readinessLabel: 'Ready', - categoryLabel: 'Tool Binary', + categoryLabel: 'Tool binary', packageLabel: 'Archive', - statusClass: 'border-emerald-800 bg-emerald-950/40 text-emerald-200', + statusGlyph: 'succeeded', }); const rows = buildManagedMediaDependencyRows(dependency); - assert.equal(rows.find((row) => row.label === 'Source')?.value, 'FFmpeg/FFmpeg'); - assert.equal(rows.find((row) => row.label === 'Catalog Version')?.value, '7.1'); - assert.equal(rows.find((row) => row.label === 'Selected')?.value, '7.1'); - assert.equal(rows.find((row) => row.label === 'Installed Versions')?.value, '1'); + assert.equal(rows.find((row) => row.key === 'Source')?.value, 'FFmpeg/FFmpeg'); + assert.equal(rows.find((row) => row.key === 'Catalog version')?.value, '7.1'); + assert.equal(rows.find((row) => row.key === 'Selected')?.value, '7.1'); + assert.equal(rows.find((row) => row.key === 'Installed versions')?.value, '1'); assert.deepEqual(managedMediaVersionOptions(dependency), ['7.1']); assert.equal(managedMediaVersionStatusLabel(dependency.versions[0]), '7.1 | active | selected'); }); +test('managed media dependency glyph follows readiness and install state', () => { + const ready = managedMediaDependencyStatus(); + assert.equal(managedMediaDependencyGlyph(ready), 'succeeded'); + assert.equal( + managedMediaDependencyGlyph({ ...ready, install_state: 'missing', readiness: 'missing' }), + 'warn', + ); + assert.equal( + managedMediaDependencyGlyph({ ...ready, install_state: 'unsupported', readiness: 'unsupported' }), + 'idle', + ); + assert.equal(formatManagedMediaDependencyStatus({ ...ready, readiness: 'missing' }).readinessLabel, 'Missing'); +}); + +test('capability counts and rows read the format capabilities, or zero when unloaded', () => { + assert.equal(formatCapabilityCount(undefined), '0 formats'); + assert.equal(formatCapabilityCount([jpgOption]), '1 format'); + assert.equal(formatCapabilityCount([jpgOption, oggOption]), '2 formats'); + + const capabilities = { + image_formats: [jpgOption], + audio_formats: [oggOption], + video_formats: [], + three_d_formats: [jpgOption, oggOption], + }; + assert.equal( + formatCapabilitySummary(capabilities), + 'Image 1 format, audio 1 format, video 0 formats, 3D 2 formats', + ); + assert.deepEqual(buildCapabilityRows(capabilities), [ + { key: 'Image', value: '1 format', mono: true }, + { key: 'Audio', value: '1 format', mono: true }, + { key: 'Video', value: '0 formats', mono: true }, + { key: '3D', value: '2 formats', mono: true }, + ]); + assert.deepEqual( + buildCapabilityRows(null).map((row) => row.value), + ['0 formats', '0 formats', '0 formats', '0 formats'], + ); +}); + function managedMediaDependencyStatus(): WorkflowManagedMediaDependencyStatus { return { id: 'ffmpeg', diff --git a/src/components/workbench/settingsPagePresenters.ts b/src/components/workbench/settingsPagePresenters.ts index d1fc2c427..0e115eef3 100644 --- a/src/components/workbench/settingsPagePresenters.ts +++ b/src/components/workbench/settingsPagePresenters.ts @@ -3,11 +3,14 @@ import type { WorkflowRetentionCleanupResult, } from '../../services/diagnostics/types'; import type { + WorkflowArtifactFormatCapabilities, WorkflowManagedMediaDependencyStatus, WorkflowManagedMediaDependencyVersionStatus, WorkflowArtifactPolicy, WorkflowMediaFormatOption, } from '../../services/workflow/types'; +import type { GlyphState } from './ui/statusGlyph'; +import type { KeyValueRow } from './ui/types'; export interface SettingsOptionItem { value: string; @@ -16,18 +19,16 @@ export interface SettingsOptionItem { unavailable?: boolean; } -export interface SettingsPolicyRow { - label: string; - value: string; - mono?: boolean; -} +/** Settings rows render through the shared KeyValue part. */ +export type SettingsPolicyRow = KeyValueRow; export interface ManagedMediaDependencyStatusPresentation { installLabel: string; readinessLabel: string; categoryLabel: string; packageLabel: string; - statusClass: string; + /** Decorative glyph beside `readinessLabel`; the label carries the status. */ + statusGlyph: GlyphState; } export interface NullableIntegerParseResult { @@ -79,11 +80,11 @@ export function formatManagedMediaDependencyStatus( dependency: WorkflowManagedMediaDependencyStatus, ): ManagedMediaDependencyStatusPresentation { return { - installLabel: titleCaseSnakeLabel(dependency.install_state), - readinessLabel: titleCaseSnakeLabel(dependency.readiness), - categoryLabel: titleCaseSnakeLabel(dependency.category), - packageLabel: titleCaseSnakeLabel(dependency.catalog.package_kind), - statusClass: managedMediaDependencyStatusClass(dependency), + installLabel: sentenceCaseSnakeLabel(dependency.install_state), + readinessLabel: sentenceCaseSnakeLabel(dependency.readiness), + categoryLabel: sentenceCaseSnakeLabel(dependency.category), + packageLabel: sentenceCaseSnakeLabel(dependency.catalog.package_kind), + statusGlyph: managedMediaDependencyGlyph(dependency), }; } @@ -91,15 +92,15 @@ export function buildManagedMediaDependencyRows( dependency: WorkflowManagedMediaDependencyStatus, ): SettingsPolicyRow[] { return [ - { label: 'Source', value: `${dependency.catalog.source.owner}/${dependency.catalog.source.project}` }, - { label: 'Catalog Version', value: dependency.catalog.version, mono: true }, - { label: 'Platform', value: dependency.catalog.platform_key, mono: true }, - { label: 'Package', value: titleCaseSnakeLabel(dependency.catalog.package_kind) }, - { label: 'Archive', value: dependency.catalog.archive_kind ? titleCaseSnakeLabel(dependency.catalog.archive_kind) : 'None' }, - { label: 'Selected', value: dependency.selection.selected_version ?? 'None', mono: true }, - { label: 'Active', value: dependency.selection.active_version ?? 'None', mono: true }, - { label: 'Default', value: dependency.selection.default_version ?? 'None', mono: true }, - { label: 'Installed Versions', value: String(dependency.versions.length), mono: true }, + { key: 'Source', value: `${dependency.catalog.source.owner}/${dependency.catalog.source.project}` }, + { key: 'Catalog version', value: dependency.catalog.version, mono: true }, + { key: 'Platform', value: dependency.catalog.platform_key, mono: true }, + { key: 'Package', value: sentenceCaseSnakeLabel(dependency.catalog.package_kind) }, + { key: 'Archive', value: dependency.catalog.archive_kind ? sentenceCaseSnakeLabel(dependency.catalog.archive_kind) : 'None' }, + { key: 'Selected', value: dependency.selection.selected_version ?? 'None', mono: true }, + { key: 'Active', value: dependency.selection.active_version ?? 'None', mono: true }, + { key: 'Default', value: dependency.selection.default_version ?? 'None', mono: true }, + { key: 'Installed versions', value: String(dependency.versions.length), mono: true }, ]; } @@ -121,46 +122,74 @@ export function managedMediaVersionStatusLabel( labels.push('selected'); } if (version.readiness !== 'ready') { - labels.push(titleCaseSnakeLabel(version.readiness).toLowerCase()); + labels.push(sentenceCaseSnakeLabel(version.readiness).toLowerCase()); } return labels.join(' | '); } -export function managedMediaDependencyStatusClass( +export function managedMediaDependencyGlyph( dependency: WorkflowManagedMediaDependencyStatus, -): string { +): GlyphState { if (dependency.readiness === 'ready' && dependency.install_state === 'installed') { - return 'border-emerald-800 bg-emerald-950/40 text-emerald-200'; + return 'succeeded'; } if (dependency.install_state === 'unsupported' || dependency.readiness === 'unsupported') { - return 'border-neutral-700 bg-neutral-900 text-neutral-400'; + return 'idle'; } - return 'border-amber-800 bg-amber-950/40 text-amber-200'; + return 'warn'; +} + +export function formatCapabilityCount(options: WorkflowMediaFormatOption[] | undefined): string { + const count = options?.length ?? 0; + return `${count} ${count === 1 ? 'format' : 'formats'}`; +} + +/** One line for the format defaults heading, for example "Image 2 formats, audio 1 format, ...". */ +export function formatCapabilitySummary( + capabilities: WorkflowArtifactFormatCapabilities | null, +): string { + return [ + `Image ${formatCapabilityCount(capabilities?.image_formats)}`, + `audio ${formatCapabilityCount(capabilities?.audio_formats)}`, + `video ${formatCapabilityCount(capabilities?.video_formats)}`, + `3D ${formatCapabilityCount(capabilities?.three_d_formats)}`, + ].join(', '); +} + +export function buildCapabilityRows( + capabilities: WorkflowArtifactFormatCapabilities | null, +): SettingsPolicyRow[] { + return [ + { key: 'Image', value: formatCapabilityCount(capabilities?.image_formats), mono: true }, + { key: 'Audio', value: formatCapabilityCount(capabilities?.audio_formats), mono: true }, + { key: 'Video', value: formatCapabilityCount(capabilities?.video_formats), mono: true }, + { key: '3D', value: formatCapabilityCount(capabilities?.three_d_formats), mono: true }, + ]; } export function buildArtifactPolicyRows(policy: WorkflowArtifactPolicy | null): SettingsPolicyRow[] { if (!policy) { return [ - { label: 'Policy', value: 'Unavailable' }, - { label: 'Version', value: 'Unavailable' }, - { label: 'TTL', value: 'Unavailable' }, - { label: 'Disk Budget', value: 'Unavailable' }, - { label: 'Memory Budget', value: 'Unavailable' }, - { label: 'Single Artifact Limit', value: 'Unavailable' }, - { label: 'Spill Threshold', value: 'Unavailable' }, - { label: 'Delete On Consume', value: 'Unavailable' }, + { key: 'Policy', value: 'Unavailable' }, + { key: 'Version', value: 'Unavailable' }, + { key: 'TTL', value: 'Unavailable' }, + { key: 'Disk budget', value: 'Unavailable' }, + { key: 'Memory budget', value: 'Unavailable' }, + { key: 'Single artifact limit', value: 'Unavailable' }, + { key: 'Spill threshold', value: 'Unavailable' }, + { key: 'Delete on consume', value: 'Unavailable' }, ]; } return [ - { label: 'Policy', value: policy.policy_id, mono: true }, - { label: 'Version', value: String(policy.policy_version), mono: true }, - { label: 'TTL', value: formatSettingsSeconds(policy.ttl_seconds) }, - { label: 'Disk Budget', value: formatSettingsBytes(policy.max_disk_bytes) }, - { label: 'Memory Budget', value: formatSettingsBytes(policy.max_memory_bytes) }, - { label: 'Single Artifact Limit', value: formatSettingsBytes(policy.max_single_artifact_bytes) }, - { label: 'Spill Threshold', value: formatSettingsBytes(policy.spill_threshold_bytes) }, - { label: 'Delete On Consume', value: formatBooleanPolicy(policy.delete_on_consume) }, + { key: 'Policy', value: policy.policy_id, mono: true }, + { key: 'Version', value: String(policy.policy_version), mono: true }, + { key: 'TTL', value: formatSettingsSeconds(policy.ttl_seconds) }, + { key: 'Disk budget', value: formatSettingsBytes(policy.max_disk_bytes) }, + { key: 'Memory budget', value: formatSettingsBytes(policy.max_memory_bytes) }, + { key: 'Single artifact limit', value: formatSettingsBytes(policy.max_single_artifact_bytes) }, + { key: 'Spill threshold', value: formatSettingsBytes(policy.spill_threshold_bytes) }, + { key: 'Delete on consume', value: formatBooleanPolicy(policy.delete_on_consume) }, ]; } @@ -169,18 +198,18 @@ export function buildDiagnosticsRetentionPolicyRows( ): SettingsPolicyRow[] { if (!policy) { return [ - { label: 'Policy', value: 'Unavailable' }, - { label: 'Version', value: 'Unavailable' }, - { label: 'Class', value: 'Unavailable' }, - { label: 'Days', value: 'Unavailable' }, + { key: 'Policy', value: 'Unavailable' }, + { key: 'Version', value: 'Unavailable' }, + { key: 'Class', value: 'Unavailable' }, + { key: 'Days', value: 'Unavailable' }, ]; } return [ - { label: 'Policy', value: policy.policy_id, mono: true }, - { label: 'Version', value: String(policy.policy_version), mono: true }, - { label: 'Class', value: policy.retention_class, mono: true }, - { label: 'Days', value: String(policy.retention_days) }, + { key: 'Policy', value: policy.policy_id, mono: true }, + { key: 'Version', value: String(policy.policy_version), mono: true }, + { key: 'Class', value: policy.retention_class, mono: true }, + { key: 'Days', value: String(policy.retention_days) }, ]; } @@ -194,24 +223,24 @@ export function buildDiagnosticsRetentionSettingRows( const settings = policy.settings; return [ { - label: 'Final Outputs', + key: 'Final outputs', value: formatRetentionPolicyMode(settings.final_outputs), }, { - label: 'Workflow Inputs', + key: 'Workflow inputs', value: formatRetentionPolicyMode(settings.workflow_inputs), }, { - label: 'Intermediate Node I/O', + key: 'Intermediate node I/O', value: formatRetentionPolicyMode(settings.intermediate_node_io), }, { - label: 'Failed Run Data', + key: 'Failed run data', value: formatRetentionPolicyMode(settings.failed_run_data), }, { - label: 'Cleanup Trigger', - value: titleCaseSnakeLabel(settings.cleanup_trigger), + key: 'Cleanup trigger', + value: sentenceCaseSnakeLabel(settings.cleanup_trigger), }, ]; } @@ -224,12 +253,12 @@ export function buildDiagnosticsRetentionCleanupRows( } return [ - { label: 'Policy', value: cleanup.policy_id, mono: true }, - { label: 'Version', value: String(cleanup.policy_version), mono: true }, - { label: 'Class', value: cleanup.retention_class, mono: true }, - { label: 'Cutoff', value: formatSettingsTimestamp(cleanup.cutoff_occurred_before_ms) }, - { label: 'Expired', value: String(cleanup.expired_artifact_count) }, - { label: 'Last Event Seq', value: String(cleanup.last_event_seq ?? 'Unavailable'), mono: true }, + { key: 'Policy', value: cleanup.policy_id, mono: true }, + { key: 'Version', value: String(cleanup.policy_version), mono: true }, + { key: 'Class', value: cleanup.retention_class, mono: true }, + { key: 'Cutoff', value: formatSettingsTimestamp(cleanup.cutoff_occurred_before_ms) }, + { key: 'Expired', value: String(cleanup.expired_artifact_count) }, + { key: 'Last event seq', value: String(cleanup.last_event_seq ?? 'Unavailable'), mono: true }, ]; } @@ -327,18 +356,19 @@ export function parseNullableIntegerField( return { value, error: null }; } -function titleCaseSnakeLabel(value: string): string { - return value - .split('_') - .filter((part) => part.length > 0) - .map((part) => `${part[0].toUpperCase()}${part.slice(1)}`) - .join(' '); +function sentenceCaseSnakeLabel(value: string): string { + const words = value.split('_').filter((part) => part.length > 0); + if (words.length === 0) { + return ''; + } + const [first, ...rest] = words; + return [`${first[0].toUpperCase()}${first.slice(1)}`, ...rest].join(' '); } function formatRetentionPolicyMode( policy: DiagnosticsRetentionPolicy['settings']['final_outputs'], ): string { - return `${policy.retention_days} days, ${titleCaseSnakeLabel(policy.payload_mode)}`; + return `${policy.retention_days} days, ${sentenceCaseSnakeLabel(policy.payload_mode)}`; } function formatSettingsTimestamp(value: number): string { diff --git a/src/components/workbench/shell/README.md b/src/components/workbench/shell/README.md new file mode 100644 index 000000000..8eb00e5e0 --- /dev/null +++ b/src/components/workbench/shell/README.md @@ -0,0 +1,102 @@ +# Workbench shell: run context + +## Purpose + +Owns the single control that chooses which run every workbench tab shows: the +header run chip and its popover, the run list it offers, and the Ctrl/Cmd+C, +Ctrl/Cmd+V shortcuts for run ids. + +## Contents + +| File | Responsibility | +| --- | --- | +| `RunContextPicker.svelte` | Chip, popover (search, grouped rows), copy toast. Mounted once by `WorkbenchShell.svelte`; owns the lifecycle of the sync and clipboard listeners. | +| `runContextPicker.ts` | Pure helpers: status to group, search and paste resolution, row decoration, chip content, engine line text. | +| `runContextRunList.ts` | Run-list source with current-invocation authority (generation token) and typed refresh outcomes. | +| `runContextClipboard.ts` | Delegated hover tracking over `data-run-id` elements and the document keydown handler for copy and paste. | +| `runContextStore.ts` | Shared picker state and the actions pages call; wires the run-list source to `workflowService.queryRunList`. | + +## Problem + +The redesign makes the selected run the context of every tab, shown once in +the header. Selecting, clearing, pasting and copying run ids must behave the +same from any tab, and the run list behind the picker must come from the +scheduler projection rather than ledger rows. + +## Constraints + +- ADR-014: the active run is transient state in `workbenchStore`; the picker + only calls `selectActiveWorkflowRun` and `clearActiveWorkflowRun`. +- The run list comes from `workflowService.queryRunList` (the scheduler + run-list projection), never from the diagnostics ledger. +- Listeners and timers that outlive one call have one owner and are removed on + destroy (Coding-Standards `topic.concurrency`, TypeScript async profile). +- Keystrokes typed into inputs, selects, textareas and editable elements are + never intercepted. + +## Decision + +The picker component is the owner: on mount it calls `startRunContextSync()` +(attach the run-list source, load once, subscribe to `run_list` projection +invalidations) and attaches one clipboard controller to `document`; on destroy +it detaches both and clears the toast timer. Overlapping run-list refreshes are +resolved by a generation token so only the newest result is applied; paste +reads use the same mechanism so a read that resolves after the popover closed +is not applied. The heading set of this README is required by +`scripts/check-decision-traceability.sh` (issue WR-001). + +## Alternatives Rejected + +- Per-element `mouseenter` handlers for copy hover: every page would have to + wire handlers. One delegated `pointerover` listener plus a `data-run-id` + attribute keeps pages declarative. +- Reading the run list from the Scheduler page's local state: the picker must + work on every tab, including before Scheduler has mounted. +- `localStorage` for the copy fallback (as in the mockup): it would persist a + run id across restarts, which ADR-014 rules out for run selection. + +## Invariants + +- At most one attachment of the run-list source and of the clipboard + controller; a second `attach()` throws. +- A refresh or paste that is superseded, or completes after detach, never + writes state. +- Transport failures keep the last projection rows and record the first + unreachable time; backend errors keep the engine marked online. +- Selecting a run closes the popover; Escape and selection return focus to the + chip; an outside click leaves focus where the pointer put it. + +## Revisit Triggers + +- The run-list projection gains a memory-wait status (add the "Waiting for + memory" group; issue WR-004). +- The Scheduler filters client-side over the 250 newest runs this store holds (WR-M1-1). Revisit when a page needs server-side filtering over older runs: either widen this store's query or give the Scheduler a filtered query while keeping one owner of refresh. +- The desktop host grants or denies clipboard permissions differently from the + browser fallback described here. + +## Dependencies + +**Internal:** `src/stores/workbenchStore.ts`, +`src/services/workflow/WorkflowService.ts`, +`src/services/workflow/WorkflowProjectionSubscriptionService.ts`, +`src/services/workflow/workflowServiceErrors.ts`, `../ui/` (StatusGlyph, Toast). + +**External:** `svelte` (stores, lifecycle). + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```svelte + + + +{run.workflow_run_id} + + + +``` diff --git a/src/components/workbench/shell/RunContextPicker.svelte b/src/components/workbench/shell/RunContextPicker.svelte new file mode 100644 index 000000000..27d06199e --- /dev/null +++ b/src/components/workbench/shell/RunContextPicker.svelte @@ -0,0 +1,457 @@ + + + + +
+ {#if chip.kind === 'run'} +
+ + +
+ {:else} + + {/if} + + {#if $runContextPicker.open} + + {/if} +
+ + + + diff --git a/src/components/workbench/shell/runContextClipboard.test.ts b/src/components/workbench/shell/runContextClipboard.test.ts new file mode 100644 index 000000000..6581a41b7 --- /dev/null +++ b/src/components/workbench/shell/runContextClipboard.test.ts @@ -0,0 +1,227 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + createRunContextClipboard, + isEditableTarget, + runIdFromTarget, + type ListenerTarget, + type RunContextClipboardDeps, +} from './runContextClipboard.ts'; + +type Listener = (event: Event) => void; + +class FakeTarget implements ListenerTarget { + listeners = new Map(); + + addEventListener(type: string, listener: Listener): void { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); + } + + removeEventListener(type: string, listener: Listener): void { + this.listeners.set(type, (this.listeners.get(type) ?? []).filter((entry) => entry !== listener)); + } + + count(): number { + return [...this.listeners.values()].reduce((total, list) => total + list.length, 0); + } + + dispatch(type: string, event: Record): void { + for (const listener of this.listeners.get(type) ?? []) listener(event as unknown as Event); + } +} + +interface FakeElement { + tagName: string; + parent: FakeElement | null; + getAttribute(name: string): string | null; + closest(selector: string): FakeElement | null; +} + +/** Minimal element: `closest` walks a parent chain matching attribute selectors. */ +function element( + attributes: Record, + parent: FakeElement | null = null, + tagName = 'DIV', +): FakeElement { + const node: FakeElement = { + tagName, + parent, + getAttribute: (name) => attributes[name] ?? null, + closest(selector) { + const attribute = selector.slice(1, -1); + for (let current: FakeElement | null = node; current; current = current.parent) { + if (current.getAttribute(attribute) !== null) return current; + } + return null; + }, + }; + return node; +} + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +function harness(overrides: Partial = {}) { + const target = new FakeTarget(); + const copied: Array<[string, string]> = []; + const pasted: Array<[string, string]> = []; + const controller = createRunContextClipboard({ + target, + onCopied: (runId, outcome) => copied.push([runId, outcome]), + onPaste: (text, source) => pasted.push([text, source]), + ...overrides, + }); + return { target, controller, copied, pasted }; +} + +const flush = () => new Promise((resolve) => setImmediate(resolve)); + +test('attach adds one listener per event, refuses a second owner, detach removes them', () => { + const { target, controller } = harness(); + controller.attach(); + assert.equal(target.count(), 3); + assert.throws(() => controller.attach(), /already attached/); + assert.equal(target.count(), 3); + controller.detach(); + controller.detach(); + assert.equal(target.count(), 0); +}); + +test('hover over a data-run-id element and Ctrl+C copies that run id', async () => { + const writes: string[] = []; + const { target, controller, copied } = harness({ + writeText: async (text) => { + writes.push(text); + }, + }); + controller.attach(); + const row = element({ 'data-run-id': 'run_a' }); + const child = element({}, row, 'SPAN'); + target.dispatch('pointerover', { target: child }); + assert.equal(controller.hoveredRunId(), 'run_a'); + + let prevented = false; + target.dispatch('keydown', { key: 'c', ctrlKey: true, target: child, preventDefault: () => (prevented = true) }); + await flush(); + assert.equal(prevented, true); + assert.deepEqual(writes, ['run_a']); + assert.deepEqual(copied, [['run_a', 'clipboard']]); + + // Cmd+C works the same; moving off the row stops copying. + target.dispatch('keydown', { key: 'C', metaKey: true, target: child }); + await flush(); + assert.equal(copied.length, 2); + target.dispatch('pointerover', { target: element({}) }); + target.dispatch('keydown', { key: 'c', ctrlKey: true, target: child }); + await flush(); + assert.equal(copied.length, 2); +}); + +test('keystrokes in fields, with a text selection or without a modifier are ignored', async () => { + let selection = false; + const { target, controller, copied } = harness({ hasTextSelection: () => selection }); + controller.attach(); + target.dispatch('pointerover', { target: element({ 'data-run-id': 'run_a' }) }); + + target.dispatch('keydown', { key: 'c', ctrlKey: true, target: { tagName: 'INPUT' } }); + target.dispatch('keydown', { key: 'c', ctrlKey: true, target: { tagName: 'div', isContentEditable: true } }); + target.dispatch('keydown', { key: 'c', target: element({}) }); + target.dispatch('keydown', { key: 'c', ctrlKey: true, altKey: true, target: element({}) }); + selection = true; + target.dispatch('keydown', { key: 'c', ctrlKey: true, target: element({}) }); + await flush(); + assert.deepEqual(copied, []); +}); + +test('a failed clipboard write still copies for this window and the paste falls back to it', async () => { + const { target, controller, copied, pasted } = harness({ + writeText: () => Promise.reject(new Error('denied')), + readText: () => Promise.reject(new Error('denied')), + }); + controller.attach(); + target.dispatch('pointerover', { target: element({ 'data-run-id': 'run_a' }) }); + target.dispatch('keydown', { key: 'c', ctrlKey: true, target: element({}) }); + await flush(); + assert.deepEqual(copied, [['run_a', 'in_app']]); + + target.dispatch('pointerover', { target: element({ 'data-run-context-chip': '' }) }); + assert.equal(controller.isChipHovered(), true); + target.dispatch('keydown', { key: 'v', ctrlKey: true, target: element({}) }); + await flush(); + assert.deepEqual(pasted, [['run_a', 'in_app']]); +}); + +test('paste with no clipboard and nothing copied hands an empty string to open the picker', async () => { + const { controller, pasted } = harness(); + controller.attach(); + assert.equal(await controller.pasteIntoRunContext(), 'applied'); + assert.deepEqual(pasted, [['', 'none']]); +}); + +test('Ctrl+V only acts while the pointer is over the chip', async () => { + const reads: number[] = []; + const { target, controller, pasted } = harness({ + readText: async () => { + reads.push(1); + return ' run_b '; + }, + }); + controller.attach(); + target.dispatch('keydown', { key: 'v', ctrlKey: true, target: element({}) }); + await flush(); + assert.equal(reads.length, 0); + + target.dispatch('pointerover', { target: element({}, element({ 'data-run-context-chip': '' })) }); + target.dispatch('keydown', { key: 'v', ctrlKey: true, target: element({}) }); + await flush(); + assert.deepEqual(pasted, [['run_b', 'clipboard']]); +}); + +test('a clipboard read that resolves after cancel, a newer paste or detach is not applied', async () => { + const reads: Array>> = []; + const { controller, pasted } = harness({ + readText: () => { + const next = deferred(); + reads.push(next); + return next.promise; + }, + }); + controller.attach(); + + const cancelled = controller.pasteIntoRunContext(); + controller.cancelPendingPaste(); + reads[0].resolve('run_cancelled'); + assert.equal(await cancelled, 'superseded'); + + const older = controller.pasteIntoRunContext(); + const newer = controller.pasteIntoRunContext(); + reads[2].resolve('run_newer'); + reads[1].resolve('run_older'); + assert.equal(await newer, 'applied'); + assert.equal(await older, 'superseded'); + + const late = controller.pasteIntoRunContext(); + controller.detach(); + reads[3].resolve('run_late'); + assert.equal(await late, 'superseded'); + + assert.deepEqual(pasted, [['run_newer', 'clipboard']]); +}); + +test('target helpers find the nearest run id and recognise editable targets', () => { + const row = element({ 'data-run-id': ' run_x ' }); + assert.equal(runIdFromTarget(element({}, row)), 'run_x'); + assert.equal(runIdFromTarget(element({ 'data-run-id': '' })), null); + assert.equal(runIdFromTarget(null), null); + assert.equal(isEditableTarget({ tagName: 'textarea' }), true); + assert.equal(isEditableTarget({ tagName: 'SELECT' }), true); + assert.equal(isEditableTarget({ tagName: 'BUTTON' }), false); +}); diff --git a/src/components/workbench/shell/runContextClipboard.ts b/src/components/workbench/shell/runContextClipboard.ts new file mode 100644 index 000000000..43591fb32 --- /dev/null +++ b/src/components/workbench/shell/runContextClipboard.ts @@ -0,0 +1,207 @@ +/** + * Clipboard shortcuts for run ids (spec "Run-context picker", Clipboard). + * + * - Ctrl/Cmd+C while the pointer is over any element carrying + * `data-run-id=""` copies that id. + * - Ctrl/Cmd+V while the pointer is over the run chip + * (`data-run-context-chip`) reads the clipboard and hands the text to + * `onPaste`, which selects a known run or opens the picker. + * + * Hover is tracked with one delegated `pointerover` listener, so pages only + * add the attribute; they never register handlers. Keystrokes whose target is + * an input, select, textarea or editable element are ignored, as is Ctrl+C + * while the user has selected text (the browser's copy wins). + * + * Lifecycle: one controller per shell. `attach()` adds exactly one listener + * per event type and throws if called twice; `detach()` removes them and + * invalidates any clipboard read still in flight. A read that completes after + * `cancelPendingPaste()`, a newer paste, or `detach()` is classified + * `superseded` and is not applied. + * + * Fallbacks: if the clipboard cannot be written, the id is kept in memory for + * this window and `onCopied` reports `in_app`. If it cannot be read, the last + * id copied in this window is used; with none, `onPaste('')` lets the caller + * open the picker. + */ + +export const RUN_ID_ATTRIBUTE = 'data-run-id'; +export const RUN_CONTEXT_CHIP_ATTRIBUTE = 'data-run-context-chip'; + +export type RunCopyOutcome = 'clipboard' | 'in_app'; +export type RunPasteSource = 'clipboard' | 'in_app' | 'none'; +export type RunPasteOutcome = 'applied' | 'superseded'; + +/** The subset of a DOM event target the controller needs. */ +export interface ListenerTarget { + addEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; +} + +export interface RunContextClipboardDeps { + target: ListenerTarget; + writeText?: (text: string) => Promise; + readText?: () => Promise; + /** True when the user has a non-empty text selection. */ + hasTextSelection?: () => boolean; + onCopied: (runId: string, outcome: RunCopyOutcome) => void; + onPaste: (text: string, source: RunPasteSource) => void; +} + +export interface RunContextClipboard { + attach(): void; + detach(): void; + isAttached(): boolean; + /** Invalidate a clipboard read in flight (picker closed, run chosen). */ + cancelPendingPaste(): void; + copyRunId(runId: string): Promise; + pasteIntoRunContext(): Promise; + /** Hover state, exposed for tests and diagnostics. */ + hoveredRunId(): string | null; + isChipHovered(): boolean; +} + +interface ElementLike { + tagName?: string; + isContentEditable?: boolean; + closest?: (selector: string) => ElementLike | null; + getAttribute?: (name: string) => string | null; +} + +interface KeyEventLike { + key?: string; + ctrlKey?: boolean; + metaKey?: boolean; + altKey?: boolean; + target?: unknown; + preventDefault?: () => void; +} + +const FIELD_TAGS = new Set(['INPUT', 'TEXTAREA', 'SELECT']); + +function asElement(value: unknown): ElementLike | null { + return typeof value === 'object' && value !== null ? (value as ElementLike) : null; +} + +export function isEditableTarget(target: unknown): boolean { + const element = asElement(target); + if (!element) return false; + if (element.isContentEditable) return true; + return typeof element.tagName === 'string' && FIELD_TAGS.has(element.tagName.toUpperCase()); +} + +/** The run id of the nearest `data-run-id` ancestor (inclusive), if any. */ +export function runIdFromTarget(target: unknown): string | null { + const element = asElement(target); + const holder = element?.closest?.(`[${RUN_ID_ATTRIBUTE}]`) ?? null; + const runId = holder?.getAttribute?.(RUN_ID_ATTRIBUTE)?.trim(); + return runId ? runId : null; +} + +export function isRunContextChipTarget(target: unknown): boolean { + const element = asElement(target); + return Boolean(element?.closest?.(`[${RUN_CONTEXT_CHIP_ATTRIBUTE}]`)); +} + +export function createRunContextClipboard(deps: RunContextClipboardDeps): RunContextClipboard { + let attached = false; + let hoveredRunId: string | null = null; + let chipHovered = false; + let lastCopiedRunId: string | null = null; + let pasteGeneration = 0; + + function onPointerOver(event: Event): void { + hoveredRunId = runIdFromTarget(event.target); + chipHovered = isRunContextChipTarget(event.target); + } + + function onPointerOut(event: Event): void { + // Leaving the window: relatedTarget is null. + if ((event as Event & { relatedTarget?: unknown }).relatedTarget == null) { + hoveredRunId = null; + chipHovered = false; + } + } + + function onKeyDown(event: Event): void { + const key = event as KeyEventLike; + const withModifier = Boolean(key.ctrlKey || key.metaKey) && !key.altKey; + if (!withModifier || isEditableTarget(key.target)) return; + const letter = (key.key ?? '').toLowerCase(); + if (letter === 'c' && hoveredRunId) { + if (deps.hasTextSelection?.()) return; + key.preventDefault?.(); + void copyRunId(hoveredRunId); + return; + } + if (letter === 'v' && chipHovered) { + key.preventDefault?.(); + void pasteIntoRunContext(); + } + } + + async function copyRunId(runId: string): Promise { + lastCopiedRunId = runId; + let outcome: RunCopyOutcome = 'in_app'; + if (deps.writeText) { + try { + await deps.writeText(runId); + outcome = 'clipboard'; + } catch { + outcome = 'in_app'; + } + } + deps.onCopied(runId, outcome); + return outcome; + } + + async function pasteIntoRunContext(): Promise { + const invocation = ++pasteGeneration; + let text = ''; + let source: RunPasteSource = 'none'; + if (deps.readText) { + try { + text = await deps.readText(); + source = 'clipboard'; + } catch { + source = 'none'; + } + } + if (source === 'none' && lastCopiedRunId) { + text = lastCopiedRunId; + source = 'in_app'; + } + if (!attached || invocation !== pasteGeneration) return 'superseded'; + deps.onPaste(text.trim(), source); + return 'applied'; + } + + return { + attach() { + if (attached) { + throw new Error('Run-context clipboard is already attached; the shell owns one attachment.'); + } + attached = true; + deps.target.addEventListener('pointerover', onPointerOver); + deps.target.addEventListener('pointerout', onPointerOut); + deps.target.addEventListener('keydown', onKeyDown); + }, + detach() { + if (!attached) return; + attached = false; + pasteGeneration += 1; + hoveredRunId = null; + chipHovered = false; + deps.target.removeEventListener('pointerover', onPointerOver); + deps.target.removeEventListener('pointerout', onPointerOut); + deps.target.removeEventListener('keydown', onKeyDown); + }, + isAttached: () => attached, + cancelPendingPaste() { + pasteGeneration += 1; + }, + copyRunId, + pasteIntoRunContext, + hoveredRunId: () => hoveredRunId, + isChipHovered: () => chipHovered, + }; +} diff --git a/src/components/workbench/shell/runContextPicker.test.ts b/src/components/workbench/shell/runContextPicker.test.ts new file mode 100644 index 000000000..4ce6c0a3f --- /dev/null +++ b/src/components/workbench/shell/runContextPicker.test.ts @@ -0,0 +1,203 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import type { RunListProjectionRecord } from '../../../services/diagnostics/types'; +import { + decorateRunContextRow, + engineLineParts, + engineLineText, + formatClockTime, + formatRunDuration, + formatRunVersion, + groupRunsForContextPicker, + looksLikeRunId, + resolveRunContextInput, + runContextChip, + runContextEmptyText, + runContextGroupForRun, + runMatchesContextQuery, + shortRunId, + startOfLocalDayMs, + toActiveRunContext, +} from './runContextPicker.ts'; + +// A fixed local noon keeps "today" independent of the machine's time zone. +const NOW = new Date(2026, 10, 3, 12, 0, 0).getTime(); +const TODAY = startOfLocalDayMs(NOW); +const YESTERDAY = TODAY - 6 * 60 * 60 * 1000; + +function run( + id: string, + status: RunListProjectionRecord['status'], + extra: Partial = {}, +): RunListProjectionRecord { + return { + workflow_run_id: id, + workflow_id: 'ingest-docs-rag', + workflow_semantic_version: '1.4.0', + status, + last_event_seq: 1, + last_updated_at_ms: NOW - 1000, + ...extra, + }; +} + +const RUNS: RunListProjectionRecord[] = [ + run('run_running_a', 'running', { selected_runtime_id: 'llama.cpp', selected_device_id: 'cuda:0' }), + run('run_queued_2', 'queued', { workflow_id: 'summarize-daily', scheduler_queue_position: 2 }), + run('run_queued_1', 'scheduled', { workflow_id: 'embed-corpus', scheduler_queue_position: 1 }), + run('run_delayed', 'delayed', { workflow_id: 'transcribe-meeting', scheduler_reason: 'needs 8 GB on cuda:0' }), + run('run_done_today', 'completed', { completed_at_ms: NOW - 5000, duration_ms: 38_000 }), + run('run_failed_today', 'failed', { + workflow_id: 'image-gen-sdxl', + workflow_semantic_version: '0.9.1', + completed_at_ms: NOW - 2000, + latest_error_message: 'out of memory, needed 14.2 GB', + }), + run('run_old', 'cancelled', { completed_at_ms: YESTERDAY, duration_ms: 70_000 }), +]; + +test('statuses map to Running, Queued and the finished groups by local day', () => { + assert.equal(runContextGroupForRun(run('a', 'running'), TODAY), 'running'); + for (const status of ['accepted', 'future', 'scheduled', 'queued', 'delayed'] as const) { + assert.equal(runContextGroupForRun(run('a', status), TODAY), 'queued', status); + } + assert.equal(runContextGroupForRun(run('a', 'completed', { completed_at_ms: TODAY }), TODAY), 'finished_today'); + assert.equal(runContextGroupForRun(run('a', 'failed', { completed_at_ms: YESTERDAY }), TODAY), 'finished_earlier'); + assert.equal( + runContextGroupForRun(run('a', 'cancelled', { completed_at_ms: null, last_updated_at_ms: NOW }), TODAY), + 'finished_today', + ); +}); + +test('groups come out in spec order, omit empty groups and sort within a group', () => { + const groups = groupRunsForContextPicker(RUNS, { query: '', selectedRunId: 'run_queued_1', nowMs: NOW }); + assert.deepEqual(groups.map((group) => group.title), ['Running', 'Queued', 'Finished today', 'Finished earlier']); + assert.deepEqual( + groups[1].rows.map((row) => row.runId), + ['run_queued_1', 'run_queued_2', 'run_delayed'], + ); + assert.deepEqual(groups[2].rows.map((row) => row.runId), ['run_failed_today', 'run_done_today']); + assert.equal(groups[1].rows[0].selected, true); + assert.equal(groups[1].rows[1].selected, false); + + const onlyRunning = groupRunsForContextPicker([RUNS[0]], { query: '', selectedRunId: null, nowMs: NOW }); + assert.deepEqual(onlyRunning.map((group) => group.id), ['running']); +}); + +test('search matches workflow id, run id and version', () => { + assert.equal(runMatchesContextQuery(RUNS[0], 'INGEST'), true); + assert.equal(runMatchesContextQuery(RUNS[0], 'running_a'), true); + assert.equal(runMatchesContextQuery(RUNS[5], 'v0.9.1'), true); + assert.equal(runMatchesContextQuery(RUNS[5], '0.9'), true); + assert.equal(runMatchesContextQuery(RUNS[0], 'sdxl'), false); + const groups = groupRunsForContextPicker(RUNS, { query: 'sdxl', selectedRunId: null, nowMs: NOW }); + assert.deepEqual(groups.flatMap((group) => group.rows.map((row) => row.runId)), ['run_failed_today']); +}); + +test('typed or pasted text resolves to select, unknown run id, search or empty', () => { + const selected = resolveRunContextInput(' run_queued_2 ', RUNS); + assert.equal(selected.kind, 'select'); + assert.equal(selected.kind === 'select' && selected.run.workflow_run_id, 'run_queued_2'); + + assert.deepEqual(resolveRunContextInput('run_01JB2ZZZZZ', RUNS), { + kind: 'unknown_run_id', + runId: 'run_01JB2ZZZZZ', + }); + assert.deepEqual(resolveRunContextInput('embed', RUNS), { kind: 'search', query: 'embed' }); + assert.deepEqual(resolveRunContextInput(' ', RUNS), { kind: 'empty' }); + assert.equal(looksLikeRunId('run_7c9e6679-7425-40de-944b-e07fc1f90ae7'), true); + assert.equal(looksLikeRunId('run with spaces'), false); +}); + +test('empty text explains unknown ids, no matches, loading and an unreachable engine', () => { + const online = { kind: 'online' } as const; + assert.equal( + runContextEmptyText({ query: 'run_abc', runCount: 3, availability: online, loading: false }), + 'No run with id run_abc in recent history.', + ); + assert.equal(runContextEmptyText({ query: 'zzz', runCount: 3, availability: online, loading: false }), 'No runs match.'); + assert.equal(runContextEmptyText({ query: '', runCount: 0, availability: online, loading: true }), 'Loading runs…'); + assert.match( + runContextEmptyText({ + query: '', + runCount: 0, + availability: { kind: 'unreachable', sinceMs: NOW, hasProjection: false }, + loading: false, + }), + /engine did not answer/, + ); +}); + +test('row decoration carries status label and one-line context', () => { + const byId = new Map(RUNS.map((record) => [record.workflow_run_id, record])); + const decorate = (id: string) => decorateRunContextRow(byId.get(id)!, null); + assert.equal(decorate('run_running_a').contextSuffix, ', llama.cpp on cuda:0'); + assert.equal(decorate('run_queued_2').contextSuffix, ', #2 in queue'); + assert.equal(decorate('run_delayed').statusLabel, 'Delayed'); + assert.equal(decorate('run_delayed').contextSuffix, ', needs 8 GB on cuda:0'); + assert.equal(decorate('run_delayed').glyph, 'queued'); + assert.equal(decorate('run_failed_today').statusIsFailure, true); + assert.equal(decorate('run_failed_today').contextSuffix, ', out of memory, needed 14.2 GB'); + assert.equal(decorate('run_done_today').contextSuffix, ', 38 s'); + assert.equal(decorate('run_done_today').versionLabel, 'v1.4.0'); +}); + +test('formatters keep durations, versions, clock times and short ids compact', () => { + assert.equal(formatRunDuration(38_000), '38 s'); + assert.equal(formatRunDuration(252_000), '4m 12s'); + assert.equal(formatRunDuration(3_780_000), '1h 03m'); + assert.equal(formatRunDuration(null), null); + assert.equal(formatRunVersion('1.4.0'), 'v1.4.0'); + assert.equal(formatRunVersion('v2.0.0'), 'v2.0.0'); + assert.equal(formatRunVersion(' '), null); + assert.equal(formatClockTime(new Date(2026, 10, 3, 9, 5).getTime()), '09:05'); + assert.equal(shortRunId('run_7c9e6679-7425-40de-944b-e07fc1f90ae7'), 'run_…c1f90ae7'); + assert.equal(shortRunId('run_01JB2K7Q3M'), 'run_01JB2K7Q3M'); +}); + +test('chip prefers the fresher run-list status over the status captured at selection', () => { + assert.deepEqual(runContextChip(null, RUNS), { kind: 'none' }); + const chip = runContextChip( + { workflow_run_id: 'run_failed_today', workflow_id: 'image-gen-sdxl', workflow_semantic_version: '0.9.1', status: 'running' }, + RUNS, + ); + assert.equal(chip.kind, 'run'); + assert.equal(chip.kind === 'run' && chip.glyph, 'failed'); + assert.equal(chip.kind === 'run' && chip.versionLabel, 'v0.9.1'); + + const absent = runContextChip( + { workflow_run_id: 'run_gone', workflow_id: null, workflow_semantic_version: null, status: 'completed' }, + RUNS, + ); + assert.equal(absent.kind === 'run' && absent.workflowLabel, 'run_gone'); + assert.equal(absent.kind === 'run' && absent.glyph, 'succeeded'); +}); + +test('selection context copies the projection identity fields', () => { + assert.deepEqual(toActiveRunContext(RUNS[1]), { + workflow_run_id: 'run_queued_2', + workflow_id: 'summarize-daily', + workflow_version_id: null, + workflow_semantic_version: '1.4.0', + status: 'queued', + }); +}); + +test('engine line names the unreachable time and whether a projection is shown', () => { + const since = new Date(2026, 10, 3, 20, 3).getTime(); + assert.equal(engineLineText({ kind: 'online' }), 'Local engine'); + assert.equal( + engineLineText({ kind: 'unreachable', sinceMs: since, hasProjection: true }), + 'Engine unreachable since 20:03, showing last projection', + ); + assert.equal( + engineLineText({ kind: 'unreachable', sinceMs: since, hasProjection: false }), + 'Engine unreachable since 20:03, nothing loaded yet', + ); + assert.deepEqual(engineLineParts({ kind: 'unreachable', sinceMs: since, hasProjection: true }), { + headline: 'Engine unreachable since 20:03', + detail: 'showing last projection', + }); + assert.equal(engineLineText({ kind: 'unknown' }), 'Local engine, connecting'); +}); diff --git a/src/components/workbench/shell/runContextPicker.ts b/src/components/workbench/shell/runContextPicker.ts new file mode 100644 index 000000000..dba123aaa --- /dev/null +++ b/src/components/workbench/shell/runContextPicker.ts @@ -0,0 +1,359 @@ +/** + * Pure presentation logic for the header run-context picker. + * + * Input is the scheduler run-list projection (`RunListProjectionRecord`, from + * `workflowService.queryRunList`); output is what the chip and popover render. + * Nothing here reads the diagnostic ledger, the DOM, timers or the clipboard. + */ +import type { + RunListProjectionRecord, + RunListProjectionStatus, +} from '../../../services/diagnostics/types'; +import type { ActiveWorkflowRunContext } from '../../../stores/workbenchStore'; +import { glyphStateForStatus, type GlyphState } from '../ui/statusGlyph.ts'; + +/** Rows the picker asks the run-list projection for. */ +export const RUN_CONTEXT_RUN_LIMIT = 250; + +export type RunContextGroupId = 'running' | 'queued' | 'finished_today' | 'finished_earlier'; + +export interface RunContextRow { + runId: string; + workflowId: string; + versionLabel: string | null; + statusLabel: string; + statusIsFailure: boolean; + /** Text after the status label, starting with ", " when present. */ + contextSuffix: string; + glyph: GlyphState; + selected: boolean; + record: RunListProjectionRecord; +} + +export interface RunContextGroup { + id: RunContextGroupId; + title: string; + rows: RunContextRow[]; +} + +export type RunContextInputResolution = + | { kind: 'empty' } + | { kind: 'select'; run: RunListProjectionRecord } + | { kind: 'unknown_run_id'; runId: string } + | { kind: 'search'; query: string }; + +export type RunContextChip = + | { kind: 'none' } + | { + kind: 'run'; + runId: string; + workflowLabel: string; + versionLabel: string | null; + statusLabel: string; + glyph: GlyphState; + }; + +export type EngineAvailability = + | { kind: 'unknown' } + | { kind: 'online' } + | { kind: 'unreachable'; sinceMs: number; hasProjection: boolean }; + +const GROUP_TITLES: Record = { + running: 'Running', + queued: 'Queued', + finished_today: 'Finished today', + finished_earlier: 'Finished earlier', +}; + +const GROUP_ORDER: RunContextGroupId[] = ['running', 'queued', 'finished_today', 'finished_earlier']; + +const STATUS_LABELS: Record = { + accepted: 'Accepted', + future: 'Future', + scheduled: 'Scheduled', + queued: 'Queued', + delayed: 'Delayed', + running: 'Running', + completed: 'Completed', + failed: 'Failed', + cancelled: 'Cancelled', +}; + +const RUN_ID_PATTERN = /^run_\S+$/i; + +export function runContextStatusLabel(status: string | null | undefined): string { + if (status && status in STATUS_LABELS) { + return STATUS_LABELS[status as RunListProjectionStatus]; + } + return 'Status unknown'; +} + +/** + * Picker group for a run. The run-list projection has no "waiting for memory" + * state today (see issues.md WR-004), so the spec's Waiting group is not + * produced; delayed runs sit with the queued ones. + */ +export function runContextGroupForRun( + run: Pick, + startOfTodayMs: number, +): RunContextGroupId { + switch (run.status) { + case 'running': + return 'running'; + case 'accepted': + case 'future': + case 'scheduled': + case 'queued': + case 'delayed': + return 'queued'; + case 'completed': + case 'failed': + case 'cancelled': { + const finishedAt = run.completed_at_ms ?? run.last_updated_at_ms; + return finishedAt >= startOfTodayMs ? 'finished_today' : 'finished_earlier'; + } + } +} + +/** Local midnight for the day containing `nowMs`. */ +export function startOfLocalDayMs(nowMs: number): number { + const day = new Date(nowMs); + day.setHours(0, 0, 0, 0); + return day.getTime(); +} + +export function looksLikeRunId(text: string): boolean { + return RUN_ID_PATTERN.test(text.trim()); +} + +/** + * Compact run id for narrow places: `run_` plus the last eight characters. + * The full id stays available in the row title and the copied text. + */ +export function shortRunId(runId: string): string { + if (runId.length <= 16) return runId; + const prefix = runId.startsWith('run_') ? 'run_' : ''; + return `${prefix}…${runId.slice(-8)}`; +} + +export function formatRunVersion(version: string | null | undefined): string | null { + const trimmed = version?.trim(); + if (!trimmed) return null; + return trimmed.startsWith('v') ? trimmed : `v${trimmed}`; +} + +export function formatRunDuration(durationMs: number | null | undefined): string | null { + if (durationMs === null || durationMs === undefined || !Number.isFinite(durationMs) || durationMs < 0) { + return null; + } + const totalSeconds = Math.round(durationMs / 1000); + if (totalSeconds < 60) return `${totalSeconds} s`; + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + if (minutes < 60) return `${minutes}m ${String(seconds).padStart(2, '0')}s`; + const hours = Math.floor(minutes / 60); + return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`; +} + +/** Local wall-clock time as HH:MM. */ +export function formatClockTime(ms: number): string { + const date = new Date(ms); + return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; +} + +function placementText(run: RunListProjectionRecord): string | null { + const runtime = run.selected_runtime_id?.trim(); + const device = run.selected_device_id?.trim(); + if (runtime && device) return `${runtime} on ${device}`; + if (runtime) return `${runtime}, device not assigned yet`; + if (device) return `on ${device}`; + return null; +} + +function contextFor(run: RunListProjectionRecord): string | null { + switch (run.status) { + case 'running': + return placementText(run); + case 'accepted': + case 'future': + case 'scheduled': + case 'queued': + return typeof run.scheduler_queue_position === 'number' + ? `#${run.scheduler_queue_position} in queue` + : null; + case 'delayed': + return run.scheduler_reason?.trim() || null; + case 'failed': + return run.latest_error_message?.trim() || run.latest_error_code?.trim() || formatRunDuration(run.duration_ms); + case 'completed': + case 'cancelled': + return formatRunDuration(run.duration_ms); + } +} + +export function decorateRunContextRow( + run: RunListProjectionRecord, + selectedRunId: string | null, +): RunContextRow { + const context = contextFor(run); + return { + runId: run.workflow_run_id, + workflowId: run.workflow_id, + versionLabel: formatRunVersion(run.workflow_semantic_version), + statusLabel: runContextStatusLabel(run.status), + statusIsFailure: run.status === 'failed', + contextSuffix: context ? `, ${context}` : '', + glyph: glyphStateForStatus(run.status), + selected: run.workflow_run_id === selectedRunId, + record: run, + }; +} + +export function runMatchesContextQuery(run: RunListProjectionRecord, query: string): boolean { + const needle = query.trim().toLowerCase(); + if (!needle) return true; + const version = formatRunVersion(run.workflow_semantic_version); + return [run.workflow_id, run.workflow_run_id, version, run.workflow_version_id] + .some((value) => typeof value === 'string' && value.toLowerCase().includes(needle)); +} + +function compareRows(groupId: RunContextGroupId, left: RunListProjectionRecord, right: RunListProjectionRecord): number { + if (groupId === 'queued') { + const leftPosition = left.scheduler_queue_position ?? Number.MAX_SAFE_INTEGER; + const rightPosition = right.scheduler_queue_position ?? Number.MAX_SAFE_INTEGER; + if (leftPosition !== rightPosition) return leftPosition - rightPosition; + } + if (groupId === 'finished_today' || groupId === 'finished_earlier') { + const leftDone = left.completed_at_ms ?? left.last_updated_at_ms; + const rightDone = right.completed_at_ms ?? right.last_updated_at_ms; + if (leftDone !== rightDone) return rightDone - leftDone; + } + if (left.last_updated_at_ms !== right.last_updated_at_ms) { + return right.last_updated_at_ms - left.last_updated_at_ms; + } + return left.workflow_run_id.localeCompare(right.workflow_run_id); +} + +/** + * Filter and group runs for the popover. Empty groups are omitted; group order + * is Running, Queued, Finished today, Finished earlier. + */ +export function groupRunsForContextPicker( + runs: readonly RunListProjectionRecord[], + options: { query: string; selectedRunId: string | null; nowMs: number }, +): RunContextGroup[] { + const startOfToday = startOfLocalDayMs(options.nowMs); + const buckets = new Map(); + for (const run of runs) { + if (!runMatchesContextQuery(run, options.query)) continue; + const groupId = runContextGroupForRun(run, startOfToday); + const bucket = buckets.get(groupId) ?? []; + bucket.push(run); + buckets.set(groupId, bucket); + } + return GROUP_ORDER.flatMap((groupId) => { + const bucket = buckets.get(groupId); + if (!bucket || bucket.length === 0) return []; + return [{ + id: groupId, + title: GROUP_TITLES[groupId], + rows: [...bucket] + .sort((left, right) => compareRows(groupId, left, right)) + .map((run) => decorateRunContextRow(run, options.selectedRunId)), + }]; + }); +} + +/** + * Resolve typed or pasted text. An exact run id selects that run; text shaped + * like a run id that is not in the list is reported as unknown; anything else + * is a search query. + */ +export function resolveRunContextInput( + text: string, + runs: readonly RunListProjectionRecord[], +): RunContextInputResolution { + const trimmed = text.trim(); + if (!trimmed) return { kind: 'empty' }; + const exact = runs.find((run) => run.workflow_run_id === trimmed); + if (exact) return { kind: 'select', run: exact }; + if (looksLikeRunId(trimmed)) return { kind: 'unknown_run_id', runId: trimmed }; + return { kind: 'search', query: text }; +} + +export function runContextEmptyText(options: { + query: string; + runCount: number; + availability: EngineAvailability; + loading: boolean; +}): string { + const query = options.query.trim(); + if (query && looksLikeRunId(query)) { + return `No run with id ${query} in recent history.`; + } + if (query) return 'No runs match.'; + if (options.loading) return 'Loading runs…'; + if (options.availability.kind === 'unreachable') { + return 'The run list is unavailable because the engine did not answer.'; + } + return 'No runs yet. Runs appear here once a workflow is submitted.'; +} + +export function toActiveRunContext( + run: RunListProjectionRecord, +): Omit { + return { + workflow_run_id: run.workflow_run_id, + workflow_id: run.workflow_id, + workflow_version_id: run.workflow_version_id ?? null, + workflow_semantic_version: run.workflow_semantic_version ?? null, + status: run.status, + }; +} + +/** + * Chip content for the active run. The run-list record wins over the status + * captured at selection time because it is the fresher projection. + */ +export function runContextChip( + active: Pick | null, + runs: readonly RunListProjectionRecord[], +): RunContextChip { + if (!active) return { kind: 'none' }; + const record = runs.find((run) => run.workflow_run_id === active.workflow_run_id); + const status = record?.status ?? active.status ?? null; + return { + kind: 'run', + runId: active.workflow_run_id, + workflowLabel: record?.workflow_id ?? active.workflow_id ?? active.workflow_run_id, + versionLabel: formatRunVersion(record?.workflow_semantic_version ?? active.workflow_semantic_version), + statusLabel: runContextStatusLabel(status), + glyph: glyphStateForStatus(status), + }; +} + +export interface EngineLineParts { + /** Always visible, for example "Engine unreachable since 20:03". */ + headline: string; + /** Trailing clause that may be truncated in a narrow header. */ + detail: string | null; +} + +export function engineLineParts(availability: EngineAvailability): EngineLineParts { + switch (availability.kind) { + case 'unknown': + return { headline: 'Local engine', detail: 'connecting' }; + case 'online': + return { headline: 'Local engine', detail: null }; + case 'unreachable': + return { + headline: `Engine unreachable since ${formatClockTime(availability.sinceMs)}`, + detail: availability.hasProjection ? 'showing last projection' : 'nothing loaded yet', + }; + } +} + +export function engineLineText(availability: EngineAvailability): string { + const parts = engineLineParts(availability); + return parts.detail ? `${parts.headline}, ${parts.detail}` : parts.headline; +} diff --git a/src/components/workbench/shell/runContextRunList.test.ts b/src/components/workbench/shell/runContextRunList.test.ts new file mode 100644 index 000000000..910d2813e --- /dev/null +++ b/src/components/workbench/shell/runContextRunList.test.ts @@ -0,0 +1,174 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { get } from 'svelte/store'; + +import type { + RunListProjectionRecord, + WorkflowRunListQueryResponse, +} from '../../../services/diagnostics/types'; +import { createRunContextRunListSource, type RunListQueryFailure } from './runContextRunList.ts'; + +interface Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (error: unknown) => void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +function response(...ids: string[]): WorkflowRunListQueryResponse { + const runs: RunListProjectionRecord[] = ids.map((id) => ({ + workflow_run_id: id, + workflow_id: 'wf', + status: 'running', + last_event_seq: 1, + last_updated_at_ms: 1, + })); + return { + runs, + facets: [], + projection_state: { + projection_name: 'run_list', + projection_version: 1, + last_applied_event_seq: 1, + status: 'current', + rebuilt_at_ms: null, + updated_at_ms: 1, + }, + } as WorkflowRunListQueryResponse; +} + +function harness() { + const pending: Deferred[] = []; + const requests: unknown[] = []; + let clock = 1_000; + const source = createRunContextRunListSource({ + queryRunList: (request) => { + requests.push(request); + const next = deferred(); + pending.push(next); + return next.promise; + }, + classifyFailure: (error): RunListQueryFailure => ({ + transport: error === 'transport', + message: String(error), + }), + now: () => clock, + limit: 250, + }); + return { + source, + pending, + requests, + tick(ms: number) { + clock += ms; + }, + }; +} + +test('refresh before attach does not query', async () => { + const { source, requests } = harness(); + assert.equal(await source.refresh(), 'detached'); + assert.equal(requests.length, 0); +}); + +test('a second attach is rejected so the shell stays the single owner', () => { + const { source } = harness(); + source.attach(); + assert.throws(() => source.attach(), /already attached/); + source.detach(); + source.detach(); + assert.equal(source.isAttached(), false); +}); + +test('overlapping refreshes apply only the newest result', async () => { + const { source, pending, requests } = harness(); + source.attach(); + const first = source.refresh(); + const second = source.refresh(); + assert.deepEqual(requests, [{ limit: 250 }, { limit: 250 }]); + + pending[1].resolve(response('run_new')); + assert.equal(await second, 'applied'); + pending[0].resolve(response('run_stale')); + assert.equal(await first, 'superseded'); + + assert.deepEqual(get(source.state).runs.map((run) => run.workflow_run_id), ['run_new']); + assert.equal(get(source.state).status, 'ready'); +}); + +test('detach classifies an in-flight completion and leaves state untouched', async () => { + const { source, pending } = harness(); + source.attach(); + const inFlight = source.refresh(); + source.detach(); + pending[0].resolve(response('run_late')); + assert.equal(await inFlight, 'detached'); + assert.deepEqual(get(source.state).runs, []); + assert.equal(get(source.state).status, 'idle'); + + // Re-attaching does not resurrect the old invocation. + source.attach(); + const fresh = source.refresh(); + pending[1].resolve(response('run_fresh')); + assert.equal(await fresh, 'applied'); + assert.deepEqual(get(source.state).runs.map((run) => run.workflow_run_id), ['run_fresh']); +}); + +test('transport failure keeps the last projection and the first unreachable time', async () => { + const { source, pending, tick } = harness(); + source.attach(); + const loaded = source.refresh(); + pending[0].resolve(response('run_kept')); + await loaded; + + tick(5_000); + const down = source.refresh(); + pending[1].reject('transport'); + assert.equal(await down, 'unreachable'); + let state = get(source.state); + assert.deepEqual(state.availability, { kind: 'unreachable', sinceMs: 6_000, hasProjection: true }); + assert.deepEqual(state.runs.map((run) => run.workflow_run_id), ['run_kept']); + + tick(5_000); + const stillDown = source.refresh(); + pending[2].reject('transport'); + await stillDown; + state = get(source.state); + assert.equal(state.availability.kind === 'unreachable' && state.availability.sinceMs, 6_000); + + const back = source.refresh(); + pending[3].resolve(response('run_back')); + assert.equal(await back, 'applied'); + assert.deepEqual(get(source.state).availability, { kind: 'online' }); +}); + +test('a backend error keeps the engine online and reports the message', async () => { + const { source, pending } = harness(); + source.attach(); + const failed = source.refresh(); + pending[0].reject('scheduler_busy'); + assert.equal(await failed, 'failed'); + const state = get(source.state); + assert.deepEqual(state.availability, { kind: 'online' }); + assert.equal(state.errorMessage, 'scheduler_busy'); + assert.equal(state.status, 'failed'); +}); + +test('unreachable before any load says no projection is shown', async () => { + const { source, pending } = harness(); + source.attach(); + const down = source.refresh(); + pending[0].reject('transport'); + await down; + const availability = get(source.state).availability; + assert.equal(availability.kind === 'unreachable' && availability.hasProjection, false); +}); diff --git a/src/components/workbench/shell/runContextRunList.ts b/src/components/workbench/shell/runContextRunList.ts new file mode 100644 index 000000000..084e471cb --- /dev/null +++ b/src/components/workbench/shell/runContextRunList.ts @@ -0,0 +1,144 @@ +/** + * The picker's view of the scheduler run-list projection. + * + * One instance per shell (created in runContextStore.ts). It owns: + * - the last projection rows it received (kept while the engine is + * unreachable so pages and the chip keep showing the last projection); + * - engine availability as observed through the run-list query; + * - current-invocation authority: every refresh takes a generation number and + * only the newest refresh may write state. Older completions are classified + * `superseded`. While detached (before the shell mounts, after it is + * destroyed) refreshes do not run and in-flight completions are classified + * `detached` without writing state. + * + * It has no service imports so it can be tested with injected functions. + */ +import { writable, type Readable } from 'svelte/store'; +import type { + RunListProjectionRecord, + WorkflowRunListQueryRequest, + WorkflowRunListQueryResponse, +} from '../../../services/diagnostics/types'; +import type { EngineAvailability } from './runContextPicker.ts'; + +export type RunListLoadStatus = 'idle' | 'loading' | 'ready' | 'failed'; + +export interface RunContextRunListState { + runs: RunListProjectionRecord[]; + status: RunListLoadStatus; + availability: EngineAvailability; + /** When the rows in `runs` were received; null before the first success. */ + loadedAtMs: number | null; + /** Backend failure that is not a transport failure (the engine answered). */ + errorMessage: string | null; +} + +export type RunListRefreshOutcome = 'applied' | 'failed' | 'unreachable' | 'superseded' | 'detached'; + +export interface RunListQueryFailure { + /** True when the transport could not reach the engine at all. */ + transport: boolean; + message: string; +} + +export interface RunContextRunListDeps { + queryRunList: (request: WorkflowRunListQueryRequest) => Promise; + classifyFailure: (error: unknown) => RunListQueryFailure; + now: () => number; + limit: number; +} + +export interface RunContextRunListSource { + state: Readable; + /** Start accepting refreshes. Throws if already attached (one owner). */ + attach(): void; + /** Stop accepting refreshes and invalidate in-flight ones. Idempotent. */ + detach(): void; + isAttached(): boolean; + refresh(): Promise; +} + +export const INITIAL_RUN_CONTEXT_RUN_LIST_STATE: RunContextRunListState = { + runs: [], + status: 'idle', + availability: { kind: 'unknown' }, + loadedAtMs: null, + errorMessage: null, +}; + +export function createRunContextRunListSource(deps: RunContextRunListDeps): RunContextRunListSource { + const store = writable({ ...INITIAL_RUN_CONTEXT_RUN_LIST_STATE }); + let generation = 0; + let attached = false; + + async function refresh(): Promise { + if (!attached) return 'detached'; + const invocation = ++generation; + store.update((state) => ({ ...state, status: 'loading' })); + + let response: WorkflowRunListQueryResponse | null = null; + let failure: RunListQueryFailure | null = null; + try { + response = await deps.queryRunList({ limit: deps.limit }); + } catch (error) { + failure = deps.classifyFailure(error); + } + + if (!attached) return 'detached'; + if (invocation !== generation) return 'superseded'; + + const nowMs = deps.now(); + if (response) { + store.set({ + runs: response.runs, + status: 'ready', + availability: { kind: 'online' }, + loadedAtMs: nowMs, + errorMessage: null, + }); + return 'applied'; + } + + const failed = failure ?? { transport: true, message: 'Run list query failed' }; + if (failed.transport) { + store.update((state) => ({ + ...state, + status: 'failed', + availability: { + kind: 'unreachable', + sinceMs: state.availability.kind === 'unreachable' ? state.availability.sinceMs : nowMs, + hasProjection: state.loadedAtMs !== null, + }, + errorMessage: null, + })); + return 'unreachable'; + } + store.update((state) => ({ + ...state, + status: 'failed', + availability: { kind: 'online' }, + errorMessage: failed.message, + })); + return 'failed'; + } + + return { + state: { subscribe: store.subscribe }, + refresh, + attach() { + if (attached) { + throw new Error('Run-context run list is already attached; the shell owns one attachment.'); + } + attached = true; + }, + detach() { + if (!attached) return; + attached = false; + generation += 1; + store.update((state) => (state.status === 'loading' ? { ...state, status: 'idle' } : state)); + }, + isAttached() { + return attached; + }, + }; +} diff --git a/src/components/workbench/shell/runContextStore.ts b/src/components/workbench/shell/runContextStore.ts new file mode 100644 index 000000000..1c565b1e2 --- /dev/null +++ b/src/components/workbench/shell/runContextStore.ts @@ -0,0 +1,133 @@ +/** + * Shared run-context state for the shell and pages. + * + * The active run itself lives in `workbenchStore` (ADR-014: transient frontend + * state shared across pages). This module adds what the header picker needs + * around it: whether the popover is open and what is typed in it, the run-list + * projection the picker shows, and the actions pages call (`openRunContextPicker`, + * `selectRunContext`, `clearRunContext`). + */ +import { writable, type Readable } from 'svelte/store'; +import type { RunListProjectionRecord } from '../../../services/diagnostics/types'; +import { subscribeDiagnosticsProjectionInvalidations } from '../../../services/workflow/WorkflowProjectionSubscriptionService'; +import { workflowService } from '../../../services/workflow/WorkflowService'; +import { normalizeWorkflowServiceError } from '../../../services/workflow/workflowServiceErrors'; +import { clearActiveWorkflowRun, selectActiveWorkflowRun } from '../../../stores/workbenchStore'; +import { RUN_CONTEXT_RUN_LIMIT, toActiveRunContext } from './runContextPicker.ts'; +import { + createRunContextRunListSource, + type RunContextRunListState, + type RunListQueryFailure, +} from './runContextRunList.ts'; + +export interface RunContextPickerState { + open: boolean; + query: string; +} + +const pickerStore = writable({ open: false, query: '' }); + +export const runContextPicker: Readable = { + subscribe: pickerStore.subscribe, +}; + +/** Open the header popover, optionally with text already in its search field. */ +export function openRunContextPicker(query = ''): void { + pickerStore.set({ open: true, query }); +} + +export function closeRunContextPicker(): void { + pickerStore.set({ open: false, query: '' }); +} + +export function setRunContextPickerQuery(query: string): void { + pickerStore.update((state) => ({ ...state, query })); +} + +/** Make `run` the active run for every tab and close the picker. */ +export function selectRunContext(run: RunListProjectionRecord): void { + selectActiveWorkflowRun(toActiveRunContext(run)); + closeRunContextPicker(); +} + +/** Clear the active run; pages fall back to their empty state. */ +export function clearRunContext(): void { + clearActiveWorkflowRun(); +} + +export function classifyRunListFailure(error: unknown): RunListQueryFailure { + const normalized = normalizeWorkflowServiceError(error); + return { + transport: normalized.code === 'transport_error', + message: normalized.message, + }; +} + +const runListSource = createRunContextRunListSource({ + queryRunList: (request) => workflowService.queryRunList(request), + classifyFailure: classifyRunListFailure, + now: () => Date.now(), + limit: RUN_CONTEXT_RUN_LIMIT, +}); + +/** The run-list projection as the picker last received it. */ +export const runContextRunList: Readable = runListSource.state; + +/** + * Whether `run_list` invalidation events reach the picker. `unavailable` means + * the event channel could not be subscribed (for example, no Tauri host); the + * list then updates only on open and on Retry, and the popover says so. + */ +export type RunContextLiveUpdates = 'stopped' | 'connecting' | 'live' | 'unavailable'; + +const liveUpdatesStore = writable('stopped'); + +export const runContextLiveUpdates: Readable = { + subscribe: liveUpdatesStore.subscribe, +}; + +/** Re-query the run list (Retry in the engine line, popover open). */ +export function refreshRunContextRunList(): Promise { + return runListSource.refresh(); +} + +/** + * Start keeping the run list current. Owned by the shell: call once on mount + * and call the returned function on destroy. It attaches the source, loads + * once, and refreshes on `run_list` projection invalidations. A failed + * subscription is published as `runContextLiveUpdates = 'unavailable'`. + */ +export function startRunContextSync(): () => void { + runListSource.attach(); + let stopped = false; + let unlisten: (() => void) | null = null; + + liveUpdatesStore.set('connecting'); + void runListSource.refresh(); + subscribeDiagnosticsProjectionInvalidations({ + projections: ['run_list'], + refresh: async () => { + await runListSource.refresh(); + }, + }) + .then((nextUnlisten) => { + if (stopped) { + nextUnlisten(); + return; + } + unlisten = nextUnlisten; + liveUpdatesStore.set('live'); + }) + .catch(() => { + if (!stopped) liveUpdatesStore.set('unavailable'); + }); + + return () => { + stopped = true; + unlisten?.(); + unlisten = null; + runListSource.detach(); + liveUpdatesStore.set('stopped'); + closeRunContextPicker(); + }; +} diff --git a/src/components/workbench/ui/Chip.svelte b/src/components/workbench/ui/Chip.svelte new file mode 100644 index 000000000..fff3e1da3 --- /dev/null +++ b/src/components/workbench/ui/Chip.svelte @@ -0,0 +1,19 @@ + + + + {#if glyph}{/if} + {@render children()} + diff --git a/src/components/workbench/ui/DeviceLanes.svelte b/src/components/workbench/ui/DeviceLanes.svelte new file mode 100644 index 000000000..c4a203957 --- /dev/null +++ b/src/components/workbench/ui/DeviceLanes.svelte @@ -0,0 +1,86 @@ + + +
+ {#if scopeLabel} +
{scopeLabel}
+ {/if} +
+ {#each lanes as lane (lane.id)} +
+
+ {lane.name}{lane.meta} +
+
+ {#each lane.blocks as block (block.id)} + {@const glyph = BLOCK_GLYPH[block.kind]} +
+ {#if glyph}{/if}{block.label} +
+ {/each} +
+
+ {/each} +
+ {#if showLegend} +
+ running + waiting for memory + next +
+ {/if} +
+ + diff --git a/src/components/workbench/ui/DimensionLine.svelte b/src/components/workbench/ui/DimensionLine.svelte new file mode 100644 index 000000000..9a70b5ce2 --- /dev/null +++ b/src/components/workbench/ui/DimensionLine.svelte @@ -0,0 +1,14 @@ + + +
+
+ {label} +
+
diff --git a/src/components/workbench/ui/EmptyState.svelte b/src/components/workbench/ui/EmptyState.svelte new file mode 100644 index 000000000..d567a6e92 --- /dev/null +++ b/src/components/workbench/ui/EmptyState.svelte @@ -0,0 +1,59 @@ + + +
+
+
{question}
+ {#if sentence} +
{sentence}
+ {/if} + {#if actionLabel && onaction} + + {/if} + {#if children} +
{@render children()}
+ {/if} +
+
+ + diff --git a/src/components/workbench/ui/ErrorCard.svelte b/src/components/workbench/ui/ErrorCard.svelte new file mode 100644 index 000000000..6d1f9da35 --- /dev/null +++ b/src/components/workbench/ui/ErrorCard.svelte @@ -0,0 +1,57 @@ + + +
+ +
+
{title}{#if code}{code}{/if}
+
{explanation}
+ {#if suggestionText} +
{suggestionText}
+ {/if} +
+ {#if actionLabel && onaction} + + {/if} +
+ + diff --git a/src/components/workbench/ui/FilterChip.svelte b/src/components/workbench/ui/FilterChip.svelte new file mode 100644 index 000000000..abae35663 --- /dev/null +++ b/src/components/workbench/ui/FilterChip.svelte @@ -0,0 +1,14 @@ + + + + {label} + + diff --git a/src/components/workbench/ui/GroupHeader.svelte b/src/components/workbench/ui/GroupHeader.svelte new file mode 100644 index 000000000..9fbe9100e --- /dev/null +++ b/src/components/workbench/ui/GroupHeader.svelte @@ -0,0 +1,24 @@ + + + diff --git a/src/components/workbench/ui/KeyValue.svelte b/src/components/workbench/ui/KeyValue.svelte new file mode 100644 index 000000000..02a05ce72 --- /dev/null +++ b/src/components/workbench/ui/KeyValue.svelte @@ -0,0 +1,18 @@ + + +
+ {#each rows as row (row.key)} +
{row.key}
+
{row.value}
+ {/each} +
diff --git a/src/components/workbench/ui/ListRow.svelte b/src/components/workbench/ui/ListRow.svelte new file mode 100644 index 000000000..6506fa4ef --- /dev/null +++ b/src/components/workbench/ui/ListRow.svelte @@ -0,0 +1,79 @@ + + + + + diff --git a/src/components/workbench/ui/LogLine.svelte b/src/components/workbench/ui/LogLine.svelte new file mode 100644 index 000000000..60818877e --- /dev/null +++ b/src/components/workbench/ui/LogLine.svelte @@ -0,0 +1,34 @@ + + +
+ {time} + + {`${LEVEL_TEXT[level]}: `}{#if kind}{kind}{` ${message}`}{:else}{message}{/if}{#if source}{` ${source}`}{/if} +
diff --git a/src/components/workbench/ui/Panel.svelte b/src/components/workbench/ui/Panel.svelte new file mode 100644 index 000000000..d46acb459 --- /dev/null +++ b/src/components/workbench/ui/Panel.svelte @@ -0,0 +1,58 @@ + + +
+ {#if column} + {#if top} +
{@render top()}
+ {/if} +
{@render children?.()}
+ {#if footer} +
{@render footer()}
+ {/if} + {:else} + {@render children?.()} + {/if} +
diff --git a/src/components/workbench/ui/README.md b/src/components/workbench/ui/README.md new file mode 100644 index 000000000..7378bddb5 --- /dev/null +++ b/src/components/workbench/ui/README.md @@ -0,0 +1,117 @@ +# Workbench UI parts + +## Purpose + +The shared presentation parts of the redesigned workbench. Every page builds +its layout from these so the tabs read as one system: same panels, rows, +glyphs, segments, chips, lanes, log lines and empty states. + +## Contents + +| File | Responsibility | +| --- | --- | +| `StatusGlyph.svelte`, `statusGlyph.ts` | The glyph vocabulary and the one mapping from backend status strings to glyph states. | +| `DimensionLine.svelte` | Page summary line (rule with ticks and a centred mono label). | +| `Panel.svelte` | Bordered panel; column variant with `top`, scrolling `children` and `footer` snippets. | +| `GroupHeader.svelte`, `ListRow.svelte` | Sticky collapsible group header and the selectable list row. | +| `SegmentedControl.svelte`, `Chip.svelte`, `FilterChip.svelte` | Status segments with counts, static pills, removable filter pills. | +| `DeviceLanes.svelte` | Per-device memory lanes with running, waiting, next and free blocks. | +| `KeyValue.svelte`, `LogLine.svelte`, `ErrorCard.svelte` | Key/value grid, one timeline line, in-place error explanation. | +| `TwoStepButton.svelte`, `EmptyState.svelte`, `Toast.svelte` | Destructive confirm with reset, centred empty state, transient status message. | +| `types.ts`, `index.ts` | Data shapes the parts accept and the barrel export. | + +## Problem + +The mockups (`docs/design/mockups/boards/*.dc.html`) express status, selection +and grouping the same way on every tab. Eight pages are rebuilt in parallel; +without shared parts each would re-derive the CSS and the status mapping and +drift apart. + +## Constraints + +- Visual values come from `docs/design/mockups/boards/shell.css`, ported to the + `pg-*` classes in `src/styles.css` (`@layer components`) and the `--pg-*` + tokens. Parts use those classes; they do not hard-code colours. +- No pulsing animation, no uppercase tracked labels, no cyan; copy is sentence + case and uses domain words. +- Native interactive elements only, each with a name; `aria-current` on + selected rows, `aria-pressed` on toggles and segments, `aria-expanded` on + disclosures; glyphs are `aria-hidden` and the status is always in text. + +## Decision + +Parts take data through props and snippets and own no domain state; pages and +their presenters decide what to show. Status strings map to glyphs only in +`statusGlyph.ts`, whose class names are literal so Tailwind keeps them. Page +agents treat this directory as read-only and report needed changes to the +integration owner (plan, Concurrent Work). The heading set of this README is +required by `scripts/check-decision-traceability.sh` (issue WR-001). + +## Alternatives Rejected + +- A third-party component library: it would bring its own visual language and + dependency weight for parts that are a few lines of markup each. +- Tailwind utility strings copied into each page: the values would drift and + the glyph vocabulary would be re-implemented per page. + +## Invariants + +- `glyphStateForStatus` maps `accepted`, `future`, `scheduled`, `queued`, + `delayed` to queued; `running` to running; `completed` to succeeded; + `failed` to failed; `cancelled` to cancelled; `waiting` to waiting; anything + unknown to idle. +- `ListRow` with a `runId` carries `data-run-id`, so Ctrl+C over it copies the + id (see `../shell/runContextClipboard.ts`). +- `TwoStepButton` returns to its first step after `resetMs` (4 s), when + disabled, or when unmounted. +- `Toast` keeps its live region mounted so each message is announced. + +## Revisit Triggers + +- A backend status or log level appears that the glyph vocabulary cannot + express. +- Two or more pages need the same composite (for example a filter bar); add it + here rather than copying it. + +## Dependencies + +**Internal:** `src/styles.css` (`pg-*` classes and tokens). + +**External:** `svelte` (snippets, runes). + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` (pages using + these parts still read only typed projections). + +## Usage Examples + +```svelte + + + + {#snippet top()} + (status = next)} /> + {/snippet} + (open = !open)} /> + {#each running as run (run.workflow_run_id)} + selectRunContext(run)} + /> + {/each} + {#snippet footer()} + + {/snippet} + +``` diff --git a/src/components/workbench/ui/SegmentedControl.svelte b/src/components/workbench/ui/SegmentedControl.svelte new file mode 100644 index 000000000..d32f75a55 --- /dev/null +++ b/src/components/workbench/ui/SegmentedControl.svelte @@ -0,0 +1,42 @@ + + +
+ {#each options as option (option.value)} + + {/each} +
+ + diff --git a/src/components/workbench/ui/StatusGlyph.svelte b/src/components/workbench/ui/StatusGlyph.svelte new file mode 100644 index 000000000..1c7f023c6 --- /dev/null +++ b/src/components/workbench/ui/StatusGlyph.svelte @@ -0,0 +1,22 @@ + + + + diff --git a/src/components/workbench/ui/Toast.svelte b/src/components/workbench/ui/Toast.svelte new file mode 100644 index 000000000..d7a5e82b1 --- /dev/null +++ b/src/components/workbench/ui/Toast.svelte @@ -0,0 +1,11 @@ + + + +
{message ?? ''}
diff --git a/src/components/workbench/ui/TwoStepButton.svelte b/src/components/workbench/ui/TwoStepButton.svelte new file mode 100644 index 000000000..cfadfe3f3 --- /dev/null +++ b/src/components/workbench/ui/TwoStepButton.svelte @@ -0,0 +1,64 @@ + + + diff --git a/src/components/workbench/ui/index.ts b/src/components/workbench/ui/index.ts new file mode 100644 index 000000000..e5512f6c0 --- /dev/null +++ b/src/components/workbench/ui/index.ts @@ -0,0 +1,32 @@ +export { default as StatusGlyph } from './StatusGlyph.svelte'; +export { default as DimensionLine } from './DimensionLine.svelte'; +export { default as Panel } from './Panel.svelte'; +export { default as GroupHeader } from './GroupHeader.svelte'; +export { default as ListRow } from './ListRow.svelte'; +export { default as SegmentedControl } from './SegmentedControl.svelte'; +export { default as Chip } from './Chip.svelte'; +export { default as FilterChip } from './FilterChip.svelte'; +export { default as DeviceLanes } from './DeviceLanes.svelte'; +export { default as KeyValue } from './KeyValue.svelte'; +export { default as LogLine } from './LogLine.svelte'; +export { default as ErrorCard } from './ErrorCard.svelte'; +export { default as TwoStepButton } from './TwoStepButton.svelte'; +export { default as EmptyState } from './EmptyState.svelte'; +export { default as Toast } from './Toast.svelte'; +export { + GLYPH_CLASS, + GLYPH_STATES, + glyphClass, + glyphStateForLogLevel, + glyphStateForStatus, + glyphStateLabel, + type GlyphState, + type LogLevel, +} from './statusGlyph'; +export type { + DeviceLane, + DeviceLaneBlock, + DeviceLaneBlockKind, + KeyValueRow, + SegmentOption, +} from './types'; diff --git a/src/components/workbench/ui/statusGlyph.test.ts b/src/components/workbench/ui/statusGlyph.test.ts new file mode 100644 index 000000000..3919a064c --- /dev/null +++ b/src/components/workbench/ui/statusGlyph.test.ts @@ -0,0 +1,50 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + GLYPH_CLASS, + GLYPH_STATES, + glyphClass, + glyphStateForLogLevel, + glyphStateForStatus, + glyphStateLabel, +} from './statusGlyph.ts'; + +test('run list statuses map to the spec glyph vocabulary', () => { + for (const status of ['accepted', 'future', 'scheduled', 'queued', 'delayed']) { + assert.equal(glyphStateForStatus(status), 'queued', status); + } + assert.equal(glyphStateForStatus('running'), 'running'); + assert.equal(glyphStateForStatus('completed'), 'succeeded'); + assert.equal(glyphStateForStatus('failed'), 'failed'); + assert.equal(glyphStateForStatus('cancelled'), 'cancelled'); +}); + +test('node statuses and display labels map the same way', () => { + assert.equal(glyphStateForStatus('waiting'), 'waiting'); + assert.equal(glyphStateForStatus('Waiting'), 'waiting'); + assert.equal(glyphStateForStatus(' Running '), 'running'); + assert.equal(glyphStateForStatus('Not reached'), 'queued'); + assert.equal(glyphStateForStatus('skipped'), 'cancelled'); +}); + +test('missing or unknown statuses render as idle instead of guessing', () => { + assert.equal(glyphStateForStatus(null), 'idle'); + assert.equal(glyphStateForStatus(undefined), 'idle'); + assert.equal(glyphStateForStatus(''), 'idle'); + assert.equal(glyphStateForStatus('exploded'), 'idle'); +}); + +test('log levels map to succeeded, warn and failed glyphs', () => { + assert.equal(glyphStateForLogLevel('info'), 'succeeded'); + assert.equal(glyphStateForLogLevel('warn'), 'warn'); + assert.equal(glyphStateForLogLevel('error'), 'failed'); +}); + +test('every glyph state has a literal class and a text label', () => { + for (const state of GLYPH_STATES) { + assert.equal(glyphClass(state), GLYPH_CLASS[state]); + assert.match(glyphClass(state), /^pg-g-[a-z]+$/); + assert.ok(glyphStateLabel(state).length > 0); + } +}); diff --git a/src/components/workbench/ui/statusGlyph.ts b/src/components/workbench/ui/statusGlyph.ts new file mode 100644 index 000000000..5f00345d3 --- /dev/null +++ b/src/components/workbench/ui/statusGlyph.ts @@ -0,0 +1,102 @@ +/** + * Status glyph vocabulary (docs/design/workbench-redesign-spec.md). + * + * Every page maps backend status strings through this one module, so a new + * backend status changes the glyph in exactly one place. The glyph is always + * decorative; callers render the status in text next to it. + */ + +export const GLYPH_STATES = [ + 'running', + 'waiting', + 'queued', + 'succeeded', + 'failed', + 'cancelled', + 'idle', + 'warn', +] as const; + +export type GlyphState = (typeof GLYPH_STATES)[number]; + +/** Log severities the LogLine part understands. */ +export type LogLevel = 'info' | 'warn' | 'error'; + +/** + * Literal class names so Tailwind's content scan keeps them in the build. + * Do not build these strings dynamically. + */ +export const GLYPH_CLASS: Record = { + running: 'pg-g-running', + waiting: 'pg-g-waiting', + queued: 'pg-g-queued', + succeeded: 'pg-g-succeeded', + failed: 'pg-g-failed', + cancelled: 'pg-g-cancelled', + idle: 'pg-g-idle', + warn: 'pg-g-warn', +}; + +const GLYPH_LABEL: Record = { + running: 'Running', + waiting: 'Waiting', + queued: 'Queued', + succeeded: 'Succeeded', + failed: 'Failed', + cancelled: 'Cancelled', + idle: 'No run', + warn: 'Warning', +}; + +const STATUS_TO_GLYPH: Record = { + // Run list projection statuses (RunListProjectionStatus). + accepted: 'queued', + future: 'queued', + scheduled: 'queued', + queued: 'queued', + delayed: 'queued', + running: 'running', + completed: 'succeeded', + failed: 'failed', + cancelled: 'cancelled', + // Node execution statuses (NodeExecutionProjectionStatus) and display labels. + waiting: 'waiting', + succeeded: 'succeeded', + done: 'succeeded', + next: 'queued', + not_reached: 'queued', + skipped: 'cancelled', +}; + +/** + * Map a backend run or node status to its glyph. Matching ignores case and + * surrounding whitespace so display labels such as `Waiting` map the same way + * as projection values. Missing or unknown statuses render as `idle`. + */ +export function glyphStateForStatus(status: string | null | undefined): GlyphState { + if (typeof status !== 'string') { + return 'idle'; + } + const key = status.trim().toLowerCase().replaceAll(' ', '_'); + return STATUS_TO_GLYPH[key] ?? 'idle'; +} + +export function glyphStateForLogLevel(level: LogLevel): GlyphState { + switch (level) { + case 'error': + return 'failed'; + case 'warn': + return 'warn'; + case 'info': + return 'succeeded'; + } +} + +export function glyphClass(state: GlyphState): string { + return GLYPH_CLASS[state]; +} + +/** Plain-language name of a glyph state, for text that accompanies the glyph. */ +export function glyphStateLabel(state: GlyphState): string { + return GLYPH_LABEL[state]; +} diff --git a/src/components/workbench/ui/types.ts b/src/components/workbench/ui/types.ts new file mode 100644 index 000000000..20b86c52d --- /dev/null +++ b/src/components/workbench/ui/types.ts @@ -0,0 +1,42 @@ +/** Data shapes the shared workbench parts accept. Presenters build these. */ + +export interface SegmentOption { + value: T; + label: string; + /** Shown in mono after the label; omit when the count is unknown. */ + count?: number | string; + /** Disabled option; `title` says why. */ + disabled?: boolean; + title?: string; +} + +export interface KeyValueRow { + key: string; + value: string; + /** Render the value in the mono face (ids, timestamps, sizes). */ + mono?: boolean; + /** Makes Ctrl+C over the value copy this run id (see shell/runContextClipboard.ts). */ + runId?: string; +} + +export type DeviceLaneBlockKind = 'running' | 'waiting' | 'queued' | 'free'; + +export interface DeviceLaneBlock { + id: string; + kind: DeviceLaneBlockKind; + /** Memory in GB; the block's width is proportional to it. */ + gb: number; + /** Visible text inside the block; empty for free space. */ + label: string; + /** Tooltip, for example "Waiting: needs 8 GB, 6.8 GB free". */ + title?: string; +} + +export interface DeviceLane { + id: string; + /** Device name, for example "cuda:0 RTX 4090". */ + name: string; + /** Usage line, for example "17.2 of 24 GB in use". */ + meta: string; + blocks: DeviceLaneBlock[]; +} diff --git a/src/components/workflowMiniMap.test.ts b/src/components/workflowMiniMap.test.ts index 2266e3e77..edceea5ed 100644 --- a/src/components/workflowMiniMap.test.ts +++ b/src/components/workflowMiniMap.test.ts @@ -1,22 +1,29 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { getWorkflowMiniMapNodeColor } from './workflowMiniMap.ts'; +import { + getWorkflowMiniMapNodeColor, + WORKFLOW_MINIMAP_GROUP_COLOR, + WORKFLOW_MINIMAP_NODE_COLOR, +} from './workflowMiniMap.ts'; test('getWorkflowMiniMapNodeColor prioritizes group nodes', () => { - assert.equal(getWorkflowMiniMapNodeColor({ type: 'node-group' }), '#7c3aed'); - assert.equal(getWorkflowMiniMapNodeColor({ data: { isGroup: true } }), '#7c3aed'); + assert.equal(getWorkflowMiniMapNodeColor({ type: 'node-group' }), WORKFLOW_MINIMAP_GROUP_COLOR); + assert.equal(getWorkflowMiniMapNodeColor({ data: { isGroup: true } }), WORKFLOW_MINIMAP_GROUP_COLOR); }); -test('getWorkflowMiniMapNodeColor maps backend categories to stable colors', () => { - assert.equal(getWorkflowMiniMapNodeColor({ data: { definition: { category: 'input' } } }), '#2563eb'); - assert.equal(getWorkflowMiniMapNodeColor({ data: { definition: { category: 'processing' } } }), '#16a34a'); - assert.equal(getWorkflowMiniMapNodeColor({ data: { definition: { category: 'tool' } } }), '#d97706'); - assert.equal(getWorkflowMiniMapNodeColor({ data: { definition: { category: 'output' } } }), '#0891b2'); - assert.equal(getWorkflowMiniMapNodeColor({ data: { definition: { category: 'control' } } }), '#9333ea'); +test('getWorkflowMiniMapNodeColor uses one token colour for every category', () => { + for (const category of ['input', 'processing', 'tool', 'output', 'control', 'custom']) { + assert.equal( + getWorkflowMiniMapNodeColor({ data: { definition: { category } } }), + WORKFLOW_MINIMAP_NODE_COLOR, + ); + } + assert.equal(getWorkflowMiniMapNodeColor({}), WORKFLOW_MINIMAP_NODE_COLOR); }); -test('getWorkflowMiniMapNodeColor falls back for unknown nodes', () => { - assert.equal(getWorkflowMiniMapNodeColor({}), '#525252'); - assert.equal(getWorkflowMiniMapNodeColor({ data: { definition: { category: 'custom' } } }), '#525252'); +test('minimap colours are workbench token references, not literals', () => { + assert.equal(WORKFLOW_MINIMAP_NODE_COLOR, 'var(--pg-border-idle)'); + assert.equal(WORKFLOW_MINIMAP_GROUP_COLOR, 'var(--pg-text-muted)'); + assert.notEqual(WORKFLOW_MINIMAP_NODE_COLOR, WORKFLOW_MINIMAP_GROUP_COLOR); }); diff --git a/src/components/workflowMiniMap.ts b/src/components/workflowMiniMap.ts index 3153e07ff..29ddd7660 100644 --- a/src/components/workflowMiniMap.ts +++ b/src/components/workflowMiniMap.ts @@ -8,23 +8,19 @@ interface WorkflowMiniMapNodeLike { } | null; } +/* + * The minimap draws node colours as inline `fill`, so CSS cannot restyle them; + * they are token references here (docs/design/mockups/boards/shell.css + * `.minimap i`). Categories are not colour-coded; groups read lighter so they + * stay distinguishable from ordinary nodes. + */ +export const WORKFLOW_MINIMAP_NODE_COLOR = 'var(--pg-border-idle)'; +export const WORKFLOW_MINIMAP_GROUP_COLOR = 'var(--pg-text-muted)'; + export function getWorkflowMiniMapNodeColor(node: WorkflowMiniMapNodeLike): string { if (node.type === 'node-group' || node.data?.isGroup) { - return '#7c3aed'; + return WORKFLOW_MINIMAP_GROUP_COLOR; } - switch (node.data?.definition?.category) { - case 'input': - return '#2563eb'; - case 'processing': - return '#16a34a'; - case 'tool': - return '#d97706'; - case 'output': - return '#0891b2'; - case 'control': - return '#9333ea'; - default: - return '#525252'; - } + return WORKFLOW_MINIMAP_NODE_COLOR; } diff --git a/src/services/diagnostics/README.md b/src/services/diagnostics/README.md new file mode 100644 index 000000000..abd1b69d3 --- /dev/null +++ b/src/services/diagnostics/README.md @@ -0,0 +1,79 @@ +# Diagnostics projection types + +## Purpose + +Holds the TypeScript projection of the typed backend read models the +workbench pages consume: run lists, run detail, scheduler timeline, node +status, I/O artifact inspection, Library usage, local Network status and +Pumas model facts. The workbench never reads diagnostic ledger rows; it reads +these projections (ADR-014). + +## Contents + +- `types.ts`: the projection record and response shapes, one interface per + backend projection, plus the Pumas library and Hugging Face search shapes. +- `projectionState.ts`: helpers for `ProjectionStateRecord` (freshness + cursors) used by pages to show "Current at seq N" style lines. + +## Problem + +Pages need stable, typed shapes for backend responses without inventing +fields or copying one sample response. The shapes must be traceable to their +producer so a renamed backend field is a visible contract change, not a +silent `undefined`. + +## Constraints + +- A TypeScript type is not runtime proof. Presenters still decode values + (`nonEmptyString`, numeric guards) before use. +- Shapes that pass through an external producer unchanged mirror that + producer's serialisation. `PumasHfModelSearchResult` mirrors Pumas + `HuggingFaceModel` (pumas-core `models/model.rs`, + `rename_all = "camelCase"`). +- Optional fields stay optional; a page omits the row rather than defaulting. + +## Decision + +Keep one projection module for all workbench read models, owned here, and +document the producer of any shape that is not generated from the host's +Rust types. The heading set of this file is required by +`scripts/check-decision-traceability.sh` (plan issue WR-001). + +## Alternatives Rejected + +- Per-page type files: the same projection is consumed by several pages + (run list by the picker, Scheduler and Sessions), so one owner avoids drift. +- Index-signature "anything goes" shapes: they hide producer changes, as the + former `{ id?: string; [key: string]: unknown }` search result did. + +## Invariants + +- No type here describes raw `diagnostic_events` rows or `payload_json`. +- Field names match the producer's serialised names exactly. +- Adding a field here does not make it available: the backend projection + must emit it, and the consuming presenter must decode it. + +## Revisit Triggers + +- The host starts generating TypeScript from its Rust projection types + (then this module becomes generated output). +- A projection gains fields the redesign assumed (device memory, retention + durations, node progress, client sessions; see the plan's issues). + +## Dependencies + +- Consumed by `src/components/workbench/**` presenters and pages, and by + `src/components/workbench/shell/` for the run list. +- Produced by the Tauri workflow commands under `src-tauri/src/workflow/`. + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` +- `docs/adr/ADR-016-workflow-error-diagnostics-spine.md` + +## Usage Examples + +```ts +import type { RunListProjectionRecord } from '../../services/diagnostics/types'; +import { mockProjectionState } from '../../services/diagnostics/projectionState'; // tests only +``` diff --git a/src/services/diagnostics/types.ts b/src/services/diagnostics/types.ts index e4c9898b2..de624f19b 100644 --- a/src/services/diagnostics/types.ts +++ b/src/services/diagnostics/types.ts @@ -645,9 +645,27 @@ export interface PumasHfModelSearchAuditRequest { hydrateLimit?: number | null; } +/** + * Projection of Pumas `HuggingFaceModel` (pumas-core `models/model.rs`), which + * the host passes through unchanged. The struct serialises with + * `rename_all = "camelCase"`, so field names here are the camelCase forms. + * Values are runtime-decoded by the Library presenter before use. + */ export interface PumasHfModelSearchResult { - id?: string | null; - [key: string]: unknown; + repoId?: string | null; + name?: string | null; + developer?: string | null; + kind?: string | null; + formats?: string[] | null; + quants?: string[] | null; + downloadOptions?: unknown[] | null; + url?: string | null; + releaseDate?: string | null; + modelCard?: Record | null; + license?: string | null; + downloads?: number | null; + totalSizeBytes?: number | null; + quantSizes?: Record | null; } export interface PumasHfModelSearchAuditResponse { diff --git a/src/stores/README.md b/src/stores/README.md new file mode 100644 index 000000000..28f80287c --- /dev/null +++ b/src/stores/README.md @@ -0,0 +1,84 @@ +# Frontend stores + +## Purpose + +Svelte stores for state the frontend owns: which workbench page is shown, the +active run shared across pages, page-local filters, panel state, and the +editor's graph session. Backend facts are not stored here as authority. + +## Contents + +| File | Responsibility | +| --- | --- | +| `workbenchStore.ts` | Workbench page registry and order (tab groups), selected page, active run context, Diagnostics and Settings focus targets. | +| `schedulerRunListStore.ts` | Scheduler filters (search, status segment, the 14 disclosure filters, sort) and view preferences (`showLanes`); the run rows come from the shell's `runContextRunList`. | +| `panelStore.ts` | Assistant side panel open state and width. | +| `graphSessionStore.ts`, `workflowStore.ts`, `storeInstances.ts` | Editable graph session and the store instances shared with `@pantograph/svelte-graph`. | +| `*.test.ts` | Node test runner tests for the pure transition functions. | + +## Problem + +Several pages need the same transient selection (the active run) and the same +navigation state, while each page keeps its own filters. Without one owner per +piece of state, pages would copy it and drift. + +## Constraints + +- ADR-014: the active run is transient frontend state shared across pages and + is not persisted across restarts. +- Store modules export pure `with*` transition functions so behaviour can be + tested without a DOM; writable stores are wrapped in read-only exports plus + named actions. + +## Decision + +Each store owns one concern and exposes read-only stores plus actions. +`workbenchStore.ts` owns the page registry: `WORKBENCH_PAGES` lists every page +with its tab group (`sessions`, `runs`, `workflows`, `settings`), and the shell +renders tabs from it. The heading set of this README is required by +`scripts/check-decision-traceability.sh` (issue WR-001 in +`docs/plans/workbench-redesign/issues.md`). + +## Alternatives Rejected + +- Persisting the active run to local storage: ADR-014 keeps it transient so a + restart never opens on a stale run. +- Hard-coding the tab bar in the shell: the page list would exist twice. + +## Invariants + +- Page order is Sessions, Scheduler, Diagnostics, I/O Inspector, Network, + Graph, Node Editor, Library, Settings; Scheduler is the default page. +- Unknown page ids normalise to Scheduler. +- Changing the active run clears a Diagnostics focus that belongs to another + run. + +## Revisit Triggers + +- A page is added, removed or regrouped in the tab bar. +- Run selection needs to survive a restart (would require superseding + ADR-014). + +## Dependencies + +**Internal:** `src/services/diagnostics/types.ts` (run-list status types). + +**External:** `svelte/store`. + +## Related ADRs + +- `docs/adr/ADR-014-run-centric-workbench-projection-boundary.md` + +## Usage Examples + +```ts +import { + selectActiveWorkflowRun, + setWorkbenchPage, + workbenchPagesInGroup, +} from './workbenchStore'; + +setWorkbenchPage('diagnostics'); +selectActiveWorkflowRun({ workflow_run_id: 'run_7c9e…', workflow_id: 'ingest-docs-rag', status: 'running' }); +const runTabs = workbenchPagesInGroup('runs').map((page) => page.label); +``` diff --git a/src/stores/schedulerRunListStore.test.ts b/src/stores/schedulerRunListStore.test.ts index fb72823f2..ce3ab9206 100644 --- a/src/stores/schedulerRunListStore.test.ts +++ b/src/stores/schedulerRunListStore.test.ts @@ -2,17 +2,15 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { - DEFAULT_SCHEDULER_RUN_COLUMN_STATE, DEFAULT_SCHEDULER_RUN_FILTERS, - normalizeSchedulerRunColumnState, + DEFAULT_SCHEDULER_VIEW_PREFERENCES, + SCHEDULER_SECONDARY_FILTER_KEYS, normalizeSchedulerRunFilters, - withSchedulerRunColumnState, withSchedulerRunFilters, + withSchedulerSecondaryFiltersCleared, + withSchedulerViewPreferences, } from './schedulerRunListStore.ts'; -import type { - SchedulerRunColumnState, - SchedulerRunFilters, -} from './schedulerRunListStore.ts'; +import type { SchedulerRunFilters } from './schedulerRunListStore.ts'; test('normalizeSchedulerRunFilters fills defaults for missing values', () => { assert.deepEqual(normalizeSchedulerRunFilters(null), DEFAULT_SCHEDULER_RUN_FILTERS); @@ -22,6 +20,7 @@ test('normalizeSchedulerRunFilters rejects unknown enum values', () => { assert.deepEqual( normalizeSchedulerRunFilters({ search: 'caption', + statusSegment: 'waiting', status: 'bogus', schedulerPolicy: '', retentionPolicy: 'ephemeral', @@ -29,6 +28,7 @@ test('normalizeSchedulerRunFilters rejects unknown enum values', () => { } as unknown as Partial), { search: 'caption', + statusSegment: 'all', status: 'all', schedulerPolicy: 'all', retentionPolicy: 'ephemeral', @@ -50,6 +50,7 @@ test('normalizeSchedulerRunFilters rejects unknown enum values', () => { test('withSchedulerRunFilters applies partial updates without losing existing fields', () => { const next = withSchedulerRunFilters(DEFAULT_SCHEDULER_RUN_FILTERS, { search: 'workflow-a', + statusSegment: 'queued', status: 'scheduled', client: 'client-a', selectedRuntime: 'runtime-a', @@ -60,6 +61,7 @@ test('withSchedulerRunFilters applies partial updates without losing existing fi assert.deepEqual(next, { search: 'workflow-a', + statusSegment: 'queued', status: 'scheduled', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -77,29 +79,37 @@ test('withSchedulerRunFilters applies partial updates without losing existing fi }); }); -test('normalizeSchedulerRunColumnState defaults and rejects unknown columns', () => { - assert.deepEqual( - normalizeSchedulerRunColumnState({ - visibleColumns: ['status', 'bogus', 'workflow', 'status'], - } as unknown as Partial), - { - visibleColumns: ['status', 'workflow'], - }, - ); +test('the Filters disclosure holds the fourteen secondary filters, not search or the segment', () => { + assert.equal(SCHEDULER_SECONDARY_FILTER_KEYS.length, 14); + assert.equal(new Set(SCHEDULER_SECONDARY_FILTER_KEYS).size, 14); + assert.ok(!SCHEDULER_SECONDARY_FILTER_KEYS.includes('search' as never)); + assert.ok(!SCHEDULER_SECONDARY_FILTER_KEYS.includes('statusSegment' as never)); +}); - assert.deepEqual( - normalizeSchedulerRunColumnState({ visibleColumns: [] }), - DEFAULT_SCHEDULER_RUN_COLUMN_STATE, - ); +test('withSchedulerSecondaryFiltersCleared resets disclosure filters and keeps search and segment', () => { + const applied = withSchedulerRunFilters(DEFAULT_SCHEDULER_RUN_FILTERS, { + search: 'caption', + statusSegment: 'failed', + status: 'failed', + sort: 'duration_desc', + selectedDevice: 'cuda:0', + acceptedDate: '2026-11-03', + }); + + assert.deepEqual(withSchedulerSecondaryFiltersCleared(applied), { + ...DEFAULT_SCHEDULER_RUN_FILTERS, + search: 'caption', + statusSegment: 'failed', + }); }); -test('withSchedulerRunColumnState applies visibility updates', () => { +test('withSchedulerViewPreferences keeps the lanes preference boolean', () => { + assert.deepEqual(DEFAULT_SCHEDULER_VIEW_PREFERENCES, { showLanes: true }); + assert.deepEqual(withSchedulerViewPreferences(DEFAULT_SCHEDULER_VIEW_PREFERENCES, { showLanes: false }), { + showLanes: false, + }); assert.deepEqual( - withSchedulerRunColumnState(DEFAULT_SCHEDULER_RUN_COLUMN_STATE, { - visibleColumns: ['status', 'duration'], - }), - { - visibleColumns: ['status', 'duration'], - }, + withSchedulerViewPreferences({ showLanes: false }, { showLanes: 'yes' } as unknown as { showLanes: boolean }), + { showLanes: false }, ); }); diff --git a/src/stores/schedulerRunListStore.ts b/src/stores/schedulerRunListStore.ts index 785710216..cb92ee725 100644 --- a/src/stores/schedulerRunListStore.ts +++ b/src/stores/schedulerRunListStore.ts @@ -1,8 +1,21 @@ +/** + * Scheduler page filter state and view preferences. + * + * The run rows themselves are not stored here: the Scheduler reads the one + * run-list projection owned by the shell (`runContextRunList` in + * `src/components/workbench/shell/runContextStore.ts`, issue WR-005) and + * applies these filters to it in `schedulerPagePresenters.ts`. + */ import { writable, type Readable } from 'svelte/store'; import type { RunListProjectionStatus } from '../services/diagnostics/types'; export type SchedulerStatusFilter = 'all' | RunListProjectionStatus; +/** The coarse status segment above the run list (All, Active, Queued, Done, Failed). */ +export type SchedulerStatusSegment = 'all' | 'active' | 'queued' | 'done' | 'failed'; + +export const SCHEDULER_STATUS_SEGMENTS: SchedulerStatusSegment[] = ['all', 'active', 'queued', 'done', 'failed']; + export type SchedulerSortKey = | 'last_updated_desc' | 'queued_desc' @@ -12,6 +25,7 @@ export type SchedulerSortKey = export interface SchedulerRunFilters { search: string; + statusSegment: SchedulerStatusSegment; status: SchedulerStatusFilter; schedulerPolicy: string; retentionPolicy: string; @@ -28,33 +42,6 @@ export interface SchedulerRunFilters { sort: SchedulerSortKey; } -export const SCHEDULER_RUN_COLUMN_IDS = [ - 'status', - 'workflow', - 'run_id', - 'accepted', - 'queued', - 'started', - 'completed', - 'duration', - 'queue_position', - 'priority', - 'estimate', - 'scheduler_reason', - 'policy', - 'retention', - 'selected_runtime', - 'selected_device', - 'selected_network_node', - 'updated', -] as const; - -export type SchedulerRunColumnId = (typeof SCHEDULER_RUN_COLUMN_IDS)[number]; - -export interface SchedulerRunColumnState { - visibleColumns: SchedulerRunColumnId[]; -} - export const SCHEDULER_STATUS_FILTERS: SchedulerStatusFilter[] = [ 'all', 'accepted', @@ -76,8 +63,32 @@ export const SCHEDULER_SORT_OPTIONS: { label: string; value: SchedulerSortKey }[ { label: 'Status', value: 'status_asc' }, ]; +/** + * The filters that live in the Filters disclosure (every field except the + * search text and the status segment). Applied ones are shown as chips. + */ +export type SchedulerSecondaryFilterKey = Exclude; + +export const SCHEDULER_SECONDARY_FILTER_KEYS: SchedulerSecondaryFilterKey[] = [ + 'status', + 'sort', + 'schedulerPolicy', + 'retentionPolicy', + 'client', + 'clientSession', + 'bucket', + 'selectedRuntime', + 'selectedRuntimeVariant', + 'selectedBackend', + 'selectedDeviceClass', + 'selectedDevice', + 'selectedNetworkNode', + 'acceptedDate', +]; + export const DEFAULT_SCHEDULER_RUN_FILTERS: SchedulerRunFilters = { search: '', + statusSegment: 'all', status: 'all', schedulerPolicy: 'all', retentionPolicy: 'all', @@ -94,28 +105,37 @@ export const DEFAULT_SCHEDULER_RUN_FILTERS: SchedulerRunFilters = { sort: 'last_updated_desc', }; -export const DEFAULT_SCHEDULER_RUN_COLUMN_STATE: SchedulerRunColumnState = { - visibleColumns: [...SCHEDULER_RUN_COLUMN_IDS], +export interface SchedulerViewPreferences { + /** + * Show the device memory strip under the dimension line. The strip renders + * a sentence instead of lanes until the local network status projection + * reports per-device memory (issue WR-006). + */ + showLanes: boolean; +} + +export const DEFAULT_SCHEDULER_VIEW_PREFERENCES: SchedulerViewPreferences = { + showLanes: true, }; -function isSchedulerStatusFilter(value: unknown): value is SchedulerStatusFilter { +function isSchedulerStatusSegment(value: unknown): value is SchedulerStatusSegment { return ( typeof value === 'string' && - SCHEDULER_STATUS_FILTERS.includes(value as SchedulerStatusFilter) + SCHEDULER_STATUS_SEGMENTS.includes(value as SchedulerStatusSegment) ); } -function isSchedulerSortKey(value: unknown): value is SchedulerSortKey { +function isSchedulerStatusFilter(value: unknown): value is SchedulerStatusFilter { return ( typeof value === 'string' && - SCHEDULER_SORT_OPTIONS.some((option) => option.value === value) + SCHEDULER_STATUS_FILTERS.includes(value as SchedulerStatusFilter) ); } -function isSchedulerRunColumnId(value: unknown): value is SchedulerRunColumnId { +function isSchedulerSortKey(value: unknown): value is SchedulerSortKey { return ( typeof value === 'string' && - SCHEDULER_RUN_COLUMN_IDS.includes(value as SchedulerRunColumnId) + SCHEDULER_SORT_OPTIONS.some((option) => option.value === value) ); } @@ -128,6 +148,7 @@ export function normalizeSchedulerRunFilters( ): SchedulerRunFilters { return { search: typeof filters?.search === 'string' ? filters.search : '', + statusSegment: isSchedulerStatusSegment(filters?.statusSegment) ? filters.statusSegment : 'all', status: isSchedulerStatusFilter(filters?.status) ? filters.status : 'all', schedulerPolicy: normalizeOption(filters?.schedulerPolicy), retentionPolicy: normalizeOption(filters?.retentionPolicy), @@ -145,15 +166,6 @@ export function normalizeSchedulerRunFilters( }; } -export function normalizeSchedulerRunColumnState( - state: Partial | null | undefined, -): SchedulerRunColumnState { - const columns = state?.visibleColumns?.filter(isSchedulerRunColumnId) ?? []; - return { - visibleColumns: columns.length > 0 ? [...new Set(columns)] : [...SCHEDULER_RUN_COLUMN_IDS], - }; -} - export function withSchedulerRunFilters( state: SchedulerRunFilters, patch: Partial, @@ -164,46 +176,51 @@ export function withSchedulerRunFilters( }); } -export function withSchedulerRunColumnState( - state: SchedulerRunColumnState, - patch: Partial, -): SchedulerRunColumnState { - return normalizeSchedulerRunColumnState({ - ...state, - ...patch, - }); +/** Reset every Filters-disclosure field; search and the status segment stay. */ +export function withSchedulerSecondaryFiltersCleared(state: SchedulerRunFilters): SchedulerRunFilters { + const defaults = Object.fromEntries( + SCHEDULER_SECONDARY_FILTER_KEYS.map((key) => [key, DEFAULT_SCHEDULER_RUN_FILTERS[key]]), + ) as Partial; + return withSchedulerRunFilters(state, defaults); +} + +export function withSchedulerViewPreferences( + state: SchedulerViewPreferences, + patch: Partial, +): SchedulerViewPreferences { + return { + showLanes: typeof patch.showLanes === 'boolean' ? patch.showLanes : state.showLanes, + }; } const schedulerRunFiltersStore = writable({ ...DEFAULT_SCHEDULER_RUN_FILTERS, }); -const schedulerRunColumnStateStore = writable({ - visibleColumns: [...DEFAULT_SCHEDULER_RUN_COLUMN_STATE.visibleColumns], +const schedulerViewPreferencesStore = writable({ + ...DEFAULT_SCHEDULER_VIEW_PREFERENCES, }); export const schedulerRunFilters: Readable = { subscribe: schedulerRunFiltersStore.subscribe, }; -export const schedulerRunColumnState: Readable = { - subscribe: schedulerRunColumnStateStore.subscribe, +export const schedulerViewPreferences: Readable = { + subscribe: schedulerViewPreferencesStore.subscribe, }; export function setSchedulerRunFilters(patch: Partial): void { schedulerRunFiltersStore.update((state) => withSchedulerRunFilters(state, patch)); } -export function setSchedulerRunColumnState(patch: Partial): void { - schedulerRunColumnStateStore.update((state) => withSchedulerRunColumnState(state, patch)); +export function clearSchedulerSecondaryFilters(): void { + schedulerRunFiltersStore.update(withSchedulerSecondaryFiltersCleared); } export function resetSchedulerRunFilters(): void { schedulerRunFiltersStore.set({ ...DEFAULT_SCHEDULER_RUN_FILTERS }); } -export function resetSchedulerRunColumnState(): void { - schedulerRunColumnStateStore.set({ - visibleColumns: [...DEFAULT_SCHEDULER_RUN_COLUMN_STATE.visibleColumns], - }); +export function setSchedulerViewPreferences(patch: Partial): void { + schedulerViewPreferencesStore.update((state) => withSchedulerViewPreferences(state, patch)); } diff --git a/src/stores/workbenchStore.test.ts b/src/stores/workbenchStore.test.ts index f681074a3..f9bd0645d 100644 --- a/src/stores/workbenchStore.test.ts +++ b/src/stores/workbenchStore.test.ts @@ -4,24 +4,61 @@ import assert from 'node:assert/strict'; import { DEFAULT_WORKBENCH_STATE, WORKBENCH_PAGE_IDS, + WORKBENCH_PAGES, + WORKBENCH_TAB_GROUPS, normalizeWorkbenchPageId, + workbenchPagesInGroup, withDiagnosticsFocus, withSettingsFocus, withActiveWorkflowRun, withSelectedWorkbenchPage, } from './workbenchStore.ts'; -test('workbench page order starts at Scheduler and includes reserved pages', () => { +test('workbench page order follows the tab bar with Sessions first', () => { assert.deepEqual(WORKBENCH_PAGE_IDS, [ + 'sessions', 'scheduler', 'diagnostics', - 'graph', 'io_inspector', - 'library', 'network', + 'graph', 'node_lab', + 'library', 'settings', ]); + assert.deepEqual( + WORKBENCH_PAGES.map((page) => page.id), + [...WORKBENCH_PAGE_IDS], + ); +}); + +test('Scheduler stays the default page after Sessions is added', () => { + assert.equal(DEFAULT_WORKBENCH_STATE.selected_page_id, 'scheduler'); + assert.equal(normalizeWorkbenchPageId('sessions'), 'sessions'); + assert.equal( + WORKBENCH_PAGES.find((page) => page.id === 'sessions')?.label, + 'Sessions', + ); +}); + +test('tab groups partition every page except the pinned Settings tab', () => { + assert.deepEqual(WORKBENCH_TAB_GROUPS, ['sessions', 'runs', 'workflows']); + assert.deepEqual( + workbenchPagesInGroup('sessions').map((page) => page.id), + ['sessions'], + ); + assert.deepEqual( + workbenchPagesInGroup('runs').map((page) => page.id), + ['scheduler', 'diagnostics', 'io_inspector', 'network'], + ); + assert.deepEqual( + workbenchPagesInGroup('workflows').map((page) => page.id), + ['graph', 'node_lab', 'library'], + ); + assert.deepEqual( + workbenchPagesInGroup('settings').map((page) => page.id), + ['settings'], + ); }); test('normalizeWorkbenchPageId falls back to Scheduler for unknown values', () => { diff --git a/src/stores/workbenchStore.ts b/src/stores/workbenchStore.ts index fcd0370e7..537513e0f 100644 --- a/src/stores/workbenchStore.ts +++ b/src/stores/workbenchStore.ts @@ -1,21 +1,29 @@ import { derived, writable, type Readable } from 'svelte/store'; export const WORKBENCH_PAGE_IDS = [ + 'sessions', 'scheduler', 'diagnostics', - 'graph', 'io_inspector', - 'library', 'network', + 'graph', 'node_lab', + 'library', 'settings', ] as const; export type WorkbenchPageId = (typeof WORKBENCH_PAGE_IDS)[number]; +/** + * Tab bar group. The shell separates groups with a divider and pins + * `settings` to the right edge of the header. + */ +export type WorkbenchPageGroup = 'sessions' | 'runs' | 'workflows' | 'settings'; + export interface WorkbenchPageDefinition { id: WorkbenchPageId; label: string; + group: WorkbenchPageGroup; } export interface ActiveWorkflowRunContext { @@ -49,16 +57,24 @@ export interface WorkbenchState { } export const WORKBENCH_PAGES: WorkbenchPageDefinition[] = [ - { id: 'scheduler', label: 'Scheduler' }, - { id: 'diagnostics', label: 'Diagnostics' }, - { id: 'graph', label: 'Graph' }, - { id: 'io_inspector', label: 'I/O Inspector' }, - { id: 'library', label: 'Library' }, - { id: 'network', label: 'Network' }, - { id: 'node_lab', label: 'Node Editor' }, - { id: 'settings', label: 'Settings' }, + { id: 'sessions', label: 'Sessions', group: 'sessions' }, + { id: 'scheduler', label: 'Scheduler', group: 'runs' }, + { id: 'diagnostics', label: 'Diagnostics', group: 'runs' }, + { id: 'io_inspector', label: 'I/O Inspector', group: 'runs' }, + { id: 'network', label: 'Network', group: 'runs' }, + { id: 'graph', label: 'Graph', group: 'workflows' }, + { id: 'node_lab', label: 'Node Editor', group: 'workflows' }, + { id: 'library', label: 'Library', group: 'workflows' }, + { id: 'settings', label: 'Settings', group: 'settings' }, ]; +/** Tab groups in header order, left to right, excluding the pinned Settings tab. */ +export const WORKBENCH_TAB_GROUPS: readonly WorkbenchPageGroup[] = ['sessions', 'runs', 'workflows']; + +export function workbenchPagesInGroup(group: WorkbenchPageGroup): WorkbenchPageDefinition[] { + return WORKBENCH_PAGES.filter((page) => page.group === group); +} + export const DEFAULT_WORKBENCH_STATE: WorkbenchState = { selected_page_id: 'scheduler', active_run: null, diff --git a/src/styles.css b/src/styles.css index e4394814d..fd1809911 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1,24 +1,55 @@ +/* Bundled fonts (SIL OFL 1.1) so the desktop app renders the same offline. */ +@import '@fontsource/newsreader/400.css'; +@import '@fontsource/newsreader/500.css'; +@import '@fontsource/atkinson-hyperlegible/400.css'; +@import '@fontsource/atkinson-hyperlegible/700.css'; +@import '@fontsource/jetbrains-mono/400.css'; +@import '@fontsource/jetbrains-mono/500.css'; + @tailwind base; @tailwind components; @tailwind utilities; +/* + * Workbench design tokens (docs/design/workbench-redesign-spec.md, "Tokens"). + * The first block is the spec palette; the second holds the few derived values + * the approved mockup CSS (docs/design/mockups/boards/shell.css) uses for ink, + * quiet text, scrollbars and borders. Pages use these through the Tailwind + * `pg-*` colours or the `pg-*` component classes below, never raw hex. + */ :root { color-scheme: dark; - --color-bg-inner: #303030; - --color-bg-outer: #4a4a4a; - --color-surface-deep: #2f2f2f; - --color-surface: #383838; - --color-surface-raised: #464646; - --color-surface-hover: #525252; - --color-border-soft: #626262; - --color-border-strong: #777; - --color-grid: rgba(255, 255, 255, 0.1); - --color-ruler: #5c5c5c; - --color-accent: #3b82f6; - --color-control-bg: #3f3f3f; - --color-control-bg-hover: #4b4b4b; - --color-control-text: #f0f0f0; - --color-control-muted: #b8b8b8; + + --pg-ground: #2a2e35; + --pg-panel: #33383f; + --pg-panel-raised: #3a3f47; + --pg-panel-selected: #434a54; + --pg-panel-sunken: #23272d; + --pg-panel-head: #2e333a; + --pg-border: #4a5059; + --pg-border-soft: #3b4048; + --pg-border-strong: #8a909a; + --pg-text: #e4e6ea; + --pg-text-bright: #ffffff; + --pg-text-muted: #a3a9b4; + --pg-text-soft: #c9cdd4; + --pg-accent: #d9b06a; + --pg-danger: #e39a9a; + --pg-ok: #a7c4a0; + --pg-info: #9fb7d9; + + --pg-ink: #1f2227; + --pg-text-quiet: #b8bdc6; + --pg-text-code: #d5d9df; + --pg-border-idle: #6b717b; + --pg-border-danger: #5a4247; + --pg-rule-log: #30353c; + --pg-scroll-thumb: #5a6069; + --pg-scroll-thumb-hover: #7a818c; + + --pg-font-serif: 'Newsreader', Georgia, serif; + --pg-font-sans: 'Atkinson Hyperlegible', system-ui, sans-serif; + --pg-font-mono: 'JetBrains Mono', ui-monospace, monospace; } html, @@ -30,115 +61,916 @@ body { body { overflow: hidden; - background: radial-gradient(circle, var(--color-bg-inner) 0%, var(--color-bg-outer) 100%); - font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; - color: #e5e7eb; -} - -body.bg-neutral-950 { - background: radial-gradient(circle, var(--color-bg-inner) 0%, var(--color-bg-outer) 100%) !important; + background: var(--pg-ground); + color: var(--pg-text); + font-family: var(--pg-font-sans); + font-size: 14px; + line-height: 1.45; } #app { height: 100%; } -.canvas-grid { - background-image: - linear-gradient(to right, var(--color-grid) 1px, transparent 1px), - linear-gradient(to bottom, var(--color-grid) 1px, transparent 1px); - background-size: 40px 40px; -} - -/* Restore the original grey drawing-app feel after the workbench shell cutover. */ -.bg-neutral-950, -[class*="bg-neutral-950/"] { - background-color: var(--color-surface-deep) !important; -} - -.bg-neutral-900, -[class*="bg-neutral-900/"] { - background-color: var(--color-surface) !important; +button, +input, +select, +textarea { + font: inherit; + color: inherit; } -.bg-neutral-800, -[class*="bg-neutral-800/"] { - background-color: var(--color-surface-raised) !important; +/* Themed scrollbars everywhere (spec "Scrollbars"). */ +* { + scrollbar-width: thin; + scrollbar-color: var(--pg-scroll-thumb) transparent; } -.bg-neutral-700, -[class*="bg-neutral-700/"] { - background-color: #515151 !important; +::-webkit-scrollbar { + width: 10px; + height: 10px; } -.hover\:bg-neutral-900:hover, -[class*="hover:bg-neutral-900/"]:hover { - background-color: var(--color-surface-raised) !important; +::-webkit-scrollbar-track, +::-webkit-scrollbar-corner { + background: transparent; } -.hover\:bg-neutral-800:hover, -[class*="hover:bg-neutral-800/"]:hover { - background-color: var(--color-surface-hover) !important; +::-webkit-scrollbar-thumb { + background: var(--pg-scroll-thumb); + border-radius: 5px; + border: 2px solid var(--pg-panel); } -.hover\:bg-neutral-700:hover, -[class*="hover:bg-neutral-700/"]:hover { - background-color: #5d5d5d !important; +::-webkit-scrollbar-thumb:hover { + background: var(--pg-scroll-thumb-hover); } -.border-neutral-900, -.border-neutral-800, -.border-neutral-700, -.border-neutral-600 { - border-color: var(--color-border-soft) !important; +/* One visible focus treatment for every focusable control (spec "Focus"). */ +:focus-visible { + outline: 2px solid var(--pg-accent); + outline-offset: 1px; } -.hover\:border-neutral-600:hover, -.hover\:border-neutral-500:hover { - border-color: var(--color-border-strong) !important; +.canvas-grid { + background-image: + linear-gradient(to right, rgba(255, 255, 255, 0.1) 1px, transparent 1px), + linear-gradient(to bottom, rgba(255, 255, 255, 0.1) 1px, transparent 1px); + background-size: 40px 40px; } +/* Form controls on pages not yet restyled keep a dark, readable baseline. */ select, textarea, input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="file"]) { color-scheme: dark; - background-color: var(--color-control-bg); - color: var(--color-control-text); - border-color: var(--color-border-soft); -} - -select:hover, -textarea:hover, -input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="file"]):hover { - background-color: var(--color-control-bg-hover); + background-color: var(--pg-panel-sunken); + color: var(--pg-text); + border-color: var(--pg-border); } select:disabled, textarea:disabled, input:disabled { - color: var(--color-control-muted); + color: var(--pg-text-muted); opacity: 0.7; } select option, select optgroup { - background-color: var(--color-control-bg); - color: var(--color-control-text); + background-color: var(--pg-panel-sunken); + color: var(--pg-text); } -select option:disabled { - color: var(--color-control-muted); +::placeholder { + color: var(--pg-text-muted); + opacity: 1; } -::placeholder { - color: #8a8a8a; +/* + * Package graph components (packages/svelte-graph) still carry literal + * pre-workbench darks in scoped styles; only an override can reach them until + * the Graph milestone (M5) restyles them through styling hooks. + */ +/* + * Workbench primitives, ported value-for-value from the approved mockup CSS + * (docs/design/mockups/boards/shell.css) with a `pg-` prefix. The shared parts + * in src/components/workbench/ui/ use them; pages may use the plain classes + * (pg-btn, pg-field, pg-mono, ...) for controls that have no shared part. + */ +@layer components { + .pg-serif { + font-family: var(--pg-font-serif); + } + + .pg-mono { + font-family: var(--pg-font-mono); + font-size: 12.5px; + } + + .pg-muted { + color: var(--pg-text-muted); + } + + .pg-small { + font-size: 12.5px; + } + + .pg-title { + font-family: var(--pg-font-serif); + font-size: 24px; + font-weight: 500; + letter-spacing: -0.01em; + color: var(--pg-text-bright); + } + + .pg-title .pg-muted { + font-size: 16px; + } + + .pg-subtitle { + font-family: var(--pg-font-serif); + font-size: 20px; + font-weight: 500; + letter-spacing: -0.01em; + color: var(--pg-text-bright); + } + + .pg-sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; + } + + /* Page body under the shell header. */ + .pg-main { + flex: 1; + min-height: 0; + padding: 10px 22px 16px; + display: flex; + flex-direction: column; + gap: 10px; + } + + .pg-field { + height: 30px; + padding: 0 10px; + border: 1px solid var(--pg-border); + border-radius: 4px; + background: var(--pg-panel-sunken); + color: var(--pg-text); + } + + .pg-fl { + font-size: 12px; + color: var(--pg-text-muted); + } + + .pg-fl .pg-field { + display: block; + width: 100%; + margin-top: 3px; + height: 28px; + } + + .pg-btn { + height: 30px; + padding: 0 11px; + border: 1px solid var(--pg-border); + border-radius: 4px; + background: var(--pg-panel); + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--pg-text); + text-decoration: none; + font-size: 13px; + white-space: nowrap; + } + + .pg-btn:hover { + border-color: var(--pg-border-strong); + } + + .pg-btn-sm { + height: 28px; + } + + .pg-btn-primary { + background: var(--pg-text); + color: var(--pg-ink); + border-color: var(--pg-text); + font-weight: 700; + } + + .pg-btn-danger { + background: transparent; + color: var(--pg-danger); + border-color: var(--pg-border-danger); + } + + .pg-btn-danger:hover { + border-color: var(--pg-danger); + } + + .pg-btn-confirm { + background: var(--pg-danger); + color: var(--pg-ink); + border-color: var(--pg-danger); + font-weight: 700; + } + + .pg-btn:disabled, + .pg-btn[aria-disabled='true'], + .pg-tgl:disabled, + .pg-tgl[aria-disabled='true'] { + opacity: 0.45; + cursor: default; + } + + .pg-btn:disabled:hover, + .pg-btn[aria-disabled='true']:hover { + border-color: var(--pg-border); + } + + .pg-tgl { + height: 26px; + padding: 0 10px; + border: 1px solid var(--pg-border); + border-radius: 4px; + background: transparent; + color: var(--pg-text-quiet); + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12.5px; + white-space: nowrap; + } + + .pg-tgl:hover { + color: var(--pg-text-bright); + border-color: var(--pg-border-strong); + } + + .pg-tgl[aria-pressed='true'] { + background: var(--pg-text); + color: var(--pg-ink); + border-color: var(--pg-text); + } + + /* Status glyphs (spec "Status glyph vocabulary"). */ + .pg-g { + display: inline-block; + width: 10px; + height: 10px; + border-radius: 50%; + border: 1.5px solid var(--pg-text-muted); + flex: none; + } + + .pg-g-sm { + width: 8px; + height: 8px; + } + + .pg-g-running { + background: var(--pg-accent); + border-color: var(--pg-accent); + } + + .pg-g-waiting { + background: linear-gradient(90deg, var(--pg-accent) 50%, transparent 50%); + border-color: var(--pg-accent); + } + + .pg-g-queued { + background: transparent; + } + + .pg-g-succeeded { + background: var(--pg-text-muted); + border-color: var(--pg-text-muted); + } + + .pg-g-failed { + background: var(--pg-danger); + border-color: var(--pg-danger); + border-radius: 1px; + transform: rotate(45deg) scale(0.9); + } + + .pg-g-cancelled { + border-style: dashed; + } + + .pg-g-idle { + border-color: var(--pg-border-idle); + } + + .pg-g-warn { + background: var(--pg-accent); + border-color: var(--pg-accent); + border-radius: 1px; + transform: rotate(45deg) scale(0.9); + } + + /* Glyph drawn on an accent fill (device lane running block). */ + .pg-g-dark { + border-color: var(--pg-ink); + } + + .pg-g-dark.pg-g-running { + background: var(--pg-ink); + } + + .pg-st-failed { + color: var(--pg-danger); + } + + /* Dimension line. */ + .pg-dimrow { + display: flex; + align-items: center; + padding: 8px 0 4px; + flex: none; + } + + .pg-dim { + position: relative; + flex: 1; + height: 1px; + background: var(--pg-border-strong); + align-self: center; + margin: 0 6px; + } + + .pg-dim::before, + .pg-dim::after { + content: ''; + position: absolute; + top: -5px; + width: 1px; + height: 11px; + background: var(--pg-border-strong); + } + + .pg-dim::before { + left: 0; + } + + .pg-dim::after { + right: 0; + } + + .pg-dim-label { + position: absolute; + left: 50%; + top: -9px; + transform: translateX(-50%); + padding: 0 12px; + background: var(--pg-ground); + font-family: var(--pg-font-mono); + font-size: 12px; + color: var(--pg-text-soft); + white-space: nowrap; + max-width: calc(100% - 24px); + overflow: hidden; + text-overflow: ellipsis; + } + + /* Panels. */ + .pg-panel { + background: var(--pg-panel); + border: 1px solid var(--pg-border); + border-radius: 4px; + } + + .pg-col { + display: flex; + flex-direction: column; + overflow: hidden; + min-width: 0; + } + + .pg-scroll { + flex: 1; + min-height: 0; + overflow: auto; + } + + .pg-ptop { + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 8px; + flex: none; + border-bottom: 1px solid var(--pg-border); + } + + .pg-pfoot { + padding: 8px 12px; + border-top: 1px solid var(--pg-border); + background: var(--pg-panel-head); + display: flex; + gap: 8px; + align-items: center; + flex: none; + min-height: 48px; + } + + .pg-sec { + padding: 14px 18px; + border-top: 1px solid var(--pg-border); + } + + .pg-sec h3 { + margin: 0 0 8px; + font-size: 13px; + font-weight: 700; + color: var(--pg-text-bright); + } + + .pg-empty { + padding: 32px 24px; + color: var(--pg-text-muted); + } + + /* Group headers and list rows. */ + .pg-ghead { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + padding: 7px 12px; + border: 0; + border-top: 1px solid var(--pg-border-soft); + background: var(--pg-panel-head); + color: var(--pg-text-soft); + font-size: 12px; + font-weight: 700; + text-align: left; + cursor: pointer; + position: sticky; + top: 0; + z-index: 1; + } + + .pg-n { + font-family: var(--pg-font-mono); + font-size: 11px; + font-weight: 400; + color: var(--pg-text-muted); + } + + .pg-ghead .pg-chev { + margin-left: auto; + font-size: 10px; + color: var(--pg-border-strong); + } + + .pg-item { + display: grid; + grid-template-columns: 14px 1fr auto; + gap: 10px; + align-items: start; + width: 100%; + padding: 8px 12px; + border: 0; + border-top: 1px solid var(--pg-border-soft); + background: transparent; + text-align: left; + cursor: pointer; + color: var(--pg-text); + } + + .pg-item:hover { + background: var(--pg-panel-raised); + } + + .pg-item[aria-current='true'] { + background: var(--pg-panel-selected); + box-shadow: inset 3px 0 0 var(--pg-text); + } + + .pg-item .pg-g { + margin-top: 4px; + } + + .pg-item .pg-name { + font-weight: 700; + color: var(--pg-text-bright); + } + + .pg-ver { + font-family: var(--pg-font-mono); + font-size: 11px; + color: var(--pg-text-muted); + margin-left: 6px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 12rem; + display: inline-block; + vertical-align: bottom; + } + + .pg-item .pg-time { + font-family: var(--pg-font-mono); + font-size: 11.5px; + color: var(--pg-text-muted); + padding-top: 2px; + white-space: nowrap; + } + + .pg-sub { + display: block; + font-size: 12.5px; + color: var(--pg-text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + /* Segmented control. */ + .pg-seg { + display: flex; + flex-wrap: wrap; + border: 1px solid var(--pg-border); + border-radius: 4px; + overflow: hidden; + background: var(--pg-panel-sunken); + } + + .pg-seg button { + height: 30px; + padding: 0 7px; + border: 0; + background: transparent; + cursor: pointer; + display: flex; + gap: 4px; + align-items: center; + justify-content: center; + color: var(--pg-text-quiet); + font-size: 12.5px; + white-space: nowrap; + min-width: 0; + flex: 1; + } + + .pg-seg button + button { + border-left: 1px solid var(--pg-border-soft); + } + + .pg-seg button:hover { + background: var(--pg-panel); + color: var(--pg-text-bright); + } + + .pg-seg button[aria-pressed='true'] { + background: var(--pg-text); + color: var(--pg-ink); + } + + .pg-seg .pg-n { + color: inherit; + opacity: 0.8; + } + + /* Chips. */ + .pg-chip { + display: inline-flex; + align-items: center; + gap: 6px; + height: 22px; + padding: 0 8px; + border: 1px solid var(--pg-border); + border-radius: 11px; + font-size: 12px; + background: var(--pg-panel-sunken); + white-space: nowrap; + } + + .pg-fchip { + display: inline-flex; + align-items: center; + gap: 4px; + height: 24px; + padding: 0 4px 0 8px; + border: 1px solid var(--pg-border-idle); + border-radius: 12px; + font-size: 12px; + background: var(--pg-panel-head); + color: var(--pg-text); + } + + .pg-fchip button { + width: 18px; + height: 18px; + border: 0; + border-radius: 9px; + background: transparent; + color: var(--pg-text-muted); + cursor: pointer; + } + + .pg-fchip button:hover { + background: var(--pg-border); + color: var(--pg-text-bright); + } + + /* Key/value grid. */ + .pg-kv { + display: grid; + grid-template-columns: max-content 1fr; + gap: 5px 16px; + font-size: 13.5px; + margin: 0; + } + + .pg-kv dt { + color: var(--pg-text-muted); + } + + .pg-kv dd { + margin: 0; + min-width: 0; + overflow-wrap: anywhere; + } + + /* Log lines. */ + .pg-log { + font-family: var(--pg-font-mono); + font-size: 12px; + line-height: 1.55; + } + + .pg-ln { + font-family: var(--pg-font-mono); + font-size: 12px; + line-height: 1.55; + display: grid; + grid-template-columns: 96px 14px 1fr; + gap: 10px; + padding: 3px 12px; + border-top: 1px solid var(--pg-rule-log); + align-items: start; + } + + .pg-ln:hover { + background: var(--pg-panel-raised); + } + + .pg-ln[aria-current='true'] { + background: var(--pg-panel-selected); + box-shadow: inset 3px 0 0 var(--pg-text); + } + + .pg-ln .pg-t { + color: var(--pg-border-strong); + } + + .pg-ln .pg-g { + margin-top: 5px; + width: 8px; + height: 8px; + } + + .pg-ln-err { + background: rgba(227, 154, 154, 0.06); + } + + .pg-ln .pg-m { + white-space: pre-wrap; + word-break: break-word; + color: var(--pg-text-code); + } + + .pg-ln .pg-m b { + color: var(--pg-text-bright); + font-weight: 500; + } + + /* Error card. */ + .pg-errcard { + padding: 10px 12px; + border: 1px solid var(--pg-border-danger); + border-left: 3px solid var(--pg-danger); + border-radius: 4px; + background: var(--pg-panel-head); + display: flex; + gap: 12px; + align-items: flex-start; + } + + .pg-errcard .pg-g { + margin-top: 5px; + } + + /* Device lanes. */ + .pg-lanes { + display: flex; + gap: 22px; + align-items: center; + padding: 8px 12px; + border: 1px solid var(--pg-border); + border-radius: 4px; + background: var(--pg-panel-head); + flex: none; + } + + .pg-lane { + display: grid; + grid-template-columns: 118px 1fr; + gap: 8px; + align-items: center; + } + + .pg-lane-name { + font-family: var(--pg-font-mono); + font-size: 11.5px; + color: var(--pg-text-soft); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.3; + } + + .pg-lane-track { + display: flex; + gap: 2px; + height: 20px; + border-radius: 3px; + overflow: hidden; + background: var(--pg-panel-sunken); + } + + .pg-blk { + display: flex; + align-items: center; + gap: 6px; + padding: 0 6px; + font-size: 11px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + border: 1px solid transparent; + border-radius: 2px; + } + + .pg-blk-running { + background: var(--pg-accent); + color: var(--pg-ink); + font-weight: 700; + } + + .pg-blk-waiting { + border-color: var(--pg-accent); + color: var(--pg-text); + background: repeating-linear-gradient(135deg, transparent 0 4px, rgba(217, 176, 106, 0.25) 4px 6px); + } + + .pg-blk-queued { + border-color: var(--pg-border-idle); + color: var(--pg-text-soft); + } + + .pg-blk-free { + border: 0; + } + + .pg-legend { + display: flex; + gap: 14px; + align-items: center; + font-size: 11.5px; + color: var(--pg-text-muted); + white-space: nowrap; + } + + /* Meters, tables, code and cards for page agents. */ + .pg-meter { + height: 6px; + border-radius: 3px; + background: var(--pg-panel-sunken); + overflow: hidden; + } + + .pg-meter > i { + display: block; + height: 100%; + background: var(--pg-border-strong); + border-radius: 3px; + } + + .pg-meter > i.pg-meter-accent { + background: var(--pg-accent); + } + + .pg-tbl { + width: 100%; + border-collapse: collapse; + font-size: 13px; + } + + .pg-tbl th { + position: sticky; + top: 0; + z-index: 1; + background: var(--pg-panel-head); + color: var(--pg-text-muted); + font-weight: 700; + font-size: 12px; + text-align: left; + padding: 7px 12px; + border-bottom: 1px solid var(--pg-border); + white-space: nowrap; + } + + .pg-tbl td { + padding: 7px 12px; + border-top: 1px solid var(--pg-border-soft); + vertical-align: top; + } + + .pg-num { + font-family: var(--pg-font-mono); + font-size: 12px; + text-align: right; + white-space: nowrap; + } + + .pg-code { + font-family: var(--pg-font-mono); + font-size: 12px; + line-height: 1.55; + white-space: pre; + overflow: auto; + padding: 12px 14px; + background: var(--pg-panel-sunken); + border-radius: 4px; + border: 1px solid var(--pg-border); + color: var(--pg-text-code); + } + + .pg-card { + background: var(--pg-panel); + border: 1px solid var(--pg-border); + border-radius: 4px; + padding: 12px 14px; + } + + .pg-card h4 { + margin: 0 0 6px; + font-size: 13px; + font-weight: 700; + color: var(--pg-text-bright); + } + + .pg-toast { + position: fixed; + left: 50%; + bottom: 22px; + transform: translateX(-50%); + z-index: 70; + padding: 7px 12px; + border: 1px solid var(--pg-border); + border-radius: 4px; + background: var(--pg-panel-sunken); + color: var(--pg-text); + font-size: 12.5px; + font-family: var(--pg-font-mono); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4); + } } -/* Package graph components still contain a few literal pre-workbench darks. */ -.svelte-flow, -.base-node, -.node-palette, -.workflow-toolbar, -.navigation-breadcrumb { - background-color: var(--color-surface) !important; +/* integration additions (M9) */ +.pg-fl textarea.pg-field { + height: auto; + min-height: 72px; + padding: 6px 10px; + resize: vertical; +} +.pg-seg button:disabled { + color: var(--pg-text-muted); + cursor: default; + opacity: 0.55; +} +.pg-seg button:disabled:hover { + background: transparent; + color: var(--pg-text-muted); +} +.pg-errcard-muted { + border-color: var(--pg-border); + border-left-color: var(--pg-border-strong); + background: var(--pg-panel-head); } diff --git a/tailwind.config.cjs b/tailwind.config.cjs index bb689d9ba..157e82e6e 100644 --- a/tailwind.config.cjs +++ b/tailwind.config.cjs @@ -1,22 +1,57 @@ +// Workbench tokens live as CSS custom properties in src/styles.css; these +// colours point at them so `bg-pg-panel`, `text-pg-text-muted`, +// `border-pg-border` and friends follow the one palette. Opacity modifiers +// (`bg-pg-panel/50`) are not supported for the `pg` colours because the +// variables hold hex values. +const pg = (name) => `var(--pg-${name})`; + module.exports = { content: ['./index.html', './src/**/*.{svelte,ts}'], theme: { extend: { colors: { + pg: { + ground: pg('ground'), + panel: pg('panel'), + 'panel-raised': pg('panel-raised'), + 'panel-selected': pg('panel-selected'), + 'panel-sunken': pg('panel-sunken'), + 'panel-head': pg('panel-head'), + border: pg('border'), + 'border-soft': pg('border-soft'), + 'border-strong': pg('border-strong'), + text: pg('text'), + 'text-bright': pg('text-bright'), + 'text-muted': pg('text-muted'), + 'text-soft': pg('text-soft'), + accent: pg('accent'), + danger: pg('danger'), + ok: pg('ok'), + info: pg('info'), + ink: pg('ink'), + }, + // Pages that are not yet restyled still use the neutral scale. It is + // tuned to the workbench greys (950 = ground, 900 = panel) so those + // pages sit on the new palette without `!important` overrides. neutral: { - 50: '#fafafa', - 100: '#f5f5f5', - 200: '#e5e5e5', - 300: '#d4d4d4', - 400: '#b8b8b8', - 500: '#969696', - 600: '#777777', - 700: '#5d5d5d', - 800: '#464646', - 900: '#383838', - 950: '#2f2f2f', + 50: '#f4f5f7', + 100: '#e4e6ea', + 200: '#d5d9df', + 300: '#c9cdd4', + 400: '#a3a9b4', + 500: '#8a909a', + 600: '#6b717b', + 700: '#4a5059', + 800: '#3a3f47', + 900: '#33383f', + 950: '#2a2e35', }, }, + fontFamily: { + serif: ['Newsreader', 'Georgia', 'serif'], + sans: ['"Atkinson Hyperlegible"', 'system-ui', 'sans-serif'], + mono: ['"JetBrains Mono"', 'ui-monospace', 'monospace'], + }, }, }, plugins: [], From fca20d6ab6f5b17b39f019b9664fc29dd56ae25c Mon Sep 17 00:00:00 2001 From: MrScripty Date: Tue, 3 Nov 2026 06:31:21 -0700 Subject: [PATCH 08/15] test(e2e): port the I/O Inspector harnesses to the redesigned page Artifacts are selected from the node and port tree before their card is checked; the stream button, Refresh and error regions use the new test ids; the stale-read check waits for the read to start before removing the artifact. Assertion intent is unchanged. The fixture harness passed on real WebKitGTK (see the plan's evidence folder). Co-Authored-By: Claude Fable 5.1 --- tests/e2e/io-inspector-image-preview/run.mjs | 137 ++++++++++++------ .../wdio.conf.mjs | 1 + .../workflow-editor-image-generation.e2e.mjs | 74 ++++++++-- 3 files changed, 161 insertions(+), 51 deletions(-) diff --git a/tests/e2e/io-inspector-image-preview/run.mjs b/tests/e2e/io-inspector-image-preview/run.mjs index 466e3d8a6..293672d02 100644 --- a/tests/e2e/io-inspector-image-preview/run.mjs +++ b/tests/e2e/io-inspector-image-preview/run.mjs @@ -1,3 +1,7 @@ +/* global process, console, fetch, setTimeout, window, document, Event */ +// Drives IoInspectorPage (workbench redesign M3 layout) in real WebKitGTK. +// The page shows a node/port tree on the left and ONE artifact card on the +// right, so every card assertion first selects the artifact's tree row. import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import path from 'node:path'; @@ -29,12 +33,27 @@ async function waitForDriver() { try { const response = await fetch(`http://${host}:${driverPort}/status`); if (response.ok) return; - } catch {} + } catch { + // WebKitWebDriver is not listening yet; poll again. + } await delay(50); } throw new Error('WebKitWebDriver did not become ready'); } +const READ_BUTTON = '[data-testid="io-artifact-read-button"]'; +const STREAM_BUTTON = '[data-testid="io-artifact-stream-button"]'; +const IMAGE_PREVIEW = '[data-testid="io-artifact-image-preview"]'; +const ACCESS_ERROR = '[data-testid="io-artifact-access-error"]'; +// The page's own Refresh lives in the footer of the "Nodes and ports" panel. +// It has no test id; the ErrorCard "Refresh" actions are deliberately not used. +const REFRESH_BUTTON = + '[data-testid="io-inspector-refresh"]'; + +function rowSelector(id) { + return `[data-testid="io-artifact-row"][data-artifact-id="${id}"]`; +} + function cardSelector(id) { return `[data-testid="io-artifact-card"][data-artifact-id="${id}"]`; } @@ -45,14 +64,36 @@ async function card(id) { return element; } +// Select the artifact's row in the node/port tree and wait for the one detail +// card to show it. Clicking the row that is already selected is a no-op in the +// page (pending reads are kept), which the image-identity checks rely on. +async function selectArtifact(artifactId) { + const row = await browser.$(rowSelector(artifactId)); + await row.waitForExist({ timeout: 10_000 }); + await row.scrollIntoView(); + await row.click(); + await browser.waitUntil( + async () => (await browser.$(rowSelector(artifactId)).getAttribute('aria-current')) === 'true', + { timeout: 10_000, timeoutMsg: `row ${artifactId} did not become the selected entry` }, + ); + return card(artifactId); +} + async function clickWithin(artifactId, selector) { - const artifactCard = await card(artifactId); + const artifactCard = await selectArtifact(artifactId); const target = await artifactCard.$(selector); await target.scrollIntoView(); await target.click(); return artifactCard; } +async function clickRefresh() { + const refresh = await browser.$(REFRESH_BUTTON); + await refresh.waitForEnabled({ timeout: 10_000 }); + await refresh.scrollIntoView(); + await refresh.click(); +} + async function waitForText(element, expected) { await browser.waitUntil(async () => (await element.getText()).includes(expected), { timeout: 10_000, @@ -60,6 +101,22 @@ async function waitForText(element, expected) { }); } +async function waitForAccessError(artifactId, expected) { + const accessError = await browser.$(`${cardSelector(artifactId)} ${ACCESS_ERROR}`); + await accessError.waitForExist({ timeout: 10_000 }); + await waitForText(accessError, expected); +} + +async function waitForArtifactGone(artifactId, timeoutMsg) { + await browser.waitUntil( + async () => browser.execute( + (selectors) => selectors.every((selector) => !document.querySelector(selector)), + [cardSelector(artifactId), rowSelector(artifactId)], + ), + { timeout: 10_000, timeoutMsg }, + ); +} + try { server = await createServer({ root: repoRoot, @@ -125,19 +182,19 @@ try { assert.ok(await browser.execute(() => window.d02.pngByteLength) > 65_536); console.log('checking valid image decode and full-body request'); - const validCard = await clickWithin('valid-image', '[data-testid="io-artifact-read-button"]'); - const validPreview = await validCard.$('[data-testid="io-artifact-image-preview"]'); + const validCard = await clickWithin('valid-image', READ_BUTTON); + const validPreview = await validCard.$(IMAGE_PREVIEW); await validPreview.waitForExist({ timeout: 10_000 }); const decoded = await browser.executeAsync((selector, done) => { const image = document.querySelector(selector); image.decode().then(() => done({ width: image.naturalWidth, height: image.naturalHeight }), (error) => done({ error: String(error) })); - }, `${cardSelector('valid-image')} [data-testid="io-artifact-image-preview"]`); + }, `${cardSelector('valid-image')} ${IMAGE_PREVIEW}`); assert.deepEqual(decoded, { width: 320, height: 320 }); let snapshot = await browser.execute(() => window.d02.snapshot()); assert.deepEqual(snapshot.readRequests[0], { artifact_id: 'payload-valid-image' }); assert.equal(snapshot.createdUrls.length, 1); - await clickWithin('valid-image', '[data-testid="io-artifact-read-button"]'); + await clickWithin('valid-image', READ_BUTTON); await browser.waitUntil(async () => (await browser.execute(() => window.d02.snapshot())).createdUrls.length === 2); snapshot = await browser.execute(() => window.d02.snapshot()); assert.ok(snapshot.revokedUrls.includes(snapshot.createdUrls[0]), 'refresh must revoke replaced preview URL'); @@ -145,56 +202,56 @@ try { console.log('checking detached and current image error identity'); await browser.execute((selector) => { window.d02DetachedImage = document.querySelector(selector); - }, `${cardSelector('valid-image')} [data-testid="io-artifact-image-preview"]`); + }, `${cardSelector('valid-image')} ${IMAGE_PREVIEW}`); console.log(' captured old image'); - await clickWithin('valid-image', '[data-testid="io-artifact-read-button"]'); + await clickWithin('valid-image', READ_BUTTON); console.log(' replacement clicked'); await browser.waitUntil(async () => (await browser.execute(() => window.d02.snapshot())).createdUrls.length === 3); console.log(' replacement installed'); await browser.execute(() => window.d02DetachedImage.dispatchEvent(new Event('error'))); console.log(' detached error dispatched'); assert.equal(await browser.execute((selector) => Boolean(document.querySelector(selector)), - `${cardSelector('valid-image')} [data-testid="io-artifact-image-preview"]`), true, + `${cardSelector('valid-image')} ${IMAGE_PREVIEW}`), true, 'an error from a detached replaced image must not remove the current preview'); await browser.execute(() => window.d02.deferValidRefresh()); console.log(' refresh deferred'); await browser.execute((selector) => document.querySelector(selector).click(), - `${cardSelector('valid-image')} [data-testid="io-artifact-read-button"]`); + `${cardSelector('valid-image')} ${READ_BUTTON}`); console.log(' pending refresh clicked'); const currentUrl = await browser.execute((selector) => document.querySelector(selector)?.src, - `${cardSelector('valid-image')} [data-testid="io-artifact-image-preview"]`); + `${cardSelector('valid-image')} ${IMAGE_PREVIEW}`); console.log(' current URL captured'); await browser.execute((selector) => document.querySelector(selector).dispatchEvent(new Event('error')), - `${cardSelector('valid-image')} [data-testid="io-artifact-image-preview"]`); + `${cardSelector('valid-image')} ${IMAGE_PREVIEW}`); console.log(' current error dispatched'); await browser.execute(() => window.d02.rejectValidRefresh()); console.log(' pending refresh rejected'); const validAfterPendingFailure = await card('valid-image'); - await waitForText(validAfterPendingFailure, 'fixture pending refresh failed'); - assert.equal(await validAfterPendingFailure.$('[data-testid="io-artifact-image-preview"]').isExisting(), false, + await waitForAccessError('valid-image', 'fixture pending refresh failed'); + assert.equal(await validAfterPendingFailure.$(IMAGE_PREVIEW).isExisting(), false, 'a matching image error must remove the broken preview while refresh is pending'); snapshot = await browser.execute(() => window.d02.snapshot()); assert.ok(snapshot.revokedUrls.includes(currentUrl), 'matching broken image URL was not revoked'); console.log('checking malformed image error'); const urlsBeforeMalformed = snapshot.createdUrls.length; - const malformedCard = await clickWithin('malformed-image', '[data-testid="io-artifact-read-button"]'); - await waitForText(malformedCard, 'could not be decoded'); - assert.equal(await malformedCard.$('[data-testid="io-artifact-image-preview"]').isExisting(), false); + const malformedCard = await clickWithin('malformed-image', READ_BUTTON); + await waitForAccessError('malformed-image', 'could not be decoded'); + assert.equal(await malformedCard.$(IMAGE_PREVIEW).isExisting(), false); snapshot = await browser.execute(() => window.d02.snapshot()); assert.equal(snapshot.createdUrls.length, urlsBeforeMalformed + 1); assert.ok(snapshot.revokedUrls.includes(snapshot.createdUrls.at(-1)), 'decode failure must revoke its object URL'); console.log('checking incomplete read and stream errors'); const urlsBeforePartial = snapshot.createdUrls.length; - const partialCard = await clickWithin('partial-image', '[data-testid="io-artifact-read-button"]'); - await waitForText(partialCard, 'complete'); - assert.equal(await partialCard.$('[data-testid="io-artifact-image-preview"]').isExisting(), false); + const partialCard = await clickWithin('partial-image', READ_BUTTON); + await waitForAccessError('partial-image', 'complete image body is required'); + assert.equal(await partialCard.$(IMAGE_PREVIEW).isExisting(), false); - const streamCard = await clickWithin('partial-stream-image', 'button[aria-label^="Read artifact stream"]'); - await waitForText(streamCard, 'complete'); - assert.equal(await streamCard.$('[data-testid="io-artifact-image-preview"]').isExisting(), false); + const streamCard = await clickWithin('partial-stream-image', STREAM_BUTTON); + await waitForAccessError('partial-stream-image', 'complete image body is required'); + assert.equal(await streamCard.$(IMAGE_PREVIEW).isExisting(), false); snapshot = await browser.execute(() => window.d02.snapshot()); assert.equal(snapshot.createdUrls.length, urlsBeforePartial, 'incomplete image bodies must be rejected before URL creation'); assert.deepEqual(snapshot.streamRequests, [{ @@ -204,10 +261,10 @@ try { }]); console.log('checking read failure and bounded text'); - const failedCard = await clickWithin('failed-image', '[data-testid="io-artifact-read-button"]'); - await waitForText(failedCard, 'fixture retained body read failed'); + await clickWithin('failed-image', READ_BUTTON); + await waitForAccessError('failed-image', 'fixture retained body read failed'); - const textCard = await clickWithin('bounded-text', '[data-testid="io-artifact-read-button"]'); + const textCard = await clickWithin('bounded-text', READ_BUTTON); await waitForText(textCard, 'text truncated'); const textLength = await browser.execute((selector) => document.querySelector(selector)?.textContent?.length ?? -1, `${cardSelector('bounded-text')} pre`); assert.equal(textLength, 32_000); @@ -219,14 +276,13 @@ try { }); console.log('checking stale pending read'); - await clickWithin('stale-image', '[data-testid="io-artifact-read-button"]'); + await clickWithin('stale-image', READ_BUTTON); + await browser.waitUntil(async () => (await browser.execute(() => window.d02.snapshot())).readRequests + .some((request) => request.artifact_id === 'payload-stale-image'), + { timeout: 10_000, timeoutMsg: 'stale read did not reach the body read' }); await browser.execute(() => window.d02.removeArtifact('stale-image')); - const refresh = await browser.$('[data-testid="io-inspector-page"] button:nth-of-type(2)'); - await refresh.click(); - await browser.waitUntil( - async () => browser.execute((selector) => !document.querySelector(selector), cardSelector('stale-image')), - { timeout: 10_000, timeoutMsg: 'stale artifact was not removed after refresh' }, - ); + await clickRefresh(); + await waitForArtifactGone('stale-image', 'stale artifact was not removed after refresh'); const urlsBeforeStaleResolution = (await browser.execute(() => window.d02.snapshot())).createdUrls.length; await browser.execute(() => window.d02.resolveStaleRead()); await delay(100); @@ -235,25 +291,22 @@ try { assert.equal(snapshot.createdUrls.length, urlsBeforeStaleResolution, 'stale read must not create a preview URL'); console.log('checking preview cleanup on inspection failure'); - await clickWithin('valid-image', '[data-testid="io-artifact-read-button"]'); + await clickWithin('valid-image', READ_BUTTON); await browser.waitUntil(async () => (await browser.execute(() => window.d02.snapshot())).createdUrls.length === urlsBeforeStaleResolution + 1); snapshot = await browser.execute(() => window.d02.snapshot()); const urlBeforeInspectionFailure = snapshot.createdUrls.at(-1); await browser.execute(() => window.d02.rejectInspectionOnce()); - await refresh.click(); - await browser.waitUntil( - async () => browser.execute((selector) => !document.querySelector(selector), cardSelector('valid-image')), - { timeout: 10_000, timeoutMsg: 'artifact cards remained after inspection refresh failure' }, - ); + await clickRefresh(); + await waitForArtifactGone('valid-image', 'artifact card and row remained after inspection refresh failure'); snapshot = await browser.execute(() => window.d02.snapshot()); assert.ok(snapshot.revokedUrls.includes(urlBeforeInspectionFailure), 'inspection failure must revoke the prior preview URL before clearing cards'); - await refresh.click(); - await card('unmount-pending-image'); + await clickRefresh(); + await selectArtifact('unmount-pending-image'); console.log('checking pending read completion after unmount'); - await clickWithin('unmount-pending-image', '[data-testid="io-artifact-read-button"]'); + await clickWithin('unmount-pending-image', READ_BUTTON); await browser.waitUntil(async () => (await browser.execute(() => window.d02.snapshot())).readRequests .some((request) => request.artifact_id === 'payload-unmount-pending-image')); snapshot = await browser.execute(() => window.d02.snapshot()); diff --git a/tests/e2e/workflow-editor-image-generation/wdio.conf.mjs b/tests/e2e/workflow-editor-image-generation/wdio.conf.mjs index bfe706749..580c0ebd1 100644 --- a/tests/e2e/workflow-editor-image-generation/wdio.conf.mjs +++ b/tests/e2e/workflow-editor-image-generation/wdio.conf.mjs @@ -1,3 +1,4 @@ +/* global process, console */ import { spawn, spawnSync } from 'node:child_process'; import { chmodSync, existsSync, writeFileSync } from 'node:fs'; import path from 'node:path'; diff --git a/tests/e2e/workflow-editor-image-generation/workflow-editor-image-generation.e2e.mjs b/tests/e2e/workflow-editor-image-generation/workflow-editor-image-generation.e2e.mjs index f939b0c53..b74e8d086 100644 --- a/tests/e2e/workflow-editor-image-generation/workflow-editor-image-generation.e2e.mjs +++ b/tests/e2e/workflow-editor-image-generation/workflow-editor-image-generation.e2e.mjs @@ -1,3 +1,4 @@ +/* global describe, it, $, browser, process, document, HTMLImageElement */ import assert from 'node:assert/strict'; describe('workflow editor image-generation desktop path', () => { @@ -7,9 +8,59 @@ describe('workflow editor image-generation desktop path', () => { return `[data-testid="${testId}"]`; } + function attributeValue(value) { + return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + } + function workflowOptionSelector(id) { - const escapedId = id.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); - return `${testIdSelector('workflow-graph-selector-option')}[data-workflow-id="${escapedId}"]`; + return `${testIdSelector('workflow-graph-selector-option')}[data-workflow-id="${attributeValue(id)}"]`; + } + + function artifactRowSelector(artifactId) { + return `${testIdSelector('io-artifact-row')}[data-artifact-id="${attributeValue(artifactId)}"]`; + } + + function artifactCardSelector(artifactId) { + return `${testIdSelector('io-artifact-card')}[data-artifact-id="${attributeValue(artifactId)}"]`; + } + + // The I/O Inspector shows a node/port tree and ONE artifact card. Select + // tree rows in order until the card shows an image artifact; the image only + // appears once the run has produced it, so keep polling the tree. + async function selectImageArtifactRow(timeout) { + let imageArtifactId = null; + await browser.waitUntil( + async () => { + const artifactIds = await browser.execute( + (rowSelector) => + Array.from(document.querySelectorAll(rowSelector), (row) => row.getAttribute('data-artifact-id') ?? ''), + testIdSelector('io-artifact-row'), + ); + for (const artifactId of new Set(artifactIds.filter(Boolean))) { + const row = await $(artifactRowSelector(artifactId)); + if (!(await row.isExisting())) { + continue; + } + await row.scrollIntoView(); + await row.click(); + const artifactCard = await $(artifactCardSelector(artifactId)); + if ( + (await artifactCard.isExisting()) && + (await artifactCard.getAttribute('data-artifact-media-family')) === 'image' + ) { + imageArtifactId = artifactId; + return true; + } + } + return false; + }, + { + timeout, + interval: 1000, + timeoutMsg: 'No I/O Inspector tree row selected an image artifact card', + }, + ); + return imageArtifactId; } it('submits a configured workflow and reads the retained image artifact through I/O Inspector', async () => { @@ -66,19 +117,24 @@ describe('workflow editor image-generation desktop path', () => { const ioInspectorPage = await $(testIdSelector('io-inspector-page')); await ioInspectorPage.waitForDisplayed({ timeout: 300000 }); - const imageArtifact = await $( - `${testIdSelector('io-artifact-card')}[data-artifact-media-family="image"]`, + const imageArtifactId = await selectImageArtifactRow(300000); + const imageCardSelector = `${artifactCardSelector(imageArtifactId)}[data-artifact-media-family="image"]`; + const imageArtifact = await $(imageCardSelector); + await imageArtifact.waitForDisplayed({ timeout: 30000 }); + assert.equal( + await $(artifactRowSelector(imageArtifactId)).getAttribute('aria-current'), + 'true', + 'The selected tree row must be the artifact shown in the card', ); - await imageArtifact.waitForDisplayed({ timeout: 300000 }); - const readButton = await imageArtifact.$(testIdSelector('io-artifact-read-button')); + const readButton = await $(`${imageCardSelector} ${testIdSelector('io-artifact-read-button')}`); await readButton.waitForClickable({ timeout: 30000 }); await readButton.click(); - const imagePreview = await imageArtifact.$(testIdSelector('io-artifact-image-preview')); + const imageSelector = `${imageCardSelector} ${testIdSelector('io-artifact-image-preview')}`; + const imagePreview = await $(imageSelector); await imagePreview.waitForDisplayed({ timeout: 120000 }); - const imageSelector = `${testIdSelector('io-artifact-card')}[data-artifact-media-family="image"] ${testIdSelector('io-artifact-image-preview')}`; const decodedImage = await browser.executeAsync((selector, done) => { const image = document.querySelector(selector); if (!(image instanceof HTMLImageElement)) { @@ -105,7 +161,7 @@ describe('workflow editor image-generation desktop path', () => { assert.ok(decodedImage.naturalWidth > 0, 'Decoded image must have positive naturalWidth'); assert.ok(decodedImage.naturalHeight > 0, 'Decoded image must have positive naturalHeight'); assert.equal( - await imageArtifact.$(testIdSelector('io-artifact-access-error')).isExisting(), + await $(`${imageCardSelector} ${testIdSelector('io-artifact-access-error')}`).isExisting(), false, 'A decoded image must not retain a read or decode error', ); From 2c5aae1d09ddaa79b172adad875ac7988b74b1ed Mon Sep 17 00:00:00 2001 From: MrScripty Date: Tue, 3 Nov 2026 06:31:21 -0700 Subject: [PATCH 09/15] docs(plan): record the workbench redesign plan, reports and evidence Plan package following the Coding-Standards template: objective and acceptance claims (A1 to A4 satisfied in a representative environment, A5 pending the owner's desktop run), binding decisions, the Standards Engine route snapshot, milestones M0 to M9 with their write sets, the execution ledger, 64 dispositioned issues (mostly projection fields the mockups assumed), per-milestone reports, the walkthrough tooling and fixtures, and the closing screenshots and WebKitGTK harness log. Co-Authored-By: Claude Fable 5.1 --- docs/plans/README.md | 1 + .../workbench-redesign/execution-ledger.md | 409 ++++++++++++++++++ docs/plans/workbench-redesign/issues.md | 72 +++ docs/plans/workbench-redesign/plan.md | 241 +++++++++++ .../reports/evidence/01-scheduler-no-run.png | Bin 0 -> 84211 bytes .../evidence/02-scheduler-failed-run.png | Bin 0 -> 148814 bytes .../reports/evidence/03-diagnostics.png | Bin 0 -> 150273 bytes .../reports/evidence/04-io-inspector.png | Bin 0 -> 143688 bytes .../reports/evidence/05-network.png | Bin 0 -> 130938 bytes .../reports/evidence/06-graph.png | Bin 0 -> 98669 bytes .../reports/evidence/07-node-editor.png | Bin 0 -> 131227 bytes .../reports/evidence/08-library.png | Bin 0 -> 130231 bytes .../reports/evidence/09-sessions.png | Bin 0 -> 131284 bytes .../reports/evidence/10-settings.png | Bin 0 -> 129095 bytes .../reports/evidence/11-io-after-paste.png | Bin 0 -> 143668 bytes .../reports/evidence/12-io-empty.png | Bin 0 -> 37156 bytes .../reports/evidence/13-diagnostics-empty.png | Bin 0 -> 31983 bytes .../reports/evidence/14-picker-open.png | Bin 0 -> 77444 bytes .../reports/m1-scheduler.md | 139 ++++++ .../reports/m2-diagnostics.md | 173 ++++++++ .../reports/m3-io-inspector.md | 181 ++++++++ .../workbench-redesign/reports/m4-network.md | 207 +++++++++ .../workbench-redesign/reports/m5-graph.md | 169 ++++++++ .../reports/m6-node-editor.md | 213 +++++++++ .../workbench-redesign/reports/m7-library.md | 173 ++++++++ .../workbench-redesign/reports/m8-sessions.md | 165 +++++++ .../reports/m9-e2e-harnesses.md | 161 +++++++ .../workbench-redesign/reports/m9-settings.md | 169 ++++++++ .../reports/m9c-settings-panels.md | 202 +++++++++ .../reports/m9d-graph-components.md | 154 +++++++ .../reports/page-agent-brief.md | 89 ++++ .../reports/tools/README.md | 15 + .../reports/tools/cdp-init.cjs | 33 ++ .../reports/tools/fixture-diagnostics.js | 193 +++++++++ .../reports/tools/fixture-graph.js | 160 +++++++ .../reports/tools/fixture-io.js | 85 ++++ .../reports/tools/fixture-library.js | 80 ++++ .../reports/tools/fixture-network.js | 138 ++++++ .../reports/tools/fixture-node-editor.js | 10 + .../reports/tools/fixture-scheduler.js | 86 ++++ .../reports/tools/fixture-sessions.js | 28 ++ .../reports/tools/fixture-settings.js | 161 +++++++ .../reports/tools/fixture.js | 23 + .../reports/tools/steps.json | 34 ++ 44 files changed, 3964 insertions(+) create mode 100644 docs/plans/workbench-redesign/execution-ledger.md create mode 100644 docs/plans/workbench-redesign/issues.md create mode 100644 docs/plans/workbench-redesign/plan.md create mode 100644 docs/plans/workbench-redesign/reports/evidence/01-scheduler-no-run.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/02-scheduler-failed-run.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/03-diagnostics.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/04-io-inspector.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/05-network.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/06-graph.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/07-node-editor.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/08-library.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/09-sessions.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/10-settings.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/11-io-after-paste.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/12-io-empty.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/13-diagnostics-empty.png create mode 100644 docs/plans/workbench-redesign/reports/evidence/14-picker-open.png create mode 100644 docs/plans/workbench-redesign/reports/m1-scheduler.md create mode 100644 docs/plans/workbench-redesign/reports/m2-diagnostics.md create mode 100644 docs/plans/workbench-redesign/reports/m3-io-inspector.md create mode 100644 docs/plans/workbench-redesign/reports/m4-network.md create mode 100644 docs/plans/workbench-redesign/reports/m5-graph.md create mode 100644 docs/plans/workbench-redesign/reports/m6-node-editor.md create mode 100644 docs/plans/workbench-redesign/reports/m7-library.md create mode 100644 docs/plans/workbench-redesign/reports/m8-sessions.md create mode 100644 docs/plans/workbench-redesign/reports/m9-e2e-harnesses.md create mode 100644 docs/plans/workbench-redesign/reports/m9-settings.md create mode 100644 docs/plans/workbench-redesign/reports/m9c-settings-panels.md create mode 100644 docs/plans/workbench-redesign/reports/m9d-graph-components.md create mode 100644 docs/plans/workbench-redesign/reports/page-agent-brief.md create mode 100644 docs/plans/workbench-redesign/reports/tools/README.md create mode 100644 docs/plans/workbench-redesign/reports/tools/cdp-init.cjs create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-diagnostics.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-graph.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-io.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-library.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-network.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-node-editor.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-scheduler.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-sessions.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture-settings.js create mode 100644 docs/plans/workbench-redesign/reports/tools/fixture.js create mode 100644 docs/plans/workbench-redesign/reports/tools/steps.json diff --git a/docs/plans/README.md b/docs/plans/README.md index 56b8370ad..99f15925c 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -3,6 +3,7 @@ | Plan | Status and purpose | | --- | --- | | [Domain architecture and multimodal workflows](domain-architecture-and-multimodal/plan.md) | Active; library-only Pumas RPC from an isolated pinned artifact, Pantograph-owned T/I/E inference, real desktop acceptance and current Coding-Standards MCP remediation. Revision 2 includes the current agent and baseline-selection policy. | +| [Workbench redesign](workbench-redesign/plan.md) | Active; replace the workbench GUI with the approved calm redesign (top tabs, shared run-context picker, eight redesigned tabs including a new Sessions tab) over existing projections. Independent write set from the RPC plan. | | [Current-standards remediation](current-standards-remediation/plan.md) | Superseded; pending claims remain mapped into the active plan. | | [Image-generation workflow](current-image-generation-graphs/plan.md) | Superseded; real image output is retained and extended to text and embeddings in the active plan. | | [Documentation consolidation](documentation-consolidation/plan.md) | Accepted historical cleanup and migration evidence. | diff --git a/docs/plans/workbench-redesign/execution-ledger.md b/docs/plans/workbench-redesign/execution-ledger.md new file mode 100644 index 000000000..3ec7a5c9a --- /dev/null +++ b/docs/plans/workbench-redesign/execution-ledger.md @@ -0,0 +1,409 @@ +# Execution ledger: workbench redesign + +Dated slice, verification, deviation and commit summaries. The plan owns +current state; this file owns history. + +## 2026-11-03 + +- Planning: mockups (rounds 1–3) reviewed with the owner on the Design canvas + and locally; direction E approved for every tab; run-context picker, + clipboard shortcuts and Graph run/edit modes added at the owner's request. + Mockup sources copied to `docs/design/mockups/`; spec written at + `docs/design/workbench-redesign-spec.md`; branch `feat/workbench-redesign` + created from `019caf4aa`. +- Standards: Coding-Standards checkout `5bce3110`; task facts routed through the + Standards Engine CLI (application purpose), snapshot + `snapshot:v1:58a8cb6f-8bc1-4f8b-9f84-caa364b3df2b`; closure recorded in the plan. +- M0 started: delegated to an Opus 5.5 agent with the write set in the plan. + +### M0 Foundation: implemented, verified, uncommitted (2026-11-03) + +What changed: + +- Tokens and base styles: `src/styles.css` now defines the spec palette as + `--pg-*` on `:root`, plus a few derived values taken from the mockup CSS + (`--pg-ink`, `--pg-text-quiet`, `--pg-text-code`, `--pg-border-idle`, + `--pg-border-danger`, `--pg-rule-log`, scrollbar thumbs). Body background is + `var(--pg-ground)` with the Atkinson Hyperlegible stack at 14px/1.45; themed + thin scrollbars and a 2px accent `:focus-visible` outline apply globally. + The `!important` neutral overrides and the radial-gradient body hacks are + deleted; one `!important` block for package graph components remains + (WR-008). The mockup primitives are ported value for value as `pg-*` + classes in `@layer components`. +- `tailwind.config.cjs`: `pg` colours keyed to the variables, font families + (serif Newsreader, sans Atkinson Hyperlegible, mono JetBrains Mono), and the + `neutral` scale retuned to the same greys (950 ground, 900 panel) so pages + not yet restyled sit on the new palette without overrides. +- `index.html`: title "Pantograph", `bg-neutral-950` body class removed. +- Dependency decision (fonts): requirement is offline-safe bundled fonts for + the desktop app. Installed `@fontsource/newsreader@5.3.0`, + `@fontsource/atkinson-hyperlegible@5.3.0`, `@fontsource/jetbrains-mono@5.3.0` + (all SIL OFL 1.1, `license: OFL-1.1` in the lockfile), nothing else + installed or upgraded (one lockfile `peer` flag npm dropped on an unrelated + entry was restored). Consumer: `@import` of weights 400/500 (Newsreader, + JetBrains Mono) and 400/700 (Atkinson) at the top of `src/styles.css`. + Verification: `vite build` emits 18 woff2 files plus woff fallbacks under + `dist/assets/` and the CSS references them. The first `npm install` timed + out (ETIMEDOUT); a retry with longer fetch timeouts succeeded, so WR-003 is + not the font fallback and system stacks are only the in-stack fallback. +- Shell: `WorkbenchShell.svelte` rewritten: brand word, three tab groups with + dividers (Sessions | Scheduler, Diagnostics, I/O Inspector, Network | Graph, + Node Editor, Library), run-context picker, engine line, Settings pinned + right, Assistant toggle (`aria-pressed`, drives the existing side panel via + `toggleSidePanel`). The header and pages pad right by `$panelWidth` so the + Assistant panel never covers them. Engine line reads the run-list query: + `transport_error` shows "Engine unreachable since HH:MM, showing last + projection" (or "nothing loaded yet") with Retry, and the page area dims to + 72%. Icon rail and "Active Run" label removed. `data-testid` + `workbench-nav-` kept for the e2e suite. +- Store: `workbenchStore.ts` gains `sessions` (first) and a `group` per page, + `WORKBENCH_TAB_GROUPS`, `workbenchPagesInGroup`; Scheduler stays default. + `SessionsPage.svelte` placeholder renders EmptyState "Sessions are coming in + Milestone 8." +- Run-context picker in `src/components/workbench/shell/`: `RunContextPicker.svelte`, + pure helpers `runContextPicker.ts`, run-list source `runContextRunList.ts` + (generation token; outcomes applied, failed, unreachable, superseded, + detached), clipboard controller `runContextClipboard.ts` (one delegated + `pointerover`, `pointerout` and `keydown` listener on `document`; second + attach throws; stale paste reads classified superseded), shared actions in + `runContextStore.ts` (`openRunContextPicker`, `closeRunContextPicker`, + `selectRunContext`, `clearRunContext`, `refreshRunContextRunList`, + `runContextRunList`, `runContextLiveUpdates`). Run list from + `workflowService.queryRunList({ limit: 250 })` only. +- Shared parts in `src/components/workbench/ui/` (exported from `index.ts`): + StatusGlyph (+ `statusGlyph.ts`), DimensionLine, Panel, GroupHeader, ListRow, + SegmentedControl, Chip, FilterChip, DeviceLanes, KeyValue, LogLine, ErrorCard, + TwoStepButton, EmptyState, Toast, plus `types.ts`. +- READMEs with the hook's headings: `src/components/workbench/`, `shell/`, + `ui/`, and (outside the literal write set, under WR-001, see WR-003) + `src/README.md` and `src/stores/README.md`. + +Verification (run from the repo root, all on the final tree): + +- `npm run typecheck`: pass. +- `npm run test:frontend`: pass, 574 tests, 0 failures (new: 5 glyph, 10 + picker helper, 7 run-list source, 8 clipboard, 2 store tests). +- `npx eslint --max-warnings 0` on every changed .ts/.svelte file and + `tailwind.config.cjs`: pass. +- `npm run lint:a11y`: fails only on pre-existing items in untouched files + (`IoInspectorPage.svelte:1024`, `RunGraphSnapshot.svelte:156`, + `SavedGraphInspectionSnapshot.svelte:77`); no finding in M0 files (WR-007). +- `npm run lint:critical`: fails only on pre-existing + `IoInspectorPage.svelte:508:20` `no-append-remove-child` (WR-007). +- `TRACEABILITY_BASE_REF=codex/pantograph-rpc-workflow-2026-09-26 ./scripts/check-decision-traceability.sh`: + exit 0, "No changed files detected" (HEAD equals the base; nothing is + committed). A scratch copy that reads the working-tree change list passes + "Decision traceability check passed."; the same copy without + `src/README.md` in the list fails as expected (WR-003). +- `npx vite build --outDir /tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/dist`: pass, no Svelte warnings. +- Headless screenshots of the built app (1440x900): + `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/shell.png` (plain browser: engine unreachable, Scheduler shows its + existing transport error), and with a scratch Tauri stand-in that answers + only `workflow_run_list_query`: `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/picker-open.png`, + `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/picker-copied.png`, `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/chip-selected.png`, `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/picker-unknown.png`, + `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/sessions.png`, `/tmp/claude-1000/-media-jeremy-OrangeCream-Linux-Software-repos-owned-ai-systems-Pantograph/26f5ffd8-b094-44e6-bf07-1b07d5fc8def/scratchpad/m0/diagnostics.png`. +- CDP walkthrough results: focus moves to the search field on open; groups + Running 2, Queued 3, Finished today 2; Ctrl+C over a hovered row copied the + id (headless denied the system clipboard, so the in-window fallback and its + toast were used, WR-010); Escape closed and returned focus to the chip; + Ctrl+V over the chip selected the copied run; `×` cleared it and focus + stayed on the chip; an unknown `run_` id showed "No run with id … in recent + history."; typing an exact id selected it and closed the popover; an outside + click closed it. + +Deviations and findings: WR-003 to WR-010 in `issues.md`. Device memory is +absent from the local network status projection (WR-006), so the plan's lanes +assumption resolves to its stop condition. +- M0 accepted by the integration owner after reviewing the shell and picker + screenshots; WR-003 READMEs kept and added to the write set; WR-009 + deviations accepted. Walkthrough tooling moved to `reports/tools/`. +- M1–M8 started in parallel (one Opus 5.5 agent per page, distinct scratch + directories, ports 8791–8798, CDP ports 9341–9348). Agents write + `reports/m-.md`; the integration owner merges them here. + +## 2026-11-03, page milestones (merged from reports/m*.md) + +### M1 Scheduler (report: reports/m1-scheduler.md) + +- M1 Scheduler implemented (Opus 5.5 agent, 2026-11-03). The Scheduler is rebuilt on the `Revised` board with the shared parts. It reads the shell's `runContextRunList` as its only run-list source and no longer queries `workflow_run_list_query` (WR-005). Grouping comes from the picker helpers, with no memory-wait group and delayed runs under Queued (WR-004). The device strip shows one muted sentence behind the `showLanes` preference (WR-006). +- The 14 filter selects moved into the Filters disclosure with applied-filter chips. The status segment and search stay outside it. +- Every action is still reachable: Move to front, Priority/Set and two-step Cancel run in the footer; Resume and GUI admin (two-step Admin cancel, Front, Priority/Set) under More actions. Each has its existing guard, and a disabled control has a title explaining why. +- Gates: typecheck pass; test:frontend 685/685; lint:a11y pass; lint:critical pass; eslint pass on the changed files; vite build pass. The traceability hook says "No changed files" (WR-003). A scratch copy run on the M1 file list needs the `src/components/workbench/README.md` and `src/stores/README.md` updates listed in the M1 report. +- CDP walkthrough with `fixture-scheduler.js`: one run-list query with Scheduler open, selection follows the chip, cancel arms then confirms, 14 disclosure selects, the page does not scroll. Screenshots are in `scratchpad/m1/`. + +### M2 Diagnostics (report: reports/m2-diagnostics.md) + +> **2026-11-03, M2 Diagnostics (Opus 5.5 agent).** +> +> `DiagnosticsPage.svelte` now follows the `Diagnostics` board, built from the shared parts: +> +> - `DimensionLine`, a 300px `Panel` "Run facts", `Chip`, `KeyValue`, `GroupHeader`, `FilterChip`, `SegmentedControl`, `ErrorCard`, `LogLine` and `EmptyState`. +> - Timing, Placement, Retention, More facts and Projection key-value blocks hold all 27 run-detail facts and all 5 projection cursors. +> - The six execution selects and the 14 comparison selects plus 2 date inputs moved into `Filters` disclosures with applied-filter chips and quick presets. +> - Node errors are log lines with the failed glyph. A compact table lists only node errors that are missing from the timeline. +> - The ErrorCard explanation and "Try:" advice come from `explainDiagnosticsError`: a known-code table with a neutral fallback that restates the message. +> - The `diagnosticsFocus` deep link switches the level filter, selects the line and scrolls it into view, once per request. +> - Transport and subscription failures are muted sentences inside the panel. +> - Service calls are unchanged, and there are no ledger reads. +> +> Gates: +> +> - typecheck, 685/685 frontend tests, lint:a11y, lint:critical, eslint on the 3 files and vite build all pass. +> - Traceability passes with `src/components/workbench/README.md` in the same change. +> - Headless CDP walkthrough with `reports/tools/fixture-diagnostics.js`. Screenshots in the M2 scratch directory: empty, failed, show-in-log, filters, more facts, nodes, running, unavailable. + +### M3 I/O Inspector (report: reports/m3-io-inspector.md) + +### M3 I/O Inspector: implemented, verified, uncommitted (2026-11-03) + +- **Board:** `IoInspectorPage.svelte` is rebuilt to the IoInspector board. + - Dimension line with run id, node and artifact counts, kept bytes and projection freshness (`data-run-id`). + - A 340px node and port tree built from the run snapshot nodes, node statuses and resolved node I/O joined with the artifact projection. Artifacts with no resolved row fall back to producer/consumer metadata, and node-less artifacts go under a "Workflow boundary" group. + - Direction segment, search, a Filters disclosure holding the Backend filter, and retention chips. + - A one-artifact detail panel: title `node:port`, chips, Read body / Read stream / Download / Acknowledge with unchanged service semantics, full-image preview, bounded 64 KiB text preview, binary-body message, metadata-only panel, and the three descriptor sections. +- **Stale graph facts:** muted ErrorCard-shaped cards inside the node they concern. +- **Saved-graph inspection:** moved into an "Inspect a saved workflow instead" disclosure under the no-run EmptyState. The select, the stable-ids note and the restyled `SavedGraphInspectionSnapshot` (native button nodes) are kept. +- **Graph strip:** the compact run graph strip (`RunGraphSnapshot`) is removed from this page. +- **WR-007 resolved for M3's files:** + - declarative download anchor, with one owner for the revoke timers; + - `
+ + {#if draftView.outputs.length} +
+

Outputs

+
    + {#each draftView.outputs as output (output.id)} +
  • {output.label}
  • + {/each} +
+

Filled when the saved workflow runs from Scheduler.

+
+ {/if} + {:else} +
+ +
+ {/if} + + {#snippet footer()} +
+ {#if view.draft} +
{ event.preventDefault(); act('save', () => controller.save(name)); }}> + + +
+ {:else} + Saved workflows run from Scheduler. + {/if} +

{view.busy ? 'Working…' : view.notice}

+
+ {/snippet} + +
+ +
+ + {#snippet top()} +
+

On the canvas

+ preview +
+ {/snippet} + + {#if selected} +
+
+
+ + + {selected.label} + {selected.identity.node_type} + +
+
+
+ {#each selected.inputs as port (port.id)} +
{port.label}
+ {/each} +
+
+ {#each selected.outputs as port (port.id)} +
{port.label}
+ {/each} +
+
+
+
+

{selected.description}

+ {:else} +

No admitted node to preview.

+ {/if} + +
+

Checks

+ {#if view.draft} +
    + {#each checks as check, index (index)} +
  • {check.text}
  • + {/each} +
+ {:else} +

Checks run on the open workflow draft.

+ {/if} +
+ + {#if selected} +
+ Implementation identity +
- - - {/each} - - {/if} -
{ event.preventDefault(); void controller.reopen(path); }}> - - -
- {#if view.savedPath}

Saved: {view.savedPath}

{/if} - {#if view.draft} -
-

Workflow draft

-

{view.draft.graph.nodes.length} nodes · {view.draft.graph.edges.length} connections. Saving preserves the selected implementation identity. Run saved workflows from Scheduler.

- {#if view.draft.graph_diagnostics.length} -
    - {#each view.draft.graph_diagnostics as diagnostic, index (index)} -
  • {diagnostic.blocking_submission ? 'Blocks execution: ' : ''}{diagnostic.message}
  • - {/each} -
- {:else}

Graph contract valid

{/if} - {#each view.draft.graph.nodes.filter(node => node.node_type === 'text-input') as node (node.id)} -
{ event.preventDefault(); const input = new FormData(event.currentTarget).get('text'); if (typeof input === 'string') void controller.update(node, input); }}> - - -
- {/each} -
{ event.preventDefault(); void controller.save(name); }}> - - -
+ {/if} + +
+

Sessions

+ {#if errorRegion === 'sessions'} + {@render errorLine()} + {/if} + {#if view.pendingCleanup} + + + {:else} +

No earlier NodeLab sessions are waiting to close.

+ {/if} +
+ +
+

Authoring on this host

+ +
+
- {/if} +
+ + diff --git a/src/components/workbench/nodeLabPresenters.test.ts b/src/components/workbench/nodeLabPresenters.test.ts index c279c61d0..4aea1bbe2 100644 --- a/src/components/workbench/nodeLabPresenters.test.ts +++ b/src/components/workbench/nodeLabPresenters.test.ts @@ -1,6 +1,20 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { buildNodeLabStatusRows, nodeLabTrustMessage } from './nodeLabPresenters.ts'; +import type { CustomNodeAuthoringEntry, NodeLabDraft } from '../../services/workflow/customNodeAuthoring.ts'; +import type { NodeLabView } from './nodeLabController.ts'; +import { + buildNodeLabCatalogRows, + buildNodeLabChecks, + buildNodeLabIdentityRows, + buildNodeLabStatusRows, + nodeLabDraftPlaceholder, + nodeLabErrorRegion, + nodeLabShowsSearch, + nodeLabSummaryLine, + nodeLabTrustMessage, + projectNodeLabDraft, + resolveNodeLabSelection, +} from './nodeLabPresenters.ts'; test('NodeLab distinguishes admitted graph authoring from unsupported code publishing', () => { assert.match(nodeLabTrustMessage(), /trusted in-process/); @@ -11,3 +25,129 @@ test('NodeLab distinguishes admitted graph authoring from unsupported code publi { label: 'Runtime Publishing', value: 'Unsupported' }, ]); }); + +const identity = (nodeType: string) => ({ + node_type: nodeType, + contract_version: '1.0.0', + contract_digest: `contract-blake3:${'c'.repeat(64)}`, + implementation_digest: `blake3:${'a'.repeat(64)}`, + environment_digest: `blake3:${'b'.repeat(64)}`, + adapter_version: 1 as const, +}); +const entry = (nodeType: string, label: string, description = 'Host transform'): CustomNodeAuthoringEntry => ({ + identity: identity(nodeType), + label, + description, + trust: 'trusted_in_process', + inputs: [{ id: 'input', label: 'Input' }], + outputs: [{ id: 'output', label: 'Output' }, { id: 'count', label: 'Count' }], +}); +const upper = entry('host-uppercase', 'Host uppercase'); +const lower = entry('host-lowercase', 'Host lowercase', 'Folds text to lower case'); +const draft = (diagnostics: NodeLabDraft['graph_diagnostics'] = []): NodeLabDraft => ({ + session_id: 'edit-1', + graph_revision: 'r1', + graph: { + nodes: [ + { id: 'custom', node_type: 'host-uppercase', position: { x: 320, y: 0 }, data: { label: 'Host uppercase', custom_node_identity: identity('host-uppercase') } }, + { id: 'input-0', node_type: 'text-input', position: { x: 0, y: 0 }, data: { label: 'Input', text: 'hello' } }, + { id: 'input-1', node_type: 'text-input', position: { x: 0, y: 160 }, data: {} }, + { id: 'output-0', node_type: 'text-output', position: { x: 640, y: 0 }, data: { label: 'Output', text: '' } }, + ], + edges: [ + { id: 'edge-input-0', source: 'input-0', source_handle: 'text', target: 'custom', target_handle: 'input' }, + { id: 'edge-output-0', source: 'custom', source_handle: 'output', target: 'output-0', target_handle: 'text' }, + ], + }, + graph_diagnostics: diagnostics, +}); +const view = (patch: Partial): NodeLabView => ({ catalog: null, draft: null, savedPath: '', busy: false, error: null, notice: '', pendingCleanup: 0, ...patch }); + +test('catalog rows filter by label, type and description and mark the node the draft uses', () => { + const all = buildNodeLabCatalogRows([upper, lower], draft(), ''); + assert.deepEqual(all.rows.map(row => [row.nodeType, row.glyph, row.time]), [ + ['host-uppercase', 'succeeded', 'in draft'], + ['host-lowercase', 'idle', ''], + ]); + assert.equal(all.rows[0].statusLabel, '1 string input, 2 string outputs'); + assert.equal(all.rows[0].title, '1 string input, 2 string outputs. Trusted in-process, used by the open draft. Host transform'); + assert.equal(all.rows[1].title, '1 string input, 2 string outputs. Trusted in-process. Folds text to lower case'); + assert.equal(all.rows[1].detail, 'Folds text to lower case'); + assert.deepEqual([all.matched, all.total], [2, 2]); + assert.deepEqual(buildNodeLabCatalogRows([upper, lower], null, 'LOWER CASE').rows.map(row => row.nodeType), ['host-lowercase']); + assert.deepEqual(buildNodeLabCatalogRows([upper, lower], null, ' host-upper ').rows.map(row => row.nodeType), ['host-uppercase']); + const none = buildNodeLabCatalogRows([upper, lower], null, 'zebra'); + assert.deepEqual([none.rows.length, none.matched, none.total], [0, 0, 2]); + assert.deepEqual(buildNodeLabCatalogRows(null, null, ''), { rows: [], matched: 0, total: 0 }); +}); + +test('search appears only for a catalog long enough to need it', () => { + assert.equal(nodeLabShowsSearch(null), false); + assert.equal(nodeLabShowsSearch([upper]), false); + assert.equal(nodeLabShowsSearch(Array.from({ length: 6 }, (_, index) => entry(`node-${index}`, `Node ${index}`))), true); +}); + +test('selection prefers the picked row, then the draft node, then the first row, and never a missing node', () => { + assert.equal(resolveNodeLabSelection(null, 'host-uppercase', null), null); + assert.equal(resolveNodeLabSelection([], null, draft()), null); + assert.equal(resolveNodeLabSelection([lower, upper], 'host-lowercase', draft()), lower); + assert.equal(resolveNodeLabSelection([lower, upper], null, draft()), upper); + assert.equal(resolveNodeLabSelection([lower, upper], 'gone', null), lower); +}); + +test('identity rows show every pinned identity field in mono', () => { + const rows = buildNodeLabIdentityRows(upper); + assert.deepEqual(rows.map(row => row.key), ['Node type', 'Contract version', 'Contract digest', 'Implementation', 'Environment', 'Adapter', 'Trust']); + assert.equal(rows[1].value, '1.0.0'); + assert.equal(rows[2].value, `contract-blake3:${'c'.repeat(64)}`); + assert.equal(rows[3].value, `blake3:${'a'.repeat(64)}`); + assert.equal(rows[4].value, `blake3:${'b'.repeat(64)}`); + assert.equal(rows[5].value, 'v1'); + assert.ok(rows.slice(0, 6).every(row => row.mono)); +}); + +test('draft projection lists text sources with their editable value, outputs and the pinned node', () => { + const projection = projectNodeLabDraft(draft()); + assert.equal(projection.countsText, '4 nodes · 2 connections'); + assert.deepEqual(projection.customNodes, [{ id: 'custom', label: 'Host uppercase', nodeType: 'host-uppercase' }]); + assert.deepEqual(projection.sources.map(source => [source.node.id, source.label, source.text]), [['input-0', 'Input', 'hello'], ['input-1', 'input-1', '']]); + assert.deepEqual(projection.outputs, [{ id: 'output-0', label: 'Output' }]); +}); + +test('checks say the contract is valid or prefix blocking diagnostics', () => { + assert.deepEqual(buildNodeLabChecks(draft()), [{ glyph: 'succeeded', text: 'Graph contract valid' }]); + assert.deepEqual(buildNodeLabChecks(draft([ + { message: 'host-uppercase is unavailable', blocking_submission: true }, + { message: 'Output is not connected', blocking_submission: false }, + ])), [ + { glyph: 'failed', text: 'Blocks execution: host-uppercase is unavailable' }, + { glyph: 'warn', text: 'Output is not connected' }, + ]); +}); + +test('summary line separates loading, failure and empty catalogs and describes the draft', () => { + assert.equal(nodeLabSummaryLine(view({ busy: true })), 'Loading admitted nodes · no draft open'); + assert.equal(nodeLabSummaryLine(view({ error: 'Qualification host unavailable' })), 'Admitted nodes unavailable · no draft open'); + assert.equal(nodeLabSummaryLine(view({ catalog: [] })), 'No admitted nodes on this host · no draft open'); + assert.equal(nodeLabSummaryLine(view({ catalog: [upper], draft: draft() })), '1 admitted node · draft of 4 nodes, contract valid'); + assert.equal( + nodeLabSummaryLine(view({ catalog: [upper, lower], draft: draft([{ message: 'x', blocking_submission: true }]), savedPath: '.pantograph/workflows/a.json' })), + '2 admitted nodes · draft of 4 nodes, 1 blocking check, saved', + ); +}); + +test('the empty-catalog placeholder keeps the admission wording; otherwise it points at both ways in', () => { + assert.equal(nodeLabDraftPlaceholder([]).question, 'This host has no admitted custom nodes.'); + assert.match(nodeLabDraftPlaceholder([]).sentence, /^A host maintainer must register a trusted implementation before creating a new draft\./); + assert.equal(nodeLabDraftPlaceholder(null).question, 'No workflow draft is open.'); + assert.equal(nodeLabDraftPlaceholder([upper]).question, 'No workflow draft is open.'); +}); + +test('errors are placed next to the control whose action raised them', () => { + assert.equal(nodeLabErrorRegion('loadCatalog'), 'catalog'); + assert.equal(nodeLabErrorRegion('create'), 'catalog'); + assert.equal(nodeLabErrorRegion('reopen'), 'draft'); + assert.equal(nodeLabErrorRegion('update'), 'draft'); + assert.equal(nodeLabErrorRegion('save'), 'draft'); + assert.equal(nodeLabErrorRegion('retryCleanup'), 'sessions'); +}); diff --git a/src/components/workbench/nodeLabPresenters.ts b/src/components/workbench/nodeLabPresenters.ts index abea6cb53..093680163 100644 --- a/src/components/workbench/nodeLabPresenters.ts +++ b/src/components/workbench/nodeLabPresenters.ts @@ -1,3 +1,12 @@ +// Pure projections for the Node Editor (NodeLab) page. Data authority stays in +// nodeLabController.ts and services/workflow/customNodeAuthoring.ts; these +// functions only shape the controller's view for the redesign's layout. +import type { CustomNodeAuthoringEntry, NodeLabDraft } from '../../services/workflow/customNodeAuthoring.ts'; +import type { GraphNode } from '../../services/workflow/types.ts'; +import type { NodeLabView } from './nodeLabController.ts'; +import type { GlyphState } from './ui/statusGlyph.ts'; +import type { KeyValueRow } from './ui/types.ts'; + export interface NodeLabStatusRow { label: string; value: string } export function buildNodeLabStatusRows(): NodeLabStatusRow[] { return [ @@ -9,3 +18,170 @@ export function buildNodeLabStatusRows(): NodeLabStatusRow[] { export function nodeLabTrustMessage(): string { return 'These nodes are supplied by this host and run as trusted in-process code. NodeLab creates workflows; it cannot install or publish code.'; } + +/** The search field appears only once the list is long enough to need it. */ +export const NODE_LAB_SEARCH_MIN_ENTRIES = 6; +export function nodeLabShowsSearch(catalog: CustomNodeAuthoringEntry[] | null): boolean { + return (catalog?.length ?? 0) >= NODE_LAB_SEARCH_MIN_ENTRIES; +} + +function plural(count: number, one: string, many: string): string { + return `${count} ${count === 1 ? one : many}`; +} + +/** Node types of the custom (pinned) nodes in a draft graph. */ +function draftCustomNodes(draft: NodeLabDraft | null): GraphNode[] { + if (!draft) return []; + return draft.graph.nodes.filter(node => { + const identity = node.data.custom_node_identity; + return identity !== null && typeof identity === 'object'; + }); +} + +function nodeLabel(node: GraphNode): string { + return typeof node.data.label === 'string' ? node.data.label : node.id; +} + +export interface NodeLabCatalogRow { + entry: CustomNodeAuthoringEntry; + nodeType: string; + label: string; + glyph: GlyphState; + /** Port summary, the first sub-line. */ + statusLabel: string; + /** The description, the second sub-line. */ + detail: string; + /** Right-hand marker: "in draft" for the nodes the open draft pins. */ + time: string; + title: string; +} +export interface NodeLabCatalogList { rows: NodeLabCatalogRow[]; matched: number; total: number } + +/** Filters by label, node type and description; marks the nodes the open draft uses. */ +export function buildNodeLabCatalogRows( + catalog: CustomNodeAuthoringEntry[] | null, + draft: NodeLabDraft | null, + query: string, +): NodeLabCatalogList { + const entries = catalog ?? []; + const needle = query.trim().toLowerCase(); + const inDraft = new Set(draftCustomNodes(draft).map(node => node.node_type)); + const rows = entries + .filter(entry => !needle || [entry.label, entry.identity.node_type, entry.description].some(text => text.toLowerCase().includes(needle))) + .map(entry => { + const used = inDraft.has(entry.identity.node_type); + const ports = `${plural(entry.inputs.length, 'string input', 'string inputs')}, ${plural(entry.outputs.length, 'string output', 'string outputs')}`; + return { + entry, + nodeType: entry.identity.node_type, + label: entry.label, + glyph: (used ? 'succeeded' : 'idle') as GlyphState, + statusLabel: ports, + detail: entry.description, + time: used ? 'in draft' : '', + title: `${ports}. Trusted in-process${used ? ', used by the open draft' : ''}. ${entry.description}`, + }; + }); + return { rows, matched: rows.length, total: entries.length }; +} + +/** + * The admitted node the right panel previews: the row the user picked, else + * the node the open draft uses, else the first one. Resolved against the whole + * catalog, so a search that hides the row keeps it; a node the catalog no + * longer lists is dropped. + */ +export function resolveNodeLabSelection( + catalog: CustomNodeAuthoringEntry[] | null, + selectedNodeType: string | null, + draft: NodeLabDraft | null, +): CustomNodeAuthoringEntry | null { + if (!catalog?.length) return null; + const byType = (type: string | null | undefined) => (type ? catalog.find(entry => entry.identity.node_type === type) : undefined); + return byType(selectedNodeType) ?? byType(draftCustomNodes(draft)[0]?.node_type) ?? catalog[0]; +} + +export function buildNodeLabIdentityRows(entry: CustomNodeAuthoringEntry): KeyValueRow[] { + const { identity } = entry; + return [ + { key: 'Node type', value: identity.node_type, mono: true }, + { key: 'Contract version', value: identity.contract_version, mono: true }, + { key: 'Contract digest', value: identity.contract_digest, mono: true }, + { key: 'Implementation', value: identity.implementation_digest, mono: true }, + { key: 'Environment', value: identity.environment_digest, mono: true }, + { key: 'Adapter', value: `v${identity.adapter_version}`, mono: true }, + { key: 'Trust', value: 'Trusted in-process' }, + ]; +} + +export interface NodeLabDraftSource { node: GraphNode; label: string; text: string } +export interface NodeLabDraftProjection { + countsText: string; + customNodes: { id: string; label: string; nodeType: string }[]; + sources: NodeLabDraftSource[]; + outputs: { id: string; label: string }[]; +} +export function projectNodeLabDraft(draft: NodeLabDraft): NodeLabDraftProjection { + return { + countsText: `${plural(draft.graph.nodes.length, 'node', 'nodes')} · ${plural(draft.graph.edges.length, 'connection', 'connections')}`, + customNodes: draftCustomNodes(draft).map(node => ({ id: node.id, label: nodeLabel(node), nodeType: node.node_type })), + sources: draft.graph.nodes + .filter(node => node.node_type === 'text-input') + .map(node => ({ node, label: nodeLabel(node), text: typeof node.data.text === 'string' ? node.data.text : '' })), + outputs: draft.graph.nodes + .filter(node => node.node_type === 'text-output') + .map(node => ({ id: node.id, label: nodeLabel(node) })), + }; +} + +export interface NodeLabCheck { glyph: GlyphState; text: string } +/** Contract validity of the open draft, in the words #95 uses. */ +export function buildNodeLabChecks(draft: NodeLabDraft): NodeLabCheck[] { + if (!draft.graph_diagnostics.length) return [{ glyph: 'succeeded', text: 'Graph contract valid' }]; + return draft.graph_diagnostics.map(diagnostic => ({ + glyph: diagnostic.blocking_submission ? 'failed' : 'warn', + text: `${diagnostic.blocking_submission ? 'Blocks execution: ' : ''}${diagnostic.message}`, + })); +} + +/** Page summary for the dimension line: catalog state, then draft state. */ +export function nodeLabSummaryLine(view: NodeLabView): string { + let catalog: string; + if (view.catalog === null) catalog = view.error && !view.busy ? 'Admitted nodes unavailable' : 'Loading admitted nodes'; + else if (view.catalog.length === 0) catalog = 'No admitted nodes on this host'; + else catalog = plural(view.catalog.length, 'admitted node', 'admitted nodes'); + if (!view.draft) return `${catalog} · no draft open`; + const blocking = view.draft.graph_diagnostics.filter(item => item.blocking_submission).length; + const parts = [`draft of ${plural(view.draft.graph.nodes.length, 'node', 'nodes')}`]; + parts.push(blocking ? plural(blocking, 'blocking check', 'blocking checks') : 'contract valid'); + if (view.savedPath) parts.push('saved'); + return `${catalog} · ${parts.join(', ')}`; +} + +export interface NodeLabPlaceholder { question: string; sentence: string } +/** Centre panel text while no draft is open. */ +export function nodeLabDraftPlaceholder(catalog: CustomNodeAuthoringEntry[] | null): NodeLabPlaceholder { + if (catalog && catalog.length === 0) { + return { + question: 'This host has no admitted custom nodes.', + sentence: 'A host maintainer must register a trusted implementation before creating a new draft. You can still reopen a saved workflow above.', + }; + } + return { + question: 'No workflow draft is open.', + sentence: 'Create a draft from an admitted node on the left, or reopen a saved workflow above.', + }; +} + +export type NodeLabAction = 'loadCatalog' | 'create' | 'reopen' | 'update' | 'save' | 'retryCleanup'; +export type NodeLabRegion = 'catalog' | 'draft' | 'sessions'; +/** The controller keeps one error; the page shows it next to the control that caused it. */ +export function nodeLabErrorRegion(action: NodeLabAction): NodeLabRegion { + if (action === 'loadCatalog' || action === 'create') return 'catalog'; + if (action === 'retryCleanup') return 'sessions'; + return 'draft'; +} + +export function nodeLabCleanupMessage(pending: number): string { + return `${pending} previous NodeLab sessions could not be closed. Close them before creating or reopening a draft.`; +}