From 3394695fb962ea5cc71a5a1dfc7f62bcbb0d608f Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Wed, 23 Sep 2026 08:51:29 +0000 Subject: [PATCH] Replay a recorded delta back into the interface without recording it again --- .../document/storage_tests/metadata_tests.rs | 15 ++ .../utility_types/network_interface.rs | 1 + .../utility_types/network_interface/apply.rs | 131 ++++++++++++++++++ .../network_interface/editor_delta_tests.rs | 95 ++++++++++++- .../utility_types/network_interface/store.rs | 43 ++++++ .../messages/portfolio/document_migration.rs | 5 + 6 files changed, 284 insertions(+), 6 deletions(-) create mode 100644 editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs diff --git a/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs b/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs index 718a6d1e6c..fb761de116 100644 --- a/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs @@ -273,6 +273,21 @@ fn rebuilt_interface_keeps_storage_identities() { assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities"); } +/// Opening an old document runs its upgrades through the ordinary mutators, so the store records them. +/// Those recordings are the document arriving rather than edits to it, so the migration has to leave +/// the buffer empty instead of handing the first commit a pile of changes to the document's own +/// starting state. +#[test] +fn migrating_a_document_records_no_changes() { + let mut document = load_demo("painted-dreams.graphite"); + document.network_interface.discard_deltas(); + + crate::messages::portfolio::document_migration::document_migration_upgrades(&mut document, false); + + let recorded = document.network_interface.take_deltas(); + assert!(recorded.is_empty(), "migration left {} recorded changes behind", recorded.len()); +} + /// Previewing and the pinned display order are document state, so they survive a registry round trip /// rather than living in `session.json`. Both name nodes, and the stored form uses storage IDs, so /// this also checks the reference resolves back to the right runtime node. diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface.rs b/editor/src/messages/portfolio/document/utility_types/network_interface.rs index d2cc9c3fbd..d6356f9602 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -1,3 +1,4 @@ +mod apply; mod caches; #[cfg(test)] mod characterization_tests; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs new file mode 100644 index 0000000000..ff83935c81 --- /dev/null +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs @@ -0,0 +1,131 @@ +use super::*; +use graph_craft::runtime_delta::RuntimeDelta; + +// Replay: putting a delta back into the interface, the inverse of the store recording one. +// +// Mechanism only. A mutator decides policy, validates, and lays nodes out, then records what it +// settled on; replaying reproduces that outcome rather than deciding it again. A peer running +// different layout rules must still end up with the state the delta describes. +impl NodeNetworkInterface { + /// Mirrors a delta into the interface without recording it. + /// + /// A delta reaching here came from somewhere else, so recording it would offer a change this peer + /// never made back to whoever sent it. Writing through the store and then dropping what the store + /// recorded keeps the two parallel trees written by one place, which is the property the store + /// exists for, without the echo. + #[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))] + pub(crate) fn apply(&mut self, delta: &EditorDelta) { + let recorded = self.deltas.len(); + self.mirror(delta); + self.deltas.truncate(recorded); + } + + fn mirror(&mut self, delta: &EditorDelta) { + match delta { + // The metadata arrives separately, so a node lands with default metadata that the paired + // snapshot then fills in. Replacing an entry and adding one are the same write here; they + // differ only in what the storage side has to remove first. + EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => { + let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default()); + self.insert_node_entry(NodeLocator::new(*node_id, network_path), template); + } + + EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => { + self.remove_node_entry(NodeLocator::new(*node_id, network_path)); + } + + EditorDelta::Graph(RuntimeDelta::SetInput { + network_path, + node_id, + input_index, + input, + }) => { + self.set_input_slot(&InputConnector::node_at_index(*node_id, *input_index), network_path, input.clone()); + } + + EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => { + let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return }; + + // The slots are what changed; their metadata follows in the paired delta. Resizing keeps the + // two arrays the same length in the meantime, which the rest of the interface assumes. + let mut input_metadata = node.input_metadata().to_vec(); + input_metadata.resize(inputs.len(), InputMetadata::default()); + node.replace_inputs(inputs.clone(), input_metadata); + } + + EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => match input { + None => { + self.remove_export_slot(network_path, *export_index); + } + // A peer can name a slot past the end of this network's exports, which is an insert here + // rather than a write to a slot that does not exist yet. + Some(input) if *export_index >= self.number_of_exports(network_path) => { + self.insert_export_slot(network_path, *export_index, input.clone(), String::new()); + } + Some(input) => { + self.set_input_slot(&InputConnector::Export(*export_index), network_path, input.clone()); + } + }, + + EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => { + if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { + node.set_visible(*visible); + } + } + + EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => { + if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { + node.set_call_argument(call_argument.clone()); + } + } + + EditorDelta::Graph(RuntimeDelta::SetContextFeatures { + network_path, + node_id, + context_features, + }) => { + if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { + node.set_context_features(*context_features); + } + } + + EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => { + if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { + node.replace_metadata((**metadata).clone()); + } + } + + EditorDelta::NodeInputMetadata { + network_path, + node_id, + input_metadata, + } => { + if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { + node.set_input_metadata(input_metadata.clone()); + } + } + + EditorDelta::NodeMetadata { network_path, node_id, change } => { + let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return }; + match change { + NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()), + NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()), + NodeMetadataChange::Locked(locked) => node.set_locked(*locked), + NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned), + NodeMetadataChange::OutputNames(output_names) => node.set_output_names(output_names.clone()), + NodeMetadataChange::InputName { index, name } => node.set_input_name(*index, name.clone()), + NodeMetadataChange::WidgetOverride { index, widget_override } => node.set_widget_override(*index, widget_override.clone()), + }; + } + + EditorDelta::NetworkMetadata { network_path, change } => { + let Some(mut network) = self.network_mut(network_path) else { return }; + match change { + NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()), + NetworkMetadataChange::Previewing(previewing) => network.set_previewing(*previewing), + NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()), + }; + } + } + } +} diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs index 2a06327f49..5f19318ff4 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs @@ -237,7 +237,7 @@ async fn emitted_deltas_reproduce_the_diff() { let node = editor.create_node_by_name(rectangle_definition()).await; let working = convert(&editor); - editor.active_document_mut().network_interface.take_deltas(); + editor.active_document_mut().network_interface.discard_deltas(); { let network_interface = &mut editor.active_document_mut().network_interface; @@ -265,7 +265,7 @@ async fn unchanged_writes_emit_nothing() { let node = editor.create_node_by_name(rectangle_definition()).await; editor.active_document_mut().network_interface.set_display_name(&node, "Named".to_string(), &[]); - editor.active_document_mut().network_interface.take_deltas(); + editor.active_document_mut().network_interface.discard_deltas(); { let network_interface = &mut editor.active_document_mut().network_interface; @@ -286,7 +286,7 @@ async fn emitted_deltas_reproduce_the_diff_for_structural_edits() { editor.new_document().await; let working = convert(&editor); - editor.active_document_mut().network_interface.take_deltas(); + editor.active_document_mut().network_interface.discard_deltas(); let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition()) .expect("rectangle definition") @@ -300,7 +300,7 @@ async fn emitted_deltas_reproduce_the_diff_for_structural_edits() { assert_same_stored_effect(&working, constructed, diffed, "emitted node insertion"); let working = convert(&editor); - editor.active_document_mut().network_interface.take_deltas(); + editor.active_document_mut().network_interface.discard_deltas(); editor.active_document_mut().network_interface.delete_nodes(vec![node_id], true, &[]); let emitted = editor.active_document_mut().network_interface.take_deltas(); @@ -333,7 +333,7 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() { .expect("the group should be a network node"); let working = convert(&editor); - editor.active_document_mut().network_interface.take_deltas(); + editor.active_document_mut().network_interface.discard_deltas(); editor .active_document_mut() @@ -373,7 +373,7 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() { .expect("the group should be a network node"); let working = convert(&editor); - editor.active_document_mut().network_interface.take_deltas(); + editor.active_document_mut().network_interface.discard_deltas(); editor.active_document_mut().network_interface.set_display_name(&group, "Renamed".to_string(), &[]); editor @@ -387,6 +387,89 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() { assert_same_stored_effect(&working, constructed, diffed, "rename then arity change"); } +/// The gate replay exists for: what the store recorded has to be enough to reproduce the write that +/// produced it. Clone the interface before an edit, apply what the edit recorded onto the clone, and +/// the two should agree. Something the store failed to record, or recorded wrongly, surfaces here +/// rather than as drift on another peer. +async fn assert_replay_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + editor + .handle_message(DocumentMessage::GroupSelectedLayers { + group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer, + }) + .await; + editor.active_document_mut().network_interface.discard_deltas(); + + let before = editor.active_document().network_interface.clone(); + edit(&mut editor); + + let recorded = editor.active_document_mut().network_interface.take_deltas(); + assert!(!recorded.is_empty(), "the edit should have recorded something to replay"); + + let mut replayed = before; + for delta in &recorded { + replayed.apply(delta); + } + + assert_eq!( + replayed, + editor.active_document().network_interface, + "replaying {} recorded deltas did not reproduce the edited interface", + recorded.len() + ); +} + +fn only_group(editor: &EditorTestUtils) -> NodeId { + editor + .active_document() + .network_interface + .document_network() + .nodes + .iter() + .find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_))) + .map(|(id, _)| *id) + .expect("the group should be a network node") +} + +#[tokio::test] +async fn replaying_metadata_edits_reproduces_the_interface() { + assert_replay_reproduces(|editor| { + let group = only_group(editor); + let network_interface = &mut editor.active_document_mut().network_interface; + network_interface.set_display_name(&group, "Renamed".to_string(), &[]); + network_interface.set_locked(&group, &[], true); + network_interface.set_pinned(&group, &[], true); + network_interface.set_visibility(&group, &[], false); + network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]); + }) + .await; +} + +#[tokio::test] +async fn replaying_an_arity_change_reproduces_the_interface() { + assert_replay_reproduces(|editor| { + let group = only_group(editor); + editor + .active_document_mut() + .network_interface + .add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]); + }) + .await; +} + +#[tokio::test] +async fn replaying_a_node_insertion_reproduces_the_interface() { + assert_replay_reproduces(|editor| { + let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition()) + .expect("rectangle definition") + .default_node_template(); + editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]); + }) + .await; +} + #[tokio::test] async fn removing_a_nested_network_node_matches_the_diff() { let mut editor = EditorTestUtils::create(); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs index 1b6afca02a..eb7e04d303 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs @@ -273,6 +273,25 @@ impl NodeMut<'_> { changed } + /// The encapsulating node's names for every one of the network's exports, replaced together since + /// they are stored as one array. + #[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))] + pub(crate) fn set_output_names(&mut self, output_names: Vec) -> bool { + let changed = self.metadata.output_names != output_names; + self.metadata.output_names = output_names; + if changed { + let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone()); + self.deltas.metadata(change); + } + changed + } + + /// The metadata array the node's inputs index, one entry per input. + #[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))] + pub(crate) fn input_metadata(&self) -> &[InputMetadata] { + &self.metadata.input_metadata + } + /// Grows `output_names` to one entry per export, which an older document may be missing. pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) { if self.metadata.output_names.len() == number_of_exports { @@ -314,6 +333,23 @@ impl NodeMut<'_> { self.deltas.snapshot(metadata); } + /// Replaces the node's whole persistent metadata, including that of everything nested under it, + /// which is the write a metadata snapshot describes. + #[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))] + pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) { + *self.metadata = metadata; + + let snapshot = Box::new(self.metadata.clone()); + self.deltas.snapshot(snapshot); + } + + /// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone. + #[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))] + pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec) { + self.metadata.input_metadata = input_metadata; + self.emit_input_metadata(); + } + /// Swaps in new inputs together with their metadata, returning the inputs replaced. pub(crate) fn replace_inputs(&mut self, inputs: Vec, input_metadata: Vec) -> Vec { self.metadata.input_metadata = input_metadata; @@ -720,6 +756,13 @@ impl NodeNetworkInterface { std::mem::take(&mut self.deltas) } + /// Drops what the writes since the last drain changed, for writes that are not edits to the + /// document. Bringing an old document up to date produces the document rather than changing it, so + /// there is nothing to report. + pub(crate) fn discard_deltas(&mut self) { + self.deltas.clear(); + } + /// Drops the network's link to the definition it was instantiated from, which no longer describes it /// once its signature is edited. pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) { diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 99e094026b..db02a12b89 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -1370,6 +1370,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ document.network_interface.shift_absolute_node_position(&converter_id, text_position + IVec2::new(7, 0), network_path); } } + + // Bringing an old document up to date is not a set of edits on it, it is how the document arrives. + // The upgrades run through the ordinary mutators, so the store records them; dropping what they + // recorded leaves the opened document as the baseline rather than as a pile of changes to itself. + document.network_interface.discard_deltas(); } /// Converts a legacy stroke dash input (a `List`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.