diff --git a/Cargo.lock b/Cargo.lock index d93a2a11..4709c95e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,6 +90,7 @@ dependencies = [ "azeroth-ingest", "azeroth-local-data", "azeroth-storage", + "schemars 1.2.2", "serde", "serde_json", "sha2", diff --git a/TODO.md b/TODO.md index e6fe1729..d0995ebb 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,34 @@ -# 1.0.0 program tracker +# 1.1.0 program tracker + +Governing decision: [ADR 0011](docs/decisions/0011-v110-guided-progression.md). +Owner: Codex `/root`; baseline `aaa73b94`; isolated branch `feat/v1.1-guided-progression`. +This program supersedes unpublished 1.0.0 preparation. Historical completed rows +below do not establish 1.1.0 readiness. + +- [x] V110.1 Record contract, unsigned exception and automated acceptance policy. +- [ ] V110.2 Verify installed tuple/interface and exact-build compatibility. +- [ ] V110.3 Regenerate/review content; version gameplay facts and enforce coverage. +- [ ] V110.4 Progression exchange, explicit addon/manual capture and persistence. + V110.4a collection/binding and V110.4b versioned exchange implemented and checked; + V110.4c companion persistence implemented and checked; + V110.4d application/native commands implemented and checked; + V110.4e Imports companion/manual money and point inputs implemented and checked; + catalog-backed manual editors, addon capture and saved workflow plans pending. +- [ ] V110.5 Trainer spell service, saved plans and rendered workflow. +- [ ] V110.6 Authored editable talents, validation and next-point workflow. +- [ ] V110.7 Profession/crafting quantities, materials and acquisition workflow. +- [ ] V110.8 Equipment enhancement advice and integrations. +- [ ] V110.9 Version-aware release tooling and four-feature acceptance journeys. + Website metadata validator (V110.9a) and reviewed evidence import (V110.9b) + support explicit 1.1.0; machine-readable unsigned exception added (V110.9c). + Inventory/Windows workloads and other tooling pending. +- [ ] V110.10 Full checks/reviews, version freeze, inventory and fresh signed closure. +- [ ] V110.11 Protected-main integration, stability, tag and eight-case packaging. +- [ ] V110.12 Independent downloaded-draft UI acceptance, publication and receipt. + +## Superseded 1.0.0 tracker + +### 1.0.0 program tracker Governing decision: [ADR 0006](docs/decisions/0006-v1-program.md) (2026-10-17). Target: the first stable live WoW Forever build after the 4 Nov 2026 launch diff --git a/apps/desktop/e2e/progression-inputs.spec.ts b/apps/desktop/e2e/progression-inputs.spec.ts new file mode 100644 index 00000000..314e4d76 --- /dev/null +++ b/apps/desktop/e2e/progression-inputs.spec.ts @@ -0,0 +1,66 @@ +import { expect, test } from "@playwright/test"; +import { fail, installMock } from "./support/mockInvoke"; +import type { CharacterSnapshotEnvelope } from "../../../schemas/v1/exchange"; +import type { ManualProgressionRequest, ProgressionRecord, ProgressionView } from "../../../schemas/v1/progression-api"; +import snapshot from "../../../fixtures/contracts/v1/character-snapshot.json" with { type: "json" }; +import companion from "../../../fixtures/contracts/v1/progression-snapshot.json" with { type: "json" }; + +// Browser journey across the real React/typed command boundary; mock storage only. +test("companion import and manual input preserve origins and survive UI reload", async ({ page }) => { + const profile = "synthetic-profile"; + const freshness = { status: "uncertain", reason: "missing_or_untrusted_time" } as const; + const imported: ProgressionRecord[] = []; const manual: ProgressionRecord[] = []; + const binding = companion.payload.binding as ProgressionView["binding"]; + let saved: ManualProgressionRequest | null = null; + const { calls } = await installMock(page, { + get_app_status: () => ({ version: "synthetic-test", data_mode: "stored", active_profile: profile, capabilities: {} }), + list_profiles: () => [{ id: profile, display_name: "Synthetic character", context: binding.context, fixture: true, data_mode: "stored", snapshot_count: 1 }], + get_stored_snapshot: () => ({ envelope: snapshot as CharacterSnapshotEnvelope, profile_id: profile, freshness, data_mode: "stored" }), + get_snapshot_history: () => [], + get_snapshot_watch: () => ({ active: false, status: null, last_import: null, error: null }), + get_progression_view: () => ({ profile_id: profile, fixture: true, binding, imported, manual }), + import_progression_text: ({ text }) => { + const request = JSON.parse(text) as { text: string; expected: unknown }; + if (request.text !== "ANAV1:synthetic-companion") throw fail("INVALID_INPUT", "Invalid progression export"); + expect(request.expected).toEqual(binding); + imported.push({ snapshot: companion.payload as ProgressionRecord["snapshot"], freshness }); + return { profile_id: profile, snapshot_id: binding.snapshot, companion_id: companion.payload.id, stored: true, fixture: true }; + }, + save_manual_progression: ({ text }) => { + saved = JSON.parse(text) as ManualProgressionRequest; + expect(saved.expected).toEqual(binding); + manual.push({ snapshot: { ...companion.payload as ProgressionRecord["snapshot"], id: saved.id, money: saved.money, available_talent_points: saved.available_talent_points, + recipes: { status: "unknown" }, bags: { status: "unknown" }, bank: { status: "unknown" } }, freshness }); + return { profile_id: profile, snapshot_id: binding.snapshot, companion_id: saved.id, stored: true, fixture: true }; + }, + }); + await page.goto("/"); + await page.getByRole("button", { name: "Imports", exact: true }).click(); + const panel = page.getByRole("region", { name: "Progression inputs", exact: true }); + await expect(panel.getByRole("button", { name: "Open progression inputs" })).toBeEnabled(); + expect(calls.filter((v) => v === "get_progression_view")).toEqual([]); + await panel.getByRole("button", { name: "Open progression inputs" }).click(); + await expect(panel.getByText(/No imported progression observations/)).toBeVisible(); + await panel.getByLabel("Progression export text", { exact: true }).fill("invalid-companion"); + await panel.getByRole("button", { name: "Import progression companion", exact: true }).click(); + await expect(panel.getByRole("alert")).toContainText("Invalid progression export"); + await panel.getByLabel("Progression export text", { exact: true }).fill("ANAV1:synthetic-companion"); + await panel.getByRole("button", { name: "Import progression companion", exact: true }).click(); + await expect(panel.getByRole("alert")).toHaveCount(0); + await panel.getByText(/Imported capture/).click(); + await expect(panel.getByText("0 recorded entries; complete enumeration")).toBeVisible(); + await expect(panel.getByText(/partial enumeration, other entries unknown/)).toBeVisible(); + await panel.getByLabel("Money (copper)", { exact: true }).fill("0"); + await panel.getByRole("button", { name: "Save manual entry" }).click(); + await expect(panel.getByText(/Saved progression capture: manual-/)).toBeVisible(); + expect(saved).toMatchObject({ money: { status: "known", value: "0" }, available_talent_points: { status: "unknown" }, recipes: { status: "unknown" } }); + await page.reload(); + await page.getByRole("button", { name: "Imports", exact: true }).click(); + await panel.getByRole("button", { name: "Open progression inputs" }).click(); + const records = panel.getByRole("region", { name: "Manual progression observations" }); + await records.getByText(/Manual capture/).click(); + await expect(records.getByText("0 copper")).toBeVisible(); + await expect(records.getByText("Source: Synthetic fixture.")).toBeVisible(); + await expect(records.getByText("Unknown (not observed)").first()).toBeVisible(); + await expect(panel.getByText(/Imported capture/)).toBeVisible(); +}); diff --git a/apps/desktop/src-tauri/src/command_tests.rs b/apps/desktop/src-tauri/src/command_tests.rs index c0d1f4e9..d3abd5c2 100644 --- a/apps/desktop/src-tauri/src/command_tests.rs +++ b/apps/desktop/src-tauri/src/command_tests.rs @@ -27,6 +27,9 @@ fn command_handler() -> fn(tauri::ipc::Invoke) -> bool get_calibration, get_joint_planning_catalog, project_positions, + get_progression_view, + import_progression_text, + save_manual_progression, reminder_view, review_selected_local_guide, set_session_calibration, diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index ee0ca9d1..2411c264 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -659,6 +659,37 @@ async fn get_calibration( ) -> Result { blocking(state, move |app| app.get_calibration(&profile_id, &request)).await } +#[tauri::command(rename_all = "snake_case")] +async fn get_progression_view( + state: State<'_, Application>, + profile_id: String, +) -> Result { + blocking(state, move |app| { + app.progression_view(&profile_id, system_now()) + }) + .await +} +#[tauri::command] +async fn import_progression_text( + state: State<'_, Application>, + text: String, +) -> Result { + blocking(state, move |app| { + app.import_progression_text(&text, system_now()) + }) + .await +} +#[tauri::command] +async fn save_manual_progression( + state: State<'_, Application>, + text: String, +) -> Result { + blocking(state, move |app| { + app.save_manual_progression(&text, system_now()) + }) + .await +} + #[tauri::command(rename_all = "snake_case")] async fn reminder_view( state: State<'_, Application>, @@ -1293,6 +1324,9 @@ pub fn run() -> i32 { plan_joint_session, set_session_calibration, get_calibration, + get_progression_view, + import_progression_text, + save_manual_progression, reminder_view, mutate_reminders, inspect_plan_route, diff --git a/apps/desktop/src/commands/client.ts b/apps/desktop/src/commands/client.ts index 7299f198..ae8ed7a4 100644 --- a/apps/desktop/src/commands/client.ts +++ b/apps/desktop/src/commands/client.ts @@ -48,6 +48,9 @@ async function run(call: () => Promise): Promise> { /** Typed command wrappers: the only way UI code reaches the backend. */ export function createClient(adapter: CommandAdapter) { return { + getProgressionView: (profileId: string) => run(() => adapter.invoke("get_progression_view", { profile_id: profileId })), + importProgression: (request: import("../../../../schemas/v1/progression-api").ImportProgressionRequest) => run(() => adapter.invoke("import_progression_text", { text: JSON.stringify(request) })), + saveManualProgression: (request: import("../../../../schemas/v1/progression-api").ManualProgressionRequest) => run(() => adapter.invoke("save_manual_progression", { text: JSON.stringify(request) })), prepareResearchDelivery:(catalog:string,locale:string,bindings?:import("./localData").LocalDeliveryChoices)=>run(()=>adapter.invoke("prepare_research_delivery",{catalog,locale,...(bindings===undefined?{}:{bindings})})), getResearchDeliveryPage:(revision:string,domain:string,offset:number)=>run(()=>adapter.invoke("get_research_delivery_page",{revision,domain,offset,limit:200})), getResearchDeliveryActivation:(revision:string)=>run(()=>adapter.invoke("get_research_delivery_activation",{revision})), diff --git a/apps/desktop/src/commands/contract.ts b/apps/desktop/src/commands/contract.ts index dd40b5d3..cc42be98 100644 --- a/apps/desktop/src/commands/contract.ts +++ b/apps/desktop/src/commands/contract.ts @@ -275,6 +275,9 @@ export interface PlanningReport { /** Every command the UI may call. Each maps to one narrowly scoped Rust command. */ export interface CommandMap { + get_progression_view: { input: { profile_id: string }; output: import("../../../../schemas/v1/progression-api").ProgressionView }; + import_progression_text: { input: { text: string }; output: import("../../../../schemas/v1/progression-api").ProgressionReceipt }; + save_manual_progression: { input: { text: string }; output: import("../../../../schemas/v1/progression-api").ProgressionReceipt }; prepare_research_delivery:{input:{catalog:string;locale:string;bindings?:import("./localData").LocalDeliveryChoices};output:string}; get_research_delivery_page:{input:{revision:string;domain:string;offset:number;limit:number};output:import("./localData").ResearchDeliveryPage}; get_research_delivery_activation:{input:{revision:string};output:import("./localData").ResearchDeliveryActivation}; diff --git a/apps/desktop/src/commands/demoAdapter.ts b/apps/desktop/src/commands/demoAdapter.ts index f0a1efb8..23c09317 100644 --- a/apps/desktop/src/commands/demoAdapter.ts +++ b/apps/desktop/src/commands/demoAdapter.ts @@ -186,6 +186,9 @@ export const demoAdapter: CommandAdapter = { case "accept_party_plan": case "set_session_calibration": case "get_calibration": + case "get_progression_view": + case "import_progression_text": + case "save_manual_progression": case "reminder_view": case "mutate_reminders": case "get_gear_catalog": diff --git a/apps/desktop/src/commands/progression.test.ts b/apps/desktop/src/commands/progression.test.ts new file mode 100644 index 00000000..b9a3e520 --- /dev/null +++ b/apps/desktop/src/commands/progression.test.ts @@ -0,0 +1,35 @@ +import { createClient } from "./client"; +import { demoAdapter } from "./demoAdapter"; +import type { CommandAdapter } from "./contract"; +import type { ManualProgressionRequest } from "../../../../schemas/v1/progression-api"; +import fixture from "../../../../fixtures/contracts/v1/progression-snapshot.json"; + +const request: ManualProgressionRequest = { + profile_id: "selected-profile", + expected: fixture.payload.binding as ManualProgressionRequest["expected"], + id: "manual-one", + spells: {status:"unknown"}, money: {status:"known", value:"0"}, + talents: {status:"unknown"}, available_talent_points:{status:"known",value:0}, + professions: {status:"unknown"}, recipes:{status:"known",value:{completeness:"partial",entries:{recipe:false}}}, + bags:{status:"unknown"}, bank:{status:"unknown"}, equipment_enhancements:{}, +}; +it("transports expected binding and manual false/zero without inventing provenance", async () => { + const calls: {command:string;input:unknown}[] = []; + const adapter:CommandAdapter = {invoke(command,input) {calls.push({command,input}); return Promise.reject({code:"SNAPSHOT_OUTDATED",message:"Reload inputs",retryable:false});}}; + const client=createClient(adapter); + expect(await client.getProgressionView("selected-profile")).toEqual({ok:false,error:{code:"SNAPSHOT_OUTDATED",message:"Reload inputs",retryable:false}}); + await client.saveManualProgression(request); + const imported={profile_id:request.profile_id,expected:request.expected,text:"ANAV1:explicit-copied-input"}; + await client.importProgression(imported); + expect(calls).toEqual([ + {command:"get_progression_view",input:{profile_id:"selected-profile"}}, + {command:"save_manual_progression",input:{text:JSON.stringify(request)}}, + {command:"import_progression_text",input:{text:JSON.stringify(imported)}}, + ]); +}); +it("browser demo explicitly refuses persistent progression actions", async () => { + const client=createClient(demoAdapter); + for (const result of [await client.getProgressionView("demo"),await client.saveManualProgression(request),await client.importProgression({profile_id:request.profile_id,expected:request.expected,text:"ANAV1:input"})]) { + expect(result.ok).toBe(false); + } +}); diff --git a/apps/desktop/src/screens/ImportScreen.tsx b/apps/desktop/src/screens/ImportScreen.tsx index 929148ee..e53cca20 100644 --- a/apps/desktop/src/screens/ImportScreen.tsx +++ b/apps/desktop/src/screens/ImportScreen.tsx @@ -5,6 +5,7 @@ import type { FileInputFormat, HistoryEntry, ImportReceipt, StoredSnapshot, Watc import { describeAge } from "../atlas/describe"; import { describeObservation } from "../observation"; import { Button, Field, Panel } from "../ui"; +import { ProgressionInputs } from "./progression/ProgressionInputs"; const WATCH_LABELS: Record = { waiting_for_stable_file: "Waiting for a complete, stable save.", imported: "The saved snapshot was imported.", @@ -192,5 +193,5 @@ export function ImportScreen({ client, onChanged }: { client: CommandClient; onC } {history.length === 0 ?

No stored snapshot history.

:
    {history.map((entry) =>
  • {entry.snapshot_id}{entry.is_current ? " (current)" : " (history only)"}: {describeAge(entry.freshness)} {!entry.is_current && }
  • )}
} - ; + {current !== null && current.profile_id === selected && }; } diff --git a/apps/desktop/src/screens/progression/ProgressionInputs.test.tsx b/apps/desktop/src/screens/progression/ProgressionInputs.test.tsx new file mode 100644 index 00000000..2644f7aa --- /dev/null +++ b/apps/desktop/src/screens/progression/ProgressionInputs.test.tsx @@ -0,0 +1,171 @@ +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { vi } from "vitest"; +import { createClient, type CommandAdapter } from "../../commands"; +import type { CommandMap, CommandName } from "../../commands/contract"; +import type { ManualProgressionRequest, ProgressionReceipt, ProgressionView } from "../../../../../schemas/v1/progression-api"; +import fixture from "../../../../../fixtures/contracts/v1/progression-snapshot.json"; +import { ProgressionInputs } from "./ProgressionInputs"; +import { ProgressionRecords } from "./ProgressionRecords"; +import { inputError, manualRequest } from "./inputs"; + +const view: ProgressionView = { profile_id: "profile-one", fixture: true, binding: fixture.payload.binding, imported: [], manual: [] } as ProgressionView; +const receipt: ProgressionReceipt = { profile_id: view.profile_id, snapshot_id: view.binding.snapshot, companion_id: "saved-companion", stored: true, fixture: true }; +const unavailable = { code: "PROVIDER_UNAVAILABLE", message: "Storage unavailable", retryable: true }; +function deferred() { let resolve!: (value: T) => void; let reject!: (reason: unknown) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } +function harness() { + const calls: { command: CommandName; input: unknown }[] = []; + const get = vi.fn<() => Promise>().mockResolvedValue(view); + const save = vi.fn<() => Promise>().mockResolvedValue(receipt); + const adapter: CommandAdapter = { invoke(command: C, input: CommandMap[C]["input"]): Promise { + calls.push({ command, input }); + return (command === "get_progression_view" ? get() : save()) as Promise; + } }; + return { client: createClient(adapter), calls, get, save }; +} +async function open() { + fireEvent.click(screen.getByRole("button", { name: "Open progression inputs" })); + await waitFor(() => expect(screen.queryByText("Loading progression observations…")).not.toBeInTheDocument()); +} +function props(h: ReturnType) { return { client: h.client, profileId: view.profile_id, snapshotId: view.binding.snapshot, disabled: false }; } + +it("loads only on explicit open and saves zero with exact binding and other observations unknown", async () => { + const h = harness(); render(); + expect(h.calls).toEqual([]); await open(); + expect(screen.getByText(/No imported progression/)).toBeInTheDocument(); + expect(screen.getByText(/No manual progression/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Save manual entry" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Money (copper)"), { target: { value: "0" } }); + fireEvent.change(screen.getByLabelText("Available talent points"), { target: { value: "0" } }); + fireEvent.click(screen.getByRole("button", { name: "Save manual entry" })); + expect(await screen.findByText(/Saved progression capture: saved-companion \(synthetic fixture\)/)).toBeInTheDocument(); + const call = h.calls.find((v) => v.command === "save_manual_progression"); + if (call === undefined) throw new Error("Manual save was not invoked"); + const request = JSON.parse((call.input as { text: string }).text) as ManualProgressionRequest; + expect(request).toMatchObject({ profile_id: view.profile_id, expected: view.binding, id: expect.stringMatching(/^manual-/), money: { status: "known", value: "0" }, available_talent_points: { status: "known", value: 0 }, spells: { status: "unknown" }, talents: { status: "unknown" }, professions: { status: "unknown" }, recipes: { status: "unknown" }, bags: { status: "unknown" }, bank: { status: "unknown" }, equipment_enhancements: {} }); + expect(screen.getByLabelText("Money (copper)")).toHaveValue(""); + expect(screen.getByLabelText("Available talent points")).toHaveValue(""); + expect(h.get).toHaveBeenCalledTimes(2); +}); + +it("rejects invalid numbers without rounding currency and preserves unknown separately from zero", () => { + for (const value of ["-1", "1.1", "1e3", "01", " ", "18446744073709551616", "999999999999999999999"]) expect(inputError(value, "")).toMatch(/Money must/); + for (const value of ["-1", "1.1", "1e3", "01", "65536", "100000"]) expect(inputError("", value)).toMatch(/talent points must/); + expect(inputError("18446744073709551615", "65535")).toBeNull(); + expect(manualRequest(view, "18446744073709551615", "").money).toEqual({ status: "known", value: "18446744073709551615" }); + expect(manualRequest(view, "", "0").money).toEqual({ status: "unknown" }); + expect(manualRequest(view, "0", "").available_talent_points).toEqual({ status: "unknown" }); + expect(manualRequest(view, "0", "").id).not.toEqual(manualRequest(view, "0", "").id); +}); + +it("imports a companion explicitly and explains duplicate receipts", async () => { + const h = harness(); h.save.mockResolvedValue({ ...receipt, stored: false, fixture: false }); + render(); await open(); + fireEvent.change(screen.getByLabelText("Progression export text"), { target: { value: "ANAV1:companion" } }); + fireEvent.click(screen.getByRole("button", { name: "Import progression companion" })); + expect(await screen.findByText(/Progression capture was already stored: saved-companion/)).toBeInTheDocument(); + expect(h.calls).toContainEqual({ command: "import_progression_text", input: { text: JSON.stringify({ profile_id: view.profile_id, expected: view.binding, text: "ANAV1:companion" }) } }); + expect(screen.getByLabelText("Progression export text")).toHaveValue(""); +}); + +it("shows capture origins, stale/uncertain age, empty/partial collections and unavailable fields", () => { + const base = fixture.payload as ProgressionView["imported"][number]["snapshot"]; + const { rerender } = render(); + expect(screen.getByText(/Imported capture.*stale/)).toBeInTheDocument(); + fireEvent.click(screen.getByText(/Imported capture/)); + expect(screen.getByText("Source: Synthetic fixture.")).toBeInTheDocument(); + expect(screen.getByText("0 copper")).toBeInTheDocument(); + expect(screen.getByText("0 recorded entries; complete enumeration")).toBeInTheDocument(); + expect(screen.getByText("1 recorded entries; partial enumeration, other entries unknown")).toBeInTheDocument(); + expect(screen.getByText("Unsupported by this client")).toBeInTheDocument(); + const manual = { ...base, capture: { ...base.capture, source: "manual_entry" as const }, money: { status: "restricted" as const }, recipes: { status: "not_applicable" as const }, bank: { status: "known" as const, value: { completeness: "partial" as const, entries: {} } } }; + rerender(); + expect(screen.getByText(/Manual capture.*age uncertain/)).toBeInTheDocument(); + expect(screen.getByText("Source: Manual entry.")).toBeInTheDocument(); + expect(screen.getByText("Restricted (hidden by the game)")).toBeInTheDocument(); + expect(screen.getByText("Not applicable")).toBeInTheDocument(); + expect(screen.getByText("0 recorded entries; partial enumeration, other entries unknown")).toBeInTheDocument(); + rerender(); + expect(screen.getByText("Source: Addon observation.")).toBeInTheDocument(); +}); + +it.each(["profile", "snapshot"])("refuses a loaded view for a different %s", async (mismatch) => { + const h = harness(); h.get.mockResolvedValue(mismatch === "profile" ? { ...view, profile_id: "other" } : { ...view, binding: { ...view.binding, snapshot: "other" } }); + render(); await open(); + expect(screen.getByRole("alert")).toHaveTextContent("SNAPSHOT_OUTDATED"); + expect(screen.getByLabelText("Money (copper)")).toBeDisabled(); + expect(screen.queryByRole("region", { name: "Manual progression observations" })).not.toBeInTheDocument(); +}); + +it("recovers read failures and preserves manual inputs through save failures", async () => { + const h = harness(); h.get.mockRejectedValueOnce(unavailable); + h.save.mockRejectedValueOnce({ code: "INVALID_INPUT", message: "Capture rejected", retryable: false }); + render(); await open(); + expect(screen.getByRole("alert")).toHaveTextContent("PROVIDER_UNAVAILABLE"); + fireEvent.click(screen.getByRole("button", { name: "Refresh progression observations" })); + await waitFor(() => expect(screen.getByLabelText("Money (copper)")).toBeEnabled()); + fireEvent.change(screen.getByLabelText("Money (copper)"), { target: { value: "-1" } }); + expect(screen.getByRole("button", { name: "Save manual entry" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Money (copper)"), { target: { value: "250" } }); + fireEvent.click(screen.getByRole("button", { name: "Save manual entry" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Capture rejected"); + expect(screen.getByLabelText("Money (copper)")).toHaveValue("250"); + fireEvent.click(screen.getByRole("button", { name: "Save manual entry" })); + expect(await screen.findByText(/Saved progression capture/)).toBeInTheDocument(); +}); + +it.each(["stale", "wrong receipt"])("invalidates the binding on %s during a write", async (kind) => { + const h = harness(); + if (kind === "stale") h.save.mockRejectedValue({ code: "SNAPSHOT_OUTDATED", message: "Changed snapshot", retryable: false }); + else h.save.mockResolvedValue({ ...receipt, snapshot_id: "different" }); + render(); await open(); + fireEvent.change(screen.getByLabelText("Available talent points"), { target: { value: "1" } }); + fireEvent.click(screen.getByRole("button", { name: "Save manual entry" })); + expect(await screen.findByRole("alert")).toHaveTextContent("SNAPSHOT_OUTDATED"); + expect(screen.getByLabelText("Available talent points")).toBeDisabled(); +}); + +it.each(["client", "profile", "snapshot"])("resets entered data and ignores delayed reads when %s changes", async (kind) => { + const h = harness(); const late = deferred(); h.get.mockReturnValueOnce(late.promise); + const original = props(h); const { rerender } = render(); + fireEvent.click(screen.getByRole("button", { name: "Open progression inputs" })); + const next = kind === "client" ? { ...original, client: harness().client } : kind === "profile" ? { ...original, profileId: "other" } : { ...original, snapshotId: "other" }; + rerender(); + await act(async () => { late.resolve(view); }); + expect(screen.getByRole("button", { name: "Open progression inputs" })).toBeInTheDocument(); + expect(screen.queryByLabelText("Money (copper)")).not.toBeInTheDocument(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); +}); + +it("ignores delayed write failures after closing and resets drafts when reopening", async () => { + const h = harness(); const late = deferred(); h.save.mockReturnValueOnce(late.promise); + render(); await open(); + fireEvent.change(screen.getByLabelText("Money (copper)"), { target: { value: "10" } }); + fireEvent.click(screen.getByRole("button", { name: "Save manual entry" })); + expect(screen.getByLabelText("Money (copper)")).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Close progression inputs" })); + await act(async () => { late.reject(unavailable); }); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + await open(); expect(screen.getByLabelText("Money (copper)")).toHaveValue(""); +}); + +it("disables mutations during parent changes and refreshes ages without replacing drafts", async () => { + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); + try { + const h = harness(); const original = props(h); const { rerender, unmount } = render(); await open(); + fireEvent.change(screen.getByLabelText("Money (copper)"), { target: { value: "10" } }); + rerender(); + expect(screen.getByLabelText("Money (copper)")).toBeDisabled(); + rerender(); + h.get.mockResolvedValue({ ...view, manual: [{ snapshot: fixture.payload as ProgressionView["manual"][number]["snapshot"], freshness: { status: "stale", age_ms: 3600000 } }] }); + await act(async () => { await vi.advanceTimersByTimeAsync(60000); }); + expect(screen.getByLabelText("Money (copper)")).toHaveValue("10"); + expect(within(screen.getByRole("region", { name: "Manual progression observations" })).getByText(/stale/)).toBeInTheDocument(); + const pending = deferred(); h.save.mockReturnValueOnce(pending.promise); + fireEvent.click(screen.getByRole("button", { name: "Save manual entry" })); + const reads = h.get.mock.calls.length; + await act(async () => { await vi.advanceTimersByTimeAsync(60000); }); + expect(h.get).toHaveBeenCalledTimes(reads); + unmount(); await act(async () => { pending.resolve(receipt); }); + await vi.advanceTimersByTimeAsync(60000); expect(h.get).toHaveBeenCalledTimes(reads); + } finally { vi.useRealTimers(); } +}); diff --git a/apps/desktop/src/screens/progression/ProgressionInputs.tsx b/apps/desktop/src/screens/progression/ProgressionInputs.tsx new file mode 100644 index 00000000..7f7f20c4 --- /dev/null +++ b/apps/desktop/src/screens/progression/ProgressionInputs.tsx @@ -0,0 +1,101 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import type { AppError, CommandClient } from "../../commands"; +import type { ProgressionReceipt, ProgressionView } from "../../../../../schemas/v1/progression-api"; +import { Button, Field, Panel } from "../../ui"; +import { inputError, manualRequest } from "./inputs"; +import { ProgressionRecords } from "./ProgressionRecords"; + +interface Props { client: CommandClient; profileId: string; snapshotId: string; disabled: boolean } +const OUTDATED: AppError = { code: "SNAPSHOT_OUTDATED", message: "The selected snapshot changed. Refresh stored state before opening progression inputs again.", retryable: false }; + +/** Remount all input and request state when its owning client or predecessor changes. */ +export function ProgressionInputs(props: Props) { + const owner = useRef({ client: props.client, profileId: props.profileId, snapshotId: props.snapshotId, key: 0 }); + if (owner.current.client !== props.client || owner.current.profileId !== props.profileId || owner.current.snapshotId !== props.snapshotId) { + owner.current = { client: props.client, profileId: props.profileId, snapshotId: props.snapshotId, key: owner.current.key + 1 }; + } + return ; +} + +function InputToggle(props: Props) { + const [open, setOpen] = useState(false); + return +

Record information for the selected character snapshot. Manual entries describe what you entered; saving does not change the game.

+ {open ? <> + + + : } +
; +} + +function InputEditor({ client, profileId, snapshotId, disabled }: Props) { + const [view, setView] = useState(null); + const [error, setError] = useState(null); + const [receipt, setReceipt] = useState(null); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [text, setText] = useState(""); + const [money, setMoney] = useState(""); + const [points, setPoints] = useState(""); + const generation = useRef(0); + const active = useRef(true); + const mutating = useRef(false); + const refresh = useCallback(async () => { + const ticket = ++generation.current; + setLoading(true); + const result = await client.getProgressionView(profileId); + if (!active.current || generation.current !== ticket) return; + setLoading(false); + if (!result.ok) { setView(null); setError(result.error); } + else if (result.value.profile_id !== profileId || result.value.binding.snapshot !== snapshotId) { setView(null); setError(OUTDATED); } + else { setView(result.value); setError(null); } + }, [client, profileId, snapshotId]); + useEffect(() => { + active.current = true; + void refresh(); + const timer = window.setInterval(() => { if (!mutating.current) void refresh(); }, 60000); + return () => { active.current = false; generation.current++; window.clearInterval(timer); }; + }, [refresh]); + + const invalid = inputError(money, points); + const blocked = disabled || busy || loading || view === null; + async function save(kind: "manual" | "import") { + if (blocked || mutating.current || view === null || (kind === "manual" && invalid !== null) || (kind === "import" && text.trim() === "")) return; + mutating.current = true; setBusy(true); setError(null); setReceipt(null); + const ticket = ++generation.current; + const result = kind === "manual" ? await client.saveManualProgression(manualRequest(view, money, points)) + : await client.importProgression({ profile_id: profileId, expected: view.binding, text }); + if (!active.current || ticket !== generation.current) return; + mutating.current = false; setBusy(false); + if (!result.ok) { setError(result.error); if (result.error.code === "SNAPSHOT_OUTDATED") setView(null); return; } + if (result.value.profile_id !== profileId || result.value.snapshot_id !== snapshotId) { setView(null); setError(OUTDATED); return; } + setReceipt(result.value); + if (kind === "manual") { setMoney(""); setPoints(""); } else setText(""); + await refresh(); + } + + return
+ {loading &&

Loading progression observations…

} + {error !== null &&

Error {error.code}: {error.message}

} + {receipt !== null &&

{receipt.stored ? "Saved progression capture" : "Progression capture was already stored"}: {receipt.companion_id}{receipt.fixture ? " (synthetic fixture)" : ""}.

} + +
+ Import progression companion + {(c) =>