diff --git a/crates/cloud-ui/src/cloud/backend.rs b/crates/cloud-ui/src/cloud/backend.rs index f92328cef2..d5479f3397 100644 --- a/crates/cloud-ui/src/cloud/backend.rs +++ b/crates/cloud-ui/src/cloud/backend.rs @@ -70,6 +70,9 @@ pub enum Event { }, } +/// An answer with the account generation its job was issued in. +pub(crate) type Stamped = (u64, Event); + /// Where a worker's answers go. /// /// Handed to [`CloudBackend::submit`] with the job it belongs to. A worker is @@ -77,7 +80,10 @@ pub enum Event { /// sign-in reports the URL it wants a browser pointed at and then reports that /// the user finished there. A send after the window closed is not a failure. pub struct Post { - tx: Sender, + /// Each event goes with the generation its job was issued in, so + /// [`super::pump`] can drop one that waited in the channel across a + /// sign-out or a new sign-in. + tx: Sender, /// The window's account generation as of the moment the job this answers /// was issued, beside a handle to what it is now. A sign-out or a new /// sign-in bumps the live value; a reply that arrives after is for a @@ -87,7 +93,7 @@ pub struct Post { } impl Post { - pub(crate) fn new(tx: Sender, generation: Arc) -> Post { + pub(crate) fn new(tx: Sender, generation: Arc) -> Post { let issued = generation.load(Ordering::Relaxed); Post { tx, generation, issued } } @@ -99,16 +105,19 @@ impl Post { Post { tx: self.tx.clone(), generation: self.generation.clone(), issued: self.issued } } - /// Delivers the event, unless the window has signed out or signed in - /// again since the job this answers was issued. Silently dropping it - /// there, rather than delivering it, is what keeps a late reply from - /// restoring the previous session's account, files or busy state on top - /// of whatever replaced it. + /// Queues the event with the generation its job was issued in. + /// + /// [`super::pump`] holds the check that keeps a late reply from restoring + /// the previous session's account, files or busy state on top of whatever + /// replaced it: it drops every event whose generation is not the current + /// one, including an event sent here just before a sign-out or a new + /// sign-in. This method only skips the send when the generation has + /// already moved on, so an answer that `pump` would drop is not queued. pub fn send(&self, event: Event) { if self.generation.load(Ordering::Relaxed) != self.issued { return; } - let _ = self.tx.send(event); + let _ = self.tx.send((self.issued, event)); } } diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index 1e22e815fe..8a1426be37 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -214,6 +214,53 @@ fn sign_out_recovers_save_after_a_backend_job_never_replies() { assert!(saved.is_ok(), "after sign-out and sign-in, Save is still refused: {saved:?}; busy={:?}", app.cloud.busy.as_ref().map(Busy::text)); } +/// While a sign-in waits on the browser, the previous account may still be the one the service +/// answers for. No folder is listed until the sign-in answers, and then both are listed again, +/// so a listing from before the sign-in does not stay on screen as the new account's files. +#[test] +fn folders_are_listed_again_only_after_a_sign_in_answers() { + let (mut app, held, _log) = two_tabs(); + let ctx = egui::Context::default(); + start(&mut app); + held.take(|j| matches!(j, Job::Account)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + held.take(|j| matches!(j, Job::List(_))).unwrap().1.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Ada.note", "a1")]) }); + drain(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + + sign_in(&mut app); + start(&mut app); + drain(&mut app, &ctx); + assert!(held.take(|j| matches!(j, Job::List(_))).is_none(), "a folder is listed before the sign-in says who is signed in"); + assert!(report(&app)["entries"].as_array().is_some_and(Vec::is_empty), "the previous account's files stay on screen during sign-in"); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Grace")))); + drain(&mut app, &ctx); + assert!(!app.cloud.mine.loading && !app.cloud.mine.loaded && !app.cloud.shared.loading && !app.cloud.shared.loaded); + start(&mut app); + let (_, list_post) = held.take(|j| matches!(j, Job::List(_))).expect("the root folder is listed again once the sign-in answers"); + list_post.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Grace.note", "g1")]) }); + drain(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!(["Grace.note"])); +} + +/// A sign-in empties the folder the Save As page was showing. Until it answers, a save would go +/// to the root rather than the folder the user picked, so Save As refuses. +#[test] +fn save_as_waits_for_a_sign_in_to_answer() { + let (mut app, held, _log) = two_tabs(); + browse(&mut app, "/Projects"); + sign_in(&mut app); + let folder = app.cloud.mine.path.clone(); + let refused = save_as(&mut app, &folder, "B"); + assert!(refused.is_err(), "Save As went ahead during sign-in: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none()); + + held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + assert!(save_as(&mut app, "", "B").is_ok()); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_some()); +} + /// An account and a listing answer a job issued before sign-out. Landing after it, they must /// not put the previous session's account and file names on screen with nobody signed in. #[test] diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index b1013a8ad4..fb3f0a5541 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -178,7 +178,8 @@ pub struct Guest { /// exists. pub struct CloudFiles { backend: Option>, - events: (Sender, Receiver), + /// Each answer with the account generation its job was issued in. + events: (Sender, Receiver), /// The badge and its menu. Signing in is the only way into any of this. /// The badge is the only control that offers it. It lives here. An /// application declares no field for it. @@ -215,9 +216,14 @@ pub struct CloudFiles { /// stay set after a failed sign-in. sign_in_from_menu: bool, /// Bumped on sign-out and on a new sign-in. Stamped onto every [`Post`] - /// handed out by [`submit`] so a reply to a job issued before the bump is - /// dropped rather than applied to the session that replaced it. + /// handed out by [`submit`] and onto every answer it queues. [`pump`] + /// drops an answer to a job issued before the bump rather than applying + /// it to the session that replaced it. account_generation: Arc, + /// Set by [`sign_in`] and cleared by the account answer that follows it. + /// While it is set both folders read as loading, so no listing is asked + /// for before the service says who is now signed in. + relist_after_sign_in: bool, /// The document Save As must act on, when it is not the active one. /// /// Set only by the conflict modal's "Save as a copy", so the copy it asks @@ -256,6 +262,7 @@ impl CloudFiles { guest: None, sign_in_from_menu: false, account_generation: Arc::new(AtomicU64::new(0)), + relist_after_sign_in: false, save_as_target: None, } } @@ -371,11 +378,17 @@ pub fn sign_in(app: &mut A) { cloud.link = None; cloud.status = Some(working); // A new session. A job the previous one left outstanding may never - // answer, and if it does, that answer is not about this account: see - // `Post::send`. Busy goes with it, or a stuck read from before this + // answer, and if it does, that answer is not about this account: `pump` + // drops it. Busy goes with it, or a stuck read from before this // sign-in would leave Save refused for a session that never asked for it. + // A folder listing that was outstanding is dropped the same way. Both + // folders wait for the account answer, which empties them so the next + // frame lists them for the account that is now signed in. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.mine = Folder { loading: true, ..Folder::default() }; + cloud.shared = Folder { loading: true, ..Folder::default() }; + cloud.relist_after_sign_in = true; submit(app, Job::SignIn); } @@ -396,26 +409,32 @@ pub fn sign_out(app: &mut A) { cloud.status = Some(signed_out); // The session this window had ends here. A job it started may never // answer, and a reply that does arrive late must not land on whatever - // comes next: see `Post::send`. Busy goes with it, so an open or a save + // comes next: `pump` drops it. Busy goes with it, so an open or a save // that never heard back does not refuse every one after it forever. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.relist_after_sign_in = false; cloud.save_as_target = None; submit(app, Job::SignOut); } /// Lists one folder. An empty path is the user's root. +/// +/// Nothing is sent while a sign-in waits for its answer. A listing sent then +/// can answer after the account does, and its files may be the previous +/// account's; the answer empties the folder so it is listed again. pub fn browse(app: &mut A, path: &str) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().mine.begin(path); submit(app, Job::List(path.to_owned())); } -/// Lists what other people have shared with this user. +/// Lists what other people have shared with this user. Like [`browse`], it +/// sends nothing while a sign-in waits for its answer. pub fn load_shared(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().relist_after_sign_in { return; } app.cloud_mut().shared.begin(""); @@ -608,6 +627,9 @@ pub fn save_as(app: &mut A, folder: &str, name: &str) -> Result(app: &mut A, ctx: &egui::Context) { while let Ok(event) = app.cloud().events.1.try_recv() { arrived.push(event); } - for event in arrived { + for (issued, event) in arrived { + // A worker that sent just before a sign-out or a new sign-in passed + // `Post::send`'s check, and its answer waited here while the session + // changed. It is about the session that is gone. + if issued != app.cloud().account_generation.load(Ordering::Relaxed) { + continue; + } apply(app, event); } poll_link(app); @@ -649,6 +677,15 @@ pub fn pump(app: &mut A, ctx: &egui::Context) { fn apply(app: &mut A, event: Event) { let noun = app.kind().noun; + if matches!(event, Event::Account(_)) && app.cloud().relist_after_sign_in { + // The sign-in has answered, whether or not it succeeded. Both folders + // are emptied and not loading, so `start` and the Open page list them + // again for whoever is signed in now. + let cloud = app.cloud_mut(); + cloud.relist_after_sign_in = false; + cloud.mine = Folder::default(); + cloud.shared = Folder::default(); + } match event { Event::Account(Ok(account)) => { let linked = account.provider_linked; diff --git a/crates/cloud-ui/src/cloud/pages.rs b/crates/cloud-ui/src/cloud/pages.rs index 86e71d1c88..e969ecc28c 100644 --- a/crates/cloud-ui/src/cloud/pages.rs +++ b/crates/cloud-ui/src/cloud/pages.rs @@ -422,7 +422,9 @@ pub fn save_page(app: &mut A, ui: &mut Ui) -> bool { asked = typing.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); }); ui.add_space(10.0); - let ready = app.cloud().busy.is_none() && !document_name(&app.cloud().save_name, kind).is_empty(); + // A sign-in in progress has emptied the folder, so the destination is not + // the one the user picked until the folders are listed again. + let ready = app.cloud().busy.is_none() && !app.cloud().relist_after_sign_in && !document_name(&app.cloud().save_name, kind).is_empty(); if ui.add_enabled(ready, egui::Button::new(save_label)).clicked() { asked = true; } diff --git a/crates/cloud-ui/src/cloud/tests.rs b/crates/cloud-ui/src/cloud/tests.rs index 875612144f..82f818db01 100644 --- a/crates/cloud-ui/src/cloud/tests.rs +++ b/crates/cloud-ui/src/cloud/tests.rs @@ -197,6 +197,12 @@ fn pumped(app: &mut Notebook, ctx: &egui::Context) { ctx.end_pass().textures_delta.clear(); } +/// Puts an answer in the channel as a worker for the current session would. +fn deliver(app: &Notebook, event: Event) { + let issued = app.cloud.account_generation.load(Ordering::Relaxed); + app.cloud.events.0.send((issued, event)).unwrap(); +} + fn wired() -> (Notebook, Arc>>, egui::Context) { let mut app = Notebook::new(); let jobs = Arc::new(Mutex::new(Vec::new())); @@ -339,7 +345,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { pumped(&mut app, &ctx); jobs.lock().unwrap().clear(); // What a service answers when somebody else saved first. - app.cloud.events.0.send(Event::Saved { uid: 1, entry: Err(Fault::Conflict) }).unwrap(); + deliver(&app, Event::Saved { uid: 1, entry: Err(Fault::Conflict) }); pumped(&mut app, &ctx); assert_eq!(report(&app)["conflict"]["name"], "Minutes.note", "the user is told, and asked what to do"); assert_eq!(app.did().dropped, vec![1], "the version that did not land is forgotten"); @@ -349,7 +355,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() { #[test] fn no_account_yet_is_an_offer_to_link_and_never_an_error() { let (mut app, _jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Account(Err(Fault::NotLinked))).unwrap(); + deliver(&app, Event::Account(Err(Fault::NotLinked))); pumped(&mut app, &ctx); assert_eq!(report(&app)["link"], "offered"); assert_eq!(report(&app)["accountError"], serde_json::Value::Null, "not having linked an account yet is not a failure"); @@ -359,7 +365,7 @@ fn no_account_yet_is_an_offer_to_link_and_never_an_error() { #[test] fn a_browser_round_trip_is_polled_until_the_user_is_done() { let (mut app, jobs, ctx) = wired(); - app.cloud.events.0.send(Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }).unwrap(); + deliver(&app, Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }); pumped(&mut app, &ctx); assert_eq!(app.did().urls, vec!["https://cloud.example/link/abc".to_owned()], "the browser is opened for them"); assert_eq!(report(&app)["link"]["waiting"], "https://cloud.example/link/abc"); @@ -403,11 +409,10 @@ fn working_together_needs_somewhere_for_the_room_to_be_keyed_on() { #[test] fn a_conversation_uses_the_hosts_chat_opener() { let (mut app, _, ctx) = wired(); - app.cloud - .events - .0 - .send(Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() }))) - .unwrap(); + deliver( + &app, + Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })), + ); pumped(&mut app, &ctx); @@ -430,6 +435,75 @@ fn signing_out_forgets_everything_this_window_knew() { assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too"); } +#[test] +fn an_answer_queued_before_the_session_changed_is_dropped() { + let (mut app, _jobs, ctx) = wired(); + let old = Account { display: "Ada Lovelace".to_owned(), capabilities: vec![Capability::Files], provider_linked: true }; + + // A worker answers, and the answers wait in the channel while the user + // signs out in the same frame. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Account(Ok(old))); + post.dup().send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Minutes.note")]) }); + sign_out(&mut app); + pumped(&mut app, &ctx); + let state = report(&app); + assert_eq!(state["account"], serde_json::Value::Null, "the previous session's account must not come back"); + assert_eq!(state["entries"], serde_json::json!([]), "nor its files"); + + // The same across a new sign-in. + let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone()); + post.send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Stale.note")]) }); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert_eq!(report(&app)["entries"], serde_json::json!([]), "a listing for the signed-out session is not shown to the new one"); +} + +#[test] +fn a_sign_in_that_drops_a_listing_leaves_no_folder_loading() { + let (mut app, _jobs, ctx) = wired(); + + // Both listings are asked for, and the answer to the first waits in the + // channel while the user signs in again. The shared one never answers. + browse(&mut app, ""); + load_shared(&mut app); + sign_in(&mut app); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loading, "a dropped listing must not leave the folder loading forever"); + assert!(!app.cloud.shared.loading, "nor the shared one, which would then never be asked for again"); + + // A listing the new session asks for still completes. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); + assert_eq!(report(&app)["entries"], serde_json::json!(["Minutes.note", "Archive"])); +} + +#[test] +fn a_listing_asked_for_before_the_sign_in_answers_is_not_sent() { + let (mut app, jobs, ctx) = wired(); + sign_in(&mut app); + jobs.lock().unwrap().clear(); + + // Asked for after the sign-in and before its answer. A listing sent now + // could answer after the account does, and its files may be the previous + // account's. + browse(&mut app, ""); + load_shared(&mut app); + assert!( + !jobs.lock().unwrap().iter().any(|j| matches!(j, Job::List(_) | Job::SharedWithMe)), + "no listing goes out while the sign-in is outstanding" + ); + pumped(&mut app, &ctx); + assert!(!app.cloud.mine.loaded && !app.cloud.mine.loading, "the folder waits to be listed for the new account"); + assert!(!app.cloud.shared.loaded && !app.cloud.shared.loading, "and so does the shared one"); + + // Once the sign-in has answered, a listing goes through. + browse(&mut app, ""); + pumped(&mut app, &ctx); + assert!(app.cloud.mine.loaded); +} + #[test] fn bytes_are_said_the_way_a_person_reads_them() { assert_eq!(size_text(None), "");