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
40 changes: 40 additions & 0 deletions e2e/team-space.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions src-tauri/src/space/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand All @@ -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,
Expand Down
10 changes: 8 additions & 2 deletions src-tauri/src/space/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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`.
Expand Down
20 changes: 15 additions & 5 deletions src/features/profile-form/ui/TagsField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ComboboxOption[]>(
() => [...tags, ...pending].map((tag) => ({ value: tag.id, label: tag.name, content: <TagChip tag={tag} /> })),
[tags, pending],
() => [
...[...tags, ...pending].map((tag) => ({ value: tag.id, label: tag.name, content: <TagChip tag={tag} /> })),
...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));
Expand All @@ -44,8 +52,10 @@ export function TagsField({ value, newNames, onChange, onNewNamesChange, onCreat
<PropertyRow id="tags" label={t("peek.tags")}>
{(labelId) => (
<>
<PropertyButton ref={anchor} labelledBy={labelId} empty={shown.length === 0} wrap expanded={open} onClick={() => setOpen((v) => !v)}>
{shown.length === 0 ? <span className="truncate">{t("peek.noTags")}</span> : shown.map((tag) => <TagChip key={tag.id} tag={tag} />)}
<PropertyButton ref={anchor} labelledBy={labelId} empty={empty} wrap expanded={open} onClick={() => setOpen((v) => !v)}>
{empty && <span className="truncate">{t("peek.noTags")}</span>}
{shown.map((tag) => <TagChip key={tag.id} tag={tag} />)}
{unavailable.map((id) => <span key={id} className="truncate text-secondary text-text-sub-600">{unavailableLabel}</span>)}
</PropertyButton>
<Popover
open={open}
Expand All @@ -67,7 +77,7 @@ export function TagsField({ value, newNames, onChange, onNewNamesChange, onCreat
onChange={toggle}
onCreate={onCreate && ((name) => { 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}
/>
</Popover>
</>
Expand Down
3 changes: 2 additions & 1 deletion src/shared/api/teamRefusals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
});
2 changes: 2 additions & 0 deletions src/shared/api/teamRefusals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.`,
Expand Down
2 changes: 2 additions & 0 deletions src/shared/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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.",
Expand Down
2 changes: 2 additions & 0 deletions src/shared/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,7 @@
"errors.switchWhileStarting": "Профиль запускается. Переключите пространство, когда он запустится.",
"errors.teamAdminOnly": "Это может только администратор команды.",
"errors.teamBadProxy": "Этот прокси нельзя назначить: на него нужно право «Запуск», «Правка» или «Экспорт». Попросите администратора команды.",
"errors.teamBadTag": "Один или несколько тегов больше недоступны.",
"errors.teamBusy": "Он ещё открывается или сохраняется здесь. Запустите его снова чуть позже.",
"errors.teamExtensionsNotYet": "Обновления расширений команды здесь пока недоступны.",
"errors.teamFolderInTrash": "Удалённые из неё профили хранятся в корзине команды, поэтому сервер команды оставляет и папку.",
Expand Down Expand Up @@ -2864,6 +2865,7 @@
"tagPicker.findOnly": "Найти тег…",
"tagPicker.label": "Теги",
"tagPicker.saved": "Теги сохранены",
"tagPicker.unavailable": "Недоступный тег",
"teamSession.discardedDetail": "То, что в нём сделано в этот раз, не сохранено.",
"teamSession.discardedTitle": "«{name}» закрыт без сохранения в команду",
"teamSession.keptDetail": "Он уйдёт в команду, когда вы вставите новое приглашение.",
Expand Down
2 changes: 2 additions & 0 deletions src/shared/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,7 @@
"errors.switchWhileStarting": "有配置正在启动。请等它启动后再切换空间。",
"errors.teamAdminOnly": "只有团队管理员可以这样做。",
"errors.teamBadProxy": "不能绑定这个代理:需要它的“启动”“编辑”或“导出”权限。请联系团队管理员。",
"errors.teamBadTag": "一个或多个标签已不可用。",
"errors.teamBusy": "它仍在这里打开或保存中。请稍后再启动。",
"errors.teamExtensionsNotYet": "团队的扩展暂时不能在这里更新。",
"errors.teamFolderInTrash": "从中删除的配置保存在团队回收站里,所以团队服务器也保留这个文件夹。",
Expand Down Expand Up @@ -2864,6 +2865,7 @@
"tagPicker.findOnly": "查找标签…",
"tagPicker.label": "标签",
"tagPicker.saved": "标签已保存",
"tagPicker.unavailable": "已不可用的标签",
"teamSession.discardedDetail": "这次在其中所做的更改未保留。",
"teamSession.discardedTitle": "“{name}”已关闭,未保存到团队",
"teamSession.keptDetail": "粘贴新邀请后,它会发送到团队。",
Expand Down
1 change: 1 addition & 0 deletions src/shared/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ const KNOWN: ReadonlyArray<readonly [RegExp, string]> = [
[/\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"],
Expand Down
16 changes: 15 additions & 1 deletion team-server/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -483,6 +484,9 @@ impl From<Refusal> 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(),
Expand Down Expand Up @@ -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<ListQuery> {
Query(ListQuery::default())
Expand Down Expand Up @@ -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.
Expand Down
108 changes: 108 additions & 0 deletions team-server/src/api/tag_attachment_tests.rs
Original file line number Diff line number Diff line change
@@ -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);
}
Loading