Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(config-sync): report what a running sync is doing

vastsa3073a02d0519
diff --git a/crates/host-core/src/config_sync/coordinator.rs b/crates/host-core/src/config_sync/coordinator.rs
index 598eced84..46ffdbc1e 100644
--- a/crates/host-core/src/config_sync/coordinator.rs
+++ b/crates/host-core/src/config_sync/coordinator.rs
@@ -1,15 +1,17 @@
use super::*;
-struct SyncProgress(Arc<AtomicBool>);
+/// Keeps "a sync is running" true for as long as the run lives, and clears it
+/// however the run ends, so an early return cannot leave the flag set.
+struct SyncRunGuard(Arc<AtomicBool>);
-impl SyncProgress {
+impl SyncRunGuard {
fn start(flag: Arc<AtomicBool>) -> Self {
flag.store(true, Ordering::Relaxed);
Self(flag)
}
}
-impl Drop for SyncProgress {
+impl Drop for SyncRunGuard {
fn drop(&mut self) {
self.0.store(false, Ordering::Relaxed);
}
@@ -18,6 +20,7 @@ impl Drop for SyncProgress {
pub(super) async fn sync_once(
state: &Arc<Mutex<AppState>>,
tx: &mpsc::UnboundedSender<String>,
+ observer: &dyn SyncProgressObserver,
) -> Result<()> {
let lock = {
let st = state.lock().await;
@@ -26,7 +29,7 @@ pub(super) async fn sync_once(
let _guard = lock.lock().await;
let progress = {
let st = state.lock().await;
- SyncProgress::start(st.config_sync_in_progress.clone())
+ SyncRunGuard::start(st.config_sync_in_progress.clone())
};
let _progress = progress;
{
@@ -52,6 +55,7 @@ pub(super) async fn sync_once(
false
};
let base = load_base(&st, &key)?;
+ observer.report(SyncProgress::started(SyncPhase::Capture));
let mut local = domains::capture(
&mut st,
&key,
@@ -61,6 +65,13 @@ pub(super) async fn sync_once(
&identity_overrides(&config),
)?;
let local_digest = domains::snapshot_digest(&local);
+ observer.report(SyncProgress::counted(
+ SyncPhase::Capture,
+ local.manifest.entities.len() as u64,
+ local.manifest.entities.len() as u64,
+ 0,
+ 0,
+ ));
if pending_waiting_for_approval
&& config.last_local_digest.as_deref() == Some(local_digest.as_str())
{
@@ -81,55 +92,59 @@ pub(super) async fn sync_once(
};
let transport = transport_with_password(&config, transport_password)?;
ensure_remote_collections(&transport, &config).await?;
- let (remote_head, remote, remote_resources, remote_parent_ids, remote_conflicts) =
- if config.remote_mode == RemoteMode::AppendOnly {
- let append_only = read_append_only_remote(&transport, &config, &key).await?;
- if let Some(append_only) = append_only {
- let remote_merge = merge_append_only_tips(base.as_ref(), &append_only.tips)?;
- let remote = RevisionManifest {
- format: REVISION_FORMAT.into(),
- version: 1,
- revision_id: append_only
- .tip_ids
- .first()
- .cloned()
- .unwrap_or_else(|| "remote-merge".into()),
- parents: append_only.tip_ids.clone(),
- created_at: Utc::now().to_rfc3339(),
- entities: remote_merge.entities,
- resource_ids: append_only.resources.keys().cloned().collect(),
- };
- (
- None,
- Some(remote),
- append_only.resources,
- append_only.tip_ids,
- remote_merge.conflicts,
- )
- } else {
- (None, None, BTreeMap::new(), Vec::new(), Vec::new())
- }
- } else {
- let remote_head = read_remote_head(&transport, &config, &key).await?;
- let (remote, remote_resources) = if let Some((head, _)) = remote_head.as_ref() {
- let value =
- read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
- (Some(value.0), value.1)
- } else {
- (None, BTreeMap::new())
+ let (remote_head, remote, remote_resources, remote_parent_ids, remote_conflicts) = if config
+ .remote_mode
+ == RemoteMode::AppendOnly
+ {
+ let append_only = read_append_only_remote(&transport, &config, &key, observer).await?;
+ if let Some(append_only) = append_only {
+ let remote_merge = merge_append_only_tips(base.as_ref(), &append_only.tips)?;
+ let remote = RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: append_only
+ .tip_ids
+ .first()
+ .cloned()
+ .unwrap_or_else(|| "remote-merge".into()),
+ parents: append_only.tip_ids.clone(),
+ created_at: Utc::now().to_rfc3339(),
+ entities: remote_merge.entities,
+ resource_ids: append_only.resources.keys().cloned().collect(),
};
- let parent_ids = remote_head
- .as_ref()
- .map(|(head, _)| vec![head.revision_id.clone()])
- .unwrap_or_default();
(
- remote_head,
- remote,
- remote_resources,
- parent_ids,
- Vec::new(),
+ None,
+ Some(remote),
+ append_only.resources,
+ append_only.tip_ids,
+ remote_merge.conflicts,
)
+ } else {
+ (None, None, BTreeMap::new(), Vec::new(), Vec::new())
+ }
+ } else {
+ let remote_head = read_remote_head(&transport, &config, &key).await?;
+ let (remote, remote_resources) = if let Some((head, _)) = remote_head.as_ref() {
+ let value =
+ read_remote_revision(&transport, &config, &key, &head.revision_id, observer)
+ .await?;
+ (Some(value.0), value.1)
+ } else {
+ (None, BTreeMap::new())
};
+ let parent_ids = remote_head
+ .as_ref()
+ .map(|(head, _)| vec![head.revision_id.clone()])
+ .unwrap_or_default();
+ (
+ remote_head,
+ remote,
+ remote_resources,
+ parent_ids,
+ Vec::new(),
+ )
+ };
+ observer.report(SyncProgress::started(SyncPhase::Merge));
let merge::MergeResult {
entities: local_entities,
conflicts: local_conflicts,
@@ -144,6 +159,13 @@ pub(super) async fn sync_once(
let can_skip_publication =
config.remote_mode == RemoteMode::Strict || remote_parent_ids.len() <= 1;
if can_skip_publication {
+ observer.report(SyncProgress::counted(
+ SyncPhase::Merge,
+ merged.entities.len() as u64,
+ merged.entities.len() as u64,
+ 0,
+ 0,
+ ));
if let (Some(remote), true) = (remote.as_ref(), !remote_parent_ids.is_empty()) {
// Skip publication when the acknowledged base, current local
// snapshot, and remote head agree for every subscribed domain.
@@ -190,7 +212,7 @@ pub(super) async fn sync_once(
},
resources,
};
- upload_snapshot(&transport, &config, &key, &candidate).await?;
+ upload_snapshot(&transport, &config, &key, &candidate, observer).await?;
let published = if config.remote_mode == RemoteMode::AppendOnly {
publish_append_only_head(
&transport,
@@ -250,6 +272,8 @@ pub(super) async fn sync_once(
journal_state: "applying".into(),
remote_revision_id: candidate_revision_id,
};
+ observer.report(SyncProgress::started(SyncPhase::Apply));
+ let applied_entities = apply_bundle_state.manifest.entities.len() as u64;
apply_bundle(
state,
&mut next_config,
@@ -259,7 +283,15 @@ pub(super) async fn sync_once(
&apply_bundle_state,
)
.await?;
+ observer.report(SyncProgress::counted(
+ SyncPhase::Apply,
+ applied_entities,
+ applied_entities,
+ 0,
+ 0,
+ ));
if config.remote_mode == RemoteMode::Strict {
+ observer.report(SyncProgress::started(SyncPhase::Cleanup));
if let Err(error) = cleanup_history(state, &transport, &config, &key).await {
tracing::warn!(error = %error, "config sync history cleanup failed after sync");
}
@@ -271,11 +303,25 @@ pub(super) async fn sync_once(
bail!("CONFIG_SYNC_CONFLICT: remote head changed while publishing")
}
+/// Runs one sync driven by the user: the manual path, with progress carried to
+/// the renderer as `configSync.progress`.
pub(crate) async fn sync_now(
state: Arc<Mutex<AppState>>,
tx: mpsc::UnboundedSender<String>,
) -> Result<Value> {
- if let Err(error) = sync_once(&state, &tx).await {
+ let observer = ProgressNotifier::new(tx.clone());
+ sync_now_with(state, tx, &observer).await
+}
+
+/// Runs one sync with the observer the caller installed, and records the same
+/// failure bookkeeping either way: a background poll and a manual run must not
+/// differ in what they record about a failure.
+pub(crate) async fn sync_now_with(
+ state: Arc<Mutex<AppState>>,
+ tx: mpsc::UnboundedSender<String>,
+ observer: &dyn SyncProgressObserver,
+) -> Result<Value> {
+ if let Err(error) = sync_once(&state, &tx, observer).await {
let mut st = state.lock().await;
if let Some(mut config) = load_config(&st)? {
mark_error(&mut config, &error);
@@ -291,7 +337,6 @@ pub(crate) async fn sync_now(
}
get_state(state).await
}
-
/// Run the configured foreground/background poll. The host process owns this
/// task so the renderer and Electron main never become a second scheduler.
pub(crate) async fn sync_if_enabled(
@@ -367,7 +412,7 @@ pub(crate) async fn sync_if_enabled(
}
};
if should_sync {
- sync_now(state, tx).await.map(|_| ())
+ sync_now_with(state, tx, &NoSyncProgress).await.map(|_| ())
} else {
Ok(())
}
diff --git a/crates/host-core/src/config_sync/engine.rs b/crates/host-core/src/config_sync/engine.rs
index ac7c2280d..e25a21fab 100644
--- a/crates/host-core/src/config_sync/engine.rs
+++ b/crates/host-core/src/config_sync/engine.rs
@@ -31,6 +31,8 @@ mod coordinator;
mod handlers;
#[path = "engine_history.rs"]
mod history;
+#[path = "progress.rs"]
+mod progress;
#[path = "engine_remote.rs"]
mod remote;
#[cfg(test)]
@@ -42,6 +44,7 @@ pub(crate) use handlers::{
reject, restore, test, unlock,
};
use history::cleanup_history;
+use progress::{NoSyncProgress, ProgressNotifier, SyncPhase, SyncProgress, SyncProgressObserver};
use remote::{
ensure_remote_collections, merge_append_only_tips, object_path, publish_append_only_head,
publish_head, read_append_only_remote, read_remote_head, read_remote_manifest,
@@ -1225,7 +1228,7 @@ mod tests {
let config = load_config(&state)?.expect("configured device");
let key = local_vault_key(&state, &config)?.expect("unlocked device");
let transport = transport_with_password(&config, String::new())?;
- let remote = read_append_only_remote(&transport, &config, &key)
+ let remote = read_append_only_remote(&transport, &config, &key, &NoSyncProgress)
.await?
.expect("compatibility revisions");
assert!(!remote.tip_ids.is_empty());
@@ -1248,6 +1251,41 @@ mod tests {
vec![b'x'; 256 * 1024]
}
+ /// Records what a sync reported, in order, so a test can assert the phases
+ /// an interface is shown.
+ #[derive(Default)]
+ struct RecordedProgress(std::sync::Mutex<Vec<SyncProgress>>);
+
+ impl SyncProgressObserver for RecordedProgress {
+ fn report(&self, progress: SyncProgress) {
+ self.0
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .push(progress);
+ }
+ }
+
+ impl RecordedProgress {
+ fn phases(&self) -> Vec<SyncPhase> {
+ self.0
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .iter()
+ .map(|progress| progress.phase)
+ .collect()
+ }
+
+ fn last(&self, phase: SyncPhase) -> Option<SyncProgress> {
+ self.0
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .iter()
+ .rev()
+ .find(|progress| progress.phase == phase)
+ .copied()
+ }
+ }
+
#[tokio::test]
async fn two_devices_sync_credentials_capabilities_and_disjoint_edit() -> Result<()> {
if run_in_isolated_process(
@@ -1358,7 +1396,34 @@ mod tests {
}
let (tx, _rx) = mpsc::unbounded_channel();
- let initial_a_state = sync_now(device_a.clone(), tx.clone()).await?;
+ let progress = RecordedProgress::default();
+ coordinator::sync_once(&device_a, &tx, &progress).await?;
+ let initial_a_state = get_state(device_a.clone()).await?;
+ let phases = progress.phases();
+ assert_eq!(
+ phases.first(),
+ Some(&SyncPhase::Capture),
+ "a sync reports what it is doing from its first phase: {phases:?}"
+ );
+ for (before, after) in [
+ (SyncPhase::Capture, SyncPhase::Merge),
+ (SyncPhase::Merge, SyncPhase::Upload),
+ (SyncPhase::Upload, SyncPhase::Apply),
+ ] {
+ let before_at = phases.iter().position(|phase| *phase == before);
+ let after_at = phases.iter().position(|phase| *phase == after);
+ assert!(
+ matches!((before_at, after_at), (Some(left), Some(right)) if left < right),
+ "{before:?} must be reported before {after:?}: {phases:?}"
+ );
+ }
+ let upload = progress
+ .last(SyncPhase::Upload)
+ .expect("upload progress for a fresh device");
+ assert!(upload.total >= 2, "upload total: {upload:?}");
+ assert_eq!(upload.done, upload.total, "upload finished: {upload:?}");
+ assert!(upload.bytes_total > 0, "upload bytes: {upload:?}");
+ assert_eq!(upload.bytes_done, upload.bytes_total);
assert!(pending_approvals(&initial_a_state).is_empty());
{
let state = device_a.lock().await;
@@ -1374,8 +1439,14 @@ mod tests {
let (head, _) = read_remote_head(&transport, &config, &key)
.await?
.expect("remote head");
- let (remote, _) =
- read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
+ let (remote, _) = read_remote_revision(
+ &transport,
+ &config,
+ &key,
+ &head.revision_id,
+ &NoSyncProgress,
+ )
+ .await?;
assert!(!remote.entities.is_empty(), "remote entities missing");
assert!(
load_base(&state, &key)?.is_none(),
@@ -1519,8 +1590,14 @@ mod tests {
let (head, _) = read_remote_head(&transport, &config, &key)
.await?
.expect("remote head after device B edit");
- let (remote, _) =
- read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
+ let (remote, _) = read_remote_revision(
+ &transport,
+ &config,
+ &key,
+ &head.revision_id,
+ &NoSyncProgress,
+ )
+ .await?;
let remote_theme = remote
.entities
.iter()
diff --git a/crates/host-core/src/config_sync/engine_history.rs b/crates/host-core/src/config_sync/engine_history.rs
index a128e718d..87c6ea892 100644
--- a/crates/host-core/src/config_sync/engine_history.rs
+++ b/crates/host-core/src/config_sync/engine_history.rs
@@ -130,7 +130,9 @@ pub(super) async fn list_history(state: Arc<Mutex<AppState>>) -> Result<Value> {
};
let transport = transport_with_password(&config, transport_password)?;
if config.remote_mode == RemoteMode::AppendOnly {
- let Some(remote) = read_append_only_remote(&transport, &config, &key).await? else {
+ let Some(remote) =
+ read_append_only_remote(&transport, &config, &key, &NoSyncProgress).await?
+ else {
return Ok(json!([]));
};
let current = remote.tip_ids.iter().cloned().collect::<BTreeSet<_>>();
@@ -327,7 +329,9 @@ pub(super) async fn restore(
};
let transport = transport_with_password(&config, transport_password)?;
let (parent_ids, current_etag) = if config.remote_mode == RemoteMode::AppendOnly {
- let Some(remote) = read_append_only_remote(&transport, &config, &key).await? else {
+ let Some(remote) =
+ read_append_only_remote(&transport, &config, &key, &NoSyncProgress).await?
+ else {
bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
};
if remote.tip_ids.is_empty() {
@@ -343,7 +347,7 @@ pub(super) async fn restore(
(vec![current_head.revision_id], Some(current_etag))
};
let (target, target_resources) =
- read_remote_revision(&transport, &config, &key, revision_id).await?;
+ read_remote_revision(&transport, &config, &key, revision_id, &NoSyncProgress).await?;
let candidate_id = Uuid::new_v4().to_string();
let candidate = LocalSnapshot {
manifest: RevisionManifest {
@@ -357,7 +361,7 @@ pub(super) async fn restore(
},
resources: target_resources,
};
- upload_snapshot(&transport, &config, &key, &candidate).await?;
+ upload_snapshot(&transport, &config, &key, &candidate, &NoSyncProgress).await?;
if config.remote_mode == RemoteMode::AppendOnly {
publish_append_only_head(&transport, &config, &key, &config.device_id, &candidate_id)
.await?;
diff --git a/crates/host-core/src/config_sync/engine_remote.rs b/crates/host-core/src/config_sync/engine_remote.rs
index 126ccd750..b4c817fa0 100644
--- a/crates/host-core/src/config_sync/engine_remote.rs
+++ b/crates/host-core/src/config_sync/engine_remote.rs
@@ -132,6 +132,7 @@ pub(super) async fn read_append_only_remote(
transport: &WebDavTransport,
config: &StoredConfig,
key: &VaultKey,
+ observer: &dyn SyncProgressObserver,
) -> Result<Option<AppendOnlyRemote>> {
let mut head_revision_ids = BTreeSet::new();
for device_id in transport
@@ -204,7 +205,7 @@ pub(super) async fn read_append_only_remote(
let mut resources = BTreeMap::new();
for revision_id in &tip_ids {
let (manifest, revision_resources) =
- read_remote_revision(transport, config, key, revision_id).await?;
+ read_remote_revision(transport, config, key, revision_id, observer).await?;
for (object_id, bytes) in revision_resources {
if let Some(existing) = resources.get(&object_id) {
if existing != &bytes {
@@ -291,6 +292,7 @@ pub(super) async fn read_remote_revision(
config: &StoredConfig,
key: &VaultKey,
revision_id: &str,
+ observer: &dyn SyncProgressObserver,
) -> Result<(RevisionManifest, BTreeMap<String, Vec<u8>>)> {
let manifest = read_remote_manifest(transport, config, key, revision_id).await?;
let mut resource_ids = BTreeSet::new();
@@ -300,7 +302,10 @@ pub(super) async fn read_remote_revision(
if resource_ids.len() > MAX_RESOURCES {
bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote revision references too many resources");
}
+ let total = resource_ids.len() as u64;
+ observer.report(SyncProgress::counted(SyncPhase::Download, 0, total, 0, 0));
let mut resources = BTreeMap::new();
+ let mut bytes_done = 0u64;
for object_id in resource_ids {
let path = object_path(config, &object_id)?;
let Some((ciphertext, _)) = transport.get(&path).await? else {
@@ -315,7 +320,15 @@ pub(super) async fn read_remote_revision(
if bytes.len() > MAX_REMOTE_RESOURCE_BYTES {
bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote resource is too large");
}
+ bytes_done = bytes_done.saturating_add(bytes.len() as u64);
resources.insert(object_id, bytes);
+ observer.report(SyncProgress::counted(
+ SyncPhase::Download,
+ resources.len() as u64,
+ total,
+ bytes_done,
+ 0,
+ ));
}
Ok((manifest, resources))
}
@@ -395,6 +408,7 @@ pub(super) async fn upload_snapshot(
config: &StoredConfig,
key: &VaultKey,
snapshot: &LocalSnapshot,
+ observer: &dyn SyncProgressObserver,
) -> Result<()> {
if snapshot.manifest.entities.len() > MAX_ENTITIES || snapshot.resources.len() > MAX_RESOURCES {
bail!("CONFIG_SYNC_LIMIT_EXCEEDED: local revision is too large");
@@ -417,6 +431,21 @@ pub(super) async fn upload_snapshot(
bail!("CONFIG_SYNC_LIMIT_EXCEEDED: local entity is too large or unsupported");
}
}
+ let total = snapshot.resources.len() as u64;
+ let bytes_total = snapshot
+ .resources
+ .values()
+ .map(|bytes| bytes.len() as u64)
+ .fold(0u64, u64::saturating_add);
+ let mut uploaded = 0u64;
+ let mut bytes_done = 0u64;
+ observer.report(SyncProgress::counted(
+ SyncPhase::Upload,
+ 0,
+ total,
+ 0,
+ bytes_total,
+ ));
for (object_id, bytes) in &snapshot.resources {
let path = object_path(config, object_id)?;
let encrypted = encrypt_object(
@@ -444,6 +473,15 @@ pub(super) async fn upload_snapshot(
if verified != *bytes {
bail!("CONFIG_SYNC_CRYPTO: immutable resource id collision");
}
+ uploaded = uploaded.saturating_add(1);
+ bytes_done = bytes_done.saturating_add(bytes.len() as u64);
+ observer.report(SyncProgress::counted(
+ SyncPhase::Upload,
+ uploaded,
+ total,
+ bytes_done,
+ bytes_total,
+ ));
}
let manifest_bytes = serialize_json(&snapshot.manifest)?;
let encrypted = encrypt_object(
diff --git a/crates/host-core/src/config_sync/progress.rs b/crates/host-core/src/config_sync/progress.rs
new file mode 100644
index 000000000..b039efa23
--- /dev/null
+++ b/crates/host-core/src/config_sync/progress.rs
@@ -0,0 +1,268 @@
+//! Progress a sync reports while it runs.
+//!
+//! A sync is one request: it captures the local snapshot, reads the remote
+//! revision, merges, uploads every resource object, publishes the head, applies
+//! the result and cleans up history. The caller hears back only at the end, and
+//! the upload is unbatched — one object per resource, two round trips each — so
+//! a vault with a few hundred resources looks like a frozen window unless the
+//! work reports itself. That is what a [`SyncProgressObserver`] is for.
+//!
+//! Nothing here knows about the interface on purpose. An observer is called by
+//! the sync; the one that ships is [`ProgressNotifier`], which writes the same
+//! NDJSON notification `configSync.changed` already uses, and tests install a
+//! recorder.
+
+use super::*;
+use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
+use std::time::{Duration, Instant};
+
+/// What a sync is doing right now.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum SyncPhase {
+ /// Collecting the local snapshot this device would publish.
+ Capture,
+ /// Reading the remote revision's resource objects.
+ Download,
+ /// Merging the acknowledged base, the local snapshot and the remote revision.
+ Merge,
+ /// Uploading the merged revision's resource objects.
+ Upload,
+ /// Writing the approved result locally.
+ Apply,
+ /// Deleting revisions the retention window no longer keeps.
+ Cleanup,
+}
+
+impl SyncPhase {
+ /// Wire name, and the name an interface shows.
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ SyncPhase::Capture => "capture",
+ SyncPhase::Download => "download",
+ SyncPhase::Merge => "merge",
+ SyncPhase::Upload => "upload",
+ SyncPhase::Apply => "apply",
+ SyncPhase::Cleanup => "cleanup",
+ }
+ }
+}
+
+/// One report from a sync.
+///
+/// `done`/`total` count this phase's units: resource objects while transferring,
+/// entities while capturing, merging or applying. `total == 0` means the phase
+/// cannot know its size ahead of time. `bytes_total == 0` means the byte size is
+/// unknown, which is the normal case for a download — remote manifests name
+/// resources by id, not by length.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct SyncProgress {
+ pub phase: SyncPhase,
+ pub done: u64,
+ pub total: u64,
+ pub bytes_done: u64,
+ pub bytes_total: u64,
+}
+
+impl SyncProgress {
+ /// A phase that started and cannot count itself.
+ pub(crate) fn started(phase: SyncPhase) -> Self {
+ Self::counted(phase, 0, 0, 0, 0)
+ }
+
+ /// A phase with the size it knows about.
+ pub(crate) fn counted(
+ phase: SyncPhase,
+ done: u64,
+ total: u64,
+ bytes_done: u64,
+ bytes_total: u64,
+ ) -> Self {
+ Self {
+ phase,
+ done,
+ total,
+ bytes_done,
+ bytes_total,
+ }
+ }
+}
+
+/// Where a sync reports what it is doing.
+pub(crate) trait SyncProgressObserver: Send + Sync {
+ fn report(&self, progress: SyncProgress);
+}
+
+/// A sync nobody is watching: the background scheduler, and every call site
+/// that has no interface to feed.
+pub(crate) struct NoSyncProgress;
+
+impl SyncProgressObserver for NoSyncProgress {
+ fn report(&self, _progress: SyncProgress) {}
+}
+
+/// Phase slot meaning "nothing reported yet".
+const NO_PHASE: u8 = u8::MAX;
+/// Timestamp meaning "nothing reported yet": a real measurement can be 0 ms, so
+/// 0 cannot be the sentinel.
+const NEVER_MS: u64 = u64::MAX;
+
+/// Reports progress to the renderer as `configSync.progress`.
+///
+/// Throttled on purpose: a large upload reports every object it writes, and an
+/// interface needs a few of those per second rather than thousands. A phase
+/// change always goes through, so a progress row never misses the transition it
+/// is displaying.
+pub(crate) struct ProgressNotifier {
+ tx: mpsc::UnboundedSender<String>,
+ /// Milliseconds since this process first reported, or [`NEVER_MS`].
+ last_ms: AtomicU64,
+ last_phase: AtomicU8,
+}
+
+impl ProgressNotifier {
+ pub(crate) fn new(tx: mpsc::UnboundedSender<String>) -> Self {
+ Self {
+ tx,
+ last_ms: AtomicU64::new(NEVER_MS),
+ last_phase: AtomicU8::new(NO_PHASE),
+ }
+ }
+
+ fn phase_slot(phase: SyncPhase) -> u8 {
+ match phase {
+ SyncPhase::Capture => 0,
+ SyncPhase::Download => 1,
+ SyncPhase::Merge => 2,
+ SyncPhase::Upload => 3,
+ SyncPhase::Apply => 4,
+ SyncPhase::Cleanup => 5,
+ }
+ }
+
+ /// Monotonic milliseconds. A wall clock would let a clock change silence
+ /// the reports an interface is waiting for.
+ fn now_ms() -> u64 {
+ static ORIGIN: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
+ ORIGIN.get_or_init(Instant::now).elapsed().as_millis() as u64
+ }
+}
+
+impl SyncProgressObserver for ProgressNotifier {
+ fn report(&self, progress: SyncProgress) {
+ const MIN_INTERVAL: Duration = Duration::from_millis(200);
+ let slot = Self::phase_slot(progress.phase);
+ let phase_changed = self.last_phase.swap(slot, Ordering::Relaxed) != slot;
+ let now = Self::now_ms();
+ if !phase_changed {
+ let last = self.last_ms.load(Ordering::Relaxed);
+ if last != NEVER_MS && now.saturating_sub(last) < MIN_INTERVAL.as_millis() as u64 {
+ return;
+ }
+ }
+ self.last_ms.store(now, Ordering::Relaxed);
+ let note = json!({
+ "jsonrpc": "2.0",
+ "method": "configSync.progress",
+ "params": {
+ "phase": progress.phase.as_str(),
+ "done": progress.done,
+ "total": progress.total,
+ "bytesDone": progress.bytes_done,
+ "bytesTotal": progress.bytes_total,
+ },
+ });
+ if let Ok(raw) = serde_json::to_string(&note) {
+ let _ = self.tx.send(format!("{raw}\n"));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn reports(mut rx: mpsc::UnboundedReceiver<String>) -> Vec<Value> {
+ let mut result = Vec::new();
+ while let Ok(line) = rx.try_recv() {
+ result.push(serde_json::from_str(&line).expect("notification is JSON"));
+ }
+ result
+ }
+
+ #[test]
+ fn phase_names_are_the_wire_contract() {
+ let phases = [
+ (SyncPhase::Capture, "capture"),
+ (SyncPhase::Download, "download"),
+ (SyncPhase::Merge, "merge"),
+ (SyncPhase::Upload, "upload"),
+ (SyncPhase::Apply, "apply"),
+ (SyncPhase::Cleanup, "cleanup"),
+ ];
+ for (phase, name) in phases {
+ assert_eq!(phase.as_str(), name);
+ }
+ }
+
+ #[test]
+ fn a_phase_change_always_reports_and_the_rest_is_throttled() {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let notifier = ProgressNotifier::new(tx);
+ notifier.report(SyncProgress::started(SyncPhase::Upload));
+ notifier.report(SyncProgress::counted(SyncPhase::Upload, 1, 9, 1024, 9216));
+ notifier.report(SyncProgress::counted(SyncPhase::Upload, 2, 9, 2048, 9216));
+ notifier.report(SyncProgress::started(SyncPhase::Merge));
+ let lines = reports(rx);
+ assert_eq!(
+ lines.len(),
+ 2,
+ "a phase change is never throttled: {lines:?}"
+ );
+ assert_eq!(
+ lines[0],
+ json!({
+ "jsonrpc": "2.0",
+ "method": "configSync.progress",
+ "params": {
+ "phase": "upload",
+ "done": 0,
+ "total": 0,
+ "bytesDone": 0,
+ "bytesTotal": 0,
+ },
+ })
+ );
+ assert_eq!(lines[1]["params"]["phase"], "merge");
+ }
+
+ #[test]
+ fn counted_progress_carries_the_numbers_an_interface_shows() {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let notifier = ProgressNotifier::new(tx);
+ notifier.report(SyncProgress::counted(
+ SyncPhase::Upload,
+ 12,
+ 45,
+ 3_145_728,
+ 16_777_216,
+ ));
+ let lines = reports(rx);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(
+ lines[0]["params"],
+ json!({
+ "phase": "upload",
+ "done": 12,
+ "total": 45,
+ "bytesDone": 3_145_728,
+ "bytesTotal": 16_777_216,
+ })
+ );
+ }
+
+ #[test]
+ fn the_unwatched_observer_swallows_everything() {
+ let observer = NoSyncProgress;
+ observer.report(SyncProgress::started(SyncPhase::Capture));
+ }
+}