diff --git a/e2e/team-space.spec.ts b/e2e/team-space.spec.ts index 216585658..8928e8587 100644 --- a/e2e/team-space.spec.ts +++ b/e2e/team-space.spec.ts @@ -182,6 +182,46 @@ test("tags and folders changed elsewhere are read again", async ({ page }) => { await expect(kept).toBeVisible(); }); +test("a deleted team tag stays removable from an open profile draft", async ({ page }) => { + await inTeam(page); + await page.evaluate(() => { + const mock = (window as unknown as M).__shardxMock; + mock.state.tags = { + tags: [ + { id: "t-review", name: "Review", color: "orange" }, + { id: "t-handoff", name: "Handoff", color: "violet" }, + ], + by_profile: {}, + }; + mock.emit("store-changed", "tags"); + }); + await row(page, ETSY_MAIN).click({ button: "right" }); + await page.getByRole("menuitem", { name: "Edit", exact: true }).click(); + const form = page.getByRole("dialog", { name: "Edit Etsy main", exact: true }); + const field = form.locator("[data-property='tags']"); + await field.getByRole("button").click(); + const picker = page.getByRole("dialog", { name: "Tags", exact: true }); + await picker.getByRole("option", { name: "Review", exact: true }).click(); + await picker.getByRole("option", { name: "Handoff", exact: true }).click(); + + await page.evaluate(() => { + const mock = (window as unknown as M).__shardxMock; + mock.state.tags!.tags = mock.state.tags!.tags.filter((tag) => tag.id !== "t-review"); + mock.emit("store-changed", "tags"); + }); + const unavailable = picker.getByRole("option", { name: "Unavailable tag", exact: true, selected: true }); + await expect(unavailable).toBeVisible(); + await expect(field).toContainText("Unavailable tag"); + await unavailable.click(); + await expect(field).not.toContainText("Unavailable tag"); + await expect(picker.getByRole("option", { name: "Handoff", exact: true, selected: true })).toBeVisible(); + await form.getByRole("textbox", { name: "Name" }).click(); + await form.getByRole("button", { name: "Save", exact: true }).click(); + await expect(form).toHaveCount(0); + await expect.poll(() => page.evaluate((id) => + (window as unknown as M).__shardxMock.state.tags?.by_profile[id], ETSY_MAIN)).toEqual(["t-handoff"]); +}); + test("a switch shows nothing of the space left, not even for a moment, on any page", async ({ page }) => { // A read of the old space is held 4 s on purpose, past the switch. test.slow(); diff --git a/src-tauri/src/space/client.rs b/src-tauri/src/space/client.rs index d2fc9e085..17709a0b8 100644 --- a/src-tauri/src/space/client.rs +++ b/src-tauri/src/space/client.rs @@ -859,6 +859,7 @@ pub enum Code { NoLease, Conflict, BadProxy, + BadTag, InTrash, TooLarge, /// The server never issued the token, or the member is gone; said before the server is trusted. @@ -880,6 +881,7 @@ impl Code { "no_lease" => Code::NoLease, "conflict" => Code::Conflict, "bad_proxy" => Code::BadProxy, + "bad_tag" => Code::BadTag, "in_trash" => Code::InTrash, "too_large" => Code::TooLarge, team_wire::UNKNOWN_TOKEN => Code::UnknownToken, @@ -901,6 +903,7 @@ impl Code { Code::NoLease => "no_lease", Code::Conflict => "conflict", Code::BadProxy => "bad_proxy", + Code::BadTag => "bad_tag", Code::InTrash => "in_trash", Code::TooLarge => "too_large", Code::UnknownToken => team_wire::UNKNOWN_TOKEN, diff --git a/src-tauri/src/space/remote.rs b/src-tauri/src/space/remote.rs index d525e342e..aae7ad457 100644 --- a/src-tauri/src/space/remote.rs +++ b/src-tauri/src/space/remote.rs @@ -9,7 +9,7 @@ use team_model::Card; use super::automation::Project; use super::bookmarks::Bookmark; -use super::client::{Method, TeamClient, TeamError}; +use super::client::{Code, Method, TeamClient, TeamError}; use super::extensions::ExtensionEntry; use super::folders::{FolderMeta, FolderState}; use super::perm::{self, Create, Delete, Edit, Granted, On}; @@ -487,7 +487,13 @@ pub async fn edit_profile( Some(_) => return Err(wrong("a folder")), None => folder, }; - put_profile(c, id, folder, f, base).await + let result = put_profile(c, id, folder, f, base).await; + if result.as_ref().is_err_and(|e| e.code() == Some(&Code::BadTag)) { + if let Some(team) = c.team() { + super::cache::heard(team, "tag", &super::live::default_tell()); + } + } + result } /// To the team's trash; refused once the profile moved past `base`. diff --git a/src/features/profile-form/ui/TagsField.tsx b/src/features/profile-form/ui/TagsField.tsx index d1b67bbbb..8a4268450 100644 --- a/src/features/profile-form/ui/TagsField.tsx +++ b/src/features/profile-form/ui/TagsField.tsx @@ -32,9 +32,17 @@ export function TagsField({ value, newNames, onChange, onNewNamesChange, onCreat return out; }, [newNames, tags]); const shown = [...tags.filter((tag) => value.includes(tag.id)), ...pending]; + // A tag deleted elsewhere can still be in this draft. Keep a checked option + // for it so the user can remove it from the form. + const unavailable = useMemo(() => value.filter((id) => !tags.some((tag) => tag.id === id)), [value, tags]); + const unavailableLabel = t("tagPicker.unavailable"); + const empty = shown.length === 0 && unavailable.length === 0; const options = useMemo( - () => [...tags, ...pending].map((tag) => ({ value: tag.id, label: tag.name, content: })), - [tags, pending], + () => [ + ...[...tags, ...pending].map((tag) => ({ value: tag.id, label: tag.name, content: })), + ...unavailable.map((id) => ({ value: id, label: unavailableLabel })), + ], + [tags, pending, unavailable, unavailableLabel], ); const toggle = (id: string) => { if (id.startsWith(NEW)) onNewNamesChange(newNames.filter((n) => `${NEW}${n}` !== id)); @@ -44,8 +52,10 @@ export function TagsField({ value, newNames, onChange, onNewNamesChange, onCreat {(labelId) => ( <> - setOpen((v) => !v)}> - {shown.length === 0 ? {t("peek.noTags")} : shown.map((tag) => )} + setOpen((v) => !v)}> + {empty && {t("peek.noTags")}} + {shown.map((tag) => )} + {unavailable.map((id) => {unavailableLabel})} { onCreate(name); setQuery(""); })} createLabel={(name) => t("tagPicker.create", { name })} - emptyText={tags.length === 0 && pending.length === 0 ? (onCreate ? t("tagPicker.empty") : t("tagPicker.emptyNoCreate")) : undefined} + emptyText={options.length === 0 ? (onCreate ? t("tagPicker.empty") : t("tagPicker.emptyNoCreate")) : undefined} /> diff --git a/src/shared/api/teamRefusals.test.ts b/src/shared/api/teamRefusals.test.ts index a462841a0..4f43b0372 100644 --- a/src/shared/api/teamRefusals.test.ts +++ b/src/shared/api/teamRefusals.test.ts @@ -95,7 +95,8 @@ test("the team server's own refusals the app reads are its words", () => { const api = read("team-server/src/api.rs"); assert.ok(api.includes(`"${TEAM_REFUSALS.folderInTrash}"`), "the folder-in-trash refusal moved"); assert.ok(api.includes(`"${TEAM_REFUSALS.badProxy}"`), "the bad-proxy refusal moved"); + assert.ok(api.includes(`"${TEAM_REFUSALS.badTag}"`), "the unavailable-tag refusal moved"); assert.ok(rust("space/mod.rs").includes(`"${TEAM_REFUSALS.teamExtensionsNotYet}"`), "the extension updates refusal moved"); const app = read("src/shared/lib/errors.ts"); - for (const key of ["folderInTrash", "badProxy", "teamExtensionsNotYet"]) assert.ok(app.includes(`phrase(TEAM_REFUSALS.${key})`), `${key} is shown raw`); + for (const key of ["folderInTrash", "badProxy", "badTag", "teamExtensionsNotYet"]) assert.ok(app.includes(`phrase(TEAM_REFUSALS.${key})`), `${key} is shown raw`); }); diff --git a/src/shared/api/teamRefusals.ts b/src/shared/api/teamRefusals.ts index 4be7845cc..aa5470c98 100644 --- a/src/shared/api/teamRefusals.ts +++ b/src/shared/api/teamRefusals.ts @@ -38,6 +38,8 @@ export const TEAM_REFUSALS = { trashTagTaken: (name: string) => `a tag named ${name} already exists`, /** A proxy the writer may not use, bound to a team profile (team-server api.rs `bad_proxy`). */ badProxy: "no such proxy to bind", + /** A tag the writer tried to attach is no longer in the team's live tag registry. */ + badTag: "one or more tags are no longer available", /** Saved by someone else since it was read (CmdError::Stale). */ stale: (what: string, now: number, had: number) => `This ${what} changed after you opened it (rev ${now}, you have ${had}) — someone else saved it. Reopen it and apply your changes to the current version.`, diff --git a/src/shared/i18n/locales/en.json b/src/shared/i18n/locales/en.json index d0db012d2..51960364b 100644 --- a/src/shared/i18n/locales/en.json +++ b/src/shared/i18n/locales/en.json @@ -501,6 +501,7 @@ "errors.switchWhileStarting": "A profile is starting. Switch spaces once it has started.", "errors.teamAdminOnly": "Only the team’s admin can do this.", "errors.teamBadProxy": "You can’t assign that proxy: it needs “Start”, “Edit” or “Take out” on it. Ask the team’s admin.", + "errors.teamBadTag": "One or more tags are no longer available.", "errors.teamBusy": "It’s still opening or being saved here. Start it again in a moment.", "errors.teamExtensionsNotYet": "A team’s extensions don’t get updates here yet.", "errors.teamFolderInTrash": "Profiles deleted from it are kept in the team’s trash, so the team server keeps the folder too.", @@ -2864,6 +2865,7 @@ "tagPicker.findOnly": "Find a tag…", "tagPicker.label": "Tags", "tagPicker.saved": "Tags saved", + "tagPicker.unavailable": "Unavailable tag", "teamSession.discardedDetail": "What was done in it this time wasn’t kept.", "teamSession.discardedTitle": "“{name}” closed without saving to the team", "teamSession.keptDetail": "It goes to the team once you paste the new invite.", diff --git a/src/shared/i18n/locales/ru.json b/src/shared/i18n/locales/ru.json index 3cef0ac13..3948fa992 100644 --- a/src/shared/i18n/locales/ru.json +++ b/src/shared/i18n/locales/ru.json @@ -501,6 +501,7 @@ "errors.switchWhileStarting": "Профиль запускается. Переключите пространство, когда он запустится.", "errors.teamAdminOnly": "Это может только администратор команды.", "errors.teamBadProxy": "Этот прокси нельзя назначить: на него нужно право «Запуск», «Правка» или «Экспорт». Попросите администратора команды.", + "errors.teamBadTag": "Один или несколько тегов больше недоступны.", "errors.teamBusy": "Он ещё открывается или сохраняется здесь. Запустите его снова чуть позже.", "errors.teamExtensionsNotYet": "Обновления расширений команды здесь пока недоступны.", "errors.teamFolderInTrash": "Удалённые из неё профили хранятся в корзине команды, поэтому сервер команды оставляет и папку.", @@ -2864,6 +2865,7 @@ "tagPicker.findOnly": "Найти тег…", "tagPicker.label": "Теги", "tagPicker.saved": "Теги сохранены", + "tagPicker.unavailable": "Недоступный тег", "teamSession.discardedDetail": "То, что в нём сделано в этот раз, не сохранено.", "teamSession.discardedTitle": "«{name}» закрыт без сохранения в команду", "teamSession.keptDetail": "Он уйдёт в команду, когда вы вставите новое приглашение.", diff --git a/src/shared/i18n/locales/zh.json b/src/shared/i18n/locales/zh.json index ffce13d68..80eb521f6 100644 --- a/src/shared/i18n/locales/zh.json +++ b/src/shared/i18n/locales/zh.json @@ -501,6 +501,7 @@ "errors.switchWhileStarting": "有配置正在启动。请等它启动后再切换空间。", "errors.teamAdminOnly": "只有团队管理员可以这样做。", "errors.teamBadProxy": "不能绑定这个代理:需要它的“启动”“编辑”或“导出”权限。请联系团队管理员。", + "errors.teamBadTag": "一个或多个标签已不可用。", "errors.teamBusy": "它仍在这里打开或保存中。请稍后再启动。", "errors.teamExtensionsNotYet": "团队的扩展暂时不能在这里更新。", "errors.teamFolderInTrash": "从中删除的配置保存在团队回收站里,所以团队服务器也保留这个文件夹。", @@ -2864,6 +2865,7 @@ "tagPicker.findOnly": "查找标签…", "tagPicker.label": "标签", "tagPicker.saved": "标签已保存", + "tagPicker.unavailable": "已不可用的标签", "teamSession.discardedDetail": "这次在其中所做的更改未保留。", "teamSession.discardedTitle": "“{name}”已关闭,未保存到团队", "teamSession.keptDetail": "粘贴新邀请后,它会发送到团队。", diff --git a/src/shared/lib/errors.ts b/src/shared/lib/errors.ts index 2a5295ad9..6ee34bea9 100644 --- a/src/shared/lib/errors.ts +++ b/src/shared/lib/errors.ts @@ -106,6 +106,7 @@ const KNOWN: ReadonlyArray = [ [/\balready_in_library \{/, "errors.alreadyInLibrary"], [/\bAn extension of this profile is being updated\b/i, "errors.extensionUpdating"], [phrase(TEAM_REFUSALS.badProxy), "errors.teamBadProxy"], + [phrase(TEAM_REFUSALS.badTag), "errors.teamBadTag"], [phrase(TEAM_REFUSALS.stillOpen), "errors.teamStillOpen"], [phrase(TEAM_REFUSALS.switchWhileStarting), "errors.switchWhileStarting"], [phrase(TEAM_REFUSALS.switchWhileMoving), "errors.switchWhileMoving"], diff --git a/team-server/src/api.rs b/team-server/src/api.rs index aa7669401..9a137e1d8 100644 --- a/team-server/src/api.rs +++ b/team-server/src/api.rs @@ -319,6 +319,7 @@ pub mod code { pub const CONFLICT: &str = "conflict"; /// A card binds a proxy that is not there for this profile, or not the writer's to use. pub const BAD_PROXY: &str = "bad_proxy"; + pub const BAD_TAG: &str = "bad_tag"; /// The id waits in the team's trash: restore or purge it, or pick another. pub const IN_TRASH: &str = "in_trash"; pub const TOO_LARGE: &str = "too_large"; @@ -483,6 +484,9 @@ impl From for ApiError { Refusal::BadProxy => { ApiError::new(StatusCode::BAD_REQUEST, code::BAD_PROXY, "no such proxy to bind") } + Refusal::BadTag => { + ApiError::new(StatusCode::BAD_REQUEST, code::BAD_TAG, "one or more tags are no longer available") + } Refusal::Forbidden => ApiError::forbidden(), Refusal::SwitchedOff => ApiError::switched_off(), Refusal::Removed => ApiError::unauthorized(), @@ -3176,6 +3180,10 @@ mod tests { } } + mod tag_attachment_tests { + include!("api/tag_attachment_tests.rs"); + } + /// `GET /profiles` with no `?ids=`. fn whole_list() -> Query { Query(ListQuery::default()) @@ -5967,7 +5975,13 @@ mod tests { let (code, got) = answer(&st, mac(ask("PUT", "/profiles/p1", &vera)), Some(with_card(c.clone(), Some(3)))).await; assert_eq!((code, got["code"].as_str()), (StatusCode::BAD_REQUEST, Some("bad_request")), "{c}"); } - let full = json!({ "proxy_id": "x1", "notes": "н".repeat(2000), "color": "c".repeat(32), "tags": vec!["т".repeat(64); 50] }); + let tag_id = "т".repeat(64); + let setup = Writer { member_id: "setup", device_id: None }; + st.store + .put_item_checked(TEAM, "tag", &tag_id, "Long tag", b"{}", setup, None, |_, _| Ok(())) + .unwrap() + .unwrap(); + let full = json!({ "proxy_id": "x1", "notes": "н".repeat(2000), "color": "c".repeat(32), "tags": vec![tag_id; 50] }); let (code, _) = answer(&st, mac(ask("PUT", "/profiles/p1", &vera)), Some(with_card(full, Some(3)))).await; assert_eq!(code, StatusCode::OK, "right at the limits"); // A blank binding is none. diff --git a/team-server/src/api/tag_attachment_tests.rs b/team-server/src/api/tag_attachment_tests.rs new file mode 100644 index 000000000..0fc9587ab --- /dev/null +++ b/team-server/src/api/tag_attachment_tests.rs @@ -0,0 +1,108 @@ +use super::*; + +fn profile_with_tags(name: &str, data: &[u8], tags: &[&str]) -> Value { + let mut body = profile_json(name, "Ads", data); + body["card"] = json!({ "notes": name, "tags": tags }); + body +} + +#[tokio::test] +async fn a_tag_deleted_after_reading_a_team_profile_cannot_be_newly_attached() { + let st = state(); + let admin = admin(&st); + let (_, editor) = member(&st, "Editor", everything()).await; + let (_, teammate) = member(&st, "Teammate", everything()).await; + let profile = "/profiles/p-tag-attachment"; + + for id in ["retired", "candidate", "kept"] { + let body = json!({ "name": id, "data": STANDARD.encode(b"{}") }); + let (status, _) = answer(&st, ask("PUT", &format!("/items/tag/{id}"), &admin), Some(body)).await; + assert_eq!(status, StatusCode::CREATED); + } + let initial = profile_with_tags("Before", b"earlier settings", &["retired", "kept"]); + assert_eq!( + answer(&st, ask("PUT", profile, &admin), Some(initial)).await.0, + StatusCode::CREATED + ); + let get = || ask("GET", profile, &editor); + let (status, before) = answer(&st, get(), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(before["card"]["tags"], json!(["retired", "kept"])); + let revision = before["revision"].as_u64().unwrap(); + + // The teammate's deletion has committed, but a tag deletion does not move the profile revision. + for id in ["retired", "candidate"] { + let (status, _) = answer(&st, ask("DELETE", &format!("/items/tag/{id}"), &teammate), None).await; + assert_eq!(status, StatusCode::NO_CONTENT); + } + assert_eq!(answer(&st, get(), None).await, (StatusCode::OK, before.clone())); + + let put = || ask("PUT", profile, &editor); + let bad_tag = json!({ "code": "bad_tag", "error": "one or more tags are no longer available" }); + let attempted = profile_with_tags( + "Rejected edit", + b"uncommitted settings", + &["retired", "kept", "candidate"], + ); + assert_eq!( + answer(&st, put(), Some(based_on(attempted, revision))).await, + (StatusCode::BAD_REQUEST, bad_tag.clone()), + ); + assert_eq!(answer(&st, get(), None).await, (StatusCode::OK, before)); + + let retained = profile_with_tags("Renamed", b"updated settings", &["retired", "kept"]); + assert_eq!( + answer(&st, put(), Some(based_on(retained, revision))).await.0, + StatusCode::OK + ); + let (status, retained) = answer(&st, get(), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(retained["revision"], revision + 1); + assert_eq!(retained["name"], "Renamed"); + assert_eq!(retained["card"]["tags"], json!(["retired", "kept"])); + assert_eq!(retained["data"], STANDARD.encode(b"updated settings")); + + let trimmed = profile_with_tags("Renamed", b"updated settings", &["kept"]); + assert_eq!( + answer(&st, put(), Some(based_on(trimmed, revision + 1))).await.0, + StatusCode::OK + ); + let readded = profile_with_tags("Renamed", b"updated settings", &["kept", "retired"]); + assert_eq!( + answer(&st, put(), Some(based_on(readded, revision + 2))).await, + (StatusCode::BAD_REQUEST, bad_tag) + ); + let (status, trimmed) = answer(&st, get(), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(trimmed["card"]["tags"], json!(["kept"])); + assert_eq!(trimmed["revision"], revision + 2); + + let restore = ask("POST", "/trash/candidate/restore?kind=tag", &admin); + assert_eq!(answer(&st, restore, None).await.0, StatusCode::OK); + let attached = profile_with_tags("Renamed", b"updated settings", &["kept", "candidate"]); + assert_eq!( + answer(&st, put(), Some(based_on(attached, revision + 2))).await.0, + StatusCode::OK + ); + let (status, attached) = answer(&st, get(), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(attached["card"]["tags"], json!(["kept", "candidate"])); + assert_eq!(attached["revision"], revision + 3); +} + +#[tokio::test] +async fn a_personal_profile_may_still_name_a_tag_before_it_syncs() { + let st = state(); + let (_, owner) = member(&st, "Owner", vec![]).await; + let profile = "/me/profiles/p-own-tag-attachment"; + let put = || ask("PUT", profile, &owner); + let initial = profile_with_tags("Before", b"earlier settings", &[]); + assert_eq!(answer(&st, put(), Some(initial)).await.0, StatusCode::CREATED); + + let updated = profile_with_tags("After", b"new settings", &["not-synced-yet"]); + assert_eq!(answer(&st, put(), Some(based_on(updated, 1))).await.0, StatusCode::OK); + let (status, detail) = answer(&st, ask("GET", profile, &owner), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(detail["card"]["tags"], json!(["not-synced-yet"])); + assert_eq!(detail["revision"], 2); +} diff --git a/team-server/src/store.rs b/team-server/src/store.rs index 7cea4b2b9..3b32e89c0 100644 --- a/team-server/src/store.rs +++ b/team-server/src/store.rs @@ -207,6 +207,8 @@ pub enum Refusal { PackageStale { current: u64 }, /// The card binds a proxy that is not in the profile's space, or not the writer's to use. BadProxy, + /// The edit attaches a tag that is not active in the team. + BadTag, /// The id waits in the team's trash: restore or purge it first. InTrash(Box), } @@ -2190,11 +2192,14 @@ impl Store { return Ok(Err(Refusal::InTrash(Box::new(t)))); } } - // A binding the row already has is not asked about again. - let bound = match card.and_then(Card::bound_proxy) { - Some(x) if existing.is_some() && self.card_in(&tx, id)?.bound_proxy() == Some(x) => None, - other => other, + let current_card = match card { + Some(c) if existing.is_some() && (c.bound_proxy().is_some() || (space == TEAM && !c.tags.is_empty())) => { + Some(self.card_in(&tx, id)?) + } + _ => None, }; + // A binding the row already has is not asked about again. + let bound = card.and_then(Card::bound_proxy).filter(|x| current_card.as_ref().and_then(Card::bound_proxy) != Some(*x)); let named = existing.is_none() && space == TEAM && named_by_grant(&tx, id)?; // Rights first: the lease and the revision are only for someone who may write it. let found = Found { bound, named }; @@ -2214,6 +2219,15 @@ impl Store { return Ok(Err(Refusal::Leased(held))); } } + // A deleted tag keeps its existing associations so restoring it brings + // them back. An edit cannot attach it to another profile in the meantime. + if let (TEAM, Some(before), Some(after)) = (space, current_card.as_ref(), card) { + for tag in after.tags.iter().filter(|tag| !before.tags.contains(tag)) { + if !matches!(item_at(&tx, TEAM, "tag", tag)?, Some((_, false))) { + return Ok(Err(Refusal::BadTag)); + } + } + } // Made in the team, or moved to another folder there: who sees what may move. let scopes = match &existing { _ if space != TEAM => Vec::new(),