From a9db9396885da442b82366381108d3b8260b01a9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 3 Dec 2026 01:02:17 +0700 Subject: [PATCH 1/3] M9: show upload progress and server-confirmed sync status (#2945) A session you joined or published now says where your changes stand on their way to the server, and calls them saved only once the server has confirmed them: Preparing, Uploading (bytes sent of the total), Waiting for the server to confirm, All changes saved to the server (with when), changes not yet saved while reconnecting, and when the server last had everything after a failure. The Share popover shows the line with a progress bar; a tab whose changes have been on their way for a second shows a thin bar and the line on hover. collab.peers reports upload and confirmedAt. The desktop connection counts what it writes, a large change in 256 KiB pieces, and reports it to the session's inbox; the browser can't measure its socket and shows waiting. --- crates/collab-net/src/guest.rs | 34 ++++++-- crates/collab-net/src/inbox.rs | 10 ++- crates/collab-net/src/lib.rs | 2 + crates/collab-net/src/manage.rs | 1 + crates/collab-net/src/net.rs | 81 +++++++++++++++++- .../collab-net/src/upload_progress_tests.rs | 63 ++++++++++++++ crates/engine/src/lib.rs | 2 + crates/engine/src/live_upload_tests.rs | 82 +++++++++++++++++++ crates/engine/src/sharing/live.rs | 53 +++++++++++- crates/engine/src/sharing/live/events.rs | 6 ++ crates/engine/src/sharing/live/join.rs | 2 +- crates/engine/src/sharing/live/sync.rs | 8 +- crates/engine/src/sharing/live/types.rs | 29 +++++++ crates/ui-egui/locales/en.toml | 8 ++ crates/ui-egui/src/dialogs/plugins_ui.rs | 3 +- crates/ui-egui/src/live.rs | 68 ++++++++++++++- crates/ui-egui/src/tabs.rs | 14 +++- docs/collab-protocol.md | 11 +++ docs/collaboration-parity.md | 1 + 19 files changed, 457 insertions(+), 21 deletions(-) create mode 100644 crates/collab-net/src/upload_progress_tests.rs create mode 100644 crates/engine/src/live_upload_tests.rs diff --git a/crates/collab-net/src/guest.rs b/crates/collab-net/src/guest.rs index 89b7d3718..ee4a115f7 100644 --- a/crates/collab-net/src/guest.rs +++ b/crates/collab-net/src/guest.rs @@ -28,7 +28,7 @@ use crate::invite::{Endpoint, Invite}; pub use crate::join::GuestConfig; use crate::join::{Next, Outcome, Resuming, Seen, Taken, after, closed, hello, resolved, take, too_large, unresolved}; use crate::manage; -use crate::net::{Duplex, NetLimits, config, open, shutdown}; +use crate::net::{Duplex, NetLimits, Sending, config, open, shutdown}; use crate::requests; pub use crate::requests::Publish; use crate::throttle::{PRESENCE_INTERVAL, Paced, Throttle, earliest}; @@ -87,7 +87,7 @@ impl Guest { let me = tx.clone(); let thread = std::thread::Builder::new().name("live-publish".into()).spawn(move || { inbox.push(Event::Status(Status::Connecting)); - let (cfg, published, hosting) = match upload(&job, cfg) { + let (cfg, published, hosting) = match Sending::new(inbox.clone()).count(|| upload(&job, cfg)) { Ok(done) => done, Err(e) => return inbox.push(Event::Status(Status::Failed { reason: format!("Couldn't publish to the server: {e}") })), }; @@ -282,15 +282,23 @@ fn session( let hello = hello(cfg, resume); let mut welcomed = false; let mut throttle = Throttle::new(PRESENCE_INTERVAL); - // Sync messages waiting their turn (a long queue from while offline). - let mut paced: Paced = Paced::new(Instant::now()); + // Sync messages waiting their turn (a long queue from while offline), encoded. + let mut paced: Paced> = Paced::new(Instant::now()); + // What of them went out: the upload progress the app shows. + let sending = Sending::new(inbox.clone()); let outcome = if send(&mut writer, &hello) { loop { let ping_at = last_ping + cfg.limits.keepalive; let wake = earliest([throttle.due(), Some(ping_at), paced.due()]).unwrap_or(ping_at); let mut out = None; match rx.recv_timeout(wake.saturating_duration_since(Instant::now())) { - Ok(Cmd::Send(m)) if welcomed => paced.push(m), + Ok(Cmd::Send(m)) if welcomed => match message::encode(&m) { + Ok(b) => { + sending.queued(b.len()); + paced.push(b); + } + Err(_) => break Outcome::Retry("the connection dropped".into()), + }, // Made for the previous connection (the sync client sends again what the server // didn't get once it has caught up with this connection's welcome). Ok(Cmd::Send(_)) => {} @@ -315,11 +323,14 @@ fn session( let now = Instant::now(); let mut sent = true; while sent && let Some(m) = paced.take_due(now) { - sent = send(&mut writer, &m); + sent = sending.count(|| send_bytes(&mut writer, m)); } if !sent { break Outcome::Retry("the connection dropped".into()); } + if paced.due().is_none() { + sending.clear(); + } let out = out.or_else(|| throttle.take_due(now)); let ok = out.is_none_or(|p| send(&mut writer, &ClientMsg::Presence(p))); let ok = ok @@ -342,7 +353,7 @@ fn session( /// Send what was waiting its turn before leaving, at its pace, for at most [`LEAVE_DRAIN`]: nothing /// waits for this thread (the app has moved on), and going faster would get the rest refused. What /// doesn't go is left to the sync client, which says so when you leave. -fn leave_paced(writer: &mut WebSocket, paced: &mut Paced) { +fn leave_paced(writer: &mut WebSocket, paced: &mut Paced>) { let give_up = Instant::now() + LEAVE_DRAIN; loop { let now = Instant::now(); @@ -350,7 +361,7 @@ fn leave_paced(writer: &mut WebSocket, paced: &mut Paced) { return; } if let Some(m) = paced.take_due(now) { - if !send(writer, &m) { + if !send_bytes(writer, m) { return; } } else if let Some(at) = paced.due().filter(|at| *at < give_up) { @@ -363,7 +374,12 @@ fn leave_paced(writer: &mut WebSocket, paced: &mut Paced) { /// Send one message; false when the connection is gone. fn send(ws: &mut WebSocket, msg: &ClientMsg) -> bool { - message::encode(msg).is_ok_and(|b| ws.send(Message::Binary(Bytes::from(b))).is_ok()) + message::encode(msg).is_ok_and(|b| send_bytes(ws, b)) +} + +/// [`send`] an encoded message. +fn send_bytes(ws: &mut WebSocket, bytes: Vec) -> bool { + ws.send(Message::Binary(Bytes::from(bytes))).is_ok() } struct ReaderCtx { diff --git a/crates/collab-net/src/inbox.rs b/crates/collab-net/src/inbox.rs index 860a80cfe..31f46202f 100644 --- a/crates/collab-net/src/inbox.rs +++ b/crates/collab-net/src/inbox.rs @@ -27,6 +27,8 @@ struct State { presence: BTreeMap, /// A presence was left out since the last drain (warned once). presence_full: bool, + /// The latest upload progress not taken yet ([`Event::Upload`]: sent, total). + upload: Option<(u64, u64)>, } /// One session's mailbox (a new session gets a new one, so a stopped session's threads can't @@ -82,8 +84,13 @@ impl Inbox { }); } + /// How far the connection's upload is: `sent` of `total` bytes (replaces one not taken yet). + pub fn upload(&self, sent: u64, total: u64) { + self.with(|s| s.upload = Some((sent, total))); + } + /// Everything since the last drain: the events in order, then the latest presence of each - /// peer. + /// peer and the latest upload progress. pub fn drain(&self) -> Vec { let mut s = self.state.lock().unwrap_or_else(PoisonError::into_inner); s.presence_full = false; @@ -101,6 +108,7 @@ impl Inbox { out.extend(next.map(|(_, e)| e)); } out.extend(std::mem::take(&mut s.presence).into_iter().map(|(id, p)| Event::Presence(id, p))); + out.extend(s.upload.take().map(|(sent, total)| Event::Upload { sent, total })); out } } diff --git a/crates/collab-net/src/lib.rs b/crates/collab-net/src/lib.rs index 6a56172e0..9418fc386 100644 --- a/crates/collab-net/src/lib.rs +++ b/crates/collab-net/src/lib.rs @@ -84,3 +84,5 @@ mod sessions_tests; mod team_library_tests; #[cfg(test)] mod tls_tests; +#[cfg(test)] +mod upload_progress_tests; diff --git a/crates/collab-net/src/manage.rs b/crates/collab-net/src/manage.rs index 40c044bb9..3fa41f8c7 100644 --- a/crates/collab-net/src/manage.rs +++ b/crates/collab-net/src/manage.rs @@ -205,6 +205,7 @@ fn close(mut ws: Ws) { fn send(ws: &mut Ws, msg: &ClientMsg) -> Result<(), String> { let bytes = message::encode(msg).map_err(|e| e.to_string())?; + crate::net::queued(bytes.len()); ws.send(Message::Binary(Bytes::from(bytes))).map_err(|e| format!("the connection to the server dropped ({e})")) } diff --git a/crates/collab-net/src/net.rs b/crates/collab-net/src/net.rs index 275029c61..81f6fec4a 100644 --- a/crates/collab-net/src/net.rs +++ b/crates/collab-net/src/net.rs @@ -6,9 +6,11 @@ //! machines over the same socket; every write goes through one lock and writes whole frames, so //! frames from the two never interleave. +use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{Shutdown, TcpStream}; +use std::rc::Rc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant}; @@ -17,6 +19,7 @@ pub use crate::limits::NetLimits; use tungstenite::protocol::WebSocketConfig; +use crate::inbox::Inbox; use crate::invite::Endpoint; use crate::tls::{self, Tls}; @@ -25,6 +28,70 @@ pub fn config(max: usize) -> WebSocketConfig { WebSocketConfig::default().max_message_size(Some(max)).max_frame_size(Some(max)) } +/// The most a counted write sends at once ([`Sending::count`]). +const COUNTED_PIECE: usize = 256 * 1024; + +thread_local! { + /// What the writes on this thread count against while [`Sending::count`] runs. + static COUNTING: RefCell>> = const { RefCell::new(None) }; +} + +/// The bytes a connection was handed and has written since it last had none waiting, reported to +/// its session's inbox as upload progress ([`figcraft_engine::live::Event::Upload`]). It lives on +/// the thread that writes. +pub(crate) struct Sending { + inbox: Inbox, + /// (sent, total). + bytes: Cell<(u64, u64)>, +} + +impl Sending { + pub(crate) fn new(inbox: Inbox) -> Rc { + Rc::new(Sending { inbox, bytes: Cell::new((0, 0)) }) + } + + /// Run `f`, counting what it writes on this thread and what it hands to [`queued`]. + pub(crate) fn count(self: &Rc, f: impl FnOnce() -> R) -> R { + let before = COUNTING.replace(Some(self.clone())); + let r = f(); + COUNTING.set(before); + r + } + + /// `n` more bytes to send. + pub(crate) fn queued(&self, n: usize) { + let (sent, total) = self.bytes.get(); + self.report(sent, total.saturating_add(n as u64)); + } + + /// `n` of them written (a frame's header counts too: never past the total). + fn wrote(&self, n: usize) { + let (sent, total) = self.bytes.get(); + self.report(sent.saturating_add(n as u64).min(total), total); + } + + /// Nothing waits any more. + pub(crate) fn clear(&self) { + if self.bytes.get() != (0, 0) { + self.report(0, 0); + } + } + + fn report(&self, sent: u64, total: u64) { + self.bytes.set((sent, total)); + self.inbox.upload(sent, total); + } +} + +/// `n` more bytes to send on this thread, for the [`Sending`] counting it (if any). +pub(crate) fn queued(n: usize) { + COUNTING.with_borrow(|c| { + if let Some(c) = c { + c.queued(n); + } + }); +} + /// One side (read or write) of a connection: reads from its own handle, writes whole buffers /// under the connection's write lock; through the connection's TLS session when it has one. pub struct Duplex { @@ -223,10 +290,18 @@ impl Read for Duplex { impl Write for Duplex { fn write(&mut self, buf: &[u8]) -> io::Result { - if let Some(t) = &self.tls { - return tls::write(t, &self.write, buf); + let counting = COUNTING.with_borrow(Option::clone); + // Counted writes go in pieces, so the progress moves while a large message goes out. + let buf = if counting.is_some() { &buf[..buf.len().min(COUNTED_PIECE)] } else { buf }; + match &self.tls { + Some(t) => { + tls::write(t, &self.write, buf)?; + } + None => self.write.lock().unwrap_or_else(PoisonError::into_inner).write_all(buf)?, + } + if let Some(c) = counting { + c.wrote(buf.len()); } - self.write.lock().unwrap_or_else(PoisonError::into_inner).write_all(buf)?; Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { diff --git a/crates/collab-net/src/upload_progress_tests.rs b/crates/collab-net/src/upload_progress_tests.rs new file mode 100644 index 000000000..fbec8d62c --- /dev/null +++ b/crates/collab-net/src/upload_progress_tests.rs @@ -0,0 +1,63 @@ +//! The upload progress a joined session reports (`Event::Upload`): what its connection was handed +//! and has written, counted while a large change goes out, and nothing once it has. + +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use figcraft_collab::Client; +use figcraft_collab::message::ServerMsg; +use figcraft_engine::live::Event; + +use crate::guest::{Guest, GuestConfig}; +use crate::inbox::Inbox; +use crate::loopback_tests::{quick, start}; + +/// An inbox that takes each event as it arrives (its waker drains it), so no report is replaced +/// by a later one before the test sees it. +fn recording() -> (Inbox, Arc>>) { + let seen = Arc::new(Mutex::new(Vec::new())); + let slot: Arc> = Arc::default(); + let (to, from) = (seen.clone(), slot.clone()); + let inbox = Inbox::new(Arc::new(move || { + if let Some(i) = from.get() { + to.lock().unwrap().extend(i.drain()); + } + })); + let _ = slot.set(inbox.clone()); + (inbox, seen) +} + +fn wait_for(seen: &Mutex>, what: &str, f: impl Fn(&[Event]) -> Option) -> T { + let start = Instant::now(); + loop { + if let Some(t) = f(&seen.lock().unwrap()) { + return t; + } + assert!(start.elapsed() < Duration::from_secs(10), "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn uploads(events: &[Event]) -> Vec<(u64, u64)> { + events.iter().filter_map(|e| if let Event::Upload { sent, total } = e { Some((*sent, *total)) } else { None }).collect() +} + +#[test] +fn a_large_change_reports_its_bytes_until_it_has_gone() { + let (mut host, _host_probe, invite) = start(); + let (inbox, seen) = recording(); + let guest = Guest::start(quick(GuestConfig::new(invite, "Ada".into())), inbox).unwrap(); + let welcome = wait_for(&seen, "the welcome", |e| { + e.iter().find_map(|e| if let Event::Sync(w @ ServerMsg::Welcome { .. }) = e { Some(w.clone()) } else { None }) + }); + let mut client = Client::join(welcome).unwrap(); + let mut doc = client.document().clone(); + // Several of the pieces a counted write sends at once. + doc.add_page(&"x".repeat(1 << 20)); + guest.send(client.edit(&doc).unwrap().unwrap()); + let reports = wait_for(&seen, "the upload to finish", |e| Some(uploads(e)).filter(|u| u.last() == Some(&(0, 0)))); + assert!(reports.iter().any(|&(sent, total)| total > 1 << 20 && sent > 0 && sent < total), "progress while it went out: {reports:?}"); + assert!(reports.iter().all(|&(sent, total)| sent <= total), "never more sent than handed over: {reports:?}"); + drop(guest); + host.stop(); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a28a7cbe0..48a7a7167 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -514,6 +514,8 @@ mod live_signal_tests; #[cfg(test)] mod live_tests; #[cfg(test)] +mod live_upload_tests; +#[cfg(test)] mod lock_behaviour_tests; #[cfg(test)] mod locked_ratio_layout_tests; diff --git a/crates/engine/src/live_upload_tests.rs b/crates/engine/src/live_upload_tests.rs new file mode 100644 index 000000000..cec3e6b85 --- /dev/null +++ b/crates/engine/src/live_upload_tests.rs @@ -0,0 +1,82 @@ +//! Where your changes stand on their way to a server (`collab.peers`' `upload`): saved only once +//! the server confirms them, whatever the connection or a local save says. + +use serde_json::{Value, json}; + +use crate::live::{Event, Published, Role, Status}; +use crate::live_tests::{info, push, relay, serve, session}; + +fn stage(s: &crate::Session) -> Value { + s.live_summary()["upload"]["stage"].clone() +} + +#[test] +fn publishing_goes_from_preparing_to_saved_only_when_the_server_answers() { + let (mut s, script) = session(); + s.execute("collab.publish", &json!({"server": "ws://127.0.0.1:1/?key=k"})).unwrap(); + push(&script, vec![Event::Status(Status::Connecting)]); + s.live_poll(); + assert_eq!(stage(&s), "preparing"); + push(&script, vec![Event::Upload { sent: 400, total: 1000 }]); + s.live_poll(); + assert_eq!(s.live_summary()["upload"], json!({"stage": "uploading", "sent": 400, "total": 1000})); + // Every byte written isn't the server keeping the file. + push(&script, vec![Event::Upload { sent: 1000, total: 1000 }]); + s.live_poll(); + assert_eq!(stage(&s), "waiting"); + assert!(s.live_summary()["confirmedAt"].is_null()); + let published = Published { + server: "ws://127.0.0.1:1/".into(), + file: "f".into(), + name: "Untitled".into(), + edit: String::new(), + view: String::new(), + owner: None, + expires: None, + }; + push(&script, vec![Event::Published(published)]); + s.live_poll(); + assert_eq!(stage(&s), "saved"); + assert!(s.live_summary()["confirmedAt"].is_u64()); +} + +#[test] +fn an_edit_waits_for_the_server_and_a_dropped_connection_keeps_it_waiting() { + let (mut s, script) = session(); + let mut doc = figcraft_doc::Document::new("Team file"); + doc.repair(); + let (mut server, _, welcome) = serve(&doc); + let Event::Sync(figcraft_collab::message::ServerMsg::Welcome { client_id: me, .. }) = welcome.clone() else { panic!("no welcome") }; + s.execute("collab.join", &json!({"link": "figcraft://join?host=a:1&file=f&token=t"})).unwrap(); + push(&script, vec![Event::Welcome { info: info(Role::Guest, me), peers: vec![] }, welcome]); + s.live_poll(); + assert_eq!(stage(&s), "saved", "joined with nothing of yours on its way"); + + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.live_sync(); + assert_eq!(s.live_summary()["upload"], json!({"stage": "waiting", "changes": 1})); + let back = relay(&script, &mut server, me); + push(&script, back); + s.live_poll(); + assert_eq!(stage(&s), "saved", "the server confirmed it"); + let confirmed = s.live_summary()["confirmedAt"].as_u64(); + assert!(confirmed.is_some()); + + s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap(); + s.live_sync(); + push(&script, vec![Event::Status(Status::Reconnecting { attempt: 1 })]); + s.live_poll(); + assert_eq!(s.live_summary()["upload"], json!({"stage": "retrying", "attempt": 1, "changes": 1})); + assert_eq!(s.live_summary()["confirmedAt"].as_u64(), confirmed, "still the last time the server had everything"); + push(&script, vec![Event::Status(Status::Failed { reason: "gone".into() })]); + s.live_poll(); + assert_eq!(stage(&s), "failed"); + assert_eq!(s.live_summary()["confirmedAt"].as_u64(), confirmed, "a session that stopped still says when the server last had everything"); +} + +#[test] +fn a_session_this_app_hosts_uploads_nothing() { + let (mut s, _) = session(); + s.execute("collab.host", &json!({})).unwrap(); + assert!(s.live_summary()["upload"].is_null()); +} diff --git a/crates/engine/src/sharing/live.rs b/crates/engine/src/sharing/live.rs index a2cd79c68..74e0327ae 100644 --- a/crates/engine/src/sharing/live.rs +++ b/crates/engine/src/sharing/live.rs @@ -74,7 +74,7 @@ pub use join::{can_remove_people, specs}; pub use types::{ Bind, DEFAULT_SERVER, Event, HostOptions, HttpResponse, LiveLink, MAX_NAME, MAX_PEERS, MAX_SELECTION, MAX_WEB_BYTES, NO_HOSTING, NO_HTTP, NO_SESSION, NO_WEB, NetReply, NetRequest, ONLINE_OFF, PEOPLE, PageInfo, PublishOptions, Published, Role, SessionId, SessionInfo, Share, Shared, - SharedLink, Status, TOO_LARGE_TO_JOIN, Via, WayIn, WebPage, join_target, parse_color, + SharedLink, Status, TOO_LARGE_TO_JOIN, Upload, Via, WayIn, WebPage, join_target, parse_color, }; /// The view a follow last applied: any other view means the user moved. @@ -152,6 +152,12 @@ pub struct Live { last_batch: Option, /// You were in this session and aren't now: what joining it again takes (`collab.reconnect`). stranded: Option, + /// Bytes the connection has sent of what it was handed ([`Event::Upload`]). + upload_bytes: (u64, u64), + /// When the server last confirmed everything you did (seconds since 1970). + pub confirmed_at: Option, + /// Since when something of yours has been on its way and not confirmed. + unconfirmed_since: Option, } /// What's kept of a session you joined once it can't go on by itself. The tab stays yours to work @@ -216,6 +222,7 @@ impl Live { published: self.published.take(), share: self.share.take(), stranded: Some(held), + confirmed_at: self.confirmed_at, ..Live::default() }; } @@ -242,6 +249,50 @@ impl Live { self.client.is_some() } + /// Where your changes stand on their way to the server; `None` when nothing of yours goes to + /// one (no session, a session this app hosts, or one you only view). + pub fn upload(&self) -> Option { + let changes = self.client.as_ref().map_or(0, Client::pending); + let (sent, total) = self.upload_bytes; + // Connecting with a tab already chosen and nobody's welcome yet: a publish. + let publishing = self.status == Status::Connecting && self.info.is_none() && self.doc_uid.is_some(); + let joined = self.role() == Some(Role::Guest) || publishing || self.published.is_some(); + let viewing = self.info.as_ref().is_some_and(|i| i.access == Access::View); + match &self.status { + _ if !joined || viewing => None, + Status::Off => None, + Status::Failed { reason } => Some(Upload::Failed { reason: reason.clone() }), + Status::Reconnecting { attempt } => Some(Upload::Retrying { attempt: *attempt, changes }), + _ if sent < total => Some(Upload::Uploading { sent, total }), + Status::Connecting if publishing && self.published.is_none() => { + Some(if total == 0 { Upload::Preparing } else { Upload::Waiting { changes: 0 } }) + } + _ if changes > 0 => Some(Upload::Waiting { changes }), + _ => Some(Upload::Saved), + } + } + + /// How long something of yours has been on its way to the server unconfirmed. + pub fn unconfirmed_for(&self) -> Option { + self.unconfirmed_since.map(|t| t.elapsed()) + } + + /// Note when the server confirmed everything ([`confirmed_at`](Self::confirmed_at)) and since + /// when it hasn't. + fn note_confirmed(&mut self) { + match self.upload() { + Some(Upload::Saved) if self.syncing() => { + if self.unconfirmed_since.take().is_some() || self.confirmed_at.is_none() { + self.confirmed_at = Some(crate::cmd::comment::now_secs()); + } + } + Some(Upload::Preparing | Upload::Uploading { .. } | Upload::Waiting { .. }) => { + self.unconfirmed_since.get_or_insert_with(web_time::Instant::now); + } + _ => {} + } + } + /// What the file's tab says about its session: `Some(true)` others get in (a session this app /// hosts, one you joined, a file of yours shared with a code or links), `Some(false)` a file of /// yours on a server that only you get into now, `None` no session (or one still on its way). diff --git a/crates/engine/src/sharing/live/events.rs b/crates/engine/src/sharing/live/events.rs index 88f4e559e..dafd0be19 100644 --- a/crates/engine/src/sharing/live/events.rs +++ b/crates/engine/src/sharing/live/events.rs @@ -26,6 +26,8 @@ fn reset_for_reconnect(live: &mut Live) { live.chats.clear(); live.chat.clear(); live.spotlight = None; + // What the dropped connection had waiting goes again once it is back. + live.upload_bytes = (0, 0); if let Some(c) = live.client.as_mut() { c.disconnect(); } @@ -238,6 +240,9 @@ impl Session { } let server = live.server.clone(); live.published = Some(p.clone()); + // The server has the file: its answer is the confirmation. + live.confirmed_at = Some(crate::cmd::comment::now_secs()); + live.unconfirmed_since = None; self.online_published(&server, &p); } Event::Shared(Ok(links)) => { @@ -253,6 +258,7 @@ impl Session { } Event::Shared(Err(why)) => self.message = Some(format!("The file is on the server, but couldn't be shared: {why}")), Event::Hosting(info) => live.hosting = Some(clean_hosting(info)), + Event::Upload { sent, total } => live.upload_bytes = (sent, total), Event::Reported(error) => { self.message = Some(error.map_or_else(|| "Your report was sent to the server's operator".into(), |e| format!("The report wasn't sent: {e}"))); diff --git a/crates/engine/src/sharing/live/join.rs b/crates/engine/src/sharing/live/join.rs index 66ec29bdb..84ed77863 100644 --- a/crates/engine/src/sharing/live/join.rs +++ b/crates/engine/src/sharing/live/join.rs @@ -273,7 +273,7 @@ pub fn specs() -> Vec { spec!( "collab.peers", "People in this file", - "{} → the open file's session (each open file has its own or none): {available, canHost (false in the browser: it can only join), session (its id; null: this file isn't in a session), status: off|connecting|live|reconnecting|failed, reason?, role, me, name, color, fileName, pages, link, url, address, network, access: edit|view|comment (view: a view link or code, a server's or a local network share's, edits are refused; comment: a server's comment link, edits other than to comment threads are refused), readOnly (the open file can't be edited now: view only, comment only, or being published), published (a file you published: {server, file, name, edit, view}), code (the join code to give others, when the file was shared with `collab.share`; null otherwise or while it is on its way), share ({via: online|local, access, shared (false: a file of yours on a server that nobody else gets into now), editCode, viewCode, commentCode, editLink, viewLink, commentLink (what others join with; null when not shared)} or null), follow, syncing, document (index of the synced open document), editing (the text layer you type in: {node, layer, caret, selection}), peers: [{id, name, color, editing (theirs, same shape, or null), presence: {cursor: [page, x, y], selection, viewport: [page, x, y, w, h], editing_text}}], sessions: [{session, document (index of its open document; null for a join on its way), status, reason, role, fileName, link, peers (how many others)}] (every session of the app)}", + "{} → the open file's session (each open file has its own or none): {available, canHost (false in the browser: it can only join), session (its id; null: this file isn't in a session), status: off|connecting|live|reconnecting|failed, reason?, role, me, name, color, fileName, pages, link, url, address, network, access: edit|view|comment (view: a view link or code, a server's or a local network share's, edits are refused; comment: a server's comment link, edits other than to comment threads are refused), readOnly (the open file can't be edited now: view only, comment only, or being published), published (a file you published: {server, file, name, edit, view}), code (the join code to give others, when the file was shared with `collab.share`; null otherwise or while it is on its way), share ({via: online|local, access, shared (false: a file of yours on a server that nobody else gets into now), editCode, viewCode, commentCode, editLink, viewLink, commentLink (what others join with; null when not shared)} or null), follow, syncing, upload (where your changes stand on their way to the server: {stage: preparing} getting a file ready to publish, {stage: uploading, sent, total} bytes written to the connection (the browser can't measure them and says waiting), {stage: waiting, changes} sent and not yet confirmed by the server, {stage: saved} the server confirmed everything, {stage: retrying, attempt, changes} the connection dropped, {stage: failed, reason}; null: nothing of yours goes to a server: no session, one this app hosts, or view only), confirmedAt (when the server last confirmed everything you did, seconds since 1970; null: not yet), document (index of the synced open document), editing (the text layer you type in: {node, layer, caret, selection}), peers: [{id, name, color, editing (theirs, same shape, or null), presence: {cursor: [page, x, y], selection, viewport: [page, x, y, w, h], editing_text}}], sessions: [{session, document (index of its open document; null for a join on its way), status, reason, role, fileName, link, peers (how many others), upload}] (every session of the app)}", false, |s, _| Ok(s.live_summary()) ), diff --git a/crates/engine/src/sharing/live/sync.rs b/crates/engine/src/sharing/live/sync.rs index 11e9da633..589d7b1c2 100644 --- a/crates/engine/src/sharing/live/sync.rs +++ b/crates/engine/src/sharing/live/sync.rs @@ -278,9 +278,10 @@ impl Session { /// it or quitting doesn't ask. Not for a session an app hosts (nothing keeps it once the host /// leaves), a file with an expiry time (a public server keeps no backups), a branch tab, /// versions or a local file the tab has (they stay on this computer), or edits that are - /// unconfirmed, deferred or held. + /// unconfirmed, deferred or held. Also notes when the server last confirmed everything. pub(super) fn live_kept(&mut self, id: SessionId) { - let Some(live) = self.live.get(id) else { return }; + let Some(live) = self.live.sessions.get_mut(&id) else { return }; + live.note_confirmed(); let kept = live.status == Status::Live && live.hosting.as_ref().is_some_and(|h| h.expires.is_none()); let confirmed = live.client.as_ref().is_some_and(|c| c.pending() == 0) && live.deferred.is_empty() && live.hold == 0; let (Some(uid), Some(synced)) = (live.doc_uid, live.synced.clone()) else { return }; @@ -434,6 +435,7 @@ impl Session { "fileName": info.map(|i| i.file_name.as_str()), "link": o.invite().0, "peers": o.peers.len(), + "upload": o.upload(), }) }) .collect(); @@ -481,6 +483,8 @@ impl Session { "spotlight": l.spotlight, "spotlighting": l.spotlighting, "syncing": l.syncing(), + "upload": l.upload(), + "confirmedAt": l.confirmed_at, "document": self.live_index(l), "editing": mine, "peers": peers, diff --git a/crates/engine/src/sharing/live/types.rs b/crates/engine/src/sharing/live/types.rs index 48d8102b3..276519899 100644 --- a/crates/engine/src/sharing/live/types.rs +++ b/crates/engine/src/sharing/live/types.rs @@ -82,6 +82,29 @@ impl Status { } } +/// Where your changes stand on their way to the server of a session you joined or published +/// (`collab.peers`' `upload`). Saved only once the server has confirmed them: a connection that +/// is up, or a file saved on this computer, says nothing about it. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", tag = "stage")] +pub enum Upload { + /// Getting the file ready to publish. + Preparing, + /// Bytes going out: `sent` of `total` written to the connection (the desktop app and the MCP + /// server measure them; the browser can't, and goes straight to [`Upload::Waiting`]). + Uploading { sent: u64, total: u64 }, + /// Sent; the server hasn't confirmed `changes` of your edits yet (0 for a file being + /// published). + Waiting { changes: usize }, + /// The server has everything you did ([`Live::confirmed_at`](super::Live::confirmed_at) says + /// since when). + Saved, + /// The connection dropped and is being tried again; `changes` the server hasn't confirmed. + Retrying { attempt: u32, changes: usize }, + /// It stopped (`reason`): what the server hadn't confirmed isn't on it. + Failed { reason: String }, +} + /// Your part in the session. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] @@ -296,6 +319,12 @@ pub enum Event { }, /// The document is on the server (`collab.publish`); joining it follows. Published(Published), + /// Bytes of your changes (or the file being published) the connection has `sent` of the + /// `total` handed to it since it last had none waiting; `(0, 0)`: none waiting. + Upload { + sent: u64, + total: u64, + }, /// The published file is shared (`collab.share`): the links and codes others join with, or /// why the server made none. Shared(std::result::Result), diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 03b0d7632..bafcbfbfd 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -1318,6 +1318,8 @@ name = "English" "Org chart" = "Org chart" "Outline" = "Outline" "Add a subtopic" = "Add a subtopic" +"All changes saved to the server {when}" = "All changes saved to the server {when}" +"All changes saved to the server" = "All changes saved to the server" "Order" = "Order" "Other apps may not open every .fig file exported here." = "Other apps may not open every .fig file exported here." "Other" = "Other" @@ -2333,6 +2335,12 @@ name = "English" "Every file on a server you run, with its key" = "Every file on a server you run, with its key" "Files on a server" = "Files on a server" "Files on a server…" = "Files on a server…" +"Last saved to the server {when}" = "Last saved to the server {when}" "No files on this server" = "No files on this server" +"Preparing the upload…" = "Preparing the upload…" "Show files" = "Show files" +"Uploading {sent} of {total} ({percent}%)" = "Uploading {sent} of {total} ({percent}%)" +"Waiting for the server to confirm {n} changes…" = { one = "Waiting for the server to confirm {n} change…", other = "Waiting for the server to confirm {n} changes…" } +"Waiting for the server to confirm…" = "Waiting for the server to confirm…" "With the key of a server you run, see every file on it, those published with the key included. Stop sharing keeps a file on the server; Remove from server deletes it for everyone." = "With the key of a server you run, see every file on it, those published with the key included. Stop sharing keeps a file on the server; Remove from server deletes it for everyone." +"{n} changes not saved to the server yet" = { one = "{n} change not saved to the server yet", other = "{n} changes not saved to the server yet" } diff --git a/crates/ui-egui/src/dialogs/plugins_ui.rs b/crates/ui-egui/src/dialogs/plugins_ui.rs index eb69b1eb6..613497542 100644 --- a/crates/ui-egui/src/dialogs/plugins_ui.rs +++ b/crates/ui-egui/src/dialogs/plugins_ui.rs @@ -569,7 +569,8 @@ fn access_text(access: &str) -> &'static str { if access == "write" { tr("can edit the document") } else { tr("reads the document") } } -fn size(bytes: u64) -> String { +/// `bytes` for people to read: "512 B", "12 KB", "3.4 MB". +pub(crate) fn size(bytes: u64) -> String { match bytes { b if b >= 1 << 20 => format!("{:.1} MB", b as f64 / f64::from(1 << 20)), b if b >= 1 << 10 => format!("{} KB", b.div_ceil(1 << 10)), diff --git a/crates/ui-egui/src/live.rs b/crates/ui-egui/src/live.rs index 2ab2ed685..19a172448 100644 --- a/crates/ui-egui/src/live.rs +++ b/crates/ui-egui/src/live.rs @@ -17,7 +17,9 @@ use std::borrow::Cow; use std::collections::BTreeMap; use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Shape, Stroke, Ui, pos2, vec2}; -use figcraft_engine::live::{Access, PEOPLE, Role, SessionId, Share, Signal, Status, TOO_LARGE_TO_JOIN, Via, initials, parse_color, presence_page}; +use figcraft_engine::live::{ + Access, Live, PEOPLE, Role, SessionId, Share, Signal, Status, TOO_LARGE_TO_JOIN, Upload, Via, initials, parse_color, presence_page, +}; use serde_json::{Value, json}; use crate::FigApp; @@ -708,6 +710,13 @@ pub fn share_popover(app: &mut FigApp, anchor: &egui::Response) { if !line.is_empty() { widgets::label(ui, &line, col); } + if let Some((text, done)) = upload_status(app.session.live()) { + widgets::label(ui, &text, t.text_secondary); + if let Some(done) = done { + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 4.0), Sense::hover()); + paint_upload_bar(ui.painter(), r, Some(done), &t); + } + } match (&status, role, &share) { (Status::Off | Status::Failed { .. }, ..) => start_ui(app, ui, &t), (Status::Live, _, Some(share)) if share.links.is_none() => private_ui(app, ui, &t, share), @@ -724,6 +733,63 @@ pub fn share_popover(app: &mut FigApp, anchor: &egui::Response) { }); } +/// How long your changes are on their way before their tab shows it: a quick round trip shows +/// nothing. +const UPLOAD_QUIET: std::time::Duration = std::time::Duration::from_secs(1); + +/// What the upload of your changes in `live` shows: its line, and how far its bytes are when the +/// app measures them. `None`: nothing of yours goes to a server. +pub fn upload_status(live: &Live) -> Option<(String, Option)> { + let when = live.confirmed_at.map(|at| crate::home::home_recents::ago(figcraft_engine::cmd::comment::now_secs(), at)); + Some(match live.upload()? { + Upload::Preparing => (tr("Preparing the upload…").into(), None), + Upload::Uploading { sent, total } => { + let percent = sent.saturating_mul(100) / total.max(1); + let args: [(&str, &dyn std::fmt::Display); 3] = + [("sent", &crate::dialogs::plugins_ui::size(sent)), ("total", &crate::dialogs::plugins_ui::size(total)), ("percent", &percent)]; + (trf("Uploading {sent} of {total} ({percent}%)", &args), Some(sent as f32 / total.max(1) as f32)) + } + Upload::Waiting { changes: 0 } => (tr("Waiting for the server to confirm…").into(), None), + Upload::Waiting { changes } => (trn("Waiting for the server to confirm {n} changes…", changes, &[]), None), + Upload::Saved => match when { + Some(when) => (trf("All changes saved to the server {when}", &[("when", &when)]), None), + None => (tr("All changes saved to the server").into(), None), + }, + Upload::Retrying { changes, .. } if changes > 0 => (trn("{n} changes not saved to the server yet", changes, &[]), None), + // The status line says what went wrong; this says what the server last had. + Upload::Retrying { .. } | Upload::Failed { .. } => (trf("Last saved to the server {when}", &[("when", &when?)]), None), + }) +} + +/// What document `uid`'s tab shows of its changes on their way to the server ([`upload_status`]), +/// once they have been for a moment. Asks for a frame when it is about to show. +pub fn tab_upload(app: &FigApp, ctx: &egui::Context, uid: u64) -> Option<(String, Option)> { + let live = app.session.live_of(uid); + let on_way = live.doc_uid == Some(uid) && matches!(live.upload()?, Upload::Preparing | Upload::Uploading { .. } | Upload::Waiting { .. }); + let waited = live.unconfirmed_for().filter(|_| on_way)?; + if waited < UPLOAD_QUIET { + ctx.request_repaint_after(UPLOAD_QUIET - waited); + return None; + } + upload_status(live) +} + +/// A tab's `label` with what [`tab_upload`] says, when it says something. +pub fn with_upload(label: String, upload: Option<&(String, Option)>) -> String { + match upload { + Some((text, _)) => format!("{label}. {text}"), + None => label, + } +} + +/// A thin progress bar in `r`: filled as far as `done` (0..=1), or whole and quieter when the +/// stage can't be measured. +pub fn paint_upload_bar(painter: &egui::Painter, r: Rect, done: Option, t: &Tokens) { + painter.rect_filled(r, CornerRadius::same(2), t.hover); + let (w, col) = done.map_or((r.width(), t.text_secondary), |d| (r.width() * d.clamp(0.0, 1.0), ACCENT)); + painter.rect_filled(Rect::from_min_size(r.min, vec2(w, r.height())), CornerRadius::same(2), col); +} + fn people_count(others: usize) -> String { match others { 0 => tr("nobody else here yet").into(), diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index 9bafad083..be04fb4b7 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -184,9 +184,11 @@ pub fn tab_bar(app: &mut FigApp, ui: &mut Ui) { } let branch_parent = d.branch_of.as_ref().and_then(|(main, _)| app.session.docs.iter().find(|m| m.uid == *main)).map(|m| m.doc.name.as_str()); + let upload = crate::live::tab_upload(app, ui.ctx(), d.uid); let label = if lost { trf("{name}, disconnected from its live session", &[("name", name)]) } else { tab_label(name, branch_parent, live) }; - let resp = if live.is_some() || lost || branch_parent.is_some() { resp.on_hover_text(&label) } else { resp }; + let label = crate::live::with_upload(label, upload.as_ref()); + let resp = if live.is_some() || lost || branch_parent.is_some() || upload.is_some() { resp.on_hover_text(&label) } else { resp }; crate::a11y::tab(&resp, &label, active); let progress = open_progress(&opening, d.uid, now); let tab = TabPaint { @@ -198,6 +200,7 @@ pub fn tab_bar(app: &mut FigApp, ui: &mut Ui) { state: [active, resp.hovered(), cresp.hovered(), dirty], live, lost, + upload: upload.map(|(_, done)| done), progress, }; paint_tab(ui, &t, &tab); @@ -484,13 +487,16 @@ struct TabPaint<'a> { live: Option, /// Disconnected from its live session. lost: bool, + /// Its changes on their way to the server: how far (`Some(None)`: a stage without a measure). + upload: Option>, /// How far the opening animation is (0..=1). progress: f32, } /// Draws a document tab: background, icon, name, live mark, unsaved dot and close button. fn paint_tab(ui: &Ui, t: &Tokens, tab: &TabPaint) { - let TabPaint { name, kind, branch, rects: [r, close_r], width: w, state: [active, hovered, close_hovered, dirty], live, lost, progress } = *tab; + let TabPaint { name, kind, branch, rects: [r, close_r], width: w, state: [active, hovered, close_hovered, dirty], live, lost, upload, progress } = + *tab; let mark_w = if live.is_some() || lost { LIVE_MARK_WIDTH } else { 0.0 }; let paint_r = r.translate(vec2(-28.0 * (1.0 - progress).powi(2), 0.0)); let painter = ui.painter().with_clip_rect(r); @@ -523,6 +529,10 @@ fn paint_tab(ui: &Ui, t: &Tokens, tab: &TabPaint) { if dirty { painter.text(pos2(shown.max.x + 4.0, paint_r.center().y), Align2::LEFT_CENTER, "•", regular(12.0), t.text.linear_multiply(progress)); } + if let Some(done) = upload { + let bar = Rect::from_min_max(pos2(paint_r.min.x + 8.0, paint_r.max.y - 4.0), pos2(paint_r.max.x - 8.0, paint_r.max.y - 2.0)); + crate::live::paint_upload_bar(&painter, bar, done, t); + } let cr = Rect::from_center_size(close_r.center() + vec2(paint_r.min.x - r.min.x, 0.0), Vec2::splat(20.0)); // The close target never overlaps the draggable body, including on inactive tabs. if hovered || close_hovered || active { diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 7fe555bfc..c4f6fbb3c 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -580,6 +580,17 @@ resuming with its offline edits, and leaving the session going back to snapshot reconnect resumes as the same client: the guest's connection keeps the session id, client id and last sequence number from the messages it read and sends them in its next `Hello` (see Offline and reconnect). +- Upload status (#2945): a session you joined or published says where your changes stand, and + calls them saved only once the server has confirmed them (a live connection or a saved local + file says nothing about that). Publishing goes Preparing, Uploading, Waiting for the server to + confirm, then saved when the server answers with the file's links; an edit is waiting until the + server orders the batch. The Share popover shows the stage, bytes sent of the total with a bar + while they go out, the changes the server hasn't confirmed while reconnecting, and when it last + confirmed everything; a tab whose changes have been on their way for a second shows a thin bar + and the same line on hover. The desktop app and the MCP server count what the connection writes + (a large change in 256 KiB pieces, `Sending` in `crates/collab-net/src/net.rs`, reported as + `Event::Upload`); the browser can't see what its socket has sent and shows waiting instead. + `collab.peers` reports it as `upload {stage, …}` and `confirmedAt`. - The browser build joins and publishes to a server (see *Built (the browser client)*); hosting needs the desktop app. diff --git a/docs/collaboration-parity.md b/docs/collaboration-parity.md index 19c8cfaf0..eb57d52d0 100644 --- a/docs/collaboration-parity.md +++ b/docs/collaboration-parity.md @@ -27,6 +27,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla | Date | Change | Summary | |---|---|---| +| 2026-12-03 | minor | M9, #2945: a session you joined or published shows where your changes stand on their way to the server, and says saved only once the server confirmed them: Preparing, Uploading (bytes sent of the total and a percentage, in the desktop app and the MCP server), Waiting for the server to confirm, All changes saved to the server (with when), changes not yet saved while reconnecting, and the last time the server had everything after a failure. The Share popover shows it with a progress bar; a tab whose changes have been on their way for a second shows a thin bar and the line on hover. `collab.peers` reports `upload` and `confirmedAt`. The browser can't measure its socket's bytes and shows waiting. Numbers unchanged | | 2026-12-02 | minor | M9, part of #2119: `team_publish = true` (beside `team_files = "edit"`, refused with `open_publish`) makes `figcraft-server` a workspace for the team: everyone who reaches it publishes from the app or the browser with the plain address, no key, and the file is on the team list (Home ▸ Online) for everyone at once until it is removed. Such files never expire, and their publisher manages them with an owner token from Home ▸ Online (rename, remove, share with a code); the server reports `open` with no idle time, so apps of any version publish there with no protocol change. Tests: `figcraft-server::team_publish_tests`. Numbers unchanged | | 2026-12-01 | minor | M9, #2786: a page hosting the browser build (`?host=parent` or `data-host="page"`) asks for the open file to be put on the server it names in ``: `figcraft:publish {name?}` opens File ▸ Publish to server… for the file in front, addressed to that server, and the user presses Publish as in the app (`collab.publish`); the page hears `figcraft:published {file, name, edit, view}`, or `{error}` when it names no server, no file is open, a request still waits, the user closed the dialog (`"cancelled"`), the publish failed or went to another server. A server in the message is never used. A publish sent while the file the page just sent is still opening waits for it. Tests: `figcraft-web` `host_publish_tests`, `ui-egui` `live_publish_to_tests`; run in a browser through an iframe host page against a local open `figcraft-server` (open then publish, Publish, Cancel, a second request while one waits, no file open). Numbers unchanged | | 2026-11-28 | minor | M9: a file joined on a server that keeps it (hosting info reports no expiry) has nothing to save on this computer once the server has confirmed every edit and no batch is deferred or held: closing its tab or quitting no longer asks to save it, and the tab shows no unsaved mark. Recording `synced` as the saved baseline preserves the clean state across version and text previews, and `live_sync_in` also rechecks after applying deferred batches or releasing holds. Still asks while an edit is unconfirmed, deferred or held, for a file with an expiry time, on servers older than hosting info, for branch tabs, for a tab saved to a local file or with changed versions, and in an app-hosted session. Tests: `engine::server_kept_tests`. Numbers unchanged. | From 06733df25c9fde974b80e0c7b910387d9842406f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 3 Dec 2026 01:38:24 +0700 Subject: [PATCH 2/3] M9: a dropped connection leaves no upload progress behind (#2945) --- crates/collab-net/src/guest.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/collab-net/src/guest.rs b/crates/collab-net/src/guest.rs index ee4a115f7..3fadcf881 100644 --- a/crates/collab-net/src/guest.rs +++ b/crates/collab-net/src/guest.rs @@ -345,6 +345,8 @@ fn session( } else { Outcome::Retry("the connection dropped".into()) }; + // What this connection had waiting is gone with it: no progress outlives it. + sending.clear(); shutdown(&sock); let _ = reader.join(); outcome From f512b80ed47d458c60424422d7743564394cb6ca Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 3 Dec 2026 01:45:00 +0700 Subject: [PATCH 3/3] M9: a publish that fails before the server answers reports its upload as failed (#2945) --- crates/engine/src/live_upload_tests.rs | 13 +++++++++++++ crates/engine/src/sharing/live.rs | 19 +++++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/live_upload_tests.rs b/crates/engine/src/live_upload_tests.rs index cec3e6b85..a87a24f3d 100644 --- a/crates/engine/src/live_upload_tests.rs +++ b/crates/engine/src/live_upload_tests.rs @@ -40,6 +40,19 @@ fn publishing_goes_from_preparing_to_saved_only_when_the_server_answers() { assert!(s.live_summary()["confirmedAt"].is_u64()); } +#[test] +fn a_publish_that_fails_before_the_server_answers_says_so() { + let (mut s, script) = session(); + s.execute("collab.publish", &json!({"server": "ws://127.0.0.1:1/?key=k"})).unwrap(); + push(&script, vec![Event::Status(Status::Connecting), Event::Upload { sent: 400, total: 1000 }]); + s.live_poll(); + assert_eq!(stage(&s), "uploading"); + push(&script, vec![Event::Status(Status::Failed { reason: "gone".into() })]); + s.live_poll(); + assert_eq!(s.live_summary()["upload"], json!({"stage": "failed", "reason": "gone"})); + assert!(s.live_summary()["confirmedAt"].is_null(), "the server never had the file"); +} + #[test] fn an_edit_waits_for_the_server_and_a_dropped_connection_keeps_it_waiting() { let (mut s, script) = session(); diff --git a/crates/engine/src/sharing/live.rs b/crates/engine/src/sharing/live.rs index 74e0327ae..426fd7f94 100644 --- a/crates/engine/src/sharing/live.rs +++ b/crates/engine/src/sharing/live.rs @@ -158,6 +158,8 @@ pub struct Live { pub confirmed_at: Option, /// Since when something of yours has been on its way and not confirmed. unconfirmed_since: Option, + /// A publish stopped before the server had the file: its failure is the upload's. + publish_failed: bool, } /// What's kept of a session you joined once it can't go on by itself. The tab stays yours to work @@ -212,7 +214,12 @@ impl Live { /// is; any other goes back to no session. fn strand(&mut self) { self.hold(); - let Some(held) = self.stranded.take() else { return self.reset() }; + let Some(held) = self.stranded.take() else { + let publishing = self.publishing(); + self.reset(); + self.publish_failed = publishing; + return; + }; *self = Live { id: self.id, tab: self.tab, @@ -254,9 +261,8 @@ impl Live { pub fn upload(&self) -> Option { let changes = self.client.as_ref().map_or(0, Client::pending); let (sent, total) = self.upload_bytes; - // Connecting with a tab already chosen and nobody's welcome yet: a publish. - let publishing = self.status == Status::Connecting && self.info.is_none() && self.doc_uid.is_some(); - let joined = self.role() == Some(Role::Guest) || publishing || self.published.is_some(); + let publishing = self.publishing(); + let joined = self.role() == Some(Role::Guest) || publishing || self.published.is_some() || self.publish_failed; let viewing = self.info.as_ref().is_some_and(|i| i.access == Access::View); match &self.status { _ if !joined || viewing => None, @@ -272,6 +278,11 @@ impl Live { } } + /// Connecting with a tab already chosen and nobody's welcome yet: a publish. + fn publishing(&self) -> bool { + self.status == Status::Connecting && self.info.is_none() && self.doc_uid.is_some() + } + /// How long something of yours has been on its way to the server unconfirmed. pub fn unconfirmed_for(&self) -> Option { self.unconfirmed_since.map(|t| t.elapsed())