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] 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": "已更改",