From c1449cd27782cb19f337bca9da4720ecba7215f4 Mon Sep 17 00:00:00 2001 From: glwhappen <40719048+glwhappen@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:09:57 +0800 Subject: [PATCH 1/4] Keep teammates tags when editing team profiles --- e2e/team-review-fixes.spec.ts | 37 +++++++++++- src-tauri/src/api.rs | 54 +++++++++++++++++ src-tauri/src/lib.rs | 17 +++++- src-tauri/src/live_e2e.rs | 2 +- src-tauri/src/space/cache.rs | 40 +++++++++++++ src-tauri/src/space/mod.rs | 7 +++ src-tauri/src/space/write.rs | 60 +++++++++++++++++-- src/dev/mock/handlers.ts | 24 +++++++- src/dev/mock/teamRights.ts | 2 +- src/entities/tag/lib/useTags.ts | 49 +++++++++++---- src/entities/tag/model/api.ts | 3 + .../profile-form/model/useProfileForm.ts | 2 +- 12 files changed, 274 insertions(+), 23 deletions(-) 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(); From e7fdad7754c48e972e6765e4fd7188d6d3dedabe Mon Sep 17 00:00:00 2001 From: glwhappen <40719048+glwhappen@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:21:23 +0800 Subject: [PATCH 2/4] Recover team profile edits from server conflicts --- e2e/profile-form.spec.ts | 87 +++++++++++++++++ src-tauri/src/api.rs | 36 +++++++ src-tauri/src/lib.rs | 12 +++ src-tauri/src/live_e2e.rs | 4 + src-tauri/src/space/doors.rs | 1 + src-tauri/src/space/mod.rs | 8 +- src-tauri/src/space/write.rs | 14 ++- src/dev/mock/handlers.ts | 5 + src/dev/mock/spaces.ts | 7 +- src/dev/mock/teamRights.ts | 11 ++- src/entities/profile/lib/useProfile.tsx | 18 +++- src/entities/profile/model/api.ts | 2 + .../profile-form/model/useProfileForm.ts | 97 +++++++++++++------ .../profile-form/ui/ProfileFormDialog.tsx | 23 +++-- src/shared/i18n/locales/en.json | 3 + src/shared/i18n/locales/ru.json | 3 + src/shared/i18n/locales/zh.json | 3 + 17 files changed, 288 insertions(+), 46 deletions(-) diff --git a/e2e/profile-form.spec.ts b/e2e/profile-form.spec.ts index 8c551df36..3c6642b76 100644 --- a/e2e/profile-form.spec.ts +++ b/e2e/profile-form.spec.ts @@ -1,6 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import { appModule, openApp, row, seedATag, storedTags, waitForIdle } from "./support/app"; import { pickOption } from "./support/select"; +import { ADMIN_INVITE, joinTeam } from "./support/team"; // One profile form for creating and editing a profile (manual save, Tasks 3 // and 4): nothing is written until Save or Create profile. @@ -9,6 +10,7 @@ type Stored = { navigator: { hardware_concurrency: number; device_memory: number }; _meta: { id: string; rev: number; folder: string; proxy_id: string | null }; geolocation?: { mode: string; latitude: number }; + extra_setting?: string; }; type Mock = { __shardxMock: { @@ -19,6 +21,7 @@ type Mock = { }; }; const SANDBOX = "f62a9d43"; +const ETSY_MAIN = "tp-shop-1"; const dialog = (page: Page, name: string) => page.getByRole("dialog", { name, exact: true }); const calls = (page: Page, cmd: string) => page.evaluate((c) => (window as unknown as Mock).__shardxMock.calls[c] ?? 0, cmd); const stored = (page: Page, id: string) => page.evaluate((i) => (window as unknown as Mock).__shardxMock.state.profiles[i], id); @@ -37,6 +40,25 @@ async function openEdit(page: Page, name = "Sandbox") { return d; } +/** The team server has advanced, but the normal detail cache has not heard yet. */ +function editOnTeamServer(page: Page, changes: Partial>) { + return page.evaluate(async ({ id, changes }) => { + const w = window as unknown as Mock & { + __TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record, options?: unknown) => Promise }; + }; + const ipc = w.__TAURI_INTERNALS__; + const invoke = ipc.invoke; + const cached = await invoke("profile_get", { id }); + ipc.invoke = (cmd, args, options) => cmd === "profile_get" && args?.id === id + ? Promise.resolve(structuredClone(cached)) + : invoke(cmd, args, options); + const profile = w.__shardxMock.state.profiles[id]; + Object.assign(profile, changes); + profile._meta.rev++; + return profile._meta.rev; + }, { id: ETSY_MAIN, changes }); +} + // ---- Edit (Task 3) --------------------------------------------------------- test("Edit opens the form on Basics with the profile's values", async ({ page }) => { @@ -151,6 +173,71 @@ test("rev conflict keeps the form open with the conflict message", async ({ page await expect(d.getByRole("textbox", { name: "Notes" })).toHaveValue("Theirs"); }); +test("saving after a team profile conflict preserves the teammate's other changes", async ({ page }) => { + await openApp(page); + await joinTeam(page, ADMIN_INVITE); + const d = await openEdit(page, "Etsy main"); + const notes = d.getByRole("textbox", { name: "Notes" }); + const save = d.getByRole("button", { name: "Save", exact: true }); + await notes.fill("My new notes"); + const latest = await editOnTeamServer(page, { name: "Teammate's name", extra_setting: "server value" }); + + await save.click(); + await expect(d.getByRole("button", { name: "Reload", exact: true })).toBeVisible(); + await expect(notes).toHaveValue("My new notes"); + expect((await stored(page, ETSY_MAIN))._meta.rev).toBe(latest); + + await save.click(); + await expect(page.getByRole("dialog")).toHaveCount(0); + expect(await stored(page, ETSY_MAIN)).toMatchObject({ + name: "Teammate's name", notes: "My new notes", extra_setting: "server value", _meta: { rev: latest + 1 }, + }); + const payload = await page.evaluate(() => { + const { log } = (window as unknown as Mock).__shardxMock; + return log.filter((x) => x.cmd === "profile_save").at(-1)?.args.payload; + }); + expect(payload).toMatchObject({ _meta: { rev: latest } }); +}); + +test("retrying a failed team conflict read keeps the draft until Reload is chosen", async ({ page }) => { + await openApp(page); + await joinTeam(page, ADMIN_INVITE); + await row(page, "Etsy main").locator("[data-cell='name']").click(); + await page.locator("aside[data-peek] [data-peek-edit]").click(); + const d = dialog(page, "Edit Etsy main"); + const notes = d.getByRole("textbox", { name: "Notes" }); + const save = d.getByRole("button", { name: "Save", exact: true }); + await notes.fill("My unsaved notes"); + const latest = await editOnTeamServer(page, { notes: "Teammate's new notes", extra_setting: "server value" }); + await knob(page, "__shardxMockFailWith", { profile_get_for_edit: "the team server did not answer" }); + + const before = await calls(page, "profile_save"); + await save.click(); + const retry = d.getByRole("button", { name: "Retry", exact: true }); + await expect(retry).toBeVisible(); + await expect(save).toBeDisabled(); + await expect(notes).toHaveValue("My unsaved notes"); + expect(await calls(page, "profile_save")).toBe(before + 1); + + await retry.click(); + const reload = d.getByRole("button", { name: "Reload", exact: true }); + await expect(reload).toBeVisible(); + await expect(notes).toHaveValue("My unsaved notes"); + expect(await calls(page, "profile_save")).toBe(before + 1); + + await reload.click(); + await expect(notes).toHaveValue("Teammate's new notes"); + await expect(save).toBeDisabled(); + expect((await stored(page, ETSY_MAIN))._meta.rev).toBe(latest); + + await notes.fill("Notes edited after reloading"); + await save.click(); + await expect(d).toHaveCount(0); + expect(await stored(page, ETSY_MAIN)).toMatchObject({ + notes: "Notes edited after reloading", extra_setting: "server value", _meta: { rev: latest + 1 }, + }); +}); + test("failed save shows the error next to Save and keeps values", async ({ page }) => { await openApp(page); const d = await openEdit(page); diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 03cb375c8..ad40010aa 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -2292,6 +2292,42 @@ mod tests { drop(t.srv); } + #[tokio::test] + async fn a_profile_conflict_reads_current_settings_in_the_editors_team_space() { + let t = Team::new(&[allow(folder("Ads"), Action::See), allow(folder("Ads"), Action::Edit)]).await; + t.folder("Ads").await; + t.profile("p-1", "Ads", "First", json!({ "other_setting": "before" })).await; + t.enter().await; + let id = "p-1".to_string(); + let epoch = crate::team::space_epoch(); + let opened = crate::profile_get(id.clone()).await.unwrap(); + let revision = opened["_meta"]["rev"].as_u64().unwrap(); + assert_eq!(opened["other_setting"], "before"); + + // The team server has a newer version while this device still holds what it opened. + t.profile(&id, "Ads", "Theirs", json!({ "other_setting": "after" })).await; + let mut draft = opened.clone(); + draft["name"] = json!("Mine"); + let error = crate::save_profile_core(None, draft, false, Door("profile_save"), &Ticket::now()).await.unwrap_err(); + assert!(error.to_string().contains("changed after you opened it"), "{error}"); + assert_eq!(crate::profile_get(id.clone()).await.unwrap(), opened); + + let current = crate::profile_get_for_edit(id.clone(), epoch).await.unwrap(); + assert_eq!(current["_meta"]["rev"], revision + 1); + assert_eq!(current["name"], "Theirs"); + assert_eq!(current["other_setting"], "after"); + assert_eq!(crate::profile_get(id.clone()).await.unwrap(), opened, "ordinary reads still use their cache"); + + t.set_grants(&[allow(folder("Ads"), Action::See)]).await; + let error = crate::profile_get_for_edit(id.clone(), epoch).await.unwrap_err(); + assert!(error.contains("needs edit on the profile"), "{error}"); + + crate::space::switch(Space::Personal).await.unwrap(); + let error = crate::profile_get_for_edit(id, epoch).await.unwrap_err(); + assert_eq!(error, CmdError::SpaceChanged.to_string()); + drop(t.srv); + } + #[tokio::test] async fn moving_a_profile_needs_create_where_it_lands() { let ads = [allow(folder("Ads"), Action::See), allow(folder("Ads"), Action::Edit)]; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc42f1ada..22e56acad 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -113,6 +113,17 @@ async fn profile_get(id: String) -> Result { serde_json::to_value(stored).map_err(|e| e.to_string()) } +/// Read the server's latest settings after an edit conflict in a team. +#[tauri::command] +async fn profile_get_for_edit(id: String, epoch: u64) -> Result { + let t = ticket(Some(epoch))?; + let mut stored = space::profile::fetch_current_for_edit(&t, &id).await.map_err(|e| e.to_string())?; + if stored.meta.gpu_preset_id.is_none() && stored.meta.lock.is_none() { + stored.meta.gpu_preset_id = infer_gpu_preset_id(&stored.config); + } + serde_json::to_value(stored).map_err(|e| e.to_string()) +} + /// Recover library fingerprint id by matching webgl.renderer (+ screen if ambiguous). fn infer_gpu_preset_id(config: &serde_json::Map) -> Option { let renderer = config.get("webgl")?.get("renderer")?.as_str()?; @@ -2794,6 +2805,7 @@ pub fn run() { helper_dismiss, profile_list, profile_get, + profile_get_for_edit, profile_protect, profile_unprotect, profile_change_password, diff --git a/src-tauri/src/live_e2e.rs b/src-tauri/src/live_e2e.rs index edfdf07f3..96b2b52b7 100644 --- a/src-tauri/src/live_e2e.rs +++ b/src-tauri/src/live_e2e.rs @@ -212,6 +212,10 @@ mod device { // ---- profiles ---- "profiles" => crate::profile_list().await.map(val), "profile_get" => crate::profile_get(s(&a, "id")).await, + "profile_get_for_edit" => { + let epoch = a["epoch"].as_u64().ok_or("harness: profile_get_for_edit needs an epoch")?; + crate::profile_get_for_edit(s(&a, "id"), epoch).await + } "create_profile" => { let mut m = crate::library_profile(FP_ID, None)?; m.insert("name".into(), Value::String(s(&a, "name"))); diff --git a/src-tauri/src/space/doors.rs b/src-tauri/src/space/doors.rs index c553fb437..580138a2f 100644 --- a/src-tauri/src/space/doors.rs +++ b/src-tauri/src/space/doors.rs @@ -128,6 +128,7 @@ const RULES: &[(&str, Need)] = &[ // Profiles. ("profile_list", SEE_P), ("profile_get", SEE_P), + ("profile_get_for_edit", SEE_P), // A password-protected profile is this machine's own: no team profile has one (#127). ("profile_protect", Off), ("profile_unprotect", Off), diff --git a/src-tauri/src/space/mod.rs b/src-tauri/src/space/mod.rs index d3122ea6d..6124c0ba5 100644 --- a/src-tauri/src/space/mod.rs +++ b/src-tauri/src/space/mod.rs @@ -397,12 +397,18 @@ pub mod profile { /// The settings to change and save whole: a team's as its server has them now. pub async fn fetch_for_edit(t: &Ticket, id: &str) -> Result { match t.team() { - Some(team) => Ok(write::read_for_edit(team, id).await?), + Some(team) => Ok(write::read_for_edit(team, id, None).await?), None if !local::exists(id) => Err(missing_here(id)), None => local::load_raw(id), } } + /// Current settings for an edit conflict, in the workspace that opened it. + pub async fn fetch_current_for_edit(t: &Ticket, id: &str) -> Result { + let team = t.team().ok_or(CmdError::NotOffered("this profile refresh requires a team space"))?; + Ok(write::read_for_edit(team, id, Some(t)).await?) + } + /// A new profile's door, asked before anything made for it (a proxy) is stored. pub fn check_create(door: Door, t: &Ticket, folder: &str, made: &Made<'_>) -> Result<()> { match t.team() { diff --git a/src-tauri/src/space/write.rs b/src-tauri/src/space/write.rs index 82712bdb6..1deedf692 100644 --- a/src-tauri/src/space/write.rs +++ b/src-tauri/src/space/write.rs @@ -70,9 +70,19 @@ async fn fresh(c: &TeamClient, id: &str) -> Result { } /// A team profile's settings to change, as the server has them now. -pub async fn read_for_edit(team: &str, id: &str) -> Result { +pub async fn read_for_edit(team: &str, id: &str, ticket: Option<&Ticket>) -> Result { + if let Some(t) = ticket { + t.still()?; + } row_of(team, id)?; - let now = fresh(&client(team)?, id).await?; + let c = client(team)?; + let now = fresh(&c, id).await?; + if let Some(t) = ticket { + t.still()?; + if !c.is_current() { + return Err(CmdError::SpaceChanged); + } + } Ok(remote::stored(&now.row, Some(&now.data))) } diff --git a/src/dev/mock/handlers.ts b/src/dev/mock/handlers.ts index 0f7973574..734a9ac5b 100644 --- a/src/dev/mock/handlers.ts +++ b/src/dev/mock/handlers.ts @@ -544,6 +544,11 @@ export const handlers: Record = { profile_list: (_a, { state }) => state.order.map((id) => metaOf(state.profiles[id])), // A protected profile's answer is a stub: its name and the open part of `_meta` (#127). profile_get: ({ id }, { state }) => { const p = profile(state, id); return p._meta.lock ? stubOf(p) : p; }, + // A team editing conflict reads the server's current settings. + profile_get_for_edit: ({ id }, { state }) => { + if (!teamInUse(state)) throw "this profile refresh requires a team space"; + return profile(state, id); + }, profile_save: ({ payload, password }, ctx) => { // `window.__shardxMockSaveFails = true` makes saves fail as a full disk would. if ((window as { __shardxMockSaveFails?: boolean }).__shardxMockSaveFails) throw "No space left on device (os error 28)"; diff --git a/src/dev/mock/spaces.ts b/src/dev/mock/spaces.ts index 3d0915a74..1db1d069a 100644 --- a/src/dev/mock/spaces.ts +++ b/src/dev/mock/spaces.ts @@ -178,11 +178,14 @@ export function mirror(state: MockState): void { }); } -/** The refusal a write gets before anything is written (space::window_ticket, then the team's reach). */ +/** The refusal an edition-bound request gets before it runs. */ export function refusal(state: MockState, cmd: string, args: Record): string | null { - if (!EPOCH_WRITES.has(cmd)) return null; + const editRead = cmd === "profile_get_for_edit"; + if (!EPOCH_WRITES.has(cmd) && !editRead) return null; const asked = args.epoch; + if (editRead && typeof asked !== "number") return SPACE_REFUSALS.noEpoch; if (typeof asked === "number" && asked !== epoch) return SPACE_REFUSALS.spaceChanged; + if (editRead) return null; const team = teamInUse(state); if (!team) return null; if (typeof asked !== "number") return SPACE_REFUSALS.noEpoch; diff --git a/src/dev/mock/teamRights.ts b/src/dev/mock/teamRights.ts index 1918c93b3..29f04aff7 100644 --- a/src/dev/mock/teamRights.ts +++ b/src/dev/mock/teamRights.ts @@ -3,7 +3,7 @@ // at equal width, nothing matching is no. Each refusal is worded as space/error.rs words it. import type { MockState, StoredProfile } from "./fixtures"; import type { Ctx } from "./handlers"; -import { NOT_IN_TEAM, teamInUse } from "./spaces"; +import { NOT_IN_TEAM, teamInUse, teamUnreachable } from "./spaces"; import { TEAM_REFUSALS } from "../../shared/api/teamRefusals"; import { decide, type Target } from "../../entities/team/lib/decide"; import type { Grant, TeamAction } from "../../entities/team/model/types"; @@ -49,6 +49,8 @@ export function rightsOf(state: MockState, p: StoredProfile): ProfileRights { return { see: m("see"), start: m("start"), edit: m("edit"), delete: m("delete"), cookies: m("cookies"), take_out: m("take_out") }; } +const readsSettings = (r: ProfileRights) => r.start || r.edit || r.cookies || r.take_out; + /** Who has a team profile open: this launcher while it runs here, or another device's lease. */ export function openOnOf(state: MockState, id: string): OpenOn | undefined { const s = server(state); @@ -112,7 +114,7 @@ export function teamView(state: MockState, cmd: string, out: unknown): unknown { // with See alone the row is all there is (remote.rs `stored(row, None)`). const p = out as StoredProfile; const r = p?._meta ? rightsOf(state, p) : null; - if (!r || r.start || r.edit || r.cookies || r.take_out) return out; + if (!r || readsSettings(r)) return out; return { _meta: { ...p._meta, pinned: false, total_runtime_ms: 0, extensions: [], gpu_preset_id: "" }, name: p.name, notes: p.notes }; } case "bookmark_list": case "extension_list": case "automation_list": @@ -171,6 +173,11 @@ export function teamDoor(state: MockState, cmd: string, args: Record void; password?: string }) => Promise; + saveProfile: (draft: ProfileForm, opts?: { onFailed?: (error: unknown) => void; password?: string; backing?: unknown }) => Promise; /** Creates the profile the profile form describes (Create profile): the * backend creates it from the form, the form's values go over what the * backend rolls for a new profile, then it goes in its Folder, on its @@ -804,6 +804,8 @@ export const useProfile = create((set, get) => ({ }, saveProfile: async (draft, opts) => { + const asked = spaceEpoch(); + const team = inTeam(); const { fingerprints } = get(); const before = get().profiles.find((p) => p.id === draft.id); const refused = before ? profileRefusal(before, "edit") : null; @@ -819,16 +821,22 @@ export const useProfile = create((set, get) => ({ try { const fp = fingerprints.find((g) => g.id === draft.gpu_preset_id) ?? null; // Built on the profile as stored, so what the form doesn't show survives. - const prev = locked ? await profileUnlock(draft.id, opts!.password!) : await profileGet(draft.id); - const saved = await profileSave(toStored(draft, fp, prev), locked ? opts!.password : undefined); + let prev = opts?.backing ?? (locked ? await profileUnlock(draft.id, opts!.password!) : await profileGet(draft.id)); + // Reloading after a conflict can leave the editor ahead of the list cache. + if (team && prev?._meta?.rev !== draft.rev) prev = await profileGetForEdit(draft.id, asked); + const saved = await withEpoch(asked, () => profileSave(toStored(draft, fp, prev), locked ? opts!.password : undefined)); if (edit) endEdit(edit); + if (asked !== spaceEpoch()) return "ok"; // Only this profile changed: its row takes the saved one, no list read. putRows(set, get, [saved]); // A protected one's settings stay in its editor: nothing else reads them. if (!locked) for (const fn of formSaved) fn(draft); return "ok"; } catch (e) { - if (edit) { endEdit(edit); putBack(set, get, edit); } + if (edit) { + endEdit(edit); + if (asked === spaceEpoch()) putBack(set, get, edit); + } const msg = String(e); if (/changed after you opened it/.test(msg)) return "conflict"; // No toast: the caller shows the failure where the edit was made (Peek's diff --git a/src/entities/profile/model/api.ts b/src/entities/profile/model/api.ts index 4b97c1aa8..f222de347 100644 --- a/src/entities/profile/model/api.ts +++ b/src/entities/profile/model/api.ts @@ -3,6 +3,8 @@ import type { ProfileMeta } from "./types"; export const profileList = () => invoke("profile_list"); export const profileGet = (id: string) => invoke("profile_get", { id }); +/** Reads the current team record in the workspace where the edit began. */ +export const profileGetForEdit = (id: string, epoch: number | undefined) => invoke("profile_get_for_edit", { id, epoch }); /** `password` saves a protected profile whole: its fingerprint and proxy are sealed again. */ export const profileSave = (payload: any, password?: string) => invoke("profile_save", password === undefined ? { payload } : { payload, password }); diff --git a/src/features/profile-form/model/useProfileForm.ts b/src/features/profile-form/model/useProfileForm.ts index b3d05325b..5b534bd75 100644 --- a/src/features/profile-form/model/useProfileForm.ts +++ b/src/features/profile-form/model/useProfileForm.ts @@ -2,15 +2,15 @@ import { create } from "zustand"; import { t } from "../../../shared/i18n"; import { toast } from "../../../shared/model/toast"; import { storeBus } from "../../../shared/lib/storeBus"; -import { onSpaceMoved } from "../../../shared/api/invoke"; +import { onSpaceMoved, spaceEpoch } from "../../../shared/api/invoke"; import { explainError } from "../../../shared/lib/errors"; import { HOST_OS } from "../../../shared/lib/utils"; import { hostScreen, type HostScreen } from "../../../shared/lib/hostScreen"; import { AUTO_LANG, AUTO_TZ, matchesOs } from "../../../shared/constants"; import { useGpuCompat, verdictsLoaded } from "../../../shared/model/gpuCompat"; -import { inFolder, teamRefusal } from "../../../entities/space"; +import { inFolder, inTeam, teamRefusal } from "../../../entities/space"; import { - cookiesImport, editsSettled, forgetForm, isProtected, passwordProblem, profileProtect, profileRefusal, enrichPicksForPreset, fromStored, resolveId, + cookiesImport, editsSettled, forgetForm, isProtected, passwordProblem, profileGetForEdit, profileProtect, profileRefusal, enrichPicksForPreset, fromStored, resolveId, pickedPlatformVersion, selectVisible, useProfile, useProfileUi, type ProfileForm, } from "../../../entities/profile"; import { askPassword } from "../../../shared/model/passwordAsk"; @@ -41,7 +41,9 @@ export type ProfileFormDraft = { sourceKind?: SourceKind; }; -export type ProfileFormStatus = "idle" | "saving" | "error" | "conflict"; +export type ProfileFormStatus = "idle" | "saving" | "error" | "conflict" | "reading-conflict"; + +type ConflictVersion = { form: ProfileForm; folder?: string; backing?: unknown }; type ProfileFormState = { open: boolean; @@ -65,9 +67,8 @@ type ProfileFormState = { /** Each open is a session: a read or a save that lands after the form * closed, or opened again, changes nothing. */ session: number; - /** After a conflict, the profile as it is on disk now: Save then writes - * this form's version over it, Reload takes it. */ - theirs: ProfileForm | null; + /** The latest version read after a refused save. */ + theirs: ConflictVersion | null; /** Save was pressed: every invalid field says why. */ tried: boolean; /** Number fields whose text is not a number now (a letter, an emptied @@ -95,6 +96,8 @@ export const useProfileForm = create(() => ({ const get = () => useProfileForm.getState(); const set = (s: Partial) => useProfileForm.setState(s); const copy = (d: ProfileFormDraft): ProfileFormDraft => structuredClone(d); +const busy = (s: ProfileFormState) => s.status === "saving" || s.status === "reading-conflict"; +const awaitingTeamVersion = (s: ProfileFormState) => s.status === "conflict" && !s.theirs && inTeam(); /** A draft as compared: the order tags were given in does not count, and a * picked cookies file counts by its name and size, not its (large) content. */ const key = (d: ProfileFormDraft) => JSON.stringify({ @@ -109,6 +112,14 @@ const PROXY = new Set(["proxy_id"]); const EXTENSIONS = new Set(["extensions"]); /** Not the person's to change: never counted as a change. */ const OWN = new Set(["id", "rev", "cookies_file"]); + +/** Use the latest team version as the base for fields the editor left alone. */ +function reapplyEdits(opened: ProfileForm, draft: ProfileForm, latest: ProfileForm): ProfileForm { + const changes = Object.fromEntries((Object.keys(draft) as (keyof ProfileForm)[]) + .filter((field) => !OWN.has(field) && JSON.stringify(opened[field]) !== JSON.stringify(draft[field])) + .map((field) => [field, draft[field]])); + return { ...latest, ...changes }; +} const tabOf = (k: keyof ProfileForm): ProfileFormTab => BASICS.has(k) ? "basics" : PROXY.has(k) ? "proxy" : EXTENSIONS.has(k) ? "extensions" : "fingerprint"; @@ -185,9 +196,9 @@ function screenFor(fp: FingerprintEntry, host: HostScreen | null): Partial ({ +const draftOf = (form: ProfileForm, folder?: string): ProfileFormDraft => ({ form, - folder: useProfile.getState().profiles.find((p) => p.id === form.id)?.folder ?? "", + folder: folder ?? useProfile.getState().profiles.find((p) => p.id === form.id)?.folder ?? "", tagIds: [...(useTags.getState().byProfile[form.id] ?? [])], newTags: [], newProxyLine: "", @@ -378,7 +389,7 @@ async function openLocked(opts: { id: string; tab?: ProfileFormTab }): Promise): void { const s = get(); const d = s.draft; - if (!d || s.status === "saving") return; + if (!d || busy(s)) return; const form = { ...d.form, ...changes }; // A new profile's screen follows another template's OS; a size picked by // hand stays only on Windows/Linux (macOS and phones keep their own). @@ -422,8 +433,9 @@ export function setFieldInvalid(field: string, bad: boolean): void { /** Changes the parts that live elsewhere: Folder, tags, new tag names, the new proxy line. */ export function patchDraft(changes: Partial>): void { - const d = get().draft; - if (!d || get().status === "saving") return; + const s = get(); + const d = s.draft; + if (!d || busy(s)) return; set({ draft: { ...d, ...changes } }); } @@ -441,8 +453,27 @@ export function addTagName(name: string): void { /** After a conflict: the profile as it is now, with nothing of this form's kept. */ export function reloadProfileForm(): void { - const theirs = get().theirs; - if (theirs) show(draftOf(theirs)); + const { status, theirs } = get(); + if (status === "conflict" && theirs) show(draftOf(theirs.form, theirs.folder)); +} + +async function readTeamConflict(id: string, session: number, epoch: number | undefined): Promise { + if (get().session !== session) return; + set({ status: "reading-conflict", theirs: null, errorDetail: null }); + try { + const backing = await profileGetForEdit(id, epoch); + if (get().session === session) { + set({ status: "conflict", theirs: { form: fromStored(backing), folder: backing._meta?.folder, backing } }); + } + } catch (e) { + if (get().session === session) set({ status: "conflict", errorDetail: explainError(e) ?? null }); + } +} + +/** Read again after a failed conflict read. The draft stays in the form. */ +export async function retryProfileConflict(): Promise { + const s = get(); + if (s.open && s.id && awaitingTeamVersion(s)) await readTeamConflict(s.id, s.session, spaceEpoch()); } /** A team's profile this person may only read: the form opens to read. */ @@ -469,7 +500,7 @@ export function rightsProblem(s: Pick 0 || passwordProblemOf(s)) return false; + if (!s.open || !s.draft || busy(s) || awaitingTeamVersion(s) || problemsOf(s.draft, s).name || s.badFields.length > 0 || passwordProblemOf(s)) return false; if (rightsProblem(s)) return false; return s.mode === "create" || (s.mode === "template" && !s.template) || isDirty(s); } @@ -506,7 +537,7 @@ async function protectNew(id: string, name: string, password: string): Promise { const s = get(); - if (!s.open || !s.draft || s.status === "saving") return false; + if (!s.open || !s.draft || busy(s) || awaitingTeamVersion(s)) return false; if (problemsOf(s.draft, s).name) { set({ tried: true, tab: "basics" }); return false; } if (s.mode === "template") return saveTemplateForm(); // A number field shows text that is not a number: it is on screen, so nothing is saved behind it. @@ -517,13 +548,15 @@ export async function saveProfileForm(): Promise { if (rightsProblem(s)) return false; const session = s.session; const here = () => get().session === session; + const team = inTeam(); + const epoch = spaceEpoch(); set({ status: "saving", error: null, tried: true }); let draft = s.draft; - const name = draft.form.name.trim(); + let name = draft.form.name.trim(); // A protected profile is read again with the password it was opened with. const reread = (id: string) => (s.unlocked !== null ? useProfile.getState().unlockForm(id, s.unlocked) : useProfile.getState().loadForm(id)); // Closed: the password goes with the form. - const close = () => { if (here()) set({ open: false, status: "idle", session: get().session + 1, password: "", passwordRepeat: "", unlocked: null }); }; + const close = () => { if (here()) closeProfileForm(); }; const failed = (error: string, title: string, detail?: unknown) => { if (here()) set({ status: "error", error, errorDetail: explainError(detail) ?? null }); toast.fail({ title, detail, subject: name }); @@ -540,7 +573,7 @@ export async function saveProfileForm(): Promise { set({ mode: "edit", id, saved: opened, draft: { ...draft, form: { ...draft.form, name, id: stored.id, rev: stored.rev }, tagIds: opened.tagIds, newTags: [] }, - status: "error", error: line, errorDetail: explainError(why) ?? null, + status: "error", error: line, errorDetail: explainError(why) ?? null, theirs: null, }); return false; }; @@ -561,6 +594,7 @@ export async function saveProfileForm(): Promise { return failed(t("profileForm.proxyFailed"), t("proxySelect.addFailed"), e); } } + if (!here()) return false; if (s.mode === "create") { const made = await useProfile.getState().createProfile({ ...draft, form: { ...draft.form, name } }); @@ -585,21 +619,29 @@ export async function saveProfileForm(): Promise { return true; } - // 2. The profile, with the rev it was opened at (or, after a conflict, - // the one on disk now: this version goes over it). + // 2. After a team conflict, apply the editor's changes at the revision just read. const id = s.id!; - const rev = s.theirs?.rev ?? draft.form.rev; + const opened = s.saved!; + const form = team && s.theirs ? reapplyEdits(opened.form, draft.form, s.theirs.form) : draft.form; + name = form.name.trim(); + const rev = s.theirs?.form.rev ?? form.rev; let why: unknown; - const result = await useProfile.getState().saveProfile({ ...draft.form, name, rev }, { onFailed: (e) => { why = e; }, password: s.unlocked ?? undefined }); + const result = await useProfile.getState().saveProfile({ ...form, name, rev }, { + onFailed: (e) => { why = e; }, password: s.unlocked ?? undefined, backing: s.theirs?.backing, + }); + if (!here()) return false; if (result === "conflict") { - const theirs = await reread(id).catch(() => null); - if (here()) set({ status: "conflict", theirs }); + if (team) await readTeamConflict(id, session, epoch); + else { + const latest = await reread(id).catch(() => null); + if (here()) set({ status: "conflict", theirs: latest ? { form: latest } : null }); + } return false; } if (result === "failed") return failed(t("profileForm.saveFailed"), t("useProfile.saveFailed", { name }), why); + draft = { ...draft, form: { ...form, name, rev } }; // 3 and 4. Its tags and its Folder, only what changed. - const opened = s.saved!; if (!sameTags(draft, opened)) { // A name typed in becomes a tag only now. const tags = useTags.getState(); @@ -614,6 +656,7 @@ export async function saveProfileForm(): Promise { if (!(await store.moveMany([id], draft.folder, { quiet: true }))) { return stayOpen(id, t("profileForm.savedNoFolder", { folder: draft.folder }), null); } + if (!here()) return false; } // 5. Cookies picked in the form, now that it is saved. diff --git a/src/features/profile-form/ui/ProfileFormDialog.tsx b/src/features/profile-form/ui/ProfileFormDialog.tsx index 2dcd2aa05..9b212404e 100644 --- a/src/features/profile-form/ui/ProfileFormDialog.tsx +++ b/src/features/profile-form/ui/ProfileFormDialog.tsx @@ -7,14 +7,13 @@ import { useUnsaved } from "../../../shared/model/unsaved"; import { LoadError, LoadingRows } from "../../../shared/ui/ListStates"; import { useT } from "../../../shared/i18n"; import { settingsRefusal, useProfile } from "../../../entities/profile"; -import { useRightsChange } from "../../../entities/space"; +import { inTeam, teamRefusal, useRightsChange } from "../../../entities/space"; import { walkTheForm } from "../../tour/lib/profileTour"; import { PROFILE_FORM_TABS, canSave, changedTabs, closeProfileForm, isDirty, openProfileForm, openTemplateForm, passwordProblemOf, problemsOf, readOnlyWhy, reloadProfileForm, - rightsProblem, saveProfileForm, setProfileFormTab, useProfileForm, type ProfileFormTab, + retryProfileConflict, rightsProblem, saveProfileForm, setProfileFormTab, useProfileForm, type ProfileFormTab, } from "../model/useProfileForm"; import { saveFormAsTemplate } from "../model/saveTemplate"; -import { teamRefusal } from "../../../entities/space"; import { useTemplates } from "../../../entities/template"; import { BasicsTab } from "./BasicsTab"; import { ProxyTab } from "./ProxyTab"; @@ -49,7 +48,8 @@ export function ProfileFormDialog() { const problems = problemsOf(draft); // A new profile's password, while one is typed: too short, or the repeat differs. const passwordProblem = passwordProblemOf(s); - const saving = status === "saving"; + const readingConflict = status === "reading-conflict"; + const saving = status === "saving" || readingConflict; // The list's name until the form has loaded, so the title never reads "Edit ". const listed = useProfile((st) => st.profiles.find((p) => p.id === s.id)); const templateMode = mode === "template"; @@ -106,9 +106,18 @@ export function ProfileFormDialog() { : undefined, })); - const note = status === "conflict" ? ( + const team = inTeam(); + const note = status === "conflict" && team && !s.theirs ? ( + + + {t("profileForm.conflictReadFailed")}{" "} + + + {s.errorDetail && {s.errorDetail}} + + ) : status === "conflict" ? ( - {t("profileForm.conflict")}{" "} + {team ? t("profileForm.teamConflict") : t("profileForm.conflict")}{" "} {s.theirs && } ) : status === "error" && draft ? ( @@ -143,7 +152,7 @@ export function ProfileFormDialog() { ); const title = templateMode ? (s.template ? t("templates.editTitle", { name }) : t("templates.newTitle")) : mode === "create" ? t("profileForm.newTitle") : readOnly ? t("profileForm.viewTitle", { name }) : t("profileForm.editTitle", { name }); - const confirmLabel = saving ? t("profileForm.saving") : mode === "create" ? t("profileForm.create") + const confirmLabel = readingConflict ? t("profileForm.readingLatest") : saving ? t("profileForm.saving") : mode === "create" ? t("profileForm.create") : templateMode && !s.template ? t("templates.create") : t("profileForm.save"); return ( diff --git a/src/shared/i18n/locales/en.json b/src/shared/i18n/locales/en.json index d0db012d2..16f7796ff 100644 --- a/src/shared/i18n/locales/en.json +++ b/src/shared/i18n/locales/en.json @@ -1734,6 +1734,8 @@ "profileForm.addProxyLine": "Add", "profileForm.close": "Close", "profileForm.conflict": "This profile was changed somewhere else. Reload it or save your version.", + "profileForm.conflictReadFailed": "Couldn’t read the latest version. Your edits are still here.", + "profileForm.teamConflict": "A teammate changed this profile. Reload to open the latest version, or save your edits.", "profileForm.create": "Create profile", "profileForm.created": "{name} created", "profileForm.createdNoFingerprint": "Created, but couldn’t keep its hardware values. Save tries again.", @@ -1766,6 +1768,7 @@ "profileForm.savedNoFolder": "Saved, but couldn’t move it to {folder}. Save tries again.", "profileForm.saveFailed": "Couldn’t save. Your changes are still here.", "profileForm.saving": "Saving", + "profileForm.readingLatest": "Reading latest version", "profileForm.showMe": "Show me around", "profileForm.tabBasics": "Basics", "profileForm.tabChanged": "Changed", diff --git a/src/shared/i18n/locales/ru.json b/src/shared/i18n/locales/ru.json index 3cef0ac13..a82183ead 100644 --- a/src/shared/i18n/locales/ru.json +++ b/src/shared/i18n/locales/ru.json @@ -1734,6 +1734,8 @@ "profileForm.addProxyLine": "Добавить", "profileForm.close": "Закрыть", "profileForm.conflict": "Этот профиль изменён в другом месте. Перезагрузите его или сохраните свою версию.", + "profileForm.conflictReadFailed": "Не удалось прочитать последнюю версию. Ваши изменения сохранены в форме.", + "profileForm.teamConflict": "Другой участник команды изменил этот профиль. Загрузите последнюю версию или сохраните свои правки.", "profileForm.create": "Создать профиль", "profileForm.created": "Профиль «{name}» создан", "profileForm.createdNoFingerprint": "Профиль создан, но не удалось сохранить параметры оборудования. Нажмите «Сохранить», чтобы повторить.", @@ -1766,6 +1768,7 @@ "profileForm.savedNoFolder": "Профиль сохранён, но не удалось переместить его в папку «{folder}». Нажмите «Сохранить», чтобы повторить.", "profileForm.saveFailed": "Не удалось сохранить. Ваши изменения не потеряны.", "profileForm.saving": "Сохранение", + "profileForm.readingLatest": "Загрузка последней версии", "profileForm.showMe": "Пройти обзор", "profileForm.tabBasics": "Основное", "profileForm.tabChanged": "Изменено", diff --git a/src/shared/i18n/locales/zh.json b/src/shared/i18n/locales/zh.json index ffce13d68..ddc514589 100644 --- a/src/shared/i18n/locales/zh.json +++ b/src/shared/i18n/locales/zh.json @@ -1734,6 +1734,8 @@ "profileForm.addProxyLine": "添加", "profileForm.close": "关闭", "profileForm.conflict": "此配置已在别处更改。请重新加载,或保存你的版本。", + "profileForm.conflictReadFailed": "无法读取最新版本。你的更改仍然保留。", + "profileForm.teamConflict": "队友已更改此配置。可以重新加载最新版本,或保存你编辑的字段。", "profileForm.create": "创建配置", "profileForm.created": "“{name}”已创建", "profileForm.createdNoFingerprint": "已创建,但无法保留其硬件参数。点击“保存”可重试。", @@ -1766,6 +1768,7 @@ "profileForm.savedNoFolder": "已保存,但无法移到“{folder}”。点击“保存”可重试。", "profileForm.saveFailed": "无法保存。你的更改仍保留在这里。", "profileForm.saving": "正在保存", + "profileForm.readingLatest": "正在读取最新版本", "profileForm.showMe": "带我看看", "profileForm.tabBasics": "基本信息", "profileForm.tabChanged": "已更改", From 0aca50dd0ac219f72c34977b347fe7f186765f75 Mon Sep 17 00:00:00 2001 From: glwhappen <1597721684@qq.com> Date: Mon, 30 Nov 2026 14:00:53 +0800 Subject: [PATCH 3/4] Retry a failed profile folder move without rewriting saved settings --- e2e/profile-form.spec.ts | 66 +++++++++++++++++++ .../profile-form/model/useProfileForm.ts | 58 ++++++++++------ 2 files changed, 104 insertions(+), 20 deletions(-) diff --git a/e2e/profile-form.spec.ts b/e2e/profile-form.spec.ts index 3c6642b76..cd2372ef7 100644 --- a/e2e/profile-form.spec.ts +++ b/e2e/profile-form.spec.ts @@ -460,6 +460,72 @@ test("an edit whose Folder move fails stays open with the move still to save, an await expect(toastText(page, "Sandbox saved")).toBeVisible(); }); +async function failTeamFolderMove(page: Page, failRead = false) { + await openApp(page); + await joinTeam(page, ADMIN_INVITE); + const form = await openEdit(page, "Etsy main"); + const name = "Etsy edited here"; + await form.getByRole("textbox", { name: "Name" }).fill(name); + await form.locator("[data-property='folder'] button").click(); + await page.getByRole("option", { name: "Ads", exact: true }).click(); + + await page.evaluate(({ id, failRead }) => { + const w = window as unknown as Mock & { + __TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record, options?: unknown) => Promise }; + __shardxMockFailWith?: Record; + }; + const ipc = w.__TAURI_INTERNALS__; + const invoke = ipc.invoke; + ipc.invoke = (cmd, args, options) => { + if (cmd !== "profile_set_folder" || args?.id !== id) return invoke(cmd, args, options); + ipc.invoke = invoke; + // The name was just written. Before the separate move fails, a teammate saves Notes. + const profile = w.__shardxMock.state.profiles[id]; + profile.notes = "Teammate's notes"; + profile._meta.rev++; + if (failRead) { + const refusing = "the team server did not answer"; + w.__shardxMockFailWith = { profile_get: refusing, profile_get_for_edit: refusing }; + } + return Promise.reject("Mock folder move refused once"); + }; + }, { id: ETSY_MAIN, failRead }); + + const saves = await calls(page, "profile_save"); + const reads = await calls(page, "profile_get_for_edit"); + await form.getByRole("button", { name: "Save", exact: true }).click(); + const edit = dialog(page, `Edit ${name}`); + await expect(edit.getByText("Saved, but couldn’t move it to Ads. Save tries again.")).toBeVisible(); + await expect(edit.locator("[data-property='folder'] button")).toContainText("Ads"); + expect(await stored(page, ETSY_MAIN)).toMatchObject({ name, notes: "Teammate's notes", _meta: { folder: "Shops" } }); + expect(await calls(page, "profile_save")).toBe(saves + 1); + return { edit, name, saves, reads }; +} + +test("a failed team Folder move shows a teammate's latest Notes and retries only the move", async ({ page }) => { + const { edit, name, saves, reads } = await failTeamFolderMove(page); + await expect(edit.getByRole("textbox", { name: "Notes" })).toHaveValue("Teammate's notes"); + expect(await calls(page, "profile_get_for_edit")).toBe(reads + 1); + + await edit.getByRole("button", { name: "Save", exact: true }).click(); + await expect(edit).toHaveCount(0); + expect(await calls(page, "profile_save")).toBe(saves + 1); + expect(await stored(page, ETSY_MAIN)).toMatchObject({ name, notes: "Teammate's notes", _meta: { folder: "Ads" } }); +}); + +test("a failed team Folder move can still be retried if refreshing the saved settings fails", async ({ page }) => { + const { edit, name, saves, reads } = await failTeamFolderMove(page, true); + expect(await calls(page, "profile_get_for_edit")).toBe(reads + 1); + await expect(edit.getByRole("textbox", { name: "Name" })).toHaveValue(name); + const save = edit.getByRole("button", { name: "Save", exact: true }); + await expect(save).toBeEnabled(); + + await save.click(); + await expect(edit).toHaveCount(0); + expect(await calls(page, "profile_save")).toBe(saves + 1); + expect(await stored(page, ETSY_MAIN)).toMatchObject({ name, notes: "Teammate's notes", _meta: { folder: "Ads" } }); +}); + test("a new profile keeps the hardware the form shows, not what the backend rolls", async ({ page }) => { await openApp(page); await page.getByRole("button", { name: "New profile" }).first().click(); diff --git a/src/features/profile-form/model/useProfileForm.ts b/src/features/profile-form/model/useProfileForm.ts index 5b534bd75..ddfe84242 100644 --- a/src/features/profile-form/model/useProfileForm.ts +++ b/src/features/profile-form/model/useProfileForm.ts @@ -113,11 +113,12 @@ const EXTENSIONS = new Set(["extensions"]); /** Not the person's to change: never counted as a change. */ const OWN = new Set(["id", "rev", "cookies_file"]); +const settingsChanges = (opened: ProfileForm, draft: ProfileForm) => (Object.keys(draft) as (keyof ProfileForm)[]) + .filter((field) => !OWN.has(field) && JSON.stringify(opened[field]) !== JSON.stringify(draft[field])); + /** Use the latest team version as the base for fields the editor left alone. */ function reapplyEdits(opened: ProfileForm, draft: ProfileForm, latest: ProfileForm): ProfileForm { - const changes = Object.fromEntries((Object.keys(draft) as (keyof ProfileForm)[]) - .filter((field) => !OWN.has(field) && JSON.stringify(opened[field]) !== JSON.stringify(draft[field])) - .map((field) => [field, draft[field]])); + const changes = Object.fromEntries(settingsChanges(opened, draft).map((field) => [field, draft[field]])); return { ...latest, ...changes }; } const tabOf = (k: keyof ProfileForm): ProfileFormTab => @@ -563,9 +564,8 @@ export async function saveProfileForm(): Promise { return false; }; - // The profile exists but one step did not land: the form goes on as its - // edit form, with what did not land still to save, and says what that was. - const stayOpen = async (id: string, line: string, why: unknown) => { + // A partial create continues as an edit of the profile that already exists. + const partlyCreated = async (id: string, line: string, why: unknown) => { const stored = await reread(id).catch(() => null); if (!here()) return false; if (!stored) { closeProfileForm(); return false; } @@ -607,7 +607,7 @@ export async function saveProfileForm(): Promise { : made.failed.step === "proxy" ? t("profileForm.createdNoProxy") : t("profileForm.createdNoFingerprint"); toast.fail({ title: t("profileForm.createdPartly", { name: meta.name }), detail: made.failed.error, subject: meta.name }); - return stayOpen(meta.id, line, made.failed.error); + return partlyCreated(meta.id, line, made.failed.error); } await importPickedCookies(meta.id, meta.name, draft.cookies); if (s.password) await protectNew(meta.id, meta.name, s.password); @@ -625,20 +625,22 @@ export async function saveProfileForm(): Promise { const form = team && s.theirs ? reapplyEdits(opened.form, draft.form, s.theirs.form) : draft.form; name = form.name.trim(); const rev = s.theirs?.form.rev ?? form.rev; - let why: unknown; - const result = await useProfile.getState().saveProfile({ ...form, name, rev }, { - onFailed: (e) => { why = e; }, password: s.unlocked ?? undefined, backing: s.theirs?.backing, - }); - if (!here()) return false; - if (result === "conflict") { - if (team) await readTeamConflict(id, session, epoch); - else { - const latest = await reread(id).catch(() => null); - if (here()) set({ status: "conflict", theirs: latest ? { form: latest } : null }); + if (settingsChanges(opened.form, draft.form).length > 0) { + let why: unknown; + const result = await useProfile.getState().saveProfile({ ...form, name, rev }, { + onFailed: (e) => { why = e; }, password: s.unlocked ?? undefined, backing: s.theirs?.backing, + }); + if (!here()) return false; + if (result === "conflict") { + if (team) await readTeamConflict(id, session, epoch); + else { + const latest = await reread(id).catch(() => null); + if (here()) set({ status: "conflict", theirs: latest ? { form: latest } : null }); + } + return false; } - return false; + if (result === "failed") return failed(t("profileForm.saveFailed"), t("useProfile.saveFailed", { name }), why); } - if (result === "failed") return failed(t("profileForm.saveFailed"), t("useProfile.saveFailed", { name }), why); draft = { ...draft, form: { ...form, name, rev } }; // 3 and 4. Its tags and its Folder, only what changed. @@ -654,7 +656,23 @@ export async function saveProfileForm(): Promise { // Quiet: this form's own "saved" says it. A move that fails has told why // already; the form stays open with the Folder still to save. if (!(await store.moveMany([id], draft.folder, { quiet: true }))) { - return stayOpen(id, t("profileForm.savedNoFolder", { folder: draft.folder }), null); + if (!here()) return false; + const read = team + ? profileGetForEdit(id, epoch).then((stored) => draftOf(fromStored(stored), stored._meta?.folder)) + : reread(id).then((form) => draftOf(form)); + const latest = await read.catch(() => null); + if (!here()) return false; + if (latest?.folder !== draft.folder) { + // The settings step already settled. Keep its version on both sides + // even if the server cannot answer a read while the move is failing. + const saved = latest ?? draftOf(draft.form, opened.folder); + set({ + saved, draft: { ...draft, form: saved.form, tagIds: saved.tagIds, newTags: [] }, + status: "error", error: t("profileForm.savedNoFolder", { folder: draft.folder }), errorDetail: null, theirs: null, + }); + return false; + } + name = latest.form.name; } if (!here()) return false; } From a97e1d644245202bda43d217f877b0d7ee6c39bc Mon Sep 17 00:00:00 2001 From: glwhappen <1597721684@qq.com> Date: Mon, 30 Nov 2026 14:10:33 +0800 Subject: [PATCH 4/4] Wait for profile tag saves and preserve selections on failure --- e2e/profile-form.spec.ts | 136 +++++++++++++++++- src/entities/profile/lib/useProfile.tsx | 11 +- src/entities/tag/lib/useTags.ts | 92 ++++++++++-- .../profile-form/model/useProfileForm.ts | 48 +++++-- src/shared/i18n/locales/en.json | 1 + src/shared/i18n/locales/ru.json | 1 + src/shared/i18n/locales/zh.json | 1 + src/shared/lib/writeQueue.test.ts | 32 +++++ src/shared/lib/writeQueue.ts | 43 ++++-- 9 files changed, 326 insertions(+), 39 deletions(-) diff --git a/e2e/profile-form.spec.ts b/e2e/profile-form.spec.ts index cd2372ef7..3eb1fe441 100644 --- a/e2e/profile-form.spec.ts +++ b/e2e/profile-form.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; -import { appModule, openApp, row, seedATag, storedTags, waitForIdle } from "./support/app"; +import { appModule, openApp, row, seedATag, storedTags, waitForIdle, type StoredTags } from "./support/app"; import { pickOption } from "./support/select"; import { ADMIN_INVITE, joinTeam } from "./support/team"; @@ -20,6 +20,10 @@ type Mock = { save: () => void; }; }; +type TeamTagMock = Mock & { + __shardxMock: { state: { tags: StoredTags }; emit: (event: string, topic: string) => void }; + __TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record, options?: unknown) => Promise }; +}; const SANDBOX = "f62a9d43"; const ETSY_MAIN = "tp-shop-1"; const dialog = (page: Page, name: string) => page.getByRole("dialog", { name, exact: true }); @@ -333,6 +337,74 @@ test("Folder and tag picks change nothing until Save; Cancel and Discard leave t await expect.poll(names).toEqual(["Fresh tag", "Warm-up"]); }); +test("a team profile waits for its label assignment and can retry without rewriting its settings", async ({ page }) => { + await openApp(page); + await joinTeam(page, ADMIN_INVITE); + await page.evaluate(() => { + const mock = (window as unknown as TeamTagMock).__shardxMock; + mock.state.tags = { + tags: [ + { id: "t-review", name: "Needs review", color: "orange" }, + { id: "t-handoff", name: "Handoff", color: "violet" }, + ], + by_profile: {}, + }; + mock.emit("store-changed", "tags"); + }); + const form = await openEdit(page, "Etsy main"); + const notes = form.getByRole("textbox", { name: "Notes" }); + await notes.fill("Updated here"); + const tags = form.locator("[data-property='tags']"); + await tags.getByRole("button").click(); + const picker = dialog(page, "Tags"); + await picker.getByRole("option", { name: "Needs review" }).click(); + await form.getByRole("textbox", { name: "Name" }).click(); + await expect(picker).toHaveCount(0); + await expect(tags).toContainText("Needs review"); + + type HeldAssign = TeamTagMock & { assignmentStarted?: boolean; releaseAssignment: () => void }; + await page.evaluate(() => { + const w = window as unknown as HeldAssign; + const ipc = w.__TAURI_INTERNALS__; + const invoke = ipc.invoke; + const held = new Promise((resolve) => { w.releaseAssignment = resolve; }); + ipc.invoke = async (cmd, args, options) => { + if (cmd !== "tag_assign") return invoke(cmd, args, options); + ipc.invoke = invoke; + w.assignmentStarted = true; + await held; + throw "Mock label assignment refused once"; + }; + }); + + const writes = await calls(page, "profile_save"); + const save = form.getByRole("button", { name: "Save", exact: true }); + await save.click(); + await page.waitForFunction(() => (window as unknown as HeldAssign).assignmentStarted); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))); + await expect(form).toBeVisible(); + await expect(toastText(page, "Etsy main saved")).toHaveCount(0); + expect((await stored(page, ETSY_MAIN)).notes).toBe("Updated here"); + + await page.evaluate(() => (window as unknown as HeldAssign).releaseAssignment()); + await expect(form.getByRole("alert")).toBeVisible(); + await expect(tags).toContainText("Needs review"); + await expect(notes).toHaveValue("Updated here"); + await expect(save).toBeEnabled(); + await expect(toastText(page, "Etsy main saved")).toHaveCount(0); + expect(await calls(page, "profile_save")).toBe(writes + 1); + expect((await storedTags(page)).by_profile[ETSY_MAIN] ?? []).toEqual([]); + + await page.evaluate((id) => { + (window as unknown as TeamTagMock).__shardxMock.state.tags.by_profile[id] = ["t-handoff"]; + }, ETSY_MAIN); + await save.click(); + await expect(form).toHaveCount(0); + await expect(toastText(page, "Etsy main saved")).toBeVisible(); + expect(await calls(page, "profile_save")).toBe(writes + 1); + expect((await storedTags(page)).by_profile[ETSY_MAIN]?.slice().sort()).toEqual(["t-handoff", "t-review"]); +}); + // ---- Create (Task 4) ------------------------------------------------------- test("New profile opens \"New profile\" with Create profile; Cancel creates nothing", async ({ page }) => { @@ -418,6 +490,68 @@ test("create failure keeps the form open with the error", async ({ page }) => { expect(await count(page)).toBe(8); }); +test("a new team profile can retry creating its label on the profile already saved", async ({ page }) => { + await openApp(page); + await joinTeam(page, ADMIN_INVITE); + const before = await count(page); + await page.getByRole("button", { name: "New profile" }).first().click(); + const form = dialog(page, "New profile"); + const name = "New team profile with label"; + const label = "Pending team label"; + await form.getByRole("textbox", { name: "Name" }).fill(name); + await form.locator("[data-property='tags'] button").click(); + const picker = dialog(page, "Tags"); + await picker.getByRole("combobox", { name: "Find or create a tag" }).fill(label); + await picker.getByRole("option", { name: /Create/ }).click(); + await form.getByRole("textbox", { name: "Name" }).click(); + await expect(picker).toHaveCount(0); + + // A team server can assign its own ID to a successful tag_save. + const confirmedTagId = "server-confirmed-label"; + await page.evaluate(({ label, confirmedTagId }) => { + const w = window as unknown as TeamTagMock & { tagSaveIds: string[] }; + const ipc = w.__TAURI_INTERNALS__; + const invoke = ipc.invoke; + w.tagSaveIds = []; + ipc.invoke = (cmd, args, options) => { + const tag = args?.tag as { id?: string; name?: string } | undefined; + if (cmd === "tag_save" && tag?.name === label && tag.id) { + w.tagSaveIds.push(tag.id); + return invoke(cmd, { ...args, tag: { ...tag, id: confirmedTagId } }, options); + } + return invoke(cmd, args, options); + }; + }, { label, confirmedTagId }); + await knob(page, "__shardxMockFailWith", { tag_save: "Mock label creation refused once" }); + const assignments = await calls(page, "tag_assign"); + await form.getByRole("button", { name: "Create profile", exact: true }).click(); + + const edit = dialog(page, `Edit ${name}`); + await expect(edit.getByRole("alert")).toBeVisible(); + await expect(edit.locator("[data-property='tags']")).toContainText(label); + await expect(edit.getByRole("textbox", { name: "Name" })).toHaveValue(name); + expect(await count(page)).toBe(before + 1); + const id = await page.evaluate((name) => + Object.values((window as unknown as Mock).__shardxMock.state.profiles) + .find((profile) => profile.name === name)?._meta.id, name); + expect(id).toBeTruthy(); + expect((await storedTags(page)).tags).toEqual([]); + expect(await calls(page, "tag_assign")).toBe(assignments); + const saves = await calls(page, "profile_save"); + + await edit.getByRole("button", { name: "Save", exact: true }).click(); + await expect(edit).toHaveCount(0); + expect(await count(page)).toBe(before + 1); + expect(await calls(page, "profile_save")).toBe(saves); + expect(await calls(page, "tag_assign")).toBe(assignments + 1); + const proposed = await page.evaluate(() => (window as unknown as { tagSaveIds: string[] }).tagSaveIds); + expect(proposed).toHaveLength(2); + expect(proposed[1]).toBe(proposed[0]); + const actual = await storedTags(page); + expect(actual.tags.map(({ id, name }) => ({ id, name }))).toEqual([{ id: confirmedTagId, name: label }]); + expect(actual.by_profile).toEqual({ [id!]: [confirmedTagId] }); +}); + test("a create whose Folder step fails keeps the profile once, and Save finishes it", async ({ page }) => { await openApp(page); await page.locator("aside [data-folder='Ads']").click(); diff --git a/src/entities/profile/lib/useProfile.tsx b/src/entities/profile/lib/useProfile.tsx index 0674909a5..dfb80faf8 100644 --- a/src/entities/profile/lib/useProfile.tsx +++ b/src/entities/profile/lib/useProfile.tsx @@ -249,9 +249,9 @@ export type ProfileStore = { /** Creates the profile the profile form describes (Create profile): the * backend creates it from the form, the form's values go over what the * backend rolls for a new profile, then it goes in its Folder, on its - * proxy and gets its tags (`newTags` are made now); its row is in the list - * on return. Once the backend has it, it is returned whatever fails after: - * a retry must never make it twice. Nothing is shown here; the form says it. */ + * proxy. Its row is in the list when the form finishes saving its tags. + * Once the backend creates the profile, this returns its id so a retry + * can finish the same profile. */ createProfile: (draft: { form: ProfileForm; folder: string; tagIds: string[]; newTags: string[] }) => Promise; /** Renames a profile; false when it failed (the error is already shown). */ @@ -1308,11 +1308,8 @@ export const useProfile = create((set, get) => ({ }); const filed = !!folder && (saved.folder === folder || await step("folder", () => profileSetFolder(saved.id, folder))); const bound = !!form.proxy_id && ((team && saved.proxy_id === form.proxy_id) || await step("proxy", () => profileBindProxy(saved.id, form.proxy_id))); - // Tags live in this app, not the backend: the new ones are made now that the profile is. - const tags = useTags.getState(); - const made = newTags.map((name) => tags.create(name)?.id).filter((id): id is string => !!id); - if (tagIds.length + made.length > 0) tags.setTags(saved.id, [...tagIds, ...made]); const meta = { ...saved, folder: filed ? folder : saved.folder, proxy_id: bound ? form.proxy_id : saved.proxy_id }; + if (asked !== spaceEpoch()) return { meta, failed }; // In the list at once, where the backend lists it; no reload (PERF-13). insertRows(set, get, [meta], newRowIndex(get)); markArrived(set, get, [meta.id]); diff --git a/src/entities/tag/lib/useTags.ts b/src/entities/tag/lib/useTags.ts index ee48465ee..0f615113d 100644 --- a/src/entities/tag/lib/useTags.ts +++ b/src/entities/tag/lib/useTags.ts @@ -2,7 +2,8 @@ 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, withEpoch } from "../../../shared/api/invoke"; +import { SPACE_REFUSALS } from "../../../shared/api/epochWrites"; import { toast } from "../../../shared/model/toast"; import { t } from "../../../shared/i18n"; import type { Tag } from "../model/types"; @@ -18,6 +19,10 @@ 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(); +// A save can commit without its answer reaching us. A retry uses the same ID. +const proposed = new Map(); +// Keep acknowledged names until the assignment lands, even through a stale tag list. +const confirmedNames = 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)])); @@ -48,6 +53,10 @@ function changedLists(before: Record, after: Record !before.includes(id)), remove: before.filter((id) => !after.includes(id)) }; +} + /** Trims, collapses internal whitespace and caps the length: the one * normaliser a tag name goes through (the TagPicker cleans its query the * same way before it compares, PC-085). */ @@ -82,6 +91,8 @@ export type TagStore = { untag: (profileId: string, tagId: 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; + /** Saves a form's selection, including new names, and reports a failure to the form. */ + saveSelection: (profileId: string, tagIds: readonly string[], newNames: readonly string[], openedTagIds?: readonly string[]) => Promise; /** 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. */ @@ -92,8 +103,9 @@ let loading: Promise | null = null; export const useTags = create((set, get) => { let queue: ReturnType | null = null; - const read = async () => { + const read = async (epoch?: number) => { const s = await tagList(); + if (epoch !== undefined && epoch !== spaceEpoch()) return; set(whole(s.tags, s.by_profile, COLOR_IDS)); // A change made while this read was out shows again after it is sent. queue?.shown(); @@ -107,10 +119,8 @@ 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) => { - queue ??= writeQueue(load(), (e) => toast.fail({ title: t("useTags.saveFailed"), detail: e }), read); - void queue(call); - }; + const writes = () => queue ??= writeQueue(load(), (e) => toast.fail({ title: t("useTags.saveFailed"), detail: e }), read); + const send = (call: () => Promise) => { void writes()(call); }; /** 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, opened?: Record) => { @@ -126,8 +136,7 @@ export const useTags = create((set, get) => { 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)); + const { add, remove } = tagDelta(base, next); if (add.length === 0 && remove.length === 0) continue; changes[pid] = { add, remove }; const kept = current.filter((id) => !remove.includes(id)); @@ -260,6 +269,71 @@ export const useTags = create((set, get) => { const opened = openedTagIds ? { [profileId]: openedTagIds.map(finalId) } : undefined; assign(byProfile, [profileId], opened); }, + saveSelection: (profileId, tagIds, newNames, openedTagIds) => { + const team = inTeam(); + const wanted = [...tagIds]; + const opened = [...(openedTagIds ?? get().byProfile[profileId] ?? [])]; + const names = [...newNames].map(clean).filter(Boolean); + return writes().confirmed(async (epoch) => { + const here = () => (epoch === undefined || epoch === spaceEpoch()) && inTeam() === team; + const check = () => { if (!here()) throw new Error(SPACE_REFUSALS.spaceChanged); }; + check(); + // The optimistic store may contain tags from another queued write. Only a + // backend read or an acknowledged create can supply IDs for this save. + const current = await tagList(); + check(); + const { refused, reason } = assignGuard([profileId]); + if (refused.length) throw new Error(reason ?? t("useTags.saveFailed")); + const tags = [...current.tags]; + const selected = new Set(wanted.map(finalId)); + for (const name of names) { + const key = name.toLocaleLowerCase(); + const remembered = confirmedNames.get(key); + const existing = tags.find((tag) => same(tag.name, name)) + ?? (remembered && !tags.some((tag) => tag.id === remembered.id) ? remembered : undefined); + if (existing) { + proposed.delete(key); + confirmedNames.set(key, existing); + selected.add(existing.id); + if (!tags.some((tag) => tag.id === existing.id)) tags.push(existing); + continue; + } + const why = teamRefusal("create"); + if (why) throw new Error(why); + const tag = proposed.get(key) ?? { id: newId(), name, color: nextTagColor(tags) }; + proposed.set(key, tag); + const saved = await withEpoch(epoch, () => tagSave(tag)); + check(); + if (!saved?.id) throw new Error(t("useTags.saveFailed")); + proposed.delete(key); + confirmedNames.set(key, saved); + selected.add(saved.id); + tags.push(saved); + // Keep the acknowledged tag even if another create or assignment fails. + set((state) => ({ tags: [...state.tags.filter((tag) => tag.id !== saved.id), saved] })); + } + + const known = new Set(tags.map((tag) => tag.id)); + const next = [...selected]; + const base = team ? opened.map(finalId) : current.by_profile[profileId] ?? []; + const { add, remove } = tagDelta(base, next); + if ((team ? add : next).some((id) => !known.has(id))) throw new Error(t("useTags.saveFailed")); + if (team) { + if (add.length || remove.length) await withEpoch(epoch, () => tagChange({ [profileId]: { add, remove } })); + } else if (next.length !== base.length || next.some((id, i) => id !== base[i])) { + await withEpoch(epoch, () => tagAssign({ [profileId]: next })); + } + if (!here()) return; + for (const name of names) confirmedNames.delete(name.toLocaleLowerCase()); + set((state) => { + const byProfile = { ...state.byProfile }; + const current = byProfile[profileId] ?? []; + const kept = team ? [...new Set([...current.filter((id) => !remove.includes(id)), ...add])] : next; + if (kept.length) byProfile[profileId] = kept; else delete byProfile[profileId]; + return { byProfile }; + }); + }); + }, forgetProfiles: (profileIds) => { const byProfile = { ...get().byProfile }; for (const pid of profileIds) delete byProfile[pid]; @@ -278,6 +352,8 @@ export const useTags = create((set, get) => { // Another space: none of the old tags show while its own are read. onSpaceMoved(() => { + proposed.clear(); + confirmedNames.clear(); if (!loading) return; useTags.setState({ tags: [], byProfile: {} }); void useTags.getState().reload(); diff --git a/src/features/profile-form/model/useProfileForm.ts b/src/features/profile-form/model/useProfileForm.ts index 80626922a..fc1d5e7d0 100644 --- a/src/features/profile-form/model/useProfileForm.ts +++ b/src/features/profile-form/model/useProfileForm.ts @@ -556,6 +556,9 @@ export async function saveProfileForm(): Promise { let name = draft.form.name.trim(); // A protected profile is read again with the password it was opened with. const reread = (id: string) => (s.unlocked !== null ? useProfile.getState().unlockForm(id, s.unlocked) : useProfile.getState().loadForm(id)); + const readSavedDraft = (id: string) => team + ? profileGetForEdit(id, epoch).then((stored) => draftOf(fromStored(stored), stored._meta?.folder)) + : reread(id).then((form) => draftOf(form)); // Closed: the password goes with the form. const close = () => { if (here()) closeProfileForm(); }; const failed = (error: string, title: string, detail?: unknown) => { @@ -564,15 +567,29 @@ export async function saveProfileForm(): Promise { return false; }; + const tagsFailed = async (id: string, baseline: ProfileFormDraft, error: unknown) => { + if (!here()) return false; + const latest = await readSavedDraft(id).catch(() => null); + if (!here()) return false; + // Keep the original tag baseline so retry still sends only the requested changes. + const saved = { ...(latest ?? { ...baseline, form: draft.form }), tagIds: baseline.tagIds }; + const folder = draft.folder === baseline.folder ? saved.folder : draft.folder; + set({ + mode: "edit", id, saved, draft: { ...draft, form: saved.form, folder }, + status: "error", error: t("profileForm.tagsSaveFailed"), errorDetail: explainError(error) ?? null, theirs: null, + }); + return false; + }; + // A partial create continues as an edit of the profile that already exists. const partlyCreated = async (id: string, line: string, why: unknown) => { const stored = await reread(id).catch(() => null); if (!here()) return false; if (!stored) { closeProfileForm(); return false; } - const opened = draftOf(stored); + const opened = { ...draftOf(stored), tagIds: [] }; set({ mode: "edit", id, saved: opened, - draft: { ...draft, form: { ...draft.form, name, id: stored.id, rev: stored.rev }, tagIds: opened.tagIds, newTags: [] }, + draft: { ...draft, form: { ...draft.form, name, id: stored.id, rev: stored.rev } }, status: "error", error: line, errorDetail: explainError(why) ?? null, theirs: null, }); return false; @@ -598,6 +615,7 @@ export async function saveProfileForm(): Promise { if (s.mode === "create") { const made = await useProfile.getState().createProfile({ ...draft, form: { ...draft.form, name } }); + if (!here()) return false; if (!made.meta) return failed(t("profileForm.createFailed"), t("useProfile.createFailed"), made.error); const meta = made.meta; if (made.failed) { @@ -609,6 +627,15 @@ export async function saveProfileForm(): Promise { toast.fail({ title: t("profileForm.createdPartly", { name: meta.name }), detail: made.failed.error, subject: meta.name }); return partlyCreated(meta.id, line, made.failed.error); } + if (draft.tagIds.length > 0 || draft.newTags.length > 0) { + try { + await useTags.getState().saveSelection(meta.id, draft.tagIds, draft.newTags, []); + } catch (error) { + draft = { ...draft, folder: meta.folder, form: { ...draft.form, name: meta.name, id: meta.id, proxy_id: meta.proxy_id } }; + return tagsFailed(meta.id, { ...draftOf(draft.form, meta.folder), tagIds: [] }, error); + } + if (!here()) return false; + } await importPickedCookies(meta.id, meta.name, draft.cookies); if (s.password) await protectNew(meta.id, meta.name, s.password); close(); @@ -643,12 +670,14 @@ export async function saveProfileForm(): Promise { } draft = { ...draft, form: { ...form, name, rev } }; - // 3 and 4. Its tags and its Folder, only what changed. + // Finish the tag write before moving the profile out of its current Folder. if (!sameTags(draft, opened)) { - // 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], opened.tagIds); + try { + await useTags.getState().saveSelection(id, draft.tagIds, draft.newTags, opened.tagIds); + } catch (error) { + return tagsFailed(id, opened, error); + } + if (!here()) return false; } if (draft.folder !== opened.folder) { const store = useProfile.getState(); @@ -657,10 +686,7 @@ export async function saveProfileForm(): Promise { // already; the form stays open with the Folder still to save. if (!(await store.moveMany([id], draft.folder, { quiet: true }))) { if (!here()) return false; - const read = team - ? profileGetForEdit(id, epoch).then((stored) => draftOf(fromStored(stored), stored._meta?.folder)) - : reread(id).then((form) => draftOf(form)); - const latest = await read.catch(() => null); + const latest = await readSavedDraft(id).catch(() => null); if (!here()) return false; if (latest?.folder !== draft.folder) { // The settings step already settled. Keep its version on both sides diff --git a/src/shared/i18n/locales/en.json b/src/shared/i18n/locales/en.json index 16f7796ff..b2ba637a8 100644 --- a/src/shared/i18n/locales/en.json +++ b/src/shared/i18n/locales/en.json @@ -1735,6 +1735,7 @@ "profileForm.close": "Close", "profileForm.conflict": "This profile was changed somewhere else. Reload it or save your version.", "profileForm.conflictReadFailed": "Couldn’t read the latest version. Your edits are still here.", + "profileForm.tagsSaveFailed": "Couldn’t save the tags. Save tries again.", "profileForm.teamConflict": "A teammate changed this profile. Reload to open the latest version, or save your edits.", "profileForm.create": "Create profile", "profileForm.created": "{name} created", diff --git a/src/shared/i18n/locales/ru.json b/src/shared/i18n/locales/ru.json index a82183ead..37f52a9a8 100644 --- a/src/shared/i18n/locales/ru.json +++ b/src/shared/i18n/locales/ru.json @@ -1735,6 +1735,7 @@ "profileForm.close": "Закрыть", "profileForm.conflict": "Этот профиль изменён в другом месте. Перезагрузите его или сохраните свою версию.", "profileForm.conflictReadFailed": "Не удалось прочитать последнюю версию. Ваши изменения сохранены в форме.", + "profileForm.tagsSaveFailed": "Не удалось сохранить теги. Нажмите «Сохранить», чтобы повторить.", "profileForm.teamConflict": "Другой участник команды изменил этот профиль. Загрузите последнюю версию или сохраните свои правки.", "profileForm.create": "Создать профиль", "profileForm.created": "Профиль «{name}» создан", diff --git a/src/shared/i18n/locales/zh.json b/src/shared/i18n/locales/zh.json index ddc514589..afcacb23b 100644 --- a/src/shared/i18n/locales/zh.json +++ b/src/shared/i18n/locales/zh.json @@ -1735,6 +1735,7 @@ "profileForm.close": "关闭", "profileForm.conflict": "此配置已在别处更改。请重新加载,或保存你的版本。", "profileForm.conflictReadFailed": "无法读取最新版本。你的更改仍然保留。", + "profileForm.tagsSaveFailed": "无法保存标签。点击“保存”可重试。", "profileForm.teamConflict": "队友已更改此配置。可以重新加载最新版本,或保存你编辑的字段。", "profileForm.create": "创建配置", "profileForm.created": "“{name}”已创建", diff --git a/src/shared/lib/writeQueue.test.ts b/src/shared/lib/writeQueue.test.ts index 3524fc2d5..a04ded343 100644 --- a/src/shared/lib/writeQueue.test.ts +++ b/src/shared/lib/writeQueue.test.ts @@ -73,3 +73,35 @@ test("a queued write carries the space it was made in, not the one in use when i // Outside a queued write, the space in use. assert.equal(epochForWrite(), 8); }); + +test("confirmed failures reach their caller and reconcile without a second report", async () => { + const { setSpaceEpoch } = await import("../api/edition.ts"); + setSpaceEpoch(9); + const seen: string[] = []; + const failure = new Error("save failed"); + const write = writeQueue( + Promise.resolve(), + (e) => seen.push(`reported ${e}`), + async (epoch) => { seen.push(`reread ${epoch}`); }, + ); + const result = write.confirmed(async () => { throw failure; }); + const next = write(async () => { seen.push("next write"); }); + await assert.rejects(result, (e) => e === failure); + await next; + assert.deepEqual(seen, ["next write", "reread 9"]); +}); + +test("a confirmed write uses its caller's pinned epoch and skips obsolete reconciliation", async () => { + const { epochForWrite, setSpaceEpoch, withEpoch } = await import("../api/edition.ts"); + setSpaceEpoch(11); + const sent: (number | undefined)[] = []; + let rereads = 0; + const write = writeQueue(Promise.resolve(), () => {}, async () => { rereads++; }); + await withEpoch(10, () => write.confirmed(async (epoch) => { + sent.push(epochForWrite()); + await Promise.resolve(); + sent.push(withEpoch(epoch, epochForWrite)); + })); + assert.deepEqual(sent, [10, 10]); + assert.equal(rereads, 0); +}); diff --git a/src/shared/lib/writeQueue.ts b/src/shared/lib/writeQueue.ts index 1284593ac..36d462e30 100644 --- a/src/shared/lib/writeQueue.ts +++ b/src/shared/lib/writeQueue.ts @@ -1,29 +1,48 @@ -import { spaceEpoch, withEpoch } from "../api/edition.ts"; +import { epochForWrite, spaceEpoch, withEpoch } from "../api/edition.ts"; + +type QueuedWrite = (epoch: number | undefined) => Promise; /// A store's backend writes, sent in order once `ready` (the first read) settled. /// A failed one is reported, and the store reads the backend again once the queue is /// empty; so it does after a read that came back while a change still waited here. /// Each carries the space it was made in, so one sent after a switch is refused there. -export function writeQueue(ready: Promise, report: (e: unknown) => void, reread: () => Promise) { +export function writeQueue(ready: Promise, report: (e: unknown) => void, reread: (epoch?: number) => Promise) { let tail: Promise = ready.then(() => {}, () => {}); let waiting = 0; let again = false; - /** Queues `call`; resolves once it has settled. */ - const write = (call: () => Promise): Promise => { + let confirmedRefresh: { epoch: number | undefined } | null = null; + const enqueue = (call: QueuedWrite, asked: number | undefined, reportFailure: boolean) => { waiting++; - const asked = spaceEpoch(); - tail = tail - .then(() => withEpoch(asked, call)) - .then(() => {}, (e) => { again = true; report(e); }) + let epoch = asked; + const operation = tail.then(() => { + epoch ??= spaceEpoch(); + return withEpoch(epoch, () => call(epoch)); + }); + tail = operation + .then(() => {}, (e) => { + if (reportFailure) { again = true; report(e); } + }) .then(async () => { + if (!reportFailure && epoch === spaceEpoch()) confirmedRefresh = { epoch }; waiting--; - if (waiting > 0 || !again) return; + if (waiting > 0) return; + const refresh = confirmedRefresh; + confirmedRefresh = null; + const unscoped = again; again = false; - await reread().catch(() => {}); + if (unscoped) await reread().catch(() => {}); + else if (refresh && refresh.epoch === spaceEpoch()) await reread(refresh.epoch).catch(() => {}); }); - return tail; + return { operation, settled: tail }; + }; + /** Queues `call`; the store reports a failure and this still resolves. */ + const write = (call: () => Promise): Promise => enqueue(call, spaceEpoch(), true).settled; + /** The caller handles a failure. Related calls can re-pin the captured epoch after awaiting. */ + const confirmed = (call: QueuedWrite): Promise => { + const { operation, settled } = enqueue(call, epochForWrite(), false); + return settled.then(async () => { await operation; }); }; /** The store just showed a read: the changes still waiting are not in it. */ const shown = () => { if (waiting > 0) again = true; }; - return Object.assign(write, { shown }); + return Object.assign(write, { confirmed, shown }); }