Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions e2e/profile-form.spec.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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: {
Expand All @@ -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);
Expand All @@ -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<Pick<Stored, "name" | "notes" | "extra_setting">>) {
return page.evaluate(async ({ id, changes }) => {
const w = window as unknown as Mock & {
__TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record<string, unknown>, options?: unknown) => Promise<unknown> };
};
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 }) => {
Expand Down Expand Up @@ -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);
Expand Down
36 changes: 36 additions & 0 deletions src-tauri/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)];
Expand Down
12 changes: 12 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ async fn profile_get(id: String) -> Result<Value, String> {
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<Value, String> {
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<String, Value>) -> Option<String> {
let renderer = config.get("webgl")?.get("renderer")?.as_str()?;
Expand Down Expand Up @@ -2794,6 +2805,7 @@ pub fn run() {
helper_dismiss,
profile_list,
profile_get,
profile_get_for_edit,
profile_protect,
profile_unprotect,
profile_change_password,
Expand Down
4 changes: 4 additions & 0 deletions src-tauri/src/live_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")));
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/space/doors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 7 additions & 1 deletion src-tauri/src/space/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<StoredProfile> {
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<StoredProfile> {
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() {
Expand Down
14 changes: 12 additions & 2 deletions src-tauri/src/space/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,19 @@ async fn fresh(c: &TeamClient, id: &str) -> Result<ProfileWithData, CmdError> {
}

/// A team profile's settings to change, as the server has them now.
pub async fn read_for_edit(team: &str, id: &str) -> Result<StoredProfile, CmdError> {
pub async fn read_for_edit(team: &str, id: &str, ticket: Option<&Ticket>) -> Result<StoredProfile, CmdError> {
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)))
}

Expand Down
5 changes: 5 additions & 0 deletions src/dev/mock/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,11 @@ export const handlers: Record<string, Handler> = {
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)";
Expand Down
7 changes: 5 additions & 2 deletions src/dev/mock/spaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, unknown>): 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;
Expand Down
11 changes: 9 additions & 2 deletions src/dev/mock/teamRights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -171,6 +173,11 @@ export function teamDoor(state: MockState, cmd: string, args: Record<string, unk
switch (cmd) {
case "profile_get":
return typeof profile(args.id) === "string" ? (profile(args.id) as string) : null;
case "profile_get_for_edit": {
const p = profile(args.id);
if (typeof p === "string") return p;
return teamUnreachable(state) ?? (readsSettings(rightsOf(state, p)) ? null : forbidden("edit", "profile"));
}
case "profile_save": {
const incoming = args.payload as StoredProfile | undefined;
const id = incoming?._meta?.id;
Expand Down
18 changes: 13 additions & 5 deletions src/entities/profile/lib/useProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { fingerprintList, type FingerprintEntry } from "../../fingerprint";
import { trashRestore } from "../../trash/model/api";
import type { ProfileMeta, ProfileForm } from "../model/types";
import {
profileList, profileGet, profileSave, profileDelete, profileClone,
profileList, profileGet, profileGetForEdit, profileSave, profileDelete, profileClone,
profileSetPin, profileSetFolder, profileBindProxy, profileImport,
processList, processKill, launch, launchCancel, syncLaunch, profileUnlock,
folderAdd, folderDelete, folderRename, cookiesExportToFile, cookiesImport, enrichPicksForPreset,
Expand Down Expand Up @@ -245,7 +245,7 @@ export type ProfileStore = {
* profile changed on disk since the form's rev, "failed" for any other
* error, which `opts.onFailed` gets. Nothing is shown here. A protected
* profile is saved with the `password` its editor was opened with. */
saveProfile: (draft: ProfileForm, opts?: { onFailed?: (error: unknown) => void; password?: string }) => Promise<SaveResult>;
saveProfile: (draft: ProfileForm, opts?: { onFailed?: (error: unknown) => void; password?: string; backing?: unknown }) => Promise<SaveResult>;
/** 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
Expand Down Expand Up @@ -804,6 +804,8 @@ export const useProfile = create<ProfileStore>((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;
Expand All @@ -819,16 +821,22 @@ export const useProfile = create<ProfileStore>((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
Expand Down
2 changes: 2 additions & 0 deletions src/entities/profile/model/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type { ProfileMeta } from "./types";

export const profileList = () => invoke<ProfileMeta[]>("profile_list");
export const profileGet = (id: string) => invoke<any>("profile_get", { id });
/** Reads the current team record in the workspace where the edit began. */
export const profileGetForEdit = (id: string, epoch: number | undefined) => invoke<any>("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<ProfileMeta>("profile_save", password === undefined ? { payload } : { payload, password });
Expand Down
Loading