diff --git a/e2e/team-space.spec.ts b/e2e/team-space.spec.ts index 216585658..c48b80ea3 100644 --- a/e2e/team-space.spec.ts +++ b/e2e/team-space.spec.ts @@ -1,6 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; +import type { SpaceState, TeamWorkspace } from "../src/entities/space/model/types"; import { openApp, waitForIdle } from "./support/app"; -import { ADMIN_INVITE, ADMIN_TEAM, joinTeam, menu, space, toast } from "./support/team"; +import { ADMIN_INVITE, ADMIN_TEAM, MEMBER_INVITE, joinTeam, menu, space, toast } from "./support/team"; // The space under every write and list (team steps 5 and 6). The mock keeps each space's lists // apart and refuses writes as space/mod.rs does (src/dev/mock/spaces.ts). @@ -276,6 +277,79 @@ test("unsaved changes are asked about before a switch: Cancel stays, Don’t sav await expect.poll(() => page.evaluate(() => (window as unknown as M).__shardxMock.state.settings.minimize_to_tray)).toBe(!before); }); +test("delayed team status belongs to its original workspace", async ({ page }) => { + const readWorkspace = () => page.evaluate(async () => { + const state = await (window as unknown as M).__TAURI_INTERNALS__.invoke("space_state") as SpaceState; + if (state.space.kind !== "team") throw new Error("Expected a team workspace"); + const teamId = state.space.team_id; + const team = state.teams.find((link) => link.id === teamId)!; + return { team_id: teamId, member_id: team.member_id, perm_key: team.perm_key, epoch: state.epoch }; + }); + const sendOffline = (workspace: TeamWorkspace) => page.evaluate(async (scope) => { + (window as unknown as M).__shardxMock.emit("team-status", { workspace: scope, status: { state: "offline" } }); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + }, workspace); + + await inTeam(page); + const ads = await readWorkspace(); + await joinTeam(page, MEMBER_INVITE); + await expect(space(page)).toHaveText("Shops team"); + await sendOffline(ads); + await expect(banner(page)).toHaveCount(0); + + await switchTo(page, "Personal"); + await expect(space(page)).toHaveText("Personal"); + await switchTo(page, "Ads team"); + await expect(space(page)).toHaveText("Ads team"); + const returned = await readWorkspace(); + expect(returned.epoch).toBeGreaterThan(ads.epoch); + await sendOffline(ads); + await expect(banner(page)).toHaveCount(0); + + await joinTeam(page, ADMIN_INVITE.replace(/#.+/, "#stm_mock_dana")); + const rejoined = await readWorkspace(); + expect(rejoined.team_id).toBe(returned.team_id); + expect(rejoined.member_id).not.toBe(returned.member_id); + expect(rejoined.epoch).toBeGreaterThan(returned.epoch); + // Match the new epoch to exercise the membership and key checks independently. + await sendOffline({ ...returned, epoch: rejoined.epoch }); + await sendOffline({ ...rejoined, perm_key: "old-key" }); + await expect(banner(page)).toHaveCount(0); + await sendOffline(rejoined); + await expect(banner(page)).toHaveAttribute("data-team-status", "offline"); +}); + +test("an earlier space_state reply cannot return the window to a workspace it left", async ({ page }) => { + await inTeam(page); + type HeldReply = M & { releaseWorkspace: () => void }; + await page.evaluate(async () => { + const w = window as unknown as HeldReply; + const ipc = w.__TAURI_INTERNALS__; + const invoke = ipc.invoke; + const held = new Promise((resolve) => { w.releaseWorkspace = resolve; }); + let capture!: () => void; + const captured = new Promise((resolve) => { capture = resolve; }); + ipc.invoke = async (cmd, args) => { + if (cmd !== "space_state") return invoke(cmd, args); + ipc.invoke = invoke; + const oldState = await invoke(cmd, args); + capture(); + await held; + return oldState; + }; + w.__shardxMock.emit("space-changed"); + await captured; + }); + await switchTo(page, "Personal"); + await expect(space(page)).toHaveText("Personal"); + await page.evaluate(async () => { + (window as unknown as HeldReply).releaseWorkspace(); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + }); + await expect(space(page)).toHaveText("Personal"); + await expect(row(page, SANDBOX)).toBeVisible(); +}); + test("joining a team with unsaved changes asks first; Cancel keeps the invite open and joins nothing", async ({ page }) => { await openApp(page, { section: "settings" }); await page.getByRole("switch", { name: /tray/i }).click(); diff --git a/src-tauri/src/space/cache.rs b/src-tauri/src/space/cache.rs index 92fe923c4..3ca247d56 100644 --- a/src-tauri/src/space/cache.rs +++ b/src-tauri/src/space/cache.rs @@ -11,6 +11,8 @@ use futures_util::StreamExt; use serde::Serialize; use serde_json::json; +use crate::team::TeamWorkspace; + use super::automation::Project; use super::bookmarks::Bookmark; use super::client::{TeamClient, TeamError}; @@ -128,7 +130,7 @@ pub struct TeamStatus { #[derive(Default)] struct Snapshot { - team: String, + workspace: TeamWorkspace, /// A read of every list has come back. full: bool, failed_at: Option, @@ -152,12 +154,12 @@ impl Snapshot { fn detail(&self, row: &ProfileRow) -> Option<&StoredProfile> { self.details .get(&row.id) - .filter(|d| d.meta.rev == row.revision && reads_settings(&perm::rights(&self.team, &row.id, &row.folder))) + .filter(|d| d.meta.rev == row.revision && reads_settings(&perm::rights(&self.workspace.team_id, &row.id, &row.folder))) } /// A proxy's login, while the permission held still hands it out. fn login(&self, id: &str) -> Option<&str> { - self.logins.get(id).filter(|_| perm::may_use_proxy(&self.team, id)).map(|(_, d)| d.as_str()) + self.logins.get(id).filter(|_| perm::may_use_proxy(&self.workspace.team_id, id)).map(|(_, d)| d.as_str()) } fn items(&self, kind: &str) -> &[ItemRow] { @@ -176,9 +178,15 @@ fn fill_turn() -> &'static tokio::sync::Mutex<()> { T.get_or_init(|| tokio::sync::Mutex::new(())) } -/// `f` over what is held for `team`; None when nothing is. +fn workspace(team: &str) -> Option { + crate::team::active_workspace().filter(|scope| scope.team_id == team) +} + +/// `f` over what is held for this entry into the team. fn with(team: &str, f: impl FnOnce(&Snapshot) -> T) -> Option { - state().as_ref().filter(|s| s.team == team).map(f) + let g = state(); + let scope = workspace(team)?; + g.as_ref().filter(|s| s.workspace == scope).map(f) } fn now_secs() -> u64 { @@ -187,8 +195,8 @@ fn now_secs() -> u64 { // ---- reads ---- -pub fn status(team: &str) -> TeamStatus { - with(team, |s| s.status.clone()).unwrap_or_default() +pub(crate) fn status(scope: &TeamWorkspace) -> TeamStatus { + state().as_ref().filter(|s| &s.workspace == scope).map(|s| s.status.clone()).unwrap_or_default() } /// Profiles by name: a team's rows have no order of their own. @@ -267,7 +275,8 @@ pub fn tests(team: &str, proxy_id: &str) -> Vec { /// Keep a test of a team proxy, here only; answers it as kept. pub fn keep_test(team: &str, proxy_id: &str, snap: TestSnapshot) -> TestSnapshot { let mut g = state(); - match g.as_mut().filter(|s| s.team == team && s.proxies.iter().any(|r| r.id == proxy_id)) { + let scope = workspace(team); + match g.as_mut().filter(|s| Some(&s.workspace) == scope.as_ref() && s.proxies.iter().any(|r| r.id == proxy_id)) { Some(s) => super::local::proxy::keep_test(s.tests.entry(proxy_id.to_string()).or_default(), snap), None => super::local::proxy::keep_test(&mut Vec::new(), snap), } @@ -278,11 +287,11 @@ pub fn keep_test(team: &str, proxy_id: &str, snap: TestSnapshot) -> TestSnapshot pub async fn profile_detail(team: &str, id: &str) -> Result { let found = with(team, |s| { let row = s.profiles.iter().find(|r| r.id == id)?; - Some((row.clone(), s.detail(row).cloned())) + Some((s.workspace.clone(), row.clone(), s.detail(row).cloned())) }) .flatten(); let missing = || super::CmdError::Missing(format!("no profile {id} in this team")); - let Some((row, cached)) = found else { return Err(missing().into()) }; + let Some((scope, row, cached)) = found else { return Err(missing().into()) }; if let Some(d) = cached { return Ok(d); } @@ -291,10 +300,15 @@ pub async fn profile_detail(team: &str, id: &str) -> Result { } let client = TeamClient::for_team(team)?; let path = format!("/profiles/{}", super::admin::seg(id)?); - match client.get::(&path).await { + let got = client.get::(&path).await; + let mut g = state(); + if workspace(team).as_ref() != Some(&scope) { + return Err(super::CmdError::SpaceChanged.into()); + } + match got { Ok(got) => { let stored = remote::stored(&got.row, Some(&got.data)); - if let Some(s) = state().as_mut().filter(|s| s.team == team) { + if let Some(s) = g.as_mut().filter(|s| s.workspace == scope) { if s.profiles.iter().any(|r| r.id == id && r.revision == got.row.revision) { s.details.insert(id.to_string(), stored.clone()); } @@ -329,7 +343,9 @@ pub fn proxy_row(team: &str, id: &str) -> Option { /// `f` over the team's held lists; nothing when another team's are held. fn change(team: &str, f: impl FnOnce(&mut Snapshot)) { - if let Some(s) = state().as_mut().filter(|s| s.team == team) { + let mut g = state(); + let scope = workspace(team); + if let Some(s) = g.as_mut().filter(|s| Some(&s.workspace) == scope.as_ref()) { f(s); } } @@ -452,10 +468,19 @@ pub fn dropped_item(team: &str, kind: &str, id: &str) { // ---- filling ---- -/// Drop what is held unless it is `team`'s: the space moved, or the team went. +/// Drop what is held when the workspace moves or the team goes. +pub fn retain_active() { + let mut g = state(); + let scope = crate::team::active_workspace(); + if g.as_ref().is_some_and(|s| Some(&s.workspace) != scope.as_ref()) { + *g = None; + } +} + +#[cfg(test)] pub fn keep_only(team: Option<&str>) { let mut g = state(); - if g.as_ref().is_some_and(|s| Some(s.team.as_str()) != team) { + if g.as_ref().is_some_and(|s| Some(s.workspace.team_id.as_str()) != team) { *g = None; } } @@ -463,13 +488,13 @@ pub fn keep_only(team: Option<&str>) { /// The team was left or withdrew this member. pub fn forget(team: &str) { let mut g = state(); - if g.as_ref().is_some_and(|s| s.team == team) { + if g.as_ref().is_some_and(|s| s.workspace.team_id == team) { *g = None; } } -fn needs_fill(team: &str) -> bool { - match state().as_ref().filter(|s| s.team == team) { +fn needs_fill(scope: &TeamWorkspace) -> bool { + match state().as_ref().filter(|s| &s.workspace == scope) { Some(s) if s.full => false, Some(s) => s.failed_at.is_none_or(|t| t.elapsed() >= RETRY_AFTER), None => true, @@ -479,31 +504,34 @@ fn needs_fill(team: &str) -> bool { /// Before a read of the team in use: fill its lists if none are held, and /// wait a while for them. Nothing to do in the personal space. pub async fn ready() { - let Some(team) = crate::team::active_team() else { return }; - if needs_fill(&team) { - run_and_wait(team, true, super::live::default_tell()).await; + let Some(scope) = crate::team::active_workspace() else { return }; + if needs_fill(&scope) { + run_and_wait(scope, true, super::live::default_tell()).await; } } /// Read again what a `team-changed` of `what` would, now: after a write that /// moved more than its own row. pub async fn refetch(team: &str, what: &str) { + let Some(scope) = workspace(team) else { return }; let _turn = fill_turn().lock().await; - refresh_held(team, Kinds::of(what), &super::live::default_tell()).await; + refresh_held(&scope, Kinds::of(what), &super::live::default_tell()).await; } /// Read every list of the team now, as on a switch, waiting a while for it. pub async fn reload(team: &str, tell: Tell) { - run_and_wait(team.to_string(), false, tell).await; + if let Some(scope) = workspace(team) { + run_and_wait(scope, false, tell).await; + } } /// The fill goes on past the wait; it tells the windows when it lands. -async fn run_and_wait(team: String, only_if_needed: bool, tell: Tell) { +async fn run_and_wait(scope: TeamWorkspace, only_if_needed: bool, tell: Tell) { let (done, wait) = tokio::sync::oneshot::channel(); super::live::spawn(async move { let _turn = fill_turn().lock().await; - if !only_if_needed || needs_fill(&team) { - refresh_held(&team, Kinds::ALL, &tell).await; + if !only_if_needed || needs_fill(&scope) { + refresh_held(&scope, Kinds::ALL, &tell).await; } let _ = done.send(()); }); @@ -511,7 +539,7 @@ async fn run_and_wait(team: String, only_if_needed: bool, tell: Tell) { } struct Pending { - team: String, + workspace: TeamWorkspace, kinds: Kinds, } @@ -531,23 +559,29 @@ pub fn heard_all(team: &str, tell: &Tell) { } fn schedule(team: &str, kinds: Kinds, tell: &Tell) { - if kinds == Kinds::NONE || crate::team::active_team().as_deref() != Some(team) { + if kinds == Kinds::NONE { return; } - { + let scope = { let mut p = pending(); - if let Some(job) = p.as_mut().filter(|j| j.team == team) { + let Some(scope) = workspace(team) else { return }; + if let Some(job) = p.as_mut().filter(|j| j.workspace == scope) { job.kinds = job.kinds.with(kinds); return; } - *p = Some(Pending { team: team.to_string(), kinds }); - } + *p = Some(Pending { workspace: scope.clone(), kinds }); + scope + }; let tell = tell.clone(); super::live::spawn(async move { tokio::time::sleep(COALESCE).await; - let Some(job) = pending().take() else { return }; + let job = { + let mut queued = pending(); + if queued.as_ref().is_some_and(|job| job.workspace == scope) { queued.take() } else { None } + }; + let Some(job) = job else { return }; let _turn = fill_turn().lock().await; - refresh_held(&job.team, job.kinds, &tell).await; + refresh_held(&job.workspace, job.kinds, &tell).await; }); } @@ -652,14 +686,14 @@ async fn login(c: &TeamClient, team: &str, id: String) -> Option<(String, u64, S } /// Refetch, keep, and tell what changed. The caller holds the fill turn. -async fn refresh_held(team: &str, kinds: Kinds, tell: &Tell) { - // Only the team in use is kept. - if crate::team::active_team().as_deref() != Some(team) { +async fn refresh_held(scope: &TeamWorkspace, kinds: Kinds, tell: &Tell) { + let team = scope.team_id.as_str(); + if workspace(team).as_ref() != Some(scope) { return; } let kinds = if with(team, |s| s.full).unwrap_or(false) { kinds } else { Kinds::ALL }; let got = fetch(team, kinds).await; - let (changed, status) = keep(team, kinds, got); + let (changed, status) = keep(scope, kinds, got); #[cfg(test)] FILLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); for (k, topic) in TOPICS { @@ -668,7 +702,7 @@ async fn refresh_held(team: &str, kinds: Kinds, tell: &Tell) { } } if let Some(st) = status { - tell("team-status", serde_json::to_value(st).unwrap_or_default()); + tell("team-status", json!({ "workspace": scope, "status": st })); } } @@ -677,14 +711,15 @@ async fn refresh_held(team: &str, kinds: Kinds, tell: &Tell) { static FILLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Put what came back in place; answers the lists that changed and the new status, if it moved. -fn keep(team: &str, kinds: Kinds, got: Result) -> (Kinds, Option) { +fn keep(scope: &TeamWorkspace, kinds: Kinds, got: Result) -> (Kinds, Option) { let mut g = state(); - // Left or switched away while it was asked: checked under the lock a forget takes. - if crate::team::active_team().as_deref() != Some(team) { + let team = scope.team_id.as_str(); + // Never install old rows into a new entry or member's view of the same team. + if workspace(team).as_ref() != Some(scope) { return (Kinds::NONE, None); } - if g.as_ref().is_none_or(|s| s.team != team) { - *g = Some(Snapshot { team: team.to_string(), ..Default::default() }); + if g.as_ref().is_none_or(|s| &s.workspace != scope) { + *g = Some(Snapshot { workspace: scope.clone(), ..Default::default() }); } let Some(s) = g.as_mut() else { return (Kinds::NONE, None) }; let before = s.status.clone(); @@ -1027,6 +1062,68 @@ mod tests { } } + #[tokio::test] + async fn a_fill_left_in_flight_cannot_populate_a_later_workspace() { + let t = Team::new(&[on(Scope::Team, Action::See)]).await; + t.profile("p-1", "Ads", json!({})).await; + reload(&t.team_id, t.tell()).await; + let first = workspace(&t.team_id).unwrap(); + let delayed = fetch(&t.team_id, Kinds::ALL).await.ok().expect("the initial read worked"); + assert_eq!(t.ids(), ["p-1"]); + assert!(t.told.lock().unwrap().iter().any(|(name, payload)| { + name == "team-status" && payload["workspace"] == json!(first) && payload["status"]["state"] == "ready" + })); + + let other = TestServer::start(t.root.path.join("other-server")).await.unwrap(); + let joined = team::join(&other.url, &other.admin_token).await.unwrap(); + assert!(joined.epoch > first.epoch); + assert!(t.ids().is_empty()); + let old_failure = Failed { offline: true, why: "late failure from the first team".into() }; + let (changed, told) = keep(&first, Kinds::ALL, Err(old_failure)); + assert!(changed == Kinds::NONE && told.is_none()); + + team::set_space(Space::Personal).unwrap(); + let returned = team::set_space(Space::Team { team_id: t.team_id.clone() }).unwrap(); + assert!(returned.epoch > first.epoch); + assert_eq!(returned.team_status.unwrap().state, Reach::Loading); + assert!(t.ids().is_empty(), "the first entry's snapshot is hidden before a new fill"); + let (changed, told) = keep(&first, Kinds::ALL, Ok(delayed)); + assert!(changed == Kinds::NONE && told.is_none()); + assert!(t.ids().is_empty(), "the delayed fill did not populate the new entry"); + + reload(&t.team_id, t.tell()).await; + assert_eq!(t.ids(), ["p-1"]); + assert_eq!(team::state().unwrap().team_status.unwrap().state, Reach::Ready); + } + + #[tokio::test] + async fn changing_members_hides_the_old_team_snapshot_before_the_next_fill() { + let t = Team::new(&[on(Scope::Team, Action::See)]).await; + t.profile("p-1", "Ads", json!({})).await; + reload(&t.team_id, t.tell()).await; + let first = workspace(&t.team_id).unwrap(); + let delayed = fetch(&t.team_id, Kinds::ALL).await.ok().expect("the initial read worked"); + assert_eq!(t.ids(), ["p-1"]); + + let member = t.srv.add_member("New member", &[]).unwrap(); + let joined = team::join(&t.srv.url, &member.token).await.unwrap(); + let current = workspace(&t.team_id).unwrap(); + assert_eq!(current.team_id, first.team_id); + assert_ne!(current.member_id, first.member_id); + assert!(joined.epoch > first.epoch); + assert_eq!(joined.team_status.unwrap().state, Reach::Loading); + assert!(t.ids().is_empty()); + let (changed, told) = keep(&first, Kinds::ALL, Ok(delayed)); + assert!(changed == Kinds::NONE && told.is_none()); + assert!(t.ids().is_empty()); + + // Match the ordinary join path's reset of the permission for the old member. + perm::forget(&t.team_id); + reload(&t.team_id, t.tell()).await; + assert_eq!(team::state().unwrap().team_status.unwrap().state, Reach::Ready); + assert!(t.ids().is_empty()); + } + #[tokio::test] async fn after_a_restart_nothing_of_the_team_is_on_disk() { let all = [Action::See, Action::Start, Action::Edit, Action::Cookies, Action::TakeOut]; @@ -1090,7 +1187,7 @@ mod tests { super::super::ready().await; assert!(super::super::profile::list_all().unwrap().is_empty()); assert!(super::super::proxy::list().unwrap().is_empty()); - let st = status(&team_id); + let st = team::state().unwrap().team_status.unwrap(); assert_eq!(st.state, Reach::Offline, "{st:?}"); drop(root); } diff --git a/src-tauri/src/space/mod.rs b/src-tauri/src/space/mod.rs index d3122ea6d..d2b9c92d3 100644 --- a/src-tauri/src/space/mod.rs +++ b/src-tauri/src/space/mod.rs @@ -218,8 +218,8 @@ pub async fn join(server: &str, token: &str) -> Result /// After the space moved: only the team in use is held, and it is read now. pub async fn settle() { + cache::retain_active(); let team = team_now(); - cache::keep_only(team.as_deref()); let tell = live::default_tell(); if let Some(team) = &team { cache::reload(team, tell.clone()).await; diff --git a/src-tauri/src/team.rs b/src-tauri/src/team.rs index 242ac1a14..f463b1773 100644 --- a/src-tauri/src/team.rs +++ b/src-tauri/src/team.rs @@ -90,6 +90,36 @@ struct Saved { machine: String, } +impl Saved { + fn active_link(&self) -> Option<&TeamLink> { + let Space::Team { team_id } = &self.space else { return None }; + self.teams.iter().find(|link| &link.id == team_id && link.usable()) + } + + // Only for checking whether an in-flight read still belongs to this connection. + fn active_identity(&self) -> Option<(&str, &str, &str, Option<&str>)> { + self.active_link().map(|link| { + (link.member_id.as_str(), link.perm_key.as_str(), link.server.as_str(), self.tokens.get(&link.id).map(String::as_str)) + }) + } + + fn workspace(&self, epoch: u64) -> Option { + let link = self.active_link()?; + Some(TeamWorkspace { + team_id: link.id.clone(), member_id: link.member_id.clone(), perm_key: link.perm_key.clone(), epoch, + }) + } +} + +/// The active team admission and this entry into its workspace. Carries no token. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub(crate) struct TeamWorkspace { + pub team_id: String, + pub member_id: String, + pub perm_key: String, + pub epoch: u64, +} + /// Where personal sync goes: a team server's `/me`, reached with the member's own token. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] struct SyncLink { @@ -226,6 +256,16 @@ pub fn active_team() -> Option { } } +pub(crate) fn active_workspace() -> Option { + loop { + let epoch = space_epoch(); + let saved = peek().ok()?; + if space_epoch() == epoch { + return saved.workspace(epoch); + } + } +} + /// This device's id, as leases name it. pub fn device_id() -> String { load().map(|s| s.device_id).unwrap_or_default() @@ -233,22 +273,23 @@ pub fn device_id() -> String { fn save(s: &Saved) -> Result<()> { let p = path()?; - let before = cell().read().ok().and_then(|g| g.as_ref().filter(|(at, _)| *at == p).map(|(_, s)| s.space.clone())); let body = serde_json::to_vec_pretty(s)?; let tmp = p.with_extension("json.tmp"); write_private(&tmp, &body)?; std::fs::rename(&tmp, &p).with_context(|| format!("replace {}", p.display()))?; if let Ok(mut g) = cell().write() { + let unchanged = g.as_ref().is_some_and(|(at, old)| { + *at == p && old.space == s.space && old.active_identity() == s.active_identity() + }); + if !unchanged { + SPACE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } *g = Some((p, s.clone())); } - if before.as_ref() != Some(&s.space) { - SPACE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } Ok(()) } -/// Up by one whenever the space in use changes: a write carries the edition it -/// was asked under, and one from before a switch is refused. +/// Up by one when the active space or its admission changes. static SPACE_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); pub fn space_epoch() -> u64 { @@ -330,12 +371,14 @@ fn machine_name() -> String { } pub fn state() -> Result { - let s = load()?; - let team_status = match &s.space { - Space::Team { team_id } => Some(crate::space::cache::status(team_id)), - Space::Personal => None, + let (s, epoch) = { + let _edit = edit_lock(); + (load()?, space_epoch()) }; - Ok(SpaceState { space: s.space, teams: s.teams, device_name: device_name(), epoch: space_epoch(), team_status }) + // Do not hold the team edit lock while reading the cache. + let team_status = s.workspace(epoch).as_ref().map(crate::space::cache::status); + let device_name = s.device_name.filter(|n| !n.trim().is_empty()).unwrap_or_else(machine_name); + Ok(SpaceState { space: s.space, teams: s.teams, device_name, epoch, team_status }) } pub fn set_space(space: Space) -> Result { @@ -710,9 +753,9 @@ pub fn forget_all() -> Result> { } if let Ok(mut g) = cell().write() { *g = None; + // Back in the personal space: a team write asked before this is refused. + SPACE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } - // Back in the personal space: a team write asked before this is refused. - SPACE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); Ok(ids) } diff --git a/src/dev/mock/spaces.ts b/src/dev/mock/spaces.ts index 3d0915a74..fd134ceb2 100644 --- a/src/dev/mock/spaces.ts +++ b/src/dev/mock/spaces.ts @@ -3,7 +3,7 @@ import type { MockState, StoredProfile } from "./fixtures"; import type { Ctx } from "./handlers"; import type { FingerprintEntry } from "../../entities/fingerprint/model/types"; -import type { SpaceState, TeamStatus } from "../../entities/space/model/types"; +import type { SpaceState, TeamLink, TeamStatus, TeamStatusEvent, TeamWorkspace } from "../../entities/space/model/types"; import { EPOCH_WRITES, SPACE_REFUSALS } from "../../shared/api/epochWrites"; import { TEAM_REFUSALS } from "../../shared/api/teamRefusals"; import { TEAM_WARNINGS } from "../../shared/api/backendWarnings"; @@ -29,8 +29,9 @@ const secsOf = (stamp: string | null): number | null => { return Number.isFinite(ms) && ms > 0 ? Math.floor(ms / 1000) : null; }; -/** Up by one each time the space in use changes (team.rs SPACE_EPOCH). */ +/** Up by one each time the active workspace changes (team.rs SPACE_EPOCH). */ let epoch = 1; +let admission: TeamWorkspace | undefined; /** Each team's reach, as its last read of the lists found it. */ const reach: Record = {}; @@ -50,6 +51,23 @@ export function teamInUse(state: MockState): string | null { return sp.kind === "team" ? sp.team_id : null; } +function teamLink(state: MockState, link: NonNullable[number]): TeamLink { + const me = state.teamServers?.[link.id]?.me; + return { member_id: link.admin ? "admin" : me ?? "", perm_key: "mock-perm-key", ...link }; +} + +function activeWorkspace(state: MockState): TeamWorkspace | undefined { + const team = (state.teams ?? []).find((link) => link.id === teamInUse(state)); + if (!team) return; + const { id, member_id, perm_key } = teamLink(state, team); + return { team_id: id, member_id, perm_key, epoch }; +} + +function tellReach(state: MockState, status: TeamStatus, emit: Ctx["emit"]): void { + const workspace = activeWorkspace(state); + if (workspace) emit("team-status", { workspace, status: { ...status } } satisfies TeamStatusEvent); +} + /** A team's reach; on first asking, what entering it found. `__shardxMockTeamStatus`, set * before, is that answer as given (no `synced_at`: nothing was ever read). */ function statusOf(team: string): TeamStatus { @@ -117,9 +135,11 @@ const takeOwn = (state: MockState): SpaceData => Object.fromEntries(OWN.map((k) export function settle(state: MockState, emit?: Ctx["emit"]): boolean { const want = keyOf(spaceInUse(state)); const have = state.dataOf ?? "personal"; - if (want === have) return false; - const kept = (state.spaceData ??= {}); - kept[have] = takeOwn(state); + const nextAdmission = activeWorkspace(state); + const sameTeamChanged = admission && nextAdmission && admission.team_id === nextAdmission.team_id + && (admission.member_id !== nextAdmission.member_id || admission.perm_key !== nextAdmission.perm_key); + admission = nextAdmission; + if (want === have && !sameTeamChanged) return false; // As cache.rs keep(): entering a team reads its lists, and the status that moved is told. const was = reach[want]; delete reach[want]; @@ -127,14 +147,18 @@ export function settle(state: MockState, emit?: Ctx["emit"]): boolean { // A server that never answered gave nothing to show: its cache is empty. const never = !!now && now.state !== "ready" && now.synced_at === undefined; if (never) unread.add(want); - const next = kept[want] ?? (want === "personal" || never ? emptyData() : teamSeed(state, want)); - delete kept[want]; - Object.assign(state, next); - if (!next.folders) delete state.folders; - if (!next.tags) delete state.tags; - state.dataOf = want; + if (want !== have) { + const kept = (state.spaceData ??= {}); + kept[have] = takeOwn(state); + const next = kept[want] ?? (want === "personal" || never ? emptyData() : teamSeed(state, want)); + delete kept[want]; + Object.assign(state, next); + if (!next.folders) delete state.folders; + if (!next.tags) delete state.tags; + state.dataOf = want; + } epoch++; - if (now && emit && (was?.state !== now.state || was?.error !== now.error)) emit("team-status", { ...now }); + if (now && emit && (was?.state !== now.state || was?.error !== now.error)) tellReach(state, now, emit); return true; } @@ -195,10 +219,7 @@ export function refusal(state: MockState, cmd: string, args: Record { - const me = state.teamServers?.[t.id]?.me; - return { member_id: t.admin ? "admin" : me ?? "", perm_key: "mock-perm-key", ...t }; - }); + const teams = (state.teams ?? []).map((t) => teamLink(state, t)); return { space, teams, device_name: "Mock-MacBook", epoch, ...(space.kind === "team" ? { team_status: { ...statusOf(space.team_id) } } : {}), @@ -231,7 +252,7 @@ export function setTeamStatus(state: MockState, next: Partial, emit: ...(next.synced_at !== undefined ? { synced_at: next.synced_at } : {}), }; reach[team] = now; - if (was.state !== now.state || was.error !== now.error) emit("team-status", { ...now }); + if (was.state !== now.state || was.error !== now.error) tellReach(state, now, emit); // Its first answer: the lists it never gave come now, and every page reads them. if (ready && unread.delete(team)) { Object.assign(state, teamSeed(state, team)); diff --git a/src/entities/space/model/store.ts b/src/entities/space/model/store.ts index bcb41aafe..1e3076e0c 100644 --- a/src/entities/space/model/store.ts +++ b/src/entities/space/model/store.ts @@ -3,7 +3,7 @@ import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { setSpaceEpoch, setSpaceReader } from "../../../shared/api/invoke"; import { confirmLeave } from "../../../shared/model/unsaved"; -import type { Space, SpaceState, TeamStatus } from "./types"; +import { activeTeam, type Space, type SpaceState, type TeamStatusEvent } from "./types"; let listening = false; @@ -18,6 +18,8 @@ export const useSpace = create<{ }>((set, get) => { // The state first, then its edition: the stores reset for it read the new space. const take = (state: SpaceState) => { + const current = get().state; + if (current && state.epoch < current.epoch) return; set({ state }); setSpaceEpoch(state.epoch); }; @@ -28,9 +30,14 @@ export const useSpace = create<{ listening = true; void listen("space-changed", () => void get().load().catch(() => {})); // The team server's reach as the backend's reads find it; the team in use only. - void listen("team-status", (e) => { + void listen("team-status", (e) => { const st = get().state; - if (st?.space.kind === "team") set({ state: { ...st, team_status: e.payload } }); + const team = activeTeam(st); + const { workspace, status } = e.payload ?? {}; + if (st && team && workspace && status && st.epoch === workspace.epoch && team.id === workspace.team_id + && team.member_id === workspace.member_id && team.perm_key === workspace.perm_key) { + set({ state: { ...st, team_status: status } }); + } }); } take(await invoke("space_state")); diff --git a/src/entities/space/model/types.ts b/src/entities/space/model/types.ts index 11b0075fc..325493514 100644 --- a/src/entities/space/model/types.ts +++ b/src/entities/space/model/types.ts @@ -16,6 +16,10 @@ export type TeamLink = { /** How the team's lists stand (cache.rs `TeamStatus`); `synced_at`: the last good read, unix seconds. */ export type TeamStatus = { state: "loading" | "ready" | "offline" | "refused"; error?: string; synced_at?: number }; +/** The active admission and entry that produced a team status update. */ +export type TeamWorkspace = { team_id: string; member_id: string; perm_key: string; epoch: number }; +export type TeamStatusEvent = { workspace: TeamWorkspace; status: TeamStatus }; + /** `epoch`: the space's edition, which every space write carries. `team_status`: in a team only. */ export type SpaceState = { space: Space; teams: TeamLink[]; device_name: string; epoch: number; team_status?: TeamStatus }; diff --git a/src/shared/api/edition.ts b/src/shared/api/edition.ts index b3f85b59a..0429f2171 100644 --- a/src/shared/api/edition.ts +++ b/src/shared/api/edition.ts @@ -12,7 +12,7 @@ export function spaceEpoch(): number | undefined { /** The space store's read of `space_state`; a new edition runs `onSpaceMoved`. */ export function setSpaceEpoch(next: number | undefined): void { - if (next === undefined || next === edition) return; + if (next === undefined || (edition !== undefined && next <= edition)) return; const was = edition; edition = next; if (was !== undefined) for (const fn of [...moved]) fn();