use super::super::*;
fn snapshot_with(
node: crate::persistence::PersistedNode,
nav: SharedNavigationMemory,
) -> crate::persistence::GraphSnapshot {
crate::persistence::GraphSnapshot {
assertion_schema: 0,
nodes: vec![node],
edges: vec![],
import_records: vec![],
timestamp_secs: 0,
fields: vec![],
couplings: vec![],
navigation: nav,
resources: vec![],
resource_edges: vec![],
shown_resources: vec![],
}
}
fn cursor_page(graph: &Graph, key: NodeKey) -> Option<String> {
let trail = graph.node_history_projection(key);
trail.entries.get(trail.current_index).cloned()
}
fn persisted_node(node_id: Uuid, url: &str) -> crate::persistence::PersistedNode {
use crate::persistence::{PersistedAddress, PersistedNode};
PersistedNode {
node_id: node_id.to_string(),
url: url.to_string(),
cached_host: None,
title: "Node".to_string(),
tags: vec![],
tag_presentation: NodeTagPresentationState::default(),
import_provenance: vec![],
is_pinned: false,
images: Default::default(),
legacy_thumbnail_png: None,
legacy_thumbnail_width: 0,
legacy_thumbnail_height: 0,
legacy_favicon_rgba: None,
legacy_favicon_width: 0,
legacy_favicon_height: 0,
session_state: None,
mime_hint: None,
address: PersistedAddress::Http(url.to_string()),
classifications: Vec::new(),
frame_layout_hints: Vec::new(),
frame_split_offer_suppressed: false,
properties: Vec::new(),
derivations: Vec::new(),
body: None,
last_session_visited: 0,
nested: None,
content_hash: None,
}
}
#[test]
fn node_body_round_trips() {
let id = Uuid::new_v4();
let mut pnode = persisted_node(id, "knot://notes");
pnode.body = Some("# Notes\n\nbody".to_string());
let graph = Graph::from_snapshot(&snapshot_with(pnode, SharedNavigationMemory::empty()));
let node = graph.nodes().next().expect("node restored").1;
assert_eq!(node.body.as_deref(), Some("# Notes\n\nbody"));
assert_eq!(
graph.to_snapshot().nodes[0].body.as_deref(),
Some("# Notes\n\nbody"),
);
}
#[test]
fn node_content_round_trips_and_excludes_inline_body() {
let mut graph = Graph::new();
let key = graph.add_node(
"smolweb://example.test/file.bin".to_string(),
Point2D::new(0.0, 0.0),
);
let content = ContentHash::of(b"downloaded bytes");
let _ = apply::apply_graph_delta(
&mut graph,
apply::GraphDelta::SetNodeBody {
key,
body: Some("legacy inline body".to_string()),
},
);
let _ = apply::apply_graph_delta(
&mut graph,
apply::GraphDelta::SetNodeContent {
key,
content: Some(content),
},
);
let restored = Graph::from_snapshot(&graph.to_snapshot());
let (_, node) = restored
.get_node_by_url("smolweb://example.test/file.bin")
.expect("restored download node");
assert_eq!(node.content, Some(content));
assert_eq!(node.body, None);
let restored_key = restored
.get_node_by_url("smolweb://example.test/file.bin")
.expect("restored download node")
.0;
let mut restored = restored;
let _ = apply::apply_graph_delta(
&mut restored,
apply::GraphDelta::SetNodeBody {
key: restored_key,
body: Some("authored replacement".to_string()),
},
);
let node = restored.get_node(restored_key).expect("updated node");
assert_eq!(node.body.as_deref(), Some("authored replacement"));
assert_eq!(node.content, None);
}
#[test]
fn snapshot_without_content_hash_stays_readable() {
let snapshot = snapshot_with(
persisted_node(Uuid::new_v4(), "https://legacy.example/"),
SharedNavigationMemory::empty(),
);
let mut json = serde_json::to_value(snapshot).expect("serialize snapshot");
json["nodes"][0]
.as_object_mut()
.expect("persisted node object")
.remove("content_hash");
let legacy: crate::persistence::GraphSnapshot =
serde_json::from_value(json).expect("load legacy snapshot");
let graph = Graph::from_snapshot(&legacy);
assert_eq!(graph.nodes().next().expect("restored node").1.content, None);
}
#[test]
fn test_update_node_url() {
let mut graph = Graph::new();
let key = graph.add_node("old".to_string(), Point2D::new(0.0, 0.0));
let old = graph.update_node_url(key, "new".to_string());
assert_eq!(old, Some("old".to_string()));
assert_eq!(graph.get_node(key).unwrap().url(), "new");
assert!(graph.get_node_by_url("new").is_some());
assert!(graph.get_node_by_url("old").is_none());
}
#[test]
fn test_update_node_url_nonexistent() {
let mut graph = Graph::new();
let fake_key = NodeKey::new(999);
assert_eq!(graph.update_node_url(fake_key, "x".to_string()), None);
}
#[test]
fn test_cold_restore_reapplies_history_index() {
let node_id = Uuid::new_v4();
let mut nav = SharedNavigationMemory::empty();
nav.seed_linear(
node_id,
vec![
"https://example.com/one".to_string(),
"https://example.com/two".to_string(),
"https://example.com/three".to_string(),
],
2,
);
let snapshot = snapshot_with(persisted_node(node_id, "https://fallback.example"), nav);
let restored = Graph::from_snapshot(&snapshot);
let (key, _) = restored.get_node_by_id(node_id).unwrap();
let history = restored.node_history_projection(key);
assert_eq!(history.entries.len(), 3);
assert_eq!(history.current_index, 2);
assert_eq!(
cursor_page(&restored, key).as_deref(),
Some("https://example.com/three")
);
}
#[test]
fn navigate_forward_fork_preserves_the_alternate_branch() {
use crate::graph::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
let mut graph = Graph::new();
let key = graph.add_node("https://example.com/a".to_string(), Point2D::new(0.0, 0.0));
let navigate = |graph: &mut Graph, url: &str| {
apply_graph_delta(
graph,
GraphDelta::NavigateNode {
key,
url: url.into(),
},
);
};
navigate(&mut graph, "https://example.com/a");
navigate(&mut graph, "https://example.com/b");
assert_eq!(
apply_graph_delta(&mut graph, GraphDelta::NodeHistoryBack { key }),
GraphDeltaResult::HistoryStepped(Some("https://example.com/a".into()))
);
navigate(&mut graph, "https://example.com/c");
let branch = graph.node_history_branch_projection(key);
let a_visit = branch
.visits
.iter()
.find(|v| v.url == "https://example.com/a")
.expect("a on the active path");
assert!(
a_visit
.alternate_children
.iter()
.any(|alt| alt.url == "https://example.com/b"),
"b is preserved as an alternate branch off a after the forward-fork",
);
assert_eq!(
cursor_page(&graph, key).as_deref(),
Some("https://example.com/c")
);
}
#[test]
fn replacing_a_navigation_parents_history_keeps_the_branched_child() {
use crate::graph::apply::{GraphDelta, add_node, apply_graph_delta};
let mut graph = Graph::new();
let parent = add_node(
&mut graph,
Some(Uuid::from_u128(1)),
"https://example.com/parent".into(),
Default::default(),
);
apply_graph_delta(
&mut graph,
GraphDelta::NavigateNode {
key: parent,
url: "https://example.com/parent".into(),
},
);
let child = add_node(
&mut graph,
Some(Uuid::from_u128(2)),
"https://example.com/child".into(),
Default::default(),
);
apply_graph_delta(&mut graph, GraphDelta::BranchHistory { child, parent });
apply_graph_delta(
&mut graph,
GraphDelta::NavigateNode {
key: child,
url: "https://example.com/child".into(),
},
);
apply_graph_delta(
&mut graph,
GraphDelta::UpdateNodeHistory {
key: parent,
entries: vec!["https://example.com/replacement".into()],
current_index: 0,
},
);
assert_eq!(
graph.node_history_projection(parent).entries,
vec!["https://example.com/replacement".to_string()]
);
assert_eq!(
cursor_page(&graph, child).as_deref(),
Some("https://example.com/child")
);
Graph::from_snapshot(&graph.to_snapshot_at(0));
}
#[test]
fn test_legacy_session_state_stays_readable_for_host_migration() {
use crate::persistence::PersistedNodeSessionState;
let node_id = Uuid::new_v4();
let mut node = persisted_node(node_id, "https://example.com");
node.session_state = Some(PersistedNodeSessionState {
scroll_x: Some(20.0),
scroll_y: Some(640.0),
form_draft: Some("draft body".to_string()),
last_visited_ms: None,
});
let snapshot = snapshot_with(node, SharedNavigationMemory::empty());
let legacy = snapshot.nodes[0]
.session_state
.as_ref()
.expect("legacy session state present");
assert_eq!(legacy.scroll_x.zip(legacy.scroll_y), Some((20.0, 640.0)));
assert_eq!(legacy.form_draft.as_deref(), Some("draft body"));
let restored = Graph::from_snapshot(&snapshot);
assert!(restored.get_node_by_url("https://example.com").is_some());
let resaved = restored.to_snapshot();
let session = resaved.nodes[0].session_state.as_ref().unwrap();
assert_eq!(session.scroll_x, None);
assert_eq!(session.scroll_y, None);
assert_eq!(session.form_draft, None);
}
#[test]
fn test_cold_restore_reapplies_last_visited() {
use crate::persistence::PersistedNodeSessionState;
let node_id = Uuid::new_v4();
let mut node = persisted_node(node_id, "https://example.com");
node.session_state = Some(PersistedNodeSessionState {
scroll_x: None,
scroll_y: None,
form_draft: None,
last_visited_ms: Some(1_763_573_400_123),
});
let snapshot = snapshot_with(node, SharedNavigationMemory::empty());
let restored = Graph::from_snapshot(&snapshot);
let (key, _) = restored.get_node_by_url("https://example.com").unwrap();
assert_eq!(
restored
.node_last_visited(key)
.expect("last visited facet")
.duration_since(std::time::UNIX_EPOCH)
.expect("last visited since epoch")
.as_millis() as u64,
1_763_573_400_123
);
}
#[test]
fn test_restore_fallback_without_session_state() {
let node_id = Uuid::new_v4();
let mut nav = SharedNavigationMemory::empty();
nav.seed_linear(node_id, vec!["https://legacy-one.example".to_string()], 0);
let snapshot = snapshot_with(persisted_node(node_id, "https://fallback.example"), nav);
let restored = Graph::from_snapshot(&snapshot);
let (key, _) = restored.get_node_by_id(node_id).unwrap();
let history = restored.node_history_projection(key);
assert_eq!(
history.entries,
vec!["https://legacy-one.example".to_string()]
);
assert_eq!(history.current_index, 0);
}
fn live_and_replayed(
live: &mut Graph,
steps: impl FnOnce(&mut Graph),
) -> (Graph, Vec<crate::graph::capture::CapturedDelta>) {
let replayed = live.clone();
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = seen.clone();
live.set_recorder(Some(std::sync::Arc::new(move |delta| {
sink.lock().unwrap().push(delta.clone())
})));
steps(live);
let captured = seen.lock().unwrap().clone();
(replayed, captured)
}
#[test]
fn live_and_replayed_navigation_leave_one_state() {
use crate::graph::apply::{GraphDelta, add_node, apply_graph_delta};
let mut live = Graph::new();
let url = |name: &str| format!("https://example.com/{name}");
let a = add_node(
&mut live,
Some(Uuid::from_u128(1)),
url("a"),
Default::default(),
);
let b = add_node(
&mut live,
Some(Uuid::from_u128(2)),
url("b"),
Default::default(),
);
let (mut replayed, captured) = live_and_replayed(&mut live, |graph| {
let mut apply = |delta| apply_graph_delta(graph, delta);
let navigate = |key, name| GraphDelta::NavigateNode {
key,
url: url(name),
};
apply(navigate(a, "a1"));
apply(navigate(a, "a2"));
apply(GraphDelta::BranchHistory {
child: b,
parent: a,
});
apply(navigate(b, "b1"));
apply(GraphDelta::NodeHistoryBack { key: a });
apply(GraphDelta::NodeHistoryForward { key: a });
apply(GraphDelta::NodeHistoryBack { key: a });
apply(navigate(a, "a3"));
});
crate::graph::capture::replay_captured_deltas_onto(&mut replayed, captured);
let snapshot = |graph: &Graph| serde_json::to_value(graph.to_snapshot_at(0)).unwrap();
assert_eq!(snapshot(&live), snapshot(&replayed));
assert_eq!(live.facets(), replayed.facets());
let current = |graph: &Graph, key| cursor_page(graph, key);
assert_eq!(current(&live, a), Some(url("a3")));
assert_eq!(current(&replayed, a), Some(url("a3")));
}
#[test]
fn navigating_a_node_in_place_moves_its_recency() {
use crate::graph::apply::{GraphDelta, add_node, apply_graph_delta};
let url = |name: &str| format!("https://example.com/{name}");
let mut live = Graph::new();
let node = |graph: &mut Graph, id: u128, name: &str| {
add_node(
graph,
Some(Uuid::from_u128(id)),
url(name),
Default::default(),
)
};
let (a, b) = (node(&mut live, 1, "a"), node(&mut live, 2, "b"));
let recency = |graph: &Graph, key| {
let visited = graph.node_last_visited(key)?;
Some(
visited
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_millis() as u64,
)
};
let (mut replayed, captured) = live_and_replayed(&mut live, |graph| {
let pin = |graph: &mut Graph, id: u128| {
apply_graph_delta(
graph,
GraphDelta::ReplayTouchNodeLastVisitedById {
node_id: Uuid::from_u128(id),
timestamp_ms: 1,
},
);
};
let moved = |graph: &Graph, key| recency(graph, key) > Some(1);
pin(graph, 1);
pin(graph, 2);
apply_graph_delta(graph, GraphDelta::NodeHistoryBack { key: a });
assert_eq!(recency(graph, a), Some(1));
let navigate = |name| GraphDelta::NavigateNode {
key: a,
url: url(name),
};
apply_graph_delta(graph, navigate("a1"));
assert!(moved(graph, a), "navigating stamps the node");
apply_graph_delta(graph, navigate("a2"));
pin(graph, 1);
apply_graph_delta(graph, GraphDelta::NodeHistoryBack { key: a });
assert!(moved(graph, a), "stepping back stamps the node");
pin(graph, 1);
apply_graph_delta(graph, GraphDelta::NodeHistoryForward { key: a });
assert!(moved(graph, a), "stepping forward stamps the node");
apply_graph_delta(
graph,
GraphDelta::BranchHistory {
child: b,
parent: a,
},
);
assert_eq!(recency(graph, b), Some(1), "a branch is not a visit");
});
crate::graph::capture::replay_captured_deltas_onto(&mut replayed, captured);
for key in [a, b] {
assert_eq!(recency(&replayed, key), recency(&live, key));
}
assert!(recency(&replayed, a) > Some(1));
}
#[test]
fn a_set_address_is_the_address_until_the_next_history_step() {
use crate::graph::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
let page = |name: &str| format!("https://example.com/{name}");
let mut graph = Graph::new();
let key = graph.add_node(page("a"), Point2D::new(0.0, 0.0));
let apply = |graph: &mut Graph, delta| apply_graph_delta(graph, delta);
for name in ["previous", "a"] {
apply(
&mut graph,
GraphDelta::NavigateNode {
key,
url: page(name),
},
);
}
apply(
&mut graph,
GraphDelta::SetNodeUrl {
key,
new_url: page("b"),
},
);
assert_eq!(graph.get_node(key).unwrap().url(), page("b"));
assert_eq!(graph.get_nodes_by_url(&page("b")), vec![key]);
assert!(graph.get_nodes_by_url(&page("a")).is_empty());
let trail = graph.node_history_projection(key);
assert_eq!(trail.entries, vec![page("previous"), page("a")]);
assert_eq!(trail.entries[trail.current_index], page("a"));
assert_eq!(
apply(&mut graph, GraphDelta::NodeHistoryBack { key }),
GraphDeltaResult::HistoryStepped(Some(page("previous")))
);
assert_eq!(graph.get_node(key).unwrap().url(), page("previous"));
assert_eq!(graph.get_nodes_by_url(&page("previous")), vec![key]);
assert!(graph.get_nodes_by_url(&page("b")).is_empty());
}