Add collaborative authored-file safety

This commit is contained in:
Rbanh committed 2026-07-12 11:27:57 -04:00
1 parent b4aa61e394
commit 5a82a9ee29
23 files changed
+2857 -89

No files matched your search

+316 -25
View File
@@ -23,8 +23,9 @@ use shared::{
use crate::assets::{import_external_assets, EditorAssets, IMPORTABLE_ASSET_EXTENSIONS};
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
use crate::project::collaboration::{publish_authored_file, FileSnapshot, FileWriteIntent};
use crate::scene::recovery::{
atomic_write, default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
default_state_root, discard_recovery_snapshots, latest_recovery_snapshot,
write_recovery_snapshot,
};
use crate::selection::SelectedEntity;
@@ -60,6 +61,7 @@ pub struct SceneTab {
pub dirty: bool,
snapshot: String,
recovery_snapshot: Option<PathBuf>,
disk_snapshot: Option<FileSnapshot>,
}
impl SceneTab {
@@ -126,6 +128,7 @@ impl Default for SceneIo {
dirty: false,
snapshot: String::new(),
recovery_snapshot: None,
disk_snapshot: None,
}],
active_tab: 0,
change_revision: 0,
@@ -252,9 +255,14 @@ fn load_startup_scene(world: &mut World) {
let path = active_path.unwrap_or(default_path);
match load_level(world, &path) {
Ok(()) => {
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
world.resource_mut::<SceneIo>().mark_clean();
Ok(disk_snapshot) => {
{
let mut io = world.resource_mut::<SceneIo>();
io.active_path = Some(path.clone());
let active_tab = io.active_tab;
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
io.mark_clean();
}
remember_path(world, path.clone());
world.resource_mut::<EditorHistory>().clear();
refresh_recovery_notice(world, &path);
@@ -396,7 +404,7 @@ fn open_path(world: &mut World, path: PathBuf) -> String {
return format!("Open failed: could not preserve active scene: {error}");
}
match load_level(world, &path) {
Ok(()) => {
Ok(disk_snapshot) => {
let id = world.resource_mut::<SceneIo>().allocate_tab_id();
{
let mut io = world.resource_mut::<SceneIo>();
@@ -406,6 +414,7 @@ fn open_path(world: &mut World, path: PathBuf) -> String {
dirty: false,
snapshot: String::new(),
recovery_snapshot: None,
disk_snapshot: Some(disk_snapshot),
});
io.active_tab = io.tabs.len() - 1;
io.active_path = Some(path.clone());
@@ -442,6 +451,7 @@ fn new_scene_tab(world: &mut World) -> String {
dirty: false,
snapshot: String::new(),
recovery_snapshot: None,
disk_snapshot: None,
});
io.active_tab = io.tabs.len() - 1;
io.active_path = None;
@@ -550,6 +560,7 @@ fn close_scene_tab(world: &mut World, index: usize) -> String {
dirty: false,
snapshot: String::new(),
recovery_snapshot: None,
disk_snapshot: None,
}];
io.active_tab = 0;
io.active_path = None;
@@ -691,12 +702,24 @@ fn save_selection_as_prefab(world: &mut World) -> String {
else {
return "Save prefab cancelled".to_string();
};
let expected = match FileSnapshot::capture(&path) {
Ok(expected) => expected,
Err(error) => return format!("Save prefab failed: {error}"),
};
if ensure_unique_actor_ids(world, &selection) > 0 {
world.resource_mut::<SceneIo>().mark_dirty();
}
match save_prefab_entities(world, &path, selection) {
match save_prefab_entities(
world,
&path,
selection,
SceneWriteContext::Standalone {
expected,
description: "prefab copy",
},
) {
Ok(count) => {
world.resource_mut::<EditorAssets>().refresh();
format!(
@@ -775,6 +798,7 @@ fn save_prefab_entities(
world: &mut World,
path: &Path,
entities: Vec<Entity>,
write_context: SceneWriteContext,
) -> Result<usize, String> {
let count = entities.len();
let original_actor_ids: Vec<_> = entities
@@ -791,7 +815,7 @@ fn save_prefab_entities(
.clone(),
);
scene::validate_prefab_graph_text(&text, path, &project_root)?;
atomic_write(path, text.as_bytes())?;
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
Ok(count)
})();
if result.is_err() {
@@ -821,7 +845,7 @@ pub fn save_active_or_prompt_world(world: &mut World) -> String {
fn save_active_or_prompt(world: &mut World) -> String {
let path = world.resource::<SceneIo>().active_path.clone();
match path {
Some(path) => match save_level(world, &path) {
Some(path) => match save_level(world, &path, SceneWriteContext::Active) {
Ok(count) => {
world.resource_mut::<SceneIo>().mark_clean();
remember_path(world, path.clone());
@@ -843,8 +867,12 @@ fn save_with_dialog(world: &mut World) -> String {
else {
return "Save cancelled".to_string();
};
let expected = match FileSnapshot::capture(&path) {
Ok(expected) => expected,
Err(error) => return format!("Save failed: {error}"),
};
match save_level(world, &path) {
match save_level(world, &path, SceneWriteContext::ActiveSaveAs { expected }) {
Ok(count) => {
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
world.resource_mut::<SceneIo>().mark_clean();
@@ -901,8 +929,20 @@ fn export_selection_with_dialog(world: &mut World) -> String {
else {
return "Export cancelled".to_string();
};
let expected = match FileSnapshot::capture(&path) {
Ok(expected) => expected,
Err(error) => return format!("Export failed: {error}"),
};
match save_standalone_entities(world, &path, vec![entity]) {
match save_standalone_entities(
world,
&path,
vec![entity],
SceneWriteContext::Standalone {
expected,
description: "selection export",
},
) {
Ok(count) => format!("Exported {count} selected entity to {}", path.display()),
Err(err) => format!("Export failed: {err}"),
}
@@ -934,12 +974,16 @@ fn clear_scene_world(world: &mut World) {
}
}
fn save_level(world: &mut World, path: &Path) -> Result<usize, String> {
fn save_level(
world: &mut World,
path: &Path,
write_context: SceneWriteContext,
) -> Result<usize, String> {
let entities = authored_scene_entities(world);
if is_prefab_document(path) {
save_prefab_entities(world, path, entities)
save_prefab_entities(world, path, entities, write_context)
} else {
save_entities(world, path, entities)
save_entities(world, path, entities, write_context)
}
}
@@ -1131,10 +1175,15 @@ fn format_actor_validation(err: ActorValidationError) -> String {
}
}
fn save_entities(world: &mut World, path: &Path, entities: Vec<Entity>) -> Result<usize, String> {
fn save_entities(
world: &mut World,
path: &Path,
entities: Vec<Entity>,
write_context: SceneWriteContext,
) -> Result<usize, String> {
let count = entities.len();
let text = serialize_entities(world, entities)?;
atomic_write(path, text.as_bytes())?;
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
Ok(count)
}
@@ -1142,13 +1191,108 @@ fn save_standalone_entities(
world: &mut World,
path: &Path,
entities: Vec<Entity>,
write_context: SceneWriteContext,
) -> Result<usize, String> {
let count = entities.len();
let text = serialize_standalone_entities(world, entities)?;
atomic_write(path, text.as_bytes())?;
publish_scene_text(world, path, text.as_bytes(), count, write_context)?;
Ok(count)
}
#[derive(Clone)]
enum SceneWriteContext {
Active,
ActiveSaveAs {
expected: FileSnapshot,
},
Standalone {
expected: FileSnapshot,
description: &'static str,
},
}
fn publish_scene_text(
world: &mut World,
path: &Path,
bytes: &[u8],
entity_count: usize,
context: SceneWriteContext,
) -> Result<(), String> {
match context {
SceneWriteContext::Active | SceneWriteContext::ActiveSaveAs { .. } => {
let (tab_id, expected) = match context {
SceneWriteContext::Active => active_scene_write_baseline(world, path)?,
SceneWriteContext::ActiveSaveAs { expected } => {
(active_scene_tab_id(world)?, expected)
}
SceneWriteContext::Standalone { .. } => unreachable!(),
};
let snapshot = publish_authored_file(
world,
path,
bytes,
&expected,
FileWriteIntent::Scene {
tab_id,
entity_count,
},
)?;
let mut io = world.resource_mut::<SceneIo>();
let Some(tab) = io.tabs.iter_mut().find(|tab| tab.id == tab_id) else {
return Err("saved scene tab no longer exists".into());
};
tab.disk_snapshot = Some(snapshot);
}
SceneWriteContext::Standalone {
expected,
description,
} => {
publish_authored_file(
world,
path,
bytes,
&expected,
FileWriteIntent::Standalone {
description: description.into(),
},
)?;
}
}
Ok(())
}
fn active_scene_write_baseline(
world: &World,
destination: &Path,
) -> Result<(u64, FileSnapshot), String> {
let io = world.resource::<SceneIo>();
let tab = io
.tabs
.get(io.active_tab)
.ok_or_else(|| "active scene tab is missing".to_string())?;
if io.active_path.as_deref() != Some(destination) || tab.path.as_deref() != Some(destination) {
return Err(format!(
"{} is not the active scene destination; use Save As",
destination.display()
));
}
let expected = tab.disk_snapshot.clone().ok_or_else(|| {
format!(
"scene disk baseline is unavailable for {}; reload it or use Save As",
destination.display()
)
})?;
Ok((tab.id, expected))
}
fn active_scene_tab_id(world: &World) -> Result<u64, String> {
let io = world.resource::<SceneIo>();
io.tabs
.get(io.active_tab)
.map(|tab| tab.id)
.ok_or_else(|| "active scene tab is missing".to_string())
}
fn serialize_entities(world: &mut World, entities: Vec<Entity>) -> Result<String, String> {
serialize_entities_inner_with_resources(world, entities, true)
}
@@ -1430,7 +1574,7 @@ fn restore_recovery(world: &mut World) -> String {
return "No scene recovery snapshot is available".to_string();
};
match load_level(world, &snapshot) {
Ok(()) => {
Ok(_) => {
mark_recovery_restored(&mut world.resource_mut::<SceneIo>(), active_path);
world.resource_mut::<EditorHistory>().clear();
format!(
@@ -1471,8 +1615,12 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
else {
return "Save recovery copy cancelled".to_string();
};
let expected = match FileSnapshot::capture(&destination) {
Ok(expected) => expected,
Err(error) => return format!("Save recovery copy failed: {error}"),
};
match write_recovery_copy(&snapshot, &destination) {
match write_recovery_copy(world, &snapshot, &destination, &expected) {
Ok(()) => format!(
"Saved recovery copy {} from {}",
destination.display(),
@@ -1482,10 +1630,24 @@ fn save_recovery_copy_with_dialog(world: &mut World) -> String {
}
}
fn write_recovery_copy(snapshot: &Path, destination: &Path) -> Result<(), String> {
fn write_recovery_copy(
world: &mut World,
snapshot: &Path,
destination: &Path,
expected: &FileSnapshot,
) -> Result<(), String> {
let bytes = std::fs::read(snapshot)
.map_err(|error| format!("could not read {}: {error}", snapshot.display()))?;
atomic_write(destination, &bytes)
publish_authored_file(
world,
destination,
&bytes,
expected,
FileWriteIntent::Standalone {
description: "recovery scene copy".into(),
},
)
.map(|_| ())
}
fn mark_recovery_restored(io: &mut SceneIo, active_path: Option<PathBuf>) {
@@ -1522,14 +1684,79 @@ fn discard_recovery(world: &mut World) -> String {
}
}
fn load_level(world: &mut World, path: &Path) -> Result<(), String> {
fn load_level(world: &mut World, path: &Path) -> Result<FileSnapshot, String> {
if !path.exists() {
return Err(format!("{} does not exist yet", path.display()));
}
let text = std::fs::read_to_string(path)
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
load_level_text(world, Some(path), &text)
let disk_snapshot = FileSnapshot::from_loaded_bytes(path, text.as_bytes());
load_level_text(world, Some(path), &text)?;
Ok(disk_snapshot)
}
pub(crate) fn reload_scene_after_file_conflict(
world: &mut World,
tab_id: u64,
path: &Path,
) -> Result<String, String> {
let active_matches = {
let io = world.resource::<SceneIo>();
io.tabs
.get(io.active_tab)
.is_some_and(|tab| tab.id == tab_id)
};
if !active_matches {
return Err("the scene conflict no longer belongs to the active tab".into());
}
let disk_snapshot = load_level(world, path)?;
{
let mut io = world.resource_mut::<SceneIo>();
io.active_path = Some(path.to_path_buf());
io.recovery_snapshot = None;
let active_tab = io.active_tab;
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
io.mark_clean();
}
world.resource_mut::<EditorHistory>().clear();
remember_path(world, path.to_path_buf());
refresh_recovery_notice(world, path);
capture_active_tab(world)?;
Ok(format!("Reloaded {} from disk", path.display()))
}
pub(crate) fn adopt_scene_conflict_save_as(
world: &mut World,
tab_id: u64,
path: PathBuf,
disk_snapshot: FileSnapshot,
entity_count: usize,
) -> Result<String, String> {
let active_matches = {
let io = world.resource::<SceneIo>();
io.tabs
.get(io.active_tab)
.is_some_and(|tab| tab.id == tab_id)
};
if !active_matches {
return Err("the scene conflict no longer belongs to the active tab".into());
}
{
let mut io = world.resource_mut::<SceneIo>();
io.active_path = Some(path.clone());
let active_tab = io.active_tab;
io.tabs[active_tab].disk_snapshot = Some(disk_snapshot);
io.mark_clean();
}
remember_path(world, path.clone());
retire_scene_recovery(world, &path);
Ok(format!(
"Saved {entity_count} level entities to {}",
path.display()
))
}
fn load_level_text(world: &mut World, path: Option<&Path>, text: &str) -> Result<(), String> {
@@ -1979,6 +2206,7 @@ mod tests {
dirty: true,
snapshot: "dirty inactive tab".to_string(),
recovery_snapshot: None,
disk_snapshot: None,
});
assert!(
io.has_unsaved_tabs(),
@@ -1993,6 +2221,61 @@ mod tests {
);
}
#[test]
fn active_scene_write_refuses_an_external_revision() {
let root = std::env::temp_dir().join(format!(
"blacksite-scene-external-write-{}",
uuid::Uuid::new_v4()
));
let path = root.join("assets/levels/main.scn.ron");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"loaded").unwrap();
let disk_snapshot = FileSnapshot::capture(&path).unwrap();
let mut io = SceneIo {
active_path: Some(path.clone()),
..Default::default()
};
io.tabs[0].path = Some(path.clone());
io.tabs[0].disk_snapshot = Some(disk_snapshot);
let mut world = World::new();
world.insert_resource(io);
std::fs::write(&path, b"external").unwrap();
let result = publish_scene_text(&mut world, &path, b"editor", 1, SceneWriteContext::Active);
assert!(result.unwrap_err().contains("changed outside Blacksite"));
assert_eq!(std::fs::read(&path).unwrap(), b"external");
assert!(world.resource::<SceneIo>().dirty);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn scene_save_as_refuses_a_file_created_after_destination_selection() {
let root = std::env::temp_dir().join(format!(
"blacksite-scene-save-as-race-{}",
uuid::Uuid::new_v4()
));
let path = root.join("assets/levels/new.scn.ron");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let expected = FileSnapshot::missing();
let mut world = World::new();
world.init_resource::<SceneIo>();
std::fs::write(&path, b"external").unwrap();
let result = publish_scene_text(
&mut world,
&path,
b"editor",
1,
SceneWriteContext::ActiveSaveAs { expected },
);
assert!(result.unwrap_err().contains("changed outside Blacksite"));
assert_eq!(std::fs::read(&path).unwrap(), b"external");
assert!(world.resource::<SceneIo>().dirty);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn composition_edits_participate_in_undo_and_redo() {
let mut app = App::new();
@@ -2770,8 +3053,13 @@ mod tests {
.insert_resource(crate::ui::hierarchy_state::HierarchyPanelState::default());
app.world_mut().init_resource::<SceneIo>();
load_level(app.world_mut(), &prefab_path).unwrap();
save_level(app.world_mut(), &prefab_path).unwrap();
let expected = load_level(app.world_mut(), &prefab_path).unwrap();
save_level(
app.world_mut(),
&prefab_path,
SceneWriteContext::ActiveSaveAs { expected },
)
.unwrap();
scene::validate_prefab_graph(&prefab_path, &root).unwrap();
let document =
@@ -2813,8 +3101,11 @@ mod tests {
let destination = root.join("kept.scn.ron");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(&snapshot, b"recovered scene bytes").unwrap();
let expected = FileSnapshot::missing();
let mut world = World::new();
world.init_resource::<SceneIo>();
write_recovery_copy(&snapshot, &destination).unwrap();
write_recovery_copy(&mut world, &snapshot, &destination, &expected).unwrap();
assert_eq!(
std::fs::read(&destination).unwrap(),