From 61113c4fbb337fd4d6093b32a0faa29497815954 Mon Sep 17 00:00:00 2001 From: glwhappen <1597721684@qq.com> Date: Mon, 30 Nov 2026 14:32:32 +0800 Subject: [PATCH] Confirm quick tag writes before reporting success --- e2e/team-review-fixes.spec.ts | 143 ++++++++++++++++++++-- src/entities/tag/lib/useTags.ts | 104 ++++++++++++---- src/features/manage-tags/ui/TagPicker.tsx | 44 ++++--- 3 files changed, 241 insertions(+), 50 deletions(-) diff --git a/e2e/team-review-fixes.spec.ts b/e2e/team-review-fixes.spec.ts index 7e2b4e2dc..08086759c 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 @@ -18,7 +18,7 @@ type M = { teamStatus: (s: Record) => void; teamWithdraw: (kind: "revoked" | "replaced") => void; }; - __TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record) => Promise }; + __TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record, options?: unknown) => Promise }; }; const TEAM: Scope = { kind: "team" }; @@ -291,23 +291,26 @@ test("leaving a team closes its profiles open here, saved to it; a withdrawal cl 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. - await page.evaluate(() => { (window as unknown as { __shardxMockSlow: Record }).__shardxMockSlow = { tag_save: 800 }; }); + await holdQuickTagWrite(page, "tag_save"); const etsy = row(page, "tp-shop-1"); await etsy.click({ button: "right" }); await item(page, /^Edit tags/).click(); - await page.getByPlaceholder("Find or create a tag…").fill("Team only"); - await page.keyboard.press("Enter"); + const picker = page.getByRole("dialog", { name: "Tags", exact: true }); + await pickNewQuickTag(picker, "Team only"); + await waitForQuickTagWrite(page); await page.keyboard.press("Escape"); + await expect(picker).toHaveCount(0); const asked = await page.evaluate(() => (window as unknown as M).__shardxMock.epoch); await page.evaluate(() => (window as unknown as { __shardxMock: { moveSpace: (s: unknown) => void } }).__shardxMock.moveSpace({ kind: "personal" })); await expect(space(page)).toHaveText("Personal"); - // The assign queued behind the save still names the team's edition, so it is refused there. - await expect.poll(async () => (await callsOf(page, "tag_assign")).length).toBeGreaterThan(0); - for (const w of [...await callsOf(page, "tag_save"), ...await callsOf(page, "tag_assign")]) expect(w.epoch).toBe(asked); + // The create carries the team's edition when it reaches the backend. + await releaseQuickTagWrite(page); await expect(toast(page, "switched to another space before this was saved").first()).toBeVisible(); - const personal = await page.evaluate(() => (window as unknown as M).__shardxMock.state.tags?.tags ?? []); - expect(personal.map((x: { name: string }) => x.name)).not.toContain("Team only"); + await waitForIdle(page); + expect((await callsOf(page, "tag_save")).map((write) => write.epoch)).toEqual([asked]); + expect(await callsOf(page, "tag_assign")).toEqual([]); + await expect(toast(page, "Tags saved")).toHaveCount(0); + expect((await storedTags(page)).tags.map((tag) => tag.name)).not.toContain("Team only"); }); test("in Russian at 1280 px with Peek open, the row's Start and Peek's name are whole", async ({ page }) => { @@ -346,3 +349,121 @@ test("the Team page in the personal space leads back to the team this launcher i await page.locator("main").getByRole("button", { name: "Switch to “Shops team”" }).click(); await expect(space(page)).toHaveText("Shops team"); }); + +const QUICK_TAG_PROFILE = "tp-shop-1"; +const QUICK_TAG = { id: "t-quick-review", name: "Needs review", color: "orange" }; + +async function openQuickTeamTagPicker(page: Page) { + await asMember(page, allow(TEAM, "see", "edit", "create")); + await page.evaluate((tag) => { + const mock = (window as unknown as M).__shardxMock; + mock.state.tags = { tags: [tag], by_profile: {} }; + mock.emit("store-changed", "tags"); + }, QUICK_TAG); + await row(page, QUICK_TAG_PROFILE).click({ button: "right" }); + await item(page, /^Edit tags/).click(); + return page.getByRole("dialog", { name: "Tags", exact: true }); +} + +type HeldQuickTagWrite = M & { + quickTagWriteStarted?: boolean; + releaseQuickTagWrite: () => void; + __shardxMockFailWith?: Record; +}; + +async function holdQuickTagWrite(page: Page, command: "tag_assign" | "tag_save", failure?: string) { + await page.evaluate(({ command, failure }) => { + const w = window as unknown as HeldQuickTagWrite; + const ipc = w.__TAURI_INTERNALS__; + const invoke = ipc.invoke; + w.quickTagWriteStarted = false; + const held = new Promise((resolve) => { w.releaseQuickTagWrite = resolve; }); + ipc.invoke = async (cmd, args, options) => { + if (cmd !== command) return invoke(cmd, args, options); + ipc.invoke = invoke; + w.quickTagWriteStarted = true; + await held; + if (failure) w.__shardxMockFailWith = { ...w.__shardxMockFailWith, [command]: failure }; + return invoke(cmd, args, options); + }; + }, { command, failure }); +} + +const waitForQuickTagWrite = (page: Page) => + page.waitForFunction(() => (window as unknown as HeldQuickTagWrite).quickTagWriteStarted); +const releaseQuickTagWrite = (page: Page) => + page.evaluate(() => (window as unknown as HeldQuickTagWrite).releaseQuickTagWrite()); + +async function pickNewQuickTag(picker: ReturnType, name: string) { + await picker.getByRole("combobox", { name: "Find or create a tag" }).fill(name); + await picker.getByRole("option", { name: `Create “${name}”`, exact: true }).click(); +} + +for (const outcome of ["accepted", "rejected"] as const) { + test(`quick team tag save waits for the server when the assignment is ${outcome}`, async ({ page }) => { + const picker = await openQuickTeamTagPicker(page); + const option = picker.getByRole("option", { name: QUICK_TAG.name, exact: true }); + await expect(option).toHaveAttribute("aria-selected", "false"); + await holdQuickTagWrite(page, "tag_assign", outcome === "rejected" ? "the team server did not answer" : undefined); + + await option.click(); + await expect(option).toHaveAttribute("aria-selected", "true"); + await waitForQuickTagWrite(page); + const saved = toast(page, "Tags saved"); + await expect(saved).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect(picker).toHaveCount(0); + await expect(saved).toHaveCount(0); + expect((await storedTags(page)).by_profile[QUICK_TAG_PROFILE] ?? []).toEqual([]); + + await releaseQuickTagWrite(page); + if (outcome === "accepted") { + await expect(saved).toHaveCount(1); + expect((await storedTags(page)).by_profile[QUICK_TAG_PROFILE]).toEqual([QUICK_TAG.id]); + } else { + await expect(toast(page, "Couldn’t save tags")).toContainText("The team server isn’t answering. Try again once it’s back."); + await row(page, QUICK_TAG_PROFILE).click({ button: "right" }); + await item(page, /^Edit tags/).click(); + await expect(option).toHaveAttribute("aria-selected", "false"); + await expect(saved).toHaveCount(0); + expect((await storedTags(page)).by_profile[QUICK_TAG_PROFILE] ?? []).toEqual([]); + } + }); +} + +test("a rejected quick team tag creation does not try to assign the tag", async ({ page }) => { + const picker = await openQuickTeamTagPicker(page); + const name = "New team tag"; + await holdQuickTagWrite(page, "tag_save", "the team server did not answer"); + await pickNewQuickTag(picker, name); + await waitForQuickTagWrite(page); + await page.keyboard.press("Escape"); + await expect(picker).toHaveCount(0); + + await releaseQuickTagWrite(page); + await expect(toast(page, "Couldn’t save tags")).toContainText("The team server isn’t answering. Try again once it’s back."); + await waitForIdle(page); + expect(await callsOf(page, "tag_save")).toHaveLength(1); + expect(await callsOf(page, "tag_assign")).toEqual([]); + const saved = await storedTags(page); + expect(saved.tags.map((tag) => tag.name)).not.toContain(name); + expect(saved.by_profile[QUICK_TAG_PROFILE] ?? []).toEqual([]); + await expect(toast(page, "Tags saved")).toHaveCount(0); +}); + +test("closing the quick team tag picker after a teammate's edit reports no save", async ({ page }) => { + const picker = await openQuickTeamTagPicker(page); + const option = picker.getByRole("option", { name: QUICK_TAG.name, exact: true }); + await expect(option).toHaveAttribute("aria-selected", "false"); + await page.evaluate(({ profileId, tagId }) => { + const mock = (window as unknown as M).__shardxMock; + mock.state.tags.by_profile[profileId] = [tagId]; + mock.emit("store-changed", "tags"); + }, { profileId: QUICK_TAG_PROFILE, tagId: QUICK_TAG.id }); + await expect(option).toHaveAttribute("aria-selected", "true"); + + await page.keyboard.press("Escape"); + await expect(picker).toHaveCount(0); + await expect(toast(page, "Tags saved")).toHaveCount(0); + expect(await callsOf(page, "tag_assign")).toEqual([]); +}); diff --git a/src/entities/tag/lib/useTags.ts b/src/entities/tag/lib/useTags.ts index 64a2e801b..ee87736ce 100644 --- a/src/entities/tag/lib/useTags.ts +++ b/src/entities/tag/lib/useTags.ts @@ -2,7 +2,7 @@ import { create } from "zustand"; import { LABEL_COLORS, type LabelColorId } from "../../../shared/constants"; import { handOver, windowStorage } from "../../../shared/lib/handOver"; import { writeQueue } from "../../../shared/lib/writeQueue"; -import { onSpaceMoved } from "../../../shared/api/invoke"; +import { onSpaceMoved, spaceEpoch } from "../../../shared/api/invoke"; import { toast } from "../../../shared/model/toast"; import { t } from "../../../shared/i18n"; import type { Tag } from "../model/types"; @@ -19,8 +19,33 @@ export function setTagAssignGuard(fn: AssignGuard): void { assignGuard = fn; } /** A tag a team's server saved under another id than sent (tag_save in a team): the new one. */ const renamed = new Map(); const finalId = (id: string) => renamed.get(id) ?? id; -const remapped = (byProfile: Record) => - Object.fromEntries(Object.entries(byProfile).map(([pid, ids]) => [pid, ids.map(finalId)])); +type TagCreation = { saved: boolean }; +const remapped = (byProfile: Record, creations: ReadonlyMap) => + Object.fromEntries(Object.entries(byProfile).map(([pid, ids]) => [ + pid, ids.filter((id) => creations.get(id)?.saved !== false).map(finalId), + ])); + +export type TagToggle = { + tagId: string; + profileIds: string[]; + adding: boolean; + saved: Promise; +}; + +/** Opposite picks cancel, including when a newly created tag received its server ID. */ +export function tagsChanged(picks: readonly TagToggle[]): boolean { + const changes = new Map(); + for (const { tagId, profileIds, adding } of picks) { + const id = finalId(tagId); + for (const pid of profileIds) { + const key = JSON.stringify([pid, id]); + const change = changes.get(key); + if (change) change.after = adding; + else changes.set(key, { before: !adding, after: adding }); + } + } + return [...changes.values()].some(({ before, after }) => before !== after); +} /// Tags, and tag ids by profile id. The backend keeps them (tags.rs); this /// store shows each change at once and sends it after. @@ -77,7 +102,7 @@ export type TagStore = { * a tag made since with its name gets those profiles instead. */ restoreTag: (tag: Tag, byProfile: Record, at?: number) => void; /** Gives the tag to every profile, or takes it off all when all have it. */ - toggle: (profileIds: string[], tagId: string) => void; + toggle: (profileIds: string[], tagId: string) => TagToggle | null; /** Takes one tag off one profile. */ untag: (profileId: string, tagId: string) => void; /** Gives one profile exactly these tags (the profile form's Save). */ @@ -92,6 +117,7 @@ let loading: Promise | null = null; export const useTags = create((set, get) => { let queue: ReturnType | null = null; + const creating = new Map(); const read = async () => { const s = await tagList(); set(whole(s.tags, s.by_profile, COLOR_IDS)); @@ -107,13 +133,19 @@ export const useTags = create((set, get) => { } })(); // Sent after the first read, in order: a change can never land before the handed-over copy. - const send = (call: () => Promise) => { + const send = (call: () => Promise, creation?: TagCreation): Promise => { queue ??= writeQueue(load(), (e) => toast.fail({ title: t("useTags.saveFailed"), detail: e }), read); - void queue(call); + let saved = false; + return queue(async () => { + // The creation was queued first and has already reported any failure. + if (creation?.saved === false) return; + await call(); + saved = true; + }).then(() => saved); }; /** 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, creation?: TagCreation) => { const asked = [...touched]; const { refused, reason } = assignGuard(asked); const byProfile = { ...wanted }; @@ -125,7 +157,9 @@ export const useTags = create((set, get) => { const changes = changedLists(get().byProfile, byProfile, asked.filter((pid) => !refused.includes(pid))); 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))); + const pending = new Map(creating); + const saved = Object.keys(changes).length ? send(() => tagAssign(remapped(changes, pending)), creation) : Promise.resolve(true); + return saved.then((ok) => ok && refused.length === 0); }; /** A team's server answered a new tag with its own id: everything that names it follows. */ const settleId = (sent: Tag, saved: Tag | null | undefined) => { @@ -136,6 +170,33 @@ export const useTags = create((set, get) => { byProfile: Object.fromEntries(Object.entries(get().byProfile).map(([pid, ids]) => [pid, ids.map((x) => (x === sent.id ? saved.id : x))])), }); }; + const forgetTag = (id: string) => { + const byProfile: Record = {}; + for (const [pid, ids] of Object.entries(get().byProfile)) { + const kept = ids.filter((x) => x !== id); + if (kept.length) byProfile[pid] = kept; + } + set({ tags: get().tags.filter((t) => t.id !== id), byProfile }); + }; + const saveNewTag = (tag: Tag, at?: number): TagCreation => { + const epoch = spaceEpoch(); + const here = () => epoch === undefined || epoch === spaceEpoch(); + const creation: TagCreation = { saved: false }; + creating.set(tag.id, creation); + // A team can return a different ID, which also follows its assignments. + void send(async () => { + const saved = await tagSave(tag, at); + if (!saved?.id) throw new Error(t("useTags.saveFailed")); + if (here()) settleId(tag, saved); + creation.saved = true; + }).then((saved) => { + if (creating.get(tag.id) !== creation) return; + // A fresh list may already have replaced the optimistic tag. + if (!saved && here() && get().tags.includes(tag)) forgetTag(tag.id); + creating.delete(tag.id); + }); + return creation; + }; /** Why a team does not take this tag change, said once; null when it does. */ const refuse = (action: "create" | "edit" | "delete"): boolean => { const why = teamRefusal(action); @@ -158,8 +219,7 @@ export const useTags = create((set, get) => { if (refuse("create")) return null; const tag: Tag = { id: newId(), name: n, color: color ?? nextTagColor(get().tags) }; set({ tags: [...get().tags, tag] }); - // A team lists its tags by name and may answer another id: the reply's is kept. - send(async () => settleId(tag, await tagSave(tag))); + saveNewTag(tag); return tag; }, rename: (id, name) => { @@ -183,23 +243,19 @@ export const useTags = create((set, get) => { }, remove: (id) => { if (refuse("delete")) return; - const byProfile: Record = {}; - for (const [pid, ids] of Object.entries(get().byProfile)) { - const kept = ids.filter((x) => x !== id); - if (kept.length) byProfile[pid] = kept; - } - set({ tags: get().tags.filter((t) => t.id !== id), byProfile }); + forgetTag(id); send(() => tagDelete(id)); }, restoreTag: (tag, byProfile, at) => { // A tag made since under its name takes its profiles: no two tags share a name. const twin = get().tags.find((x) => x.id !== tag.id && same(x.name, tag.name)); + let creation: TagCreation | undefined; if (!twin) { if (refuse("create")) return; const tags = [...get().tags]; if (!tags.some((x) => x.id === tag.id)) tags.splice(at ?? tags.length, 0, tag); set({ tags }); - send(async () => settleId(tag, await tagSave(tag, at))); + creation = saveNewTag(tag, at); } const back = twin?.id ?? tag.id; const merged = { ...get().byProfile }; @@ -209,18 +265,22 @@ export const useTags = create((set, get) => { merged[pid] = [...new Set([...(merged[pid] ?? []), back])]; touched.push(pid); } - assign(merged, touched); + assign(merged, touched, creation); }, toggle: (profileIds, tagId) => { + const id = finalId(tagId); const cur = get().byProfile; - const all = profileIds.every((pid) => cur[pid]?.includes(tagId)); + const all = profileIds.every((pid) => cur[pid]?.includes(id)); + const touched = all ? profileIds : profileIds.filter((pid) => !cur[pid]?.includes(id)); + if (touched.length === 0) return null; const byProfile = { ...cur }; - for (const pid of profileIds) { + for (const pid of touched) { const ids = cur[pid] ?? []; - const next = all ? ids.filter((x) => x !== tagId) : ids.includes(tagId) ? ids : [...ids, tagId]; + const next = all ? ids.filter((x) => x !== id) : [...ids, id]; if (next.length) byProfile[pid] = next; else delete byProfile[pid]; } - assign(byProfile, profileIds); + const saved = assign(byProfile, touched, creating.get(id)); + return { tagId: id, profileIds: touched, adding: !all, saved }; }, untag: (profileId, tagId) => { const ids = (get().byProfile[profileId] ?? []).filter((x) => x !== tagId); diff --git a/src/features/manage-tags/ui/TagPicker.tsx b/src/features/manage-tags/ui/TagPicker.tsx index 2a4f61f43..f4f6dfd95 100644 --- a/src/features/manage-tags/ui/TagPicker.tsx +++ b/src/features/manage-tags/ui/TagPicker.tsx @@ -1,8 +1,9 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { Combobox, Popover, type ComboboxOption } from "@proxyshard/shardx-ui-kit"; -import { useT } from "../../../shared/i18n"; +import { t as translate, useT } from "../../../shared/i18n"; +import { spaceEpoch } from "../../../shared/api/invoke"; import { toast } from "../../../shared/model/toast"; -import { TAG_NAME_MAX, useTags } from "../../../entities/tag"; +import { TAG_NAME_MAX, tagsChanged, useTags, type TagToggle } from "../../../entities/tag"; import { teamRefusal, useRightsChange } from "../../../entities/space"; import { TagChip } from "../../../shared/ui/TagChip"; @@ -14,8 +15,8 @@ import { TagChip } from "../../../shared/ui/TagChip"; /// is the target (FEEL-25). Each tag is the tinted chip a row shows (owner /// feedback 5t: one look for a tag everywhere). It opens under `anchorRef`, /// or at `anchorPoint` (a key, a cell) with `triggerRef` the control that -/// toggles it. Each pick applies at once and is quiet; closing it after a net -/// change says "Tags saved" once (manual save, Ruling 2). +/// toggles it. Each pick applies at once and is quiet; closing it after a +/// confirmed net change says "Tags saved" once (manual save, Ruling 2). export function TagPicker({ open, profileIds, anchorRef, anchorPoint, triggerRef, onClose }: { open: boolean; profileIds: string[]; @@ -34,20 +35,28 @@ export function TagPicker({ open, profileIds, anchorRef, anchorPoint, triggerRef const toggle = useTags((s) => s.toggle); const [query, setQuery] = useState(""); - // The tags these profiles had as it opened, to tell on closing whether a - // pick (or two that cancel) left a change. - const opened = useRef(null); - const tagsOf = () => { - const now = useTags.getState().byProfile; - return profileIds.map((id) => [...(now[id] ?? [])].sort().join(",")).join("|"); - }; + const opening = useRef<{ picks: TagToggle[]; refused: boolean } | null>(null); useEffect(() => { - if (open) { opened.current = tagsOf(); return; } - if (opened.current !== null && opened.current !== tagsOf()) toast.saved(t("tagPicker.saved")); - opened.current = null; - // eslint-disable-next-line react-hooks/exhaustive-deps -- runs when it opens or closes + if (!open) return; + const epoch = spaceEpoch(); + const session = { picks: [] as TagToggle[], refused: false }; + opening.current = session; + return () => { + opening.current = null; + if (session.refused || session.picks.length === 0) return; + // Normal dismissal can unmount the picker before the last write settles. + void Promise.all(session.picks.map((pick) => pick.saved)).then((results) => { + if (epoch === spaceEpoch() && results.every(Boolean) && tagsChanged(session.picks)) { + toast.saved(translate("tagPicker.saved")); + } + }); + }; }, [open]); + const pick = (id: string) => { + const receipt = toggle(profileIds, id); + if (receipt) opening.current?.picks.push(receipt); + }; const count = (tagId: string) => profileIds.filter((pid) => byProfile[pid]?.includes(tagId)).length; const options = useMemo( () => tags.map((tag) => ({ value: tag.id, label: tag.name, content: })), @@ -79,10 +88,11 @@ export function TagPicker({ open, profileIds, anchorRef, anchorPoint, triggerRef // comparison with the existing names is the real one (PC-085). onQueryChange={(q) => setQuery(q.replace(/\s+/g, " ").slice(0, TAG_NAME_MAX))} // A mixed tag goes to every profile; a checked one comes off all. - onChange={(id) => toggle(profileIds, id)} + onChange={pick} onCreate={noCreate ? undefined : (name) => { const tag = create(name); - if (tag && count(tag.id) < profileIds.length) toggle(profileIds, tag.id); + if (tag && count(tag.id) < profileIds.length) pick(tag.id); + if (!tag && opening.current) opening.current.refused = true; setQuery(""); }} createLabel={(name) => t("tagPicker.create", { name })}