From bb532273646261b5559dcafbb2dcea9614d5a582 Mon Sep 17 00:00:00 2001 From: DarkSky <25152247+darkskygit@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:55:54 +0900 Subject: [PATCH] fix(desktop): sync workspace media in write order Track local media writes when editors change blob bytes. Apply writes in order and skip unchanged editors during shell sync. --- .../playground/src/room_client/blob_map.rs | 134 ++++++ .../crates/playground/src/room_client/mod.rs | 11 +- .../frontend/desktop/src/editor_host/blobs.rs | 169 +++++++ .../frontend/desktop/src/editor_host/mod.rs | 182 +++---- .../desktop/src/workbench/local_workspace.rs | 447 +++++++++++------- .../frontend/desktop/src/workbench/mod.rs | 12 +- 6 files changed, 698 insertions(+), 257 deletions(-) create mode 100644 blocksuite/crates/playground/src/room_client/blob_map.rs create mode 100644 packages/frontend/desktop/src/editor_host/blobs.rs diff --git a/blocksuite/crates/playground/src/room_client/blob_map.rs b/blocksuite/crates/playground/src/room_client/blob_map.rs new file mode 100644 index 0000000000..5053b31469 --- /dev/null +++ b/blocksuite/crates/playground/src/room_client/blob_map.rs @@ -0,0 +1,134 @@ +use std::{ + collections::{BTreeMap, HashMap, hash_map}, + ops::{ + Bound::{Excluded, Unbounded}, + Deref, + }, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, +}; + +static NEXT_BLOB_WRITE_SEQ: AtomicU64 = AtomicU64::new(1); + +/// Blob bytes and the latest local write for each source. +#[derive(Clone, Debug, Default)] +pub struct BlobMap { + entries: HashMap>>, + writes: BTreeMap, + key_seq: HashMap, + last_seq: u64, +} + +impl BlobMap { + pub fn insert(&mut self, key: String, bytes: Arc>) -> Option>> { + let seq = NEXT_BLOB_WRITE_SEQ.fetch_add(1, Ordering::Relaxed); + if let Some(previous) = self.key_seq.insert(key.clone(), seq) { + self.writes.remove(&previous); + } + self.writes.insert(seq, key.clone()); + self.last_seq = seq; + self.entries.insert(key, bytes) + } + + pub fn extend(&mut self, entries: impl IntoIterator>)>) { + for (key, bytes) in entries { + self.insert(key, bytes); + } + } + + pub fn remove(&mut self, key: &str) -> Option>> { + if let Some(seq) = self.key_seq.remove(key) { + self.writes.remove(&seq); + } + self.entries.remove(key) + } + + /// Load the workspace cache into a new editor. + pub fn replace_synced(&mut self, entries: HashMap>>) { + *self = Self { + entries, + ..Self::default() + }; + } + + /// Apply workspace updates without recording local writes. + pub fn extend_synced(&mut self, entries: impl IntoIterator>)>) { + for (key, bytes) in entries { + if let Some(seq) = self.key_seq.remove(&key) { + self.writes.remove(&seq); + } + self.entries.insert(key, bytes); + } + } + + pub fn last_seq(&self) -> u64 { + self.last_seq + } + + pub fn changes_since( + &self, + after_seq: u64, + ) -> impl Iterator>)> { + self.writes + .range((Excluded(after_seq), Unbounded)) + .map(|(&seq, key)| (seq, key.as_str(), &self.entries[key])) + } +} + +impl Deref for BlobMap { + type Target = HashMap>>; + + fn deref(&self) -> &Self::Target { + &self.entries + } +} + +impl<'a> IntoIterator for &'a BlobMap { + type Item = (&'a String, &'a Arc>); + type IntoIter = hash_map::Iter<'a, String, Arc>>; + + fn into_iter(self) -> Self::IntoIter { + self.entries.iter() + } +} + +impl IntoIterator for BlobMap { + type Item = (String, Arc>); + type IntoIter = hash_map::IntoIter>>; + + fn into_iter(self) -> Self::IntoIter { + self.entries.into_iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn local_writes_get_new_sequences_and_synced_values_clear_stale_writes() { + let bytes = Arc::new(vec![1]); + let key = "source".to_owned(); + let mut first = BlobMap::default(); + let mut peer = BlobMap::default(); + first.insert(key.clone(), bytes.clone()); + let initial_seq = first.last_seq(); + peer.insert(key.clone(), Arc::new(vec![2])); + first.insert(key.clone(), bytes.clone()); + + assert!(initial_seq < peer.last_seq()); + assert!(peer.last_seq() < first.last_seq()); + assert_eq!( + first.changes_since(0).collect::>(), + [(first.last_seq(), key.as_str(), &bytes)] + ); + + let peer_seq = peer.last_seq(); + peer.extend_synced(first); + assert_eq!(peer.last_seq(), peer_seq); + assert_eq!(peer.changes_since(0).count(), 0); + assert!(Arc::ptr_eq(&peer[&key], &bytes)); + } +} diff --git a/blocksuite/crates/playground/src/room_client/mod.rs b/blocksuite/crates/playground/src/room_client/mod.rs index d909e0173a..733d1c8c07 100644 --- a/blocksuite/crates/playground/src/room_client/mod.rs +++ b/blocksuite/crates/playground/src/room_client/mod.rs @@ -11,15 +11,13 @@ //! blobs over HTTP from the relay's blob endpoint (a bare HTTP/1.1 `GET` natively, `fetch` //! on the Web). +mod blob_map; #[cfg(not(target_family = "wasm"))] mod native; #[cfg(target_family = "wasm")] mod web; -use std::{ - collections::{BTreeMap, HashMap}, - sync::Arc, -}; +use std::{collections::BTreeMap, sync::Arc}; use blocksuite_playground_doc::{ DocResult, @@ -31,6 +29,7 @@ use blocksuite_playground_doc::{ }, }; +pub use blob_map::BlobMap; #[cfg(not(target_family = "wasm"))] pub use native::connect; #[cfg(target_family = "wasm")] @@ -49,7 +48,7 @@ pub struct DocState { pub workspace: WorkspaceSession, pub awareness: RoomAwareness, /// Blob bytes by `sourceId`. - pub blobs: HashMap>>, + pub blobs: BlobMap, } impl DocState { @@ -58,7 +57,7 @@ impl DocState { Ok(Self { workspace: WorkspaceSession::new(room, client_id)?, awareness: RoomAwareness::new(client_id)?, - blobs: HashMap::new(), + blobs: BlobMap::default(), }) } } diff --git a/packages/frontend/desktop/src/editor_host/blobs.rs b/packages/frontend/desktop/src/editor_host/blobs.rs new file mode 100644 index 0000000000..e1c2dcd641 --- /dev/null +++ b/packages/frontend/desktop/src/editor_host/blobs.rs @@ -0,0 +1,169 @@ +use std::{ + collections::{BTreeMap, HashMap}, + ops::Bound::{Excluded, Unbounded}, + rc::Rc, + sync::Arc, +}; + +use ui::Context; + +use super::DesktopEditorHost; +use crate::{ + doc_store::DesktopDocStore, + workbench::{DesktopShellView, LocalWorkspaces, StoredBlobs}, +}; + +type BlobEntry = (String, Arc>); + +#[derive(Default)] +pub(super) struct WorkspaceBlobs { + pub(super) revision: usize, + // Keep one buffer per source and index it by its most recent change. + pub(super) entries: BTreeMap, + sources: HashMap, +} + +impl WorkspaceBlobs { + fn get(&self, source: &str) -> Option<&Arc>> { + let revision = self.sources.get(source)?; + self.entries.get(revision).map(|(_, bytes)| bytes) + } + + fn put(&mut self, source: String, bytes: Arc>) { + self.revision += 1; + if let Some(previous) = self.sources.insert(source.clone(), self.revision) { + self.entries.remove(&previous); + } + self.entries.insert(self.revision, (source, bytes)); + } +} + +impl DesktopEditorHost { + pub(crate) fn seed_workspace_blobs(&mut self, workspace_id: &str, blobs: &StoredBlobs) { + if blobs.is_empty() { + return; + } + let cache = self + .workspace_blobs + .entry(workspace_id.to_owned()) + .or_default(); + for (source, bytes) in blobs { + cache.put(source.clone(), bytes.clone()); + } + } + + pub(crate) fn bind_local_media( + &mut self, + workspaces: &Rc, + cx: &mut Context, + ) { + self.local_workspaces = Rc::downgrade(workspaces); + self.broadcast_blobs(cx); + } + + pub(crate) fn sync_blobs( + &mut self, + store: &DesktopDocStore, + cx: &mut Context, + ) -> bool { + if !self.workspace_blobs.is_empty() { + self.workspace_blobs + .retain(|id, _| store.workspaces.iter().any(|workspace| &workspace.id == id)); + } + + let mut changes = Vec::new(); + for mounted in self + .pane_editors + .values_mut() + .chain(self.peek_editor.iter_mut()) + { + if !store + .workspaces + .iter() + .any(|workspace| workspace.id == mounted.workspace_id) + { + mounted.blob_cursor = 0; + mounted.seen_blob_seq = 0; + mounted.resync_all_blobs = true; + continue; + } + let workspace_id = mounted.workspace_id.as_str(); + let blobs = &mounted.entity.read(cx).document().blobs; + if !mounted.resync_all_blobs && blobs.last_seq() == mounted.seen_blob_seq { + continue; + } + if mounted.resync_all_blobs { + changes.extend( + blobs + .iter() + .map(|(source, bytes)| (0, workspace_id, source.clone(), bytes.clone())), + ); + mounted.resync_all_blobs = false; + } else { + changes.extend(blobs.changes_since(mounted.seen_blob_seq).map( + |(seq, source, bytes)| (seq, workspace_id, source.to_owned(), bytes.clone()), + )); + } + mounted.seen_blob_seq = blobs.last_seq(); + } + if changes.is_empty() { + return self.broadcast_blobs(cx); + } + + changes.sort_by_key(|(seq, ..)| *seq); + let local = self.local_workspaces.upgrade(); + for (_, workspace, source, bytes) in changes { + let blobs = self + .workspace_blobs + .entry(workspace.to_owned()) + .or_default(); + if blobs + .get(&source) + .is_some_and(|current| Arc::ptr_eq(current, &bytes)) + { + continue; + } + if let Some(local) = &local { + local.record_blob(workspace, source.clone(), bytes.clone()); + } + blobs.put(source, bytes); + } + self.broadcast_blobs(cx) + } + + fn broadcast_blobs(&mut self, cx: &mut Context) -> bool { + let mut changed = false; + for mounted in self + .pane_editors + .values_mut() + .chain(self.peek_editor.iter_mut()) + { + let Some(blobs) = self.workspace_blobs.get(&mounted.workspace_id) else { + continue; + }; + if mounted.blob_cursor == blobs.revision { + continue; + } + let doc = mounted.entity.read(cx).document(); + let updates: Vec<_> = blobs + .entries + .range((Excluded(mounted.blob_cursor), Unbounded)) + .map(|(_, entry)| entry) + .filter(|(source, bytes)| { + doc.blobs + .get(source) + .is_none_or(|current| !Arc::ptr_eq(current, bytes)) + }) + .cloned() + .collect(); + mounted.blob_cursor = blobs.revision; + if !updates.is_empty() { + mounted.entity.update(cx, |view, cx| { + view.edit_document(cx, |doc| doc.blobs.extend_synced(updates)); + }); + changed = true; + } + } + changed + } +} diff --git a/packages/frontend/desktop/src/editor_host/mod.rs b/packages/frontend/desktop/src/editor_host/mod.rs index 7fe68b3bac..7cb59d6d8c 100644 --- a/packages/frontend/desktop/src/editor_host/mod.rs +++ b/packages/frontend/desktop/src/editor_host/mod.rs @@ -5,6 +5,7 @@ //! keeps multiple panes viewing the same `doc_id` bidirectionally synchronized via incremental //! Yjs V1 state-vector diffs (`encode_diff_v1`). +mod blobs; mod directory; mod references; @@ -12,8 +13,8 @@ pub(crate) use references::{open_inline_reference, reference_modifiers}; use std::{ cell::{Cell, RefCell}, - collections::{HashMap, HashSet}, - rc::Rc, + collections::HashMap, + rc::{Rc, Weak}, sync::Arc, }; @@ -29,23 +30,17 @@ use crate::{ doc_store::DesktopDocStore, playground_theme_for, split_view::{DocViewMode, PaneId}, - workbench::DesktopShellView, + workbench::{DesktopShellView, LocalWorkspaces}, }; -use self::directory::DesktopDirectory; - -type BlobEntry = (String, Arc>); - -#[derive(Default)] -struct WorkspaceBlobs { - sources: HashSet, - entries: Vec, -} +use self::{blobs::WorkspaceBlobs, directory::DesktopDirectory}; struct MountedEditor { workspace_id: String, doc_id: String, blob_cursor: usize, + seen_blob_seq: u64, + resync_all_blobs: bool, last_synced_store_rev: u64, last_synced_store_sv: Vec, last_seen_view_rev: u64, @@ -62,6 +57,7 @@ pub struct DesktopEditorHost { pub(crate) workspace_origins: HashMap, pane_editors: HashMap, workspace_blobs: HashMap, + local_workspaces: Weak, directories: HashMap, peek_editor: Option, rendered_panes_this_frame: Vec, @@ -81,7 +77,7 @@ fn load_doc_into_playground( doc_id: &str, workspace_id: &str, source_session: &PageDocSession, - initial_blobs: Option<&[BlobEntry]>, + initial_blobs: Option>>>, cx: &mut Context, ) -> (u64, Vec) { let update = source_session.encode_update_v1().unwrap_or_default(); @@ -103,7 +99,7 @@ fn load_doc_into_playground( } doc_state.workspace = ws; if let Some(blobs) = initial_blobs { - doc_state.blobs = blobs.iter().cloned().collect(); + doc_state.blobs.replace_synced(blobs); } } }); @@ -123,11 +119,10 @@ fn apply_update_to_playground( view: &mut PlaygroundView, doc_id: &str, update: &[u8], - blobs: &[BlobEntry], cx: &mut Context, ) -> (u64, Vec) { let has_update = !update.is_empty() && update != [0, 0]; - if !has_update && blobs.is_empty() { + if !has_update { return view .document() .workspace @@ -140,8 +135,7 @@ fn apply_update_to_playground( }); } view.edit_document(cx, |doc_state| { - doc_state.blobs.extend(blobs.iter().cloned()); - if has_update && let Ok(page) = doc_state.workspace.ensure_page(doc_id) { + if let Ok(page) = doc_state.workspace.ensure_page(doc_id) { let _ = page.apply_remote_update_v1(update); if page.inner().client_required() && let Ok(cid) = try_random_client_id() @@ -176,14 +170,21 @@ impl DesktopEditorHost { &mut self, store: &mut DesktopDocStore, cx: &mut Context, + ) -> bool { + let media_changed = self.sync_blobs(store, cx); + self.sync_documents(store, cx) | media_changed + } + + pub(crate) fn sync_documents( + &mut self, + store: &mut DesktopDocStore, + cx: &mut Context, ) -> bool { if self.syncing { return false; } self.syncing = true; let mut changed = false; - self.workspace_blobs - .retain(|id, _| store.workspaces.iter().any(|workspace| &workspace.id == id)); let workspace_id = &store.active_workspace().id; let directory = if let Some(directory) = self.directories.get_mut(workspace_id) { @@ -207,43 +208,10 @@ impl DesktopEditorHost { .values_mut() .chain(self.peek_editor.iter_mut()) { - if !store - .workspaces - .iter() - .any(|workspace| workspace.id == mounted.workspace_id) - { - mounted.blob_cursor = 0; - continue; - } - let doc = mounted.entity.read(cx).document(); - // Each mounted view starts with the workspace prefix. Only scan its map when - // an upload or paste has added a source since the last broadcast. - if doc.blobs.len() > mounted.blob_cursor { - let workspace_blobs = - if let Some(blobs) = self.workspace_blobs.get_mut(&mounted.workspace_id) { - blobs - } else { - self.workspace_blobs - .entry(mounted.workspace_id.clone()) - .or_default() - }; - for (source, bytes) in &doc.blobs { - if !workspace_blobs.sources.contains(source) { - workspace_blobs.sources.insert(source.clone()); - workspace_blobs - .entries - .push((source.clone(), bytes.clone())); - } - } - // Stop at the first blob from another pane that this editor needs. - mounted.blob_cursor += workspace_blobs.entries[mounted.blob_cursor..] - .iter() - .take_while(|(source, _)| doc.blobs.contains_key(source)) - .count(); - } if &mounted.workspace_id != workspace_id { continue; } + let doc = mounted.entity.read(cx).document(); let prev_sv = &mounted.last_seen_view_sv; let (view_rev, next_sv, maybe_update) = doc.workspace.page(&mounted.doc_id).map_or( (mounted.last_seen_view_rev, None, None), @@ -282,19 +250,14 @@ impl DesktopEditorHost { directory.refresh(store); - // 3. Install the new blobs before refreshing any updated block that refers to them. + // 3. Fan out the store changes to the mounted editors. let workspace_id = &store.active_workspace().id; - let workspace_blobs = self - .workspace_blobs - .get(workspace_id) - .map_or(&[][..], |blobs| blobs.entries.as_slice()); for mounted in self .pane_editors .values_mut() .chain(self.peek_editor.iter_mut()) .filter(|mounted| &mounted.workspace_id == workspace_id) { - let blobs = &workspace_blobs[mounted.blob_cursor..]; let entry = store .get_doc(&mounted.doc_id) .filter(|entry| entry.revision > mounted.last_synced_store_rev); @@ -308,26 +271,16 @@ impl DesktopEditorHost { .ok() } }); - if update.is_some() || !blobs.is_empty() { + if let (Some(entry), Some(update)) = (entry, update) { let (new_view_rev, new_view_sv) = mounted.entity.update(cx, |view, cx| { - apply_update_to_playground( - view, - &mounted.doc_id, - update.as_deref().unwrap_or_default(), - blobs, - cx, - ) + apply_update_to_playground(view, &mounted.doc_id, &update, cx) }); - mounted.blob_cursor = workspace_blobs.len(); mounted.last_seen_view_rev = new_view_rev; mounted.last_seen_view_sv = new_view_sv; - if let (Some(entry), Some(update)) = (entry, update) { - mounted.last_synced_store_rev = entry.revision; - mounted.last_synced_store_sv = - entry.session.encode_state_vector_v1().unwrap_or_default(); - changed |= !update.is_empty() && update.as_slice() != [0, 0]; - } - changed |= !blobs.is_empty(); + mounted.last_synced_store_rev = entry.revision; + mounted.last_synced_store_sv = + entry.session.encode_state_vector_v1().unwrap_or_default(); + changed |= !update.is_empty() && update.as_slice() != [0, 0]; } } @@ -357,10 +310,12 @@ impl DesktopEditorHost { .or_insert_with(|| DesktopDirectory::new(workspace_id.clone())); directory.refresh(store); let origin = self.workspace_origins.get(workspace_id).map(String::as_str); - let blobs = self - .workspace_blobs - .get(workspace_id) - .map_or(&[][..], |blobs| blobs.entries.as_slice()); + let blobs = self.workspace_blobs.get(workspace_id); + let initial_blobs = blobs + .into_iter() + .flat_map(|blobs| blobs.entries.values()) + .cloned() + .collect(); let shell = cx.weak_entity(); let last_synced_mode = Rc::new(Cell::new(pg_mode)); let pending_open_doc = Rc::new(RefCell::new(None::<(String, bool)>)); @@ -401,7 +356,14 @@ impl DesktopEditorHost { } }); }); - load_doc_into_playground(view, doc_id, workspace_id, &entry.session, Some(blobs), cx) + load_doc_into_playground( + view, + doc_id, + workspace_id, + &entry.session, + Some(initial_blobs), + cx, + ) }); let last_mode_obs = last_synced_mode.clone(); let observed_workspace = workspace_id.clone(); @@ -432,7 +394,9 @@ impl DesktopEditorHost { Some(MountedEditor { workspace_id: workspace_id.clone(), doc_id: doc_id.to_string(), - blob_cursor: blobs.len(), + blob_cursor: blobs.map_or(0, |blobs| blobs.revision), + seen_blob_seq: 0, + resync_all_blobs: false, last_synced_store_rev: entry.revision, last_synced_store_sv: entry.session.encode_state_vector_v1().unwrap_or_default(), last_seen_view_rev: view_rev, @@ -495,7 +459,6 @@ impl DesktopEditorHost { view, doc_id, &update.unwrap_or_default(), - &[], cx, )) } else { @@ -1001,6 +964,59 @@ pub(crate) mod tests { } } + #[test] + fn memory_workspace_replacement_reaches_mounted_peer_and_new_peek() { + use crate::split_view::DocViewMode; + use std::sync::Arc; + + let state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-01"); + let (_, app, wh, _) = open_test_shell(state, 1280, 680); + app.update(|cx| { + wh.update(cx, |shell, _, cx| { + let store = &mut shell.state_mut().store; + let mut host = super::DesktopEditorHost::new(); + let mut pane = |host: &mut super::DesktopEditorHost, id| { + host.ensure_pane_editor( + id, + "doc-arch", + DocViewMode::Page, + ThemeMode::Light, + 0.0, + 0.0, + 640.0, + 680.0, + store, + cx, + ) + .unwrap() + }; + let source = pane(&mut host, 0); + let peer = pane(&mut host, 1); + for byte in [1, 2] { + let bytes = Arc::new(vec![byte]); + source.update(cx, |view, cx| { + view.edit_document(cx, |doc| { + doc.blobs.insert("upload".into(), bytes.clone()); + }); + }); + assert!(host.sync_all(store, cx)); + assert!(Arc::ptr_eq( + &peer.read(cx).document().blobs["upload"], + &bytes + )); + assert!(!host.sync_all(store, cx)); + } + let peek = host + .ensure_peek_editor("doc-arch", ThemeMode::Light, 640.0, 680.0, store, cx) + .unwrap(); + assert_eq!(peek.read(cx).document().blobs["upload"].as_slice(), [2]); + let cache = &host.workspace_blobs[&store.active_workspace().id]; + assert_eq!(cache.entries.len(), 1); + }) + .unwrap(); + }); + } + #[test] fn clicking_peek_body_moves_keyboard_input_to_the_peek_editor() { use blocksuite_playground_doc::read::BlockContent; diff --git a/packages/frontend/desktop/src/workbench/local_workspace.rs b/packages/frontend/desktop/src/workbench/local_workspace.rs index 70e6a7741c..8b2f39b9fc 100644 --- a/packages/frontend/desktop/src/workbench/local_workspace.rs +++ b/packages/frontend/desktop/src/workbench/local_workspace.rs @@ -10,10 +10,10 @@ //! changes, and whenever the host asks with [`LocalWorkspaces::save`]. use std::{ - cell::{Cell, RefCell}, - collections::{BTreeMap, btree_map::Entry}, + cell::RefCell, + collections::BTreeMap, rc::Rc, - sync::{Arc, Mutex, Weak}, + sync::{Arc, Mutex}, time::Duration, }; @@ -24,8 +24,7 @@ use affine_store::{ }; use anyhow::{Context as _, Result, anyhow}; use blocksuite_playground_doc::{session::PageDocSession, try_random_client_id}; -use playground::PlaygroundView; -use ui::{Context, Entity, EntityId, Subscription}; +use ui::Context; use ui_tokens::ThemeMode; use super::{DesktopAppState, DesktopShellView}; @@ -95,8 +94,6 @@ struct LocalBlobs { submitted: StoredBlobs, pending: StoredBlobs, paused: bool, - // The editor host can give a newly mounted editor an older shared buffer. - replaced: BTreeMap>>>, } /// The sessions of the local workspaces and the store that keeps them. @@ -172,21 +169,16 @@ impl LocalWorkspaces { blobs.pending.is_empty() } - fn record_blob(&self, workspace_id: &str, blob_id: String, bytes: Arc>) { + pub(crate) fn record_blob(&self, workspace_id: &str, blob_id: String, bytes: Arc>) { if let Some(local) = self.sessions.get(workspace_id) { let mut blobs = local.blobs.borrow_mut(); - if let Some(previous) = blobs + if blobs .pending .get(&blob_id) .or_else(|| blobs.submitted.get(&blob_id)) + == Some(&bytes) { - if previous == &bytes { - return; - } - let previous = Arc::downgrade(previous); - let replaced = blobs.replaced.entry(blob_id.clone()).or_default(); - replaced.retain(|bytes| bytes.strong_count() > 0); - replaced.push(previous); + return; } blobs.pending.insert(blob_id, bytes); blobs.paused = false; @@ -213,10 +205,6 @@ pub(super) struct LocalBinding { bound: Option, saved: Option, _timer: ui::Task<()>, - _shell_observer: Subscription, - editors: BTreeMap, - after_render: Box, - syncing_media: bool, } /// Merge the stored frames of one document into one update. @@ -445,6 +433,7 @@ impl DesktopShellView { .filter(|_| !readonly) .map(|(id, session)| { let submitted = initial_blobs.remove(&id).unwrap_or_default(); + self.editor_host.seed_workspace_blobs(&id, &submitted); let local = LocalSession { session: Arc::new(Mutex::new(session)), pending: PendingUpdates::default(), @@ -452,7 +441,6 @@ impl DesktopShellView { submitted, pending: StoredBlobs::new(), paused: false, - replaced: BTreeMap::new(), }), deferred: RefCell::default(), }; @@ -472,33 +460,11 @@ impl DesktopShellView { if readonly { return workspaces; } - let shell = cx.entity(); - let weak_shell = shell.downgrade(); - let executor = cx.foreground_executor().clone(); - let app = cx.to_async(); - let scheduled = Rc::new(Cell::new(false)); - let after_render = Box::new(move || { - if scheduled.replace(true) { - return; - } - let scheduled = scheduled.clone(); - let shell = weak_shell.clone(); - let mut app = app.clone(); - executor - .spawn(async move { - scheduled.set(false); - let _ = shell.update(&mut app, |shell, cx| shell.observe_local_editors(cx)); - }) - .detach(); - }); + self.editor_host.bind_local_media(&workspaces, cx); self.local = Some(LocalBinding { workspaces: workspaces.clone(), bound: None, saved: None, - _shell_observer: cx.observe(&shell, |shell, _, cx| shell.observe_local_editors(cx)), - editors: BTreeMap::new(), - after_render, - syncing_media: false, _timer: cx.spawn(async move |view, cx| { loop { clock.timer(Self::LOCAL_SAVE_INTERVAL).await; @@ -511,130 +477,15 @@ impl DesktopShellView { } }), }); - self.observe_local_editors(cx); self.save_local_workspaces(); workspaces } pub(crate) fn save_mounted_local_media(&mut self, cx: &mut Context, flush: bool) { - self.observe_local_editors(cx); + self.editor_host.sync_blobs(&self.state.store, cx); self.save_local_workspaces_with(flush); } - fn mounted_local_editors(&self) -> Vec> { - self.state - .split - .panes - .iter() - .filter_map(|pane| self.editor_host.pane_entity(pane.id)) - .chain(self.editor_host.peek_entity()) - .collect() - } - - fn observe_local_editors(&mut self, cx: &mut Context) { - let editors = self.mounted_local_editors(); - let Some(local) = &mut self.local else { - return; - }; - local - .editors - .retain(|id, _| editors.iter().any(|editor| editor.entity_id() == *id)); - let mut mounted = Vec::new(); - for editor in editors { - if let Entry::Vacant(entry) = local.editors.entry(editor.entity_id()) { - entry.insert(cx.observe(&editor, |shell, editor, cx| { - shell.sync_local_media_from(&editor, false, cx); - })); - mounted.push(editor); - } - } - for editor in mounted { - self.sync_local_media_from(&editor, true, cx); - } - } - - fn sync_local_media_from( - &mut self, - source: &Entity, - mounted: bool, - cx: &mut Context, - ) { - let Some(local) = self.local.as_ref().filter(|local| !local.syncing_media) else { - return; - }; - let doc = source.read(cx).document(); - let workspace_id = doc.workspace.room(); - let Some(session) = local.workspaces.sessions.get(workspace_id) else { - return; - }; - let (changes, corrections) = { - let blobs = session.blobs.borrow(); - let mut changes = StoredBlobs::new(); - let mut corrections = StoredBlobs::new(); - for (id, bytes) in &doc.blobs { - let current = blobs.pending.get(id).or_else(|| blobs.submitted.get(id)); - if current == Some(bytes) { - continue; - } - if blobs.replaced.get(id).is_some_and(|older| { - older - .iter() - .any(|old| old.upgrade().is_some_and(|old| Arc::ptr_eq(&old, bytes))) - }) { - if let Some(current) = current { - corrections.insert(id.clone(), current.clone()); - } - } else { - changes.insert(id.clone(), bytes.clone()); - } - } - if mounted { - corrections.extend(blobs.submitted.clone()); - corrections.extend(blobs.pending.clone()); - corrections.extend(changes.clone()); - } - (changes, corrections) - }; - if changes.is_empty() && corrections.is_empty() { - return; - } - let workspace_id = workspace_id.to_owned(); - for (id, bytes) in &changes { - local - .workspaces - .record_blob(&workspace_id, id.clone(), bytes.clone()); - } - - let editors = self.mounted_local_editors(); - if let Some(local) = &mut self.local { - local.syncing_media = true; - } - for editor in editors { - let doc = editor.read(cx).document(); - if doc.workspace.room() != workspace_id { - continue; - } - let bytes = if editor == *source { - &corrections - } else { - &changes - }; - let changed: Vec<_> = bytes - .iter() - .filter(|(id, bytes)| doc.blobs.get(*id) != Some(*bytes)) - .map(|(id, bytes)| (id.clone(), bytes.clone())) - .collect(); - if !changed.is_empty() { - editor.update(cx, |editor, cx| { - editor.edit_document(cx, |doc| doc.blobs.extend(changed)); - }); - } - } - if let Some(local) = &mut self.local { - local.syncing_media = false; - } - } - /// Bind the session of the active workspace as its writer, write every queued update /// and deletion to the store, and remember the open document. pub(crate) fn save_local_workspaces(&mut self) { @@ -677,8 +528,6 @@ impl DesktopShellView { let Some(local) = &self.local else { return; }; - // This method runs before the shell mounts the editors for the new frame. - (local.after_render)(); let store = &self.state.store; let doc = self.state.split.active().active_route().doc_id(); let unchanged = local.saved.as_ref().is_some_and(|(id, rev, saved_doc)| { @@ -698,11 +547,22 @@ mod tests { use affine_store::directory::DocMode; use blocksuite_playground_doc::read::BlockContent; - use ui::{AppContext as _, Application, HeadlessPlatform}; + use ui::{AppContext as _, Application, Entity, HeadlessPlatform}; use super::*; use crate::showcase::SHOWCASE_WORKSPACE_IDS; + fn mounted_editors(shell: &DesktopShellView) -> Vec> { + shell + .state + .split + .panes + .iter() + .filter_map(|pane| shell.editor_host.pane_entity(pane.id)) + .chain(shell.editor_host.peek_entity()) + .collect() + } + const NOW_MS: i64 = 1_764_400_000_000; const SCRATCH: &str = SHOWCASE_WORKSPACE_IDS[1]; @@ -711,6 +571,7 @@ mod tests { workspaces: RefCell, route: RefCell)>>, blobs: RefCell>, + blob_dir: Option, fail_blob: std::cell::Cell, blob_attempts: std::cell::Cell, writes: RefCell>, @@ -733,6 +594,22 @@ mod tests { } fn load_blobs(&self, workspace_id: &str) -> StoredBlobs { + if let Some(dir) = &self.blob_dir { + let dir = dir.join(workspace_id); + return match std::fs::read_dir(dir) { + Ok(entries) => entries + .map(|entry| { + let entry = entry.unwrap(); + let bytes = std::fs::read(entry.path()).unwrap(); + (entry.file_name().into_string().unwrap(), Arc::new(bytes)) + }) + .collect(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + StoredBlobs::new() + } + Err(error) => panic!("{error}"), + }; + } self.blobs .borrow() .get(workspace_id) @@ -748,6 +625,12 @@ mod tests { self.writes .borrow_mut() .push(("blob", workspace_id.to_owned())); + if let Some(dir) = &self.blob_dir { + let dir = dir.join(workspace_id); + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join(blob_id), bytes)?; + return Ok(()); + } self.blobs .borrow_mut() .entry(workspace_id.to_owned()) @@ -1095,6 +978,142 @@ mod tests { }); } + #[cfg(not(target_family = "wasm"))] + #[test] + fn first_pane_mount_has_all_stored_workspace_media() { + use crate::{editor_host::tests::open_test_shell, split_view::DocViewMode}; + + let local = Rc::new(MemoryStore::default()); + local + .put_blob(SHOWCASE_WORKSPACE_ID, "first", &[1, 2]) + .unwrap(); + local + .put_blob(SHOWCASE_WORKSPACE_ID, "second", &[3, 4]) + .unwrap(); + let (state, sessions) = open(&local); + let (_, app, window, _) = open_test_shell(state, 1280, 800); + app.update(|cx| { + window + .update(cx, |shell, _, cx| { + shell.bind_local_workspaces(sessions, local.clone(), NOW_MS, cx); + shell.state.open_doc_in_split("doc-arch"); + let editor = shell + .editor_host + .ensure_pane_editor( + shell.state.split.active().id, + "doc-arch", + DocViewMode::Page, + ThemeMode::Light, + 0.0, + 0.0, + 640.0, + 800.0, + &mut shell.state.store, + cx, + ) + .unwrap(); + let blobs = &editor.read(cx).document().blobs; + let stored = local.load_blobs(SHOWCASE_WORKSPACE_ID); + assert_eq!(blobs.len(), stored.len()); + for (source, bytes) in stored { + assert!(Arc::ptr_eq(&blobs[&source], &bytes)); + } + }) + .unwrap(); + }); + assert_eq!(local.blob_attempts.get(), 2); + } + + #[cfg(not(target_family = "wasm"))] + #[test] + fn closing_new_split_in_same_turn_saves_media_on_timer_and_cold_reopen() { + use crate::{editor_host::tests::open_test_shell, split_view::DocViewMode}; + + const DOC: &str = "doc-arch"; + const SOURCE: &str = "same-turn-upload"; + const BYTES: &[u8] = &[4, 2, 7]; + + let local = Rc::new(MemoryStore::default()); + { + let (mut state, sessions) = open(&local); + state.navigate_active_pane(crate::split_view::DesktopRoute::AllDocs); + let (platform, app, window, _) = open_test_shell(state, 1280, 800); + app.update(|cx| { + window + .update(cx, |shell, _, cx| { + shell.bind_local_workspaces(sessions, local.clone(), NOW_MS, cx); + }) + .unwrap(); + }); + platform.run_until_parked(); + app.update(|cx| { + window + .update(cx, |shell, window, cx| { + shell.state.open_doc_in_split(DOC); + let pane_index = shell.state.split.active_pane; + let pane_id = shell.state.split.active().id; + let editor = shell + .editor_host + .ensure_pane_editor( + pane_id, + DOC, + DocViewMode::Page, + ThemeMode::Light, + 0.0, + 0.0, + 640.0, + 800.0, + &mut shell.state.store, + cx, + ) + .unwrap(); + editor.update(cx, |editor, cx| { + editor.edit_document(cx, |doc| { + doc.blobs.insert(SOURCE.into(), Arc::new(BYTES.to_vec())); + }); + }); + assert!(shell.state.split.close_pane(pane_index)); + let _ = ui::Render::render(shell, window, cx); + assert!(shell.editor_host.pane_entity(pane_id).is_none()); + }) + .unwrap(); + }); + assert!(local.load_blobs(SHOWCASE_WORKSPACE_ID).is_empty()); + platform.advance_clock(DesktopShellView::LOCAL_SAVE_INTERVAL); + platform.run_until_parked(); + assert_eq!( + local.load_blobs(SHOWCASE_WORKSPACE_ID)[SOURCE].as_slice(), + BYTES + ); + } + + let (state, sessions) = open(&local); + let (_, app, window, _) = open_test_shell(state, 1280, 800); + app.update(|cx| { + window + .update(cx, |shell, _, cx| { + shell.bind_local_workspaces(sessions, local.clone(), NOW_MS, cx); + let editor = shell + .editor_host + .ensure_pane_editor( + shell.state.split.active().id, + DOC, + DocViewMode::Page, + ThemeMode::Light, + 0.0, + 0.0, + 1280.0, + 800.0, + &mut shell.state.store, + cx, + ) + .unwrap(); + assert_eq!(editor.read(cx).document().blobs[SOURCE].as_slice(), BYTES); + }) + .unwrap(); + }); + } + #[cfg(not(target_family = "wasm"))] #[test] fn same_source_replacement_updates_both_panes_and_survives_cold_reopen() { @@ -1170,7 +1189,7 @@ mod tests { app.update(|cx| { window .update(cx, |shell, window, cx| { - for editor in shell.mounted_local_editors() { + for editor in mounted_editors(shell) { assert_eq!( editor.read(cx).document().blobs[SOURCE].as_slice(), LAST @@ -1197,7 +1216,7 @@ mod tests { app.update(|cx| { window .update(cx, |shell, _, cx| { - let editors = shell.mounted_local_editors(); + let editors = mounted_editors(shell); assert_eq!(editors.len(), 2); for editor in editors { assert_eq!(editor.read(cx).document().blobs[SOURCE].as_slice(), LAST); @@ -1208,6 +1227,104 @@ mod tests { } } + #[cfg(not(target_family = "wasm"))] + #[test] + fn same_turn_media_writes_use_the_last_writer_in_panes_peek_and_local_storage() { + use crate::editor_host::tests::open_test_shell; + + const DOC: &str = "doc-arch"; + const SOURCE: &str = "same-turn-peer-media"; + const FIRST: &[u8] = &[1]; + const LAST: &[u8] = &[2]; + const PEEK: usize = 2; + + let root = std::env::temp_dir().join(format!( + "affine-desktop-same-turn-blobs-{}", + std::process::id() + )); + std::fs::create_dir(&root).unwrap(); + for (first, last) in [(PEEK, 0), (0, PEEK), (0, 1), (1, 0)] { + let blob_dir = root.join(format!("{first}-{last}")); + let open_store = || { + Rc::new(MemoryStore { + blob_dir: Some(blob_dir.clone()), + ..MemoryStore::default() + }) + }; + let open_shell = |local: Rc| { + let (mut state, sessions) = open(&local); + state.open_doc_in_split(DOC); + state.open_peek_view(DOC); + let (platform, app, window, headless) = open_test_shell(state, 1280, 800); + app.update(|cx| { + window + .update(cx, |shell, _, cx| { + shell.bind_local_workspaces(sessions, local.clone(), NOW_MS, cx); + }) + .unwrap(); + }); + headless.request_frame(); + platform.run_until_parked(); + (platform, app, window) + }; + let assert_editors = |shell: &DesktopShellView, cx: &ui::App| { + let editors = mounted_editors(shell); + assert_eq!(editors.len(), 3); + for (index, editor) in editors.iter().enumerate() { + assert_eq!( + editor.read(cx).document().blobs[SOURCE].as_slice(), + LAST, + "editor {index} after writes from {first} then {last}" + ); + } + }; + + { + let local = open_store(); + let (platform, app, window) = open_shell(local.clone()); + app.update(|cx| { + window + .update(cx, |shell, _, cx| { + let editors = mounted_editors(shell); + assert_eq!(editors.len(), 3); + for (index, bytes) in [(first, FIRST), (last, LAST)] { + editors[index].update(cx, |editor, cx| { + editor.edit_document(cx, |doc| { + doc.blobs.insert(SOURCE.into(), Arc::new(bytes.to_vec())); + }); + }); + } + }) + .unwrap(); + }); + platform.advance_clock(DesktopShellView::LOCAL_SAVE_INTERVAL); + platform.run_until_parked(); + assert_eq!( + std::fs::read(blob_dir.join(SHOWCASE_WORKSPACE_ID).join(SOURCE)).unwrap(), + LAST, + "stored bytes after writes from {first} then {last}" + ); + assert_eq!(local.blob_attempts.get(), 1); + app.update(|cx| { + window + .update(cx, |shell, window, cx| { + assert_editors(shell, cx); + window.remove_window(); + }) + .unwrap(); + }); + } + + let (_, app, window) = open_shell(open_store()); + app.update(|cx| { + window + .update(cx, |shell, _, cx| assert_editors(shell, cx)) + .unwrap(); + }); + } + std::fs::remove_dir_all(root).unwrap(); + } + #[cfg(not(target_family = "wasm"))] #[tokio::test] async fn read_only_sqlite_workspace_never_binds_a_local_writer() { diff --git a/packages/frontend/desktop/src/workbench/mod.rs b/packages/frontend/desktop/src/workbench/mod.rs index 756a8ae4ca..25981f73d7 100644 --- a/packages/frontend/desktop/src/workbench/mod.rs +++ b/packages/frontend/desktop/src/workbench/mod.rs @@ -12,6 +12,7 @@ mod topbar; #[cfg(test)] mod peek_lifecycle_tests; +pub(crate) use local_workspace::StoredBlobs; pub use local_workspace::{LocalDocStore, LocalWorkspaces, StoredDocs, StoredWorkspaces}; use blocksuite_editor::inline_input::Utf16ImeBuffer; @@ -221,8 +222,14 @@ impl DesktopShellView { /// Synchronize live CRDT edits across all mounted `Entity` panes. pub fn sync_editors(&mut self, cx: &mut Context) { + self.sync_mounted_editors(cx); + } + + fn sync_mounted_editors(&mut self, cx: &mut Context) -> bool { + // Collect media before a closed pane or deleted page can lose its editor. + let media_changed = self.editor_host.sync_blobs(&self.state.store, cx); self.editor_host.retain_openable_editors(&self.state, cx); - self.editor_host.sync_all(&mut self.state.store, cx); + self.editor_host.sync_documents(&mut self.state.store, cx) | media_changed } pub(crate) fn open_block_link( @@ -274,8 +281,7 @@ impl DesktopShellView { /// Flush any mounted `Entity` edits into `DesktopDocStore` and fan out /// to sibling panes/outline/topbar immediately when an observed editor changes. pub(crate) fn sync_editors_from_observer(&mut self, cx: &mut Context) { - self.editor_host.retain_openable_editors(&self.state, cx); - if self.editor_host.sync_all(&mut self.state.store, cx) { + if self.sync_mounted_editors(cx) { cx.notify(); } }