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
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
54 changes: 54 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
17 changes: 15 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1164,9 +1164,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
2 changes: 1 addition & 1 deletion src-tauri/src/live_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
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
7 changes: 7 additions & 0 deletions src-tauri/src/space/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,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 +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<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
60 changes: 56 additions & 4 deletions src-tauri/src/space/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,18 +246,30 @@ async fn rewrite(
) -> Result<(), CmdError> {
let c = client(team)?;
let now = fresh(&c, id).await?;
let edit = perm::team_write::<Edit>(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::<Edit>(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::<Create>(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));
Expand Down Expand Up @@ -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<String>,
remove: Vec<String>,
}

/// Adds or removes only the requested tags, preserving changes made elsewhere.
pub async fn change_tags(door: Door, t: &Ticket, team: &str, changes: BTreeMap<String, TagChange>) -> 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<String, CmdError> {
Expand Down
24 changes: 23 additions & 1 deletion src/dev/mock/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -87,6 +88,15 @@ function assignTags(s: MockTags, byProfile: Record<string, string[]>) {
}
}

/** Apply explicit edits to the team's current assignments. */
function changeTags(s: MockTags, changes: Record<string, TagChange>) {
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();
Expand Down Expand Up @@ -860,7 +870,19 @@ export const handlers: Record<string, Handler> = {
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);
Expand Down
2 changes: 1 addition & 1 deletion src/dev/mock/teamRights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ export function teamDoor(state: MockState, cmd: string, args: Record<string, unk
return onTeam(id && (state.templates ?? []).some((x) => x.id === id) ? "edit" : "create");
}
case "tag_assign":
return Object.keys((args.byProfile ?? {}) as Record<string, unknown>).map((id) => onProfile(id, "edit")).find((r) => r) ?? null;
return Object.keys((args.changes ?? args.byProfile ?? {}) as Record<string, unknown>).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");
Expand Down
Loading