diff --git a/e2e/team-review-fixes.spec.ts b/e2e/team-review-fixes.spec.ts index 7e2b4e2dc..bcd8cad6e 100644 --- a/e2e/team-review-fixes.spec.ts +++ b/e2e/team-review-fixes.spec.ts @@ -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 @@ -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. diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 03cb375c8..8c3141f16 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -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; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc42f1ada..4e1e854af 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1164,9 +1164,22 @@ async fn tag_delete(id: String, epoch: Option) -> Result<(), String> { } #[tauri::command] -async fn tag_assign(by_profile: std::collections::BTreeMap>, epoch: Option) -> Result<(), String> { +async fn tag_assign( + by_profile: std::collections::BTreeMap>, + changes: Option>, + epoch: Option, +) -> 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. diff --git a/src-tauri/src/live_e2e.rs b/src-tauri/src/live_e2e.rs index edfdf07f3..9014b08d0 100644 --- a/src-tauri/src/live_e2e.rs +++ b/src-tauri/src/live_e2e.rs @@ -307,7 +307,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), diff --git a/src-tauri/src/space/cache.rs b/src-tauri/src/space/cache.rs index 92fe923c4..41cb2b873 100644 --- a/src-tauri/src/space/cache.rs +++ b/src-tauri/src/space/cache.rs @@ -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); @@ -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) -> (Kinds, Option) { let mut g = state(); @@ -700,6 +717,9 @@ fn keep(team: &str, kinds: Kinds, got: Result) -> (Kinds, Option Result { match team_now() { @@ -850,6 +851,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) -> 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 { t.here(NOT_IN_TEAM)?; diff --git a/src-tauri/src/space/write.rs b/src-tauri/src/space/write.rs index 82712bdb6..8eff1cc4d 100644 --- a/src-tauri/src/space/write.rs +++ b/src-tauri/src/space/write.rs @@ -246,18 +246,30 @@ async fn rewrite( ) -> Result<(), CmdError> { let c = client(team)?; let now = fresh(&c, id).await?; - let edit = perm::team_write::(team, On::Profile { id: id.to_string(), folder: now.row.folder.clone() })?; + let mut card = now.row.card.clone(); + change(&mut card); + write_card(t, team, &c, &now, dest, card).await +} + +async fn write_card( + t: &Ticket, + team: &str, + c: &TeamClient, + now: &ProfileWithData, + dest: Option<&str>, + card: team_model::Card, +) -> Result<(), CmdError> { + let id = &now.row.id; + let edit = perm::team_write::(team, On::Profile { id: id.clone(), folder: now.row.folder.clone() })?; let to = match dest.filter(|d| *d != now.row.folder) { Some(d) => Some(perm::team_write::(team, On::Folder(d.to_string()))?), None => None, }; - let mut card = now.row.card.clone(); - change(&mut card); let created_at = remote::made_at(&now.row, &now.data); let fields = ProfileFields { name: &now.row.name, data: &now.data, card: Some(&card), created_at }; let base = now.row.revision; t.commit().await?; - let w = remote::edit_profile(&c, &edit, to.as_ref(), &fields, base) + let w = remote::edit_profile(c, &edit, to.as_ref(), &fields, base) .await .map_err(|e| CmdError::from_team(e, &doing(need("edit", "profile"), "profile", id, Some(base))))?; cache::wrote_profile(team, remote::row_after(&w, Some(card), Some(&now.row)), Some(&now.data)); @@ -300,6 +312,46 @@ pub async fn assign_tags(door: Door, t: &Ticket, team: &str, by_profile: BTreeMa Ok(()) } +#[derive(serde::Deserialize)] +pub struct TagChange { + add: Vec, + remove: Vec, +} + +/// Adds or removes only the requested tags, preserving changes made elsewhere. +pub async fn change_tags(door: Door, t: &Ticket, team: &str, changes: BTreeMap) -> Result<(), CmdError> { + const MAX_RETRIES: usize = 2; + let c = client(team)?; + for (id, change) in changes { + let mut retries = MAX_RETRIES; + loop { + let now = fresh(&c, &id).await?; + doors::clear(door, team, &Ask { profile: Some((&id, &now.row.folder)), ..Default::default() })?; + let mut card = now.row.card.clone(); + card.tags.retain(|tag| !change.remove.contains(tag)); + for tag in &change.add { + if !card.tags.contains(tag) { + card.tags.push(tag.clone()); + } + } + if card.tags == now.row.card.tags { + // Someone else may already have made this change. Make it visible here too. + t.still()?; + cache::remember_profile_read(team, now); + break; + } + match write_card(t, team, &c, &now, None, card).await { + Err(CmdError::Stale { .. }) if retries > 0 => retries -= 1, + result => { + result?; + break; + } + } + } + } + Ok(()) +} + // ---- folders: the admin's ---- fn admin_path(name: &str) -> Result { diff --git a/src/dev/mock/handlers.ts b/src/dev/mock/handlers.ts index 0f7973574..a8294e4b9 100644 --- a/src/dev/mock/handlers.ts +++ b/src/dev/mock/handlers.ts @@ -23,6 +23,7 @@ import { TEAM_REFUSALS } from "../../shared/api/teamRefusals"; import type { ProxyEntry, ProxyTestSnapshot } from "../../entities/proxy/model/types"; import type { FingerprintEntry } from "../../entities/fingerprint/model/types"; import type { Project, RunState, ModuleInfo } from "../../entities/automation/model/types"; +import type { TagChange } from "../../entities/tag/model/api"; import type { ProfileTemplate } from "../../entities/template/model/types"; import { osOfPlatform, templateSettingsOf } from "../../entities/template/lib/settings"; @@ -87,6 +88,15 @@ function assignTags(s: MockTags, byProfile: Record) { } } +/** Apply explicit edits to the team's current assignments. */ +function changeTags(s: MockTags, changes: Record) { + const byProfile = Object.fromEntries(Object.entries(changes).map(([pid, { add, remove }]) => { + const kept = (s.by_profile[pid] ?? []).filter((id) => !remove.includes(id)); + return [pid, [...kept, ...add]]; + })); + assignTags(s, byProfile); +} + /** As folders.rs `rename`: a kept entry keeps its place, the look follows; a folder never kept stays unkept. */ function renameFolder(s: MockFolders, old: string, next: string) { const to = next.trim(); @@ -860,7 +870,19 @@ export const handlers: Record = { ctx.save(); return null; }, - tag_assign: ({ byProfile }, ctx) => { if (ctx.state.tags) { assignTags(ctx.state.tags, byProfile ?? {}); ctx.save(); } return null; }, + tag_assign: ({ byProfile, changes }, ctx) => { + const s = ctx.state.tags; + if (changes != null) { + if (!teamInUse(ctx.state)) throw "tag changes require a team space"; + if (s) changeTags(s, changes); + changed(ctx, "tags"); + ctx.emit("store-changed", "profiles"); + } else if (s) { + assignTags(s, byProfile ?? {}); + ctx.save(); + } + return null; + }, // Taken only while nothing was ever saved: a second import changes nothing. tag_import: ({ state: given }, ctx) => { personalOnly(ctx.state); diff --git a/src/dev/mock/teamRights.ts b/src/dev/mock/teamRights.ts index 1918c93b3..e74d73608 100644 --- a/src/dev/mock/teamRights.ts +++ b/src/dev/mock/teamRights.ts @@ -245,7 +245,7 @@ export function teamDoor(state: MockState, cmd: string, args: Record x.id === id) ? "edit" : "create"); } case "tag_assign": - return Object.keys((args.byProfile ?? {}) as Record).map((id) => onProfile(id, "edit")).find((r) => r) ?? null; + return Object.keys((args.changes ?? args.byProfile ?? {}) as Record).map((id) => onProfile(id, "edit")).find((r) => r) ?? null; case "bookmark_save": { const id = (args.entry as { id?: string } | undefined)?.id; return onTeam(id && state.bookmarks.some((b) => b.id === id) ? "edit" : "create"); diff --git a/src/entities/tag/lib/useTags.ts b/src/entities/tag/lib/useTags.ts index 64a2e801b..ee48465ee 100644 --- a/src/entities/tag/lib/useTags.ts +++ b/src/entities/tag/lib/useTags.ts @@ -6,9 +6,9 @@ import { onSpaceMoved } from "../../../shared/api/invoke"; import { toast } from "../../../shared/model/toast"; import { t } from "../../../shared/i18n"; import type { Tag } from "../model/types"; -import { tagAssign, tagDelete, tagImport, tagList, tagSave } from "../model/api"; +import { tagAssign, tagChange, tagDelete, tagImport, tagList, tagSave, type TagChange } from "../model/api"; import { fromLegacy, whole } from "./stored"; -import { teamRefusal } from "../../space"; +import { inTeam, teamRefusal } from "../../space"; /** Which of these profiles a team lets this person tag (Edit on each), and why not the rest. * The profile store says (it holds the rows); everyone may, until it does. */ @@ -80,8 +80,8 @@ export type TagStore = { toggle: (profileIds: string[], tagId: string) => void; /** Takes one tag off one profile. */ untag: (profileId: string, tagId: string) => void; - /** Gives one profile exactly these tags (the profile form's Save). */ - setTags: (profileId: string, tagIds: string[]) => void; + /** Gives a profile the chosen tags. An open team form passes the tags it started with. */ + setTags: (profileId: string, tagIds: string[], openedTagIds?: readonly string[]) => void; /** Drops the tags of profiles deleted for good. */ forgetProfiles: (profileIds: string[]) => void; /** A profile got another id (one being created got its real one): its tags follow. */ @@ -113,18 +113,42 @@ export const useTags = create((set, get) => { }; /** Shows the new lists and sends the profiles whose list changed. A profile a * team does not let this person tag keeps its list, and the toast says why. */ - const assign = (wanted: Record, touched: Iterable) => { + const assign = (wanted: Record, touched: Iterable, opened?: Record) => { const asked = [...touched]; const { refused, reason } = assignGuard(asked); + if (refused.length > 0) toast.fail({ title: t("useTags.saveFailed"), detail: reason }); + const allowed = asked.filter((pid) => !refused.includes(pid)); + const before = get().byProfile; + if (inTeam()) { + const byProfile = { ...before }; + const changes: Record = {}; + for (const pid of allowed) { + const current = before[pid] ?? []; + const base = opened?.[pid] ?? current; + const next = wanted[pid] ?? []; + const add = next.filter((id) => !base.includes(id)); + const remove = base.filter((id) => !next.includes(id)); + if (add.length === 0 && remove.length === 0) continue; + changes[pid] = { add, remove }; + const kept = current.filter((id) => !remove.includes(id)); + const visible = [...new Set([...kept, ...add])]; + if (visible.length) byProfile[pid] = visible; else delete byProfile[pid]; + } + if (Object.keys(changes).length === 0) return; + set({ byProfile }); + // Resolve tag ids at send time, after any queued tag creation. + send(() => tagChange(Object.fromEntries(Object.entries(changes).map(([pid, { add, remove }]) => [ + pid, { add: add.map(finalId), remove: remove.map(finalId) }, + ])))); + return; + } const byProfile = { ...wanted }; for (const pid of refused) { - const had = get().byProfile[pid]; + const had = before[pid]; if (had) byProfile[pid] = had; else delete byProfile[pid]; } - if (refused.length > 0) toast.fail({ title: t("useTags.saveFailed"), detail: reason }); - const changes = changedLists(get().byProfile, byProfile, asked.filter((pid) => !refused.includes(pid))); + const changes = changedLists(before, byProfile, allowed); set({ byProfile }); - // Ids read as it goes: a tag the team saved under another id is sent by that one. if (Object.keys(changes).length) send(() => tagAssign(remapped(changes))); }; /** A team's server answered a new tag with its own id: everything that names it follows. */ @@ -228,12 +252,13 @@ export const useTags = create((set, get) => { if (ids.length) byProfile[profileId] = ids; else delete byProfile[profileId]; assign(byProfile, [profileId]); }, - setTags: (profileId, tagIds) => { + setTags: (profileId, tagIds, openedTagIds) => { const known = new Set(get().tags.map((t) => t.id)); - const ids = [...new Set(tagIds)].filter((id) => known.has(id)); + const ids = [...new Set(tagIds.map(finalId))].filter((id) => known.has(id)); const byProfile = { ...get().byProfile }; if (ids.length) byProfile[profileId] = ids; else delete byProfile[profileId]; - assign(byProfile, [profileId]); + const opened = openedTagIds ? { [profileId]: openedTagIds.map(finalId) } : undefined; + assign(byProfile, [profileId], opened); }, forgetProfiles: (profileIds) => { const byProfile = { ...get().byProfile }; diff --git a/src/entities/tag/model/api.ts b/src/entities/tag/model/api.ts index f8cb63adb..ab56ff5a2 100644 --- a/src/entities/tag/model/api.ts +++ b/src/entities/tag/model/api.ts @@ -11,5 +11,8 @@ export const tagSave = (tag: Tag, at?: number) => invoke("tag_save", { tag, export const tagDelete = (id: string) => invoke("tag_delete", { id }); /** Gives each listed profile exactly these tags; an empty list clears it. */ export const tagAssign = (byProfile: Record) => invoke("tag_assign", { byProfile }); +/** Applies only the additions and removals a team member made. */ +export type TagChange = { add: string[]; remove: string[] }; +export const tagChange = (changes: Record) => invoke("tag_assign", { byProfile: {}, changes }); /** Hands over the copy an older build kept in this window; false when the backend had tags already. */ export const tagImport = (state: TagState) => invoke("tag_import", { state }); diff --git a/src/features/profile-form/model/useProfileForm.ts b/src/features/profile-form/model/useProfileForm.ts index b3d05325b..fe44f3bd7 100644 --- a/src/features/profile-form/model/useProfileForm.ts +++ b/src/features/profile-form/model/useProfileForm.ts @@ -604,7 +604,7 @@ export async function saveProfileForm(): Promise { // A name typed in becomes a tag only now. const tags = useTags.getState(); const made = draft.newTags.map((n) => tags.create(n)?.id).filter((x): x is string => !!x); - tags.setTags(id, [...draft.tagIds, ...made]); + tags.setTags(id, [...draft.tagIds, ...made], opened.tagIds); } if (draft.folder !== opened.folder) { const store = useProfile.getState();