Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
289 changes: 288 additions & 1 deletion e2e/profile-form.spec.ts

Large diffs are not rendered by default.

37 changes: 36 additions & 1 deletion e2e/team-review-fixes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test, type Page } from "@playwright/test";
import { openApp, waitForIdle } from "./support/app";
import { openApp, storedTags, waitForIdle } from "./support/app";
import { ADMIN_INVITE, MEMBER_INVITE, joinTeam, menu, space, toast } from "./support/team";

// A team's member and admin against the backend as the Rust and the team server judge them
Expand Down Expand Up @@ -289,6 +289,41 @@ test("leaving a team closes its profiles open here, saved to it; a withdrawal cl
expect(await page.evaluate(() => Object.keys((window as unknown as M).__shardxMock.state.running))).not.toContain("tp-misc-1");
});

test("a bulk team tag edit preserves tags added by teammates before the list refreshes", async ({ page }) => {
await asMember(page, allow(TEAM, "see", "edit"));
const profiles = ["tp-shop-1", "tp-misc-1"];
await page.evaluate(() => {
const mock = (window as unknown as M).__shardxMock;
mock.state.tags = {
tags: [
{ id: "t-review", name: "Needs review", color: "orange" },
{ id: "t-handoff", name: "Handoff", color: "violet" },
{ id: "t-verified", name: "Verified", color: "green" },
],
by_profile: {},
};
mock.emit("store-changed", "tags");
});
for (const id of profiles) await row(page, id).locator("[data-cell='checkbox'] input").check({ force: true });
await page.getByRole("toolbar", { name: /selected/ }).getByRole("button", { name: "Edit tags" }).click();
const review = page.getByRole("option", { name: "Needs review" });
await expect(review).toHaveAttribute("aria-selected", "false");

// The server has a teammate's changes, but the open picker has not read them yet.
await page.evaluate(() => {
const mock = (window as unknown as M).__shardxMock;
mock.state.tags.by_profile["tp-shop-1"] = ["t-handoff"];
mock.state.tags.by_profile["tp-misc-1"] = ["t-verified"];
});
await expect(page.getByRole("option", { name: "Handoff" })).toHaveAttribute("aria-selected", "false");
await review.click();
await expect(review).toHaveAttribute("aria-selected", "true");
await expect.poll(async () => {
const { by_profile } = await storedTags(page);
return profiles.map((id) => [...(by_profile[id] ?? [])].sort());
}).toEqual([["t-handoff", "t-review"], ["t-review", "t-verified"]]);
});

test("a queued write goes to the space it was made in, never the one in use after a switch", async ({ page }) => {
await asMember(page, allow(TEAM, "see", "start", "edit", "create"));
// The new tag's write waits on a slow server; the launcher moves to Personal meanwhile.
Expand Down
90 changes: 90 additions & 0 deletions src-tauri/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2250,6 +2250,60 @@ mod tests {
drop(t.srv);
}

#[tokio::test]
async fn team_tag_changes_preserve_other_members_tags_and_retry_a_stale_write() {
let t = Team::new(&[
allow(folder("Ads"), Action::See),
allow(folder("Ads"), Action::Edit),
allow(folder("Shops"), Action::See),
allow(folder("Shops"), Action::Start),
]).await;
t.folder("Ads").await;
t.folder("Shops").await;
let path = "/profiles/p-1";
let profile = |tags: &[&str]| {
json!({ "name": "Shop", "folder": "Ads", "data": b64(json!({})), "card": { "tags": tags } })
};
let change = |add: &[&str], remove: &[&str]| {
serde_json::from_value(json!({ "p-1": { "add": add, "remove": remove } })).unwrap()
};
t.admin_call(Method::PUT, path, Some(profile(&[]))).await;
t.enter().await;
let epoch = Some(crate::team::space_epoch());

t.admin_call(Method::PUT, path, Some(profile(&["red"]))).await;
let rows = crate::space::profile::list_all().unwrap();
assert!(rows[0].tags.as_ref().unwrap().is_empty(), "this launcher still has the old list");

// The server moves on once more, after the launcher has read the latest card.
crate::space::hold::arm();
let save = tokio::spawn(crate::tag_assign(Default::default(), change(&["blue"], &[]), epoch));
crate::space::hold::wait_reached().await;
t.admin_call(Method::PUT, path, Some(profile(&["red", "green"]))).await;
crate::space::hold::release();
save.await.unwrap().unwrap();

let there = t.on_server("p-1").await;
assert_eq!(there["card"]["tags"], json!(["red", "green", "blue"]));

t.admin_call(Method::PUT, path, Some(profile(&["red", "green", "blue", "gold"]))).await;
let revision = t.on_server("p-1").await["revision"].clone();
crate::tag_assign(Default::default(), change(&["blue"], &[]), epoch).await.unwrap();
assert_eq!(t.on_server("p-1").await["revision"], revision, "already applied");
assert_eq!(crate::space::profile::list_all().unwrap()[0].tags.as_deref().unwrap(), ["red", "green", "blue", "gold"]);

crate::tag_assign(Default::default(), change(&[], &["green"]), epoch).await.unwrap();
assert_eq!(t.on_server("p-1").await["card"]["tags"], json!(["red", "blue", "gold"]));

let mut moved = profile(&["red", "blue", "gold"]);
moved["folder"] = json!("Shops");
t.admin_call(Method::PUT, path, Some(moved)).await;
let error = crate::tag_assign(Default::default(), change(&["green"], &[]), epoch).await.unwrap_err();
assert!(error.contains("needs edit on the profile"), "{error}");
assert_eq!(t.on_server("p-1").await["card"]["tags"], json!(["red", "blue", "gold"]));
drop(t.srv);
}

#[tokio::test]
async fn a_write_from_an_old_revision_is_stale_and_one_under_a_lease_is_leased() {
let t = Team::new(&[allow(folder("Ads"), Action::See), allow(folder("Ads"), Action::Edit)]).await;
Expand Down Expand Up @@ -2292,6 +2346,42 @@ mod tests {
drop(t.srv);
}

#[tokio::test]
async fn a_profile_conflict_reads_current_settings_in_the_editors_team_space() {
let t = Team::new(&[allow(folder("Ads"), Action::See), allow(folder("Ads"), Action::Edit)]).await;
t.folder("Ads").await;
t.profile("p-1", "Ads", "First", json!({ "other_setting": "before" })).await;
t.enter().await;
let id = "p-1".to_string();
let epoch = crate::team::space_epoch();
let opened = crate::profile_get(id.clone()).await.unwrap();
let revision = opened["_meta"]["rev"].as_u64().unwrap();
assert_eq!(opened["other_setting"], "before");

// The team server has a newer version while this device still holds what it opened.
t.profile(&id, "Ads", "Theirs", json!({ "other_setting": "after" })).await;
let mut draft = opened.clone();
draft["name"] = json!("Mine");
let error = crate::save_profile_core(None, draft, false, Door("profile_save"), &Ticket::now()).await.unwrap_err();
assert!(error.to_string().contains("changed after you opened it"), "{error}");
assert_eq!(crate::profile_get(id.clone()).await.unwrap(), opened);

let current = crate::profile_get_for_edit(id.clone(), epoch).await.unwrap();
assert_eq!(current["_meta"]["rev"], revision + 1);
assert_eq!(current["name"], "Theirs");
assert_eq!(current["other_setting"], "after");
assert_eq!(crate::profile_get(id.clone()).await.unwrap(), opened, "ordinary reads still use their cache");

t.set_grants(&[allow(folder("Ads"), Action::See)]).await;
let error = crate::profile_get_for_edit(id.clone(), epoch).await.unwrap_err();
assert!(error.contains("needs edit on the profile"), "{error}");

crate::space::switch(Space::Personal).await.unwrap();
let error = crate::profile_get_for_edit(id, epoch).await.unwrap_err();
assert_eq!(error, CmdError::SpaceChanged.to_string());
drop(t.srv);
}

#[tokio::test]
async fn moving_a_profile_needs_create_where_it_lands() {
let ads = [allow(folder("Ads"), Action::See), allow(folder("Ads"), Action::Edit)];
Expand Down
29 changes: 27 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ async fn profile_get(id: String) -> Result<Value, String> {
serde_json::to_value(stored).map_err(|e| e.to_string())
}

/// Read the server's latest settings after an edit conflict in a team.
#[tauri::command]
async fn profile_get_for_edit(id: String, epoch: u64) -> Result<Value, String> {
let t = ticket(Some(epoch))?;
let mut stored = space::profile::fetch_current_for_edit(&t, &id).await.map_err(|e| e.to_string())?;
if stored.meta.gpu_preset_id.is_none() && stored.meta.lock.is_none() {
stored.meta.gpu_preset_id = infer_gpu_preset_id(&stored.config);
}
serde_json::to_value(stored).map_err(|e| e.to_string())
}

/// Recover library fingerprint id by matching webgl.renderer (+ screen if ambiguous).
fn infer_gpu_preset_id(config: &serde_json::Map<String, Value>) -> Option<String> {
let renderer = config.get("webgl")?.get("renderer")?.as_str()?;
Expand Down Expand Up @@ -1164,9 +1175,22 @@ async fn tag_delete(id: String, epoch: Option<u64>) -> Result<(), String> {
}

#[tauri::command]
async fn tag_assign(by_profile: std::collections::BTreeMap<String, Vec<String>>, epoch: Option<u64>) -> Result<(), String> {
async fn tag_assign(
by_profile: std::collections::BTreeMap<String, Vec<String>>,
changes: Option<std::collections::BTreeMap<String, space::tags::TagChange>>,
epoch: Option<u64>,
) -> Result<(), String> {
let t = ticket(epoch)?;
space::tags::assign(space::Door("tag_assign"), &t, by_profile).await.map_err(|e| e.to_string())
let door = space::Door("tag_assign");
if let Some(changes) = changes {
let result = space::tags::change(door, &t, changes).await;
// A bulk edit can have changed earlier profiles before a later one was refused.
notify_store_changed("profiles");
notify_store_changed("tags");
result.map_err(|e| e.to_string())
} else {
space::tags::assign(door, &t, by_profile).await.map_err(|e| e.to_string())
}
}

/// The tags the interface kept in its own storage, taken once.
Expand Down Expand Up @@ -2794,6 +2818,7 @@ pub fn run() {
helper_dismiss,
profile_list,
profile_get,
profile_get_for_edit,
profile_protect,
profile_unprotect,
profile_change_password,
Expand Down
6 changes: 5 additions & 1 deletion src-tauri/src/live_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@ mod device {
// ---- profiles ----
"profiles" => crate::profile_list().await.map(val),
"profile_get" => crate::profile_get(s(&a, "id")).await,
"profile_get_for_edit" => {
let epoch = a["epoch"].as_u64().ok_or("harness: profile_get_for_edit needs an epoch")?;
crate::profile_get_for_edit(s(&a, "id"), epoch).await
}
"create_profile" => {
let mut m = crate::library_profile(FP_ID, None)?;
m.insert("name".into(), Value::String(s(&a, "name")));
Expand Down Expand Up @@ -307,7 +311,7 @@ mod device {
"set_folder" => crate::profile_set_folder(s(&a, "id"), s(&a, "folder"), epoch()).await.map(val),
"folder_list" => crate::folder_list().await.map(val),
"tag_save" => crate::tag_save(from(&a["tag"])?, None, epoch()).await.map(val),
"tag_assign" => crate::tag_assign(from(&a["by_profile"])?, epoch()).await.map(val),
"tag_assign" => crate::tag_assign(from(&a["by_profile"])?, from(&a["changes"])?, epoch()).await.map(val),
"tag_list" => crate::tag_list().await.map(val),
"automation_create" => crate::automation_create(s(&a, "name"), epoch()).await.map(val),
"automation_save" => crate::automation_save(from(&a["project"])?, epoch()).await.map(val),
Expand Down
40 changes: 40 additions & 0 deletions src-tauri/src/space/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,16 @@ pub fn wrote_profile(team: &str, row: ProfileRow, data: Option<&str>) {
});
}

/// Advance a visible row learned from a fresh read, if the list is still older.
pub fn remember_profile_read(team: &str, got: ProfileWithData) {
change(team, |s| {
if let Some(row) = s.profiles.iter_mut().find(|r| r.id == got.row.id && r.revision < got.row.revision) {
s.details.insert(got.row.id.clone(), remote::stored(&got.row, Some(&got.data)));
*row = got.row;
}
});
}

pub fn dropped_profile(team: &str, id: &str) {
change(team, |s| {
s.profiles.retain(|r| r.id != id);
Expand Down Expand Up @@ -676,6 +686,13 @@ async fn refresh_held(team: &str, kinds: Kinds, tell: &Tell) {
#[cfg(test)]
static FILLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

fn tag_assignments(rows: &[ProfileRow]) -> HashMap<&str, &[String]> {
rows.iter()
.filter(|row| !row.card.tags.is_empty())
.map(|row| (row.id.as_str(), row.card.tags.as_slice()))
.collect()
}

/// 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<Got, Failed>) -> (Kinds, Option<TeamStatus>) {
let mut g = state();
Expand All @@ -700,6 +717,9 @@ fn keep(team: &str, kinds: Kinds, got: Result<Got, Failed>) -> (Kinds, Option<Te
if let Some(rows) = got.profiles {
if rows != s.profiles {
changed = changed.with(Kinds::PROFILES);
if tag_assignments(&rows) != tag_assignments(&s.profiles) {
changed = changed.with(Kinds::TAGS);
}
}
s.profiles = rows;
let rows = &s.profiles;
Expand Down Expand Up @@ -952,6 +972,26 @@ mod tests {
drop(t.srv);
}

#[tokio::test]
async fn a_profile_refresh_tells_tags_only_when_assignments_change() {
let t = Team::new(&[on(Scope::Team, Action::See)]).await;
t.profile("p-1", "", json!({})).await;
reload(&t.team_id, t.tell()).await;
t.told.lock().unwrap().clear();

let lease = "/profiles/p-1/lease";
t.admin().call(Method::POST, lease, None).await.unwrap();
reload(&t.team_id, t.tell()).await;
assert_eq!(t.topics(), ["profiles"]);
t.told.lock().unwrap().clear();

t.admin().call(Method::DELETE, lease, None).await.unwrap();
t.put("/profiles/p-1", json!({ "name": "name of p-1", "data": b64(json!({})), "card": { "tags": [] } })).await;
reload(&t.team_id, t.tell()).await;
assert_eq!(t.topics(), ["profiles", "tags"]);
drop(t.srv);
}

#[tokio::test]
async fn a_team_changed_event_refreshes_within_a_second() {
let t = Team::new(&[on(Scope::Team, Action::See)]).await;
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/space/doors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ const RULES: &[(&str, Need)] = &[
// Profiles.
("profile_list", SEE_P),
("profile_get", SEE_P),
("profile_get_for_edit", SEE_P),
// A password-protected profile is this machine's own: no team profile has one (#127).
("profile_protect", Off),
("profile_unprotect", Off),
Expand Down
15 changes: 14 additions & 1 deletion src-tauri/src/space/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,12 +397,18 @@ pub mod profile {
/// The settings to change and save whole: a team's as its server has them now.
pub async fn fetch_for_edit(t: &Ticket, id: &str) -> Result<StoredProfile> {
match t.team() {
Some(team) => Ok(write::read_for_edit(team, id).await?),
Some(team) => Ok(write::read_for_edit(team, id, None).await?),
None if !local::exists(id) => Err(missing_here(id)),
None => local::load_raw(id),
}
}

/// Current settings for an edit conflict, in the workspace that opened it.
pub async fn fetch_current_for_edit(t: &Ticket, id: &str) -> Result<StoredProfile> {
let team = t.team().ok_or(CmdError::NotOffered("this profile refresh requires a team space"))?;
Ok(write::read_for_edit(team, id, Some(t)).await?)
}

/// A new profile's door, asked before anything made for it (a proxy) is stored.
pub fn check_create(door: Door, t: &Ticket, folder: &str, made: &Made<'_>) -> Result<()> {
match t.team() {
Expand Down Expand Up @@ -808,6 +814,7 @@ pub mod tags {
use std::collections::BTreeMap;

pub use local::{Tag, TagState};
pub use write::TagChange;

pub fn list() -> Result<TagState> {
match team_now() {
Expand Down Expand Up @@ -850,6 +857,12 @@ pub mod tags {
}
}

/// Changes the listed tags on a team's profiles without replacing the rest.
pub async fn change(door: Door, t: &Ticket, changes: BTreeMap<String, TagChange>) -> Result<()> {
let team = t.team().ok_or(super::CmdError::NotOffered("tag changes require a team space"))?;
Ok(write::change_tags(door, t, team, changes).await?)
}

/// The interface's old copy, taken once: false when tags were saved here already.
pub fn import(t: &Ticket, state: TagState) -> Result<bool> {
t.here(NOT_IN_TEAM)?;
Expand Down
Loading