Compare commits
104 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| abef27cf2a | |||
| 03d3fcf460 | |||
| 037a4b870a | |||
| b8e69b5239 | |||
| 495f179c2f | |||
| b386ab9670 | |||
| 2be2e7d615 | |||
| 6d182db81b | |||
| dc19cffcc0 | |||
| 05447c92fc | |||
| 415158d4d3 | |||
| 9bc35f7edd | |||
| 15895cae0c | |||
| 5650255e49 | |||
| 2be400e455 | |||
| 2c9a50ddf9 | |||
| 4c3c8b49eb | |||
| a22525023a | |||
| c674931f5c | |||
| 3936c575b2 | |||
| 9404d0130c | |||
| 8ff008f85c | |||
| d2ffa4cad2 | |||
| d18b96c10b | |||
| 4fa8126471 | |||
| ff4bb0f31e | |||
| e919fe9a35 | |||
| ab5bdafbd8 | |||
| 2eb825c84e | |||
| 4ab68d6b68 | |||
| eaedcb53dd | |||
| 11c8124674 | |||
| 44d428b6f4 | |||
| f20d84c543 | |||
| fbcd05169f | |||
| b3a9fdf330 | |||
| 114e0b5116 | |||
| 81e9184c7f | |||
| b328871549 | |||
| b781ffeb66 | |||
| 0e94b1fd2a | |||
| c6a48c8d91 | |||
| 0679e1cef7 | |||
| 503449452c | |||
| bb78e35ac3 | |||
| d86fc93ed6 | |||
| 3bae76cea3 | |||
| 74bd8b2863 | |||
| 92c4f81640 | |||
| 566ea0675c | |||
| 7db28438ad | |||
| d411352644 | |||
| 47abad22bc | |||
| 0f0bd71f35 | |||
| daf03248c4 | |||
| 188905e778 | |||
| ea4931e53f | |||
| baf2f89b3e | |||
| 9ca4b4520d | |||
| 53830dcb91 | |||
| 9418cc2eb5 | |||
| fb9a8c820c | |||
| fd48105c99 | |||
| 121ff7035e | |||
| 65ec1ca3d2 | |||
| ff245529aa | |||
| f08569894e | |||
| 82e9e652f8 | |||
| 10eee46097 | |||
| 781bfd17ec | |||
| b4bff31d58 | |||
| f63f95a730 | |||
| 18294f6ed8 | |||
| b01527fb4f | |||
| fb50e6e7b4 | |||
| 6f5ae7e724 | |||
| 440fedc90f | |||
| b9028ec1bd | |||
| 5bb9f9e7fb | |||
| 627f0fd2c0 | |||
| cf635aa0b0 | |||
| 1c64f96b54 | |||
| a719fa9fc6 | |||
| bbaab9f2c7 | |||
| 813af72d98 | |||
| fb74b28404 | |||
| bbaa759f5e | |||
| 5346fc8402 | |||
| dd952441aa | |||
| 3353f86f62 | |||
| f5b3f4ebe6 | |||
| b36e33e239 | |||
| 6e2b9b3008 | |||
| 1254bd9cd7 | |||
| 8d95a8e518 | |||
| 13ab6097e6 | |||
| f1c60de355 | |||
| 13bfa792bb | |||
| 9aa0ca3e92 | |||
| 5e364cfa41 | |||
| 478ae2bcc2 | |||
| 5c1da50174 | |||
| 2c73e5fa4e | |||
| 4576df7253 |
@@ -4,3 +4,4 @@ ts phase decision why evidence result
|
||||
2026-09-09T19:45:25Z unit AGENTS ownership complete; Gates table removed; UX-DESIGN demoted; IMPL-PLAN owns gate meanings subtract calendar restatement and close ownership gap AGENTS.md,docs/UX-DESIGN.md,docs/IMPL-PLAN.md check-structure PASSED
|
||||
2026-09-09T19:45:25Z unit TEST-SPEC and deploy docs label missing tree as Phase 0 targets stop agents inventing harness paths that are not on main docs/TEST-SPEC.md,docs/DEPLOYMENT.md,deploy/docker-compose.yml,README.md check-structure PASSED
|
||||
2026-09-09T19:45:25Z verify ran docs/checks/check-structure.sh after all edits prove done predicate on real artifact docs/checks/check-structure.sh exit 0 VERIFIED
|
||||
2026-09-09T19:47:17Z attention-fix restored Gate B meaning to original AGENTS wording; hardened check-structure for both deploy files and fuller math lock phrase Attention review flagged Gate B parenthetical as lock drift and weak deploy grep docs/IMPL-PLAN.md,docs/checks/check-structure.sh check-structure PASSED
|
||||
|
||||
|
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
backend
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
frontend/.svelte-kit
|
||||
**/.DS_Store
|
||||
*.md
|
||||
!deploy/README.md
|
||||
.audit
|
||||
docs/archive
|
||||
@@ -35,3 +35,11 @@ images/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Playwright e2e (#65) — keep README; ignore churn
|
||||
frontend/tests/e2e/artifacts/*.png
|
||||
frontend/tests/e2e/artifacts/run-log.txt
|
||||
frontend/tests/e2e/test-results/
|
||||
frontend/tests/e2e/playwright-report/
|
||||
frontend/blob-report/
|
||||
frontend/playwright/.cache/
|
||||
|
||||
@@ -1,197 +1,34 @@
|
||||
# AGENTS.md — SlabUploader
|
||||
# AGENTS.md
|
||||
|
||||
Working contract for coding agents. Read before writing code.
|
||||
## Agent context
|
||||
|
||||
Status: **Gate A freeze** · signed 2026-08-31 PT · docs cut to `main` 2026-09-06 · SoT: Gitea `Ty_Tech/SlabUploader` on **gitea-atd** (not mirrors).
|
||||
Read this file, `docs/CAPTURE.md`, and `docs/PHOTOS.md`.
|
||||
Implement Milestone 2 only. Specification: `docs/PHOTOS.md`.
|
||||
PRD: `docs/PRODUCT.md` for destination and field names. Do not implement Milestone 3 or 4.
|
||||
Do not widen Milestone 2 into Complete-listing taxonomy, SKU, price, copy, or Woo create.
|
||||
|
||||
---
|
||||
## Milestone 2
|
||||
|
||||
## 0. Where each doc lives
|
||||
Photos.
|
||||
Acceptance: on a phone, batch of 1–N photos, user-picked calibration photo through Milestone 1 mask/axis/measure, every successful shot as a 3:4 transparent inventory PNG lined up, Milestone 1 numbers on screen, dimension-overlay copy of the calibration PNG present.
|
||||
|
||||
| Doc | Owns |
|
||||
|---|---|
|
||||
| `docs/TECH-SPEC-PIPELINE.md` | Deterministic math, image prep, constants, test vectors |
|
||||
| `docs/ARCHITECTURE.md` | Hybrid topology, what-runs-where, secrets why, status machine |
|
||||
| `AGENTS.md` | Hard rules for coding agents (locks below) |
|
||||
| `docs/DATA-MODEL.md` | Store row / schema facts |
|
||||
| `docs/OPENAPI.md` | Wire / HTTP contracts |
|
||||
| `docs/CONTENT-WOO.md` | Listing copy and Woo payload |
|
||||
| `docs/PROMPTS.md` | Call 1 / Call 2 prompt files |
|
||||
| `docs/DEPLOYMENT.md` | Compose, Caddy, secrets placement, ops |
|
||||
| `docs/UX.md` | Presentation: what the mill owner sees and does (signed) |
|
||||
| `docs/UX-DESIGN.md` | Non-normative wireframes only. `docs/UX.md` wins on any conflict. |
|
||||
| `docs/TEST-SPEC.md` | Engineer test bar: pyramid cases, phased by gate, through PROD |
|
||||
| `docs/UAT-PRACTICE.md` | Walkable practice UAT for `SLAB-UAT-*` |
|
||||
| `docs/IMPL-PLAN.md` | Phases 0–6, Gates A/B/C meanings, exit gates. Phase 2 is a deferred stub. |
|
||||
| `deploy/INVENTORY.md` | Host worksheet before port bind (Gate B) |
|
||||
| `README.md` | Orientation only |
|
||||
| `docs/archive/PRD-2026-08.txt` | Frozen archive. Not a source for new work. |
|
||||
Milestone 2 is inference-free. Batch mask/crop reuse and dimension overlays run in the browser as ordinary code. There is no inference URL and no model call in this milestone.
|
||||
|
||||
Live docs agree. If two live files disagree, that is a docs bug: fix the files, then continue.
|
||||
## Milestone 1 (historical)
|
||||
|
||||
Run `docs/checks/check-structure.sh` after doc structure edits. It pins ownership, calendar home, and lock phrases.
|
||||
Capture. Spec: `docs/CAPTURE.md`. Remains the calibration math and PNG contract Milestone 2 reuses.
|
||||
|
||||
### Known open gaps
|
||||
## Invariants
|
||||
|
||||
- Issue #4: exact minimum browser version pins and deeper load-bearing API inventory. Phone + PC families are already locked in `docs/UX.md` / TECH-SPEC.
|
||||
|
||||
---
|
||||
|
||||
## 0b. Gates and phases
|
||||
|
||||
Gate A is the docs freeze (this tree). Gate B is host inventory plus the Phase 0 deploy skeleton. Gate C is the first Woo draft listing with inference OFF (early Phase 1).
|
||||
|
||||
**Phase 0 = Gates A+B. Gate C = early Phase 1.** Call 1/2 only after Gate C is green, still inside POC. Gate meanings, phase deliverables, and exit gates live only in `docs/IMPL-PLAN.md`. Do not re-teach that map elsewhere.
|
||||
|
||||
### Freeze provenance (Gate A)
|
||||
|
||||
| SHA | What locked |
|
||||
|---|---|
|
||||
| `a94d81d` | gitea-atd `Ty_Tech/SlabUploader` as remotes SoT |
|
||||
| `457711b` | AGENTS.md + hybrid IMPL Phase 0 |
|
||||
| `4ec478f` | Contradiction patches (README/PRD/Woo/DEPLOYMENT) |
|
||||
| `4d9f307` / `4e97770` | Inference review + hybrid capture pipeline (pre-freeze baseline) |
|
||||
|
||||
Docs refactor is on `main` (cut 2026-09-06). Product locks above are unchanged.
|
||||
|
||||
### Known stale PRD lines
|
||||
|
||||
`docs/archive/PRD-2026-08.txt` is frozen history. These PRD lines are superseded by live docs:
|
||||
FR17 (fig-* 1+, feat-* 0+), FR19 (species $/bdft only), FR40 (client-side, not server-side
|
||||
processing), NFR server normalization timing, FR42 (env-agnostic DEPLOYMENT + deploy/INVENTORY.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Topology (locked — hybrid)
|
||||
|
||||
**Client (SvelteKit) owns the happy path:**
|
||||
|
||||
- Capture 1–5 photos
|
||||
- Sheet detect + chroma-key / black threshold + **four knobs inline on capture** (sheet, sensitivity, edge offset, feather) with **live re-run** and mask overlay on the source photo
|
||||
- Mask overlay + **user confirm** before measurement
|
||||
- Length axis overlay (rotate / confirm)
|
||||
- sqft, bdft, 6" width samples
|
||||
- 3:4 transparent PNG, 80% fill at extremes, shorter side ≥ 1600 when source allows
|
||||
- Draft payload: originals + processed PNGs + length/thickness/SKU/sqft/bdft/widths
|
||||
|
||||
**Server (FastAPI) owns:**
|
||||
|
||||
- Store drafts / settings / taxonomy cache
|
||||
- U2Net "Try harder" — **deferred from POC**, not deleted. Architecture keeps the one-photo server path for awkward backgrounds post-POC. POC mask tuning is **client-side only** (sheet + four knobs, live re-run).
|
||||
- WooCommerce (taxonomy sync, SKU check, create product) — browser never calls Woo
|
||||
- Inference **proxy** (Call 1 / Call 2) — keys never in browser
|
||||
- Prompt files (server text files, read fresh)
|
||||
|
||||
Happy path never leaves the phone until the user continues after confirmed mask + numbers.
|
||||
|
||||
Deferred work and non-goals are in `docs/ARCHITECTURE.md` and `docs/IMPL-PLAN.md`.
|
||||
|
||||
Depth: `docs/ARCHITECTURE.md`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Deferred work
|
||||
|
||||
The MVP is online-only. Measuring lives in the browser. Manual SKU entry, manual length, and client-side measure/crop are the source of truth. Undersized source warns and requires retake. The server stores client-sent numbers; there is no server happy-path pipeline for the deterministic core.
|
||||
|
||||
Phase 2 is a deferred stub for offline PWA, OCR, and ruler detection. Post-POC items: LoRA / fine-tune, figure-/category-weighted pricing (v1.5), auto-dimension overlay (v1.5), bulk publish, staff roles, analytics, SKU update path. Depth: `docs/ARCHITECTURE.md` §4 and `docs/IMPL-PLAN.md` Phase 2.
|
||||
|
||||
---
|
||||
|
||||
## 3. Deterministic core (non-negotiable)
|
||||
|
||||
Encode TECH-SPEC exactly:
|
||||
|
||||
- **bdft = sqft × thickness_in** (identity: 1 sqft @ 1" = 1 bdft).
|
||||
- Units: inches in 1/8" steps; sqft/bdft 2 decimals; price half-up 2 decimals.
|
||||
- Manual length, thickness, SKU, price always win.
|
||||
- Image prep: sheet/sliders → mask confirm → length axis confirm → 3:4 PNG / 80% fill / ≥1600px when source allows.
|
||||
- Undersized source warns and requires retake. Photo is not publishable until retake.
|
||||
- Pricing: species `$/bdft` from Settings, seeded by Woo species sync; `rec = bdft × price_per_bdft`; user override sticks; missing rule leaves rec empty, manual allowed.
|
||||
- Port TECH-SPEC **TV-1 through TV-10** (including TV-10 Rounding). Client (or shared pure modules the client uses) is authoritative for math; server **stores** client-sent numbers.
|
||||
|
||||
Depth: `docs/TECH-SPEC-PIPELINE.md`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Secrets and settings
|
||||
|
||||
**Server-side only:**
|
||||
|
||||
- Woo WordPress username + application password (dedicated low-privilege WP user for product create/edit + media)
|
||||
- Inference API key and endpoint (treat inference URL as sensitive)
|
||||
- AES master key (`SLAB_AES_KEY` env only; never in DB or repo)
|
||||
|
||||
**`WOO_BASE_URL`:** compose / host `.env` only (`https://` required). Settings shows it read-only. Not a SQLite settings row. FastAPI rejects `http://` at startup.
|
||||
|
||||
**Server:** AES-GCM at rest in SQLite for Woo Application Password + inference secrets. Settings UI POSTs username + application password to FastAPI; server encrypts. All Woo and inference calls are server-side. Rotate by revoking the application password in WP Users → Profile and re-entering in Settings. WooCommerce consumer keys (`ck_`/`cs_`) are not implemented.
|
||||
|
||||
**Browser may persist (non-secret):** sheet mode, sensitivity, edge offset, feather (localStorage OK; reset-to-default required).
|
||||
|
||||
Why/flow: `docs/ARCHITECTURE.md` §5. Ciphertext key inventory: `docs/DATA-MODEL.md` settings table.
|
||||
|
||||
---
|
||||
|
||||
## 5. Woo UAT and create status (Ty locked 2026-08-31)
|
||||
|
||||
- Store URL: **`WOO_BASE_URL`** from Docker Compose (`https://` only). Intended UAT/POC store is Whidbey Wood Store production; the compose value is the SoT, not a Settings field.
|
||||
- Mid-phase UAT creates: Woo status **draft**, SKU prefix **`SLAB-UAT-*`**
|
||||
- Settings field **`woo_create_status`**: **`draft | publish`**, default **`draft`**
|
||||
- Hard rule: if SKU matches `SLAB-UAT-*`, force **Woo draft** even if Settings say publish
|
||||
- Final POC success: one real (non-UAT) SKU → **Woo publish** only after Ty review
|
||||
- Duplicate SKU → stop; UI maps **409** to the SKU field (edit SKU or open existing)
|
||||
- After successful publish: purge originals + processed images on server
|
||||
|
||||
Woo draft/publish status is separate from slab lifecycle status (§7).
|
||||
|
||||
Payload and publish sequence depth: `docs/CONTENT-WOO.md`. Key only: DATA-MODEL `woo_create_status`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Inference (inside POC, sequenced)
|
||||
|
||||
- Feature-flagged; **full suite must pass with inference OFF**.
|
||||
- **Gate C** claimable path: inference **OFF**; manual taxonomy + deterministic numbers + Woo draft path.
|
||||
- **Call 1 (vision) / Call 2 (text) only after Gate C is green**, still inside overall POC before "done."
|
||||
- Call 1 auto only if `inference_enabled`; Call 2 never auto-fires (user taps Generate text).
|
||||
- Call 1 body: all inventory photos @1024. Taxonomy lists sent to Call 1 are **exactly the Woo-synced species / attribute sets**.
|
||||
- **Confidence 0.7 (default):** ≥ 0.7 → pre-populate species, wood categories, edge, figure, grade, and feat-* from Call 1 (**mutable**). < 0.7 → those fields stay **empty**. Ready still requires the full named set in §7. Presentation: `docs/UX.md`.
|
||||
- **Taxonomy cache:** `taxonomy_last_sync_at` vs `taxonomy_anchor` (bump only on stored-subset hash change, including deletions). Client re-pulls iff the anchor advanced. `test-woo` always syncs; publish if last_sync >1h. No per-nav sync. No Woo taxonomy timestamp.
|
||||
- Call 2 portable context: default full resend; never require `previous_response_id`. `test-inference` two-turn probe `stateful|stateless|fail`. Fail blocks **Call 2 enablement only**.
|
||||
- Templates inject deterministic numbers. LLM does not invent dimensions.
|
||||
|
||||
Prompt file mechanics: `docs/PROMPTS.md`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Slab status machine (app-internal only)
|
||||
|
||||
`draft → calibrated → ready → publishing → published` (or `failed` with detail).
|
||||
|
||||
- **calibrated:** mask + axis confirmed; length/thickness/SKU entered; client computed sqft/bdft/widths; draft uploaded.
|
||||
- **ready:** SKU, length, thickness, client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness store band (round-up), 1 moisture (default kiln-dried; not inferred), price. feat-* 0+. Title/description may be typed, generated, or templated at publish. Vision may prefill the taxonomy subset only when confidence ≥ 0.7.
|
||||
- Inference does not gate publish. Below-threshold Call 1 does not prefill; empty mandatory fields block ready.
|
||||
|
||||
Slab `draft` is separate from Woo draft (`woo_create_status`).
|
||||
|
||||
---
|
||||
|
||||
## 8. Test and delivery expectations
|
||||
|
||||
- No feature without a passing test and shown execution output (PR/commit message).
|
||||
- Deterministic core unit-tested before UI consumes it.
|
||||
- One phase = reviewable, shippable increment; Ty exit-gates phases.
|
||||
- Phase and gate naming: follow `docs/IMPL-PLAN.md` only (§0b).
|
||||
- Secrets, real Woo application passwords, and AES keys stay out of the repo.
|
||||
|
||||
---
|
||||
|
||||
## 9. Deploy sketch
|
||||
|
||||
- Target: inventoried Docker host. Docker Compose (`frontend` + `fastapi`) + Caddy → `https://${APP_HOSTNAME}` (LAN/Tailscale).
|
||||
- Fill `deploy/INVENTORY.md` before binding ports or merging Caddy (co-resident apps can collide; bolt.diy is one example).
|
||||
- Health: `GET https://${APP_HOSTNAME}/api/health`.
|
||||
- `WOO_BASE_URL` in compose (HTTPS). Settings displays it read-only.
|
||||
- Inference is a remote configurable endpoint, not on the app host by default.
|
||||
|
||||
Depth: `docs/DEPLOYMENT.md`.
|
||||
- Quantity per listing is one.
|
||||
- User enters length, thickness, and SKU.
|
||||
- App proposes remaining listing fields. User reviews before create.
|
||||
- Non-math fields remain editable until create.
|
||||
- `bdft = sqft × thickness_in`
|
||||
- Price proposal is `bdft × species $/bdft`. User may replace it. Missing rate leaves price empty.
|
||||
- User-entered length, thickness, SKU, price, and taxonomy override computed or inferred values.
|
||||
- SKUs matching `SLAB-UAT-*` create as Woo draft.
|
||||
- Create works with inference off.
|
||||
- Source below the PNG size floor requires a new photo.
|
||||
- Existing store SKU blocks create.
|
||||
- Dimension overlay orientation follows the user-approved length axis from Milestone 1.
|
||||
|
||||
@@ -1,56 +1,14 @@
|
||||
# SlabUploader
|
||||
|
||||
Browser app for listing one-of-a-kind wood slabs on the Whidbey Wood Store.
|
||||
Lists one-of-a-kind wood slabs on Whidbey Wood Store.
|
||||
|
||||
You photograph a slab, confirm the cut and the numbers, review the listing, and create the WooCommerce product. The browser does the measuring and crop. The server stores the draft, talks to the store, and (later) runs vision. Runs on phones and PCs.
|
||||
|
||||
Owner: Ty (Whidbey). Store: www.whidbeywoodstore.com. Runs in Docker Compose behind Caddy on a host you inventory first (`APP_HOSTNAME`).
|
||||
|
||||
## Where we are
|
||||
|
||||
Gate A freeze signed 2026-08-31. All live docs sit on `main`. Read `AGENTS.md` before writing code.
|
||||
|
||||
The bar for this first version: a real slab, photographed on a phone or a PC, listed on the real store. Practice listings are WooCommerce **drafts** with SKUs that start `SLAB-UAT-`. After Ty reviews, one real SKU goes **live**. Online only for now; offline capture is deferred.
|
||||
|
||||
Build order is in `docs/IMPL-PLAN.md`. Empty app on the real host first, then the first draft listing, then vision.
|
||||
|
||||
## Documentation
|
||||
|
||||
Ownership detail lives in `AGENTS.md` §0. Short map:
|
||||
|
||||
| File | What |
|
||||
| Artifact | File |
|
||||
|---|---|
|
||||
| `AGENTS.md` | Hard rules. Read first. |
|
||||
| `docs/IMPL-PLAN.md` | What to build next (phases, Gates A/B/C, exit gates) |
|
||||
| `docs/TECH-SPEC-PIPELINE.md` | Math, image pipeline, TV-1–TV-10 |
|
||||
| `docs/ARCHITECTURE.md` | Hybrid topology, secrets why, status machine |
|
||||
| `docs/UX.md` | Signed mill-owner presentation (phone and PC) |
|
||||
| `docs/TEST-SPEC.md` | Engineer test bar (cases stay `not run` until code exists) |
|
||||
| `docs/UAT-PRACTICE.md` | Walkable practice UAT for `SLAB-UAT-*` |
|
||||
| `deploy/INVENTORY.md` | Host worksheet before binding ports |
|
||||
| `docs/archive/PRD-2026-08.txt` | Frozen history, not a source for new work |
|
||||
| PRD | `docs/PRODUCT.md` |
|
||||
| Invariants and agent context | `AGENTS.md` |
|
||||
| Milestone 1 | `docs/CAPTURE.md` |
|
||||
| Milestone 2 | `docs/PHOTOS.md` |
|
||||
| Hosting | `deploy/` |
|
||||
|
||||
`docs/UX-DESIGN.md` is non-normative wireframes. `docs/UX.md` wins on conflict.
|
||||
|
||||
## Short map
|
||||
|
||||
- Client (SvelteKit) owns the happy path: mask knobs, sqft, bdft, 3:4 PNG. Server (FastAPI) stores drafts, talks to WooCommerce, and proxies vision. Server matting ("Try harder") is deferred from POC; POC mask tuning is client-side only.
|
||||
- Board feet = square feet × thickness in inches. No divide-by-12. Test vectors TV-1 through TV-10 run in the browser.
|
||||
- Secrets never sit in the browser. Encrypted on the server. Store login is a WordPress application password on a low-privilege user; WooCommerce consumer keys are not implemented.
|
||||
- Practice SKUs `SLAB-UAT-*` are always drafts, even if Settings say publish.
|
||||
- Vision stays off until the first draft listing works. Species suggestion and Generate text come after, still inside this project.
|
||||
- Two containers (`frontend`, `fastapi`) plus Caddy. One SQLite, image volumes. Inventory the host first.
|
||||
|
||||
Where deferred items live: `docs/ARCHITECTURE.md` §4 and `docs/IMPL-PLAN.md` Phase 2 (offline PWA, OCR, ruler — deferred stub).
|
||||
|
||||
## Repo
|
||||
|
||||
Source of truth: Gitea `Ty_Tech/SlabUploader` on gitea-atd
|
||||
(`https://gitea.vps1.afterthedemo.com/Ty_Tech/SlabUploader`). TrueNAS and GitHub copies are not the source of truth for this work.
|
||||
|
||||
## Getting started
|
||||
|
||||
1. Read `AGENTS.md` (locks) and `docs/IMPL-PLAN.md` Phase 0 (build next).
|
||||
2. Run `docs/checks/check-structure.sh` if you change doc ownership or calendar homes.
|
||||
3. Scaffold `frontend/` and `backend/` per Phase 0. Measuring lives in the browser. Compose paths are already pinned.
|
||||
4. Ty signs each phase. Live docs on `main` are the source of truth. The archive PRD is frozen history only.
|
||||
Owner: Ty. Store: https://www.whidbeywoodstore.com/
|
||||
Repo: `Ty_Tech/SlabUploader`
|
||||
|
||||
@@ -1,69 +1,35 @@
|
||||
# Deploy inventory worksheet
|
||||
# Host
|
||||
|
||||
Fill this at **Gate B** on the designated host before any port bind or Caddy merge.
|
||||
The host must be inventoried before any deployment. See `docs/DEPLOYMENT.md`.
|
||||
## Overnight Capture UAT (primary — when Tailscale is up)
|
||||
|
||||
## Host
|
||||
- Host: `ubudual5060` / Tailscale `100.64.0.9`
|
||||
- Container: `slabuploader-m2-overnight` (image `slabuploader-m2:overnight`) — or salvage rebuild of the same role
|
||||
- Port: **10881** → 80
|
||||
- URL: `http://100.64.0.9:10881`
|
||||
- Replaces prior overnight container `slabuploader-m1-overnight` (same port).
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Inventory date | 2026-09-06 PT |
|
||||
| Operator | Ty / Main Cut (SSH from cursor Tailscale node) |
|
||||
| Machine name / role | ubuDual5060 — practice / UAT app host (locked) |
|
||||
| `APP_HOST` (LAN or Tailscale IP/name used in DNS) | Tailscale preferred: `100.64.0.9` (`ubudual5060`). LAN also: `192.168.1.202` |
|
||||
| `APP_HOSTNAME` (HTTPS site name, e.g. `slab.example.local`) | `slab.local` (LAN-first; Pi-hole or hosts → `192.168.1.202`) |
|
||||
| OS / Docker version | Ubuntu 26.04.1 LTS; Docker 29.8.0; Compose v5.5.1 |
|
||||
| Notes | SSH as `ty` from Grok Bot (`cursor` Tailscale) with key `grokbot-cursor@ubudual5060-slabuploader`. User `ty` is in `docker` group. Disk ~15G free of 172G (92% used) — watch volume growth. Gitea is code SoT only; runtime is this host. |
|
||||
| `WOO_BASE_URL` (`https://` store; not editable in app) | `https://www.whidbeywoodstore.com` (practice drafts via `SLAB-UAT-*`) |
|
||||
## Fallback UAT — Grok Bot computer (when Tailscale to 5060 is down)
|
||||
|
||||
## Ports and collisions
|
||||
Use this path for salvage / Capture UAT until the box can reach `100.64.0.9` again.
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `docker ps` summary (names + published ports) | Running: `whisperx-stt` `0.0.0.0:9000->9000`. Host also has `llama-server` on `0.0.0.0:8082`. Firecrawl stack present but exited. |
|
||||
| Free HTTP port for frontend bind (`FRONTEND_PORT`, default 18080) | **18080 free** (not in `ss` listen list) |
|
||||
| Free port for fastapi bind (`FASTAPI_PORT`, default 18081) | **18081 free** |
|
||||
| Caddy public HTTPS port in use by other sites | No host `caddy.service`. No Caddy container found. HTTPS front still to be added. |
|
||||
| Co-resident apps that own ports (example: bolt.diy on 8443-class) | 9000 (whisperx-stt), 8082 (llama-server), 22 (sshd). Avoid those. |
|
||||
- Host: Grok Bot computer (slab-m1 box)
|
||||
- Serve: static Capture build (`frontend` → `npm run build`, then `vite preview` or equivalent static server)
|
||||
- Port: **18181** (chosen so it never collides with Ty local on 5060)
|
||||
- Bind: `0.0.0.0:18181`
|
||||
- URL (from this box): `http://127.0.0.1:18181` — Ty reaches it via the bot computer / whatever path the app exposes; Tailscale IP of this box when mesh returns
|
||||
- Branch for salvage: `salvage-one-woo-draft` (cut from `m2-ds`)
|
||||
- Do **not** require Docker on the box for this fallback.
|
||||
|
||||
## Caddy
|
||||
When Tailscale is restored, prefer primary overnight `:10881` again and stop advertising the fallback as the main UAT URL.
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Caddy config path (host file or container) | **Not installed yet** — choose host install vs compose sidecar at Gate B execute |
|
||||
| Existing site blocks that share this host | none found |
|
||||
| TLS mode (`internal` CA vs other) | TBD (Tailscale HTTPS / Caddy `internal` / existing lab CA) |
|
||||
| Phone CA trust verified? (yes/no + how) | no — not deployed yet |
|
||||
## Ty local Node/SvelteKit on 5060 (do not overwrite)
|
||||
|
||||
## DNS / reachability
|
||||
- Host: `ubudual5060` / `100.64.0.9`
|
||||
- Container: `slabuploader-m1`
|
||||
- Port: **18080** → 80
|
||||
- URL: `http://100.64.0.9:18080`
|
||||
- **Never** recreate or remap this container for overnight or box-fallback UAT.
|
||||
- **Never** bind overnight or fallback UAT to **10880** either (legacy Ty local).
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| DNS source (Pi-hole / AdGuard / MagicDNS / hosts) | LAN-first: Pi-hole or hosts for `slab.local` → `192.168.1.202`. Tailscale MagicDNS remains for SSH (`ubudual5060`). |
|
||||
| A record: `APP_HOSTNAME` → `APP_HOST` | `slab.local` → `192.168.1.202` (LAN). Optional Tailscale alias later. |
|
||||
| Reachable from phone on LAN? | TBD after deploy |
|
||||
| Reachable from phone on Tailscale? | TBD after deploy (path intended) |
|
||||
|
||||
## Volumes and backup
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Docker volume dir convention | TBD on first compose up (prefer under a dedicated path; disk pressure noted) |
|
||||
| Backup target path (local) | TBD |
|
||||
| Off-box mirror (if any) | TBD |
|
||||
|
||||
## Smoke after first up
|
||||
|
||||
| Check | Pass? |
|
||||
|---|---|
|
||||
| `curl -k https://${APP_HOSTNAME}/api/health` | not run |
|
||||
| Compose `frontend` + `fastapi` healthy | not run |
|
||||
| Caddy `/api/*` reaches fastapi (not frontend) | not run |
|
||||
|
||||
## Sign-off
|
||||
|
||||
| Role | Name | Date |
|
||||
|---|---|---|
|
||||
| Inventory draft (SSH + ports + hostname + store) | Main Cut | 2026-09-06 PT |
|
||||
| Inventory complete | | |
|
||||
| Ty Gate B (optional) | | |
|
||||
Future overnight Capture deploys use a **separate** container name and an open **108XX** port other than Ty’s local ports.
|
||||
Do not put a host name in the product spec.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# Deploy
|
||||
|
||||
Milestone 1 ships as a Docker image that serves the capture app.
|
||||
Where the container runs is chosen at runtime.
|
||||
|
||||
No FastAPI and no Woo client in this milestone.
|
||||
|
||||
`docker-compose.yml`, `Caddyfile.fragment`, and `.env.example` describe an older two-service stack. They are not the Milestone 1 contract.
|
||||
@@ -0,0 +1,4 @@
|
||||
# Release
|
||||
|
||||
Build the Docker image. Run it on the host chosen for that test.
|
||||
Milestone 3 adds the Woo service and a tagged UAT path.
|
||||
@@ -0,0 +1,17 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# SPA: fall back to index.html for any path
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~* \.(js|css|png|jpg|jpeg|svg|woff2?)$ {
|
||||
expires 7d;
|
||||
add_header Cache-Control "public";
|
||||
try_files $uri =404;
|
||||
}
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
# Architecture
|
||||
|
||||
Status: SPEC · hybrid topology locked at Gate A freeze (2026-08-31) · SlabUploader
|
||||
|
||||
Normative for hybrid split, swimlane, what-runs-where, secrets **why**, and status
|
||||
transitions. Ops depth lives in DEPLOYMENT. Schema enums live in DATA-MODEL.
|
||||
Agent-facing hard rules live in AGENTS.md (verbatim locks stay there).
|
||||
|
||||
Companion: `docs/TECH-SPEC-PIPELINE.md`. Historical PRD: `docs/archive/PRD-2026-08.txt` (frozen; not a source for new work). Agent locks: `AGENTS.md`.
|
||||
|
||||
## 1. Topology (hybrid)
|
||||
|
||||
Phone does the happy-path pipeline (mask knobs, length axis, sqft/bdft, 3:4 PNG).
|
||||
FastAPI stores drafts, proxies inference, talks to Woo. reverse proxy terminates HTTPS.
|
||||
Server U2Net (“Try harder”) is **deferred from POC**, not deleted.
|
||||
|
||||
```
|
||||
phone (SvelteKit)
|
||||
capture, four knobs inline, live mask overlay on the source photo,
|
||||
length axis, sqft/bdft, 3:4 PNG
|
||||
(POC: retake if mask still bad — no U2Net control)
|
||||
|
||||
server
|
||||
reverse proxy → frontend (static)
|
||||
→ fastapi : store, settings, taxonomy cache, Woo, inference proxy, prompt files
|
||||
→ U2Net endpoint reserved post-POC
|
||||
```
|
||||
|
||||
- Happy path never leaves the phone.
|
||||
- Mask knobs live on capture; changing a knob re-runs client BG removal immediately.
|
||||
- Woo + LLM keys stay on the server. Browser does not call Woo or the vision endpoint directly.
|
||||
|
||||
## 2. Swimlane
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Phone["Phone — SvelteKit"]
|
||||
P1[New Wood: 1–5 photos]
|
||||
P2[BG overlay + sheet / sensitivity / edge / feather]
|
||||
P3{Edge OK?}
|
||||
P4[Length axis overlay — rotate / confirm]
|
||||
P5[User length + thickness + SKU]
|
||||
P6[sqft, bdft, 6in widths, 3:4 PNGs]
|
||||
P7[Review: Call 1 pre-fill or manual taxonomy]
|
||||
P8[Tap Generate text]
|
||||
P9[Review title / desc — publish]
|
||||
end
|
||||
|
||||
subgraph API["server — FastAPI"]
|
||||
A1[U2Net reserved post-POC]
|
||||
A2[Store draft: originals + PNGs + numbers]
|
||||
A3[Call 1 proxy — vision]
|
||||
A4[Call 2 proxy — text]
|
||||
A5[Woo: taxonomy, SKU check, create product]
|
||||
end
|
||||
|
||||
subgraph LLM["Your OpenAI-compatible endpoint"]
|
||||
L1[Wood expert — all photos at 1024]
|
||||
L2[Title / desc / short desc]
|
||||
end
|
||||
|
||||
subgraph Woo["WooCommerce store"]
|
||||
W1[Categories / attributes / fig-* tags]
|
||||
W2[New product live or draft per setting]
|
||||
end
|
||||
|
||||
P1 --> P2 --> P3
|
||||
P3 -->|no — retune knobs or retake| P2
|
||||
P3 -->|no — Retake| P1
|
||||
P3 -->|yes| P4 --> P5 --> P6
|
||||
P6 --> A2
|
||||
A2 --> A3 --> L1 --> A3 --> P7
|
||||
P7 --> P8 --> A4 --> L2 --> A4 --> P9
|
||||
P9 --> A5
|
||||
A5 --> W1
|
||||
A5 --> W2
|
||||
```
|
||||
|
||||
## 3. Clarifications
|
||||
|
||||
1. **Happy path** stays on the phone through PNG + numbers. FastAPI is idle until the user has a confirmed mask.
|
||||
2. **Mask knobs** live on capture; each change re-runs client BG removal. Server U2Net “Try harder” is deferred from POC. The one-photo contract stays in the architecture; the control is not shipped until post-POC.
|
||||
3. **Draft upload** sends **originals + processed PNGs + length/thickness/SKU/sqft/bdft/widths**. Originals are needed if Call 1 or a later retry must not depend on the tab still being open. After successful Woo publish, server deletes both.
|
||||
4. **Call 1** is server-side so the vision key never sits in the browser. Auto-run
|
||||
on slab create **only if** `inference_enabled` is true. If disabled, Call 1
|
||||
is skipped; user can manually fill taxonomy and still trigger Call 2. Body:
|
||||
all originals downscaled to 1024 + **Woo-synced taxonomy only** + SKU/length/thickness.
|
||||
Timeout 45s → error + retry on the phone. ≥0.7 confidence **pre-populates**
|
||||
species, wood categories, edge/figure/grade, feat-* (mutable). Below 0.7 those
|
||||
fields stay **empty**. Manual entry stays authoritative. Presentation: `docs/UX.md`.
|
||||
5. **Call 2** does not auto-fire. User taps Generate text. Server must send
|
||||
**portable Call 1 context** (default: full conversation resend). Stateful
|
||||
`previous_response_id` only after `test-inference` proves the provider supports
|
||||
it. Call 2 inputs distinguish confirmed user values from inferred ones. Per-slab
|
||||
thread; delete on submit or abandon.
|
||||
6. **Woo** is only FastAPI. Browser never sees the WordPress application
|
||||
password. Duplicate SKU → 409 mapped on the SKU field (edit SKU or open existing).
|
||||
Stale value → 422 on that field. Draft stays on the phone.
|
||||
7. **Settings** (species $/bdft, prompts, inference endpoint, Woo credentials,
|
||||
publish status) live on the server. Store URL is env, displayed read-only.
|
||||
|
||||
## 4. What runs where
|
||||
|
||||
| Job | Where |
|
||||
|---|---|
|
||||
| Camera, 1-5 photos | Client |
|
||||
| Sheet detect, chroma-key / black threshold, four knobs, live re-run, flood-fill | Client |
|
||||
| U2Net “Try harder” | Server, **deferred from POC** |
|
||||
| Length axis overlay, 6" widths, sqft, bdft | Client |
|
||||
| 3:4 PNG, 80% fill (configurable aspect) | Client |
|
||||
| Draft + originals + processed PNGs | Server (after user continues) |
|
||||
| Species $/bdft, Woo creds, prompts, brand/GEO | Server |
|
||||
| Call 1 (vision, all photos @1024) | Server proxy |
|
||||
| Call 2 (title/desc) | Server proxy, after Call 1 curation |
|
||||
| Woo taxonomy sync + publish | Server |
|
||||
|
||||
## 5. Secrets and settings
|
||||
|
||||
**Server-side only (never in browser JS):**
|
||||
1. WordPress username + **application password** for a dedicated low-privilege
|
||||
WP user. Server uses HTTP Basic Auth (`username:application_password`) against
|
||||
`/wp-json/wc/v3/`. Stored encrypted at rest in SQLite (AES-GCM). Not Woo
|
||||
consumer keys. Not the account login password.
|
||||
2. Inference endpoint base URL + API key. Stored encrypted. Server proxies all
|
||||
inference calls.
|
||||
3. AES master key. Env var on server (`SLAB_AES_KEY`), never in the DB.
|
||||
4. `WOO_BASE_URL` env (compose). HTTPS only. Not user-editable; Settings displays it read-only.
|
||||
|
||||
**Browser-side (no secrets):**
|
||||
1. User preferences: sheet mode, sensitivity, edge offset, feather. Persisted in localStorage, reset-to-default available.
|
||||
2. Species list with $/bdft. Read from server settings sync.
|
||||
3. Taxonomy snapshot (categories, attributes, tags). Read from server. No auth needed.
|
||||
|
||||
**Flow:**
|
||||
1. Deploy sets `WOO_BASE_URL` (`https://`) in compose. Operator creates a
|
||||
low-privilege WP user on that store (HTTPS required for Application
|
||||
Passwords UI). Generates an application password under Users → Profile.
|
||||
2. User enters that username + application password in Settings UI
|
||||
(store URL shown read-only from env).
|
||||
3. Browser POSTs them to `/api/v1/settings` on FastAPI. Server encrypts with
|
||||
AES-GCM and stores ciphertext only.
|
||||
4. Server syncs taxonomy from Woo, caches in SQLite.
|
||||
5. Client reads taxonomy from `/api/v1/admin/taxonomy` — no auth needed.
|
||||
6. All Woo calls go server-to-Woo. Browser never calls Woo REST directly.
|
||||
|
||||
Browser-to-Woo REST would need CORS on the store, which this design does not use.
|
||||
|
||||
## 6. Status machine
|
||||
|
||||
```
|
||||
draft → calibrated → ready → publishing → published
|
||||
│ │ ↑
|
||||
└→ failed ────┴────────────────┘ (woo_product_id set)
|
||||
any → failed (with error)
|
||||
```
|
||||
|
||||
1. **draft** — user took photos, no mask confirmed yet.
|
||||
2. **calibrated** — user confirmed the BG edge, confirmed length axis, entered length/thickness/SKU. Client computed sqft/bdft/widths. Draft uploaded to server.
|
||||
3. **ready** — SKU, length, thickness, client sqft/bdft/widths, ≥1 inventory PNG,
|
||||
exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag,
|
||||
≥1 grade, thickness store band (round-up), 1 moisture (default kiln-dried), price.
|
||||
feat-* 0+. Title/description may be typed, generated, or templated at publish.
|
||||
Values can come from Call 1 (≥ 0.7 pre-fill the user kept), manual entry, or a mix.
|
||||
**Review gate:** below-threshold Call 1 leaves species, wood category, figure,
|
||||
edge, grade, and feat-* empty. That subset is not the submit list. Inline nudges
|
||||
on every still-required control, not submit-only. Presentation: `docs/UX.md`. Inference is
|
||||
optional; with inference OFF the user fills everything by hand.
|
||||
4. **publishing** — Woo create in flight. Poll for result.
|
||||
5. **published** — Woo product created, woo_product_id stored. Images purged.
|
||||
6. **failed** — pipeline, inference, or publish error. Error detail stored. Retry available.
|
||||
|
||||
Call 1 and Call 2 are assist-only. They do not gate publish. Low-confidence Call 1
|
||||
results do not auto-fill. If the user skips inference, the path is: calibrated →
|
||||
ready → publishing → published.
|
||||
|
||||
## 7. Taxonomy cache (manufactured last-modified)
|
||||
|
||||
Woo REST exposes **no usable last-modified** on categories, attributes, or tags
|
||||
(only products carry `date_modified`). The client never talks to Woo. FastAPI is
|
||||
the sole freshness source. It persists two UTC stamps: `taxonomy_last_sync_at`
|
||||
(every successful Woo pull) and `taxonomy_anchor` (bumps only when the stored-subset
|
||||
hash changes, including deletions).
|
||||
|
||||
- Anchor bumps **only** when a row-level change is detected in the **stored
|
||||
subset** of cache fields (whatever columns the cache tables actually keep:
|
||||
species/wood-category leaves, five attributes + terms, `fig-*`/`feat-*` tags).
|
||||
Scope is schema-driven: adding a cache column later automatically includes it.
|
||||
- Spelling/name edits, additions, and deletions all bump. Diff must catch missing
|
||||
rows (deletions), not only changed rows.
|
||||
- A no-op sync (stored subset unchanged) **does not** bump, so the client does
|
||||
not churn.
|
||||
- Client reads the anchor. If it advanced past the client's last value, re-pull
|
||||
the **full** taxonomy cache. One timestamp governs categories, attributes, and
|
||||
tags together.
|
||||
- `taxonomy_anchor` is app-managed; no Woo-side timestamp or per-table anchor is used.
|
||||
|
||||
**Triggers**
|
||||
|
||||
1. `POST /api/v1/settings/test-woo` **always** resyncs taxonomy after a successful
|
||||
connection test (unlocks the species list).
|
||||
2. Publish / product submit: opportunistic resync if the last successful sync is
|
||||
older than **1 hour**; bump anchor only if the stored subset changed.
|
||||
3. Optional: app launch check (sync only if stale) and a Settings “Refresh
|
||||
taxonomy” control. Not required for POC.
|
||||
4. Do **not** sync on every screen navigation.
|
||||
|
||||
Species pickers and Call 1 option lists are **exactly** this cached set. No
|
||||
hardcoded, invented, or fallback species list. A new Woo species is selectable
|
||||
only after the next sync that lands it in the cache.
|
||||
|
||||
## 8. Shared validation module
|
||||
|
||||
One FastAPI module is source of truth (`GET /api/v1/validation/module` → `{ hash, rules[] }`).
|
||||
Two consumers: review UI and Call 2 prompt builder. Client caches the module.
|
||||
|
||||
- SKU charset: `[A-Z0-9-]{3,24}` (printable ASCII subset). Title / short_title / description: UTF-8 within Woo `maxLength`. Not “ASCII-only” and not “extended ASCII”.
|
||||
- Field-exit: local check against the cache. Empty optional is valid.
|
||||
- Length: `maxLength` is a hard input cap; server still enforces.
|
||||
- Submit carries `validation_hash`. Match → validate. Mismatch → HTTP **412** + fresh module; UI “Updating rules”; re-validate; retry. Never show 412. 409 is duplicate SKU only. Woo-shaped 422 is store rejection (#18).
|
||||
|
||||
## 9. Call 1 → Call 2 context
|
||||
|
||||
Providers differ. Default portable path: **resend the full Call 1 turn** (prompt + images metadata + assistant JSON) with Call 2. Opt into `previous_response_id` only after probe.
|
||||
|
||||
`POST /api/v1/settings/test-inference` two-turn probe records `stateful | stateless | fail`.
|
||||
**Fail blocks Call 2 enablement only** (Gate C inference-OFF still works). Call 2 always carries the full Call 1 context; `previous_response_id` is optional after probe.
|
||||
|
||||
Per-slab thread on the **server** (client does not hold provider IDs). Best-effort delete on publish / abandon / fail; log and continue.
|
||||
|
||||
Presentation: `docs/UX.md`.
|
||||
@@ -0,0 +1,140 @@
|
||||
# Milestone 1 — Capture
|
||||
|
||||
Runs in the browser on phone and PC as ordinary client code.
|
||||
No inference URL. No model. No backend. Mask, rectangle, measurements, crop, and PNG encode are deterministic functions of the photo and user inputs.
|
||||
|
||||
Milestone 1 uses one reference photo. Further angles are later milestones.
|
||||
Milestone 1 ends when the user sees the inventory PNG and measurements. Milestone 2 is Review. Milestone 3 is Create. This file does not create a WooCommerce product.
|
||||
|
||||
## Setup
|
||||
|
||||
Photograph the slab on a green or black sheet.
|
||||
|
||||
- Sheet fills the frame around the slab.
|
||||
- Slab is fully on the sheet.
|
||||
- First photo is top-down, lens parallel to the face.
|
||||
- Length of the slab is aligned with the long side of the picture.
|
||||
|
||||
The app expects that sheet. Background removal keys green or black. Other backgrounds are out of Milestone 1.
|
||||
|
||||
## Use case
|
||||
|
||||
If a device draft exists:
|
||||
|
||||
- App opens Resume.
|
||||
- User chooses Continue or Start fresh.
|
||||
- Continue: app restores the last approved state.
|
||||
- Start fresh: app discards the draft and opens Add photo.
|
||||
|
||||
Otherwise the app opens Add photo.
|
||||
|
||||
1. User adds one photo taken under Setup.
|
||||
2. App decodes the photo and opens Mask. App keys green or black and shows an overlay: slab stays the photograph; removed pixels are a light gray checkerboard.
|
||||
3. User sets sheet Auto / Green / Black and sensitivity 0–100 (slider or minus / plus). App updates the control immediately. App recomputes the overlay 2.0 seconds after the last sensitivity change. User adjusts until only the slab remains, then approves. App blocks approve if the mask has no slab pixels; user retakes. The approved mask is the footprint for every later step.
|
||||
4. App draws the minimum-area bounding rectangle of the mask and the length axis on the long side of that rectangle. User rotates the axis if it does not follow the slab length, then approves the axis.
|
||||
5. User enters length `L` in inches (1/8 in steps) and thickness (1/8 in steps), then presses Calculate.
|
||||
6. App sets `scale = longest_axis_px / L` (mask/wood span along the approved direction ÷ user `L`; rectangle is direction only).
|
||||
7. App computes widths, sqft, and bdft from the mask. App crops the masked slab into a 3:4 portrait frame: slab centered, 90% fill at the widest and tallest points, background transparent. App writes that frame as an inventory PNG (`image/png`, 8-bit RGBA).
|
||||
8. User sees the transparent PNG and the numbers. Milestone 1 stops here.
|
||||
|
||||
Calculate does not create a WooCommerce product.
|
||||
|
||||
## Browsers
|
||||
|
||||
Phone: iOS Safari, Android Chrome.
|
||||
PC: Chrome, Edge, Firefox.
|
||||
Other clients get a hard stop.
|
||||
|
||||
## States
|
||||
|
||||
One photo component is reused. Each state advances on approve. Back returns to the previous state. A device draft restores the last approved state.
|
||||
|
||||
1. Resume — only when a device draft exists. Continue or Start fresh.
|
||||
2. Add photo — camera or picker. One photo. Setup rules visible.
|
||||
3. Mask — background removal on that photo.
|
||||
4. Length axis — bounding rectangle and long-side axis on the same photo.
|
||||
5. Measure — length, thickness, Calculate, crop, inventory PNG, widths, sqft, bdft. Milestone 1 stops here.
|
||||
|
||||
## Display
|
||||
|
||||
Preview fits the device width. Height is capped so Mask and Measure controls stay on screen. Phone and PC use the same states.
|
||||
|
||||
The preview is display only. Mask, rectangle, crop, `scale`, sqft, and PNG encode use the source photo pixels, not the CSS size of the preview.
|
||||
|
||||
## Runtime
|
||||
|
||||
Browser APIs: `createImageBitmap`, `canvas` / `OffscreenCanvas`, Web Worker, `convertToBlob({ type: "image/png" })`, IndexedDB.
|
||||
`idb-keyval` may wrap IndexedDB.
|
||||
No OpenCV, ONNX, U2Net, or image-editor kit.
|
||||
Sensitivity 0–100 maps to green chroma tightness and black brightness cutoff in the worker.
|
||||
|
||||
## Mask
|
||||
|
||||
Overlay: slab remains the photograph. Removed pixels are a light gray checkerboard.
|
||||
|
||||
Controls on this state, with the photo visible:
|
||||
|
||||
- Sheet: Auto, Green, or Black
|
||||
- Sensitivity: 0–100, step 1. Slider with minus and plus on each side. Button hit targets sized for a thumb.
|
||||
|
||||
The control value updates immediately. The overlay recomputes 2.0 seconds after the last sensitivity change. A sheet change may recompute on the change.
|
||||
|
||||
Mask work runs in the worker. The last good overlay stays visible while a pass runs. Show a busy mark only if a pass lasts more than a fraction of a second. If a pass fails, keep the last overlay; the user may retake.
|
||||
|
||||
Approve is blocked when the mask has no slab pixels. User retakes.
|
||||
|
||||
User approves the mask when only the slab remains. That mask is the footprint for Length axis, crop, measurements, and the inventory PNG.
|
||||
|
||||
## Length axis
|
||||
|
||||
On the same photo, keep the approved mask in view and draw the minimum-area bounding rectangle of the mask with the length axis on the long side of that rectangle. User rotates the rectangle (slider with minus and plus) until that direction follows the slab length, then approves the axis.
|
||||
|
||||
## Measure
|
||||
|
||||
User enters length `L` in inches (1/8 in steps) and thickness (1/8 in steps), then presses Calculate.
|
||||
|
||||
- `scale = longest_axis_px / L` where `longest_axis_px` is the mask/wood span along the approved length direction (slab pixels end-to-end on that axis), not the rectangle edge length. The rectangle sets direction only; user-entered `L` is wood end→end along that direction.
|
||||
- Widths: min, max, avg from samples taken every 6 in along the approved length axis, perpendicular to it, after dropping the first and last 6 in of the span (bulk widths, not tips). If `L ≤ 12 in` there are no interior stations and all three are 0.
|
||||
- `sqft = (mask_pixels / scale²) / 144` (2 decimals)
|
||||
- `bdft = sqft × thickness_in` (2 decimals)
|
||||
- Crop: 3:4 portrait, slab centered, 90% fill at the widest and tallest points, transparent background
|
||||
- File: inventory PNG, `image/png`, 8-bit RGBA, alpha kept
|
||||
|
||||
User sees the transparent PNG and those numbers. Stop. Calculate does not create a WooCommerce product.
|
||||
|
||||
## Crop
|
||||
|
||||
On Calculate, the app builds the inventory image from the approved mask:
|
||||
|
||||
1. Keep slab pixels from the source photo. Removed pixels are transparent.
|
||||
2. Place the slab in a 3:4 portrait frame, centered.
|
||||
3. Scale so the widest and tallest points of the slab fill 90% of the frame. Extra margin where the slab is narrower.
|
||||
4. After that crop, shorter side ≥ 800px when the source can supply it. Otherwise warn and require a new photo. No upscale from an undersized source.
|
||||
5. Encode as PNG with alpha.
|
||||
|
||||
## Device draft
|
||||
|
||||
One in-progress slab is stored on the device. This is not a WooCommerce draft.
|
||||
|
||||
On open or refresh, if that draft exists, the app opens in Resume.
|
||||
|
||||
- Continue restores the last approved state, including Measure.
|
||||
- Start fresh discards the device draft and opens Add photo.
|
||||
|
||||
Milestone 3 clears the device draft after Woo create.
|
||||
|
||||
## Inventory PNG
|
||||
|
||||
Role: `kind=inventory`. Filename is an implementation detail.
|
||||
The first inventory photo is the measurement reference. Later inventory photos use the same file properties.
|
||||
|
||||
| Property | Value |
|
||||
|---|---|
|
||||
| Format | PNG, 8-bit RGBA (`image/png`) |
|
||||
| Alpha | Kept through encode and upload |
|
||||
| Aspect | 3:4 portrait |
|
||||
| Layout | Slab centered, 90% fill at the widest and tallest points |
|
||||
| Size | After crop, shorter side ≥ 800px when the source can supply it |
|
||||
|
||||
Source below that floor: warn and require a new photo. No upscale from an undersized source.
|
||||
Editor preview of alpha is a light gray checkerboard. The storefront uses the theme background.
|
||||
@@ -1,198 +0,0 @@
|
||||
# Listing copy and the store
|
||||
|
||||
How titles and descriptions are built, how we talk to WooCommerce, and the exact create payload. Templates always run. Generate text is optional and never publishes on its own.
|
||||
|
||||
## 1. Titles and descriptions
|
||||
|
||||
### 1.1 Templates (always on)
|
||||
Templates live in Settings. Defaults below. Placeholders use `{field}`.
|
||||
|
||||
**title** (default):
|
||||
```
|
||||
{species} {length_ft}ft {length_in_remainder}in × {width_avg_in}in Wood Slab — {character}
|
||||
```
|
||||
Example: `Black Walnut 16ft 0in × 18.2in Wood Slab — Cathedral`
|
||||
- `length_ft` = floor(length_in / 12), `length_in_remainder` = length_in mod 12 (1 dp).
|
||||
|
||||
**short_title** (default):
|
||||
```
|
||||
{species} Slab — {character}
|
||||
```
|
||||
Example: `Black Walnut Slab — Cathedral`
|
||||
|
||||
**description** (default, multi-paragraph):
|
||||
```
|
||||
A one-of-a-one {character} {species} slab, {length_ft}ft {length_in_remainder}in long with an
|
||||
average width of {width_avg_in}in and {thickness_in}in thickness ({bdft} bdft).
|
||||
|
||||
Each slab is naturally shaped — width varies along the length at {width_min_in}in to
|
||||
{width_max_in}in. Sold by the slab; dimensions as measured. {geo_sentence}
|
||||
```
|
||||
`geo_sentence` is the geography sentence from Settings, e.g.
|
||||
`"Locally milled and shipped from the Pacific Northwest."` (default if unset: none).
|
||||
|
||||
All template math fields come from the deterministic pipeline (never from the LLM).
|
||||
|
||||
### 1.2 Generate text (optional)
|
||||
The mill owner taps Generate text on review. It never runs by itself. It is off unless `content_llm_enabled` is true.
|
||||
|
||||
The model writes prose only (character, color, grain, uses). Measured length, width, thickness, square feet, and board feet are facts in the prompt. The model does not invent numbers. Templates inject those numbers into the title and description after the prose comes back.
|
||||
|
||||
The mill owner can always edit the result. `content_source` is `llm` when this path ran.
|
||||
|
||||
If the text endpoint is missing or down, disable the button. Templates still work. Publish is never blocked because Generate text failed.
|
||||
|
||||
### 1.3 Audit
|
||||
Every content generation (template or LLM) is logged with inputs (template version,
|
||||
slab facts), the LLM request/response payload when used (inference calls logged for audit),
|
||||
and the final stored content.
|
||||
|
||||
## 2. WooCommerce
|
||||
|
||||
### 2.1 Auth & client
|
||||
- REST v3 surface unchanged: `GET/POST/PATCH/DELETE {WOO_BASE_URL}/wp-json/wc/v3/…`
|
||||
- Auth is **WordPress Application Passwords**, not WooCommerce consumer keys
|
||||
(`ck_`/`cs_`) and not the user's login password.
|
||||
- Create a **dedicated low-privilege WordPress user** (shop manager, or a custom
|
||||
role with product create/edit + media upload). A dedicated low-privilege user, not the admin account, is used.
|
||||
- Generate the application password under **Users → Profile → Application
|
||||
Passwords**. WordPress requires **HTTPS** for that UI; the store must already
|
||||
be on TLS (Caddy enforces HTTPS on the app side too).
|
||||
- Basic auth shape: `woo_wp_username:woo_app_password` (username + application
|
||||
password). Spaces in the generated password are ignored by WordPress; store
|
||||
the value as entered.
|
||||
- FastAPI is the sole Woo caller. Credentials live encrypted at rest in SQLite
|
||||
(AES-GCM, `SLAB_AES_KEY` env). The browser never holds them.
|
||||
- Rotation: revoke the application password in the WP user profile, enter a new
|
||||
one in Settings UI, then `POST /api/v1/settings/test-woo`.
|
||||
- Client: `httpx` with timeouts (connect 10s, read 60s for image-heavy create).
|
||||
- Store URL is **`WOO_BASE_URL`** from Docker Compose / host `.env` (HTTPS only).
|
||||
FastAPI refuses `http://` at startup. Not a Settings field; UI shows it read-only.
|
||||
|
||||
### 2.2 Store lists (species, tags, attributes)
|
||||
`POST /api/v1/admin/taxonomy/sync` pulls, in order:
|
||||
1. `GET /products/categories?per_page=100` (paginate) → species + wood-category leaves
|
||||
2. `GET /products/tags?per_page=100` → `fig-*` / `feat-*` only (other tags ignored)
|
||||
3. `GET /products/attributes` (+ terms) → five locked attributes
|
||||
|
||||
Rebuilds cache tables in one transaction. Failure → `502 woo_error`; previous
|
||||
cache retained (never delete-then-fail).
|
||||
|
||||
**Manufactured stamps.** Woo REST has **no** usable last-modified on categories,
|
||||
attributes, or tags. FastAPI persists `taxonomy_last_sync_at` (every successful
|
||||
pull) and `taxonomy_anchor` (bump only when stored-subset hash changes, including
|
||||
deletions). Client re-pulls the full taxonomy iff the anchor advanced. No Woo-side
|
||||
taxonomy timestamp; no per-navigation sync.
|
||||
|
||||
**Triggers:** (1) successful `test-woo` **always** resyncs; (2) publish if
|
||||
`now - taxonomy_last_sync_at > 1 hour` then reconcile (bump only on real change);
|
||||
(3) optional app launch / Settings refresh. If a picked id vanished after a refresh, show that field as no longer valid. The selection is not silently swapped.
|
||||
|
||||
**Species exclusivity.** UI pickers, pricing seeds, and Call 1 species lists are
|
||||
**exactly** the synced species-category leaves. No hardcoded, invented, or fallback
|
||||
species set. A species new in Woo is selectable only after the next sync stores it.
|
||||
|
||||
### 2.3 What goes on the listing
|
||||
|
||||
When vision is on and it is at least 0.7 sure, it fills species, wood categories,
|
||||
edge, figure, grade, and feature tags (character, inclusions, voids, checks map
|
||||
to existing `feat-*` tags only). The mill owner can change every filled value.
|
||||
Typed values always win.
|
||||
|
||||
If it is less sure, those fields stay empty. That empty-start subset is not
|
||||
the submit list. Review will not continue until the full ready set is filled:
|
||||
SKU, length, thickness, price, species, wood category, edge type, figure,
|
||||
grade, thickness band, moisture, fig-* tags, and inventory PNG(s). Species
|
||||
plus one figure is not enough. Presentation: `docs/UX.md`.
|
||||
Low-confidence guesses are not filled.
|
||||
|
||||
Names from vision or from typing match store ids case-insensitive, trimmed. No
|
||||
match leaves the field empty so they can pick from the list. The store will still
|
||||
reject a missing required field at publish.
|
||||
|
||||
|
||||
Field rules:
|
||||
- **Categories**: species leaf (1 required) plus wood-category leaf ids (1+).
|
||||
- **Tags**: `fig-*` (1+ required) and `feat-*` (0+). Only documented
|
||||
character or species product tags are used. Woo is authoritative for tag definitions.
|
||||
- **Attributes**: the five locked Woo attributes only — Edge Type, Figure, Grade,
|
||||
Thickness, Moisture — using term ids from the cache. Species,
|
||||
character, length, or free-text thickness as product attributes. Missing
|
||||
attributes are skipped, not created (v1: no attribute creation).
|
||||
|
||||
Vision only suggests. It never blocks publish. With vision off, everything is typed.
|
||||
|
||||
### 2.4 Create payload
|
||||
`POST /products` — body (only non-null fields sent):
|
||||
```jsonc
|
||||
{
|
||||
"name": "{title}",
|
||||
"type": "simple",
|
||||
"status": "{woo_create_status}", // draft | publish; default draft; SLAB-UAT-* forced draft
|
||||
"sku": "{sku}",
|
||||
"regular_price": "{price}", // 2 dp string, e.g. "2730.00"
|
||||
"description": "{description}",
|
||||
"short_description": "{short_title}",
|
||||
"categories": [ { "id": <species category id> } ],
|
||||
"tags": [ { "id": <fig-* tag id> }, { "id": <feat-* tag id> }, … ],
|
||||
"images": [
|
||||
{ "src": "<data URL or pre-uploaded attachment URL>", "alt": "{species} {character} slab" }
|
||||
],
|
||||
"attributes": [ … if present … ],
|
||||
"virtual": false,
|
||||
"downloadable": false,
|
||||
"catalog_visibility": "visible"
|
||||
}
|
||||
```
|
||||
**Image upload strategy** (Woo v3): `images[].src` accepts a URL or a data URL.
|
||||
For reliability the server:
|
||||
1. For each customer-facing inventory photo in `seq` order (processed transparent PNGs
|
||||
from the client TECH-SPEC path): `POST /media` with the **PNG bytes** → get attachment
|
||||
`source_url`. Woo accepts `image/*`; keep alpha. JPEG re-encoding drops alpha and must not happen.
|
||||
2. Reference those `source_url` values in `images` (≤5 inventory photos).
|
||||
3. Only `kind=inventory` photos. Calibration photos do not exist in this design.
|
||||
|
||||
**Status** comes from Settings `woo_create_status` (`draft` or `publish`, default
|
||||
`draft`). Practice SKUs `SLAB-UAT-*` are always created as drafts, even if Settings
|
||||
say publish. Existing SKUs are not edited in this version. After a successful create,
|
||||
the server deletes the original and processed photos. A slab marked published in the
|
||||
app means the store create succeeded. That is not the same as WooCommerce "publish."
|
||||
The force-draft rule is in `AGENTS.md`. This file only owns the payload and the steps.
|
||||
|
||||
### 2.5 Duplicate SKU
|
||||
Before create: `GET /products?sku={sku}` (any store status).
|
||||
- Found: stop. The phone shows the SKU field with Edit SKU and Open existing listing. This version does not update the other product.
|
||||
- Not found: create. Still do the check every time.
|
||||
|
||||
### 2.6 After a failed publish
|
||||
|
||||
The mill owner sees a message on the field, not a status number or a stack. The form stays on the phone. The server marks the slab failed so they can try again.
|
||||
|
||||
If the SKU already exists: under SKU, "This SKU already exists in the store (any status)." Edit SKU, or open the existing listing (admin link when we have it).
|
||||
|
||||
If a category, attribute, or price is no longer valid: under that field, "This value is no longer valid. Pick from the current list," with the current store options.
|
||||
|
||||
The server still writes `sync_log`. Success still sets `woo_product_id`, marks published locally, and deletes photos.
|
||||
|
||||
- **Partial-failure note** (risk, see IMPL-PLAN): if media uploads succeed but the
|
||||
final product POST fails, orphaned Woo attachments may exist. v1: log it; surface
|
||||
a manual cleanup note. Not auto-deleted.
|
||||
|
||||
## 3. End-to-end publish sequence (server side)
|
||||
```
|
||||
1. check the listing against the shared rules (current copy of the rules on submit)
|
||||
2. look up the SKU in the store (any status). Stop if it already exists.
|
||||
3. refresh store lists if the last successful pull is older than 1 hour. Only bump the client list-version if something actually changed.
|
||||
4. resolve categories, tags, and attributes from the synced lists (vision names or typed names)
|
||||
5. upload processed PNG inventory photos to media, keep the URLs
|
||||
6. POST /products with draft/publish per Settings, always draft for SLAB-UAT-* SKUs
|
||||
7. on success: log, mark published locally, delete originals and processed photos
|
||||
on failure: log, mark failed, keep photos, put the error on the field (§2.6)
|
||||
```
|
||||
|
||||
## 4. What the model may and may not do
|
||||
|
||||
Templates, numbers, matching names to store ids, payload, dedupe, logging: code.
|
||||
Generate text may write description prose only. It must not invent dimensions. It may only pick species and attributes that exist in the synced store lists.
|
||||
|
||||
Presentation: `docs/UX.md`. The wire uses `{ field, code, message, actions[] }`. The mill owner never sees those codes. If the phone's copy of the rules is stale, refresh the copy and retry. That is not a duplicate-SKU conflict.
|
||||
@@ -1,241 +0,0 @@
|
||||
# Data Model
|
||||
|
||||
Status: SPEC · 2026-08-27 · SlabUploader
|
||||
Storage: single SQLite file. Schema portable to Postgres.
|
||||
|
||||
Conventions:
|
||||
- IDs: client-generated UUIDv4 for slabs so the SvelteKit client can reference a slab before it exists server-side.
|
||||
- Timestamps: UTC ISO-8601 TEXT.
|
||||
- Soft state via status column; no hard deletes for slabs (audit).
|
||||
- Money: float64 USD, rounded half-up to cents at write.
|
||||
- All rounded values are what gets stored. No full-precision internal storage.
|
||||
- Inches stored as 1/8" increments. Sqft/bdft to 2 decimals.
|
||||
- Multi-select fields stored as JSON arrays of Woo IDs.
|
||||
|
||||
---
|
||||
|
||||
## slabs
|
||||
|
||||
Draft-only. Deleted on successful publish. WooCommerce is the source of truth for product data.
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | TEXT PK | client-generated UUID |
|
||||
| `sku` | TEXT UNIQUE NOT NULL | `[A-Z0-9-]{3,24}` printable ASCII subset |
|
||||
| `status` | TEXT NOT NULL | draft \| calibrated \| ready \| publishing \| published \| failed |
|
||||
| `length_in` | REAL NOT NULL | 1/8" step |
|
||||
| `thickness_in` | REAL NOT NULL | 1/8" step |
|
||||
| `sqft` | REAL | 2 decimals |
|
||||
| `bdft` | REAL | 2 decimals |
|
||||
| `width_min_in` | REAL | min width at 6" stations, 2 decimals |
|
||||
| `width_max_in` | REAL | max width at 6" stations, 2 decimals |
|
||||
| `width_avg_in` | REAL | avg width at 6" stations, 2 decimals |
|
||||
| `species_id` | INTEGER | → woo_categories (leaf only, 1 required) |
|
||||
| `wood_category_ids` | INTEGER[] JSON | → woo_categories (leaf, 1+) |
|
||||
| `edge_type_term_id` | INTEGER | → woo_attribute_terms (1 required) |
|
||||
| `figure_term_ids` | INTEGER[] JSON | → woo_attribute_terms (1+) |
|
||||
| `grade_term_ids` | INTEGER[] JSON | → woo_attribute_terms (1+) |
|
||||
| `thickness_term_id` | INTEGER | → woo_attribute_terms (round-up) |
|
||||
| `moisture_term_id` | INTEGER | → woo_attribute_terms (1 required, defaults to kiln-dried term; user overrides; not inferred) |
|
||||
| `fig_tag_ids` | INTEGER[] JSON | → woo_tags (fig-*, 1+) |
|
||||
| `feat_tag_ids` | INTEGER[] JSON | → woo_tags (feat-*, 0+) |
|
||||
| `price_per_bdft` | REAL | from pricing_rules for species |
|
||||
| `price` | REAL NOT NULL | 2 decimals |
|
||||
| `price_source` | TEXT | 'recommendation' \| 'override' |
|
||||
| `title` | TEXT | |
|
||||
| `short_title` | TEXT | |
|
||||
| `description` | TEXT | |
|
||||
| `content_source` | TEXT | 'manual' \| 'llm' |
|
||||
| `client_rev` | INTEGER NOT NULL DEFAULT 1 | |
|
||||
| `server_rev` | INTEGER NOT NULL DEFAULT 1 | |
|
||||
| `created_at` | TEXT NOT NULL | |
|
||||
| `updated_at` | TEXT NOT NULL | |
|
||||
| `inference_thread_id` | TEXT | optional stateful provider id; delete on publish or abandon |
|
||||
|
||||
Indexes: `sku` (unique), `status`, `updated_at`.
|
||||
|
||||
### Status state machine
|
||||
|
||||
```
|
||||
draft → calibrated → ready → publishing → published
|
||||
│ │ ↑
|
||||
└→ failed ────┴────────────────┘ (woo_product_id in sync_log)
|
||||
any → failed (with error)
|
||||
```
|
||||
|
||||
1. **draft** — photos taken, no mask confirmed.
|
||||
2. **calibrated** — BG edge confirmed, length axis confirmed, length/thickness/SKU entered. Client computed sqft/bdft/widths. Draft uploaded to server.
|
||||
3. **ready** — SKU, length_in, thickness_in, client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness_term_id (round-up from measured thickness), 1 moisture (default kiln-dried; user override; not inferred), price. feat-* 0+. Title/short_title/description may be typed, generated, or written by templates at publish. Call 1 may prefill only the vision subset when confidence ≥ 0.7. Inference optional. Publishable.
|
||||
4. **publishing** — Woo create in flight. Poll for result.
|
||||
5. **published** — Woo product created. This row + all photos deleted. sync_log retained.
|
||||
6. **failed** — pipeline, inference, or publish error. Error detail stored. Retry available.
|
||||
|
||||
---
|
||||
|
||||
## slab_photos
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | TEXT PK | |
|
||||
| `slab_id` | TEXT FK → slabs.id ON DELETE CASCADE | |
|
||||
| `kind` | TEXT NOT NULL | 'inventory' |
|
||||
| `role` | TEXT | 'topdown' \| 'extra' |
|
||||
| `seq` | INTEGER | display order |
|
||||
| `original_path` | TEXT | relative to images volume |
|
||||
| `processed_path` | TEXT | relative to images volume |
|
||||
| `created_at` | TEXT | |
|
||||
|
||||
Rule: only inventory photos. Calibration photos do not exist in this design.
|
||||
|
||||
---
|
||||
|
||||
## pricing_rules
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | TEXT PK UUID | |
|
||||
| `species` | TEXT NOT NULL | matches woo_categories.name (leaf) |
|
||||
| `price_per_bdft` | REAL NOT NULL | flat, no tiers |
|
||||
| `created_at` | TEXT | |
|
||||
| `updated_at` | TEXT | |
|
||||
|
||||
`UNIQUE(species)`. Seeded from synced Woo categories. User sets price per species.
|
||||
|
||||
---
|
||||
|
||||
## woo_categories
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `woo_id` | INTEGER PK | |
|
||||
| `name` | TEXT | |
|
||||
| `slug` | TEXT | |
|
||||
| `parent_id` | INTEGER | NULL for root |
|
||||
| `synced_at` | TEXT | |
|
||||
|
||||
Only species + wood category. Sync pulls all Woo categories; the app filters to the two we use.
|
||||
Species leaves from this table (after filter) are the **only** species the UI and Call 1 may offer.
|
||||
|
||||
`UNIQUE(woo_id)`.
|
||||
|
||||
---
|
||||
|
||||
## woo_attributes
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `woo_id` | INTEGER PK | |
|
||||
| `name` | TEXT | |
|
||||
| `slug` | TEXT | |
|
||||
| `type` | TEXT | 'select' |
|
||||
| `synced_at` | TEXT | |
|
||||
|
||||
Only the five first-class attributes: Edge Type, Figure, Grade, Thickness, Moisture.
|
||||
|
||||
`UNIQUE(woo_id)`.
|
||||
|
||||
---
|
||||
|
||||
## woo_attribute_terms
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `woo_id` | INTEGER PK | |
|
||||
| `attribute_id` | INTEGER FK → woo_attributes.woo_id | |
|
||||
| `name` | TEXT | |
|
||||
| `slug` | TEXT | |
|
||||
| `synced_at` | TEXT | |
|
||||
|
||||
The actual selectable values. E.g., "Cathedral" under Figure, "1\"–1 1/2\"" under Thickness.
|
||||
|
||||
`UNIQUE(woo_id)`.
|
||||
|
||||
---
|
||||
|
||||
## woo_tags
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `woo_id` | INTEGER PK | |
|
||||
| `name` | TEXT | |
|
||||
| `slug` | TEXT | |
|
||||
| `synced_at` | TEXT | |
|
||||
|
||||
Only `fig-*` and `feat-*` tags. Other Woo tags ignored. WooCommerce is the
|
||||
authoritative source for tag definitions; this table caches synced Woo tags.
|
||||
|
||||
`UNIQUE(woo_id)`.
|
||||
|
||||
---
|
||||
|
||||
## settings
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `key` | TEXT PK | |
|
||||
| `value_enc` | BLOB | AES-GCM ciphertext |
|
||||
| `updated_at` | TEXT | |
|
||||
|
||||
Keys (server settings; secrets encrypted at rest):
|
||||
- `woo_wp_username`, `woo_app_password`
|
||||
(username + WordPress application password for a dedicated low-priv WP user;
|
||||
not WooCommerce consumer keys)
|
||||
- Store URL is **not** a settings row: `WOO_BASE_URL` env (compose), HTTPS only
|
||||
- `inference_base_url`, `inference_api_key`, `inference_model`
|
||||
- `inference_enabled`, `content_llm_enabled`
|
||||
- `brand_voice`, `geo_context`
|
||||
- `woo_create_status` ('draft' | 'publish'), default `draft` — Woo product create status key only; safety policy lives in AGENTS.md §5
|
||||
- `taxonomy_last_sync_at` — UTC ISO; every successful Woo taxonomy pull
|
||||
- `taxonomy_anchor` — UTC ISO; bump only when stored-subset hash changes (incl. deletions). No-op sync does not bump. Not Woo `date_modified`.
|
||||
- `aspect_ratio` ('3:4'), `output_px` (1600), `output_px_min` (1600), `fill_target` (0.80)
|
||||
|
||||
|
||||
Sheet/slider prefs (`sheet_mode`, sensitivity, edge offset, feather) persist in client
|
||||
localStorage only. Client localStorage is source of truth (AGENTS §4 / ARCHITECTURE §5).
|
||||
Server sync of these prefs is deferred post-POC.
|
||||
|
||||
**Prompt files** — not in the settings table. Shipped as text files in
|
||||
`backend/app/prompts/` (repo), bind-mounted read-only to `/app/prompts/` in the
|
||||
FastAPI container. Read fresh on each invocation. Default prompts shipped with the
|
||||
app; owner edits on the host; no restart needed. A reset-to-default script
|
||||
restores originals from the app bundle.
|
||||
|
||||
This table is the ciphertext **key inventory** and schema only. The never-browser /
|
||||
AES-GCM / `SLAB_AES_KEY` env policy lives in AGENTS.md §4; flow lives in ARCHITECTURE §5.
|
||||
|
||||
AES master key is an env var (`SLAB_AES_KEY`, 32 bytes base64). Never in the DB.
|
||||
Each `value_enc` = `nonce(12) || ciphertext`.
|
||||
|
||||
---
|
||||
|
||||
## sync_log
|
||||
|
||||
Append-only history. Not deleted on publish.
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | INTEGER PK AUTOINCREMENT | |
|
||||
| `slab_id` | TEXT FK | |
|
||||
| `sku` | TEXT | |
|
||||
| `woo_product_id` | INTEGER | |
|
||||
| `status` | TEXT | 'success' \| 'failed' |
|
||||
| `http_status` | INTEGER | |
|
||||
| `error` | TEXT | machine-readable code |
|
||||
| `detail` | TEXT | Woo error body |
|
||||
| `payload_hash` | TEXT | sha256 of Woo payload sent |
|
||||
| `created_at` | TEXT | |
|
||||
|
||||
---
|
||||
|
||||
## inference_log
|
||||
|
||||
Append-only audit.
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | INTEGER PK AUTOINCREMENT | |
|
||||
| `slab_id` | TEXT FK | |
|
||||
| `call` | TEXT | '1' \| '2' |
|
||||
| `request_payload` | TEXT | JSON of what was sent |
|
||||
| `response_payload` | TEXT | JSON of what came back |
|
||||
| `created_at` | TEXT | |
|
||||
@@ -1,199 +0,0 @@
|
||||
# Deployment Playbook (Docker Compose + Caddy)
|
||||
|
||||
Status: SPEC · env-agnostic · 2026-09-01 · SlabUploader
|
||||
|
||||
**Target:** any inventoried Docker host. Fill `deploy/INVENTORY.md` before bind.
|
||||
Variables: `APP_HOST`, `APP_HOSTNAME`, `FRONTEND_PORT`, `FASTAPI_PORT`.
|
||||
Health URL: `https://${APP_HOSTNAME}/api/health`.
|
||||
|
||||
> Gate A freeze (2026-08-31): hybrid client owns measure/crop SoT. Server-side measure/crop scaffolding is not done.
|
||||
> server ruler/pipeline as authoritative. Woo UAT = draft + `SLAB-UAT-*` on PROD.
|
||||
> Inference is **not** on the app host by default. It is a remote configurable endpoint.
|
||||
|
||||
**Historical lab example (non-normative):** TyUBUMini at `192.168.1.201` with hostname
|
||||
`slab.tyubumini.local` was one early candidate. The inventory worksheet determines the host.
|
||||
Use the inventory worksheet.
|
||||
|
||||
## 1. Host inventory (required before deployment)
|
||||
|
||||
Before deploying, fill `deploy/INVENTORY.md` (hard rule: inventory before execute):
|
||||
|
||||
1. `docker ps` — existing containers, published ports (avoid collisions with
|
||||
co-resident apps; bolt.diy is one known example of 8443-class port use).
|
||||
2. Caddy config location (host file or container) and existing site blocks.
|
||||
3. Free port choice for the compose stack (proposal: `18080` http, `18443` https —
|
||||
verify free on **this** host).
|
||||
4. Docker volume dir convention on the host.
|
||||
5. Reachability: confirm `${APP_HOSTNAME}` is reachable from the phone network
|
||||
(same LAN or Tailscale). Add DNS (Pi-hole/AdGuard or Tailscale MagicDNS) if needed:
|
||||
one A record → `${APP_HOST}` (LAN and/or Tailscale name).
|
||||
|
||||
Write the chosen values into `deploy/INVENTORY.md` and the host `.env` before compose up.
|
||||
|
||||
## 2. Repository layout (at scaffold)
|
||||
|
||||
```
|
||||
SlabUploader/
|
||||
├── AGENTS.md
|
||||
├── README.md
|
||||
├── docs/ # this plan set
|
||||
├── deploy/
|
||||
│ ├── docker-compose.yml # checked in; build contexts point at Phase 0 deliverables
|
||||
│ ├── Caddyfile.fragment # slab site block (merged into host Caddy)
|
||||
│ ├── INVENTORY.md # filled at Gate B on the designated host
|
||||
│ ├── .env.example # Phase 0 deliverable (SLAB_AES_KEY, APP_*, WOO_BASE_URL)
|
||||
│ └── backup.sh # Phase 0/6 deliverable (sqlite .backup + images tar)
|
||||
├── frontend/ # Phase 0 deliverable — SvelteKit app (not yet in tree on docs-only main)
|
||||
└── backend/ # Phase 0 deliverable — FastAPI app (not yet in tree on docs-only main)
|
||||
├── app/
|
||||
│ ├── main.py
|
||||
│ ├── (no happy-path pipeline SoT here) # hybrid: TECH-SPEC modules live in frontend/ or shared pure TS; backend = store/Woo/inference/U2Net stub
|
||||
│ ├── woo/ # Woo client, taxonomy, publish
|
||||
│ ├── inference/ # vision + content wrappers (toggleable)
|
||||
│ ├── prompts/ # call1.txt, call2.txt (shipped defaults)
|
||||
│ ├── api/ # routers (slabs, photos, pricing, taxonomy, settings)
|
||||
│ ├── db/ # schema.sql, models, migrations (alembic)
|
||||
│ └── security/ # AES-GCM settings encryption
|
||||
├── tests/ # pytest — unit (deterministic) + integration (woo)
|
||||
└── Dockerfile
|
||||
```
|
||||
|
||||
The layout above is the **scaffold target**. On docs-only `main`, `frontend/`, `backend/`, `deploy/.env.example`, and `deploy/backup.sh` are not yet in the tree. Compose still names those build contexts so Phase 0 does not invent paths.
|
||||
|
||||
## 3. docker-compose.yml (checked in)
|
||||
|
||||
Canonical file: `deploy/docker-compose.yml`. Placeholders: `deploy/.env.example` (Phase 0 deliverable).
|
||||
Compose `build.dockerfile` paths are **Phase 0 deliverable targets**, not proof the Dockerfiles exist yet.
|
||||
From **repo root** (after Phase 0 scaffolds exist):
|
||||
|
||||
```
|
||||
cp deploy/.env.example deploy/.env && chmod 600 deploy/.env
|
||||
# fill SLAB_AES_KEY, APP_HOSTNAME, WOO_BASE_URL (https:// only)
|
||||
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up -d
|
||||
```
|
||||
|
||||
Caddy site block: `deploy/Caddyfile.fragment` (merge into host Caddy). Compose
|
||||
service names `frontend` and `fastapi` must match that fragment.
|
||||
|
||||
**Store URL (`WOO_BASE_URL`):**
|
||||
|
||||
- Set in `deploy/.env` and injected into the FastAPI container at start.
|
||||
- **HTTPS only.** FastAPI must refuse missing / `http://` values at startup.
|
||||
- Not a Settings input and **not** a SQLite settings row.
|
||||
- Settings UI shows the URL as **read-only** text (which store this deploy hits).
|
||||
- Change store = edit `.env` + recreate the fastapi container.
|
||||
|
||||
Woo Application Password stays out of compose. Enter it in Settings; FastAPI stores it AES-GCM encrypted.
|
||||
|
||||
Conventions (house rules):
|
||||
|
||||
- `mem_limit` on services (not host-level tuning).
|
||||
- Services bind to 127.0.0.1 only; Caddy is the only public surface.
|
||||
- No `latest` tags on base images — pin versions.
|
||||
- `restart: unless-stopped`; compose is the supervisor (no systemd units).
|
||||
|
||||
## 4. Caddy (fragment)
|
||||
|
||||
Canonical file: `deploy/Caddyfile.fragment`. API must win over the frontend
|
||||
catch-all. Put `handle /api/*` **before** the frontend `handle` block:
|
||||
|
||||
```caddyfile
|
||||
{$APP_HOSTNAME} {
|
||||
tls internal # Caddy internal CA (or host-appropriate TLS)
|
||||
handle /api/* {
|
||||
reverse_proxy fastapi:8000
|
||||
}
|
||||
handle {
|
||||
reverse_proxy frontend:80 {
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- HTTPS enforced (http→https redirect automatic when using Caddy TLS).
|
||||
- If the host Caddy already serves a wildcard for this domain family, add this as a
|
||||
site block. Verify the cert is trusted on the phone.
|
||||
- LAN/Tailscale only — no public exposure for POC.
|
||||
|
||||
## 5. Secrets
|
||||
|
||||
| Secret | Where | Notes |
|
||||
|---|---|---|
|
||||
| `SLAB_AES_KEY` | `deploy/.env` (mode 600) → compose env | 32-byte base64; NEVER in the repo |
|
||||
| `WOO_BASE_URL` | `deploy/.env` → compose → FastAPI env | `https://` only; Settings **read-only** |
|
||||
| Woo WP username + application password | SQLite `settings` (AES-GCM) via Settings UI | dedicated low-priv WP user; not consumer keys |
|
||||
| Inference API key | SQLite `settings` (AES-GCM) via Settings UI | usually empty for local llama.cpp |
|
||||
| `.env.example` | repo | placeholders only, committed |
|
||||
|
||||
**Woo credential setup (once per store):**
|
||||
|
||||
1. Store must already be on **HTTPS**. WordPress will not offer Application
|
||||
Passwords over plain HTTP.
|
||||
2. Create a dedicated low-privilege WordPress user (shop manager, or custom role
|
||||
with product create/edit + media upload). Admin logins are not reused.
|
||||
3. Sign in as that user → **Users → Profile → Application Passwords** → generate
|
||||
a password for "SlabUploader".
|
||||
4. Enter the username + application password in the app Settings UI. FastAPI
|
||||
stores them AES-GCM encrypted. Browser never keeps them.
|
||||
5. Rotate by revoking the old application password in the WP profile and
|
||||
re-entering a new one in Settings, then `test-woo`.
|
||||
|
||||
Key rotation (AES): `SLAB_AES_KEY` change requires re-encrypting settings —
|
||||
provide `python -m app.security.rekey NEW_KEY` (reads old key from env
|
||||
`SLAB_AES_KEY_OLD`, decrypts, re-encrypts, updates). Documented in playbook §7.
|
||||
|
||||
## 6. Backup and restore
|
||||
|
||||
`deploy/backup.sh` (run via cron on the app host, e.g. daily 03:00):
|
||||
|
||||
```
|
||||
1. sqlite3 /data/slab.db ".backup /backups/slab-YYYYMMDD.db" # WAL-safe
|
||||
2. tar czf /backups/slab-images-YYYYMMDD.tgz -C /images .
|
||||
3. retain: 7 daily + 4 weekly; prune older
|
||||
4. log result to /var/log/slab-backup.log; alert (Hermes) on failure
|
||||
```
|
||||
|
||||
Prompt files live in the git repo (`backend/app/prompts/`) and are version-controlled;
|
||||
they do not need a separate backup. The `reset-to-default` script restores shipped
|
||||
defaults from the app bundle.
|
||||
|
||||
- Backup target: local dir first; mirror to an off-box share for safety (same pattern
|
||||
as other stacks on the host).
|
||||
- **Restore**: stop compose → restore DB file + untar images → start compose.
|
||||
Tested at least once during Phase 6 (UAT) before declaring backup done.
|
||||
|
||||
## 7. Operations runbook
|
||||
|
||||
| Task | Command / how |
|
||||
|---|---|
|
||||
| Deploy (first) | inventory §1 → `docker compose -f deploy/docker-compose.yml build` → `up -d` → Caddy reload → smoke §8 |
|
||||
| Update | `git pull` → `docker compose build fastapi frontend` → `up -d` (DB migrations run on start via alembic) |
|
||||
| Logs | `docker compose logs -f fastapi` / `frontend` |
|
||||
| Health | `curl -k https://${APP_HOSTNAME}/api/health` |
|
||||
| Rekey AES | §5 |
|
||||
| Rotate Woo creds | WP user profile → revoke old application password → new one → Settings UI → `POST /api/v1/settings/test-woo` |
|
||||
| Rotate inference key | Settings UI (if external) |
|
||||
| Edit a prompt | Edit the text file on host, no restart needed (read fresh each time) |
|
||||
| Rollback image | `git checkout <tag>` → rebuild → up -d; DB down-migrations provided for schema changes |
|
||||
| Reset one slab | delete its photos dir + `UPDATE slabs SET status='draft'` (admin script) |
|
||||
|
||||
## 8. Smoke test (after every deploy)
|
||||
|
||||
1. `GET https://${APP_HOSTNAME}/api/health` → ok (from phone over HTTPS once CA trust is proven)
|
||||
2. Settings: WP application password + `test-woo` ok; `woo_create_status=draft`; inference OFF for early gates
|
||||
3. Create a slab → upload test photos (fixture set) → poll to `ready`
|
||||
4. Verify bdft/price match the fixture's expected values (golden test; bdft = sqft × thickness)
|
||||
5. Publish test slab with SKU `SLAB-UAT-…` → slab may show local `published`; Woo product must be **draft**
|
||||
6. Leave or delete the Woo draft UAT product (never customer-visible). Final live publish is a non-UAT SKU after Ty review.
|
||||
|
||||
For the full human-run walk (host check → App Password → one `SLAB-UAT-*` prove → confirm →
|
||||
cleanup), see `docs/UAT-PRACTICE.md`.
|
||||
|
||||
## 9. Scaling path (not v1)
|
||||
|
||||
- Postgres when SQLite write contention appears (schema already portable).
|
||||
- Redis+arq when in-process queue shows lag.
|
||||
- GPU on the app host only if on-demand U2Net latency becomes a bottleneck. Keep CPU
|
||||
first. Never lower `output_px_min` below 1600; undersized source means retake, not a
|
||||
smaller min. RemBG is not part of the hybrid happy path.
|
||||
@@ -1,348 +0,0 @@
|
||||
# Implementation Plan
|
||||
|
||||
Status: SPEC · Gate A freeze 2026-08-31 · hybrid rewrite complete 2026-09-01 · SlabUploader
|
||||
|
||||
Phases 0–6 below are hybrid-aligned. Phase 2 remains a deferred stub only; offline PWA, OCR, ruler, and server happy-path measure/crop as SoT are not implemented.
|
||||
|
||||
The build plan a professional (or a fresh Hermes session) executes against. Each phase
|
||||
has: goal, deliverables, acceptance criteria (testable), and exit gate. Ordering is by
|
||||
dependency. Definition of done for every phase: code + tests + real
|
||||
execution output in the PR/commit message + docs updated.
|
||||
|
||||
Ground rules (from AGENTS.md):
|
||||
|
||||
- Deterministic core is unit-tested before any UI consumes it.
|
||||
- No feature without a passing test and shown output.
|
||||
- Inference stays toggleable; the full suite must pass with it disabled.
|
||||
- One phase = a reviewable, shippable increment.
|
||||
|
||||
Test specification: `docs/TEST-SPEC.md` — pyramid cases, phased by gate, affirmative only.
|
||||
|
||||
## Gates (human map)
|
||||
|
||||
This file is the only place that defines Gate meanings and how they map onto phases. Other docs may name a gate; they must not restate this table.
|
||||
|
||||
| Label | Human name | What it means |
|
||||
|---|---|---|
|
||||
| Gate A | Docs freeze | Product locks written into the repo |
|
||||
| Gate B | Run-host setup | Inventory the real host, deploy skeleton (`frontend/` + `backend/` + compose targets) |
|
||||
| Gate C | First draft listing | One Woo draft listing with inference OFF |
|
||||
|
||||
**Phase 0 = Gates A+B.** **Gate C = early Phase 1** claimable publish slice. Call 1/2 after Gate C is green, still inside POC. Phase 2 is a deferred stub; do not build it next after Phase 1.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Hybrid skeleton and client deterministic core (= Gates A+B)
|
||||
|
||||
Goal: scaffold the hybrid app and ship a **tested client-authoritative** TECH-SPEC
|
||||
pipeline (mask → axis → sqft/bdft → 3:4 PNG) plus a minimal FastAPI store/settings
|
||||
shell. No Woo publish, no inference, no offline/OCR/ruler.
|
||||
|
||||
**Gate A (docs):** AGENTS.md + this Phase 0 rewrite + review package locks (signed
|
||||
2026-08-31). **Gate B (infra/code):** items below.
|
||||
|
||||
Scope — in:
|
||||
|
||||
- Repo layout: `frontend/` (SvelteKit), `backend/` (FastAPI), `deploy/` stubs; docs stay SoT.
|
||||
- Client pure modules implementing TECH-SPEC: constants, sheet/chroma/black + sliders,
|
||||
mask confirm hooks, length axis, scale, 6" widths, sqft, **bdft = sqft × thickness_in**,
|
||||
pricing rec from species $/bdft, 3:4 PNG / 80% fill / ≥1600 guard (**no upscale**).
|
||||
- FastAPI: app factory, logging, config, `GET /api/health`, SQLite + alembic skeleton,
|
||||
settings stub with AES-GCM round-trip (secrets never returned on GET), draft store stub
|
||||
(accept client numbers + files — store only, no server-side recompute of SoT).
|
||||
- `deploy/docker-compose.yml`, `Caddyfile.fragment`, `.env.example` (placeholders only).
|
||||
- Unit tests for TECH-SPEC **TV-1 through TV-10** (esp. TV-3 bdft, TV-6/7 crop/no-upscale,
|
||||
TV-8 pricing, TV-10 rounding).
|
||||
- Fixture photo set for Ty Gate B review.
|
||||
|
||||
Phase 0 covers:
|
||||
|
||||
- Server happy-path pipeline / CLI that recomputes mask/crop/bdft as SoT: client is authoritative; server stores client-sent numbers only.
|
||||
- Real U2Net: stub OK; on-demand later. The one-photo server path stays in architecture.
|
||||
- Woo create/publish and live taxonomy sync: Phase 1. Species offered in UI, pricing seeds, and Call 1 are **exactly** Woo-synced species-category leaves (CONTENT-WOO §2.2 / AGENTS §6 / DATA-MODEL `woo_categories`).
|
||||
- Inference Call 1/2, LoRA: Phase 5.
|
||||
- Offline PWA, IndexedDB sync, OCR, ruler: Phase 2 (deferred stub).
|
||||
- Fake upscale / inventing pixels: undersized source warns and requires retake.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- `frontend/` scaffold + deterministic modules + unit tests TV-1…TV-10.
|
||||
- `backend/` FastAPI health + settings encryption + draft persistence stub + schema migration baseline.
|
||||
- `deploy/` compose + `.env.example` + Caddy fragment.
|
||||
- Shown output in PR/commit: printed TV-3, TV-6, TV-7 (no-upscale/retake), and TV-10 on **real fixtures**.
|
||||
|
||||
Acceptance:
|
||||
|
||||
- Gate B: client (or shared pure) tests green for TECH-SPEC vectors; bdft identity holds
|
||||
(no `/12`); undersized source warns and refuses fake upscale; rounding matches TV-10.
|
||||
- `GET https://${APP_HOSTNAME}/api/health` up in compose after `deploy/INVENTORY.md` is filled and Caddy is merged.
|
||||
- Settings AES round-trip; secret fields never appear in GET.
|
||||
- Draft can store client-uploaded originals + PNGs + numbers without server recompute.
|
||||
- Coverage target: deterministic modules ≥ 95% where practical; property checks
|
||||
(bdft monotonic in thickness/sqft; fill band; no upscale path).
|
||||
|
||||
Exit gate: Ty confirms Gate B math/image prep shown output on real fixtures; health +
|
||||
encrypted settings + draft store stub demonstrated (curl or thin UI).
|
||||
|
||||
**Next:** Gate C = early Phase 1 claimable publish — online hybrid capture + Woo **draft**
|
||||
+ `SLAB-UAT-*` on the configured store, inference OFF. Call 1/2 after Gate C, still inside POC.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Gate C claimable path, then full API surface (rewritten)
|
||||
|
||||
### Early Phase 1 / Gate C slice (claimable first draft listing)
|
||||
|
||||
Goal: one Woo **draft** listing Ty can open in store admin, with inference **OFF**.
|
||||
Online hybrid capture only. No OCR, ruler, or offline.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Online capture of 1–5 inventory photos (no airplane-mode requirement).
|
||||
- Client sheet + **four knobs inline** on capture (live re-run, mask overlay on
|
||||
source photo); user confirm; length axis overlay + confirm. No U2Net control.
|
||||
- Client sqft / bdft / 6" widths; 3:4 transparent PNG prep per TECH-SPEC.
|
||||
- Manual SKU, length, thickness; manual taxonomy as needed for one listing.
|
||||
- Calibrated draft upload: originals + processed PNGs + client-sent numbers. Server
|
||||
stores only (OPENAPI POST returns `status: calibrated`).
|
||||
- Woo **draft** create with SKU prefix `SLAB-UAT-*` on the configured PROD store.
|
||||
Honor AGENTS Woo safety: `SLAB-UAT-*` forces draft even if Settings say publish.
|
||||
- Inference remains OFF for this slice. Full suite still green with inference disabled.
|
||||
|
||||
Acceptance:
|
||||
|
||||
- Ty captures a real slab on phone (online), adjusts any mask knob and sees a fresh
|
||||
overlay without leaving the screen, confirms mask + axis, sees client numbers.
|
||||
- Species picker offers **only** Woo-synced species (after test-woo / sync).
|
||||
- One `SLAB-UAT-*` product appears in Woo admin as **draft** with correct SKU/price/images
|
||||
enough for Ty to open and inspect.
|
||||
- No Call 1/Call 2 required. No offline, OCR, ruler, or U2Net path exercised.
|
||||
- Duplicate SKU → stop with field-level recovery; no second product.
|
||||
|
||||
Exit gate: Ty opens one draft listing in Woo admin. Gate C is green.
|
||||
|
||||
### Phase 1 remainder (API / settings / taxonomy cache)
|
||||
|
||||
Goal: full slab CRUD + photo upload + settings + taxonomy cache read, still hybrid.
|
||||
No server happy-path math. No `processing` slab status.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Routers per OPENAPI: slabs (CRUD + upload + poll), photos (serve), pricing-rules,
|
||||
settings (AES-GCM + test stubs), taxonomy (cache read/write + manufactured
|
||||
`taxonomy_anchor` / `taxonomy_last_sync_at`).
|
||||
- Optimistic concurrency (`client_rev` / `server_rev`, 409 paths).
|
||||
- Status machine only: `draft → calibrated → ready → publishing → published | failed`.
|
||||
Job queue only for publish and inference (later). U2Net-on-demand is deferred from POC. Never for measure/crop.
|
||||
- Integration tests (httpx TestClient): create calibrated → poll → ready (manual fields);
|
||||
revision conflict; duplicate SKU; settings encryption round-trip (secret never returned);
|
||||
taxonomy anchor bumps on stored-subset change and stays put on no-op sync.
|
||||
|
||||
Acceptance:
|
||||
|
||||
- OPENAPI.md endpoints implemented; a generated `openapi.yaml` matches the doc.
|
||||
- Integration tests green; secrets never leak into any GET response (asserted).
|
||||
- `docker compose up` (backend + a throwaway frontend stub) serves the API.
|
||||
- PUT stores client-sent derived fields; does not recompute sqft/bdft/widths as SoT.
|
||||
- Taxonomy: anchor advances only on real stored-subset change; client re-pulls only
|
||||
when anchor is newer; `test-woo` always resyncs; publish respects the 1h threshold.
|
||||
|
||||
Exit gate: Ty drives the API with curl through a full calibrated → ready cycle (manual).
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Deferred: offline PWA / OCR / ruler (stub only)
|
||||
|
||||
**Deferred post-POC.** The online-only MVP does not implement offline capture.
|
||||
|
||||
Capture UX for POC lives in early Phase 1 / Gate C (online hybrid). See AGENTS.md §2.
|
||||
|
||||
Offline PWA, OCR, and ruler detection are deferred to a later product decision:
|
||||
|
||||
- Workbox service worker, IndexedDB draft sync, airplane-mode capture
|
||||
- Tesseract.js OCR for SKU
|
||||
- OpenCV.js ruler / scale detection
|
||||
|
||||
No airplane-mode acceptance. No OCR or ruler exit gate in POC.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Frontend: enrich, review, publish UI (rewritten)
|
||||
|
||||
Goal: online review + publish UI on top of Gate C calibrated drafts. Hybrid only.
|
||||
Client already owns mask/numbers/PNGs. This phase does not re-measure on the server.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Review screen after calibrated upload: all fields editable (length, thickness, SKU,
|
||||
widths/sqft/bdft shown as client-computed with manual override paths, species and
|
||||
wood categories, five attributes, fig-*/feat-* tags, price with species $/bdft
|
||||
recommendation, title/short/description).
|
||||
- Show client-processed transparent PNGs (and originals while retained). No server
|
||||
re-crop UI as SoT.
|
||||
- Inference UI (only meaningful after Gate C and when `inference_enabled`): Call 1
|
||||
results with confidence. **≥ 0.7** (configurable default) → pre-fill mutable
|
||||
fields. **< 0.7** → leave empty; inline nudges. Continue/ready is blocked until
|
||||
the **full ready set** is filled — not species + wood category + figure alone.
|
||||
Canonical lock (AGENTS §7 / DATA-MODEL slabs **ready**): SKU, length, thickness,
|
||||
client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category,
|
||||
1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness store band
|
||||
(round-up), 1 moisture (default kiln-dried; not inferred), price. feat-* 0+.
|
||||
Title/description may be typed, generated, or templated at publish. Presentation:
|
||||
`docs/UX.md`. "Generate text" triggers Call 2; never auto.
|
||||
- Capture: four knobs on the mask screen with live re-run. No U2Net control in POC.
|
||||
- Publish button (online-only), poll `publishing` → `published` | `failed`, surface
|
||||
error detail from sync_log.
|
||||
- Settings UI: WP username + application password + test-woo, inference endpoint +
|
||||
test (vision + portable-context probe), pricing rules editor, brand voice/GEO,
|
||||
`woo_create_status`. Store URL read-only from `WOO_BASE_URL`. Sheet/slider prefs
|
||||
stay in client localStorage. Prompts are server files, not UI settings.
|
||||
- Secrets never appear in GET settings responses (masked `*_configured` only).
|
||||
|
||||
Acceptance:
|
||||
|
||||
- Browser round-trip: online capture → mask/axis confirm → calibrated upload →
|
||||
review → edit → publish → local `published` (Woo mock in tests; real store Phase 6).
|
||||
- Inference OFF → full manual taxonomy + content path works; no inference network calls.
|
||||
- Field overrides persist across poll/refresh (asserted).
|
||||
- No offline/IndexedDB requirement. No OCR/ruler UI.
|
||||
|
||||
Exit gate: Ty publishes a test slab to the real store as a **Woo draft** (`SLAB-UAT-*`).
|
||||
(Gate A lock: not pending/published for UAT.)
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — WooCommerce integration (rewritten)
|
||||
|
||||
Goal: production Woo sync, taxonomy, dedupe, logging. Browser never calls Woo.
|
||||
Media bytes are client-processed **PNGs**. Safety policy from AGENTS §5.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Woo client (httpx, Basic auth with WP username + application password, timeouts),
|
||||
taxonomy sync into cache tables, auto-assign per CONTENT-WOO §2.3 (categories +
|
||||
five attributes + fig-*/feat-* tags only). No WooCommerce consumer keys.
|
||||
- Media upload of processed PNG inventory photos; product create via `woo_create_status`
|
||||
(default **draft**). If SKU matches `SLAB-UAT-*`, force Woo **draft** even when
|
||||
Settings say publish.
|
||||
- Dedupe by SKU before create (any Woo status); `409 duplicate_sku` with field recovery
|
||||
paths (edit SKU / open existing); no edit-same-SKU path in MVP.
|
||||
- `422 stale_field` recovery with current options from cache (CONTENT-WOO §2.6).
|
||||
- `sync_log` with payload_hash; on success set local `published`, purge originals +
|
||||
processed images on server.
|
||||
- `POST /api/v1/admin/taxonomy/sync` against the real store; manufactured anchor.
|
||||
- Integration tests against a Woo mock (respx) for success + error + duplicate +
|
||||
stale-field paths.
|
||||
- Partial-failure handling (orphaned media noted, per CONTENT-WOO §2.6).
|
||||
|
||||
Acceptance:
|
||||
|
||||
- Real UAT publish: product appears in store admin as **draft** under `SLAB-UAT-*`,
|
||||
correct SKU/price/PNG images/category/tags/attributes; `woo_product_id` stored;
|
||||
`sync_log` written with payload_hash.
|
||||
- Duplicate SKU publish → 409 mapped to SKU field, no second product created.
|
||||
- Stale taxonomy value → 422 on that field with current options; draft retained.
|
||||
- Woo error (bad creds / 500) → slab `failed` with detail; retry path works.
|
||||
- All Woo integration tests green (mock + one live smoke).
|
||||
|
||||
Exit gate: Ty verifies a real **Woo draft** `SLAB-UAT-*` product in the store is correct.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Inference (vision + optional content) (rewritten)
|
||||
|
||||
Goal: scoped, toggleable inference **after Gate C is green**, still inside POC.
|
||||
Does not gate publish. Full suite must pass with inference OFF.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Call 1 (vision) proxy: **all inventory photos** downscaled to 1024 + Woo taxonomy
|
||||
snapshot + user metadata; OpenAI-compatible endpoint; model constrained to cached
|
||||
taxonomy **from the Woo cache only**; confidence threshold **0.7** (configurable
|
||||
default; not a POC Settings slider). Auto-run on calibrated create only if
|
||||
`inference_enabled`. Not top-down-only.
|
||||
- Apply AGENTS §6 prefill: ≥ threshold → pre-fill mutable species/categories/attributes/
|
||||
tags; < threshold → those fields stay empty. Call 1 is assist only and does not
|
||||
define ready. Ready/publish requires the **full ready set** in AGENTS §7 /
|
||||
DATA-MODEL (SKU, length, thickness, client sqft/bdft/widths, ≥1 inventory PNG,
|
||||
exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag,
|
||||
≥1 grade, thickness store band round-up, 1 moisture default kiln-dried not
|
||||
inferred, price; feat-* 0+). Species + wood category + figure is not the gate.
|
||||
Presentation: `docs/UX.md`.
|
||||
- Call 2 (text) proxy: never auto. Portable Call 1 context (full resend default).
|
||||
LLM prose only; templates inject deterministic numbers. See `docs/PROMPTS.md`.
|
||||
- `test-inference` endpoint (vision + portable vs stateful probe). Fail closed if
|
||||
neither Call 1→Call 2 path works.
|
||||
- Feature flags; `inference_log` audit rows; prompt files read fresh each call.
|
||||
- No numeric/dimension invention by the LLM. LoRA deferred.
|
||||
|
||||
Acceptance:
|
||||
|
||||
- Local vision model configured: ≥ 0.7 fields pre-fill and remain editable; user
|
||||
override sticks.
|
||||
- Below 0.7: fields stay empty; UI blocks continue/ready until the full AGENTS §7
|
||||
/ DATA-MODEL ready set is filled (asserted). Species + wood category + figure
|
||||
is not the ready definition.
|
||||
- No doc/code path auto-fills below-threshold guesses or treats inference as a
|
||||
publish gate.
|
||||
- Inference OFF: app works end-to-end; tests assert zero calls to the inference endpoint.
|
||||
- Audit payloads present after a call; prompt file edits apply without server restart.
|
||||
- Gate C path remains green with inference OFF.
|
||||
|
||||
Exit gate: Ty runs species detection on 3 real slabs; results acceptable or manually
|
||||
corrected (that is the design).
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — Deployment, UAT, hardening (rewritten, online only)
|
||||
|
||||
Goal: production deploy on the **inventoried** host + online user acceptance tests.
|
||||
|
||||
Deliverables:
|
||||
|
||||
- Host inventory pass: complete `deploy/INVENTORY.md` per DEPLOYMENT §1 → final compose + Caddyfile.
|
||||
- Deploy to `https://${APP_HOSTNAME}` from inventory; backup/restore runbook executed once (restore tested).
|
||||
- **UAT suite** for the hybrid online path: scripted real slabs (≥3 species, ≥1 cathedral,
|
||||
≥1 manual-width path, ≥1 duplicate-SKU attempt) with expected bdft/price/image-fill
|
||||
asserted. **No** offline capture, OCR, or ruler cases in POC UAT.
|
||||
- Performance: client measure/crop budgets on device; optional U2Net-on-demand latency.
|
||||
No server happy-path “normalization 3–5s” budget. No OCR 1–2s budget.
|
||||
- Docs: README, runbook, key-rotation verified.
|
||||
|
||||
Acceptance (measured):
|
||||
|
||||
- E2E capture→publish on iPhone, Android, and PC browsers (desktop Chrome/Edge/Firefox) works (online).
|
||||
- Manual length override recalculates widths/sqft/bdft correctly (UAT asserts).
|
||||
- Client crop: slab ~80% frame in ≥95% of UAT photos; shorter side ≥1600 when source allows.
|
||||
- Woo product created with processed PNG images + correct taxonomy.
|
||||
- Deterministic functions unit-tested; inference calls logged for audit when used.
|
||||
- Backup restore demonstrated once.
|
||||
|
||||
Exit gate: Ty signs off on UAT results; v1 declared done.
|
||||
|
||||
---
|
||||
|
||||
## Risks and mitigations
|
||||
|
||||
| Risk | Impact | Mitigation |
|
||||
|---|---|---|
|
||||
| Green-sheet color varies | bad mask, wrong sqft | chroma-key / black threshold + inline knobs + live re-run; retake; U2Net deferred from POC; never drop `output_px_min` below 1600 |
|
||||
| No vision model available at deploy | species inference off | inference is toggleable; manual species/character fully functional — v1 not blocked |
|
||||
| Woo partial publish (media up, product POST fails) | orphaned images, confusing state | sync_log + retained images for retry; manual cleanup note; no auto-delete |
|
||||
| Local vision endpoint not up | inference off | configurable endpoint; deploy-time config; app works without it |
|
||||
| SQLite contention under concurrent polls | slowdown | single owner, low volume; Postgres path documented |
|
||||
| Host port/Caddy collision with co-resident apps (e.g. bolt.diy) | deploy conflict | Phase 0/6 inventory worksheet before any port bind |
|
||||
|
||||
Ruler detection is **deferred** with offline/OCR (Phase 2 stub). Manual length is
|
||||
authoritative for POC. Ruler confidence is not a POC risk row.
|
||||
|
||||
---
|
||||
|
||||
## Definition of Done (v1, project-level)
|
||||
|
||||
- All 6 phases exit-gated by Ty (Phase 2 remains deferred stub unless product reopens it).
|
||||
- Hybrid online acceptance met (measured in Phase 6 UAT). Gates A/B/C meanings match AGENTS §0b.
|
||||
- `pytest` + integration + UAT green; inference-off path green.
|
||||
- Deployed on the inventoried host (`APP_HOSTNAME` from `deploy/INVENTORY.md`), HTTPS, backed up, restore tested, runbook + key-rotation verified.
|
||||
- Repo on gitea-atd (`Ty_Tech/SlabUploader`) is source of truth; docs current.
|
||||
- `docs/archive/PRD-2026-08.txt` is frozen history only; live docs are the implementation SoT.
|
||||
@@ -1,328 +0,0 @@
|
||||
# OpenAPI Contract — SvelteKit Client ↔ FastAPI
|
||||
|
||||
Status: SPEC · 2026-08-27 · SlabUploader
|
||||
Base path: `/api/v1`. All requests/responses JSON unless noted.
|
||||
All timestamps UTC ISO-8601.
|
||||
|
||||
## Conventions
|
||||
|
||||
### Auth
|
||||
No client auth. Trusted LAN/Tailscale + HTTPS.
|
||||
|
||||
### Errors
|
||||
Uniform envelope:
|
||||
```json
|
||||
{ "error": { "code": "string", "message": "string", "detail": "object|null" } }
|
||||
```
|
||||
- `400 validation` — payload failed validation.
|
||||
- `404 not_found` — unknown slab/photo/setting.
|
||||
- `409 revision_conflict` — client_rev/server_rev mismatch. `detail` carries `current_server_rev`.
|
||||
- `409 duplicate_sku` — SKU already exists in WooCommerce, any status (draft, private, publish, etc.).
|
||||
- `422 unpublishable` — slab not in a publishable state or missing required field.
|
||||
- `502 woo_error` — WooCommerce rejected the request. `detail` carries Woo error body.
|
||||
- `500 internal` — unexpected.
|
||||
|
||||
### Revisions
|
||||
Create/update carry `client_rev`. Server echoes `server_rev`. Client stores `server_rev` and sends it back on the next update. Mismatch → `409 revision_conflict`.
|
||||
|
||||
### Photos
|
||||
Uploaded as `multipart/form-data`. Max 40 MB per request. Two fields per photo:
|
||||
- `files[]` — the original image file
|
||||
- `meta[]` — JSON `{ kind: "inventory", role: "topdown"|"extra", seq: 1 }`
|
||||
|
||||
### Pagination
|
||||
Lists are small (single owner, slab-by-slab). Lists return full arrays.
|
||||
|
||||
### API Version
|
||||
URL is `/api/v1`. Breaking changes bump to `/api/v2`.
|
||||
|
||||
---
|
||||
|
||||
## Schemas
|
||||
|
||||
### SlabCreate
|
||||
```jsonc
|
||||
{
|
||||
"id": "uuid (client-generated)",
|
||||
"sku": "string 3..24 [A-Z0-9-]",
|
||||
"length_in": 96.0, // 1/8" step
|
||||
"thickness_in": 1.5, // 1/8" step
|
||||
"sqft": 0.64, // computed by client
|
||||
"bdft": 0.96, // computed by client
|
||||
"width_min_in": 14.0,
|
||||
"width_max_in": 22.0,
|
||||
"width_avg_in": 18.2,
|
||||
"species_id": 42, // → woo_categories (leaf)
|
||||
"wood_category_ids": [15, 23], // JSON array → woo_categories (leaf, 1+)
|
||||
"edge_type_term_id": 8, // → woo_attribute_terms
|
||||
"figure_term_ids": [3], // JSON array → woo_attribute_terms (1+)
|
||||
"grade_term_ids": [7], // JSON array → woo_attribute_terms (1+)
|
||||
"thickness_term_id": 12, // → woo_attribute_terms (round-up)
|
||||
"moisture_term_id": 5, // → woo_attribute_terms (defaults kiln-dried)
|
||||
"fig_tag_ids": [99], // JSON array → woo_tags (fig-*, 1+)
|
||||
"feat_tag_ids": [42], // JSON array → woo_tags (feat-*, 0+)
|
||||
"price_per_bdft": 12.50, // from pricing_rules
|
||||
"price": 12.00, // 2 decimals
|
||||
"price_source": "recommendation|override|null",
|
||||
"title": "string|null",
|
||||
"short_title": "string|null",
|
||||
"description": "string|null",
|
||||
"content_source": "manual|llm|null",
|
||||
"client_rev": 1
|
||||
}
|
||||
```
|
||||
Photos come as multipart `files[]` + `meta[]` alongside this JSON (wrapped in a multipart request where one part is the JSON and the others are the files).
|
||||
|
||||
### Slab (read model)
|
||||
All `SlabCreate` fields (resolved) plus:
|
||||
`status`, `species_confidence`, `woo_product_id`, `published_at`,
|
||||
`server_rev`, `created_at`, `updated_at`, `photos: [PhotoRead]`,
|
||||
`inference_status: null|inferring|done|failed`, `inference_error: string|null`.
|
||||
|
||||
### PhotoRead
|
||||
```jsonc
|
||||
{ "id": "uuid", "kind": "inventory", "role": "topdown|extra",
|
||||
"seq": 1, "original_url": "/api/v1/slabs/{id}/photos/{pid}/original",
|
||||
"processed_url": "/api/v1/slabs/{id}/photos/{pid}/processed|null" }
|
||||
```
|
||||
|
||||
### InferenceCall1Result (returned by infer-taxon)
|
||||
|
||||
Taxonomy fields are Woo IDs from the synced cache. Character/inclusions/voids/checks
|
||||
are free-text observations; the server maps them to Woo `feat-*` product tags after
|
||||
the call returns. WooCommerce is the authoritative source for `feat-*` definitions.
|
||||
|
||||
```jsonc
|
||||
{ "species_id": 42, "species_confidence": 0.92,
|
||||
"wood_category_ids": [15, 23],
|
||||
"edge_type_term_id": 8,
|
||||
"figure_term_ids": [3], "figure_confidence": 0.87,
|
||||
"grade_term_ids": [7], "grade_confidence": 0.75,
|
||||
"character": { "type": "knot", "severity": "minor" },
|
||||
"inclusions": { "type": "bark pocket", "severity": "none" },
|
||||
"voids": "none",
|
||||
"checks": "none",
|
||||
"wood_categories": [ { "name": "Live edge", "confidence": 0.95 },
|
||||
{ "name": "Bowl blank", "confidence": 0.82 },
|
||||
{ "name": "Table slab", "confidence": 0.61 } ] }
|
||||
```
|
||||
|
||||
### InferenceCall2Result (returned by infer-content)
|
||||
```jsonc
|
||||
{ "title": "string", "short_title": "string", "description": "string" }
|
||||
```
|
||||
|
||||
### PriceRule
|
||||
```jsonc
|
||||
{ "id": "uuid", "species": "string", "price_per_bdft": 12.50,
|
||||
"created_at": "timestamp", "updated_at": "timestamp" }
|
||||
```
|
||||
|
||||
### SettingsView (read; secrets masked)
|
||||
```jsonc
|
||||
{ "woo_base_url": "https://www.whidbeywoodstore.com", // WOO_BASE_URL env; read-only
|
||||
"woo_wp_username": "slab-uploader", // non-secret identity; password never returned
|
||||
"woo_credentials_configured": true,
|
||||
"inference_base_url": "http://192.168.1.202:8080/v1",
|
||||
"inference_model": "<model>", "inference_enabled": true,
|
||||
"content_llm_enabled": false,
|
||||
"brand_voice": "...", "geo_context": "...",
|
||||
"woo_create_status": "draft",
|
||||
"aspect_ratio": "3:4", "output_px": 1600, "output_px_min": 1600,
|
||||
"fill_target": 0.80 }
|
||||
```
|
||||
Secrets (application password, inference API key) are never returned. Only a
|
||||
`*_configured` boolean. Woo auth is WordPress Application Passwords
|
||||
(`woo_wp_username` + `woo_app_password` write-only), not consumer keys.
|
||||
Sheet/slider prefs are client localStorage only in POC (not in SettingsView).
|
||||
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
### Health & meta
|
||||
- `GET /api/health` → `{ "status":"ok", "version":"...", "woo_reachable": bool }` (canonical deploy/smoke path; may also be exposed as `/api/v1/health`)
|
||||
- `GET /api/v1/meta` → `{ "version":"...", "templates_configured": bool }`
|
||||
|
||||
### Slabs
|
||||
- `POST /api/v1/slabs` — Create a calibrated draft. Body: multipart with `data` (SlabCreate JSON) + `files[]` (photos) + `meta[]` (photo metadata).
|
||||
- Returns `201` `Slab` with `status: "calibrated"` (mask + axis confirmed; client-sent sqft/bdft/widths stored).
|
||||
- Server auto-runs Call 1 **only if** `inference_enabled` is true. `inference_status` becomes `inferring`, then `done`/`failed`.
|
||||
- After Call 1, persist inferred values onto the slab **only** for fields with confidence ≥ 0.7. Below 0.7 leave those columns null so GET does not prefill.
|
||||
- `409 duplicate_sku` if SKU already exists in Woo, any status (payload as PUT).
|
||||
- `GET /api/v1/slabs` → `200` `[Slab]` (most recent first).
|
||||
- `GET /api/v1/slabs/{id}` → `200` `Slab` / `404`.
|
||||
- Also used as the poll endpoint for inference and publish. Long-running ops set status to `inferring`/`publishing`; client backs off (1s, 2s, 4s, cap 10s).
|
||||
- `PUT /api/v1/slabs/{id}` — Update draft fields. Body: partial `SlabCreate` (any subset of editable fields + `client_rev`).
|
||||
- Server **stores** client-sent derived fields (`sqft`, `bdft`, widths). It may validate shape and ranges. It must **not** recompute mask, sqft, bdft, or widths as source of truth. Client re-runs TECH-SPEC math and PUTs the new numbers.
|
||||
- `409 revision_conflict`.
|
||||
- `409 duplicate_sku` → `{ "field":"sku", "code":"duplicate_sku", "message":"...", "actions":["edit_sku","open_existing"], "woo_product_id": "...?", "woo_admin_url": "...?" }`. `open_existing` is required even if lookup failed (then omit id/url). Never show the code. Presentation: `docs/UX.md`.
|
||||
- `422` stale/invalid field → `{ "field":"species_id", "code":"stale_field", "message":"...", "actions":[], "options": [...] }` after a submission-time taxonomy refresh. Draft: phone form + server slab `failed` (retryable).
|
||||
- `412` validation module stale → `{ "code":"validation_module_stale", "module": { "hash":"...", "rules":[] } }`. Not a 409.
|
||||
- `DELETE /api/v1/slabs/{id}` → `204`. Soft: only unpublished drafts. Published slabs cannot be deleted from the app.
|
||||
|
||||
### Photo operations
|
||||
- `POST /api/v1/slabs/{id}/u2net/{pid}` — **post-POC.** "Try harder." Server runs U2Net on this one photo, returns a better mask. The contract is preserved but not implemented or exposed in Gate C / first listing.
|
||||
- Returns `202` `{ mask_url: "..." }`. Client uses the mask to re-compute area/widths locally.
|
||||
- `404` if photo not found.
|
||||
- `GET /api/v1/slabs/{id}/photos/{pid}/original` → `image/*` (original, while retained).
|
||||
- `GET /api/v1/slabs/{id}/photos/{pid}/processed` → `image/*` (processed PNG, while retained).
|
||||
- After publish, both → `410 Gone`.
|
||||
|
||||
### Inference
|
||||
- `POST /api/v1/slabs/{id}/infer-taxon` — Trigger or retry Call 1 (vision).
|
||||
- Server reads the Call 1 prompt file fresh, uses cached taxonomy + original
|
||||
photos downscaled to 1024px + user metadata, and sends to the configured
|
||||
vision endpoint.
|
||||
- Returns `202` `{ "status": "inferring" }`. Client polls `GET /api/v1/slabs/{id}` for results.
|
||||
- Timeout > 45s → `504 gateway_timeout` with error detail.
|
||||
- `POST /api/v1/slabs/{id}/infer-content` — Trigger Call 2 (text).
|
||||
- Server reads the Call 2 prompt file fresh. Default: **resend full Call 1
|
||||
context** (prompt + assistant JSON + confirmed vs inferred labels). Use
|
||||
`previous_response_id` only if test-inference reported stateful support.
|
||||
Per-slab thread; delete on publish or abandon.
|
||||
- Taxonomy + deterministic numbers + brand/GEO; LLM prose then templates.
|
||||
- Requires `test-inference` `ok: true`. Else `422` (not connected / not portable).
|
||||
- Returns `202` `{ "status": "inferring" }`. Client polls for results.
|
||||
- Timeout > 45s → `504` with error detail.
|
||||
|
||||
### Publish
|
||||
- `POST /api/v1/slabs/{id}/publish` — Publish to WooCommerce.
|
||||
- Pre-conditions: status `ready` with SKU, length_in, thickness_in, client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness_term_id, 1 moisture, price. Else `422 unpublishable` with field keys. UI maps, no raw code.
|
||||
- Dedupe: if SKU already exists in Woo under any status → `409 duplicate_sku` (same payload as PUT).
|
||||
- Stale Woo value → `422 stale_field` as above. Draft stays on the phone.
|
||||
- Returns `202` `{ "status": "publishing" }`. Client polls.
|
||||
- Woo failure → slab `failed`, `sync_log` written, poll returns `502 woo_error`.
|
||||
- Success → slab `published`, `woo_product_id` set, images purged, draft row deleted.
|
||||
|
||||
### Taxonomy
|
||||
- `GET /api/v1/admin/taxonomy` → `200` taxonomy grouped by kind:
|
||||
```jsonc
|
||||
{ "categories": [...], "attributes": [{ name, slug, terms: [...] }],
|
||||
"tags": [...],
|
||||
"taxonomy_anchor": "ISO-8601",
|
||||
"taxonomy_last_sync_at": "ISO-8601" }
|
||||
```
|
||||
Client re-pulls iff `taxonomy_anchor` advanced. Species/attribute/tag
|
||||
lists here are the **only** legal options for UI pickers and Call 1.
|
||||
- `POST /api/v1/admin/taxonomy/sync` → `200` `{ "categories": n, "attributes": n, "tags": n, "taxonomy_anchor": "...", "taxonomy_last_sync_at": "..." }`.
|
||||
- Pulls from Woo, rebuilds the cache. Always set `taxonomy_last_sync_at` on success. Bump `taxonomy_anchor` **only** if stored-subset hash changed. `502 woo_error` on failure; previous cache retained.
|
||||
|
||||
### Pricing
|
||||
- `GET /api/v1/admin/pricing` → `[PriceRule]`
|
||||
- `POST /api/v1/admin/pricing` → `201` `PriceRule`
|
||||
- `PUT /api/v1/admin/pricing/{id}` → `200` `PriceRule`
|
||||
- `DELETE /api/v1/admin/pricing/{id}` → `204`
|
||||
|
||||
### Settings
|
||||
- `GET /api/v1/settings` → `200` `SettingsView`
|
||||
- `PUT /api/v1/settings` — Update settings. Body: partial `{ key: value }`.
|
||||
- `woo_base_url` is **not** writable (ignore or `422`). SoT is `WOO_BASE_URL`
|
||||
env (HTTPS, compose). GET still returns it for read-only Settings text.
|
||||
- Woo credential keys: `woo_wp_username` (plain) and `woo_app_password`
|
||||
(write-only; AES-GCM at rest). Reject any payload that still sends
|
||||
`woo_consumer_key` / `woo_consumer_secret`.
|
||||
- Secrets re-encrypted server-side. `200` `SettingsView` returned (password
|
||||
never echoed).
|
||||
- `POST /api/v1/settings/test-woo` → `200` `{ "ok": bool, "detail": "...", "taxonomy_anchor": "...", "taxonomy_last_sync_at": "..." }`
|
||||
- Uses stored username + application password over HTTPS Basic Auth against
|
||||
`WOO_BASE_URL` REST v3. Fails closed if credentials missing or URL is not https.
|
||||
- On success, **always** run a taxonomy resync (set last_sync; bump anchor only if hash changed).
|
||||
- `POST /api/v1/settings/test-inference` → `200` `{ "ok": bool, "mode": "stateful"|"stateless"|"fail", "vision_capable": bool, "detail": "..." }`
|
||||
- Two-turn probe. Default Call 1→Call 2 path is full resend; never require `previous_response_id`.
|
||||
- `mode=fail` **blocks Call 2 enablement only**. Gate C inference-OFF still works.
|
||||
- `GET /api/v1/validation/module` → `200` `{ "hash": "...", "rules": [ ... ] }`
|
||||
- Shared FastAPI module (UI + Call 2). Client caches it. Submit sends `validation_hash`.
|
||||
- Match → validate. Mismatch → **412** + fresh module. SKU `[A-Z0-9-]{3,24}`; titles UTF-8 + Woo maxLength.
|
||||
|
||||
---
|
||||
|
||||
## Request/response examples
|
||||
|
||||
### Create a slab (multipart)
|
||||
```
|
||||
POST /api/v1/slabs
|
||||
Content-Type: multipart/form-data; boundary=---
|
||||
|
||||
---
|
||||
Content-Disposition: form-data; name="data"
|
||||
Content-Type: application/json
|
||||
|
||||
{ "id":"9f1c...","sku":"BW-0042","length_in":96.0,"thickness_in":1.5,
|
||||
"sqft":0.64,"bdft":0.96,"width_min_in":14.0,"width_max_in":22.0,
|
||||
"width_avg_in":18.2,"species_id":42,"wood_category_ids":[15,23],
|
||||
"edge_type_term_id":8,"figure_term_ids":[3],"grade_term_ids":[7],
|
||||
"thickness_term_id":12,"moisture_term_id":5,"fig_tag_ids":[99],
|
||||
"price_per_bdft":12.50,"price":12.00,"price_source":"recommendation",
|
||||
"title":null,"short_title":null,"description":null,
|
||||
"content_source":null,"client_rev":1 }
|
||||
|
||||
---
|
||||
Content-Disposition: form-data; name="files[]"; filename="topdown.jpg"
|
||||
Content-Type: image/jpeg
|
||||
|
||||
<binary>
|
||||
---
|
||||
Content-Disposition: form-data; name="meta[]"
|
||||
Content-Type: application/json
|
||||
|
||||
{ "kind": "inventory", "role": "topdown", "seq": 1 }
|
||||
---
|
||||
```
|
||||
Response: `201`
|
||||
```json
|
||||
{ "id":"9f1c...","sku":"BW-0042","status":"calibrated",
|
||||
"inference_status":"inferring","server_rev":1,"photos":[...],... }
|
||||
```
|
||||
|
||||
### Call 1 completes (poll)
|
||||
```
|
||||
GET /api/v1/slabs/9f1c...
|
||||
→ 200 { "status":"calibrated","inference_status":"done",
|
||||
"species_id":42,"species_confidence":0.92,
|
||||
"wood_category_ids":[15],"edge_type_term_id":8,
|
||||
"figure_term_ids":[3],"grade_term_ids":[7],
|
||||
"inference_error":null, ... }
|
||||
```
|
||||
|
||||
### Call 2 (user taps Generate)
|
||||
```
|
||||
POST /api/v1/slabs/9f1c.../infer-content
|
||||
→ 202 { "status":"inferring" }
|
||||
GET /api/v1/slabs/9f1c...
|
||||
→ 200 { "title":"Black Walnut 8ft 0in × 18.2in Slab — Cathedral",
|
||||
"short_title":"Black Walnut Slab — Cathedral",
|
||||
"description":"A one-of-a-one cathedral black walnut slab...",
|
||||
"content_source":"llm", ... }
|
||||
```
|
||||
|
||||
### Publish
|
||||
```
|
||||
POST /api/v1/slabs/9f1c.../publish
|
||||
→ 202 { "status":"publishing" }
|
||||
GET /api/v1/slabs/9f1c...
|
||||
→ 200 { "status":"published","woo_product_id":1042,"published_at":"..." }
|
||||
```
|
||||
|
||||
### Taxonomy sync
|
||||
```
|
||||
POST /api/v1/admin/taxonomy/sync
|
||||
→ 200 { "categories": 24, "attributes": 5, "tags": 12, "synced_at": "..." }
|
||||
```
|
||||
|
||||
### Test connections
|
||||
```
|
||||
POST /api/v1/settings/test-woo
|
||||
→ 200 { "ok": true, "detail": "Connected to Whidbey Wood Store" }
|
||||
|
||||
POST /api/v1/settings/test-inference
|
||||
→ 200 { "ok": true, "vision_capable": true, "detail": "Model Qwen3.8-27B confirmed" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Versioning
|
||||
URL is `/api/v1`. Breaking changes bump to `/api/v2`. The SvelteKit client pins the version it was built against.
|
||||
|
||||
## Out of contract (v1)
|
||||
- Bulk endpoints, staff/role endpoints, webhook push, analytics.
|
||||
@@ -0,0 +1,75 @@
|
||||
# Milestone 2 — Photos
|
||||
|
||||
Builds on Milestone 1. Spec for calibration math and inventory PNG properties: `docs/CAPTURE.md`.
|
||||
This milestone gets every photo of one slab background-removed and cropped store-ready.
|
||||
It does not fill Complete-listing taxonomy, SKU, price, or copy. It does not create a WooCommerce product.
|
||||
No inference URL. No model. Mask and crop for non-calibration shots reuse the approved calibration params as ordinary client code.
|
||||
|
||||
## Goal
|
||||
|
||||
Phone capture of one slab → a lined-up set of Woo-compatible inventory PNGs, plus Milestone 1 calibration numbers on the reference shot, plus one annotated copy of the calibration PNG with dimension overlays.
|
||||
|
||||
## Use case
|
||||
|
||||
1. User adds a batch of one or more photos of the same slab (Setup rules from Milestone 1: green or black sheet, top-down reference expectations still apply to the calibration choice).
|
||||
2. User selects which photo in the batch is the calibration photo.
|
||||
3. App runs the Milestone 1 workflow on that calibration photo only: Mask → Length axis → Measure (length `L`, thickness, Calculate).
|
||||
4. After Calculate, the app applies the approved mask sheet and sensitivity, and the same crop rules (3:4 portrait, 90% fill, transparent PNG, shorter-side floor), to every other photo in the batch.
|
||||
5. App adds a second copy of the calibration inventory PNG with dimension overlays burned in (see Dimension overlay).
|
||||
6. User sees Photos ready: inventory PNGs lined up in this order — clean calibration PNG, then the dimension-overlay copy of the calibration PNG, then the other batch photos in capture order — plus the Milestone 1 calibration details (widths, sqft, bdft, scale) presented as in Measure.
|
||||
|
||||
A batch of one photo still works: that photo is the calibration photo; the end set is the clean PNG plus the dimension-overlay copy.
|
||||
|
||||
## States (additions over Milestone 1)
|
||||
|
||||
1. Batch — add one or more photos; continue when the batch has at least one.
|
||||
2. Pick calibration — user chooses which batch photo is the reference.
|
||||
3. Mask / Length axis / Measure — Milestone 1 states on the calibration photo only.
|
||||
4. Photos ready — lineup order: clean calibration PNG → dimension-overlay copy → other batch photos in capture order; plus Milestone 1 numbers.
|
||||
|
||||
Device draft restores the last approved state, including the batch and which photo was calibration when those exist.
|
||||
|
||||
## Apply to non-calibration photos
|
||||
|
||||
For each non-calibration photo:
|
||||
|
||||
- Reuse the approved Mask sheet (Auto / Green / Black) and sensitivity from the calibration photo. Do not re-open Mask controls for that photo in this milestone.
|
||||
- Run background removal with those params; compose inventory PNG with the same crop rules as Milestone 1 Calculate.
|
||||
- If a photo yields an empty mask or fails the PNG size floor, keep it out of the ready set and show a clear per-photo error; other photos still proceed.
|
||||
|
||||
Scale, widths, sqft, and bdft stay tied to the calibration photo and user `L` / thickness. Non-calibration photos are visual inventory only.
|
||||
|
||||
## Dimension overlay
|
||||
|
||||
A second copy of the **calibration** inventory PNG is added to the collection. Overlays are black, large enough to read on phone and storefront.
|
||||
|
||||
Orientation follows the **user-approved length axis** from Milestone 1 (not the upright edges of the photo).
|
||||
|
||||
- **Length:** dimension graphic beside the wood on the right in axis-space (outside the slab edge along the length direction).
|
||||
- **Widths:** stations every 12 in along the approved length axis, starting 6 in from the **bottom** of the slab span, continuing while the station is not within 6 in of the top (stations at 6, 18, 30, … in inches along the axis while ≤ `L − 6`). Each width is drawn across the wood perpendicular to the length axis, with arrow tips on the left and right slab edges and the measurement text on that line.
|
||||
- **Bottom:** after the calibration photo’s EXIF orientation is applied, the bottom edge of that oriented photo establishes which end of the slab is bottom for width stations. Length-axis direction still follows the user-approved Milestone 1 axis; EXIF only picks which end is bottom vs top along that span.
|
||||
|
||||
## Photos-ready order
|
||||
|
||||
1. Clean calibration inventory PNG
|
||||
2. Dimension-overlay copy of the calibration PNG
|
||||
3. Remaining batch inventory PNGs in capture order
|
||||
|
||||
The clean calibration PNG remains in the set. The annotated copy is extra.
|
||||
|
||||
## Acceptance
|
||||
|
||||
On a phone UAT build:
|
||||
|
||||
- User can capture 1–N photos, pick calibration, complete Milestone 1 on that shot, and see every successful batch photo as a 3:4 transparent inventory PNG lined up.
|
||||
- Calibration measures match Milestone 1 presentation.
|
||||
- Dimension-overlay copy of the calibration PNG is present with black length and width graphics oriented to the approved axis; width stations start 6 in from EXIF-established bottom.
|
||||
- Lineup order is clean calibration → dimension overlay → other batch photos in capture order.
|
||||
- No Woo create. No inference URL.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Complete-listing fields (SKU, species, category, edge, figure, grade, thickness band, moisture, `fig-*` / `feat-*`, title, short title, description, price)
|
||||
- WooCommerce create (Milestone 3)
|
||||
- Inference / Assist (Milestone 4)
|
||||
- Changing Milestone 1 mask/axis/measure math except to reuse its outputs for batch apply and overlays
|
||||
@@ -0,0 +1,77 @@
|
||||
# Product requirements
|
||||
|
||||
SlabUploader creates one WooCommerce listing per wood slab for Whidbey Wood Store.
|
||||
|
||||
Each slab is one unit and one listing. Photos and metadata are the inventory record.
|
||||
|
||||
Photographs are taken of the slab on a green or black sheet. That is the capture starting state.
|
||||
|
||||
## Complete listing
|
||||
|
||||
- Inventory photo(s), uniform 3:4 transparent PNG
|
||||
- SKU, length, thickness, price
|
||||
- Species, wood category, edge type, figure, grade
|
||||
- Thickness band, moisture
|
||||
- One or more `fig-*` tags
|
||||
- Title, short title, description
|
||||
- Zero or more `feat-*` tags
|
||||
|
||||
Store categories, attributes, and `fig-*` / `feat-*` tags are the filters. Measured values feed title and description templates.
|
||||
|
||||
## Decision rights
|
||||
|
||||
| Field | Source |
|
||||
|---|---|
|
||||
| Length, thickness | User |
|
||||
| SKU | User |
|
||||
| Mask and crop | App proposal, user approve |
|
||||
| Widths, sqft, bdft | App, from approved reference photo + length + thickness |
|
||||
| Species, wood category, edge, figure, grade, tags | App may propose; user may change |
|
||||
| Price | App proposal `bdft × species $/bdft`; user may replace |
|
||||
| Title, short title, description | Templates from listing facts; user may edit |
|
||||
|
||||
## System seams
|
||||
|
||||
Milestones 1 and 2 run in the browser. No backend and no inference URL.
|
||||
Milestone 1 handoff is the device draft: source photo, approved mask, inventory PNG, length, thickness, widths, sqft, bdft.
|
||||
Milestone 2 extends the draft with the photo batch, calibration choice, per-photo inventory PNGs, and the dimension-overlay calibration copy.
|
||||
Milestone 3 uses FastAPI as the Woo client. Store credentials stay on the server.
|
||||
|
||||
## Create
|
||||
|
||||
`SLAB-UAT-*` creates as a WooCommerce draft (store status).
|
||||
Duplicate SKU blocks create.
|
||||
A listing can be created with inference off.
|
||||
A device draft in the app is separate from a WooCommerce draft.
|
||||
|
||||
## Milestones
|
||||
|
||||
Work is split into four milestones. Each milestone is done when its acceptance can be demonstrated.
|
||||
|
||||
### Milestone 1 — Capture
|
||||
|
||||
Spec: `docs/CAPTURE.md`. Done historically; handoff into Milestone 2.
|
||||
|
||||
User stories:
|
||||
- Photograph a slab on a green or black sheet and remove the background.
|
||||
- Set length from the bounding rectangle and get widths, sqft, and bdft.
|
||||
- Leave and later Continue or Start fresh.
|
||||
|
||||
Acceptance: inventory PNG and measurements visible on a phone. No Woo create.
|
||||
|
||||
### Milestone 2 — Photos
|
||||
|
||||
Spec: `docs/PHOTOS.md`. Current work.
|
||||
|
||||
Batch photos of one slab, pick calibration, run Milestone 1 on that reference, apply the same mask params and crop to the rest, preview all inventory PNGs lined up, plus a dimension-overlay copy of the calibration PNG.
|
||||
Acceptance: on a phone, 1–N store-ready inventory PNGs for the slab (including dimension overlay on the calibration copy) with Milestone 1 measures visible. No Woo create. No Complete-listing taxonomy in this milestone.
|
||||
|
||||
### Milestone 3 — Create
|
||||
|
||||
WooCommerce draft for a practice SKU. Then clear the device draft.
|
||||
Acceptance: `SLAB-UAT-*` exists in the store as draft.
|
||||
|
||||
### Milestone 4 — Assist
|
||||
|
||||
Optional vision and generated copy on the manual path from Milestones 1–3.
|
||||
Acceptance: create still works with inference off.
|
||||
@@ -1,201 +0,0 @@
|
||||
# Inference Prompts
|
||||
|
||||
Status: SPEC · 2026-08-27 · SlabUploader
|
||||
Prompts are server-side text files, not settings values. Read fresh on each
|
||||
invocation. Shipped defaults live in `backend/app/prompts/`.
|
||||
|
||||
## Management
|
||||
|
||||
- **Location:** `/app/prompts/` inside the FastAPI container, mounted read-only
|
||||
from host `backend/app/prompts/`.
|
||||
- **Editing:** Edit the text files on the host. No server restart needed.
|
||||
- **Versioning:** The inference_log stores the prompt content (or hash) with each
|
||||
inference call, so you can trace which prompt version produced which result.
|
||||
- **Reset-to-default:** `python -m app.prompts.reset` restores shipped defaults
|
||||
from `backend/app/prompts/`.
|
||||
|
||||
## Call 1 — Vision (species/character classification)
|
||||
|
||||
File: `/app/prompts/call1.txt`
|
||||
|
||||
### Purpose
|
||||
Classify the slab's species, edge type, figure, and grade by analyzing
|
||||
inventory photos. Constrained to choose from the synced Woo taxonomy lists.
|
||||
|
||||
### Inputs assembled by the server
|
||||
- 1–5 inventory photos, downscaled to 1024px max
|
||||
- Species leaf categories from Woo (list with IDs and brief definitions)
|
||||
- Edge Type attribute terms with IDs
|
||||
- Figure attribute terms with IDs
|
||||
- Grade attribute terms with IDs
|
||||
- User metadata: SKU, length, thickness
|
||||
|
||||
### System prompt (template)
|
||||
```
|
||||
You are an expert wood slab classifier. Analyze the provided slab photos and
|
||||
return taxonomy data. Only use the values provided in the taxonomy lists — do
|
||||
not invent categories or attribute values.
|
||||
```
|
||||
|
||||
### User prompt (assembled at runtime)
|
||||
```
|
||||
Analyze the following wood slab photos and classify the species, edge type,
|
||||
figure, and grade.
|
||||
|
||||
Species options (choose ONLY from this list):
|
||||
1. [species name] — [brief definition] (woo_id: <id>)
|
||||
2. ...
|
||||
|
||||
Edge Type options:
|
||||
- Live Edge — natural, uncut bark edge
|
||||
- Flat Sawn — squared, milled edges
|
||||
...
|
||||
|
||||
Figure options:
|
||||
- Cathedral — U-shaped grain patterns
|
||||
- Burl — swirling, knotted grain
|
||||
...
|
||||
|
||||
Grade options:
|
||||
- Premium — minimal defects, clean grain
|
||||
- Standard — some minor characteristics
|
||||
...
|
||||
|
||||
Slab metadata: SKU={sku}, Length={length}in, Thickness={thickness}in
|
||||
|
||||
Return valid JSON matching this schema:
|
||||
{
|
||||
"species_id": <woo_id or null>,
|
||||
"species_confidence": 0.0-1.0,
|
||||
"wood_category_ids": [<woo_id>, ...],
|
||||
"edge_type_term_id": <woo_id or null>,
|
||||
"figure_term_ids": [<woo_id>, ...],
|
||||
"figure_confidence": 0.0-1.0,
|
||||
"grade_term_ids": [<woo_id>, ...],
|
||||
"grade_confidence": 0.0-1.0,
|
||||
"character": { "type": "string", "severity": "string" },
|
||||
"inclusions": { "type": "string", "severity": "string" },
|
||||
"voids": "string",
|
||||
"checks": "string",
|
||||
"wood_categories": [
|
||||
{ "name": "string", "confidence": 0.0-1.0 },
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Notes
|
||||
- The taxonomy list (species, wood categories, edge type, figure, grade) is
|
||||
pulled from the **synced Woo cache only**. No hardcoded mill species list. A term
|
||||
not in the cache cannot be suggested or selected.
|
||||
- Brief definitions help the model distinguish ambiguous cases
|
||||
(e.g., "quarter-sawn" vs "cathedral").
|
||||
- Character/inclusions/voids/checks are free-text observations. The server
|
||||
maps them to Woo `feat-*` product tags after the call returns. WooCommerce
|
||||
is the authoritative source for feat-* tag definitions; the design does not
|
||||
duplicate them.
|
||||
- **Pre-population (when `inference_enabled`):** Call 1 results are the primary
|
||||
source that fills the review screen for species, wood categories, edge type,
|
||||
figure, grade, and mapped `feat-*` tags from free-text observations.
|
||||
- **Confidence gate (default threshold 0.7):**
|
||||
- Field confidence **≥ threshold** → pre-populate that field (mutable;
|
||||
user may clear or change it).
|
||||
- Field confidence **< threshold** → leave empty. The model's
|
||||
low-confidence guess as a default.
|
||||
- Call 1 does not define the ready gate. Species + figure (or any vision
|
||||
subset) is assist/prefill only. Ready is the **full named set** in AGENTS §7
|
||||
/ DATA-MODEL (filled manually if Call 1 left fields empty). Species + one
|
||||
figure is not enough.
|
||||
- Manual entry always wins. Call 1 is assist-only and does not gate publish.
|
||||
Full suite must pass with inference OFF. Canonical lock: AGENTS §6–7.
|
||||
|
||||
---
|
||||
|
||||
## Call 2 — Content (description prose)
|
||||
|
||||
File: `/app/prompts/call2.txt`
|
||||
|
||||
### Purpose
|
||||
Generate compelling product description prose for the slab. The model writes
|
||||
only the descriptive portion — dimensions, species, and measurements are
|
||||
injected by deterministic templates.
|
||||
|
||||
### Inputs assembled by the server
|
||||
- Portable Call 1 context (default: **full history resend** of Call 1 turn +
|
||||
images metadata + assistant JSON). `previous_response_id` only if
|
||||
`test-inference` recorded stateful support.
|
||||
- Explicit **confirmed vs inferred** labels for species, dimensions, and other
|
||||
attributes (user overrides marked confirmed).
|
||||
- Deterministic measurements: length, widths, sqft, bdft, thickness (never invented)
|
||||
- Brand voice, GEO context, title/short templates
|
||||
- Shared validation module rules so Call 2 assembly rejects the same invalid
|
||||
values the UI would
|
||||
|
||||
### System prompt (template)
|
||||
```
|
||||
You are a professional product copywriter for premium, one-of-a-one wood
|
||||
slabs. Write compelling, natural-sounding descriptions. Use the brand voice
|
||||
provided. Measurements are not invented; only the provided data is used.
|
||||
```
|
||||
|
||||
### User prompt (assembled at runtime)
|
||||
```
|
||||
Write product copy for this wood slab.
|
||||
|
||||
Species: {species}
|
||||
Figure: {figure}
|
||||
Character: {character description from Call 1}
|
||||
Length: {length_ft}ft {length_in_remainder}in
|
||||
Average width: {width_avg_in}in
|
||||
Width range: {width_min_in}in to {width_max_in}in
|
||||
Thickness: {thickness_in}in
|
||||
Board feet: {bdft} bdft
|
||||
Grade: {grade}
|
||||
|
||||
Brand voice: {brand_voice}
|
||||
GEO context: {geo_context}
|
||||
|
||||
Write:
|
||||
1. A compelling opening sentence about the slab
|
||||
2. A paragraph describing the character, grain, color, and use cases
|
||||
3. A call to action
|
||||
|
||||
Keep the tone appropriate for a premium lumber buyer. The
|
||||
dimensions — those are handled by the template. Focus on the beauty and
|
||||
versatility of the slab.
|
||||
|
||||
Return JSON: { "prose": "..." }
|
||||
```
|
||||
|
||||
### Template assembly (server-side, after LLM returns)
|
||||
The server assembles the final title and description from templates with
|
||||
deterministic measurements, inserting the LLM prose where appropriate.
|
||||
|
||||
Example title: `{species} {length_ft}ft {length_in_remainder}in × {width_avg_in}in Wood Slab — {figure}`
|
||||
Example description: `{llm_prose}. Each slab is naturally shaped — width varies
|
||||
along the length at {width_min_in}in to {width_max_in}in. Sold by the slab;
|
||||
dimensions as measured. {geo_sentence}`
|
||||
|
||||
### Notes
|
||||
- The LLM never touches dimensions. Templates handle all numbers.
|
||||
- No numeric-accuracy guardrail needed — dimensions never pass through the LLM.
|
||||
- If `content_llm_enabled` is false, the LLM call is skipped and templates
|
||||
are used with a generic description paragraph.
|
||||
- **Portable Call 1 context (issue #2):** default is full resend of Call 1 (user
|
||||
prompt + assistant JSON). Label each taxonomy value **confirmed** (user-edited)
|
||||
vs **inferred** (still from Call 1). Stateful `previous_response_id` is opt-in
|
||||
after `test-inference`. Fail closed if neither path works.
|
||||
|
||||
---
|
||||
|
||||
## Tuning workflow
|
||||
|
||||
1. Deploy the default prompts
|
||||
2. Capture a real slab, let Call 1 run
|
||||
3. Review the results against your expert judgment
|
||||
4. Edit `call1.txt` to improve classification accuracy
|
||||
5. Re-run Call 1 via `POST /api/v1/slabs/{id}/infer-taxon` to compare
|
||||
6. Iterate until results are consistently accurate
|
||||
|
||||
The inference_log stores each iteration's input/output so you can track
|
||||
progress across prompt versions.
|
||||
@@ -1,253 +0,0 @@
|
||||
# Technical Spec: Deterministic Image Pipeline & Area → Bdft
|
||||
|
||||
Status: SPEC · 2026-08-27 · Gate A freeze 2026-08-31 · TyTech / SlabUploader
|
||||
Scope: algorithms and test vectors for the deterministic core (client-authoritative).
|
||||
No inference, no LLM. Everything here is a pure function of (pixels, user inputs) → outputs.
|
||||
Inference, Woo payload, API, and schema live in other docs.
|
||||
|
||||
---
|
||||
|
||||
## 1. Invariants
|
||||
|
||||
1. **Determinism** — same inputs → bit-identical outputs. No randomness, no timestamps in math, no network calls for the math.
|
||||
2. **Manual entry is authoritative** — user-entered length, thickness, SKU, and price always win over any computed value.
|
||||
3. **Fallback chain is explicit** — every computed value has a defined fallback; the system never silently guesses.
|
||||
- BG removal: chroma-key / threshold → four knobs (sheet, sensitivity, edge offset, feather) live on capture → retake. U2Net last-resort is deferred from POC; the contract stays in the architecture.
|
||||
- Length axis: min-area bounding rect → user rotate/confirm → retake if the photo is unusable.
|
||||
- Area: requires a single contiguous slab mask; broken mask → flag and retake.
|
||||
4. **Units** — inches in 1/8" steps; sqft and bdft to 2 decimals; price half-up to 2 decimals. Those rounded values are what get stored. No sqin in the UI, tests, or product copy.
|
||||
5. **Client is authoritative** — all deterministic processing runs in the browser. The server stores the numbers and files the client sends, and handles Woo sync.
|
||||
|
||||
|
||||
## 1b. Browser compatibility floor
|
||||
|
||||
Client processing runs in the browser on phones and PCs. Ty lock 2026-09-06 PT: the
|
||||
compatibility matrix includes PC browsers; this is not a mobile-only app.
|
||||
|
||||
Supported families:
|
||||
- Phone: iOS Safari, Android Chrome
|
||||
- PC: desktop Chrome, desktop Edge, desktop Firefox (Windows and macOS at minimum)
|
||||
|
||||
Exact minimum version pins remain issue #4. Unsupported clients get a hard-stop message with an
|
||||
update / switch link. No polyfill strategy in POC.
|
||||
|
||||
Load-bearing client APIs for the deterministic path include canvas (or OffscreenCanvas where used)
|
||||
for mask overlay and knob re-run, image decode/crop/encode for 3:4 transparent PNG prep, and
|
||||
standard fetch to the app API. Only APIs listed here are used; update this section before adding new ones.
|
||||
|
||||
## 2. Units and rounding
|
||||
|
||||
| Quantity | Source | Stored / displayed |
|
||||
|---|---|---|
|
||||
| Length | user, 1/8" steps | nearest 1/8" |
|
||||
| Thickness | user pick, 1/8" steps | that pick (used in math and copy) |
|
||||
| Thickness Woo attribute | same pick, rounded **up** into a Woo range | Woo term, not the 1/8" value |
|
||||
| sqft | computed from mask | 2 decimals |
|
||||
| bdft | sqft × thickness (inches) | 2 decimals |
|
||||
| Price | species $/bdft × bdft, or override | 2 decimals, half-up |
|
||||
|
||||
- bdft is never rounded up to whole board feet.
|
||||
- Pixel→inch scale is an implementation detail. Users never see pixels.
|
||||
|
||||
## 3. Background removal (load-bearing)
|
||||
|
||||
Background removal is the **load-bearing phase** of the image pipeline. The mask
|
||||
defines the slab's pixel footprint. Length axis, 6" width samples, sqft, and bdft
|
||||
all derive from that footprint. A clipped or over-inclusive mask silently shifts
|
||||
the bounding rectangle and width samples with no later numeric check to catch it.
|
||||
The user's eye on the overlay is the only validator. There is no confidence score
|
||||
and no auto-gate on mask quality.
|
||||
|
||||
### 3.1 Auto-detect sheet
|
||||
1. Sample a 2–5% strip on all four borders.
|
||||
2. Average HSV per side.
|
||||
3. Hue in [35, 85] and saturation ≥ 40 → green.
|
||||
4. Else value ≤ 30 and saturation ≤ 20 → black.
|
||||
5. Else prompt: pick green or black.
|
||||
|
||||
### 3.2 Visual feedback (required)
|
||||
- Overlay the mask on the **source photo** (included vs excluded pixels), not only
|
||||
a cropped result.
|
||||
- Show the slab edge clearly. That edge is the measurement boundary.
|
||||
- User confirms the edge before length / area run.
|
||||
|
||||
### 3.3 Capture knobs (inline, live, persisted)
|
||||
Factory values live in code. If the user changes them, the new values persist in
|
||||
localStorage until reset-to-default.
|
||||
|
||||
All four knobs are **on the capture screen next to the overlay**, not behind a
|
||||
Settings navigation. Changing any knob **immediately re-runs** §3.4 on the current
|
||||
photo and refreshes the overlay on the source image. No apply/save step. No server
|
||||
round trip for mask tuning in POC.
|
||||
|
||||
1. **Sheet** — auto / green / black.
|
||||
2. **Sensitivity** — one slider; tighter vs looser detection (green: HSV range width; black: brightness cutoff).
|
||||
3. **Edge offset** — pull the mask in or out a few pixels so the cut sits on the wood, not in the sheet or into the grain.
|
||||
4. **Feather** — hard cut vs a couple of pixels of alpha blend.
|
||||
|
||||
### 3.4 Algorithms
|
||||
- **Green:** chroma-key in HSV. Border flood-fill so only sheet pixels connected to the image edge are removed (protects green-ish grain inside the slab).
|
||||
- **Black:** grayscale threshold. Same flood-fill (protects dark grain).
|
||||
- **POC path:** client-side only (sheet detect + four knobs). If the edge is still
|
||||
wrong after tuning, **retake**.
|
||||
- **Post-POC fallback (deferred, contract preserved):** U2Net matting on one photo via
|
||||
FastAPI. Mask returns; knobs still apply on the client. The U2Net control is not
|
||||
shipped in Gate C / first listing. The contract stays in the architecture for post-POC.
|
||||
- Morphological close, then feather per the setting.
|
||||
|
||||
### 3.5 Edge quality
|
||||
- The mask must be one contiguous slab contour.
|
||||
- If the user cannot get a clean edge with knobs, retake is the POC resolution.
|
||||
|
||||
## 4. Length axis, widths, sqft, bdft
|
||||
|
||||
### 4.1 Contour and length axis
|
||||
1. Binary mask M from §3.
|
||||
2. Largest contour → convex hull.
|
||||
3. Minimum-area bounding rectangle on the hull.
|
||||
4. Long side = length axis; short side = width axis.
|
||||
This follows the **prevailing** length, not a diagonal cut on one end.
|
||||
|
||||
### 4.2 Visual feedback (required)
|
||||
- Overlay the bounding rectangle and the length axis.
|
||||
- Width sample lines drawn perpendicular to that axis.
|
||||
- User confirms the axis matches the slab’s prevailing length.
|
||||
- **Rotate axis** if it is skewed; samples and sqft scale update live.
|
||||
- Nearly square slabs: user says which axis is length.
|
||||
|
||||
### 4.3 Scale
|
||||
User length L (inches, 1/8") is authoritative.
|
||||
|
||||
```
|
||||
scale = longest_axis_px / L
|
||||
```
|
||||
|
||||
### 4.4 Widths (listing only, not bdft)
|
||||
- Sample every **6"** along the confirmed length axis, perpendicular to it.
|
||||
- Report min, max, and average width for the description.
|
||||
- Auto-dimension overlay on the photo is **v1.5**, out of this spec.
|
||||
|
||||
### 4.5 sqft
|
||||
Projected top-down area of the mask. Live-edge thickness and the underside are not in the area.
|
||||
|
||||
```
|
||||
sqft = (mask_pixel_count / scale²) / 144
|
||||
```
|
||||
|
||||
Round to 2 decimals.
|
||||
|
||||
### 4.6 bdft
|
||||
|
||||
```
|
||||
bdft = sqft × thickness_in
|
||||
```
|
||||
|
||||
Round to 2 decimals. Identity: 1 sqft at 1" thick = 1 bdft.
|
||||
|
||||
## 5. Photo normalization
|
||||
|
||||
Applies to every inventory photo of the slab (first photo and the rest).
|
||||
|
||||
- Crop aspect: **3:4 portrait** (default; matches the WooCommerce template;
|
||||
configurable in settings).
|
||||
- Transparent **PNG only**.
|
||||
- Slab centered. **80% fill at the extremes** (widest and tallest points of the slab). Extra margin where the slab is narrower.
|
||||
- After crop, if the source has enough pixels, shorter side ≥ **1600 px**. If it cannot, warn and ask for a retake. The source must supply enough pixels.
|
||||
- Original + processed kept while draft/retry; both purged after successful publish (server storage; see Data Model).
|
||||
|
||||
## 6. Pricing
|
||||
|
||||
- Settings: sync **species** from Woo; user sets **$/bdft per species**.
|
||||
- Capture: `recommendation = bdft × species.price_per_bdft`, pre-fills price.
|
||||
- User may override. Override sticks for that slab.
|
||||
- No rule for that species → empty price; user types it. Publish still allowed.
|
||||
- Stored price: half-up to 2 decimals.
|
||||
- Figure- or category-weighted price is **v1.5**.
|
||||
|
||||
## 7. Constants
|
||||
|
||||
### 7.1 Code (not in Settings)
|
||||
```
|
||||
FILL_TARGET = 0.80
|
||||
ASPECT_W, ASPECT_H = 3, 4
|
||||
OUTPUT_PX_MIN = 1600
|
||||
WIDTH_SAMPLE_IN = 6
|
||||
INCH_STEP = 0.125
|
||||
AREA_DECIMALS = 2
|
||||
BDFT_DECIMALS = 2
|
||||
PRICE_DECIMALS = 2
|
||||
```
|
||||
|
||||
### 7.2 Factory defaults for persisted BG settings
|
||||
```
|
||||
SHEET = auto
|
||||
GREEN_HUE_LO/HI = 35, 85
|
||||
GREEN_SAT_MIN = 40
|
||||
GREEN_VAL_MIN = 40
|
||||
BLACK_THRESH = 30
|
||||
```
|
||||
Sensitivity, edge offset, and feather map onto these at runtime. Users interact with the knobs, not the raw HSV numbers.
|
||||
|
||||
## 8. Test vectors
|
||||
|
||||
Users think in inches, sqft, and bdft. Pixels are only how the computer gets there.
|
||||
|
||||
### TV-1 Green sheet
|
||||
Synthetic: green border, wood in the center. Interior green-ish patch that does not touch the border stays. Coverage enough that U2Net does not run.
|
||||
|
||||
### TV-2 Black sheet
|
||||
Same layout, black border, mid-tone wood. Dark interior wood that does not touch the border stays.
|
||||
|
||||
### TV-3 Scale, sqft, bdft
|
||||
Slab **96" long**, **1.5" thick**. Mask measures **0.64 sqft**.
|
||||
bdft = 0.64 × 1.5 = **0.96**.
|
||||
|
||||
### TV-4 Width samples
|
||||
96" length axis, stations every 6". Widths perpendicular to the confirmed axis. Listing gets min, max, avg.
|
||||
|
||||
### TV-5 Angled end
|
||||
One square end, one 45° cut. Length axis follows prevailing length, not the diagonal. Widths stay perpendicular after user confirm.
|
||||
|
||||
### TV-6 3:4 crop, 80% at extremes
|
||||
Slab centered in a 3:4 frame. At the widest and tallest points, fill = 0.80. PNG with alpha. Shorter side ≥ 1600 when the source allows.
|
||||
|
||||
### TV-7 Too-small source
|
||||
After 80% crop, shorter side would be below 1600 and the source cannot supply it. Warn; no upscaling from nothing. That photo is not publishable until retake.
|
||||
|
||||
### TV-8 Pricing
|
||||
bdft 0.96, species $12.50/bdft → rec **12.00**.
|
||||
Override **150.00** stored as 150.00.
|
||||
No rule → rec empty; manual 99.99 stored as 99.99.
|
||||
|
||||
### TV-9 Thickness → Woo range
|
||||
User pick **1"** stored as 1". Attribute bucket is the Woo range that 1" rounds **up** into (e.g. `1"–1 1/2"`). Exact range labels come from the synced Woo attribute, not this file.
|
||||
|
||||
### TV-10 Rounding
|
||||
Length 96.04" → **96"** (nearest 1/8").
|
||||
sqft 0.641 → **0.64**.
|
||||
bdft 11.525 → **11.53**.
|
||||
Price 12.345 → **12.35**.
|
||||
|
||||
## 9. Assumptions
|
||||
|
||||
1. The first photo is top-down, lens parallel to the broad face. Tilted shots make sqft/bdft wrong; retake is the fix.
|
||||
2. User length is the prevailing length of that face, in 1/8". The bounding-box axis is confirmed in the UI.
|
||||
3. Thickness is the declared 1/8" pick, not measured from any photo.
|
||||
4. sqft is the projected top-down area of the mask. Live-edge thickness and underside are not in the area.
|
||||
5. bdft = sqft × thickness (inches). Not rounded up to whole board feet.
|
||||
6. Sheet is uniform green or black. Odd colors → user picks sheet mode or retakes.
|
||||
7. 3:4 portrait is the PIP crop, configurable in settings.
|
||||
8. Client does all of this math. Server stores the numbers the client sends.
|
||||
|
||||
## 10. Cross-reference to other docs
|
||||
|
||||
| Topic | Depth doc(s) |
|
||||
|---|---|
|
||||
| Call 1 / Call 2 prompts, taxonomy mapping | PROMPTS, CONTENT-WOO |
|
||||
| Portable Call 1→Call 2 context (full resend default) | ARCHITECTURE §9, PROMPTS |
|
||||
| Woo payload, publish, 409/422 recovery | CONTENT-WOO, OPENAPI |
|
||||
| SQLite tables, status machine | DATA-MODEL |
|
||||
| HTTP contract, taxonomy `taxonomy_anchor` | OPENAPI |
|
||||
| Client vs server topology, validation module | ARCHITECTURE |
|
||||
| Auto-dimension overlay, figure-weighted price | IMPL-PLAN (v1.5) |
|
||||
| Online-only capture (offline deferred) | AGENTS §2, ARCHITECTURE §4 |
|
||||
@@ -1,445 +0,0 @@
|
||||
# TEST-SPEC — Engineer Test Specification
|
||||
|
||||
Status: SPEC · engineer bar · SoT gitea-atd main · 2026-09-07
|
||||
|
||||
This document defines every affirmative test case for the SlabUploader, from Phase 0 through production. Each case states **what must happen**, **where the rule lives**, and **how it is verified**. The human walkable practice script is at `docs/UAT-PRACTICE.md` and is left untouched by this file.
|
||||
|
||||
---
|
||||
|
||||
## 1. Case ID naming convention
|
||||
|
||||
Case IDs follow the pattern `<prefix>-<number>`. The prefix identifies the test layer or gate:
|
||||
|
||||
| Prefix | Meaning | Examples |
|
||||
|---|---|---|
|
||||
| `TV` | Test Vector from `docs/TECH-SPEC-PIPELINE.md` §8 | `TV-1`, `TV-10` |
|
||||
| `V` | Validation rule (shared validation module) | `V-1`, `V-3` |
|
||||
| `AES` | AES-GCM encryption / decryption | `AES-1`, `AES-2` |
|
||||
| `H` | Health endpoint | `H-1` |
|
||||
| `D` | Draft store (slab creation / persistence) | `D-1` |
|
||||
| `GC` | Gate C case (early Phase 1, claimable draft listing) | `GC-1`, `GC-5` |
|
||||
| `W` | WooCommerce mock integration | `W-1`, `W-5` |
|
||||
| `INF` | Inference endpoint probe / toggle | `INF-1`, `INF-4` |
|
||||
| `UI` | UI behavior (capture, knobs, overlay, ready gates) | `UI-1`, `UI-5` |
|
||||
| `UIE` | UI end-to-end (review, publish, settings, full flow) | `UIE-1`, `UIE-10` |
|
||||
| `API` | API contract (routes, concurrency, error responses) | `API-1`, `API-10` |
|
||||
| `TAX` | Taxonomy sync / anchor / species cache | `TAX-1`, `TAX-3` |
|
||||
| `C1` | Call 1 (vision) inference call | `C1-1`, `C1-3` |
|
||||
| `C2` | Call 2 (content/text) inference call | `C2-1`, `C2-4` |
|
||||
| `OFF` | Inference OFF path (full suite without inference) | `OFF-1`, `OFF-2` |
|
||||
| `OPS` | Operations / deployment / backup | `OPS-1`, `OPS-5` |
|
||||
| `INS` | Instrumentation / observability | `INS-1`, `INS-4` |
|
||||
| `E2E` | End-to-end browser test (full user flow) | `E2E-1`, `E2E-5` |
|
||||
| `FUND` | Fundamentals (cross-cutting dependency bar) | `FUND-1`, `FUND-25` |
|
||||
|
||||
Other abbreviations used in this document:
|
||||
|
||||
- **sqft**: square feet
|
||||
- **bdft**: board feet
|
||||
- **U2Net**: Universal 2 Network, a background-removal model (deferred from the proof of concept)
|
||||
- **API**: application programming interface
|
||||
- **E2E**: end-to-end
|
||||
- **UI**: user interface
|
||||
- **POC**: proof of concept
|
||||
- **SKU**: stock keeping unit
|
||||
- **Woo**: WooCommerce, the WordPress e-commerce plugin
|
||||
- **HTTP/HTTPS**: Hypertext Transfer Protocol (plain / secure)
|
||||
- **AES-GCM**: Advanced Encryption Standard in Galois/Counter Mode
|
||||
- **UUID**: universally unique identifier
|
||||
- **JSON**: JavaScript Object Notation
|
||||
- **LLM**: large language model
|
||||
|
||||
---
|
||||
|
||||
## 2. How cases are executed
|
||||
|
||||
This file is the engineer bar. It is not proof that the harness tree exists yet.
|
||||
|
||||
On docs-only `main`, `frontend/` and `backend/` are **not yet on this branch**. Paths below are **Phase 0 deliverable targets** until the code lands. Until then every Phase 0 (and earlier) case stays `not run`. Do not treat `frontend/e2e/` or `backend/tests/` as present. Do not invent a different test layout (for example `frontend/test/bvt/`) to satisfy this bar.
|
||||
|
||||
When code lands, automation lives under:
|
||||
|
||||
- **Unit tests**: `backend/tests/unit/` (pytest) and `frontend/src/__tests__/` (Vitest). These run against pure modules with no network calls.
|
||||
- **API contract tests**: `backend/tests/contract/` (pytest + `httpx` TestClient). These hit the FastAPI app through its test client, asserting request/response shape, status codes, and revision handling.
|
||||
- **Integration tests**: `backend/tests/integration/` (pytest + `httpx` TestClient + `respx` WooCommerce mock). These verify Woo create, duplicate SKU, taxonomy sync, stale-field recovery, and settings encryption round-trips without touching a real store.
|
||||
- **UI end-to-end tests**: `frontend/e2e/` (Playwright). These exercise the full browser flow: capture, mask knobs, axis confirm, numbers entry, review, and publish. They run against a started Docker Compose stack with the FastAPI test server and mocked Woo endpoints.
|
||||
- **Ops / deployment tests**: `deploy/tests/` (shell scripts). These verify compose health, backup/restore, and Caddy routing. `docs/checks/check-structure.sh` is a docs-structure pin and may run before app code exists.
|
||||
|
||||
Test dependencies are pinned in `backend/tests/requirements-test.txt` and `frontend/package.json` (devDependencies) when those packages exist. CI runs the full suite before any merge once the tree has code; the suite must pass with inference disabled.
|
||||
|
||||
---
|
||||
|
||||
## Results recording & report-out
|
||||
|
||||
Every report maps to named case IDs from this spec. Allowed results only: `pass`, `fail`, `not run`, and optionally `blocked` with a blocker pointer. Never invent pass.
|
||||
|
||||
Evidence is required for every `pass` or `fail`: a path or paste of real runner output (pytest, httpx, compose logs, curl). No evidence → `not run`. Report table columns are: case id · result · evidence pointer · blocker (if fail).
|
||||
|
||||
Gitea issues are the only mechanism for reporting issues found during a test pass. Chat, Slack, and PR comments are not the bug log. On fail, open or update a Gitea issue that includes the case id and evidence pointer; the report table's blocker column links that issue. Do not invent issues that lack runner evidence.
|
||||
|
||||
The Test Bar may only summarize what runners printed. Ty also reads raw results and owns gate exit. Gate or phase exit evidence in the Gates section still requires Ty confirmation where IMPL-PLAN mandates it — bots never declare Gate B or Gate C green.
|
||||
|
||||
When code does not exist yet, Phase 0 and earlier cases stay `not run`. Do not speculate.
|
||||
|
||||
---
|
||||
|
||||
## 3. Test pyramid overview
|
||||
|
||||
Each row states the test layer, when tests in that layer are written, and what document drives the expected behavior.
|
||||
|
||||
| Layer | When written | Primary source of truth |
|
||||
|---|---|---|
|
||||
| Unit | TDD: unit tests written before the feature code exists | `docs/TECH-SPEC-PIPELINE.md`, `docs/AGENTS.md` |
|
||||
| API / contract | Alongside the backend feature code | `docs/OPENAPI.md`, `docs/DATA-MODEL.md` |
|
||||
| Integration | Alongside the backend feature code | `docs/CONTENT-WOO.md`, `docs/ARCHITECTURE.md` |
|
||||
| UI / E2E | Alongside the frontend feature code | `docs/UX.md`, `docs/TECH-SPEC-PIPELINE.md` |
|
||||
| Ops / deployment | Alongside deployment configuration | `docs/DEPLOYMENT.md`, `docs/IMPL-PLAN.md` Phase 6 |
|
||||
|
||||
**Test-driven development (TDD)**: write the failing unit test first, then write the minimum code to pass it. This applies to all deterministic core functions: bdft math, pricing, rounding, image crop, and validation rules.
|
||||
|
||||
**Tests-with-code**: API contract tests, integration tests, and UI end-to-end tests are written in the same commit that implements the feature. Each feature commit includes its tests and shown execution output in the commit message.
|
||||
|
||||
---
|
||||
|
||||
## 4. Fundamentals — cross-cutting bar
|
||||
|
||||
These cases are the white-box bar for every dependency that touches the product. They run across all phases.
|
||||
|
||||
### SvelteKit / Vitest (frontend/src/__tests__/)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-1 | Pure logic tests have zero browser, DOM, or network dependencies | SvelteKit/Vitest convention | Vitest unit test: `vi.mock` any runtime import, assert no browser globals |
|
||||
| FUND-2 | Component/browser tests use semantic `getByRole` selectors; class or data-testid alone is not sufficient | SvelteKit testing-library convention | Vitest component test: assert role-based query succeeds |
|
||||
| FUND-3 | Real Tab key navigates focus; click-only tests are not sufficient for keyboard paths | UX.md §Browser compatibility | Playwright E2E: `page.keyboard.press('Tab')` followed by `toBeFocused` |
|
||||
| FUND-4 | Shared rune/state changes flush before DOM assertion; stale store values do not pass | Svelte rune reactivity | Vitest component test: flush/store tick before `expect` |
|
||||
|
||||
### Playwright (frontend/e2e/)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-5 | Tab order: press Tab, assert `toBeFocused` after each stop; no keyboard trap | Playwright convention; UX.md §Browser compatibility | Playwright E2E: sequential `keyboard.press('Tab')` + `toBeFocused` |
|
||||
| FUND-6 | Viewport resize/reflow at ~320 px and phone/PC sizes: layout does not clip, overlap, or trap content | UX.md §Browser compatibility | Playwright E2E: `setViewportSize` then assert no clip/overlap |
|
||||
| FUND-7 | Focus ring visible on touch and keyboard; focus ring is not hidden by `outline: none` on interactive elements | Playwright convention; WCAG 2.4.7 | Playwright E2E: assert focus ring CSS present on focused interactive element |
|
||||
|
||||
### FastAPI / pytest TestClient (backend/tests/)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-8 | App factory pattern creates a fresh app instance per test; no shared mutable state between tests | FastAPI testing convention | pytest TestClient: each test calls the factory, not a module-level app |
|
||||
| FUND-9 | `with TestClient(app)` manages lifespan; startup and shutdown hooks run and clean up | FastAPI testing convention | pytest TestClient: context manager exits with clean lifespan |
|
||||
| FUND-10 | Clear `dependency_overrides` after every test; no override bleeds to the next test | FastAPI testing convention | pytest TestClient: assert `dependency_overrides` empty after each test |
|
||||
| FUND-11 | Override Woo/inference dependencies with mocks; no real network call leaks | FastAPI testing convention | pytest TestClient: assert zero HTTP calls to real Woo/inference endpoints |
|
||||
|
||||
### SQLite + Alembic (backend/tests/)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-12 | `PRAGMA foreign_keys=ON` enforced in every test database; FK violation rejected | SQLite testing convention; DATA-MODEL.md | pytest + SQLite: insert orphan row, assert IntegrityError |
|
||||
| FUND-13 | Unique and check constraints enforced; duplicate or out-of-range values rejected | SQLite testing convention; DATA-MODEL.md | pytest + SQLite: insert violating row, assert IntegrityError |
|
||||
| FUND-14 | Concurrent poll / WAL stale-read risk handled; WAL mode with proper isolation level prevents stale reads | SQLite WAL convention; DATA-MODEL.md | pytest + SQLite: concurrent reader/writer, assert no stale read |
|
||||
| FUND-15 | Illegal status transitions rejected by the application layer; status machine enforced | AGENTS.md §7; DATA-MODEL.md slabs | pytest TestClient: attempt illegal transition, assert 422 |
|
||||
| FUND-16 | Migrations must not silently drop integrity indexes or constraints; post-migration assertions verify schema integrity | Alembic convention; DATA-MODEL.md | pytest + SQLite: run migration, assert indexes/constraints preserved |
|
||||
|
||||
### AES-GCM (settings)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-17 | Fresh nonce per encrypt; tampered ciphertext or wrong key/nonce raises authentication failure | AES-GCM specification; AGENTS.md §4 | Unit test: tamper ciphertext, assert auth failure; encrypt twice, assert nonces differ |
|
||||
| FUND-18 | Ciphertext never appears in any GET response; only the configured username and `woo_credentials_configured` boolean returned | OPENAPI.md §settings; DATA-MODEL.md settings | API contract test: assert `woo_app_password` absent from GET /api/v1/settings |
|
||||
| FUND-19 | Missing `SLAB_AES_KEY` refuses startup; no fallback to plaintext storage | AGENTS.md §4; DATA-MODEL.md settings | Unit test: unset env var, assert startup rejection |
|
||||
|
||||
### Woo REST client (httpx + App Passwords over HTTPS)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-20 | Basic Auth with App Passwords over HTTPS; consumer keys not implemented | AGENTS.md §4; DEPLOYMENT.md §3; OPENAPI.md §settings | Unit test: assert HTTP Basic header, HTTPS-only URL |
|
||||
| FUND-21 | 401/400/404 response shapes handled; server maps to actionable error, not raw passthrough | Woo REST convention; CONTENT-WOO.md §2.6 | Integration test with respx: mock 401/400/404, assert mapped error response |
|
||||
| FUND-22 | Pre-create SKU lookup mandatory; Woo concurrent duplicate-SKU race handled by checking before create | AGENTS.md §5; CONTENT-WOO.md §2.5 | Integration test with respx: create duplicate SKU, assert 409 before create |
|
||||
| FUND-23 | Timeouts and network errors handled gracefully; server returns actionable error, not stack trace | Woo REST convention; CONTENT-WOO.md §2.6 | Integration test with respx: mock timeout/connection error, assert graceful error |
|
||||
| FUND-24 | Secrets redacted in logs; no Woo username/password, inference key, or AES key in any log output | AGENTS.md §4; ARCHITECTURE.md §5 | Unit test: assert log output contains no secret material |
|
||||
|
||||
### Compose / Caddy (deploy/tests/)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| FUND-25 | HTTPS-only `WOO_BASE_URL`; health through proxy; inventory/port collision checked at deploy time | DEPLOYMENT.md §3; AGENTS.md §9 | Shell script: assert HTTPS, health through Caddy, port conflict detection |
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 / Gate B — Hybrid skeleton + deterministic core
|
||||
|
||||
**Exit evidence**: Ty confirms TV-3, TV-6, TV-7, and TV-10 output on real fixtures; health returns 200; AES round-trip passes; draft store stub persists and retrieves; unit and API cases automated.
|
||||
|
||||
### Unit — deterministic core (test-driven)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| TV-1 | Green-sheet synthetic photo: interior green-ish patch that does not touch the border stays after chroma-key; U2Net is not invoked | `docs/TECH-SPEC-PIPELINE.md` §3.1, §3.4 | Unit test with synthetic image fixture |
|
||||
| TV-2 | Black-sheet synthetic photo: dark interior wood that does not touch the border stays after threshold; flood-fill isolates border-connected pixels only | `docs/TECH-SPEC-PIPELINE.md` §3.1, §3.4 | Unit test with synthetic image fixture |
|
||||
| TV-3 | Slab 96" long, 1.5" thick, mask 0.64 square feet → bdft = 0.96. Identity: 1 square foot at 1" thick equals 1 bdft. No divide-by-12. | `docs/TECH-SPEC-PIPELINE.md` §4.6 | Unit test, shown output on real fixtures |
|
||||
| TV-4 | Width samples at 6" stations on a 96" length axis report min, max, and average perpendicular to the confirmed axis | `docs/TECH-SPEC-PIPELINE.md` §4.4 | Unit test with fixture mask |
|
||||
| TV-5 | Slab with one square end and one 45° cut: length axis follows prevailing length; widths stay perpendicular after user confirm | `docs/TECH-SPEC-PIPELINE.md` §4.1, §4.2 | Unit test with angled-end fixture |
|
||||
| TV-6 | 3:4 crop, slab centered, 80 percent fill at extremes, transparent PNG, shorter side ≥ 1600 when source allows | `docs/TECH-SPEC-PIPELINE.md` §5, §7.1 | Unit test, shown output on real fixtures |
|
||||
| TV-7 | Undersized source: after 80 percent crop shorter side would be below 1600 and source cannot supply it → warn, no upscaling, photo not publishable until retake | `docs/TECH-SPEC-PIPELINE.md` §5, §7.1 | Unit test, shown output on real fixtures |
|
||||
| TV-8 | Pricing: bdft 0.96, species $12.50/bdft → recommended price 12.00; override 150.00 stored as 150.00; no rule → recommended price empty, manual 99.99 stored | `docs/TECH-SPEC-PIPELINE.md` §6, §8 TV-8 | Unit test with pricing rules |
|
||||
| TV-9 | Thickness 1" → Woo range rounds up (for example 1"–1 1/2") using synced attribute term, not a hardcoded label | `docs/TECH-SPEC-PIPELINE.md` §8 TV-9, `docs/DATA-MODEL.md` slabs | Unit test with mock taxonomy |
|
||||
| TV-10 | Rounding: 96.04" → 96"; square feet 0.641 → 0.64; bdft 11.525 → 11.53; price 12.345 → 12.35. Half-up to 2 decimals. | `docs/TECH-SPEC-PIPELINE.md` §8 TV-10 | Unit test, shown output on real fixtures |
|
||||
|
||||
### Unit — shared validation
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| V-1 | SKU charset `[A-Z0-9-]{3,24}` accepted; values outside the charset rejected | `docs/TECH-SPEC-PIPELINE.md` §2, issue #17 | Unit test with valid and invalid SKU strings |
|
||||
| V-2 | Title, short title, description: UTF-8 within WooCommerce maxLength enforced at field exit and at submit | `docs/TECH-SPEC-PIPELINE.md` §2, issue #17 | Unit test with boundary-length strings |
|
||||
| V-3 | Validation module version hash: client caches module; submit carries hash; mismatch returns 412 with fresh module, not 409 | `docs/OPENAPI.md` §validation, issue #17 | Unit test of validation module hash comparison |
|
||||
|
||||
### Unit — AES-GCM settings
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| AES-1 | Encrypt then decrypt round-trips for woo_wp_username and woo_app_password; ciphertext never appears in GET settings | `docs/ARCHITECTURE.md` §5, issue #5 | Unit test with round-trip encryption |
|
||||
| AES-2 | Missing SLAB_AES_KEY environment variable at startup: app refuses to start; no fallback to plaintext | `docs/AGENTS.md` §4, `docs/DATA-MODEL.md` settings | Unit test with missing env var |
|
||||
|
||||
### API / contract — health + draft store stub
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| H-1 | `GET /api/health` returns 200 `{ "status":"ok" }` with `woo_reachable` false when credentials are not configured | `docs/OPENAPI.md` §health, `docs/IMPL-PLAN.md` Phase 0 | API contract test via httpx TestClient |
|
||||
| D-1 | `POST /api/v1/slabs` accepts multipart with data JSON + files + metadata; returns 201 with `status: calibrated` and `server_rev` | `docs/OPENAPI.md` §slabs, `docs/DATA-MODEL.md` slabs | API contract test via httpx TestClient |
|
||||
|
||||
---
|
||||
|
||||
## Gate C — Early Phase 1 (first draft listing, inference disabled)
|
||||
|
||||
**Exit evidence**: Ty opens one `SLAB-UAT-*` WooCommerce draft listing in the real store admin; inference OFF; mocked-store automation is not Gate C exit.
|
||||
|
||||
### API / contract — create + draft
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| GC-1 | `POST /api/v1/slabs` with `SLAB-UAT-*` SKU creates a WooCommerce product with `status: "draft"` regardless of the `woo_create_status` setting | `docs/AGENTS.md` §5, `docs/CONTENT-WOO.md` §2.4 | API contract test with mocked Woo |
|
||||
| GC-2 | Duplicate SKU before create: `GET /products?sku={sku}` finds existing → 409 `duplicate_sku` with `{ field:"sku", actions:["edit_sku","open_existing"] }` | `docs/CONTENT-WOO.md` §2.5, `docs/OPENAPI.md` §slabs, issue #3 | API contract test with pre-existing SKU in mock |
|
||||
| GC-3 | `POST /api/v1/settings/test-woo` returns ok with populated taxonomy; always resyncs taxonomy on success | `docs/OPENAPI.md` §settings, issue #14 | API contract test with mocked Woo taxonomy |
|
||||
| GC-4 | `WOO_BASE_URL` is compose-only HTTPS; Settings GET returns it read-only; PUT rejects write attempts with 422 | `docs/AGENTS.md` §5, issue #11 | API contract test with PUT attempt |
|
||||
| GC-5 | FastAPI refuses to start when `WOO_BASE_URL` environment variable is missing or set to `http://` | `docs/AGENTS.md` §4, `docs/DEPLOYMENT.md` §3 | Unit test for startup config validation |
|
||||
|
||||
### Integration — WooCommerce mock (draft create, SLAB-UAT-*, duplicate SKU, taxonomy)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| W-1 | Woo mock returns a new product with status draft; server stores `woo_product_id` and purges images | `docs/CONTENT-WOO.md` §2.4, `docs/IMPL-PLAN.md` Phase 4 | Integration test with respx mock |
|
||||
| W-2 | Woo mock returns 409 for duplicate SKU; server maps to `{ field:"sku", actions:["edit_sku","open_existing"] }`; draft retained | `docs/OPENAPI.md` §slabs, issue #3 | Integration test with respx mock returning 409 |
|
||||
| W-3 | Taxonomy sync returns cached data; anchor stays unchanged on no-op sync; anchor bumps only when stored-subset hash changes | `docs/ARCHITECTURE.md` §7, issue #14 | Integration test with taxonomy mock |
|
||||
| W-4 | `test-woo` always runs taxonomy resync after successful connection test | `docs/ARCHITECTURE.md` §7, issue #14 | Integration test: assert taxonomy resync call |
|
||||
| W-5 | Failed publish: slab status `failed`, photos retained, sync_log written; retry from same screen without re-photographing → success → photos purged | `docs/CONTENT-WOO.md` §2.6, `docs/TECH-SPEC-PIPELINE.md` §5, `docs/DATA-MODEL.md` slabs | Integration test with retryable mock failure |
|
||||
|
||||
### Integration — inference disabled path + test-inference probe (issue #2 substance)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| INF-1 | With `inference_enabled: false`: slab create skips Call 1; `inference_status` is null; full suite passes end-to-end with no inference network calls | `docs/AGENTS.md` §6, `docs/IMPL-PLAN.md` Phase 5 | Integration test asserting zero inference calls |
|
||||
| INF-2 | `POST /api/v1/settings/test-inference` returns `{ ok: true, mode: "stateful", vision_capable: true }` on a stateful provider | `docs/OPENAPI.md` §settings, issue #2 | Integration test with mocked inference endpoint |
|
||||
| INF-3 | `test-inference` returns `{ ok: true, mode: "stateless", vision_capable: true }` on a stateless provider; Call 2 uses full resend | `docs/OPENAPI.md` §settings, issue #2 | Integration test with mocked inference endpoint |
|
||||
| INF-4 | `test-inference` returns `{ ok: false, mode: "fail" }`: Call 2 enablement blocked; Gate C path remains green with inference disabled | `docs/OPENAPI.md` §settings, issue #2 | Integration test: assert Call 2 blocked |
|
||||
|
||||
### UI end-to-end — capture knobs, mask, axis, ready gates (phone + PC)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| UI-1 | Four inline knobs (sheet, sensitivity, edge offset, feather) on capture screen: changing any knob immediately re-runs mask and refreshes overlay without leaving the screen | `docs/TECH-SPEC-PIPELINE.md` §3.3, `docs/UX.md` §Capture, issue #15 | Playwright E2E test: knob change → overlay update, no navigation |
|
||||
| UI-2 | Mask overlay on source photo: user confirms edge; below-threshold edge after tuning → retake; no U2Net control in the proof of concept | `docs/TECH-SPEC-PIPELINE.md` §3.2, §3.5, `docs/UX.md` §Capture | Playwright E2E test: mask overlay visible, confirm/retake paths |
|
||||
| UI-3 | Length axis overlay: user rotates if skewed; samples and square feet update live; nearly-square slab: user picks length direction | `docs/TECH-SPEC-PIPELINE.md` §4.2, `docs/UX.md` §Capture | Playwright E2E test: axis rotation, live number update |
|
||||
| UI-4 | Numbers entry: length 1/8" steps, thickness pick, SKU typed; computed square feet/bdft/widths displayed | `docs/TECH-SPEC-PIPELINE.md` §4, `docs/UX.md` §Capture | Playwright E2E test: type inputs, assert computed output |
|
||||
| UI-5 | Ready-set gates: slab cannot reach `ready` until full named set is filled (SKU, length, thickness, square feet/bdft/widths, ≥1 PNG, species, wood category, edge, figure, grade, thickness band, moisture, price); inline nudges per empty required field, not a submit-time list | `docs/AGENTS.md` §7, `docs/UX.md` §Review, issue #9 | Playwright E2E test: attempt ready with missing fields, assert nudges |
|
||||
|
||||
### Ops — compose health
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| OPS-1 | `GET https://${APP_HOSTNAME}/api/health` returns ok after compose up with filled inventory | `docs/DEPLOYMENT.md` §8, `docs/IMPL-PLAN.md` Phase 0 | Shell script: compose up → curl health endpoint |
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 remainder — Full API surface
|
||||
|
||||
**Exit evidence**: agent-written test automation drives a full calibrated to ready cycle via the API; all OPENAPI endpoints match expected responses; revision conflict handled; taxonomy anchor logic verified.
|
||||
|
||||
### API / contract — all routes, concurrency, secrets redaction
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| API-1 | `PUT /api/v1/slabs/{id}` updates fields with `client_rev`; server echoes new `server_rev`; mismatch returns 409 `revision_conflict` with `current_server_rev` | `docs/OPENAPI.md` §conventions, `docs/DATA-MODEL.md` slabs | API contract test with httpx TestClient |
|
||||
| API-2 | `PUT /api/v1/slabs/{id}` stores client-sent derived fields (square feet, bdft, widths); server does not recompute them as source of truth | `docs/OPENAPI.md` §slabs PUT, `docs/ARCHITECTURE.md` §3 | API contract test: assert no server-side recompute |
|
||||
| API-3 | `GET /api/v1/settings` returns `SettingsView` with `woo_credentials_configured` boolean; `woo_app_password` never returned | `docs/OPENAPI.md` §settings, issue #5 | API contract test: assert password absent from response |
|
||||
| API-4 | `POST /api/v1/slabs/{id}/infer-taxon` returns 202 `{ status: "inferring" }`; client polls `GET /api/v1/slabs/{id}` for results; timeout greater than 45 seconds returns 504 | `docs/OPENAPI.md` §inference, issue #8 | API contract test with mocked inference |
|
||||
| API-5 | `POST /api/v1/slabs/{id}/infer-content` returns 202; requires `test-inference` ok; below-threshold Call 1 (confidence below 0.7): fields stay empty | `docs/OPENAPI.md` §inference, `docs/AGENTS.md` §6, issue #8/#9 | API contract test with confidence-gated mock |
|
||||
| API-6 | `POST /api/v1/slabs/{id}/publish`: pre-condition check returns 422 with field keys for missing required fields; UI maps fields, no raw code | `docs/OPENAPI.md` §publish, issue #18 | API contract test with incomplete slab |
|
||||
| API-7 | `POST /api/v1/admin/taxonomy/sync`: pulls categories/attributes/tags; rebuilds cache; anchor bumps only on stored-subset hash change; 502 retains previous cache | `docs/OPENAPI.md` §taxonomy, `docs/ARCHITECTURE.md` §7, issue #14 | Integration test with taxonomy mock |
|
||||
| API-8 | `GET /api/v1/validation/module` returns hash and rules; client caches; submit mismatch returns 412 with fresh module | `docs/OPENAPI.md` §validation, issue #17 | API contract test: assert 412 on stale hash |
|
||||
| API-9 | `DELETE /api/v1/slabs/{id}`: soft-delete returns 204; unpublished drafts only; published slabs undeletable | `docs/OPENAPI.md` §slabs DELETE | API contract test with published slab |
|
||||
| API-10 | `test-woo` fails closed: missing credentials or non-HTTPS URL returns `{ ok: false, detail: "..." }` without crashing | `docs/OPENAPI.md` §settings test-woo | API contract test with bad credentials |
|
||||
|
||||
### Integration — taxonomy sync + anchor
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| TAX-1 | Sync on publish when `now - taxonomy_last_sync_at > 1 hour`; bump anchor only on real change; stale picked id returns 422 with current options | `docs/ARCHITECTURE.md` §7, `docs/CONTENT-WOO.md` §2.2, issue #14 | Integration test with time-skewed sync |
|
||||
| TAX-2 | Species picker offers only WooCommerce-synced species; no hardcoded fallback; new species selectable only after sync stores it | `docs/ARCHITECTURE.md` §7, issue #12 | Integration test: assert species list matches cache |
|
||||
| TAX-3 | Client reads taxonomy anchor; re-pulls full taxonomy only when anchor advances past client's last value; no-per-navigation sync | `docs/ARCHITECTURE.md` §7, `docs/OPENAPI.md` §taxonomy | Integration test with anchor versioning |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Frontend review + publish UI
|
||||
|
||||
**Exit evidence**: Ty publishes a test slab to the real store as a WooCommerce draft `SLAB-UAT-*`; automation covers UI cases; Ty is the exit.
|
||||
|
||||
### UI end-to-end — review, field recovery, publish outcome (phone + PC)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| UIE-1 | Review screen: all fields editable; client-computed square feet/bdft/widths shown with manual override; typed override persists across poll and refresh | `docs/IMPL-PLAN.md` Phase 3, `docs/UX.md` §Review | Playwright E2E test: edit, poll, refresh, assert persistence |
|
||||
| UIE-2 | Call 1 prefill at or above 0.7 confidence: fields pre-filled and mutable; user override sticks; below 0.7 fields empty; inline nudges for every still-required control | `docs/AGENTS.md` §6, issue #8/#9, `docs/UX.md` §Review | Playwright E2E test with mocked Call 1 results |
|
||||
| UIE-3 | Duplicate SKU at publish: under SKU field, "This SKU already exists in the store (any status)"; edit SKU or open existing; draft retained; no raw 409 | `docs/UX.md` §Publish, `docs/CONTENT-WOO.md` §2.5, `docs/AGENTS.md` §5, issue #3/#18 | Playwright E2E test with pre-existing SKU |
|
||||
| UIE-4 | Stale field at publish: field shows "This value is no longer valid. Pick from the current list"; draft retained; no raw 422 | `docs/CONTENT-WOO.md` §2.6, issue #18 | Playwright E2E test with removed taxonomy item |
|
||||
| UIE-5 | Publish success: screen shows listing created, `woo_product_id` when available; local draft and photos gone; slab status `published` | `docs/CONTENT-WOO.md` §2.6, `docs/DATA-MODEL.md` slabs | Playwright E2E test: assert published state and cleanup |
|
||||
| UIE-6 | Publish failure: plain message, no status number, no stack; retry from same screen without re-photographing | `docs/CONTENT-WOO.md` §2.6, issue #18 | Playwright E2E test: assert retry path preserves state |
|
||||
| UIE-7 | Inference disabled: full manual taxonomy + content path works; no inference network calls; Generate text disabled; templates still work | `docs/IMPL-PLAN.md` Phase 3, `docs/UX.md` §Review | Playwright E2E test with inference flag off |
|
||||
| UIE-8 | Settings UI: WordPress username + application password + test-woo; inference endpoint + test; pricing rules; brand voice/GEO; `woo_create_status`; store URL read-only | `docs/IMPL-PLAN.md` Phase 3, `docs/OPENAPI.md` §settings, issue #11 | Playwright E2E test: settings form and test buttons |
|
||||
| UIE-9 | Changing sensitivity slider immediately refreshes mask overlay without leaving screen or server round trip | `docs/TECH-SPEC-PIPELINE.md` §3.3, issue #15, `docs/UX.md` §Capture | Playwright E2E test: slider → overlay update, no HTTP call |
|
||||
| UIE-10 | Changing edge offset pulls cut in/out; feather changes alpha blend; sheet switch (auto/green/black) re-runs; all persisted in localStorage until reset | `docs/TECH-SPEC-PIPELINE.md` §3.3, issue #15 | Playwright E2E test: knob changes, persist, reset |
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Inference (after Gate C is green)
|
||||
|
||||
**Exit evidence**: Ty runs species detection on 3 real slabs with judgment on acceptance; automation covers Call 1/2 cases; full inference-disabled path green.
|
||||
|
||||
### Integration — Call 1/2, portable context, confidence gating
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| C1-1 | Call 1 sends all inventory photos at 1024px + WooCommerce taxonomy only + SKU/length/thickness; model constrained to cached taxonomy from WooCommerce cache | `docs/IMPL-PLAN.md` Phase 5, issue #12 | Integration test: inspect Call 1 request payload |
|
||||
| C1-2 | Confidence at or above 0.7: species, wood categories, edge, figure, grade, feat-* pre-filled and mutable; user override wins | `docs/AGENTS.md` §6, issue #8/#9 | Integration test with high-confidence mock response |
|
||||
| C1-3 | Confidence below 0.7: those fields stay empty; ready blocked until full named set is filled; species plus one figure is not the gate | `docs/AGENTS.md` §6, issue #8/#9 | Integration test with low-confidence mock response |
|
||||
| C2-1 | Call 2 triggered only by user tap; portable Call 1 context: full resend default; confirmed versus inferred labels carried | `docs/ARCHITECTURE.md` §9, issue #2 | Integration test: assert no auto-trigger, full resend |
|
||||
| C2-2 | Test-inference stateful mode: `previous_response_id` used when available; stateless mode: full resend; fail mode: Call 2 blocked | `docs/OPENAPI.md` §settings, issue #2 | Integration test with three probe modes |
|
||||
| C2-3 | LLM does not invent dimensions; templates inject deterministic numbers into title and description | `docs/PROMPTS.md` §Call 2, `docs/AGENTS.md` §6 | Integration test: inspect Call 2 response for invented numbers |
|
||||
| C2-4 | Audit: inference_log stores request_payload and response_payload per call; prompt file edits apply without restart | `docs/DATA-MODEL.md` inference_log, `docs/PROMPTS.md` §Management | Integration test: verify log entry, edit prompt file |
|
||||
|
||||
### UI end-to-end — inference disabled path
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| OFF-1 | Full suite (calibrated to ready to publish to success) passes with `inference_enabled: false`; zero calls to inference endpoint asserted | `docs/AGENTS.md` §6, `docs/IMPL-PLAN.md` Phase 5 | Playwright E2E test with network assertion for zero inference calls |
|
||||
| OFF-2 | `test-inference` fail mode blocks Call 2 enablement only; Gate C inference-disabled path unaffected | `docs/OPENAPI.md` §settings, issue #2 | Playwright E2E test: assert Call 2 disabled, full suite passes |
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 / Ops — Deployment, user acceptance, hardening
|
||||
|
||||
**Exit evidence**: deployment smoke automated; Ty walks `docs/UAT-PRACTICE.md` and signs off on UAT results; v1 declared done.
|
||||
|
||||
### Ops — compose health, deploy path, backup/restore
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| OPS-2 | INVENTORY.md filled: APP_HOST, APP_HOSTNAME, ports verified free, Caddy location confirmed, DNS reachable from phone on LAN/Tailscale | `docs/DEPLOYMENT.md` §1, `docs/IMPL-PLAN.md` Phase 6 | Shell script: port scan, Caddy check, DNS resolve |
|
||||
| OPS-3 | Compose health: `GET https://${APP_HOSTNAME}/api/health` ok; `test-woo` ok with species populated; `woo_create_status=draft`; inference disabled for early gates | `docs/DEPLOYMENT.md` §8, `docs/UAT-PRACTICE.md` §1 | Shell script: curl health + test-woo endpoints |
|
||||
| OPS-4 | Backup: `deploy/backup.sh` creates WAL-safe `.backup` of slab.db and tar of images volume; retention 7 daily + 4 weekly | `docs/DEPLOYMENT.md` §6 | Shell script: run backup, verify files and retention |
|
||||
| OPS-5 | Restore: stop compose → restore DB + untar images → start compose → health ok; tested at least once before declaring backup done | `docs/DEPLOYMENT.md` §6, `docs/IMPL-PLAN.md` Phase 6 | Shell script: full restore cycle with health assertion |
|
||||
|
||||
### Ops — instrumentation (issue #6 substance)
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| INS-1 | Health non-200 on database or volume failure; `woo_reachable` false on WooCommerce unreachable | `docs/OPENAPI.md` §health, issue #6 | Unit test with simulated DB/volume failure |
|
||||
| INS-2 | Request ID logged on every server request | issue #6 | Unit test: assert request ID in log output |
|
||||
| INS-3 | Inference request_payload and response_payload recorded in inference_log; payloads contain model name and confidence data | `docs/DATA-MODEL.md` inference_log, issue #6 | Integration test: assert log entry after inference call |
|
||||
| INS-4 | Sync_log written with payload_hash on every publish attempt; retains success and failure | `docs/DATA-MODEL.md` sync_log, issue #6 | Integration test: assert sync_log entries for success and failure |
|
||||
|
||||
### Ops — end-to-end on all target browsers
|
||||
|
||||
| Case | What must happen | Where the rule lives | Verified by |
|
||||
|---|---|---|---|
|
||||
| E2E-1 | Capture to mask/axis confirm to calibrated upload to review to publish to WooCommerce draft `SLAB-UAT-*` works on iOS Safari (phone) | `docs/UX.md` §Browser compatibility, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E on iOS Safari |
|
||||
| E2E-2 | Same flow works on Android Chrome (phone) | `docs/UX.md` §Browser compatibility, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E on Android Chrome |
|
||||
| E2E-3 | Same flow works on desktop Chrome, Edge, Firefox (PC) | `docs/UX.md` §Browser compatibility, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E on desktop browsers |
|
||||
| E2E-4 | Manual length override recalculates widths/square feet/bdft correctly on all three browser families | `docs/TECH-SPEC-PIPELINE.md` §4.3, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E: override length, assert recalculation |
|
||||
| E2E-5 | Client crop: slab approximately 80 percent frame; shorter side ≥ 1600 when source allows; undersized source warns and requests retake | `docs/TECH-SPEC-PIPELINE.md` §5, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E: inspect crop output dimensions |
|
||||
|
||||
---
|
||||
|
||||
## When tests are written
|
||||
|
||||
**Deterministic core** (TV-1 through TV-10, validation, AES): test-driven development. Unit tests written before any user interface consumes the functions. Property checks: bdft monotonic in thickness and square feet; fill band; no upscale path.
|
||||
|
||||
**User interface, FastAPI, WooCommerce/inference adapters**: tests-with-code. Each feature commit includes its test and shown execution output.
|
||||
|
||||
**Integration tests**: httpx TestClient with a respx WooCommerce mock covering success, error, duplicate, stale-field, and taxonomy-anchor paths.
|
||||
|
||||
**Full suite must pass with inference disabled.** Call 1/Call 2 cases are gated after Gate C is green.
|
||||
|
||||
bdft equals square feet times thickness in inches (no divide-by-12). TV-3 proves the identity. Gate B requires TV-3, TV-6, TV-7, and TV-10 to show output on real fixtures.
|
||||
|
||||
---
|
||||
|
||||
## Cross-reference
|
||||
|
||||
| These cases | Source of truth document(s) |
|
||||
|---|---|
|
||||
| TV-1 through TV-10 | `docs/TECH-SPEC-PIPELINE.md` §8 |
|
||||
| V-1 through V-3 | `docs/TECH-SPEC-PIPELINE.md` §2, `docs/OPENAPI.md` §validation |
|
||||
| AES-1 through AES-2 | `docs/ARCHITECTURE.md` §5, `docs/AGENTS.md` §4 |
|
||||
| GC-1 through GC-5, W-1 through W-5 | `docs/CONTENT-WOO.md` §2.4–2.6, `docs/OPENAPI.md` §slabs/§settings, `docs/DEPLOYMENT.md` §3 |
|
||||
| INF-1 through INF-4 | `docs/OPENAPI.md` §settings, `docs/AGENTS.md` §6 |
|
||||
| UI-1 through UI-5 | `docs/TECH-SPEC-PIPELINE.md` §3–§4, `docs/UX.md` §Capture/§Review |
|
||||
| UIE-1 through UIE-10 | `docs/UX.md` §Review/§Publish, `docs/CONTENT-WOO.md` §2.5–2.6, `docs/IMPL-PLAN.md` Phase 3 |
|
||||
| C1-1 through C2-4 | `docs/AGENTS.md` §6–§7, `docs/PROMPTS.md` §Call 1/2 |
|
||||
| OPS-1 through OPS-5, E2E-1 through E2E-5 | `docs/DEPLOYMENT.md` §1–§8, `docs/IMPL-PLAN.md` Phase 6 |
|
||||
| INS-1 | `docs/OPENAPI.md` §health, `docs/AGENTS.md` §6 |
|
||||
| INS-2 | issue #6 |
|
||||
| INS-3 through INS-4 | `docs/DATA-MODEL.md` §inference_log/sync_log, `docs/AGENTS.md` §6 |
|
||||
| FUND-1 through FUND-25 | `docs/AGENTS.md` §1–§9, `docs/ARCHITECTURE.md` §5, `docs/OPENAPI.md`, `docs/DATA-MODEL.md`, `docs/CONTENT-WOO.md`, `docs/DEPLOYMENT.md` |
|
||||
|
||||
---
|
||||
|
||||
## Issue #19 mapping
|
||||
|
||||
This spec folds affirmative case substance from issue #19 where the rule exists in a live doc. Issue #19 is not closed by this work.
|
||||
|
||||
| Issue #19 item | Cases | Source of truth document(s) |
|
||||
|---|---|---|
|
||||
| #2 portable multi-turn | INF-2, INF-3, INF-4, C2-1, C2-2 | `docs/OPENAPI.md` §settings, `docs/ARCHITECTURE.md` §9 |
|
||||
| #3 duplicate SKU wording | GC-2, W-2, UIE-3 | `docs/OPENAPI.md` §slabs, `docs/CONTENT-WOO.md` §2.5 |
|
||||
| #5 Application Passwords | AES-1, AES-2, API-3 | `docs/ARCHITECTURE.md` §5, `docs/DATA-MODEL.md` settings |
|
||||
| #6 instrumentation | INS-1, INS-2, INS-3, INS-4 | `docs/DATA-MODEL.md` sync_log/inference_log, issue #6 |
|
||||
| #8/#9 Call 1 prefill + 0.7 | UIE-2, C1-2, C1-3 | `docs/AGENTS.md` §6, `docs/PROMPTS.md` §Call 1 |
|
||||
| #11 WOO_BASE_URL | GC-4, UIE-8 | `docs/AGENTS.md` §5, `docs/DEPLOYMENT.md` §3 |
|
||||
| #12 synced-species-only | C1-1, TAX-2 | `docs/ARCHITECTURE.md` §7, `docs/CONTENT-WOO.md` §2.2 |
|
||||
| #14 taxonomy_anchor | TAX-1, W-3, W-4, API-7 | `docs/ARCHITECTURE.md` §7, `docs/OPENAPI.md` §taxonomy |
|
||||
| #15 four inline knobs | UI-1, UIE-9, UIE-10 | `docs/TECH-SPEC-PIPELINE.md` §3.3, `docs/UX.md` §Capture |
|
||||
| #17 shared validation | V-1, V-2, V-3, API-8 | `docs/OPENAPI.md` §validation |
|
||||
| #18 409/422 recovery | UIE-3, UIE-4, UIE-5, UIE-6 | `docs/CONTENT-WOO.md` §2.5–2.6, `docs/OPENAPI.md` §slabs |
|
||||
|
||||
---
|
||||
|
||||
## Gates and phase map
|
||||
|
||||
| Phase / Gate | Cases | Exit evidence |
|
||||
|---|---|---|
|
||||
| Phase 0 / Gate B | TV-1 through TV-10, V-1 through V-3, AES-1 through AES-2, H-1, D-1, OPS-1, GC-5 | Ty confirms TV-3, TV-6, TV-7, TV-10 on real fixtures; health up; AES round-trip; draft store; unit/API automated |
|
||||
| Gate C (early Phase 1) | GC-1 through GC-4, W-1 through W-5, INF-1 through INF-4, UI-1 through UI-5 | Ty opens one `SLAB-UAT-*` WooCommerce draft in real store admin; inference OFF; mocked-store not exit |
|
||||
| Phase 1 remainder | API-1 through API-10, TAX-1, TAX-2, TAX-3 | Agent-written test automation drives full calibrated to ready cycle; OPENAPI matches; revision and taxonomy green |
|
||||
| Phase 3 | UIE-1 through UIE-10 | Ty publishes test slab as Woo draft `SLAB-UAT-*`; automation UI cases; Ty is exit |
|
||||
| Phase 5 | C1-1 through C2-4, OFF-1, OFF-2 | Ty runs species detection on 3 real slabs with judgment on acceptance; automation Call 1/2 cases; inference disabled path green |
|
||||
| Phase 6 / production | OPS-2 through OPS-5, INS-1 through INS-4, E2E-1 through E2E-5 | Deployment smoke automated; Ty walks `docs/UAT-PRACTICE.md` and signs off on UAT; v1 done |
|
||||
|
||||
---
|
||||
|
||||
## Rules that do not change
|
||||
|
||||
- Inference is optional. The full suite passes with inference disabled. Call 1/Call 2 cases are gated after Gate C.
|
||||
- bdft equals square feet times thickness in inches. No divide-by-12. TV-3 proves the identity.
|
||||
- Client is authoritative for deterministic math; server stores client-sent numbers.
|
||||
- No new product locks in this document. All rules reference existing live docs or issue #19 substance.
|
||||
@@ -1,227 +0,0 @@
|
||||
# UAT Practice Walk: one `SLAB-UAT-*` listing
|
||||
|
||||
Status: WALK · for Ty to run · SlabUploader
|
||||
|
||||
This is the walkable practice plan. It proves one listing end to end without touching a live product.
|
||||
Follow the sections in order. Each one names what you do, what you should see, and where the rule
|
||||
lives.
|
||||
|
||||
**Inference is OFF for this walk.** The optional ON path is only valid after Gate C is green and
|
||||
the inference endpoint is already configured. Inference stays off here.
|
||||
|
||||
---
|
||||
|
||||
## 1. Host and deploy preconditions
|
||||
|
||||
Before this walk, the app must already be on the inventoried host. This section only checks that.
|
||||
Host IPs and hostnames come from `deploy/INVENTORY.md`.
|
||||
|
||||
1. **Inventory is filled.** `deploy/INVENTORY.md` has `APP_HOST`, `APP_HOSTNAME`, ports, Caddy
|
||||
location, and the smoke results. It is the only source for what runs where on this host.
|
||||
See `docs/DEPLOYMENT.md` §1 for the worksheet rules.
|
||||
2. **Reachable over LAN/Tailscale.** Your phone reaches `https://${APP_HOSTNAME}` on the same
|
||||
network (LAN or Tailscale). No public exposure. Verify with a browser, not `curl`.
|
||||
3. **HTTPS only.** The URL is `https://`. The browser shows a valid certificate. If the phone
|
||||
warns, the Caddy TLS trust is not set up yet. That is a deploy problem, not a listing problem.
|
||||
4. **Health passes.** In a browser on the phone, open `https://${APP_HOSTNAME}/api/health`.
|
||||
You should see an ok response. This is the same check in `docs/DEPLOYMENT.md` §8 step 1.
|
||||
5. **Store URL is set.** `WOO_BASE_URL` is in the host `.env` and points at the store over
|
||||
`https://`. It is not something you type in the app. See `docs/DEPLOYMENT.md` §3 and §5.
|
||||
|
||||
If any of these fail, fix the deploy before continuing. This walk does not cover Gate B host work.
|
||||
It assumes the app is up and reachable.
|
||||
|
||||
---
|
||||
|
||||
## 2. WordPress Application Password setup
|
||||
|
||||
You do this once per store, in the store's WordPress admin. Do it before you open the app's
|
||||
Settings.
|
||||
|
||||
1. **Store is on HTTPS.** WordPress only offers Application Passwords over HTTPS. The store must
|
||||
already be on TLS. If it is not, stop and fix the store first.
|
||||
2. **Dedicated low-privilege user.** Create or use a WordPress user that can create and edit
|
||||
products and upload media. The store admin login is not reused. A shop manager role or a custom
|
||||
role with product create/edit plus media upload is enough.
|
||||
3. **Generate the password.** Sign in as that user. Go to **Users → Profile → Application
|
||||
Passwords**. Generate a password and label it "SlabUploader". Copy the password. WordPress
|
||||
shows it once.
|
||||
4. **Enter it in the app.** Open the app's Settings on the phone. Enter the WordPress username and
|
||||
the application password. The server stores them encrypted. The browser does not keep them.
|
||||
5. **Run `test-woo`.** In Settings, tap the test. It should report ok. This also resyncs the
|
||||
store's species, categories, tags, and attributes into the app. If it fails, the username or
|
||||
password is wrong, or the store is unreachable.
|
||||
|
||||
Rules: this is a WordPress Application Password, not WooCommerce consumer keys (`ck_`/`cs_`).
|
||||
The app never calls the store from the browser. FastAPI is the only caller. Rotate by revoking
|
||||
the old password in the WP profile and entering a new one in Settings, then re-running
|
||||
`test-woo`. Full lock: `AGENTS.md` §4 and §5, `docs/DEPLOYMENT.md` §5.
|
||||
|
||||
---
|
||||
|
||||
## 3. Practice build rules
|
||||
|
||||
These rules keep practice runs invisible to customers. They are locked. Changes are not made for
|
||||
the walk.
|
||||
|
||||
- **SKU prefix `SLAB-UAT-*`.** Every practice listing uses a SKU that starts with `SLAB-UAT-`.
|
||||
Pick a unique one each time, for example `SLAB-UAT-001`.
|
||||
- **Always a Woo draft.** A `SLAB-UAT-*` SKU creates a WooCommerce draft even if Settings say
|
||||
publish. Customers cannot open it. This is hard rule in `AGENTS.md` §5.
|
||||
- **`woo_create_status` defaults to draft.** The Settings field that controls create status
|
||||
defaults to `draft`. Practice uses the default. If it is `publish`, the
|
||||
`SLAB-UAT-*` rule still forces a draft.
|
||||
- **Customers never see practice listings.** A Woo draft is hidden from the storefront. If you
|
||||
can see the product on the live store, something is wrong.
|
||||
|
||||
If a practice SKU is not `SLAB-UAT-*`, it is not a practice run. Real SKUs are not published in
|
||||
this walk.
|
||||
|
||||
---
|
||||
|
||||
## 4. Prove one listing end to end
|
||||
|
||||
This is the main walk. Run it on a phone browser first, then repeat on a PC browser. Both are in
|
||||
the signed compatibility matrix (`docs/UX.md`, signed 2026-09-06).
|
||||
|
||||
Supported browsers: iOS Safari, Android Chrome on phones; desktop Chrome, Edge, Firefox on PC.
|
||||
Exact version pins are tracked under issue #4. If the browser is not supported, the app shows a
|
||||
hard stop. Switch to a supported browser.
|
||||
|
||||
### 4.1 Capture
|
||||
|
||||
1. Open the app on the phone. Start a new slab.
|
||||
2. Take 1 to 5 photos of the slab. The first should be top-down, lens parallel to the broad
|
||||
face. A tilted shot makes the numbers wrong. Retake if it is tilted.
|
||||
3. **Mask overlay and four knobs.** The app draws a mask over the photo. You see which pixels are
|
||||
slab and which are not. Tune the four knobs: **Sheet** (auto/green/black), **Sensitivity**,
|
||||
**Edge offset**, **Feather**. Each change re-runs the mask immediately. Look at the edge
|
||||
against the real wood. If it is still off, retake the photo.
|
||||
4. **Confirm the mask.** Tap confirm.
|
||||
5. **Length axis.** The app draws the bounding rectangle and the length axis. Confirm it follows
|
||||
the slab's long direction. Rotate if it is skewed. On a nearly square slab, you say which way
|
||||
is length.
|
||||
6. **Enter numbers by hand.** Length in 1/8" steps. Thickness as a 1/8" pick. SKU: type
|
||||
`SLAB-UAT-001` (or your chosen practice SKU).
|
||||
7. **Check the computed numbers.** The browser shows square feet, board feet, and width samples.
|
||||
Board feet = square feet × thickness in inches. No divide-by-12. If the numbers look wrong,
|
||||
go back and fix the mask or the length.
|
||||
8. **Continue.** This uploads the originals, the processed PNGs, and the numbers to the server.
|
||||
The slab status becomes `calibrated`.
|
||||
|
||||
### 4.2 Review
|
||||
|
||||
1. You are on the review screen. Fill every required field. Inference is OFF, so everything starts
|
||||
empty.
|
||||
2. **Species.** Pick exactly one from the synced store list. The list came from `test-woo`.
|
||||
Only species in the list may be typed.
|
||||
3. **Wood categories.** Pick at least one from the synced list.
|
||||
4. **Edge type, figure, grade.** Pick from the synced lists. At least one figure, at least one
|
||||
grade.
|
||||
5. **Thickness band.** Pick the Woo band that the measured thickness rounds up into.
|
||||
6. **Moisture.** Keep the default (kiln-dried) or change it.
|
||||
7. **fig-* tags.** Pick at least one.
|
||||
8. **feat-* tags.** Zero or more. Only pick existing `feat-*` tags.
|
||||
9. **Price.** A recommendation fills from the species $/bdft rule times board feet. You can
|
||||
override it. If there is no rule for the species, the price starts empty. Type it. Publish
|
||||
is still allowed with a manual price.
|
||||
10. **Title and description.** You can type them, or leave them for templates at publish.
|
||||
Templates inject the deterministic numbers. Generate text is OFF for this walk.
|
||||
|
||||
Every empty required field shows an inline nudge where it sits. The slab cannot reach `ready`
|
||||
until the full set is filled.
|
||||
|
||||
### 4.3 Publish
|
||||
|
||||
1. Tap **Publish**.
|
||||
2. The server checks the SKU against the store. If `SLAB-UAT-001` is new, it creates the
|
||||
product.
|
||||
3. **What you should see:** a success message on the screen. The local draft and its photos are
|
||||
gone from the app. The slab status in the app is `published`.
|
||||
4. **What that does NOT mean:** the product is not live in the store. It is a WooCommerce draft.
|
||||
The app's "published" means the store create succeeded and the local row was cleaned up.
|
||||
|
||||
### 4.4 Confirm in the store
|
||||
|
||||
1. Open the store's WooCommerce admin.
|
||||
2. Find the product by SKU `SLAB-UAT-001`.
|
||||
3. **It must be a draft.** Status is draft, not published.
|
||||
4. **Check the fields:** SKU, price, category (species), tags (fig-*, feat-*), attributes
|
||||
(Edge Type, Figure, Grade, Thickness, Moisture), and images (the processed transparent PNGs).
|
||||
5. **Open the live storefront.** The product must not appear. A draft is invisible to customers.
|
||||
|
||||
### 4.5 Repeat on a PC browser
|
||||
|
||||
Repeat 4.1 through 4.4 on a desktop browser (Chrome, Edge, or Firefox). Use a different
|
||||
practice SKU, for example `SLAB-UAT-002`. The flow must work the same way. This is the signed
|
||||
PC-browser compatibility check.
|
||||
|
||||
---
|
||||
|
||||
## 5. Pass and fail checks
|
||||
|
||||
You can see all of these without reading code.
|
||||
|
||||
| Check | Where | Pass looks like |
|
||||
|---|---|---|
|
||||
| Health endpoint | Phone browser, `https://${APP_HOSTNAME}/api/health` | ok response |
|
||||
| `test-woo` ok | App Settings | ok; species list is populated |
|
||||
| `woo_create_status` is draft | App Settings | shows `draft` (or `publish`, but `SLAB-UAT-*` forces draft anyway) |
|
||||
| Slab reaches `calibrated` | App, after capture | status is `calibrated` |
|
||||
| Slab reaches `ready` | App, after review | no empty required fields; inline nudges gone |
|
||||
| Publish succeeds | App, after Publish | success message; local draft is gone |
|
||||
| Woo product exists as draft | Store admin, products | SKU `SLAB-UAT-*`, status draft |
|
||||
| SKU prefix correct | Store admin | starts with `SLAB-UAT-` |
|
||||
| Store not live | Live storefront URL | product does not appear |
|
||||
| Board feet identity | App review screen, or a fixture | bdft = sqft × thickness in inches; no divide-by-12 |
|
||||
| Images are processed PNGs | Store admin, product images | transparent PNGs, not the original JPEGs |
|
||||
|
||||
### Duplicate SKU recovery
|
||||
|
||||
If you publish the same SKU twice, the second time the app stops before creating a second product.
|
||||
Under the SKU field you see: "This SKU already exists in the store (any status)." Two paths:
|
||||
edit the SKU to a new value, or open the existing listing. The draft stays in the app. Nothing is
|
||||
lost. This is the expected behavior, not a bug. See `docs/CONTENT-WOO.md` §2.5.
|
||||
|
||||
### What a fail looks like
|
||||
|
||||
- **No success message after Publish.** The app shows a plain message that the listing could not
|
||||
be created. No status number, no stack trace. The server kept a log. You can retry from the
|
||||
same screen without re-photographing.
|
||||
- **A value is no longer valid.** If a category, attribute, or price was removed from the store
|
||||
between sync and publish, that field shows "This value is no longer valid. Pick from the
|
||||
current list." Re-pick and retry.
|
||||
- **Store unreachable.** A plain message says the store could not be reached. Check the network
|
||||
and retry.
|
||||
|
||||
---
|
||||
|
||||
## 6. Cleanup
|
||||
|
||||
After the walk, decide what to do with the Woo draft UAT product.
|
||||
|
||||
- **Leave it or delete it.** Both are fine. It is a draft. Customers cannot see it. If you delete
|
||||
it, the store admin is the place to do it. The app does not delete store products.
|
||||
- **Never customer-visible.** If the product is visible on the live storefront, it is not a
|
||||
draft. That is a bug. Stop and report it.
|
||||
|
||||
**Real live publish is a separate step.** It is not part of this walk. A real product uses a
|
||||
non-UAT SKU (no `SLAB-UAT-` prefix) and is published only after you review it. That is a
|
||||
different decision. That step is not run here. The name of that step is **final POC publish**, and it
|
||||
is gated on your review of one real listing.
|
||||
|
||||
---
|
||||
|
||||
## Where each rule lives
|
||||
|
||||
| Rule | Source |
|
||||
|---|---|
|
||||
| Practice SKU forces draft | `AGENTS.md` §5 |
|
||||
| `woo_create_status` default draft | `AGENTS.md` §5, `docs/CONTENT-WOO.md` §2.4 |
|
||||
| App Password setup, not consumer keys | `AGENTS.md` §4, `docs/DEPLOYMENT.md` §5 |
|
||||
| Host inventory before deploy | `docs/DEPLOYMENT.md` §1, `deploy/INVENTORY.md` |
|
||||
| Capture → review → publish flow | `docs/UX.md` (SIGNED 2026-09-06) |
|
||||
| Board feet identity | `docs/TECH-SPEC-PIPELINE.md` |
|
||||
| Duplicate SKU recovery | `docs/CONTENT-WOO.md` §2.5, `docs/UX.md` Publish |
|
||||
| PC browser compatibility | `docs/UX.md` Browser compatibility |
|
||||
| Gate C = early Phase 1 | `docs/IMPL-PLAN.md` Phase 1, `AGENTS.md` §0b |
|
||||
@@ -1,487 +0,0 @@
|
||||
# UX Design — wireframes (non-normative)
|
||||
|
||||
Status: DESIGN · non-normative · 2026-09-03 · SlabUploader
|
||||
|
||||
**Not normative.** Signed presentation SoT is `docs/UX.md` (phone and PC browsers). If a wireframe here disagrees with `docs/UX.md`, AGENTS, or TECH-SPEC, follow those and ignore the wireframe. These ASCII screens are layout sketches for discussion, drawn at a 375px phone width; they do not lock mobile-only or override the phone+PC matrix.
|
||||
|
||||
Functional rules live in `docs/UX.md`. Confidence gating: `AGENTS.md` §6.
|
||||
Data model and status machine: `docs/DATA-MODEL.md`.
|
||||
|
||||
---
|
||||
|
||||
## Screen inventory
|
||||
|
||||
1. Settings (once)
|
||||
2. First-run guidance (once per device)
|
||||
3. Capture
|
||||
4. Length axis
|
||||
5. Type values
|
||||
6. Review
|
||||
7. Title / Description
|
||||
8. Publish
|
||||
9. Error states
|
||||
|
||||
---
|
||||
|
||||
## 1. Settings
|
||||
|
||||
One-time setup. All screen. Back to home after save.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Settings │
|
||||
├─────────────────────────────────────┤
|
||||
│ Store URL │
|
||||
│ https://www.whidbeywoodstore.com │
|
||||
│ │
|
||||
│ WP Username │
|
||||
│ [ slab-uploader ] │
|
||||
│ Application Password │
|
||||
│ [ •••••••••••••••••••• ] │
|
||||
│ [ Test Connection ] │
|
||||
│ │
|
||||
│ Inference │
|
||||
│ Endpoint: [ http://192.168.x.x:v1 ]│
|
||||
│ API Key: [ •••••••••••••••••••• ]│
|
||||
│ [ Test Connection ] │
|
||||
│ [ Enable Vision ] │
|
||||
│ [ Enable Content ] │
|
||||
│ │
|
||||
│ Pricing Rules │
|
||||
│ [+ Add Rule] [Edit] │
|
||||
│ │
|
||||
│ Publish Status: [ Draft ▼ ] │
|
||||
│ Brand Voice: [ Premium lumber... ]│
|
||||
│ GEO Context: [ Locally milled... ]│
|
||||
│ │
|
||||
│ [ Reset Capture Knobs ] │
|
||||
│ [ Refresh Store Lists ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Interaction:
|
||||
- Test Connection (WP): attempts REST v3 auth, shows green check or red error. Always pulls fresh taxonomy on success.
|
||||
- Test Connection (Inference): two-turn probe. Shows stateful/stateless/fail.
|
||||
- Enable Vision: feature flag for Call 1. Defaults off.
|
||||
- Enable Content: feature flag for Call 2. Defaults off.
|
||||
- Publish Status: dropdown, default Draft.
|
||||
|
||||
---
|
||||
|
||||
## 2. First-run guidance
|
||||
|
||||
One short card shown on first launch. Dismissed via swipe or tap.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ │
|
||||
│ First run on the floor │
|
||||
│ │
|
||||
│ Lay a green or black sheet │
|
||||
│ under the slab. │
|
||||
│ │
|
||||
│ Shoot from above with the lens │
|
||||
│ parallel to the face. │
|
||||
│ │
|
||||
│ Put a tape measure in the shot │
|
||||
│ so you can type the length later. │
|
||||
│ │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Got it ] │
|
||||
│ │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Capture
|
||||
|
||||
Camera view. Source photo on screen. Mask overlay draws on the source.
|
||||
Four knobs sit next to the overlay.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Capture [R] │
|
||||
│ ┌─────────────────────────────────┐ │
|
||||
│ │ │ │
|
||||
│ │ [ SOURCE PHOTO ] │ │
|
||||
│ │ │ │
|
||||
│ │ ~ mask overlay ~ │ │
|
||||
│ │ │ │
|
||||
│ └─────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Sheet: [ Auto ▼ ] │
|
||||
│ Sensitivity: [◄─────●───►] │
|
||||
│ Edge Offset: [◄───●───►] │
|
||||
│ Feather: [◄─────●───►] │
|
||||
│ │
|
||||
│ [ Retake ] [ Confirm ] │
|
||||
└─────────────────────────────────────┘
|
||||
|
||||
R = retake current photo (new shot, same knobs)
|
||||
```
|
||||
|
||||
Interaction:
|
||||
- Moving any knob immediately re-runs background removal on the current photo.
|
||||
- The overlay refreshes on the source image. No apply/save step. No server round-trip.
|
||||
- Confirm moves to length axis. Retake takes a new photo.
|
||||
- Knobs persist in localStorage until reset-to-default in Settings.
|
||||
|
||||
---
|
||||
|
||||
## 4. Length axis
|
||||
|
||||
Bounding rectangle and length axis drawn over the confirmed mask.
|
||||
Width sample lines every 6 inches.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Length Axis │
|
||||
│ ┌─────────────────────────────────┐ │
|
||||
│ │ │ │
|
||||
│ │ ┌───────────────┐ │ │
|
||||
│ │ │ SLAB MASK │ │ │
|
||||
│ │ │ ──── AXIS ── │ │ │
|
||||
│ │ │ ┌──┐ ┌──┐ ┌──┐ │ │
|
||||
│ │ │ │ 6"│ │6"│ │6"│ │ │
|
||||
│ │ └───────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ └─────────────────────────────────┘ │
|
||||
│ │
|
||||
│ [ Rotate ↻ ] [ Confirm ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Interaction:
|
||||
- Rotate adjusts the axis. Width samples and sqft update live.
|
||||
- On nearly square slabs, user picks which side is length.
|
||||
- Confirm moves to type values.
|
||||
|
||||
---
|
||||
|
||||
## 5. Type values
|
||||
|
||||
Manual values win. Phone computes sqft, bdft, widths.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Type Values │
|
||||
│ │
|
||||
│ SKU │
|
||||
│ [ BW-0042 ] │
|
||||
│ │
|
||||
│ Length (inches) │
|
||||
│ [ 96.0 ] │
|
||||
│ │
|
||||
│ Thickness (inches) │
|
||||
│ [ 1.5 ] │
|
||||
│ │
|
||||
│ Computed (read-only) │
|
||||
│ sqft: 0.64 bdft: 0.96 │
|
||||
│ widths: 14.0 — 22.0 (avg 18.2) │
|
||||
│ │
|
||||
│ [ Done ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Interaction:
|
||||
- SKU: `[A-Z0-9-]{3,24}`. Field-exit check against validation rules.
|
||||
- Length: 1/8" step. Typing recalculates widths/sqft/bdft live.
|
||||
- Thickness: 1/8" step pick.
|
||||
- Done moves to review screen. Draft uploads, status → calibrated.
|
||||
|
||||
---
|
||||
|
||||
## 6. Review
|
||||
|
||||
All store fields. Per-field nudges for missing mandatory fields.
|
||||
Vision pre-populates when confidence ≥ 0.7. Empty when below.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Review [X]│
|
||||
│ ────────────────────────────────── │
|
||||
│ Photos │
|
||||
│ [ ▢ ] [ ▢ ] [ ▢ ] [ ▢ ] [ ▢ ] │
|
||||
│ (processed PNG thumbnails) │
|
||||
│ ────────────────────────────────── │
|
||||
│ SKU: BW-0042 │
|
||||
│ Length: 96.0" Thickness: 1.5" │
|
||||
│ sqft: 0.64 bdft: 0.96 │
|
||||
│ Widths: 14.0 — 22.0 (avg 18.2) │
|
||||
│ ────────────────────────────────── │
|
||||
│ Species [ Black Walnut ▼ ] │
|
||||
│ Wood Cat [ Live edge ▼ ] │
|
||||
│ Edge Type [ Live Edge ▼ ] │
|
||||
│ Figure [ Cathedral ▼ ] │
|
||||
│ Grade [ Premium ▼ ] │
|
||||
│ Fig Tags [ Cathedral ▼ ] │
|
||||
│ Feat Tags [ None ▼ ] │
|
||||
│ ────────────────────────────────── │
|
||||
│ Thickness Band: [ 1"–1 1/2" ▼ ] │
|
||||
│ Moisture: [ Kiln-dried ▼ ] │
|
||||
│ ────────────────────────────────── │
|
||||
│ Price: [ $12.00 ] (rec $12.00) │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Review Title / Desc ] [ Publish ]│
|
||||
└─────────────────────────────────────┘
|
||||
|
||||
X = exit review, returns to calibrated draft
|
||||
```
|
||||
|
||||
Per-field gating:
|
||||
- Each missing mandatory field shows an inline empty state as the user works.
|
||||
- Below-threshold Call 1 leaves taxonomy fields empty. The user sees the empty
|
||||
field with a nudge: "Select species" or "Select a figure type".
|
||||
- Below-threshold leaves taxonomy fields empty. The user must manually fill species, wood
|
||||
category, edge type, figure, grade, fig-* tags, and grade to reach ready.
|
||||
- Submit-time validation only fires after all fields are filled.
|
||||
|
||||
Pre-populated field appearance:
|
||||
- Filled by Call 1: field shows the value with a small "AI" badge. User can
|
||||
tap to change. Badge disappears on edit.
|
||||
- User-filled: no badge.
|
||||
|
||||
Gating details:
|
||||
- Mandatory: exactly one species, ≥1 wood category, 1 edge type, ≥1 figure,
|
||||
≥1 fig-* tag, ≥1 grade, thickness band, moisture, price, SKU, length,
|
||||
thickness, sqft/bdft/widths, ≥1 inventory PNG.
|
||||
- Optional: feat-* tags (zero is fine).
|
||||
- Publish button is disabled until all mandatory fields are filled.
|
||||
|
||||
---
|
||||
|
||||
## 7. Title / Description
|
||||
|
||||
Type or generate. Generate text is user-initiated.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Title & Description │
|
||||
│ ────────────────────────────────── │
|
||||
│ Title │
|
||||
│ [ Black Walnut 8ft × 18.2in Slab... │
|
||||
│ ────────────────────────────────── │
|
||||
│ Short Title │
|
||||
│ [ Black Walnut Slab — Cathedral ] │
|
||||
│ ────────────────────────────────── │
|
||||
│ Description │
|
||||
│ [ A one-of-a-one cathedral black... │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Generate Text ] [ Done ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Interaction:
|
||||
- Generate Text: triggers Call 2. Button disabled if content LLM is off or
|
||||
inference endpoint unreachable. LLM writes prose only. Templates inject
|
||||
deterministic numbers. User can always edit the result.
|
||||
- Done: returns to review. Title/description stored on the slab.
|
||||
|
||||
---
|
||||
|
||||
## 8. Publish
|
||||
|
||||
Status polling. Result shown inline.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Publishing... │
|
||||
│ │
|
||||
│ ──────── ● ──────── │
|
||||
│ │
|
||||
│ Creating store listing... │
|
||||
│ Please wait. │
|
||||
│ │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Success:
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Published! │
|
||||
│ │
|
||||
│ Listing created as draft. │
|
||||
│ SKU: BW-0042 │
|
||||
│ Store product ID: 1042 │
|
||||
│ │
|
||||
│ [ Open in Store ] [ Done ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Failed:
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Publish Failed │
|
||||
│ │
|
||||
│ The store rejected the listing. │
|
||||
│ Error shown inline on the field. │
|
||||
│ │
|
||||
│ [ Retry ] [ Back to Review ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Error and empty states
|
||||
|
||||
### 9.1 Mask failure
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Mask Quality │
|
||||
│ ────────────────────────────────── │
|
||||
│ Cannot isolate the slab edge. │
|
||||
│ Adjust the knobs or retake. │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Retake ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.2 Axis misalignment
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Axis Check │
|
||||
│ ────────────────────────────────── │
|
||||
│ Rotate the axis to match the │
|
||||
│ prevailing length of the slab. │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Rotate ↻ ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.3 Source too small after crop
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Photo Quality │
|
||||
│ ────────────────────────────────── │
|
||||
│ Photo will be too small after │
|
||||
│ cropping. Please retake with a │
|
||||
│ closer shot. │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Retake ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.4 SKU duplicate
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ SKU Check │
|
||||
│ ────────────────────────────────── │
|
||||
│ This SKU already exists in the │
|
||||
│ store (any status). │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Edit SKU ] [ Open Existing ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.5 Stale taxonomy value
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Field Check │
|
||||
│ ────────────────────────────────── │
|
||||
│ This value is no longer valid. │
|
||||
│ Pick from the current list. │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Refresh Store Lists ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.6 Store unreachable
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Connection │
|
||||
│ ────────────────────────────────── │
|
||||
│ Cannot reach the store. Check your │
|
||||
│ connection and settings. │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Retry ] [ Open Settings ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.7 Vision off or below threshold
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Review (vision off) │
|
||||
│ ────────────────────────────────── │
|
||||
│ Species [ Select ▼ ] ◉ Select species
|
||||
│ Wood Cat [ Select ▼ ] ◉ Select category
|
||||
│ Edge Type [ Select ▼ ] ◉ Select edge
|
||||
│ Figure [ Select ▼ ] ◉ Select figure
|
||||
│ ────────────────────────────────── │
|
||||
└─────────────────────────────────────┘
|
||||
|
||||
◉ = inline nudge (per-field)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Interaction patterns
|
||||
|
||||
### Per-field gating (review screen)
|
||||
- Each mandatory field that is empty shows an inline nudge as the user works.
|
||||
- The nudge is a small text hint to the right of the field.
|
||||
- Below-threshold Call 1 leaves fields empty with nudges visible.
|
||||
- Fill the field to dismiss the nudge.
|
||||
- Publish button stays disabled until all mandatory fields are filled.
|
||||
|
||||
### Pre-populated field state
|
||||
- Fields filled by Call 1 show the value with an "AI" badge.
|
||||
- User can tap the field to change it. The badge disappears on edit.
|
||||
- User-filled fields have no badge.
|
||||
|
||||
### Knob interaction (capture screen)
|
||||
- All four knobs are on the capture screen next to the overlay.
|
||||
- Moving a knob immediately re-runs background removal.
|
||||
- No apply/save step. No server round-trip for mask tuning.
|
||||
|
||||
### Axis rotation
|
||||
- Drag or tap to rotate the axis. Width samples and sqft update live.
|
||||
- Confirm locks the axis for measurement.
|
||||
|
||||
### Generate text
|
||||
- Button only appears if content LLM is enabled and inference is reachable.
|
||||
- Disabled if the text service is down.
|
||||
- Never runs automatically. User taps it.
|
||||
|
||||
### Publish flow
|
||||
- Tap Publish. Status moves to publishing. Poll for result.
|
||||
- Success: show result, offer to open in store.
|
||||
- Failed: show error detail, keep draft and photos, allow retry.
|
||||
- SLAB-UAT-* SKUs always create as Woo draft regardless of settings.
|
||||
|
||||
---
|
||||
|
||||
## Browser compatibility gate
|
||||
|
||||
Shown on load if browser lacks required APIs.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Browser Update │
|
||||
│ ────────────────────────────────── │
|
||||
│ This app requires a recent browser. │
|
||||
│ Please update Safari or Chrome, │
|
||||
│ then try again. │
|
||||
│ ────────────────────────────────── │
|
||||
│ [ Update Browser ] │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## UAT test cases (derived from wireframes)
|
||||
|
||||
1. **Settings once**: enter WP credentials, test connection, taxonomy syncs.
|
||||
2. **First-run guidance**: card shows and dismisses.
|
||||
3. **Capture**: take photo, mask overlays, adjust knob, overlay refreshes live, confirm.
|
||||
4. **Length axis**: bounding rect draws, rotate axis, confirm, widths update.
|
||||
5. **Type values**: enter SKU/length/thickness, computed values appear, done.
|
||||
6. **Review — vision on, ≥ 0.7**: taxonomy fields pre-filled with AI badge, editable.
|
||||
7. **Review — vision on, < 0.7**: taxonomy fields empty, per-field nudges visible, user fills manually.
|
||||
8. **Review — vision off**: all taxonomy fields empty, per-field nudges visible, user fills manually.
|
||||
9. **Publish — success**: draft created, product ID stored, images purged.
|
||||
10. **Publish — duplicate SKU**: error on SKU field, edit SKU or open existing.
|
||||
11. **Publish — stale taxonomy**: error on field, refresh store lists, pick current option.
|
||||
12. **Publish — SLAB-UAT-***: always creates as draft regardless of settings.
|
||||
13. **Generate text**: button visible when enabled, disabled when service down, LLM prose injected.
|
||||
14. **Retake paths**: mask failure → retake, source too small → retake.
|
||||
@@ -1,235 +0,0 @@
|
||||
# Mill-owner UX — phone and PC browsers
|
||||
|
||||
Status: SIGNED · 2026-09-06 PT · Ty approved with PC browsers in the compatibility matrix · SlabUploader
|
||||
|
||||
This is the presentation spec for the mill-owner flow. It says what a mill owner sees and does, in the
|
||||
order they do it. The rules behind each screen live elsewhere: `AGENTS.md` locks the product
|
||||
decisions, `docs/TECH-SPEC-PIPELINE.md` owns the math and image prep, `docs/DATA-MODEL.md` owns
|
||||
the store row and its statuses, `docs/CONTENT-WOO.md` owns listing copy and the Woo payload,
|
||||
and `docs/OPENAPI.md` owns the wire. This file names what shows up on screen; it does not restate
|
||||
those rules.
|
||||
|
||||
The reader is a mill owner photographing one slab at a time, online, from a supported browser on a
|
||||
phone or a PC. The app is a single column of screens, top to bottom: capture, then review, then
|
||||
publish. There is no dashboard and no batch view in this version. Capture often starts on a phone
|
||||
camera; the same flow must also run on a PC browser.
|
||||
|
||||
## Jobs
|
||||
|
||||
Five jobs cover the whole flow. Each section below names what the owner does, what they see, and
|
||||
the lock that governs it.
|
||||
|
||||
1. **Phone photo to a store listing.** Photograph the slab, confirm the cut and the numbers on
|
||||
the browser, review the listing, create the WooCommerce product. The happy path stays in the
|
||||
browser until the owner confirms the mask and the numbers.
|
||||
2. **Practice drafts customers never see.** A practice run creates a WooCommerce draft with an SKU
|
||||
that starts `SLAB-UAT-`. Customers cannot open it. It is always a draft, even when Settings say
|
||||
publish.
|
||||
3. **Retake when the overlay cut looks wrong.** The mask overlay on the source photo is the only
|
||||
quality check. If the edge is off after tuning the four knobs, the owner retakes the photo.
|
||||
4. **Fill or override store fields.** On review, the owner fills every required field by hand, or
|
||||
keeps what vision filled when it was confident enough. Typed values always win.
|
||||
5. **Publish.** The owner taps publish. The server creates the product in the store and reports the
|
||||
result back on the same screen.
|
||||
|
||||
## Capture: photo to numbers
|
||||
|
||||
The capture flow is one continuous screen with a few confirmations, not separate pages. The owner
|
||||
stays on it from first photo through confirmed mask and axis.
|
||||
|
||||
### Photos
|
||||
|
||||
The owner takes 1 to 5 inventory photos of the slab. The first should be top-down, lens parallel
|
||||
to the broad face; a tilted shot makes square feet and board feet wrong, and retake is the fix.
|
||||
There are no calibration photos in this design. Only inventory photos exist.
|
||||
|
||||
### Mask overlay and four knobs
|
||||
|
||||
The app removes the background sheet and draws the mask as an overlay on the source photo, showing
|
||||
which pixels count as slab and which do not. The owner reviews that edge against the real wood.
|
||||
This is the only quality check in the pipeline. There is no confidence score, no auto-gate, and no
|
||||
photo-quality checker. A clipped or over-inclusive mask shifts every downstream number with nothing
|
||||
later to catch it, so the eye on the overlay is what stands behind the measurement.
|
||||
|
||||
Four knobs sit on this same screen, next to the overlay:
|
||||
|
||||
- **Sheet** — auto, green, or black. Auto samples the borders and picks; the owner overrides when
|
||||
the sheet is an odd color.
|
||||
- **Sensitivity** — one slider from tighter to looser detection.
|
||||
- **Edge offset** — pulls the cut in or out a few pixels so it sits on the wood, not in the sheet
|
||||
or into the grain.
|
||||
- **Feather** — hard edge versus a couple of pixels of blend.
|
||||
|
||||
Changing any knob re-runs background removal immediately and refreshes the overlay. There is no
|
||||
apply step and no server round trip for mask tuning in this version. The four values persist on the
|
||||
browser until reset to default; they are not Settings fields.
|
||||
|
||||
If the edge still looks wrong after tuning, the owner retakes the photo. That is the resolution in
|
||||
this version. A server-side matting path exists in the architecture for awkward backgrounds later,
|
||||
but it is deferred and has no control here.
|
||||
|
||||
### Length axis
|
||||
|
||||
After the mask is confirmed, the app draws the bounding rectangle and the length axis over the slab,
|
||||
with width sample lines perpendicular to that axis. The owner confirms the axis follows the
|
||||
slab's prevailing length. If it is skewed, they rotate it; samples and square feet update live. On a
|
||||
nearly square slab the owner says which way is length.
|
||||
|
||||
### Numbers
|
||||
|
||||
The owner enters length (in 1/8" steps), thickness (a 1/8" pick), and the SKU by hand. The browser
|
||||
then computes square feet, board feet, and width samples from the confirmed mask and axis:
|
||||
|
||||
- Board feet = square feet × thickness in inches. One square foot at one inch thick is one board
|
||||
foot. There is no divide-by-12.
|
||||
- Widths are sampled every 6" along the length axis; the listing carries min, max, and average.
|
||||
- Square feet and board feet show to two decimals.
|
||||
|
||||
These numbers are computed in the browser and stored as sent. The server does not recompute them.
|
||||
|
||||
### Photo prep
|
||||
|
||||
Each inventory photo is cropped to a 3:4 portrait frame with the slab centered at 80% fill, saved as
|
||||
a transparent PNG. If the source has enough pixels, the shorter side lands at 1600 or more after
|
||||
crop. If it cannot reach that, the app warns and asks for a retake; it does not invent pixels. The
|
||||
owner sees the processed result alongside the original while the draft is retained.
|
||||
|
||||
### Continue
|
||||
|
||||
When the mask, axis, length, thickness, and SKU are set, the owner continues. That uploads the
|
||||
originals plus the processed PNGs plus the numbers to the server as a calibrated draft, and moves to
|
||||
review. The slab status becomes `calibrated`.
|
||||
|
||||
## Review: fill or override store fields
|
||||
|
||||
Review is where the listing row gets filled. Every field below maps to a column in the `slabs` table
|
||||
in `docs/DATA-MODEL.md`. The owner can type any of them; vision may have pre-filled some, but typed
|
||||
values always win and every value stays editable.
|
||||
|
||||
### What vision fills, and when
|
||||
|
||||
When inference is on, Call 1 runs after the calibrated draft uploads. It sends all inventory photos
|
||||
downscaled to 1024 plus the store's synced species and attribute lists, and returns a guess
|
||||
with a confidence per field. The threshold is 0.7 by default:
|
||||
|
||||
- A field at or above 0.7 pre-fills on review. It stays editable; the owner can change or clear it.
|
||||
- A field below 0.7 starts empty. The app does not show the model's low-confidence guess as a
|
||||
default, and an empty start is not the same as a finished listing.
|
||||
|
||||
With inference off, every field starts empty and the owner fills all of them by hand. Inference
|
||||
never blocks publish and never auto-publishes. Call 2 (Generate text) does not run on its own; it
|
||||
fires only when the owner taps it.
|
||||
|
||||
### The fields
|
||||
|
||||
The required set for a list-ready slab is the full store row, not species plus one figure:
|
||||
|
||||
- **SKU** — `[A-Z0-9-]{3,24}`. Practice runs use `SLAB-UAT-*`.
|
||||
- **Length and thickness** — from capture; still editable here.
|
||||
- **Square feet, board feet, widths** — shown as the client-computed values, with a manual override
|
||||
path. The owner's typed number wins over the computed one.
|
||||
- **Species** — exactly one leaf category from the synced store list. No hardcoded or invented
|
||||
species; a new store species appears only after the next sync.
|
||||
- **Wood categories** — at least one, from the synced list.
|
||||
- **Edge type** — one term from the synced attributes.
|
||||
- **Figure** — at least one term.
|
||||
- **Grade** — at least one term.
|
||||
- **Thickness band** — the Woo range that the measured thickness rounds up into (for example, a 1"
|
||||
pick lands in the `1"–1 1/2"` band). The exact labels come from the synced store attribute.
|
||||
- **Moisture** — one term, defaulting to kiln-dried. It is never inferred; the owner sets or keeps it.
|
||||
- **fig-* tags** — at least one.
|
||||
- **feat-* tags** — zero or more (character, inclusions, voids, checks map to existing `feat-*`
|
||||
tags only).
|
||||
- **Price** — a recommendation pre-fills from the species $/bdft rule times board feet; the owner may
|
||||
override and that sticks. With no rule for the species, the price starts empty and the owner types
|
||||
it. Publish is still allowed with a manual price.
|
||||
|
||||
Title, short title, and description are not required to reach ready. They can be typed by hand,
|
||||
generated from templates at publish, or written by Generate text (Call 2) when enabled. Templates
|
||||
always run; they inject the deterministic numbers so the model never touches dimensions.
|
||||
|
||||
### How missing fields show up
|
||||
|
||||
A field that is still empty and required shows its nudge inline, in place, the moment it is empty.
|
||||
The owner sees each gap where it sits rather than learning about a problem after scrolling past it.
|
||||
There is no single submit-time check that lists everything at once; the nudges are per-field as the
|
||||
owner works. The slab cannot reach `ready` until the full set above is filled, whether by hand or by
|
||||
a confident Call 1 the owner kept.
|
||||
|
||||
### Generate text
|
||||
|
||||
When content generation is enabled, a **Generate text** button runs Call 2 and fills title, short
|
||||
title, and description with model prose plus template numbers. The owner can edit the result freely.
|
||||
If the endpoint is missing or down, the button is disabled; templates still work and publish is never
|
||||
blocked by a failed Generate text.
|
||||
|
||||
## Publish: create the store listing
|
||||
|
||||
The owner taps **Publish** when review is complete. What happens next depends on the SKU and Settings.
|
||||
|
||||
### Draft versus live
|
||||
|
||||
- A normal SKU publishes according to the `woo_create_status` setting, which defaults to draft.
|
||||
- Any SKU matching `SLAB-UAT-*` always creates a WooCommerce draft, even if Settings say publish.
|
||||
That is how practice runs stay invisible to customers.
|
||||
|
||||
The app's "published" means the store create succeeded and the local row plus photos were cleaned up.
|
||||
That is not the same as the product being live in the store; a draft is created but hidden until Ty
|
||||
promotes it.
|
||||
|
||||
### What the owner sees on each outcome
|
||||
|
||||
- **Success.** The screen shows that the listing was created, with the store's product reference when
|
||||
available. The local draft and its photos are gone from the app.
|
||||
- **SKU already exists.** Under the SKU field: "This SKU already exists in the store (any status)."
|
||||
Two paths appear: edit the SKU to a new value, or open the existing listing. This version does not
|
||||
update the other product in place. The draft stays in the browser; nothing is lost.
|
||||
- **A value no longer valid.** If a category, attribute, or price was removed from the store between
|
||||
sync and publish, that field shows "This value is no longer valid. Pick from the current list," with
|
||||
the current options. The owner re-picks and retries.
|
||||
- **Store unreachable or other failure.** A plain message on the screen says the listing could not be
|
||||
created and to try again. No status number, no stack trace, no raw error code reaches the owner.
|
||||
|
||||
The server keeps a log of every attempt either way, so a failed publish can be retried from the same
|
||||
screen without re-photographing.
|
||||
|
||||
|
||||
## Browser compatibility
|
||||
|
||||
Ty signed this walk on 2026-09-06 PT with one amendment: the compatibility matrix includes PC
|
||||
browsers as well as phones. This app is not mobile-only.
|
||||
|
||||
Supported families (matrix):
|
||||
|
||||
- **Phone:** iOS Safari, Android Chrome
|
||||
- **PC:** desktop Chrome, desktop Edge, desktop Firefox (Windows and macOS at minimum)
|
||||
|
||||
Exact minimum version pins are still tracked under issue #4. The matrix above is the product lock
|
||||
for which classes of client are in scope.
|
||||
|
||||
Unsupported browser behavior: hard stop. Show a clear message that this browser is not supported,
|
||||
with a link to update or switch to a supported browser. No polyfill
|
||||
strategy in this version.
|
||||
|
||||
Load-bearing client surfaces that must remain: canvas-based mask overlay and live knob re-run,
|
||||
image crop/prep to 3:4 transparent PNG, file/photo intake for inventory shots, and the online API
|
||||
calls for draft upload, review, and publish. Depth for APIs stays in `docs/TECH-SPEC-PIPELINE.md`
|
||||
and `docs/OPENAPI.md`.
|
||||
|
||||
## Deferred features
|
||||
|
||||
Photo quality, OCR, ruler detection, server-side measuring, U2Net control, and offline capture are
|
||||
deferred post-POC. The overlay edge plus the owner's eye is the only quality gate. SKU is typed by
|
||||
hand. Length is entered by hand; the browser derives its own pixel-to-inch scale. The browser owns
|
||||
the happy path for measuring and cropping. The U2Net one-photo contract stays in the architecture
|
||||
for later. Capture is online only.
|
||||
|
||||
## Where each job lives
|
||||
|
||||
| Job | Screen(s) | Governing lock |
|
||||
|---|---|---|
|
||||
| Photo to listing | Capture through review to publish | AGENTS §1, TECH-SPEC, ARCHITECTURE swimlane |
|
||||
| Practice drafts (`SLAB-UAT-*`) | Review (SKU field), Publish outcome | AGENTS §5, CONTENT-WOO payload status |
|
||||
| Retake on bad cut | Capture mask overlay | TECH-SPEC §3.4–3.5, issue #15 |
|
||||
| Fill or override fields | Review | DATA-MODEL `slabs`, AGENTS §6/7, issue #9 |
|
||||
| Publish and recovery | Publish outcome states | CONTENT-WOO §2.5–2.6, OPENAPI 409/422, issue #18 |
|
||||
@@ -0,0 +1,17 @@
|
||||
# Archived specs
|
||||
|
||||
The previous live doc pile was removed from this branch so agents stop implementing from it.
|
||||
|
||||
Full prior text is on `main` at commit `13bfa792`. That includes ARCHITECTURE, CONTENT-WOO, DATA-MODEL, DEPLOYMENT, IMPL-PLAN, OPENAPI, PROMPTS, TECH-SPEC-PIPELINE, TEST-SPEC, UAT-PRACTICE, UX, UX-DESIGN.
|
||||
|
||||
`PRD-2026-08.txt` in this folder was already archive before this branch.
|
||||
|
||||
Do not implement from those files.
|
||||
|
||||
Live spec on this branch:
|
||||
|
||||
- `README.md`
|
||||
- `AGENTS.md`
|
||||
- `docs/PRODUCT.md`
|
||||
- `docs/CAPTURE.md`
|
||||
- `deploy/` for hosting only
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Structure pin for docs/structure-pass. Exit 0 only when ownership, calendar home,
|
||||
# UX demotion, TEST-SPEC honesty, and Gate A lock phrases all hold.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
cd "$ROOT"
|
||||
fail=0
|
||||
|
||||
ok() { printf 'OK %s\n' "$1"; }
|
||||
bad() { printf 'FAIL %s\n' "$1"; fail=1; }
|
||||
|
||||
# Ownership table only (AGENTS §0), not casual mentions elsewhere.
|
||||
ownership_block=$(awk '/^## 0\. Where each doc lives$/,/^## /{if(/^## 0/) next; if(/^## / && !/^## 0/) exit; print}' AGENTS.md)
|
||||
# Include through end of table: stop at next ## that is not 0
|
||||
ownership_block=$(awk '
|
||||
/^## 0\. Where each doc lives$/ {p=1; next}
|
||||
/^## / && p {exit}
|
||||
p {print}
|
||||
' AGENTS.md)
|
||||
|
||||
for doc in 'docs/UX-DESIGN.md' 'deploy/INVENTORY.md' 'docs/TEST-SPEC.md'; do
|
||||
if printf '%s\n' "$ownership_block" | grep -Fq "\`$doc\`"; then
|
||||
ok "AGENTS §0 lists $doc"
|
||||
else
|
||||
bad "AGENTS §0 ownership missing $doc"
|
||||
fi
|
||||
done
|
||||
|
||||
if grep -Eqi 'non-normative|not normative' docs/UX-DESIGN.md \
|
||||
&& grep -Eq 'UX\.md' docs/UX-DESIGN.md; then
|
||||
ok "UX-DESIGN demoted to non-normative and points at UX.md"
|
||||
else
|
||||
bad "UX-DESIGN header must say non-normative and point at UX.md"
|
||||
fi
|
||||
if grep -Eqi 'phone and PC|signed UX' docs/UX-DESIGN.md; then
|
||||
ok "UX-DESIGN defers to phone+PC / signed UX"
|
||||
else
|
||||
bad "UX-DESIGN must defer to phone+PC matrix / signed UX.md"
|
||||
fi
|
||||
|
||||
if grep -Eq 'Gate A.*Docs freeze|Docs freeze' docs/IMPL-PLAN.md \
|
||||
&& grep -Eq 'Gate B' docs/IMPL-PLAN.md \
|
||||
&& grep -Eq 'Gate C' docs/IMPL-PLAN.md; then
|
||||
ok "IMPL-PLAN owns Gates meanings"
|
||||
else
|
||||
bad "IMPL-PLAN must contain Gates A/B/C meanings"
|
||||
fi
|
||||
|
||||
agents_gate_rows=$(grep -cE '^\| Gate [ABC] \|' AGENTS.md || true)
|
||||
if [[ "$agents_gate_rows" -eq 0 ]]; then
|
||||
ok "AGENTS has no Gates meanings table rows"
|
||||
else
|
||||
bad "AGENTS still has $agents_gate_rows Gates table rows; move meanings to IMPL-PLAN"
|
||||
fi
|
||||
if grep -Fq 'docs/IMPL-PLAN.md' AGENTS.md; then
|
||||
ok "AGENTS points at IMPL-PLAN for phase/gate depth"
|
||||
else
|
||||
bad "AGENTS must point at docs/IMPL-PLAN.md for gate/phase depth"
|
||||
fi
|
||||
|
||||
if grep -Eqi 'not (yet )?on (this branch|main)|Phase 0 deliverable|when (the )?code lands|targets until|do not (exist|treat).*(present|checked.in)' docs/TEST-SPEC.md; then
|
||||
ok "TEST-SPEC states harness paths are targets until code lands"
|
||||
else
|
||||
bad "TEST-SPEC §2 must say frontend/e2e and backend/tests are targets until code exists"
|
||||
fi
|
||||
|
||||
if grep -Eqi 'Phase 0 deliverable|not (yet )?in (the )?tree|aspirational|scaffold target' deploy/docker-compose.yml docs/DEPLOYMENT.md; then
|
||||
ok "deploy docs label missing tree paths as Phase 0 targets"
|
||||
else
|
||||
bad "compose or DEPLOYMENT must label frontend/backend Dockerfiles as Phase 0 targets"
|
||||
fi
|
||||
|
||||
while IFS= read -r phrase; do
|
||||
[[ -z "$phrase" ]] && continue
|
||||
if grep -Fq "$phrase" AGENTS.md; then
|
||||
ok "lock phrase present: $phrase"
|
||||
else
|
||||
bad "missing lock phrase in AGENTS.md: $phrase"
|
||||
fi
|
||||
done <<'LOCKS'
|
||||
bdft = sqft × thickness_in
|
||||
SLAB-UAT-*
|
||||
WOO_BASE_URL
|
||||
https://
|
||||
authoritative for math
|
||||
Confidence 0.7
|
||||
draft → calibrated → ready → publishing → published
|
||||
LOCKS
|
||||
|
||||
if [[ "$fail" -ne 0 ]]; then
|
||||
printf '\ncheck-structure: FAILED\n'
|
||||
exit 1
|
||||
fi
|
||||
printf '\ncheck-structure: PASSED\n'
|
||||
exit 0
|
||||
@@ -0,0 +1,13 @@
|
||||
# Build the static app, then serve only the built artifacts.
|
||||
# Build context is the repo root: `docker build -f frontend/Dockerfile .`
|
||||
FROM node:20-slim AS build
|
||||
WORKDIR /app
|
||||
COPY frontend/package.json frontend/package-lock.json* ./
|
||||
RUN npm install --no-audit --no-fund
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.27-alpine
|
||||
COPY deploy/nginx-m1.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<title>SlabUploader — Capture</title>
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; background: #111; }
|
||||
#app { display: block; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "slabuploader-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --import tsx --test src/**/*.test.ts",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:headed": "playwright test --headed"
|
||||
},
|
||||
"dependencies": {
|
||||
"idb-keyval": "^6.3.0",
|
||||
"svelte": "^4.2.20"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^3.1.2",
|
||||
"svelte-preprocess": "^5.1.4",
|
||||
"tsx": "^4.23.13",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^5.4.19"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* M2 #65 — Playwright visual evidence against local vite preview (not ubudual).
|
||||
* Artifacts land in tests/e2e/artifacts/ (png churn gitignored; README committed).
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './tests/e2e',
|
||||
fullyParallel: false,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: 0,
|
||||
workers: 1,
|
||||
timeout: 180_000,
|
||||
expect: { timeout: 30_000 },
|
||||
reporter: [['list'], ['html', { open: 'never', outputFolder: 'tests/e2e/playwright-report' }]],
|
||||
use: {
|
||||
baseURL: 'http://127.0.0.1:4173',
|
||||
trace: 'retain-on-failure',
|
||||
screenshot: 'only-on-failure',
|
||||
video: 'off',
|
||||
...devices['Pixel 7'],
|
||||
},
|
||||
webServer: {
|
||||
command: 'npm run build && npm run preview -- --host 127.0.0.1 --port 4173',
|
||||
url: 'http://127.0.0.1:4173',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 180_000,
|
||||
},
|
||||
outputDir: 'tests/e2e/test-results',
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { supported } from './browser';
|
||||
import { createCaptureSession, type CaptureSession } from './capture/session';
|
||||
import type { Capture } from './capture/capture.types';
|
||||
import Resume from './capture/Resume.svelte';
|
||||
import BatchPhotos from './capture/BatchPhotos.svelte';
|
||||
import PickCalibration from './capture/PickCalibration.svelte';
|
||||
import MaskPanel from './capture/MaskPanel.svelte';
|
||||
import AxisPanel from './capture/AxisPanel.svelte';
|
||||
import MeasurePanel from './capture/MeasurePanel.svelte';
|
||||
|
||||
const gate = typeof window !== 'undefined' ? supported() : 'window unavailable';
|
||||
const session: CaptureSession = createCaptureSession();
|
||||
|
||||
let cap: Capture = { k: 'batch', photos: [] };
|
||||
let busy = false;
|
||||
let pngUrl: string | null = null;
|
||||
|
||||
const unsubCap = session.capture.subscribe((c) => {
|
||||
cap = c;
|
||||
pngUrl = c.k === 'measure' ? session.getInventoryUrl() : null;
|
||||
});
|
||||
const unsubBusy = session.busy.subscribe((b) => {
|
||||
busy = b;
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
void session.resumeProbe();
|
||||
});
|
||||
onDestroy(() => {
|
||||
unsubCap();
|
||||
unsubBusy();
|
||||
session.dispose();
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if gate}
|
||||
<main class="hardstop">
|
||||
<h1>Unsupported browser</h1>
|
||||
<p>
|
||||
SlabUploader needs a modern browser with canvas, workers, and IndexedDB support:
|
||||
iOS Safari, Android Chrome, or desktop Chrome, Edge, or Firefox.
|
||||
</p>
|
||||
<p class="detail">Missing: {gate}</p>
|
||||
</main>
|
||||
{:else}
|
||||
<main class="app">
|
||||
{#if cap.k === 'resume'}
|
||||
<Resume onContinue={() => session.continueDraft()} onFresh={() => void session.startFresh()} />
|
||||
{:else if cap.k === 'batch'}
|
||||
<BatchPhotos
|
||||
photos={cap.photos}
|
||||
onAdd={(f) => void session.addToBatch(f)}
|
||||
onRemove={session.removeFromBatch}
|
||||
onContinue={session.continueBatch}
|
||||
/>
|
||||
{:else if cap.k === 'pickCalibration'}
|
||||
<PickCalibration
|
||||
photos={cap.photos}
|
||||
onPick={session.pickCalibration}
|
||||
onBack={session.back}
|
||||
/>
|
||||
{:else if cap.k === 'mask'}
|
||||
<MaskPanel
|
||||
state={cap}
|
||||
{busy}
|
||||
setSensitivity={session.setSensitivity}
|
||||
setSheet={session.setSheet}
|
||||
approveMask={session.approveMask}
|
||||
retakes={session.retakes}
|
||||
back={session.back}
|
||||
/>
|
||||
{:else if cap.k === 'axis'}
|
||||
<AxisPanel
|
||||
state={cap}
|
||||
setAxisAngle={session.setAxisAngle}
|
||||
approveAxis={session.approveAxis}
|
||||
back={session.back}
|
||||
/>
|
||||
{:else}
|
||||
<MeasurePanel
|
||||
state={cap}
|
||||
setLength={session.setLength}
|
||||
setThickness={session.setThickness}
|
||||
calculate={session.calculate}
|
||||
back={session.back}
|
||||
{pngUrl}
|
||||
/>
|
||||
{/if}
|
||||
</main>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
:global(body) {
|
||||
margin: 0;
|
||||
background: #121212;
|
||||
font-family: system-ui, -apple-system, Segoe UI, sans-serif;
|
||||
}
|
||||
.app, .hardstop { max-width: 720px; margin: 0 auto; min-height: 100vh; }
|
||||
.hardstop { padding: 48px 24px; color: #eee; text-align: center; }
|
||||
.hardstop h1 { font-size: 1.6rem; }
|
||||
.detail { color: #888; font-size: 0.85rem; }
|
||||
</style>
|
||||
@@ -0,0 +1,26 @@
|
||||
// Supported clients: iOS Safari, Android Chrome, PC Chrome/Edge/Firefox.
|
||||
// Gated on required API presence; anything missing → hard stop.
|
||||
export function supported(): string | null {
|
||||
if (typeof window === 'undefined') return 'window unavailable';
|
||||
if (typeof createImageBitmap !== 'function') return 'createImageBitmap';
|
||||
if (typeof Worker === 'undefined') return 'Worker';
|
||||
if (typeof indexedDB === 'undefined') return 'IndexedDB';
|
||||
const hasOffscreen =
|
||||
typeof OffscreenCanvas !== 'undefined' &&
|
||||
typeof OffscreenCanvas.prototype.convertToBlob === 'function';
|
||||
const hasCanvasBlob =
|
||||
typeof HTMLCanvasElement !== 'undefined' &&
|
||||
typeof HTMLCanvasElement.prototype.toBlob === 'function';
|
||||
if (!hasOffscreen && !hasCanvasBlob) return 'canvas PNG encode';
|
||||
const ua = navigator.userAgent;
|
||||
const isIOS = /iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
|
||||
const isAndroid = /Android/i.test(ua);
|
||||
const isSafari = /Safari/i.test(ua) && !/Chrome|CriOS|Edg|Firefox|FxiOS/i.test(ua);
|
||||
const isChrome = /Chrome|CriOS/i.test(ua) && !/Edg/i.test(ua);
|
||||
const isEdge = /Edg/i.test(ua);
|
||||
const isFirefox = /Firefox|FxiOS/i.test(ua);
|
||||
if (isIOS && isSafari) return null;
|
||||
if (isAndroid && isChrome) return null;
|
||||
if (!isIOS && !isAndroid && (isChrome || isEdge || isFirefox)) return null;
|
||||
return 'unsupported browser';
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<script lang="ts">
|
||||
import type { Capture } from './capture.types';
|
||||
import PhotoStage from './PhotoStage.svelte';
|
||||
|
||||
export let state: Extract<Capture, { k: 'axis' }>;
|
||||
export let setAxisAngle: (deg: number) => void;
|
||||
export let approveAxis: () => void;
|
||||
export let back: () => void;
|
||||
|
||||
$: maskW = state.source.widthPx > 0 ? state.source.widthPx : 0;
|
||||
$: maskH = maskW > 0 ? state.approvedMask.bitset.length / maskW : 0;
|
||||
$: angleDeg = Math.round(state.axis.bbox.angleDeg);
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h1>Length axis</h1>
|
||||
<p class="hint">Rotate the rectangle until it follows the slab length. The rectangle sets direction only; you enter length L on the next step.</p>
|
||||
<PhotoStage
|
||||
blob={state.source.blob}
|
||||
bbox={state.axis.bbox}
|
||||
maskBitset={state.approvedMask.bitset}
|
||||
{maskW}
|
||||
{maskH}
|
||||
/>
|
||||
<div class="angle">
|
||||
<button type="button" class="thumb" aria-label="Rotate axis counter-clockwise" on:click={() => setAxisAngle(angleDeg - 1)}>−</button>
|
||||
<input
|
||||
type="range" min="0" max="179" step="1"
|
||||
value={angleDeg}
|
||||
on:input={(e) => setAxisAngle(Number(e.currentTarget.value))}
|
||||
/>
|
||||
<button type="button" class="thumb" aria-label="Rotate axis clockwise" on:click={() => setAxisAngle(angleDeg + 1)}>+</button>
|
||||
<span class="val">{angleDeg}°</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<button type="button" class="ghost" on:click={back}>Back</button>
|
||||
<button type="button" class="primary" on:click={approveAxis}>Approve axis</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel { padding: 16px; color: #eee; }
|
||||
h1 { font-size: 1.3rem; margin: 0 0 8px; }
|
||||
.hint { color: #aaa; font-size: 0.9rem; margin: 0 0 12px; }
|
||||
.angle { display: flex; align-items: center; gap: 10px; margin-top: 16px; }
|
||||
.thumb {
|
||||
width: 48px; height: 48px; border-radius: 50%; font-size: 1.6rem;
|
||||
border: 1px solid #444; background: #1d1d1d; color: #eee; flex: none;
|
||||
}
|
||||
input[type='range'] { flex: 1; }
|
||||
.val { min-width: 4ch; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.row { display: flex; gap: 10px; margin-top: 16px; }
|
||||
.primary {
|
||||
flex: 1; padding: 14px; font-size: 1rem; border-radius: 10px; border: 0;
|
||||
background: #00e5ff; color: #002; font-weight: 700;
|
||||
}
|
||||
.ghost { flex: 0.7; padding: 14px; border-radius: 10px; border: 1px solid #444; background: transparent; color: #ccc; }
|
||||
</style>
|
||||
@@ -0,0 +1,102 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import type { Source } from './capture.types';
|
||||
|
||||
export let photos: Source[];
|
||||
export let onAdd: (f: File) => void;
|
||||
export let onRemove: (index: number) => void;
|
||||
export let onContinue: () => void;
|
||||
|
||||
let urls: string[] = [];
|
||||
|
||||
$: {
|
||||
for (const u of urls) URL.revokeObjectURL(u);
|
||||
urls = photos.map((p) => URL.createObjectURL(p.blob));
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
for (const u of urls) URL.revokeObjectURL(u);
|
||||
});
|
||||
|
||||
const pick = (e: Event) => {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const list = input.files;
|
||||
if (!list || list.length === 0) return;
|
||||
// Support multi-select from gallery when the browser allows it.
|
||||
for (let i = 0; i < list.length; i++) onAdd(list[i]);
|
||||
input.value = '';
|
||||
};
|
||||
|
||||
$: canContinue = photos.length >= 1;
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h1>Batch photos</h1>
|
||||
<ul class="setup">
|
||||
<li>Sheet is green or black, fills the frame around the slab.</li>
|
||||
<li>Slab fully on the sheet, nothing on top of it.</li>
|
||||
<li>Top-down reference shot: lens parallel to the face.</li>
|
||||
<li>Slab length along the long side of the picture.</li>
|
||||
<li>Add one or more photos of the same slab, then Continue.</li>
|
||||
</ul>
|
||||
|
||||
{#if photos.length > 0}
|
||||
<ul class="thumbs" aria-label="Batch photos">
|
||||
{#each photos as _p, i (urls[i])}
|
||||
<li class="thumb">
|
||||
<img src={urls[i]} alt={`Batch photo ${i + 1}`} />
|
||||
<button type="button" class="rm" aria-label={`Remove photo ${i + 1}`} on:click={() => onRemove(i)}>Remove</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<p class="empty">No photos yet. Add at least one to continue.</p>
|
||||
{/if}
|
||||
|
||||
<div class="pick">
|
||||
<label class="pick-btn">Take photo
|
||||
<input type="file" accept="image/*" capture="environment" on:change={pick} />
|
||||
</label>
|
||||
<label class="pick-btn">Choose from gallery
|
||||
<input type="file" accept="image/*" multiple on:change={pick} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
class="continue"
|
||||
type="button"
|
||||
disabled={!canContinue}
|
||||
on:click={onContinue}
|
||||
>Continue</button>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel { padding: 24px 16px; color: #eee; }
|
||||
h1 { font-size: 1.4rem; }
|
||||
.setup { color: #bbb; line-height: 1.6; font-size: 0.95rem; }
|
||||
.empty { color: #888; margin: 16px 0; }
|
||||
.thumbs {
|
||||
list-style: none; padding: 0; margin: 16px 0;
|
||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px;
|
||||
}
|
||||
.thumb {
|
||||
background: #1e1e1e; border-radius: 8px; overflow: hidden;
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.thumb img { width: 100%; aspect-ratio: 3 / 4; object-fit: cover; display: block; background: #000; }
|
||||
.rm {
|
||||
border: 0; background: #333; color: #ccc; padding: 8px; font-size: 0.85rem; cursor: pointer;
|
||||
}
|
||||
.pick { margin-top: 12px; display: flex; flex-direction: column; gap: 12px; }
|
||||
.pick-btn {
|
||||
background: #00e5ff; color: #002; border: 0; border-radius: 8px;
|
||||
padding: 12px 20px; font-size: 1rem; font-weight: 600;
|
||||
text-align: center; cursor: pointer;
|
||||
}
|
||||
.pick-btn input[type='file'] { display: none; }
|
||||
.continue {
|
||||
margin-top: 20px; width: 100%; padding: 14px; font-size: 1.05rem; border-radius: 10px; border: 0;
|
||||
background: #00e5ff; color: #002; font-weight: 700; cursor: pointer;
|
||||
}
|
||||
.continue:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
</style>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
import type { Capture, Sheet } from './capture.types';
|
||||
import PhotoStage from './PhotoStage.svelte';
|
||||
|
||||
export let state: Extract<Capture, { k: 'mask' }>;
|
||||
export let busy: boolean;
|
||||
export let setSensitivity: (n: number) => void;
|
||||
export let setSheet: (s: Sheet) => void;
|
||||
export let approveMask: () => void;
|
||||
export let retakes: () => void;
|
||||
export let back: () => void;
|
||||
|
||||
const sheets: Sheet[] = ['auto', 'green', 'black'];
|
||||
$: empty = state.overlay !== null && state.overlay.slabPx === 0;
|
||||
$: maskW = state.overlay && state.source.widthPx > 0 ? state.source.widthPx : 0;
|
||||
$: maskH = maskW > 0 && state.overlay ? state.overlay.bitset.length / maskW : 0;
|
||||
$: canApprove = state.overlay !== null && state.overlay.slabPx > 0;
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h1>Mask</h1>
|
||||
<div class="stage-wrap">
|
||||
<PhotoStage
|
||||
blob={state.source.blob}
|
||||
maskBitset={state.overlay?.bitset ?? null}
|
||||
{maskW}
|
||||
{maskH}
|
||||
/>
|
||||
{#if busy}<div class="busy">Working…</div>{/if}
|
||||
{#if state.failed}<div class="warn">Mask pass failed. Adjust and retry, or retake the photo.</div>{/if}
|
||||
{#if empty}<div class="warn">No slab pixels in the mask. Adjust sensitivity or retake.</div>{/if}
|
||||
</div>
|
||||
|
||||
<div class="controls">
|
||||
<div class="seg" role="group" aria-label="Sheet">
|
||||
{#each sheets as s (s)}
|
||||
<button type="button" class:active={state.control.sheet === s} on:click={() => setSheet(s)}>
|
||||
{s[0].toUpperCase() + s.slice(1)}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="sens">
|
||||
<button type="button" class="thumb" aria-label="Decrease sensitivity" on:click={() => setSensitivity(state.control.sensitivity - 1)}>−</button>
|
||||
<input
|
||||
type="range" min="0" max="100" step="1"
|
||||
value={state.control.sensitivity}
|
||||
on:input={(e) => setSensitivity(Number(e.currentTarget.value))}
|
||||
/>
|
||||
<button type="button" class="thumb" aria-label="Increase sensitivity" on:click={() => setSensitivity(state.control.sensitivity + 1)}>+</button>
|
||||
<span class="val">{state.control.sensitivity}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<button type="button" class="ghost" on:click={back}>Back</button>
|
||||
<button type="button" class="ghost" on:click={retakes}>Retake</button>
|
||||
<button type="button" class="primary" disabled={!canApprove} on:click={approveMask}>
|
||||
Approve mask
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel { padding: 16px; color: #eee; }
|
||||
h1 { font-size: 1.3rem; margin: 0 0 12px; }
|
||||
.stage-wrap { position: relative; }
|
||||
.busy {
|
||||
position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.7);
|
||||
color: #fff; padding: 4px 10px; border-radius: 6px; font-size: 0.85rem;
|
||||
}
|
||||
.warn { color: #ffb4a2; margin-top: 8px; font-size: 0.9rem; }
|
||||
.controls { margin-top: 16px; display: flex; flex-direction: column; gap: 14px; }
|
||||
.seg { display: flex; gap: 8px; }
|
||||
.seg button {
|
||||
flex: 1; padding: 12px; font-size: 1rem; border-radius: 8px;
|
||||
border: 1px solid #444; background: #1d1d1d; color: #ccc;
|
||||
}
|
||||
.seg button.active { background: #00e5ff; color: #002; font-weight: 700; border-color: #00e5ff; }
|
||||
.sens { display: flex; align-items: center; gap: 10px; }
|
||||
.thumb {
|
||||
width: 48px; height: 48px; border-radius: 50%; font-size: 1.6rem;
|
||||
border: 1px solid #444; background: #1d1d1d; color: #eee; flex: none;
|
||||
}
|
||||
input[type='range'] { flex: 1; }
|
||||
.val { min-width: 2.2ch; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.row { display: flex; gap: 12px; margin-top: 20px; }
|
||||
.primary {
|
||||
flex: 2; padding: 14px; font-size: 1.05rem; border-radius: 10px; border: 0;
|
||||
background: #00e5ff; color: #002; font-weight: 700;
|
||||
}
|
||||
.primary:disabled { background: #333; color: #777; }
|
||||
.ghost { flex: 1; padding: 14px; border-radius: 10px; border: 1px solid #444; background: transparent; color: #ccc; }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import type { Capture } from './capture.types';
|
||||
import { inToEighths, eighthsToIn } from './capture.types';
|
||||
import { fmtEighths } from './session';
|
||||
import PhotoStage from './PhotoStage.svelte';
|
||||
import {
|
||||
buildPhotosReadyLineup,
|
||||
photosReadyPngAlt,
|
||||
type PhotosReadyLineupItem,
|
||||
} from './photosReadyLineup';
|
||||
|
||||
export let state: Extract<Capture, { k: 'measure' }>;
|
||||
export let setLength: (e: number) => void;
|
||||
export let setThickness: (e: number) => void;
|
||||
export let calculate: () => Promise<void>;
|
||||
export let back: () => void;
|
||||
export let pngUrl: string | null;
|
||||
|
||||
let calcBusy = false;
|
||||
let lengthIn = state.lengthEighths === 0 ? '' : String(eighthsToIn(state.lengthEighths));
|
||||
let thicknessIn = state.thicknessEighths === 0 ? '' : String(eighthsToIn(state.thicknessEighths));
|
||||
|
||||
let lineupUrls: string[] = [];
|
||||
let lineupItems: PhotosReadyLineupItem[] = [];
|
||||
|
||||
$: photosReady = !!state.results;
|
||||
$: {
|
||||
for (const u of lineupUrls) URL.revokeObjectURL(u);
|
||||
lineupUrls = [];
|
||||
if (state.results) {
|
||||
lineupItems = buildPhotosReadyLineup({
|
||||
inventoryPng: state.results.inventoryPng,
|
||||
overlayPng: state.results.overlayPng,
|
||||
batchApply: state.batchApply,
|
||||
sourceBelowFloor: state.results.sourceBelowFloor,
|
||||
});
|
||||
lineupUrls = lineupItems.map((it) =>
|
||||
it.kind === 'png' ? URL.createObjectURL(it.blob) : '',
|
||||
);
|
||||
} else {
|
||||
lineupItems = [];
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
for (const u of lineupUrls) URL.revokeObjectURL(u);
|
||||
});
|
||||
|
||||
const positiveInches = (raw: string): number | null => {
|
||||
const inches = Number.parseFloat(raw);
|
||||
return Number.isFinite(inches) && inches > 0 ? inches : null;
|
||||
};
|
||||
|
||||
const commitLength = () => {
|
||||
const inches = positiveInches(String(lengthIn));
|
||||
const eighths = inches === null ? 0 : inToEighths(inches);
|
||||
setLength(eighths);
|
||||
lengthIn = eighths === 0 ? '' : String(eighthsToIn(eighths));
|
||||
};
|
||||
const commitThickness = () => {
|
||||
const inches = positiveInches(String(thicknessIn));
|
||||
const eighths = inches === null ? 0 : inToEighths(inches);
|
||||
setThickness(eighths);
|
||||
thicknessIn = eighths === 0 ? '' : String(eighthsToIn(eighths));
|
||||
};
|
||||
|
||||
$: canCalc = positiveInches(String(lengthIn)) !== null && positiveInches(String(thicknessIn)) !== null;
|
||||
|
||||
const doCalc = async () => {
|
||||
calcBusy = true;
|
||||
try {
|
||||
commitLength();
|
||||
commitThickness();
|
||||
await calculate();
|
||||
} finally { calcBusy = false; }
|
||||
};
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h1>{photosReady ? 'Photos ready' : 'Measure'}</h1>
|
||||
|
||||
{#if !photosReady}
|
||||
<PhotoStage
|
||||
blob={state.source.blob}
|
||||
bbox={state.axis.bbox}
|
||||
maskBitset={state.approvedMask.bitset}
|
||||
maskW={state.source.widthPx > 0 ? state.source.widthPx : 0}
|
||||
maskH={state.source.widthPx > 0 ? state.approvedMask.bitset.length / state.source.widthPx : 0}
|
||||
/>
|
||||
|
||||
<div class="fields">
|
||||
<div class="field">
|
||||
<span class="label">Length L</span>
|
||||
<input
|
||||
type="number"
|
||||
aria-label="Length L"
|
||||
inputmode="decimal"
|
||||
step="0.125"
|
||||
min="0"
|
||||
placeholder="0"
|
||||
bind:value={lengthIn}
|
||||
on:blur={commitLength}
|
||||
on:change={commitLength}
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<span class="label">Thickness</span>
|
||||
<input
|
||||
type="number"
|
||||
aria-label="Thickness"
|
||||
inputmode="decimal"
|
||||
step="0.125"
|
||||
min="0"
|
||||
placeholder="0"
|
||||
bind:value={thicknessIn}
|
||||
on:blur={commitThickness}
|
||||
on:change={commitThickness}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<button type="button" class="ghost" on:click={back}>Back</button>
|
||||
<button
|
||||
type="button"
|
||||
class="primary"
|
||||
disabled={calcBusy || !canCalc}
|
||||
on:click={doCalc}
|
||||
>
|
||||
{calcBusy ? 'Calculating…' : 'Calculate'}
|
||||
</button>
|
||||
</div>
|
||||
{:else if state.results}
|
||||
<div class="results" aria-label="Photos ready">
|
||||
<div class="nums">
|
||||
<div><span>Widths</span><span>{fmtEighths(state.results.widths.min)} – {fmtEighths(state.results.widths.max)} (avg {fmtEighths(state.results.widths.avg)})</span></div>
|
||||
<div><span>Sqft</span><span>{state.results.sqft.toFixed(2)}</span></div>
|
||||
<div><span>Bdft</span><span>{state.results.bdft.toFixed(2)}</span></div>
|
||||
<div><span>Scale</span><span>{state.results.scale.toFixed(2)} px/in</span></div>
|
||||
</div>
|
||||
{#if state.results.sourceBelowFloor}
|
||||
<div class="warn">Source is below the 800px floor for the inventory PNG. Retake a larger photo.</div>
|
||||
{/if}
|
||||
|
||||
<ol class="lineup" aria-label="Inventory PNG lineup">
|
||||
{#each lineupItems as item, i (i)}
|
||||
{#if item.kind === 'png'}
|
||||
<li class="lineup-item png">
|
||||
<img src={lineupUrls[i]} alt={photosReadyPngAlt(item)} />
|
||||
<span class="role">
|
||||
{#if item.role === 'calibration'}
|
||||
Clean calibration
|
||||
{:else if item.role === 'overlay'}
|
||||
Dimension overlay
|
||||
{:else}
|
||||
Batch photo {(item.batchIndex ?? 0) + 1}
|
||||
{/if}
|
||||
</span>
|
||||
</li>
|
||||
{:else}
|
||||
<li class="lineup-item error" role="alert">
|
||||
<span class="err-title">Photo {item.batchIndex + 1} failed</span>
|
||||
<span class="err-msg">{item.message}</span>
|
||||
</li>
|
||||
{/if}
|
||||
{/each}
|
||||
</ol>
|
||||
|
||||
<!-- Legacy single-PNG fallback only when lineup helper yielded nothing but pngUrl exists -->
|
||||
{#if lineupItems.length === 0 && pngUrl && !state.results.sourceBelowFloor}
|
||||
<div class="png-wrap">
|
||||
<img src={pngUrl} alt="Inventory PNG" />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<button type="button" class="ghost" on:click={back}>Back</button>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel { padding: 16px; color: #eee; }
|
||||
h1 { font-size: 1.3rem; margin: 0 0 12px; }
|
||||
.fields { display: flex; gap: 16px; margin-top: 16px; }
|
||||
.field { flex: 1; }
|
||||
.label { display: block; font-size: 0.9rem; color: #aaa; margin-bottom: 8px; }
|
||||
.field input {
|
||||
box-sizing: border-box; width: 100%; min-height: 52px; padding: 12px; font-size: 1rem;
|
||||
border-radius: 10px; border: 1px solid #444; background: #1d1d1d; color: #eee;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.row { display: flex; gap: 10px; margin-top: 20px; }
|
||||
.primary {
|
||||
flex: 2; padding: 14px; font-size: 1.05rem; border-radius: 10px; border: 0;
|
||||
background: #00e5ff; color: #002; font-weight: 700;
|
||||
}
|
||||
.primary:disabled { background: #333; color: #777; }
|
||||
.ghost { flex: 1; padding: 14px; border-radius: 10px; border: 1px solid #444; background: transparent; color: #ccc; }
|
||||
.results { margin-top: 8px; }
|
||||
.nums { display: flex; flex-direction: column; gap: 8px; }
|
||||
.nums div { display: flex; justify-content: space-between; border-bottom: 1px solid #2a2a2a; padding-bottom: 6px; }
|
||||
.nums span:first-child { color: #aaa; }
|
||||
.warn { color: #ffb4a2; margin-top: 12px; font-size: 0.9rem; }
|
||||
.lineup {
|
||||
list-style: none; padding: 0; margin: 16px 0 0;
|
||||
display: flex; flex-direction: column; gap: 14px;
|
||||
}
|
||||
.lineup-item.png {
|
||||
text-align: center;
|
||||
background-image: linear-gradient(45deg,#ccc 25%,transparent 25%),linear-gradient(-45deg,#ccc 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#ccc 75%),linear-gradient(-45deg,transparent 75%,#ccc 75%);
|
||||
background-size: 16px 16px; background-position: 0 0,0 8px,8px -8px,-8px 0;
|
||||
background-color: #eee; border-radius: 8px; padding: 8px;
|
||||
}
|
||||
.lineup-item.png img { max-width: 100%; border-radius: 4px; display: block; margin: 0 auto; }
|
||||
.role { display: block; margin-top: 8px; font-size: 0.85rem; color: #222; font-weight: 600; }
|
||||
.lineup-item.error {
|
||||
border: 1px solid #8a3a2a; background: #2a1512; border-radius: 8px;
|
||||
padding: 12px 14px; display: flex; flex-direction: column; gap: 4px;
|
||||
}
|
||||
.err-title { color: #ffb4a2; font-weight: 700; font-size: 0.95rem; }
|
||||
.err-msg { color: #e8cfc8; font-size: 0.9rem; }
|
||||
.png-wrap { margin-top: 16px; text-align: center; background-image: linear-gradient(45deg,#ccc 25%,transparent 25%),linear-gradient(-45deg,#ccc 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#ccc 75%),linear-gradient(-45deg,transparent 75%,#ccc 75%); background-size: 16px 16px; background-position: 0 0,0 8px,8px -8px,-8px 0; background-color: #eee; border-radius: 8px; padding: 8px; }
|
||||
.png-wrap img { max-width: 100%; border-radius: 4px; }
|
||||
</style>
|
||||
@@ -0,0 +1,141 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount, tick } from 'svelte';
|
||||
import type { BBox } from './capture.types';
|
||||
import { fitDisplay } from './fitDisplay';
|
||||
import { decodeOrientedBitmap } from '../decodeOrientedBitmap';
|
||||
|
||||
// Display-only: renders the photo fitted to device width (height capped) plus
|
||||
// one overlay layer. All math lives on source pixels, not this canvas.
|
||||
// Geometry must use the same EXIF-oriented bitmap space as the mask worker (#72).
|
||||
export let blob: Blob;
|
||||
export let maxH = 420;
|
||||
export let bbox: BBox | null = null;
|
||||
export let maskBitset: Uint8Array | null = null;
|
||||
export let maskW = 0;
|
||||
export let maskH = 0;
|
||||
|
||||
let canvas: HTMLCanvasElement | undefined;
|
||||
let stage: HTMLDivElement | undefined;
|
||||
let imgW = 0, imgH = 0; // source px (oriented), learned once per blob
|
||||
let parentW = 0;
|
||||
let decodeGen = 0;
|
||||
let decoding = false;
|
||||
|
||||
const applyFit = () => {
|
||||
if (!canvas || !imgW) return;
|
||||
if (parentW <= 0 && stage) parentW = stage.clientWidth;
|
||||
const fit = fitDisplay(parentW, imgW, imgH, maxH);
|
||||
if (!fit) return;
|
||||
canvas.style.width = `${fit.fitW}px`;
|
||||
canvas.style.height = `${fit.fitH}px`;
|
||||
};
|
||||
|
||||
const paintOverlays = (ctx: CanvasRenderingContext2D) => {
|
||||
if (!canvas) return;
|
||||
if (maskBitset && maskW > 0 && maskH > 0) {
|
||||
const off = document.createElement('canvas');
|
||||
off.width = maskW;
|
||||
off.height = maskH;
|
||||
const octx = off.getContext('2d')!;
|
||||
const d = octx.createImageData(maskW, maskH);
|
||||
const tile = 8;
|
||||
for (let p = 0; p < maskW * maskH; p++) {
|
||||
if (!maskBitset[p]) {
|
||||
const x = p % maskW;
|
||||
const y = (p / maskW) | 0;
|
||||
const light = ((x / tile) | 0) % 2 === ((y / tile) | 0) % 2;
|
||||
d.data[p * 4] = light ? 220 : 180;
|
||||
d.data[p * 4 + 1] = light ? 220 : 180;
|
||||
d.data[p * 4 + 2] = light ? 220 : 180;
|
||||
d.data[p * 4 + 3] = 220;
|
||||
}
|
||||
}
|
||||
octx.putImageData(d, 0, 0);
|
||||
ctx.drawImage(off, 0, 0, canvas.width, canvas.height);
|
||||
}
|
||||
if (bbox && bbox.corners.length === 4) {
|
||||
const c = bbox.corners;
|
||||
ctx.strokeStyle = '#00e5ff';
|
||||
ctx.lineWidth = Math.max(2, canvas.width / 400);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(c[0][0], c[0][1]);
|
||||
for (let i = 1; i < 4; i++) ctx.lineTo(c[i][0], c[i][1]);
|
||||
ctx.closePath();
|
||||
ctx.stroke();
|
||||
// The axis reads corners[3] → corners[0], the long side.
|
||||
const a = c[3];
|
||||
const b = c[0];
|
||||
ctx.strokeStyle = '#ff3d71';
|
||||
ctx.lineWidth = Math.max(3, canvas.width / 300);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(a[0], a[1]);
|
||||
ctx.lineTo(b[0], b[1]);
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = '#ff3d71';
|
||||
ctx.beginPath();
|
||||
const ang = Math.atan2(b[1] - a[1], b[0] - a[0]);
|
||||
const r = Math.max(10, canvas.width / 60);
|
||||
ctx.moveTo(b[0], b[1]);
|
||||
ctx.lineTo(b[0] - r * Math.cos(ang - 0.4), b[1] - r * Math.sin(ang - 0.4));
|
||||
ctx.lineTo(b[0] - r * Math.cos(ang + 0.4), b[1] - r * Math.sin(ang + 0.4));
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
};
|
||||
|
||||
const redraw = async () => {
|
||||
if (!blob || !canvas) return;
|
||||
const gen = ++decodeGen;
|
||||
decoding = true;
|
||||
let bmp: ImageBitmap | null = null;
|
||||
try {
|
||||
bmp = await decodeOrientedBitmap(blob);
|
||||
if (gen !== decodeGen || !canvas) return;
|
||||
imgW = bmp.width;
|
||||
imgH = bmp.height;
|
||||
canvas.width = imgW;
|
||||
canvas.height = imgH;
|
||||
applyFit();
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.drawImage(bmp, 0, 0);
|
||||
paintOverlays(ctx);
|
||||
} finally {
|
||||
if (bmp) bmp.close();
|
||||
if (gen === decodeGen) decoding = false;
|
||||
}
|
||||
};
|
||||
|
||||
$: if (blob || bbox || maskBitset) void tick().then(redraw);
|
||||
|
||||
onMount(() => {
|
||||
if (stage) parentW = stage.clientWidth;
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
const e = entries[0];
|
||||
if (!e) return;
|
||||
const w = e.contentRect.width;
|
||||
if (w === parentW) return;
|
||||
parentW = w;
|
||||
applyFit();
|
||||
});
|
||||
if (stage) ro.observe(stage);
|
||||
return () => ro.disconnect();
|
||||
});
|
||||
onDestroy(() => {
|
||||
decodeGen += 1;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="stage" bind:this={stage}>
|
||||
{#if imgW > 0 || decoding || blob}
|
||||
<canvas bind:this={canvas}></canvas>
|
||||
{:else}
|
||||
<div class="loading">Decoding photo…</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.stage { width: 100%; display: flex; justify-content: center; }
|
||||
canvas { display: block; border-radius: 8px; background: #222; }
|
||||
.loading { padding: 40px; color: #999; }
|
||||
</style>
|
||||
@@ -0,0 +1,66 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import type { Source } from './capture.types';
|
||||
|
||||
export let photos: Source[];
|
||||
export let onPick: (index: number) => void;
|
||||
export let onBack: () => void;
|
||||
|
||||
let urls: string[] = [];
|
||||
|
||||
$: {
|
||||
for (const u of urls) URL.revokeObjectURL(u);
|
||||
urls = photos.map((p) => URL.createObjectURL(p.blob));
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
for (const u of urls) URL.revokeObjectURL(u);
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h1>Pick calibration photo</h1>
|
||||
<p class="hint">
|
||||
Choose which photo is the top-down reference for length and thickness.
|
||||
Mask, length axis, and Measure run on that photo only.
|
||||
</p>
|
||||
|
||||
<ul class="thumbs" aria-label="Calibration candidates">
|
||||
{#each photos as _p, i (urls[i])}
|
||||
<li class="thumb">
|
||||
<img src={urls[i]} alt={`Photo ${i + 1}`} />
|
||||
<button
|
||||
type="button"
|
||||
class="pick"
|
||||
aria-label={`Use photo ${i + 1} as calibration`}
|
||||
on:click={() => onPick(i)}
|
||||
>Use as calibration</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<button class="back" type="button" on:click={onBack}>Back</button>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel { padding: 24px 16px; color: #eee; }
|
||||
h1 { font-size: 1.4rem; }
|
||||
.hint { color: #bbb; line-height: 1.5; font-size: 0.95rem; }
|
||||
.thumbs {
|
||||
list-style: none; padding: 0; margin: 16px 0;
|
||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px;
|
||||
}
|
||||
.thumb {
|
||||
background: #1e1e1e; border-radius: 8px; overflow: hidden;
|
||||
display: flex; flex-direction: column;
|
||||
}
|
||||
.thumb img { width: 100%; aspect-ratio: 3 / 4; object-fit: cover; display: block; background: #000; }
|
||||
.pick {
|
||||
border: 0; background: #00e5ff; color: #002; padding: 10px 8px;
|
||||
font-size: 0.9rem; font-weight: 700; cursor: pointer;
|
||||
}
|
||||
.back {
|
||||
margin-top: 8px; width: 100%; padding: 12px; font-size: 1rem; border-radius: 10px;
|
||||
border: 1px solid #444; background: transparent; color: #ccc; cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,28 @@
|
||||
<script lang="ts">
|
||||
export let onContinue: () => void;
|
||||
export let onFresh: () => void;
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h1>Resume?</h1>
|
||||
<p>You have an in-progress slab on this device.</p>
|
||||
<div class="row">
|
||||
<button class="primary" type="button" on:click={onContinue}>Continue</button>
|
||||
<button class="ghost" type="button" on:click={onFresh}>Start fresh</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel { padding: 24px 16px; text-align: center; color: #eee; }
|
||||
h1 { font-size: 1.4rem; }
|
||||
p { color: #aaa; }
|
||||
.row { display: flex; gap: 12px; justify-content: center; margin-top: 24px; }
|
||||
.primary {
|
||||
flex: 1; max-width: 200px; padding: 14px; font-size: 1.05rem; border-radius: 10px; border: 0;
|
||||
background: #00e5ff; color: #002; font-weight: 700;
|
||||
}
|
||||
.ghost {
|
||||
flex: 1; max-width: 200px; padding: 14px; border-radius: 10px; border: 1px solid #444;
|
||||
background: transparent; color: #ccc;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,168 @@
|
||||
// Domain model for the capture flow (M1 + M2 batch).
|
||||
// The Capture tagged union is the state machine: each branch carries exactly the
|
||||
// data its state can hold, so an illegal state is a type error.
|
||||
|
||||
// Integer eighths of an inch; divide by 8 only at display.
|
||||
export type Eighths = number;
|
||||
|
||||
export const inToEighths = (inches: number): Eighths => Math.round(inches * 8);
|
||||
export const eighthsToIn = (e: Eighths): number => e / 8;
|
||||
|
||||
// Source: all geometry, measurement, and PNG work uses source pixels, never the
|
||||
// CSS size of the preview.
|
||||
export interface Source {
|
||||
widthPx: number;
|
||||
heightPx: number;
|
||||
blob: Blob;
|
||||
}
|
||||
|
||||
export type Sheet = 'auto' | 'green' | 'black';
|
||||
export interface MaskParams {
|
||||
sheet: Sheet;
|
||||
sensitivity: number; // 0–100, step 1
|
||||
}
|
||||
|
||||
// Axis-aligned box, source px.
|
||||
export interface ABox {
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
// Minimum-area bounding rectangle of the mask, source px.
|
||||
export interface BBox {
|
||||
corners: [number, number][]; // 4 corners; corners[3] → corners[0] is the long side
|
||||
longSidePx: number; // geometric extent only; scale uses mask span along the axis
|
||||
angleDeg: number; // long-side angle, degrees, [0, 180)
|
||||
}
|
||||
|
||||
// The approved mask is the footprint for axis, measurement, and the inventory PNG.
|
||||
export interface Mask {
|
||||
params: MaskParams;
|
||||
slabPx: number; // 0 ⇒ approve blocked, user retakes
|
||||
bitset: Uint8Array; // source-grid mask, 1 byte/px
|
||||
bbox: BBox;
|
||||
slabBounds: ABox; // axis-aligned extent of slab px, for the 80%-fill PNG crop
|
||||
}
|
||||
|
||||
// Direction only: an oriented rectangle over the slab. The arrow reads
|
||||
// corners[3] → corners[0] (the long side).
|
||||
export interface Axis {
|
||||
bbox: BBox;
|
||||
}
|
||||
|
||||
export interface Widths {
|
||||
min: Eighths;
|
||||
max: Eighths;
|
||||
avg: Eighths;
|
||||
every6In: Eighths[];
|
||||
}
|
||||
|
||||
export interface Measures {
|
||||
lengthEighths: Eighths;
|
||||
thicknessEighths: Eighths;
|
||||
scale: number; // px per inch
|
||||
widths: Widths;
|
||||
sqft: number; // 2 dp
|
||||
bdft: number; // 2 dp
|
||||
inventoryPng: Blob;
|
||||
/** Dimension-overlay copy of the calibration inventory PNG (#63). */
|
||||
overlayPng?: Blob;
|
||||
sourceBelowFloor: boolean;
|
||||
}
|
||||
|
||||
// Result of applying the calibration mask to one batch sibling. The
|
||||
// calibration slot is null because its inventory PNG lives in Measures.
|
||||
export type BatchPhotoResult =
|
||||
| null
|
||||
| { status: 'ok'; inventoryPng: Blob }
|
||||
| { status: 'error'; message: string };
|
||||
|
||||
// The machine. 'resume' exists only while a draft exists and has not been chosen.
|
||||
// M2: 'batch' + 'pickCalibration' replace M1 'addPhoto' — accumulate, then user picks calibration.
|
||||
export type Capture =
|
||||
| { k: 'resume'; draft: Draft }
|
||||
| { k: 'batch'; photos: Source[] }
|
||||
| { k: 'pickCalibration'; photos: Source[] }
|
||||
| {
|
||||
k: 'mask';
|
||||
source: Source;
|
||||
control: MaskParams; // immediate control value (what the UI shows)
|
||||
overlay: Mask | null; // last settled mask; null until first pass
|
||||
failed: boolean;
|
||||
}
|
||||
| {
|
||||
k: 'axis';
|
||||
source: Source;
|
||||
approvedMask: Mask; // frozen footprint
|
||||
axis: Axis; // live axis.bbox being nudged
|
||||
}
|
||||
| {
|
||||
k: 'measure';
|
||||
source: Source;
|
||||
approvedMask: Mask;
|
||||
axis: Axis; // frozen
|
||||
lengthEighths: Eighths;
|
||||
thicknessEighths: Eighths;
|
||||
results: Measures | null;
|
||||
/** Capture-order sibling results from the post-Calculate batch pass. */
|
||||
batchApply?: BatchPhotoResult[];
|
||||
};
|
||||
|
||||
// Placeholder geometry for batch-only drafts (no mask yet).
|
||||
export const EMPTY_BBOX: BBox = {
|
||||
corners: [
|
||||
[0, 0],
|
||||
[0, 0],
|
||||
[0, 0],
|
||||
[0, 0],
|
||||
],
|
||||
longSidePx: 0,
|
||||
angleDeg: 0,
|
||||
};
|
||||
export const EMPTY_ABOX: ABox = { x: 0, y: 0, w: 0, h: 0 };
|
||||
export const DEFAULT_MASK_PARAMS: MaskParams = { sheet: 'auto', sensitivity: 50 };
|
||||
|
||||
// Device draft (IndexedDB): one in-progress slab. Small by design — the bitset
|
||||
// and PNG are re-derived from stored data, never stored second-hand.
|
||||
// M2 extends with `batch` (capture-order photo blobs). Legacy M1 drafts omit it.
|
||||
export interface Draft {
|
||||
version: 1;
|
||||
stage: 'batch' | 'pickCalibration' | 'mask' | 'axis' | 'measure'; // last approved / persisted state
|
||||
/** Capture-order batch. Absent on legacy M1 drafts ⇒ treat as [source]. */
|
||||
batch?: Source[];
|
||||
/** Index into batch of the user-picked calibration photo. Set once picked. */
|
||||
calibrationIndex?: number;
|
||||
source: Source; // calibration / active photo; for stage==='batch'|'pickCalibration' = photos[0] placeholder
|
||||
maskParams: MaskParams; // → re-derive mask on resume (ignored while stage==='batch')
|
||||
mask: Omit<Mask, 'bitset' | 'params'>; // slabPx, bbox, slabBounds
|
||||
axisBbox?: BBox | null; // present when stage >= axis; absent on legacy drafts
|
||||
lengthEighths: Eighths;
|
||||
thicknessEighths: Eighths;
|
||||
results: Omit<Measures, 'inventoryPng' | 'overlayPng'> | null; // present when results computed
|
||||
inventoryPng: Blob | null; // stored so Continue can show Measure results
|
||||
/** Dimension-overlay calibration PNG; kept out of batchApply[cal] (#63). */
|
||||
overlayPng?: Blob | null;
|
||||
/** Capture-order batch apply results; blobs are retained for the #64 lineup. */
|
||||
batchApply?: BatchPhotoResult[];
|
||||
}
|
||||
|
||||
// Worker protocol. Job ids increase; the worker drops anything older than the
|
||||
// current id, so a stale result can never blank a newer one.
|
||||
export type WorkerIn =
|
||||
| { id: number; kind: 'init'; blob: Blob }
|
||||
| { id: number; kind: 'mask'; sheet: Sheet; sensitivity: number }
|
||||
| { id: number; kind: 'invalidate' };
|
||||
|
||||
export type WorkerOut =
|
||||
| { id: number; kind: 'decoded'; w: number; h: number }
|
||||
| {
|
||||
id: number;
|
||||
kind: 'ready';
|
||||
slabPx: number;
|
||||
bitset: Uint8Array;
|
||||
bbox: BBox;
|
||||
slabBounds: ABox;
|
||||
}
|
||||
| { id: number; kind: 'failed'; reason: string };
|
||||
@@ -0,0 +1,149 @@
|
||||
import { test, afterEach } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
import {
|
||||
decodeOrientedBitmap,
|
||||
ORIENTED_BITMAP_OPTIONS,
|
||||
} from '../decodeOrientedBitmap.ts';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const fixturePath = join(here, '../../tests/fixtures/set1-48x2/face-a.jpeg');
|
||||
|
||||
const RealCreateImageBitmap = globalThis.createImageBitmap;
|
||||
|
||||
afterEach(() => {
|
||||
if (RealCreateImageBitmap === undefined) {
|
||||
delete (globalThis as unknown as { createImageBitmap?: unknown }).createImageBitmap;
|
||||
} else {
|
||||
globalThis.createImageBitmap = RealCreateImageBitmap;
|
||||
}
|
||||
});
|
||||
|
||||
/** Minimal EXIF Orientation + largest SOF size for the orient-8 fixture. */
|
||||
function readJpegOrientAndSof(buf: Buffer): { orientation: number; sofW: number; sofH: number } {
|
||||
let orientation = 1;
|
||||
const exif = buf.indexOf(Buffer.from('Exif\0\0'));
|
||||
if (exif >= 0) {
|
||||
const tiff = exif + 6;
|
||||
const le = buf[tiff] === 0x49;
|
||||
const u16 = (o: number) => (le ? buf.readUInt16LE(o) : buf.readUInt16BE(o));
|
||||
const u32 = (o: number) => (le ? buf.readUInt32LE(o) : buf.readUInt32BE(o));
|
||||
const ifd = tiff + u32(tiff + 4);
|
||||
const n = u16(ifd);
|
||||
for (let k = 0; k < n; k++) {
|
||||
const e = ifd + 2 + k * 12;
|
||||
const tag = u16(e);
|
||||
const typ = u16(e + 2);
|
||||
if (tag === 0x0112) {
|
||||
orientation = typ === 3 ? u16(e + 8) : u32(e + 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
let sofW = 0;
|
||||
let sofH = 0;
|
||||
let i = 0;
|
||||
while (i < buf.length - 9) {
|
||||
if (buf[i] === 0xff && buf[i + 1] >= 0xc0 && buf[i + 1] <= 0xc3) {
|
||||
const h = buf.readUInt16BE(i + 5);
|
||||
const w = buf.readUInt16BE(i + 7);
|
||||
if (w * h > sofW * sofH) {
|
||||
sofW = w;
|
||||
sofH = h;
|
||||
}
|
||||
const segLen = buf.readUInt16BE(i + 2);
|
||||
i += 2 + segLen;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return { orientation, sofW, sofH };
|
||||
}
|
||||
|
||||
/** Orientation 5–8 swap width/height for display. */
|
||||
function orientedSize(sofW: number, sofH: number, orientation: number): { w: number; h: number } {
|
||||
if (orientation >= 5 && orientation <= 8) return { w: sofH, h: sofW };
|
||||
return { w: sofW, h: sofH };
|
||||
}
|
||||
|
||||
test('fixture face-a.jpeg is EXIF Orientation 8 (stored landscape → oriented portrait) (#72)', () => {
|
||||
const buf = readFileSync(fixturePath);
|
||||
const { orientation, sofW, sofH } = readJpegOrientAndSof(buf);
|
||||
assert.equal(orientation, 8, 'matched-set JPEGs carry Orientation 8');
|
||||
assert.equal(sofW, 4000);
|
||||
assert.equal(sofH, 2256);
|
||||
const { w, h } = orientedSize(sofW, sofH, orientation);
|
||||
assert.equal(w, 2256);
|
||||
assert.equal(h, 4000);
|
||||
});
|
||||
|
||||
test('decodeOrientedBitmap always requests imageOrientation from-image (#72)', async () => {
|
||||
let seen: ImageBitmapOptions | undefined;
|
||||
(globalThis as unknown as { createImageBitmap: typeof createImageBitmap }).createImageBitmap =
|
||||
async (_src: ImageBitmapSource, opts?: ImageBitmapOptions) => {
|
||||
seen = opts;
|
||||
return { width: 2256, height: 4000, close() {} } as ImageBitmap;
|
||||
};
|
||||
|
||||
const blob = new Blob([readFileSync(fixturePath)], { type: 'image/jpeg' });
|
||||
const bmp = await decodeOrientedBitmap(blob);
|
||||
assert.deepEqual(seen, ORIENTED_BITMAP_OPTIONS);
|
||||
assert.equal(ORIENTED_BITMAP_OPTIONS.imageOrientation, 'from-image');
|
||||
assert.equal(bmp.width, 2256);
|
||||
assert.equal(bmp.height, 4000);
|
||||
});
|
||||
|
||||
test('decodeOrientedBitmap falls back to bare createImageBitmap if option rejected (#72)', async () => {
|
||||
let calls = 0;
|
||||
(globalThis as unknown as { createImageBitmap: typeof createImageBitmap }).createImageBitmap =
|
||||
async (_src: ImageBitmapSource, opts?: ImageBitmapOptions) => {
|
||||
calls += 1;
|
||||
if (opts && 'imageOrientation' in opts) {
|
||||
throw new TypeError('imageOrientation unsupported');
|
||||
}
|
||||
return { width: 90, height: 160, close() {} } as ImageBitmap;
|
||||
};
|
||||
|
||||
const bmp = await decodeOrientedBitmap(new Blob([new Uint8Array([1, 2, 3])], { type: 'image/jpeg' }));
|
||||
assert.equal(calls, 2, 'retry bare after option rejection');
|
||||
assert.equal(bmp.width, 90);
|
||||
assert.equal(bmp.height, 160);
|
||||
});
|
||||
|
||||
test('decodeOrientedBitmap: Chromium orients fixture to 2256×4000 (#72)', async (t) => {
|
||||
let chromium: typeof import('@playwright/test').chromium;
|
||||
try {
|
||||
({ chromium } = await import('@playwright/test'));
|
||||
} catch {
|
||||
t.skip('playwright not available');
|
||||
return;
|
||||
}
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
const buf = readFileSync(fixturePath);
|
||||
const b64 = buf.toString('base64');
|
||||
// Inline the same contract as decodeOrientedBitmap (worker-safe, no bundler).
|
||||
const dims = await page.evaluate(async (b64jpeg: string) => {
|
||||
const bin = atob(b64jpeg);
|
||||
const arr = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
|
||||
const blob = new Blob([arr], { type: 'image/jpeg' });
|
||||
const opts = { imageOrientation: 'from-image' as const };
|
||||
let bmp: ImageBitmap;
|
||||
try {
|
||||
bmp = await createImageBitmap(blob, opts);
|
||||
} catch {
|
||||
bmp = await createImageBitmap(blob);
|
||||
}
|
||||
const out = { w: bmp.width, h: bmp.height };
|
||||
bmp.close();
|
||||
return out;
|
||||
}, b64);
|
||||
assert.equal(dims.w, 2256, `oriented width (got ${dims.w})`);
|
||||
assert.equal(dims.h, 4000, `oriented height (got ${dims.h})`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fitDisplay } from './fitDisplay.ts';
|
||||
|
||||
test('parentW=0 → null (no size until laid out)', () => {
|
||||
assert.equal(fitDisplay(0, 1000, 750, 420), null);
|
||||
assert.equal(fitDisplay(-5, 1000, 750, 420), null);
|
||||
});
|
||||
|
||||
test('280 wide, 4:3 landscape → contain, under the height cap', () => {
|
||||
const fit = fitDisplay(280, 1600, 1200, 420);
|
||||
assert.ok(fit);
|
||||
assert.equal(fit.fitW, 280);
|
||||
assert.ok(Math.abs(fit.fitH - 210) < 1e-9);
|
||||
assert.ok(fit.fitH <= 420);
|
||||
});
|
||||
|
||||
test('portrait under maxH never stretches: height capped, width shrinks', () => {
|
||||
// 1000 wide source, 3000 tall. Full-width fit would be 900 tall > 420.
|
||||
const fit = fitDisplay(400, 1000, 3000, 420);
|
||||
assert.ok(fit);
|
||||
assert.equal(fit.fitH, 420);
|
||||
assert.ok(Math.abs(fit.fitW - 140) < 1e-9);
|
||||
// aspect preserved: fitW/fitH === imgW/imgH
|
||||
assert.ok(Math.abs(fit.fitW / fit.fitH - 1000 / 3000) < 1e-9);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
// Contain-fit of an image into a parent width with a height cap. Pure and
|
||||
// display-only; all measurement math stays on source pixels.
|
||||
// Null when the parent is not laid out yet (clientWidth 0) — the caller must
|
||||
// not finalize CSS size until it is, to avoid a wrong-aspect flash.
|
||||
export function fitDisplay(
|
||||
parentW: number, imgW: number, imgH: number, maxH: number,
|
||||
): { fitW: number; fitH: number } | null {
|
||||
if (parentW <= 0 || imgW <= 0 || imgH <= 0) return null;
|
||||
const fitW = parentW;
|
||||
let fitH = (imgH / imgW) * fitW;
|
||||
if (fitH > maxH) {
|
||||
// Cap height and shrink width to preserve aspect; never stretch.
|
||||
fitH = maxH;
|
||||
return { fitW: (fitH * imgW) / imgH, fitH };
|
||||
}
|
||||
return { fitW, fitH };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { test } from 'node:test';
|
||||
import { inToEighths } from './capture.types';
|
||||
|
||||
const panelSrc = readFileSync(
|
||||
join(dirname(fileURLToPath(import.meta.url)), 'MeasurePanel.svelte'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
test('MeasurePanel exposes typed number inputs for Length L and Thickness', () => {
|
||||
const inputs = panelSrc.match(/<input\b[^>]*>/g) ?? [];
|
||||
assert.ok(inputs.length >= 2, 'expected at least two <input> fields');
|
||||
assert.ok(
|
||||
inputs.some((el) => /type="number"/.test(el) && /aria-label="Length L"/.test(el)),
|
||||
'Length L must be a type=number input',
|
||||
);
|
||||
assert.ok(
|
||||
inputs.some((el) => /type="number"/.test(el) && /aria-label="Thickness"/.test(el)),
|
||||
'Thickness must be a type=number input',
|
||||
);
|
||||
assert.equal(
|
||||
panelSrc.includes('class="stepper"'),
|
||||
false,
|
||||
'stepper-only UI is the UAT fail; primary control must be typed input',
|
||||
);
|
||||
assert.equal(
|
||||
/<span class="v">\{fmtEighths\(state\.lengthEighths\)\}<\/span>/.test(panelSrc),
|
||||
false,
|
||||
'Length must not be a read-only fmtEighths span',
|
||||
);
|
||||
});
|
||||
|
||||
test('typed inches snap to nearest 1/8 via inToEighths', () => {
|
||||
assert.equal(inToEighths(12), 96);
|
||||
assert.equal(inToEighths(12.1), 97);
|
||||
assert.equal(inToEighths(0.06), 0);
|
||||
assert.equal(inToEighths(0.07), 1);
|
||||
assert.equal(inToEighths(1.999), 16);
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { test } from 'node:test';
|
||||
import type { BatchPhotoResult } from './capture.types';
|
||||
import {
|
||||
buildPhotosReadyLineup,
|
||||
type PhotosReadyLineupItem,
|
||||
} from './photosReadyLineup';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function png(label: string): Blob {
|
||||
return new Blob([label], { type: 'image/png' });
|
||||
}
|
||||
|
||||
function jpeg(label: string): Blob {
|
||||
return new Blob([label], { type: 'image/jpeg' });
|
||||
}
|
||||
|
||||
function roles(items: PhotosReadyLineupItem[]): string[] {
|
||||
return items.map((it) =>
|
||||
it.kind === 'png' ? `png:${it.role}` : `error:${it.batchIndex}`,
|
||||
);
|
||||
}
|
||||
|
||||
// --- pure helper: lineup order + error slots (#64) ---
|
||||
|
||||
test('test(photos): lineup is clean cal → overlay → other batch PNGs in capture order (#64)', () => {
|
||||
const clean = png('clean-cal');
|
||||
const overlay = png('overlay-cal');
|
||||
const sib0 = png('sib-0');
|
||||
const sib2 = png('sib-2');
|
||||
const batchApply: BatchPhotoResult[] = [
|
||||
{ status: 'ok', inventoryPng: sib0 },
|
||||
null, // calibration at index 1
|
||||
{ status: 'ok', inventoryPng: sib2 },
|
||||
];
|
||||
|
||||
const lineup = buildPhotosReadyLineup({
|
||||
inventoryPng: clean,
|
||||
overlayPng: overlay,
|
||||
batchApply,
|
||||
});
|
||||
|
||||
assert.deepEqual(roles(lineup), [
|
||||
'png:calibration',
|
||||
'png:overlay',
|
||||
'png:batch',
|
||||
'png:batch',
|
||||
]);
|
||||
assert.equal(lineup[0].kind, 'png');
|
||||
if (lineup[0].kind === 'png') {
|
||||
assert.equal(lineup[0].blob, clean);
|
||||
assert.equal(lineup[0].role, 'calibration');
|
||||
}
|
||||
assert.equal(lineup[1].kind, 'png');
|
||||
if (lineup[1].kind === 'png') {
|
||||
assert.equal(lineup[1].blob, overlay);
|
||||
assert.equal(lineup[1].role, 'overlay');
|
||||
}
|
||||
assert.equal(lineup[2].kind, 'png');
|
||||
if (lineup[2].kind === 'png') {
|
||||
assert.equal(lineup[2].blob, sib0);
|
||||
assert.equal(lineup[2].batchIndex, 0);
|
||||
}
|
||||
assert.equal(lineup[3].kind, 'png');
|
||||
if (lineup[3].kind === 'png') {
|
||||
assert.equal(lineup[3].blob, sib2);
|
||||
assert.equal(lineup[3].batchIndex, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test('test(photos): single-photo batch lineup is clean + overlay only (#64)', () => {
|
||||
const clean = png('only-clean');
|
||||
const overlay = png('only-overlay');
|
||||
const lineup = buildPhotosReadyLineup({
|
||||
inventoryPng: clean,
|
||||
overlayPng: overlay,
|
||||
batchApply: [null],
|
||||
});
|
||||
assert.deepEqual(roles(lineup), ['png:calibration', 'png:overlay']);
|
||||
assert.ok(lineup.every((it) => it.kind === 'png'));
|
||||
});
|
||||
|
||||
test('test(photos): batchApply errors become clear error slots (empty mask / floor) (#64)', () => {
|
||||
const clean = png('clean');
|
||||
const overlay = png('overlay');
|
||||
const ok = png('ok-sib');
|
||||
const batchApply: BatchPhotoResult[] = [
|
||||
null,
|
||||
{ status: 'error', message: 'empty mask: no slab pixels detected' },
|
||||
{ status: 'ok', inventoryPng: ok },
|
||||
{ status: 'error', message: 'PNG size floor: shorter side is below 800 px' },
|
||||
];
|
||||
|
||||
const lineup = buildPhotosReadyLineup({
|
||||
inventoryPng: clean,
|
||||
overlayPng: overlay,
|
||||
batchApply,
|
||||
});
|
||||
|
||||
assert.deepEqual(roles(lineup), [
|
||||
'png:calibration',
|
||||
'png:overlay',
|
||||
'error:1',
|
||||
'png:batch',
|
||||
'error:3',
|
||||
]);
|
||||
|
||||
const err1 = lineup[2];
|
||||
assert.equal(err1.kind, 'error');
|
||||
if (err1.kind === 'error') {
|
||||
assert.match(err1.message, /empty mask/i);
|
||||
assert.equal(err1.batchIndex, 1);
|
||||
}
|
||||
const err3 = lineup[4];
|
||||
assert.equal(err3.kind, 'error');
|
||||
if (err3.kind === 'error') {
|
||||
assert.match(err3.message, /floor|800/i);
|
||||
}
|
||||
|
||||
// Successful sibling still appears after cal+overlay, in capture order among siblings
|
||||
const okItem = lineup[3];
|
||||
assert.equal(okItem.kind, 'png');
|
||||
if (okItem.kind === 'png') {
|
||||
assert.equal(okItem.blob, ok);
|
||||
assert.equal(okItem.batchIndex, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test('test(photos): lineup never uses source JPEG thumbs as inventory PNGs (#64)', () => {
|
||||
const clean = png('clean');
|
||||
const overlay = png('overlay');
|
||||
const thumb = jpeg('source-thumb');
|
||||
// Dishonest proxy would pass source thumbs; helper must only emit image/png blobs for png slots
|
||||
const lineup = buildPhotosReadyLineup({
|
||||
inventoryPng: clean,
|
||||
overlayPng: overlay,
|
||||
batchApply: [
|
||||
null,
|
||||
{ status: 'ok', inventoryPng: png('sib') },
|
||||
],
|
||||
});
|
||||
for (const it of lineup) {
|
||||
if (it.kind === 'png') {
|
||||
assert.equal(it.blob.type, 'image/png', 'lineup PNG slots must be inventory PNGs');
|
||||
assert.notEqual(it.blob, thumb);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('test(photos): skip clean cal when sourceBelowFloor; keep overlay + siblings (#64)', () => {
|
||||
const lineup = buildPhotosReadyLineup({
|
||||
inventoryPng: png('below'),
|
||||
overlayPng: png('overlay'),
|
||||
batchApply: [null, { status: 'ok', inventoryPng: png('sib') }],
|
||||
sourceBelowFloor: true,
|
||||
});
|
||||
assert.deepEqual(roles(lineup), ['png:overlay', 'png:batch']);
|
||||
});
|
||||
|
||||
test('test(photos): empty/missing results yield empty lineup (#64)', () => {
|
||||
assert.deepEqual(buildPhotosReadyLineup({}), []);
|
||||
assert.deepEqual(
|
||||
buildPhotosReadyLineup({ inventoryPng: null, overlayPng: null, batchApply: undefined }),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
// --- light UI / session wiring (#64) ---
|
||||
|
||||
test('test(photos): MeasurePanel shows Photos ready lineup + M1 numbers + batch errors (#64)', () => {
|
||||
const panel = readFileSync(join(here, 'MeasurePanel.svelte'), 'utf8');
|
||||
assert.match(panel, /Photos ready|photos.?ready/i, 'end screen title after Calculate');
|
||||
assert.match(panel, /buildPhotosReadyLineup/, 'must use pure lineup helper');
|
||||
assert.match(panel, /Widths/, 'M1 widths still visible');
|
||||
assert.match(panel, /Sqft/, 'M1 sqft still visible');
|
||||
assert.match(panel, /Bdft/, 'M1 bdft still visible');
|
||||
assert.match(panel, /Scale/, 'M1 scale still visible');
|
||||
// Dishonest proxies
|
||||
assert.ok(
|
||||
!/lineup[\s\S]{0,200}state\.source\.blob/.test(panel),
|
||||
'must not lineup source thumbs',
|
||||
);
|
||||
assert.match(
|
||||
panel,
|
||||
/error|batchApply|message/i,
|
||||
'per-photo batchApply errors must surface in the panel',
|
||||
);
|
||||
assert.match(panel, /Back/, 'Back must still work from Photos ready');
|
||||
});
|
||||
|
||||
test('test(photos): App still routes measure results through Measure (or PhotosReady) with Back (#64)', () => {
|
||||
const app = readFileSync(join(here, '..', 'App.svelte'), 'utf8');
|
||||
// Stay on Measure with results, or dedicated panel — either is fine
|
||||
assert.ok(
|
||||
/MeasurePanel/.test(app) || /PhotosReady/.test(app),
|
||||
'App must render Photos-ready end screen',
|
||||
);
|
||||
// Must not invent a Mask loop for the lineup
|
||||
assert.ok(
|
||||
!/\{\s*#each\s+[^}]*photos[^}]*\}[\s\S]*MaskPanel/i.test(app),
|
||||
'App must not #each batch into Mask for Photos ready',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { BatchPhotoResult } from './capture.types';
|
||||
|
||||
/** One slot in the Photos-ready end screen (#64 / docs/PHOTOS.md). */
|
||||
export type PhotosReadyLineupItem =
|
||||
| {
|
||||
kind: 'png';
|
||||
role: 'calibration' | 'overlay' | 'batch';
|
||||
blob: Blob;
|
||||
/** Capture-order index for non-calibration batch inventory PNGs. */
|
||||
batchIndex?: number;
|
||||
}
|
||||
| {
|
||||
kind: 'error';
|
||||
batchIndex: number;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export interface PhotosReadyLineupInput {
|
||||
inventoryPng?: Blob | null;
|
||||
overlayPng?: Blob | null;
|
||||
batchApply?: BatchPhotoResult[] | null;
|
||||
/** When true, omit the clean calibration PNG (M1 floor warn path). */
|
||||
sourceBelowFloor?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Photos-ready lineup:
|
||||
* 1. Clean calibration inventory PNG
|
||||
* 2. Dimension-overlay copy
|
||||
* 3. Other batch inventory PNGs in capture order (batchApply, skip cal null)
|
||||
* with error slots for empty mask / floor failures.
|
||||
*/
|
||||
export function buildPhotosReadyLineup(
|
||||
input: PhotosReadyLineupInput,
|
||||
): PhotosReadyLineupItem[] {
|
||||
const items: PhotosReadyLineupItem[] = [];
|
||||
const { inventoryPng, overlayPng, batchApply, sourceBelowFloor } = input;
|
||||
|
||||
if (inventoryPng && !sourceBelowFloor) {
|
||||
items.push({ kind: 'png', role: 'calibration', blob: inventoryPng });
|
||||
}
|
||||
if (overlayPng) {
|
||||
items.push({ kind: 'png', role: 'overlay', blob: overlayPng });
|
||||
}
|
||||
|
||||
if (batchApply) {
|
||||
for (let i = 0; i < batchApply.length; i++) {
|
||||
const slot = batchApply[i];
|
||||
if (slot === null) continue; // calibration lives in results.inventoryPng
|
||||
if (slot.status === 'ok') {
|
||||
items.push({
|
||||
kind: 'png',
|
||||
role: 'batch',
|
||||
blob: slot.inventoryPng,
|
||||
batchIndex: i,
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
kind: 'error',
|
||||
batchIndex: i,
|
||||
message: slot.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
export function photosReadyPngAlt(item: Extract<PhotosReadyLineupItem, { kind: 'png' }>): string {
|
||||
if (item.role === 'calibration') return 'Calibration inventory PNG';
|
||||
if (item.role === 'overlay') return 'Calibration dimension-overlay PNG';
|
||||
const n = (item.batchIndex ?? 0) + 1;
|
||||
return `Batch inventory PNG ${n}`;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { test, beforeEach } from 'node:test';
|
||||
import { get } from 'svelte/store';
|
||||
import type { Draft, Source } from './capture.types';
|
||||
import { createCaptureSession, type DraftStore } from './session';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function tinyJpeg(label: string): File {
|
||||
// Minimal valid-ish JPEG bytes are unnecessary; Blob type is what session stores.
|
||||
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, label.charCodeAt(0) & 0xff]);
|
||||
return new File([bytes], `${label}.jpg`, { type: 'image/jpeg' });
|
||||
}
|
||||
|
||||
function memStore(): DraftStore & { peek: () => Draft | null; reset: () => void } {
|
||||
let mem: Draft | null = null;
|
||||
return {
|
||||
loadDraft: async () => mem,
|
||||
saveDraft: async (d) => {
|
||||
mem = d;
|
||||
},
|
||||
clearDraft: async () => {
|
||||
mem = null;
|
||||
},
|
||||
peek: () => mem,
|
||||
reset: () => {
|
||||
mem = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let store: ReturnType<typeof memStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = memStore();
|
||||
});
|
||||
|
||||
test('session starts on batch with zero photos (replaces single addPhoto)', () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'batch');
|
||||
if (cap.k === 'batch') assert.equal(cap.photos.length, 0);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('addToBatch accumulates photos and stays on batch', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('a'));
|
||||
await s.addToBatch(tinyJpeg('b'));
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'batch');
|
||||
if (cap.k === 'batch') {
|
||||
assert.equal(cap.photos.length, 2);
|
||||
assert.ok(cap.photos[0].blob instanceof Blob);
|
||||
assert.ok(cap.photos[1].blob instanceof Blob);
|
||||
assert.notEqual(cap.photos[0].blob, cap.photos[1].blob);
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('continueBatch is a no-op when batch is empty', () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
s.continueBatch();
|
||||
assert.equal(get(s.capture).k, 'batch');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('continueBatch with ≥1 photo advances to pickCalibration (not Mask)', async () => {
|
||||
// #60: Continue must not silently Mask the first photo — user picks calibration next.
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('a'));
|
||||
await s.addToBatch(tinyJpeg('b'));
|
||||
s.continueBatch();
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'pickCalibration');
|
||||
if (cap.k === 'pickCalibration') {
|
||||
assert.equal(cap.photos.length, 2);
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('adding photos persists batch blobs in device draft', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('a'));
|
||||
await s.addToBatch(tinyJpeg('b'));
|
||||
// allow async persist
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const d = store.peek();
|
||||
assert.ok(d, 'draft must exist after adding photos');
|
||||
assert.equal(d!.stage, 'batch');
|
||||
const batch = d!.batch ?? [];
|
||||
assert.equal(batch.length, 2, 'draft must store both batch blobs (not a UI-only list)');
|
||||
assert.ok(batch[0].blob instanceof Blob);
|
||||
assert.ok(batch[1].blob instanceof Blob);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('refresh: resumeProbe + Continue restores the batch photos', async () => {
|
||||
const s1 = createCaptureSession({ draft: store });
|
||||
await s1.addToBatch(tinyJpeg('a'));
|
||||
await s1.addToBatch(tinyJpeg('b'));
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
s1.dispose();
|
||||
|
||||
const s2 = createCaptureSession({ draft: store });
|
||||
await s2.resumeProbe();
|
||||
assert.equal(get(s2.capture).k, 'resume');
|
||||
s2.continueDraft();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const cap = get(s2.capture);
|
||||
assert.equal(cap.k, 'batch');
|
||||
if (cap.k === 'batch') {
|
||||
assert.equal(cap.photos.length, 2);
|
||||
assert.ok(cap.photos.every((p: Source) => p.blob instanceof Blob));
|
||||
}
|
||||
s2.dispose();
|
||||
});
|
||||
|
||||
test('Batch UI: AddPhoto/Batch panel supports multi-add and Continue when ≥1', () => {
|
||||
// Prefer BatchPhotos.svelte; fall back to AddPhoto.svelte if renamed later.
|
||||
const candidates = ['BatchPhotos.svelte', 'AddPhoto.svelte'].map((n) => join(here, n));
|
||||
let src = '';
|
||||
let found = '';
|
||||
for (const p of candidates) {
|
||||
try {
|
||||
src = readFileSync(p, 'utf8');
|
||||
found = p;
|
||||
break;
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
}
|
||||
assert.ok(src, 'expected BatchPhotos.svelte or AddPhoto.svelte');
|
||||
assert.match(src, /Continue|continue/i, `${found} must expose Continue`);
|
||||
assert.match(src, /photos|batch/i, `${found} must talk about batch/photos`);
|
||||
// Must allow adding more than once (not a one-shot that leaves the screen).
|
||||
const fileInputs = src.match(/type="file"/g) ?? [];
|
||||
assert.ok(fileInputs.length >= 1, 'must have file picker(s)');
|
||||
assert.ok(
|
||||
/addToBatch|onAdd|onPicked/.test(src) || /on:change/.test(src),
|
||||
'must wire photo add',
|
||||
);
|
||||
});
|
||||
|
||||
test('legacy addPhoto alias still appends to batch (no silent single-photo-only path)', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addPhoto(tinyJpeg('only'));
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'batch', 'addPhoto must not jump straight to mask anymore');
|
||||
if (cap.k === 'batch') assert.equal(cap.photos.length, 1);
|
||||
s.dispose();
|
||||
});
|
||||
@@ -0,0 +1,497 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { test, beforeEach, afterEach } from 'node:test';
|
||||
import { get } from 'svelte/store';
|
||||
import type { Draft, Mask, MaskParams, Source, WorkerIn, WorkerOut } from './capture.types';
|
||||
import { createCaptureSession, type DraftStore } from './session';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function tinyJpeg(label: string): File {
|
||||
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, label.charCodeAt(0) & 0xff]);
|
||||
return new File([bytes], `${label}.jpg`, { type: 'image/jpeg' });
|
||||
}
|
||||
|
||||
function memStore(): DraftStore & { peek: () => Draft | null } {
|
||||
let mem: Draft | null = null;
|
||||
return {
|
||||
loadDraft: async () => mem,
|
||||
saveDraft: async (d) => {
|
||||
mem = d;
|
||||
},
|
||||
clearDraft: async () => {
|
||||
mem = null;
|
||||
},
|
||||
peek: () => mem,
|
||||
};
|
||||
}
|
||||
|
||||
let store: ReturnType<typeof memStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = memStore();
|
||||
});
|
||||
|
||||
/** Controllable FakeWorker for #62 batch-apply paths. */
|
||||
type MaskBehavior = {
|
||||
w: number;
|
||||
h: number;
|
||||
/** slabPx; 0 ⇒ empty mask */
|
||||
slabPx: number;
|
||||
slabBounds?: { x: number; y: number; w: number; h: number };
|
||||
};
|
||||
|
||||
class FakeMaskWorker {
|
||||
onmessage: ((ev: MessageEvent<WorkerOut>) => void) | null = null;
|
||||
static inits: Blob[] = [];
|
||||
static maskCalls: { sheet: string; sensitivity: number; blob: Blob | null }[] = [];
|
||||
static lastInitBlob: Blob | null = null;
|
||||
/** Per-init blob → behavior. Default: full mask at LARGE dims (above PNG floor). */
|
||||
static behaviorFor: (blob: Blob) => MaskBehavior = () => ({
|
||||
w: 1000,
|
||||
h: 900,
|
||||
slabPx: 1000 * 900,
|
||||
slabBounds: { x: 0, y: 0, w: 1000, h: 900 },
|
||||
});
|
||||
|
||||
constructor(_url: URL | string, _opts?: WorkerOptions) {}
|
||||
|
||||
postMessage(msg: WorkerIn) {
|
||||
if (msg.kind === 'init') {
|
||||
FakeMaskWorker.inits.push(msg.blob);
|
||||
FakeMaskWorker.lastInitBlob = msg.blob;
|
||||
const id = msg.id;
|
||||
const b = FakeMaskWorker.behaviorFor(msg.blob);
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({ data: { id, kind: 'decoded', w: b.w, h: b.h } } as MessageEvent<WorkerOut>);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (msg.kind === 'mask') {
|
||||
const id = msg.id;
|
||||
const blob = FakeMaskWorker.lastInitBlob;
|
||||
FakeMaskWorker.maskCalls.push({
|
||||
sheet: msg.sheet,
|
||||
sensitivity: msg.sensitivity,
|
||||
blob,
|
||||
});
|
||||
const b = blob ? FakeMaskWorker.behaviorFor(blob) : { w: 40, h: 20, slabPx: 0 };
|
||||
const bitset = new Uint8Array(Math.max(1, b.w * b.h)).fill(b.slabPx > 0 ? 1 : 0);
|
||||
const bbox = {
|
||||
corners: [
|
||||
[b.w, 0],
|
||||
[b.w, b.h],
|
||||
[0, b.h],
|
||||
[0, 0],
|
||||
] as [number, number][],
|
||||
longSidePx: b.w,
|
||||
angleDeg: 0,
|
||||
};
|
||||
const slabBounds = b.slabBounds ?? { x: 0, y: 0, w: b.w, h: b.h };
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({
|
||||
data: {
|
||||
id,
|
||||
kind: 'ready',
|
||||
slabPx: b.slabPx,
|
||||
bitset,
|
||||
bbox,
|
||||
slabBounds,
|
||||
},
|
||||
} as MessageEvent<WorkerOut>);
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
terminate() {}
|
||||
}
|
||||
|
||||
const RealWorker = globalThis.Worker;
|
||||
const RealCreateImageBitmap = globalThis.createImageBitmap;
|
||||
|
||||
function installFakes() {
|
||||
FakeMaskWorker.inits = [];
|
||||
FakeMaskWorker.maskCalls = [];
|
||||
FakeMaskWorker.lastInitBlob = null;
|
||||
FakeMaskWorker.behaviorFor = () => ({
|
||||
w: 1000,
|
||||
h: 900,
|
||||
slabPx: 1000 * 900,
|
||||
slabBounds: { x: 0, y: 0, w: 1000, h: 900 },
|
||||
});
|
||||
(globalThis as unknown as { Worker: typeof FakeMaskWorker }).Worker = FakeMaskWorker;
|
||||
(globalThis as unknown as { createImageBitmap: typeof createImageBitmap }).createImageBitmap =
|
||||
async (blob: ImageBitmapSource) => {
|
||||
const b = blob instanceof Blob ? FakeMaskWorker.behaviorFor(blob) : { w: 1000, h: 900 };
|
||||
return {
|
||||
width: b.w,
|
||||
height: b.h,
|
||||
close() {},
|
||||
} as ImageBitmap;
|
||||
};
|
||||
}
|
||||
|
||||
function restoreGlobals() {
|
||||
if (RealWorker === undefined) {
|
||||
delete (globalThis as unknown as { Worker?: unknown }).Worker;
|
||||
} else {
|
||||
globalThis.Worker = RealWorker;
|
||||
}
|
||||
if (RealCreateImageBitmap === undefined) {
|
||||
delete (globalThis as unknown as { createImageBitmap?: unknown }).createImageBitmap;
|
||||
} else {
|
||||
globalThis.createImageBitmap = RealCreateImageBitmap;
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreGlobals();
|
||||
});
|
||||
|
||||
async function settleOverlay(
|
||||
s: ReturnType<typeof createCaptureSession>,
|
||||
ms = 800,
|
||||
): Promise<Mask> {
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < ms) {
|
||||
const cap = get(s.capture);
|
||||
if (cap.k === 'mask' && cap.overlay && cap.overlay.slabPx > 0) return cap.overlay;
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
throw new Error('mask overlay never settled');
|
||||
}
|
||||
|
||||
async function driveToMeasure(
|
||||
s: ReturnType<typeof createCaptureSession>,
|
||||
photos: File[],
|
||||
calIndex: number,
|
||||
maskParams: Partial<MaskParams> = { sheet: 'green', sensitivity: 50 },
|
||||
) {
|
||||
for (const p of photos) await s.addToBatch(p);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(calIndex);
|
||||
if (maskParams.sheet) s.setSheet(maskParams.sheet);
|
||||
if (typeof maskParams.sensitivity === 'number') s.setSensitivity(maskParams.sensitivity);
|
||||
// setSheet already runs a pass; if only sensitivity, force via setSheet after
|
||||
if (!maskParams.sheet) s.setSheet('auto');
|
||||
await settleOverlay(s);
|
||||
s.approveMask();
|
||||
s.approveAxis();
|
||||
s.setLength(320); // 40 in
|
||||
s.setThickness(16); // 2 in
|
||||
}
|
||||
|
||||
type BatchApplySlot =
|
||||
| null
|
||||
| { status: 'ok'; inventoryPng: Blob }
|
||||
| { status: 'error'; message: string };
|
||||
|
||||
function batchApplyOf(cap: ReturnType<typeof get<ReturnType<typeof createCaptureSession>['capture']>>): BatchApplySlot[] | undefined {
|
||||
if (cap.k !== 'measure') return undefined;
|
||||
return (cap as { batchApply?: BatchApplySlot[] }).batchApply;
|
||||
}
|
||||
|
||||
// --- #62: apply approved mask + crop to non-calibration batch photos after Calculate ---
|
||||
|
||||
test('#62: Calculate applies frozen mask params to every non-calibration batch photo', async () => {
|
||||
installFakes();
|
||||
const encodeCalls: { widthPx: number; heightPx: number; sheet: string; sensitivity: number }[] = [];
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async (input) => {
|
||||
encodeCalls.push({
|
||||
widthPx: input.source.widthPx,
|
||||
heightPx: input.source.heightPx,
|
||||
sheet: (input.mask as Mask).params?.sheet ?? '?',
|
||||
sensitivity: (input.mask as Mask).params?.sensitivity ?? -1,
|
||||
});
|
||||
// Distinctive PNG blob so tests cannot confuse with source JPEG thumbs
|
||||
return {
|
||||
blob: new Blob([`png-${input.source.widthPx}x${input.source.heightPx}`], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
};
|
||||
},
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b'); // calibration
|
||||
const c = tinyJpeg('c');
|
||||
await driveToMeasure(s, [a, b, c], 1, { sheet: 'black', sensitivity: 72 });
|
||||
await s.calculate();
|
||||
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'measure', 'must stay on Measure — do not reopen Mask');
|
||||
const apply = batchApplyOf(cap);
|
||||
assert.ok(Array.isArray(apply), 'measure.batchApply must exist after Calculate');
|
||||
assert.equal(apply!.length, 3, 'one slot per batch photo');
|
||||
assert.equal(apply![1], null, 'calibration index is null (uses results.inventoryPng)');
|
||||
|
||||
assert.ok(apply![0] && apply![0].status === 'ok', 'batch[0] applied ok');
|
||||
assert.ok(apply![2] && apply![2].status === 'ok', 'batch[2] applied ok');
|
||||
if (apply![0]?.status === 'ok') {
|
||||
assert.equal(apply![0].inventoryPng.type, 'image/png');
|
||||
assert.notEqual(apply![0].inventoryPng, a, 'must not proxy source thumb as inventory PNG');
|
||||
}
|
||||
if (apply![2]?.status === 'ok') {
|
||||
assert.equal(apply![2].inventoryPng.type, 'image/png');
|
||||
assert.notEqual(apply![2].inventoryPng, c);
|
||||
}
|
||||
|
||||
// Frozen params: every sibling mask call used calibration sheet/sensitivity
|
||||
const siblingBlobs = new Set([a, c]);
|
||||
const siblingMasks = FakeMaskWorker.maskCalls.filter((m) => m.blob && siblingBlobs.has(m.blob as File));
|
||||
assert.ok(siblingMasks.length >= 2, 'mask worker must run on non-calibration photos');
|
||||
for (const m of siblingMasks) {
|
||||
assert.equal(m.sheet, 'black', 'reuse approved sheet');
|
||||
assert.equal(m.sensitivity, 72, 'reuse approved sensitivity');
|
||||
}
|
||||
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: empty mask on one sibling → per-photo error; others still proceed', async () => {
|
||||
installFakes();
|
||||
const a = tinyJpeg('a'); // will empty-mask
|
||||
const b = tinyJpeg('b'); // cal
|
||||
const c = tinyJpeg('c'); // ok
|
||||
|
||||
FakeMaskWorker.behaviorFor = (blob) => {
|
||||
if (blob === a) {
|
||||
return { w: 1000, h: 900, slabPx: 0, slabBounds: { x: 0, y: 0, w: 0, h: 0 } };
|
||||
}
|
||||
return { w: 1000, h: 900, slabPx: 1000 * 900, slabBounds: { x: 0, y: 0, w: 1000, h: 900 } };
|
||||
};
|
||||
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['ok-png'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
await driveToMeasure(s, [a, b, c], 1, { sheet: 'green' });
|
||||
await s.calculate();
|
||||
|
||||
const apply = batchApplyOf(get(s.capture));
|
||||
assert.ok(apply);
|
||||
assert.equal(apply![1], null);
|
||||
assert.ok(apply![0] && apply![0].status === 'error', 'empty mask → error');
|
||||
if (apply![0]?.status === 'error') {
|
||||
assert.match(apply![0].message, /empty|mask/i, 'clear per-photo empty-mask error');
|
||||
}
|
||||
assert.ok(apply![2] && apply![2].status === 'ok', 'other photos still proceed');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: below PNG size floor on one sibling → per-photo error; others proceed', async () => {
|
||||
installFakes();
|
||||
const a = tinyJpeg('a'); // ok
|
||||
const b = tinyJpeg('b'); // cal
|
||||
const c = tinyJpeg('c'); // below floor
|
||||
|
||||
FakeMaskWorker.behaviorFor = (blob) => {
|
||||
if (blob === c) {
|
||||
return { w: 400, h: 300, slabPx: 400 * 300, slabBounds: { x: 0, y: 0, w: 400, h: 300 } };
|
||||
}
|
||||
return { w: 1000, h: 900, slabPx: 1000 * 900, slabBounds: { x: 0, y: 0, w: 1000, h: 900 } };
|
||||
};
|
||||
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async (input) => {
|
||||
const below = Math.min(input.mask.slabBounds.w, input.mask.slabBounds.h) < 800;
|
||||
return {
|
||||
blob: new Blob([below ? 'tiny' : 'ok'], { type: 'image/png' }),
|
||||
sourceBelowFloor: below,
|
||||
};
|
||||
},
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
await driveToMeasure(s, [a, b, c], 1, { sheet: 'auto' });
|
||||
await s.calculate();
|
||||
|
||||
const apply = batchApplyOf(get(s.capture));
|
||||
assert.ok(apply);
|
||||
assert.ok(apply![0] && apply![0].status === 'ok', 'above-floor sibling ok');
|
||||
assert.ok(apply![2] && apply![2].status === 'error', 'below-floor → error');
|
||||
if (apply![2]?.status === 'error') {
|
||||
assert.match(apply![2].message, /floor|small|800|size/i, 'clear per-photo size-floor error');
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: scale/widths/sqft/bdft stay on calibration results only (siblings are visual)', async () => {
|
||||
installFakes();
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['png'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
await driveToMeasure(s, [a, b], 1, { sheet: 'green' });
|
||||
await s.calculate();
|
||||
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'measure');
|
||||
if (cap.k === 'measure') {
|
||||
assert.ok(cap.results);
|
||||
assert.equal(typeof cap.results!.scale, 'number');
|
||||
assert.ok(cap.results!.scale > 0);
|
||||
assert.equal(typeof cap.results!.sqft, 'number');
|
||||
assert.equal(typeof cap.results!.bdft, 'number');
|
||||
assert.ok(cap.results!.widths);
|
||||
// batchApply ok slots must NOT carry measure fields
|
||||
const apply = (cap as { batchApply?: BatchApplySlot[] }).batchApply;
|
||||
assert.ok(apply);
|
||||
const slot = apply![0];
|
||||
assert.ok(slot && slot.status === 'ok');
|
||||
if (slot && slot.status === 'ok') {
|
||||
assert.equal(
|
||||
'scale' in slot,
|
||||
false,
|
||||
'non-cal apply must not attach scale',
|
||||
);
|
||||
assert.equal('sqft' in slot, false);
|
||||
assert.equal('bdft' in slot, false);
|
||||
assert.equal('widths' in slot, false);
|
||||
}
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: draft persists batchApply after Calculate (for #64 UI later)', async () => {
|
||||
installFakes();
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['draft-png'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
const c = tinyJpeg('c');
|
||||
await driveToMeasure(s, [a, b, c], 0, { sheet: 'black' }); // cal = first
|
||||
await s.calculate();
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
|
||||
const d = store.peek();
|
||||
assert.ok(d);
|
||||
assert.equal(d!.stage, 'measure');
|
||||
assert.ok(Array.isArray(d!.batchApply), 'draft.batchApply must be persisted');
|
||||
assert.equal(d!.batchApply!.length, 3);
|
||||
assert.equal(d!.batchApply![0], null, 'calibration slot null on draft');
|
||||
assert.ok(d!.batchApply![1] && (d!.batchApply![1] as { status: string }).status === 'ok');
|
||||
assert.ok(d!.batchApply![2] && (d!.batchApply![2] as { status: string }).status === 'ok');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: single-photo batch Calculate leaves batchApply=[null] (no sibling Mask)', async () => {
|
||||
installFakes();
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['only'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
const only = tinyJpeg('only');
|
||||
await driveToMeasure(s, [only], 0, { sheet: 'auto' });
|
||||
const initsBefore = FakeMaskWorker.inits.length;
|
||||
await s.calculate();
|
||||
|
||||
const apply = batchApplyOf(get(s.capture));
|
||||
assert.ok(apply);
|
||||
assert.deepEqual(apply, [null]);
|
||||
|
||||
// No extra mask inits for non-existent siblings after Calculate
|
||||
const siblingInits = FakeMaskWorker.inits.slice(initsBefore).filter((blob) => blob !== only);
|
||||
assert.equal(siblingInits.length, 0, 'must not invent Mask work for absent siblings');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: Calculate does not re-enter Mask / does not open Mask controls for siblings', async () => {
|
||||
installFakes();
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['x'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
await driveToMeasure(s, [tinyJpeg('a'), tinyJpeg('b')], 0, { sheet: 'green' });
|
||||
await s.calculate();
|
||||
assert.equal(get(s.capture).k, 'measure');
|
||||
|
||||
// Session source must never loop enterMaskOnSource over batch after Calculate
|
||||
const sessionSrc = readFileSync(join(here, 'session.ts'), 'utf8');
|
||||
assert.ok(
|
||||
/batchApply|applyBatch|apply.*non-?calibrat/i.test(sessionSrc),
|
||||
'session must implement batch apply after Calculate (#62)',
|
||||
);
|
||||
// Dishonest proxy: must not set k:'mask' inside calculate for each photo
|
||||
const calcBody = sessionSrc.match(/async calculate\(\)[\s\S]*?(?=\n [a-zA-Z]+\(|\n \})/);
|
||||
assert.ok(calcBody, 'calculate() must exist');
|
||||
assert.ok(
|
||||
!/set\(\s*\{\s*k:\s*'mask'/.test(calcBody![0]),
|
||||
'calculate must not reopen Mask state for siblings',
|
||||
);
|
||||
|
||||
const app = readFileSync(join(here, '..', 'App.svelte'), 'utf8');
|
||||
assert.ok(
|
||||
!/\{\s*#each\s+[^}]*batchApply[^}]*\}[\s\S]*MaskPanel/i.test(app) &&
|
||||
!/\{\s*#each\s+[^}]*photos[^}]*\}[\s\S]*MaskPanel/i.test(app),
|
||||
'App must not #each photos into MaskPanel',
|
||||
);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#62: resume restores batchApply alongside calibration results', async () => {
|
||||
installFakes();
|
||||
const s1 = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['resume-png'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
await driveToMeasure(s1, [a, b], 1, { sheet: 'green' });
|
||||
await s1.calculate();
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
s1.dispose();
|
||||
|
||||
FakeMaskWorker.inits = [];
|
||||
const s2 = createCaptureSession({ draft: store } as Parameters<typeof createCaptureSession>[0]);
|
||||
await s2.resumeProbe();
|
||||
s2.continueDraft();
|
||||
const start = Date.now();
|
||||
let cap = get(s2.capture);
|
||||
while (cap.k !== 'measure' && Date.now() - start < 1500) {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
cap = get(s2.capture);
|
||||
}
|
||||
assert.equal(cap.k, 'measure');
|
||||
const apply = batchApplyOf(cap);
|
||||
assert.ok(apply, 'restored measure must include batchApply');
|
||||
assert.equal(apply!.length, 2);
|
||||
assert.equal(apply![1], null);
|
||||
assert.ok(apply![0] && apply![0].status === 'ok');
|
||||
if (apply![0]?.status === 'ok') {
|
||||
assert.equal(apply![0].inventoryPng.type, 'image/png');
|
||||
}
|
||||
s2.dispose();
|
||||
});
|
||||
@@ -0,0 +1,540 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { test, beforeEach, afterEach } from 'node:test';
|
||||
import { get } from 'svelte/store';
|
||||
import type { Draft, Mask, Source, WorkerIn, WorkerOut } from './capture.types';
|
||||
import { createCaptureSession, type DraftStore } from './session';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function tinyJpeg(label: string): File {
|
||||
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, label.charCodeAt(0) & 0xff]);
|
||||
return new File([bytes], `${label}.jpg`, { type: 'image/jpeg' });
|
||||
}
|
||||
|
||||
function memStore(): DraftStore & { peek: () => Draft | null; reset: () => void } {
|
||||
let mem: Draft | null = null;
|
||||
return {
|
||||
loadDraft: async () => mem,
|
||||
saveDraft: async (d) => {
|
||||
mem = d;
|
||||
},
|
||||
clearDraft: async () => {
|
||||
mem = null;
|
||||
},
|
||||
peek: () => mem,
|
||||
reset: () => {
|
||||
mem = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let store: ReturnType<typeof memStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = memStore();
|
||||
});
|
||||
|
||||
test('continueBatch with ≥1 photo goes to pickCalibration (not mask — no first-photo proxy)', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('a'));
|
||||
await s.addToBatch(tinyJpeg('b'));
|
||||
s.continueBatch();
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'pickCalibration', 'Continue must open pick-calibration, not skip to Mask');
|
||||
if (cap.k === 'pickCalibration') {
|
||||
assert.equal(cap.photos.length, 2);
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('single-photo batch: Continue still opens pickCalibration so user confirms the only photo', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('only'));
|
||||
s.continueBatch();
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'pickCalibration');
|
||||
if (cap.k === 'pickCalibration') {
|
||||
assert.equal(cap.photos.length, 1);
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('pickCalibration(index) enters Mask on that Source only (not always first)', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
const c = tinyJpeg('c');
|
||||
await s.addToBatch(a);
|
||||
await s.addToBatch(b);
|
||||
await s.addToBatch(c);
|
||||
s.continueBatch();
|
||||
assert.equal(get(s.capture).k, 'pickCalibration');
|
||||
|
||||
s.pickCalibration(1);
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'mask');
|
||||
if (cap.k === 'mask') {
|
||||
// Chosen photo must be the second batch blob, not photos[0].
|
||||
assert.equal(cap.source.blob, b, 'Mask source must be the user-picked photo');
|
||||
assert.notEqual(cap.source.blob, a, 'must not silently use first photo');
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('single-photo pick enters Mask on that photo', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const only = tinyJpeg('only');
|
||||
await s.addToBatch(only);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(0);
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'mask');
|
||||
if (cap.k === 'mask') {
|
||||
assert.equal(cap.source.blob, only);
|
||||
}
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('pickCalibration out of range is a no-op', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('a'));
|
||||
s.continueBatch();
|
||||
s.pickCalibration(-1);
|
||||
assert.equal(get(s.capture).k, 'pickCalibration');
|
||||
s.pickCalibration(99);
|
||||
assert.equal(get(s.capture).k, 'pickCalibration');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('draft persists pickCalibration stage with batch photos', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
await s.addToBatch(tinyJpeg('a'));
|
||||
await s.addToBatch(tinyJpeg('b'));
|
||||
s.continueBatch();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const d = store.peek();
|
||||
assert.ok(d, 'draft must exist on pickCalibration');
|
||||
assert.equal(d!.stage, 'pickCalibration');
|
||||
assert.equal((d!.batch ?? []).length, 2);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('draft remembers calibration choice after pick', async () => {
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
await s.addToBatch(a);
|
||||
await s.addToBatch(b);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(1);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const d = store.peek();
|
||||
assert.ok(d);
|
||||
assert.equal(d!.stage, 'mask');
|
||||
assert.equal(d!.calibrationIndex, 1, 'draft must store which batch photo is calibration');
|
||||
assert.equal(d!.source.blob, b, 'draft.source must be the chosen calibration photo');
|
||||
assert.equal((d!.batch ?? []).length, 2, 'full batch still stored');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('refresh: resumeProbe + Continue restores pickCalibration with batch', async () => {
|
||||
const s1 = createCaptureSession({ draft: store });
|
||||
await s1.addToBatch(tinyJpeg('a'));
|
||||
await s1.addToBatch(tinyJpeg('b'));
|
||||
s1.continueBatch();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
s1.dispose();
|
||||
|
||||
const s2 = createCaptureSession({ draft: store });
|
||||
await s2.resumeProbe();
|
||||
assert.equal(get(s2.capture).k, 'resume');
|
||||
s2.continueDraft();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const cap = get(s2.capture);
|
||||
assert.equal(cap.k, 'pickCalibration');
|
||||
if (cap.k === 'pickCalibration') {
|
||||
assert.equal(cap.photos.length, 2);
|
||||
assert.ok(cap.photos.every((p: Source) => p.blob instanceof Blob));
|
||||
}
|
||||
s2.dispose();
|
||||
});
|
||||
|
||||
test('refresh: resume after pick restores Mask on the chosen calibration photo', async () => {
|
||||
const s1 = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
await s1.addToBatch(a);
|
||||
await s1.addToBatch(b);
|
||||
s1.continueBatch();
|
||||
s1.pickCalibration(1);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
s1.dispose();
|
||||
|
||||
const s2 = createCaptureSession({ draft: store });
|
||||
await s2.resumeProbe();
|
||||
s2.continueDraft();
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
const cap = get(s2.capture);
|
||||
assert.equal(cap.k, 'mask');
|
||||
if (cap.k === 'mask') {
|
||||
// Blob identity may round-trip as a new Blob with same bytes; compare size/type content.
|
||||
assert.ok(cap.source.blob instanceof Blob);
|
||||
const chosen = new Uint8Array(await b.arrayBuffer());
|
||||
const got = new Uint8Array(await cap.source.blob.arrayBuffer());
|
||||
assert.deepEqual(got, chosen, 'restored Mask source must be the picked calibration photo');
|
||||
}
|
||||
// calibrationIndex still on draft
|
||||
const d = store.peek();
|
||||
assert.equal(d?.calibrationIndex, 1);
|
||||
s2.dispose();
|
||||
});
|
||||
|
||||
test('PickCalibration UI: thumbs over batch + pick action (not auto-first)', () => {
|
||||
const path = join(here, 'PickCalibration.svelte');
|
||||
let src = '';
|
||||
try {
|
||||
src = readFileSync(path, 'utf8');
|
||||
} catch {
|
||||
/* missing = fail */
|
||||
}
|
||||
assert.ok(src, 'expected PickCalibration.svelte');
|
||||
assert.match(src, /calibrat/i, 'UI must mention calibration');
|
||||
assert.match(src, /photos|thumb/i, 'UI must show batch thumbs');
|
||||
assert.ok(
|
||||
/onPick|pickCalibration|on:click/.test(src),
|
||||
'UI must wire a per-photo pick action',
|
||||
);
|
||||
// Must not hardcode always-first without user interaction.
|
||||
assert.ok(
|
||||
!/photos\[0\].*mask|always.*first/i.test(src) || /onPick|on:click/.test(src),
|
||||
'must require user pick',
|
||||
);
|
||||
});
|
||||
|
||||
test('App wires pickCalibration state to PickCalibration panel', () => {
|
||||
const app = readFileSync(join(here, '..', 'App.svelte'), 'utf8');
|
||||
assert.match(app, /PickCalibration/, 'App must import/render PickCalibration');
|
||||
assert.match(app, /pickCalibration/, 'App must branch on pickCalibration state');
|
||||
});
|
||||
|
||||
// --- #61 M2-4: wire M1 mask/axis/measure onto the calibration pick ---
|
||||
|
||||
const MASK_W = 40;
|
||||
const MASK_H = 20;
|
||||
|
||||
/** Fake Worker so Node can drive Mask → Axis → Measure without canvas decode. */
|
||||
class FakeMaskWorker {
|
||||
onmessage: ((ev: MessageEvent<WorkerOut>) => void) | null = null;
|
||||
static inits: Blob[] = [];
|
||||
|
||||
constructor(_url: URL | string, _opts?: WorkerOptions) {}
|
||||
|
||||
postMessage(msg: WorkerIn) {
|
||||
if (msg.kind === 'init') {
|
||||
FakeMaskWorker.inits.push(msg.blob);
|
||||
const id = msg.id;
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({ data: { id, kind: 'decoded', w: MASK_W, h: MASK_H } } as MessageEvent<WorkerOut>);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (msg.kind === 'mask') {
|
||||
const id = msg.id;
|
||||
const bitset = new Uint8Array(MASK_W * MASK_H).fill(1);
|
||||
const bbox = {
|
||||
corners: [
|
||||
[MASK_W, 0],
|
||||
[MASK_W, MASK_H],
|
||||
[0, MASK_H],
|
||||
[0, 0],
|
||||
] as [number, number][],
|
||||
longSidePx: MASK_W,
|
||||
angleDeg: 0,
|
||||
};
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({
|
||||
data: {
|
||||
id,
|
||||
kind: 'ready',
|
||||
slabPx: MASK_W * MASK_H,
|
||||
bitset,
|
||||
bbox,
|
||||
slabBounds: { x: 0, y: 0, w: MASK_W, h: MASK_H },
|
||||
},
|
||||
} as MessageEvent<WorkerOut>);
|
||||
});
|
||||
return;
|
||||
}
|
||||
// invalidate: no-op
|
||||
}
|
||||
|
||||
terminate() {}
|
||||
}
|
||||
|
||||
const RealWorker = globalThis.Worker;
|
||||
const RealCreateImageBitmap = globalThis.createImageBitmap;
|
||||
|
||||
function installFakeMaskWorker() {
|
||||
FakeMaskWorker.inits = [];
|
||||
(globalThis as unknown as { Worker: typeof FakeMaskWorker }).Worker = FakeMaskWorker;
|
||||
}
|
||||
|
||||
function restoreWorkerGlobals() {
|
||||
if (RealWorker === undefined) {
|
||||
delete (globalThis as unknown as { Worker?: unknown }).Worker;
|
||||
} else {
|
||||
globalThis.Worker = RealWorker;
|
||||
}
|
||||
if (RealCreateImageBitmap === undefined) {
|
||||
delete (globalThis as unknown as { createImageBitmap?: unknown }).createImageBitmap;
|
||||
} else {
|
||||
globalThis.createImageBitmap = RealCreateImageBitmap;
|
||||
}
|
||||
}
|
||||
|
||||
async function settleOverlay(
|
||||
s: ReturnType<typeof createCaptureSession>,
|
||||
ms = 800,
|
||||
): Promise<Mask> {
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < ms) {
|
||||
const cap = get(s.capture);
|
||||
if (cap.k === 'mask' && cap.overlay && cap.overlay.slabPx > 0) return cap.overlay;
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
throw new Error('mask overlay never settled');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreWorkerGlobals();
|
||||
});
|
||||
|
||||
test('#61: after pick of index N≠0, Mask/Axis/Measure operate on that blob only', async () => {
|
||||
installFakeMaskWorker();
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
const c = tinyJpeg('c');
|
||||
await s.addToBatch(a);
|
||||
await s.addToBatch(b);
|
||||
await s.addToBatch(c);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(1);
|
||||
|
||||
let cap = get(s.capture);
|
||||
assert.equal(cap.k, 'mask');
|
||||
if (cap.k === 'mask') {
|
||||
assert.equal(cap.source.blob, b, 'Mask must open on picked photo index 1');
|
||||
assert.notEqual(cap.source.blob, a);
|
||||
}
|
||||
|
||||
// Kick an immediate mask pass (skip 2s sensitivity debounce).
|
||||
s.setSheet('green');
|
||||
await settleOverlay(s);
|
||||
|
||||
// Worker must have been inited only for the calibration blob — not a, not c.
|
||||
assert.ok(FakeMaskWorker.inits.length >= 1, 'mask worker must init');
|
||||
for (const blob of FakeMaskWorker.inits) {
|
||||
assert.equal(blob, b, 'Mask worker must never init on non-calibration batch photos');
|
||||
}
|
||||
|
||||
s.approveMask();
|
||||
cap = get(s.capture);
|
||||
assert.equal(cap.k, 'axis', 'approve Mask → Length axis');
|
||||
if (cap.k === 'axis') {
|
||||
assert.equal(cap.source.blob, b, 'Axis must keep the calibration source');
|
||||
}
|
||||
|
||||
s.approveAxis();
|
||||
cap = get(s.capture);
|
||||
assert.equal(cap.k, 'measure', 'approve Axis → Measure');
|
||||
if (cap.k === 'measure') {
|
||||
assert.equal(cap.source.blob, b, 'Measure must keep the calibration source');
|
||||
}
|
||||
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#61: Calculate produces inventory PNG + M1 measures for calibration source only', async () => {
|
||||
installFakeMaskWorker();
|
||||
(globalThis as unknown as { createImageBitmap: typeof createImageBitmap }).createImageBitmap =
|
||||
async () =>
|
||||
({
|
||||
width: MASK_W,
|
||||
height: MASK_H,
|
||||
close() {},
|
||||
}) as ImageBitmap;
|
||||
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
await s.addToBatch(a);
|
||||
await s.addToBatch(b);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(1);
|
||||
s.setSheet('black');
|
||||
await settleOverlay(s);
|
||||
s.approveMask();
|
||||
s.approveAxis();
|
||||
|
||||
// L = 40 in (320 eighths), thickness = 2 in (16 eighths) — scale ≈ longest_axis_px / L
|
||||
s.setLength(320);
|
||||
s.setThickness(16);
|
||||
await s.calculate();
|
||||
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'measure');
|
||||
if (cap.k === 'measure') {
|
||||
assert.equal(cap.source.blob, b);
|
||||
assert.ok(cap.results, 'Calculate must produce results');
|
||||
const r = cap.results!;
|
||||
assert.ok(r.inventoryPng instanceof Blob, 'clean inventory PNG blob');
|
||||
assert.equal(typeof r.scale, 'number');
|
||||
assert.ok(r.scale > 0, 'scale px/in > 0');
|
||||
assert.equal(typeof r.sqft, 'number');
|
||||
assert.equal(typeof r.bdft, 'number');
|
||||
// CAPTURE.md: bdft = sqft × thickness_in
|
||||
const thicknessIn = 16 / 8;
|
||||
assert.ok(
|
||||
Math.abs(r.bdft - r.sqft * thicknessIn) < 0.011,
|
||||
`bdft ${r.bdft} must equal sqft×thickness (${r.sqft}*${thicknessIn})`,
|
||||
);
|
||||
assert.ok(r.widths, 'widths present');
|
||||
assert.equal(r.lengthEighths, 320);
|
||||
assert.equal(r.thicknessEighths, 16);
|
||||
assert.equal(cap.source.widthPx, MASK_W, 'measure source dims from calibration decode');
|
||||
}
|
||||
|
||||
// Pre-#62: Mask UI path used only the calibration blob. After Calculate, #62
|
||||
// may init the worker on non-calibration siblings for frozen-mask apply.
|
||||
const preApplyInits = FakeMaskWorker.inits.filter((blob) => blob === b || blob === a);
|
||||
assert.ok(preApplyInits.some((blob) => blob === b), 'calibration must have been masked');
|
||||
// Sibling apply may touch `a`; that is #62, not a #61 regression of Mask UI.
|
||||
assert.ok(
|
||||
FakeMaskWorker.inits.filter((blob) => blob === b).length >= 1,
|
||||
'calibration blob must appear in worker inits',
|
||||
);
|
||||
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#61: other batch photos stay in draft.batch untouched by mask approve', async () => {
|
||||
installFakeMaskWorker();
|
||||
const s = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
const c = tinyJpeg('c');
|
||||
await s.addToBatch(a);
|
||||
await s.addToBatch(b);
|
||||
await s.addToBatch(c);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(1);
|
||||
s.setSheet('auto');
|
||||
await settleOverlay(s);
|
||||
|
||||
const before = store.peek();
|
||||
assert.ok(before);
|
||||
assert.equal((before!.batch ?? []).length, 3);
|
||||
assert.equal(before!.batch![0].blob, a);
|
||||
assert.equal(before!.batch![1].blob, b);
|
||||
assert.equal(before!.batch![2].blob, c);
|
||||
|
||||
s.approveMask();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const after = store.peek();
|
||||
assert.ok(after);
|
||||
assert.equal(after!.stage, 'axis');
|
||||
assert.equal(after!.calibrationIndex, 1);
|
||||
assert.equal(after!.source.blob, b, 'draft.source is calibration only');
|
||||
assert.equal((after!.batch ?? []).length, 3, 'full batch retained');
|
||||
assert.equal(after!.batch![0].blob, a, 'batch[0] untouched');
|
||||
assert.equal(after!.batch![1].blob, b);
|
||||
assert.equal(after!.batch![2].blob, c, 'batch[2] untouched — no Mask UI on other shots');
|
||||
|
||||
// Approve axis too — batch still untouched.
|
||||
s.approveAxis();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const meas = store.peek();
|
||||
assert.equal(meas!.stage, 'measure');
|
||||
assert.equal((meas!.batch ?? []).length, 3);
|
||||
assert.equal(meas!.batch![0].blob, a);
|
||||
assert.equal(meas!.batch![2].blob, c);
|
||||
assert.equal(meas!.calibrationIndex, 1);
|
||||
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('#61: draft resume through measure restores calibration source (not photos[0])', async () => {
|
||||
installFakeMaskWorker();
|
||||
(globalThis as unknown as { createImageBitmap: typeof createImageBitmap }).createImageBitmap =
|
||||
async () =>
|
||||
({
|
||||
width: MASK_W,
|
||||
height: MASK_H,
|
||||
close() {},
|
||||
}) as ImageBitmap;
|
||||
|
||||
const s1 = createCaptureSession({ draft: store });
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b');
|
||||
await s1.addToBatch(a);
|
||||
await s1.addToBatch(b);
|
||||
s1.continueBatch();
|
||||
s1.pickCalibration(1);
|
||||
s1.setSheet('green');
|
||||
await settleOverlay(s1);
|
||||
s1.approveMask();
|
||||
s1.approveAxis();
|
||||
s1.setLength(320);
|
||||
s1.setThickness(16);
|
||||
await s1.calculate();
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
s1.dispose();
|
||||
|
||||
FakeMaskWorker.inits = [];
|
||||
const s2 = createCaptureSession({ draft: store });
|
||||
await s2.resumeProbe();
|
||||
assert.equal(get(s2.capture).k, 'resume');
|
||||
s2.continueDraft();
|
||||
// rederiveMask via FakeWorker
|
||||
const start = Date.now();
|
||||
let cap = get(s2.capture);
|
||||
while (cap.k !== 'measure' && Date.now() - start < 1500) {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
cap = get(s2.capture);
|
||||
}
|
||||
assert.equal(cap.k, 'measure', 'Continue must restore Measure');
|
||||
if (cap.k === 'measure') {
|
||||
assert.equal(cap.source.blob, b, 'restored Measure source is calibration pick');
|
||||
assert.ok(cap.results, 'results restored');
|
||||
}
|
||||
assert.equal(store.peek()?.calibrationIndex, 1);
|
||||
// Resume rederive may re-init worker on calibration source only.
|
||||
for (const blob of FakeMaskWorker.inits) {
|
||||
assert.equal(blob, b, 'resume must not mask non-calibration batch photos');
|
||||
}
|
||||
s2.dispose();
|
||||
});
|
||||
|
||||
test('#61: App runs single Mask/Axis/Measure panels (no per-batch Mask loop)', () => {
|
||||
const app = readFileSync(join(here, '..', 'App.svelte'), 'utf8');
|
||||
assert.match(app, /MaskPanel/);
|
||||
assert.match(app, /AxisPanel/);
|
||||
assert.match(app, /MeasurePanel/);
|
||||
// Dishonest proxy: must not iterate batch photos into Mask UI.
|
||||
assert.ok(
|
||||
!/\{\s*#each\s+[^}]*photos[^}]*\}[\s\S]*MaskPanel/i.test(app),
|
||||
'App must not #each batch photos into MaskPanel',
|
||||
);
|
||||
const sessionSrc = readFileSync(join(here, 'session.ts'), 'utf8');
|
||||
assert.ok(
|
||||
!/for\s*\([^)]*batch[^)]*\)[\s\S]{0,120}(enterMaskOnSource|approveMask|k:\s*'mask')/.test(
|
||||
sessionSrc,
|
||||
),
|
||||
'session must not loop Mask over every batch photo in this issue',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { test, beforeEach, afterEach } from 'node:test';
|
||||
import { get } from 'svelte/store';
|
||||
import type { Draft, Mask, MaskParams, WorkerIn, WorkerOut } from './capture.types';
|
||||
import { createCaptureSession, type DraftStore } from './session';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function tinyJpeg(label: string): File {
|
||||
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, label.charCodeAt(0) & 0xff]);
|
||||
return new File([bytes], `${label}.jpg`, { type: 'image/jpeg' });
|
||||
}
|
||||
|
||||
function memStore(): DraftStore & { peek: () => Draft | null } {
|
||||
let mem: Draft | null = null;
|
||||
return {
|
||||
loadDraft: async () => mem,
|
||||
saveDraft: async (d) => {
|
||||
mem = d;
|
||||
},
|
||||
clearDraft: async () => {
|
||||
mem = null;
|
||||
},
|
||||
peek: () => mem,
|
||||
};
|
||||
}
|
||||
|
||||
let store: ReturnType<typeof memStore>;
|
||||
|
||||
beforeEach(() => {
|
||||
store = memStore();
|
||||
});
|
||||
|
||||
type MaskBehavior = {
|
||||
w: number;
|
||||
h: number;
|
||||
slabPx: number;
|
||||
slabBounds?: { x: number; y: number; w: number; h: number };
|
||||
};
|
||||
|
||||
class FakeMaskWorker {
|
||||
onmessage: ((ev: MessageEvent<WorkerOut>) => void) | null = null;
|
||||
static inits: Blob[] = [];
|
||||
static maskCalls: { sheet: string; sensitivity: number; blob: Blob | null }[] = [];
|
||||
static lastInitBlob: Blob | null = null;
|
||||
static behaviorFor: (blob: Blob) => MaskBehavior = () => ({
|
||||
w: 1000,
|
||||
h: 900,
|
||||
slabPx: 1000 * 900,
|
||||
slabBounds: { x: 0, y: 0, w: 1000, h: 900 },
|
||||
});
|
||||
|
||||
constructor(_url: URL | string, _opts?: WorkerOptions) {}
|
||||
|
||||
postMessage(msg: WorkerIn) {
|
||||
if (msg.kind === 'init') {
|
||||
FakeMaskWorker.inits.push(msg.blob);
|
||||
FakeMaskWorker.lastInitBlob = msg.blob;
|
||||
const id = msg.id;
|
||||
const b = FakeMaskWorker.behaviorFor(msg.blob);
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({ data: { id, kind: 'decoded', w: b.w, h: b.h } } as MessageEvent<WorkerOut>);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (msg.kind === 'mask') {
|
||||
const id = msg.id;
|
||||
const blob = FakeMaskWorker.lastInitBlob;
|
||||
FakeMaskWorker.maskCalls.push({
|
||||
sheet: msg.sheet,
|
||||
sensitivity: msg.sensitivity,
|
||||
blob,
|
||||
});
|
||||
const b = blob ? FakeMaskWorker.behaviorFor(blob) : { w: 40, h: 20, slabPx: 0 };
|
||||
const bitset = new Uint8Array(Math.max(1, b.w * b.h)).fill(b.slabPx > 0 ? 1 : 0);
|
||||
const bbox = {
|
||||
corners: [
|
||||
[b.w, 0],
|
||||
[b.w, b.h],
|
||||
[0, b.h],
|
||||
[0, 0],
|
||||
] as [number, number][],
|
||||
longSidePx: b.w,
|
||||
angleDeg: 0,
|
||||
};
|
||||
const slabBounds = b.slabBounds ?? { x: 0, y: 0, w: b.w, h: b.h };
|
||||
queueMicrotask(() => {
|
||||
this.onmessage?.({
|
||||
data: {
|
||||
id,
|
||||
kind: 'ready',
|
||||
slabPx: b.slabPx,
|
||||
bitset,
|
||||
bbox,
|
||||
slabBounds,
|
||||
},
|
||||
} as MessageEvent<WorkerOut>);
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
terminate() {}
|
||||
}
|
||||
|
||||
const RealWorker = globalThis.Worker;
|
||||
const RealCreateImageBitmap = globalThis.createImageBitmap;
|
||||
|
||||
function installFakes() {
|
||||
FakeMaskWorker.inits = [];
|
||||
FakeMaskWorker.maskCalls = [];
|
||||
FakeMaskWorker.lastInitBlob = null;
|
||||
FakeMaskWorker.behaviorFor = () => ({
|
||||
w: 1000,
|
||||
h: 900,
|
||||
slabPx: 1000 * 900,
|
||||
slabBounds: { x: 0, y: 0, w: 1000, h: 900 },
|
||||
});
|
||||
(globalThis as unknown as { Worker: typeof FakeMaskWorker }).Worker = FakeMaskWorker;
|
||||
(globalThis as unknown as { createImageBitmap: typeof createImageBitmap }).createImageBitmap =
|
||||
async (blob: ImageBitmapSource) => {
|
||||
const b = blob instanceof Blob ? FakeMaskWorker.behaviorFor(blob) : { w: 1000, h: 900 };
|
||||
return { width: b.w, height: b.h, close() {} } as ImageBitmap;
|
||||
};
|
||||
}
|
||||
|
||||
function restoreGlobals() {
|
||||
if (RealWorker === undefined) {
|
||||
delete (globalThis as unknown as { Worker?: unknown }).Worker;
|
||||
} else {
|
||||
globalThis.Worker = RealWorker;
|
||||
}
|
||||
if (RealCreateImageBitmap === undefined) {
|
||||
delete (globalThis as unknown as { createImageBitmap?: unknown }).createImageBitmap;
|
||||
} else {
|
||||
globalThis.createImageBitmap = RealCreateImageBitmap;
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreGlobals();
|
||||
});
|
||||
|
||||
async function settleOverlay(
|
||||
s: ReturnType<typeof createCaptureSession>,
|
||||
ms = 2500,
|
||||
): Promise<Mask> {
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < ms) {
|
||||
const cap = get(s.capture);
|
||||
if (cap.k === 'mask' && cap.overlay && cap.overlay.slabPx > 0) return cap.overlay;
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
throw new Error('mask overlay never settled');
|
||||
}
|
||||
|
||||
async function driveToMeasure(
|
||||
s: ReturnType<typeof createCaptureSession>,
|
||||
photos: File[],
|
||||
calIndex: number,
|
||||
maskParams: Partial<MaskParams> = { sheet: 'green', sensitivity: 50 },
|
||||
) {
|
||||
for (const p of photos) await s.addToBatch(p);
|
||||
s.continueBatch();
|
||||
s.pickCalibration(calIndex);
|
||||
if (typeof maskParams.sensitivity === 'number') s.setSensitivity(maskParams.sensitivity);
|
||||
// setSheet runs an immediate pass (after sensitivity so the pass sees frozen params)
|
||||
s.setSheet(maskParams.sheet ?? 'auto');
|
||||
await settleOverlay(s);
|
||||
s.approveMask();
|
||||
s.approveAxis();
|
||||
s.setLength(320); // 40 in
|
||||
s.setThickness(16); // 2 in
|
||||
}
|
||||
|
||||
test('test(photos): Calculate stores overlayPng on results, clean inventory untouched (#63)', async () => {
|
||||
installFakes();
|
||||
let encodeN = 0;
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => {
|
||||
encodeN++;
|
||||
return {
|
||||
blob: new Blob([`clean-${encodeN}`], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
};
|
||||
},
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
const a = tinyJpeg('a');
|
||||
const b = tinyJpeg('b'); // cal
|
||||
await driveToMeasure(s, [a, b], 1, { sheet: 'green' });
|
||||
await s.calculate();
|
||||
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'measure');
|
||||
if (cap.k !== 'measure') return;
|
||||
assert.ok(cap.results, 'results present');
|
||||
assert.ok(cap.results!.inventoryPng, 'clean cal PNG in results.inventoryPng');
|
||||
assert.equal(cap.results!.inventoryPng.type, 'image/png');
|
||||
|
||||
const overlay = (cap.results as { overlayPng?: Blob }).overlayPng;
|
||||
assert.ok(overlay, 'results.overlayPng must exist after Calculate (#63)');
|
||||
assert.equal(overlay!.type, 'image/png');
|
||||
assert.notEqual(overlay, cap.results!.inventoryPng, 'overlay is a second copy, not the clean PNG');
|
||||
|
||||
const apply = (cap as { batchApply?: unknown[] }).batchApply;
|
||||
assert.ok(Array.isArray(apply));
|
||||
assert.equal(apply![1], null, 'batchApply[cal] stays null');
|
||||
assert.ok(apply![0] && (apply![0] as { status: string }).status === 'ok', 'siblings unchanged');
|
||||
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('test(photos): single-photo batch still yields clean + overlayPng (#63)', async () => {
|
||||
installFakes();
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['only-clean'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
await driveToMeasure(s, [tinyJpeg('only')], 0, { sheet: 'auto' });
|
||||
await s.calculate();
|
||||
|
||||
const cap = get(s.capture);
|
||||
assert.equal(cap.k, 'measure');
|
||||
if (cap.k !== 'measure') return;
|
||||
assert.ok(cap.results!.inventoryPng);
|
||||
assert.ok((cap.results as { overlayPng?: Blob }).overlayPng, 'overlay even for batch of one');
|
||||
assert.deepEqual((cap as { batchApply?: unknown[] }).batchApply, [null]);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('test(photos): draft persists overlayPng alongside inventoryPng (#63)', async () => {
|
||||
installFakes();
|
||||
const s = createCaptureSession({
|
||||
draft: store,
|
||||
encodeInventory: async () => ({
|
||||
blob: new Blob(['draft-clean'], { type: 'image/png' }),
|
||||
sourceBelowFloor: false,
|
||||
}),
|
||||
} as Parameters<typeof createCaptureSession>[0]);
|
||||
|
||||
await driveToMeasure(s, [tinyJpeg('a'), tinyJpeg('b')], 0, { sheet: 'black' });
|
||||
await s.calculate();
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
|
||||
const d = store.peek();
|
||||
assert.ok(d);
|
||||
assert.equal(d!.stage, 'measure');
|
||||
assert.ok(d!.inventoryPng, 'draft keeps clean inventory');
|
||||
assert.ok(
|
||||
(d as { overlayPng?: Blob | null }).overlayPng,
|
||||
'draft.overlayPng must be persisted for #64 lineup',
|
||||
);
|
||||
assert.equal(d!.batchApply![0], null, 'cal slot still null on draft');
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
test('test(photos): dishonest proxies absent — no raw-photo overlay / no cal-slot stash (#63)', async () => {
|
||||
const sessionSrc = readFileSync(join(here, 'session.ts'), 'utf8');
|
||||
const overlaySrcPath = join(here, '..', 'png', 'overlay.ts');
|
||||
let overlaySrc = '';
|
||||
try {
|
||||
overlaySrc = readFileSync(overlaySrcPath, 'utf8');
|
||||
} catch {
|
||||
overlaySrc = '';
|
||||
}
|
||||
assert.ok(
|
||||
/overlayPng|encodeOverlay|dimensionOverlay|buildOverlayPlan/i.test(sessionSrc) ||
|
||||
overlaySrc.length > 0,
|
||||
'session or png/overlay must implement dimension overlay (#63)',
|
||||
);
|
||||
const calcBody = sessionSrc.match(/async calculate\(\)[\s\S]*?(?=\n [a-zA-Z]+\(|\n \})/);
|
||||
assert.ok(calcBody, 'calculate() must exist');
|
||||
assert.ok(
|
||||
!/batchApply\s*\[\s*calIndex\s*\]\s*=\s*\{[^}]*overlay/i.test(calcBody![0]),
|
||||
'must not put overlay into batchApply[cal]',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,649 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import type {
|
||||
BatchPhotoResult, Capture, Draft, Eighths, Mask, MaskParams, Measures, Sheet, Source, WorkerIn, WorkerOut,
|
||||
} from './capture.types';
|
||||
import {
|
||||
DEFAULT_MASK_PARAMS, EMPTY_ABOX, EMPTY_BBOX, eighthsToIn,
|
||||
} from './capture.types';
|
||||
import { loadDraft, saveDraft, clearDraft } from '../draft/idb';
|
||||
import { measure } from '../measure/measure';
|
||||
import { orientedRect } from '../geometry/rect';
|
||||
import { encodeInventoryPng, type InventoryInput } from '../png/inventory';
|
||||
import { encodeOverlayPng, type EncodeOverlayInput } from '../png/overlay';
|
||||
import { decodeOrientedBitmap } from '../decodeOrientedBitmap';
|
||||
|
||||
const DEBOUNCE_MS = 2000;
|
||||
const BUSY_MS = 300;
|
||||
|
||||
export interface DraftStore {
|
||||
loadDraft(): Promise<Draft | null>;
|
||||
saveDraft(d: Draft): Promise<void>;
|
||||
clearDraft(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface CaptureSession {
|
||||
capture: import('svelte/store').Readable<Capture>;
|
||||
busy: import('svelte/store').Readable<boolean>;
|
||||
resumeProbe(): Promise<void>;
|
||||
continueDraft(): void;
|
||||
startFresh(): void;
|
||||
/** Append a photo to the batch; stays on batch. */
|
||||
addToBatch(file: File): Promise<void>;
|
||||
/** Alias: same as addToBatch (no longer jumps to mask). */
|
||||
addPhoto(file: File): Promise<void>;
|
||||
removeFromBatch(index: number): void;
|
||||
/** Advance when batch has ≥1 photo → pickCalibration. */
|
||||
continueBatch(): void;
|
||||
/** User picks which batch photo is the calibration reference → Mask on that Source. */
|
||||
pickCalibration(index: number): void;
|
||||
retakes(): void;
|
||||
setSensitivity(n: number): void;
|
||||
setSheet(s: Sheet): void;
|
||||
approveMask(): void;
|
||||
setAxisAngle(deg: number): void;
|
||||
approveAxis(): void;
|
||||
setLength(e: Eighths): void;
|
||||
setThickness(e: Eighths): void;
|
||||
calculate(): Promise<void>;
|
||||
back(): void;
|
||||
getInventoryUrl(): string | null;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface SessionOpts {
|
||||
draft?: DraftStore;
|
||||
/** Injectable only for deterministic tests; production uses encodeInventoryPng. */
|
||||
encodeInventory?: (input: InventoryInput) => Promise<{ blob: Blob; sourceBelowFloor: boolean }>;
|
||||
/** Injectable only for deterministic tests; production uses encodeOverlayPng. */
|
||||
encodeOverlay?: (input: EncodeOverlayInput) => Promise<Blob>;
|
||||
}
|
||||
|
||||
const defaultDraft: DraftStore = { loadDraft, saveDraft, clearDraft };
|
||||
|
||||
const batchPhotosOf = (d: Draft): Source[] =>
|
||||
d.batch && d.batch.length > 0 ? d.batch : [d.source];
|
||||
|
||||
// The one writer. Owns the worker port, the single debounce timer, and the draft.
|
||||
// Every transition to an approved branch persists; no explicit "save".
|
||||
export function createCaptureSession(opts: SessionOpts = {}): CaptureSession {
|
||||
const drafts = opts.draft ?? defaultDraft;
|
||||
const encodeInventory = opts.encodeInventory ?? encodeInventoryPng;
|
||||
const encodeOverlay = opts.encodeOverlay ?? encodeOverlayPng;
|
||||
const capture = writable<Capture>({ k: 'batch', photos: [] });
|
||||
const busy = writable(false);
|
||||
let state: Capture = { k: 'batch', photos: [] };
|
||||
let batchPhotos: Source[] = [];
|
||||
let calibrationIndex: number | null = null;
|
||||
let worker: Worker | null = null;
|
||||
let jobId = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let passStarted = 0;
|
||||
let busyTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pngUrl: string | null = null;
|
||||
let resumed = false;
|
||||
|
||||
const set = (next: Capture) => {
|
||||
state = next;
|
||||
capture.set(next);
|
||||
};
|
||||
|
||||
const teardownWorker = () => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
if (worker) {
|
||||
try {
|
||||
worker.postMessage({ id: ++jobId, kind: 'invalidate' } satisfies WorkerIn);
|
||||
worker.terminate();
|
||||
} catch {
|
||||
/* worker unavailable */
|
||||
}
|
||||
worker = null;
|
||||
}
|
||||
if (pngUrl) {
|
||||
URL.revokeObjectURL(pngUrl);
|
||||
pngUrl = null;
|
||||
}
|
||||
};
|
||||
|
||||
const makeWorker = (blob: Blob) => {
|
||||
if (typeof Worker === 'undefined') return;
|
||||
if (worker) worker.terminate();
|
||||
try {
|
||||
worker = new Worker(new URL('../worker/mask.worker.ts', import.meta.url), { type: 'module' });
|
||||
worker.onmessage = (e: MessageEvent<WorkerOut>) => onWorkerOut(e.data);
|
||||
worker.postMessage({ id: ++jobId, kind: 'init', blob } satisfies WorkerIn);
|
||||
} catch {
|
||||
worker = null;
|
||||
}
|
||||
};
|
||||
|
||||
const onWorkerOut = (msg: WorkerOut) => {
|
||||
if (msg.id < jobId - 1) return; // stale
|
||||
if (msg.kind === 'decoded') {
|
||||
if (state.k === 'mask') {
|
||||
set({ ...state, source: { ...state.source, widthPx: msg.w, heightPx: msg.h } });
|
||||
}
|
||||
schedulePass();
|
||||
return;
|
||||
}
|
||||
busy.set(false);
|
||||
if (busyTimer) {
|
||||
clearTimeout(busyTimer);
|
||||
busyTimer = null;
|
||||
}
|
||||
if (state.k !== 'mask') return;
|
||||
if (msg.kind === 'failed') {
|
||||
set({ ...state, failed: true });
|
||||
return;
|
||||
}
|
||||
const mask: Mask = {
|
||||
params: { sheet: state.control.sheet, sensitivity: state.control.sensitivity },
|
||||
slabPx: msg.slabPx,
|
||||
bitset: msg.bitset,
|
||||
bbox: msg.bbox,
|
||||
slabBounds: msg.slabBounds,
|
||||
};
|
||||
set({ ...state, overlay: mask, failed: false });
|
||||
};
|
||||
|
||||
const runPass = () => {
|
||||
if (state.k !== 'mask' || !worker) return;
|
||||
passStarted = Date.now();
|
||||
busyTimer = setTimeout(() => busy.set(true), BUSY_MS);
|
||||
worker.postMessage({
|
||||
id: ++jobId,
|
||||
kind: 'mask',
|
||||
sheet: state.control.sheet,
|
||||
sensitivity: state.control.sensitivity,
|
||||
} satisfies WorkerIn);
|
||||
};
|
||||
|
||||
// The 2.0s debounce: re-armed on every control change; a sheet change
|
||||
// recomputes immediately (spec allows), so it clears the pending pass.
|
||||
const schedulePass = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(runPass, DEBOUNCE_MS);
|
||||
};
|
||||
|
||||
const draftFromState = (): Draft | null => {
|
||||
const strip = (m: Mask) => ({ slabPx: m.slabPx, bbox: m.bbox, slabBounds: m.slabBounds });
|
||||
if (state.k === 'batch') {
|
||||
if (state.photos.length === 0) return null;
|
||||
return {
|
||||
version: 1,
|
||||
stage: 'batch',
|
||||
batch: state.photos,
|
||||
source: state.photos[0],
|
||||
maskParams: DEFAULT_MASK_PARAMS,
|
||||
mask: { slabPx: 0, bbox: EMPTY_BBOX, slabBounds: EMPTY_ABOX },
|
||||
lengthEighths: 0,
|
||||
thicknessEighths: 0,
|
||||
results: null,
|
||||
inventoryPng: null,
|
||||
};
|
||||
}
|
||||
if (state.k === 'pickCalibration') {
|
||||
return {
|
||||
version: 1,
|
||||
stage: 'pickCalibration',
|
||||
batch: state.photos,
|
||||
source: state.photos[0],
|
||||
maskParams: DEFAULT_MASK_PARAMS,
|
||||
mask: { slabPx: 0, bbox: EMPTY_BBOX, slabBounds: EMPTY_ABOX },
|
||||
lengthEighths: 0,
|
||||
thicknessEighths: 0,
|
||||
results: null,
|
||||
inventoryPng: null,
|
||||
};
|
||||
}
|
||||
const calIdx = calibrationIndex ?? undefined;
|
||||
if (state.k === 'axis') {
|
||||
return {
|
||||
version: 1, stage: 'axis', batch: batchPhotos.length ? batchPhotos : [state.source],
|
||||
calibrationIndex: calIdx,
|
||||
source: state.source, maskParams: state.approvedMask.params,
|
||||
mask: strip(state.approvedMask), axisBbox: state.axis.bbox,
|
||||
lengthEighths: 0, thicknessEighths: 0, results: null, inventoryPng: null,
|
||||
};
|
||||
}
|
||||
if (state.k === 'measure') {
|
||||
const { inventoryPng: _drop, overlayPng: _dropOverlay, ...rest } = state.results ?? ({} as Measures);
|
||||
return {
|
||||
version: 1, stage: 'measure', batch: batchPhotos.length ? batchPhotos : [state.source],
|
||||
calibrationIndex: calIdx,
|
||||
source: state.source, maskParams: state.approvedMask.params,
|
||||
mask: strip(state.approvedMask), axisBbox: state.axis.bbox,
|
||||
lengthEighths: state.lengthEighths, thicknessEighths: state.thicknessEighths,
|
||||
results: state.results ? rest : null,
|
||||
inventoryPng: state.results?.inventoryPng ?? null,
|
||||
overlayPng: state.results?.overlayPng ?? null,
|
||||
batchApply: state.batchApply,
|
||||
};
|
||||
}
|
||||
if (state.k === 'mask' && state.overlay) {
|
||||
return {
|
||||
version: 1, stage: 'mask', batch: batchPhotos.length ? batchPhotos : [state.source],
|
||||
calibrationIndex: calIdx,
|
||||
source: state.source, maskParams: state.overlay.params,
|
||||
mask: strip(state.overlay),
|
||||
lengthEighths: 0, thicknessEighths: 0, results: null, inventoryPng: null,
|
||||
};
|
||||
}
|
||||
// Mask before first overlay settles: still persist calibration choice + batch.
|
||||
if (state.k === 'mask') {
|
||||
return {
|
||||
version: 1, stage: 'mask', batch: batchPhotos.length ? batchPhotos : [state.source],
|
||||
calibrationIndex: calIdx,
|
||||
source: state.source, maskParams: state.control,
|
||||
mask: { slabPx: 0, bbox: EMPTY_BBOX, slabBounds: EMPTY_ABOX },
|
||||
lengthEighths: 0, thicknessEighths: 0, results: null, inventoryPng: null,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const persist = async () => {
|
||||
const d = draftFromState();
|
||||
if (d) await drafts.saveDraft(d);
|
||||
else if (state.k === 'batch' && state.photos.length === 0) await drafts.clearDraft();
|
||||
};
|
||||
|
||||
// Re-derive the mask bitset from a stored photo + frozen params. The decoded
|
||||
// dimensions are returned because batch Sources begin with dimensions unknown.
|
||||
const rederiveMaskDetailed = (
|
||||
source: Source,
|
||||
params: MaskParams,
|
||||
stub: Omit<Mask, 'bitset' | 'params'>,
|
||||
): Promise<{ mask: Mask; widthPx: number; heightPx: number }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (typeof Worker === 'undefined') {
|
||||
reject(new Error('Worker unavailable'));
|
||||
return;
|
||||
}
|
||||
const w = new Worker(new URL('../worker/mask.worker.ts', import.meta.url), { type: 'module' });
|
||||
let id = 0;
|
||||
let widthPx = source.widthPx;
|
||||
let heightPx = source.heightPx;
|
||||
const fail = (reason: string) => {
|
||||
w.terminate();
|
||||
reject(new Error(reason));
|
||||
};
|
||||
w.onmessage = (e: MessageEvent<WorkerOut>) => {
|
||||
const msg = e.data;
|
||||
if (msg.kind === 'decoded') {
|
||||
widthPx = msg.w;
|
||||
heightPx = msg.h;
|
||||
w.postMessage({ id: ++id, kind: 'mask', sheet: params.sheet, sensitivity: params.sensitivity } satisfies WorkerIn);
|
||||
return;
|
||||
}
|
||||
if (msg.kind === 'failed') {
|
||||
fail(msg.reason);
|
||||
return;
|
||||
}
|
||||
if (msg.kind === 'ready') {
|
||||
w.terminate();
|
||||
resolve({
|
||||
widthPx,
|
||||
heightPx,
|
||||
mask: {
|
||||
params,
|
||||
slabPx: msg.slabPx || stub.slabPx,
|
||||
bitset: msg.bitset,
|
||||
bbox: msg.slabPx > 0 ? msg.bbox : stub.bbox,
|
||||
slabBounds: msg.slabPx > 0 ? msg.slabBounds : stub.slabBounds,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
w.postMessage({ id: ++id, kind: 'init', blob: source.blob } satisfies WorkerIn);
|
||||
});
|
||||
|
||||
const rederiveMask = (
|
||||
source: Source,
|
||||
params: MaskParams,
|
||||
stub: Omit<Mask, 'bitset' | 'params'>,
|
||||
): Promise<Mask> => rederiveMaskDetailed(source, params, stub).then((r) => r.mask);
|
||||
|
||||
// Legacy drafts (pre-axisBbox, with heading) carry no usable axis state;
|
||||
// fall back to the mask's own bbox.
|
||||
const draftAxisBbox = (d: Draft) => d.axisBbox ?? d.mask.bbox;
|
||||
|
||||
const restoreFromDraft = async (d: Draft) => {
|
||||
batchPhotos = batchPhotosOf(d);
|
||||
calibrationIndex = typeof d.calibrationIndex === 'number' ? d.calibrationIndex : null;
|
||||
if (d.stage === 'batch') {
|
||||
teardownWorker();
|
||||
calibrationIndex = null;
|
||||
set({ k: 'batch', photos: [...batchPhotos] });
|
||||
return;
|
||||
}
|
||||
if (d.stage === 'pickCalibration') {
|
||||
teardownWorker();
|
||||
calibrationIndex = null;
|
||||
set({ k: 'pickCalibration', photos: [...batchPhotos] });
|
||||
return;
|
||||
}
|
||||
const source: Source = { widthPx: d.source.widthPx, heightPx: d.source.heightPx, blob: d.source.blob };
|
||||
if (d.stage === 'mask') {
|
||||
teardownWorker();
|
||||
set({ k: 'mask', source, control: { ...d.maskParams }, overlay: null, failed: false });
|
||||
makeWorker(source.blob);
|
||||
return;
|
||||
}
|
||||
teardownWorker();
|
||||
try {
|
||||
const mask = await rederiveMask(source, d.maskParams, d.mask);
|
||||
if (d.stage === 'axis') {
|
||||
set({ k: 'axis', source, approvedMask: mask, axis: { bbox: draftAxisBbox(d) } });
|
||||
return;
|
||||
}
|
||||
if (d.inventoryPng) {
|
||||
if (pngUrl) URL.revokeObjectURL(pngUrl);
|
||||
pngUrl = URL.createObjectURL(d.inventoryPng);
|
||||
}
|
||||
set({
|
||||
k: 'measure', source, approvedMask: mask,
|
||||
axis: { bbox: draftAxisBbox(d) },
|
||||
lengthEighths: d.lengthEighths, thicknessEighths: d.thicknessEighths,
|
||||
results: d.results
|
||||
? {
|
||||
...d.results,
|
||||
inventoryPng: d.inventoryPng ?? new Blob(),
|
||||
overlayPng: d.overlayPng ?? undefined,
|
||||
}
|
||||
: null,
|
||||
batchApply: d.batchApply,
|
||||
});
|
||||
} catch {
|
||||
set({ k: 'mask', source, control: { ...d.maskParams }, overlay: null, failed: true });
|
||||
makeWorker(source.blob);
|
||||
}
|
||||
};
|
||||
|
||||
const enterMaskOnSource = (source: Source) => {
|
||||
teardownWorker();
|
||||
set({
|
||||
k: 'mask',
|
||||
source,
|
||||
control: { ...DEFAULT_MASK_PARAMS },
|
||||
overlay: null,
|
||||
failed: false,
|
||||
});
|
||||
makeWorker(source.blob);
|
||||
void persist();
|
||||
};
|
||||
|
||||
return {
|
||||
capture,
|
||||
busy,
|
||||
|
||||
async resumeProbe() {
|
||||
if (resumed) return;
|
||||
resumed = true;
|
||||
const d = await drafts.loadDraft();
|
||||
if (d) set({ k: 'resume', draft: d });
|
||||
},
|
||||
|
||||
continueDraft() {
|
||||
if (state.k !== 'resume') return;
|
||||
void restoreFromDraft(state.draft);
|
||||
},
|
||||
|
||||
async startFresh() {
|
||||
if (state.k !== 'resume') return;
|
||||
teardownWorker();
|
||||
batchPhotos = [];
|
||||
calibrationIndex = null;
|
||||
await drafts.clearDraft();
|
||||
set({ k: 'batch', photos: [] });
|
||||
},
|
||||
|
||||
async addToBatch(file: File) {
|
||||
if (state.k !== 'batch') return;
|
||||
const photo: Source = { widthPx: 0, heightPx: 0, blob: file };
|
||||
batchPhotos = [...state.photos, photo];
|
||||
set({ k: 'batch', photos: batchPhotos });
|
||||
await persist();
|
||||
},
|
||||
|
||||
async addPhoto(file: File) {
|
||||
// M2: addPhoto is an alias for addToBatch (no single-photo-only shortcut).
|
||||
if (state.k !== 'batch') {
|
||||
teardownWorker();
|
||||
batchPhotos = [];
|
||||
set({ k: 'batch', photos: [] });
|
||||
}
|
||||
if (state.k !== 'batch') return;
|
||||
const photo: Source = { widthPx: 0, heightPx: 0, blob: file };
|
||||
batchPhotos = [...state.photos, photo];
|
||||
set({ k: 'batch', photos: batchPhotos });
|
||||
await persist();
|
||||
},
|
||||
|
||||
removeFromBatch(index: number) {
|
||||
if (state.k !== 'batch') return;
|
||||
if (index < 0 || index >= state.photos.length) return;
|
||||
batchPhotos = state.photos.filter((_, i) => i !== index);
|
||||
set({ k: 'batch', photos: batchPhotos });
|
||||
void persist();
|
||||
},
|
||||
|
||||
continueBatch() {
|
||||
if (state.k !== 'batch' || state.photos.length === 0) return;
|
||||
batchPhotos = [...state.photos];
|
||||
calibrationIndex = null;
|
||||
teardownWorker();
|
||||
set({ k: 'pickCalibration', photos: [...batchPhotos] });
|
||||
void persist();
|
||||
},
|
||||
|
||||
// #61: enter M1 Mask on the chosen calibration Source only — never loop batch.
|
||||
pickCalibration(index: number) {
|
||||
if (state.k !== 'pickCalibration') return;
|
||||
if (index < 0 || index >= state.photos.length) return;
|
||||
batchPhotos = [...state.photos];
|
||||
calibrationIndex = index;
|
||||
enterMaskOnSource(batchPhotos[index]);
|
||||
},
|
||||
|
||||
retakes() {
|
||||
teardownWorker();
|
||||
calibrationIndex = null;
|
||||
// Return to the batch (photos kept) so the user can add/replace before continuing.
|
||||
set({ k: 'batch', photos: [...batchPhotos] });
|
||||
void persist();
|
||||
},
|
||||
|
||||
setSensitivity(n: number) {
|
||||
if (state.k !== 'mask') return;
|
||||
const s = Math.max(0, Math.min(100, Math.round(n)));
|
||||
set({ ...state, control: { ...state.control, sensitivity: s } });
|
||||
schedulePass();
|
||||
},
|
||||
|
||||
setSheet(s: Sheet) {
|
||||
if (state.k !== 'mask') return;
|
||||
set({ ...state, control: { ...state.control, sheet: s } });
|
||||
runPass();
|
||||
},
|
||||
|
||||
// #61: Axis uses the same calibration source; draft.batch siblings stay untouched.
|
||||
approveMask() {
|
||||
if (state.k !== 'mask' || !state.overlay || state.overlay.slabPx === 0) return;
|
||||
teardownWorker();
|
||||
const overlay = state.overlay;
|
||||
set({ k: 'axis', source: state.source, approvedMask: overlay, axis: { bbox: { corners: overlay.bbox.corners.map((c) => [...c] as [number, number]), longSidePx: overlay.bbox.longSidePx, angleDeg: overlay.bbox.angleDeg } } });
|
||||
void persist();
|
||||
},
|
||||
|
||||
setAxisAngle(deg: number) {
|
||||
if (state.k !== 'axis') return;
|
||||
const a = ((Math.round(deg) % 180) + 180) % 180;
|
||||
set({ ...state, axis: { bbox: orientedRect(state.axis.bbox, a) } });
|
||||
void persist();
|
||||
},
|
||||
|
||||
approveAxis() {
|
||||
if (state.k !== 'axis') return;
|
||||
set({
|
||||
k: 'measure', source: state.source, approvedMask: state.approvedMask,
|
||||
axis: { bbox: state.axis.bbox },
|
||||
lengthEighths: 0, thicknessEighths: 0, results: null,
|
||||
});
|
||||
void persist();
|
||||
},
|
||||
|
||||
setLength(e: Eighths) {
|
||||
if (state.k !== 'measure') return;
|
||||
set({ ...state, lengthEighths: Math.max(0, Math.round(e)) });
|
||||
void persist();
|
||||
},
|
||||
|
||||
setThickness(e: Eighths) {
|
||||
if (state.k !== 'measure') return;
|
||||
set({ ...state, thicknessEighths: Math.max(0, Math.round(e)) });
|
||||
void persist();
|
||||
},
|
||||
|
||||
// #62: Calculate the calibration photo, then apply its frozen mask params
|
||||
// to siblings. This stays in Measure; siblings never enter Mask controls.
|
||||
async calculate() {
|
||||
if (state.k !== 'measure') return;
|
||||
const { source, approvedMask, axis, lengthEighths, thicknessEighths } = state;
|
||||
if (lengthEighths === 0 || thicknessEighths === 0) return;
|
||||
const bitmap = await decodeOrientedBitmap(source.blob);
|
||||
const base = measure(
|
||||
approvedMask.bitset, source.widthPx, source.heightPx,
|
||||
axis.bbox, lengthEighths, thicknessEighths, approvedMask.slabPx,
|
||||
);
|
||||
let pngBlob: Blob;
|
||||
let belowFloor = false;
|
||||
try {
|
||||
const r = await encodeInventory({ bitmap, mask: approvedMask, source });
|
||||
pngBlob = r.blob;
|
||||
belowFloor = r.sourceBelowFloor;
|
||||
} catch {
|
||||
// CAPTURE.md: inventory is image/png even when encode is unavailable.
|
||||
pngBlob = new Blob([], { type: 'image/png' });
|
||||
}
|
||||
bitmap.close();
|
||||
if (pngUrl) URL.revokeObjectURL(pngUrl);
|
||||
pngUrl = URL.createObjectURL(pngBlob);
|
||||
|
||||
// #63: second copy of the calibration inventory PNG with dimension overlays.
|
||||
// Keep clean inventoryPng untouched; never stash overlay into batchApply[cal].
|
||||
let overlayBlob: Blob;
|
||||
try {
|
||||
overlayBlob = await encodeOverlay({
|
||||
inventoryPng: pngBlob,
|
||||
bitset: approvedMask.bitset,
|
||||
widthPx: source.widthPx,
|
||||
heightPx: source.heightPx,
|
||||
bbox: axis.bbox,
|
||||
scale: base.scale,
|
||||
lengthIn: eighthsToIn(lengthEighths),
|
||||
lengthLabel: fmtEighths(lengthEighths),
|
||||
slabBounds: approvedMask.slabBounds,
|
||||
source,
|
||||
});
|
||||
} catch {
|
||||
// Deterministic tests may inject a non-decodable inventory blob; still
|
||||
// return a distinct image/png so callers never confuse it with clean.
|
||||
overlayBlob = new Blob(['overlay'], { type: 'image/png' });
|
||||
}
|
||||
const results: Measures = {
|
||||
...base,
|
||||
inventoryPng: pngBlob,
|
||||
overlayPng: overlayBlob,
|
||||
sourceBelowFloor: belowFloor,
|
||||
};
|
||||
const params = approvedMask.params;
|
||||
const calIndex = calibrationIndex != null && calibrationIndex >= 0
|
||||
? calibrationIndex
|
||||
: 0;
|
||||
const batch = batchPhotos.length ? batchPhotos : [source];
|
||||
const batchApply: BatchPhotoResult[] = batch.map((_, index) => (index === calIndex ? null : {
|
||||
status: 'error',
|
||||
message: 'Batch photo was not processed',
|
||||
}));
|
||||
|
||||
// Process serially so each worker owns exactly one sibling photo and a
|
||||
// failing decode/mask/encode cannot prevent later siblings from running.
|
||||
for (let index = 0; index < batch.length; index++) {
|
||||
if (index === calIndex) continue;
|
||||
const photo = batch[index];
|
||||
try {
|
||||
const derived = await rederiveMaskDetailed(photo, params, {
|
||||
slabPx: 0,
|
||||
bbox: EMPTY_BBOX,
|
||||
slabBounds: EMPTY_ABOX,
|
||||
});
|
||||
if (derived.mask.slabPx === 0) {
|
||||
throw new Error('empty mask: no slab pixels detected');
|
||||
}
|
||||
const siblingSource: Source = {
|
||||
...photo,
|
||||
widthPx: derived.widthPx,
|
||||
heightPx: derived.heightPx,
|
||||
};
|
||||
const siblingBitmap = await decodeOrientedBitmap(photo.blob);
|
||||
let encoded: { blob: Blob; sourceBelowFloor: boolean };
|
||||
try {
|
||||
encoded = await encodeInventory({ bitmap: siblingBitmap, mask: derived.mask, source: siblingSource });
|
||||
} finally {
|
||||
siblingBitmap.close();
|
||||
}
|
||||
if (encoded.sourceBelowFloor) {
|
||||
throw new Error('PNG size floor: shorter side is below 800 px');
|
||||
}
|
||||
batchApply[index] = { status: 'ok', inventoryPng: encoded.blob };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'unable to process photo';
|
||||
batchApply[index] = { status: 'error', message };
|
||||
}
|
||||
}
|
||||
|
||||
set({ ...state, results, batchApply });
|
||||
void persist();
|
||||
},
|
||||
|
||||
back() {
|
||||
if (state.k === 'pickCalibration') {
|
||||
calibrationIndex = null;
|
||||
set({ k: 'batch', photos: [...batchPhotos] });
|
||||
void persist();
|
||||
} else if (state.k === 'mask') {
|
||||
teardownWorker();
|
||||
calibrationIndex = null;
|
||||
set({ k: 'pickCalibration', photos: [...batchPhotos] });
|
||||
void persist();
|
||||
} else if (state.k === 'axis') {
|
||||
// back to mask keeps the last approved mask as the live overlay
|
||||
const m = state.approvedMask;
|
||||
set({ k: 'mask', source: state.source, control: m.params, overlay: m, failed: false });
|
||||
} else if (state.k === 'measure') {
|
||||
set({ k: 'axis', source: state.source, approvedMask: state.approvedMask, axis: { bbox: state.axis.bbox } });
|
||||
}
|
||||
},
|
||||
|
||||
getInventoryUrl() {
|
||||
return pngUrl;
|
||||
},
|
||||
|
||||
dispose() {
|
||||
teardownWorker();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Display helper: format eighths as inches with fractions.
|
||||
export function fmtEighths(e: Eighths): string {
|
||||
const whole = Math.floor(eighthsToIn(e));
|
||||
const rem = e - whole * 8;
|
||||
if (rem === 0) return `${whole}"`;
|
||||
const frac: Record<number, string> = { 1: '1/8', 2: '1/4', 3: '3/8', 4: '1/2', 5: '5/8', 6: '3/4', 7: '7/8' };
|
||||
const part = frac[rem] ?? `${rem}/8`;
|
||||
return whole > 0 ? `${whole} ${part}"` : `${part}"`;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Shared decode for capture photos so PhotoStage, mask worker, inventory, and
|
||||
* calculate all share one EXIF-oriented pixel space.
|
||||
*
|
||||
* Matched-set / DJI JPEGs often carry EXIF Orientation 8 (stored landscape,
|
||||
* display portrait). `new Image()` and bare `createImageBitmap(blob)` can
|
||||
* disagree across browsers → pink axis arrow space ≠ mask/overlay bitset space.
|
||||
*
|
||||
* Contract: always request `imageOrientation: 'from-image'`. If the runtime
|
||||
* rejects that option (older engines), fall back to bare `createImageBitmap`;
|
||||
* engines that already apply EXIF by default still match Image/canvas size.
|
||||
* Engines that never apply EXIF may still diverge after fallback — document
|
||||
* that path rather than inventing a software rotate.
|
||||
*/
|
||||
export const ORIENTED_BITMAP_OPTIONS: ImageBitmapOptions = {
|
||||
imageOrientation: 'from-image',
|
||||
};
|
||||
|
||||
export async function decodeOrientedBitmap(blob: Blob): Promise<ImageBitmap> {
|
||||
try {
|
||||
return await createImageBitmap(blob, ORIENTED_BITMAP_OPTIONS);
|
||||
} catch (first) {
|
||||
try {
|
||||
return await createImageBitmap(blob);
|
||||
} catch {
|
||||
throw first;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { get, set, del } from 'idb-keyval';
|
||||
import type { Draft } from '../capture/capture.types';
|
||||
|
||||
const KEY = 'slabuploader-draft';
|
||||
|
||||
export async function loadDraft(): Promise<Draft | null> {
|
||||
try {
|
||||
const d = await get<Draft>(KEY);
|
||||
return d && d.version === 1 ? d : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveDraft(d: Draft): Promise<void> {
|
||||
await set(KEY, d);
|
||||
}
|
||||
|
||||
export async function clearDraft(): Promise<void> {
|
||||
try {
|
||||
await del(KEY);
|
||||
} catch {
|
||||
// idb unavailable: draft persistence is best-effort, app state is not
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { minAreaRect, orientedRect, maskSpanAlong } from './rect.ts';
|
||||
import { measure } from '../measure/measure.ts';
|
||||
|
||||
// 100×20 horizontal slab
|
||||
const W = 100, H = 20;
|
||||
const bitset = new Uint8Array(W * H);
|
||||
for (let x = 0; x < W; x++) for (let y = 0; y < H; y++) bitset[y * W + x] = 1;
|
||||
|
||||
test('maskSpanAlong of a 100×20 slab: X ≈ 99–100, Y ≈ 19–20', () => {
|
||||
const sx = maskSpanAlong(bitset, W, H, 1, 0);
|
||||
const sy = maskSpanAlong(bitset, W, H, 0, 1);
|
||||
assert.ok(sx >= 99 && sx <= 100, `spanX ${sx}`);
|
||||
assert.ok(sy >= 19 && sy <= 20, `spanY ${sy}`);
|
||||
});
|
||||
|
||||
test('orientedRect changes angleDeg and preserves longSidePx', () => {
|
||||
const prev = minAreaRect(bitset, W, H);
|
||||
assert.ok(prev, 'minAreaRect returned a box');
|
||||
const rotated = orientedRect(prev, 45);
|
||||
assert.ok(Math.abs(rotated.angleDeg - 45) < 1e-9);
|
||||
assert.equal(rotated.longSidePx, prev.longSidePx);
|
||||
// The long side (angleDeg 0 → +x) must be preserved by the rotation.
|
||||
const longOf = (c) => Math.hypot(c[3][0] - c[0][0], c[3][1] - c[0][1]);
|
||||
assert.ok(Math.abs(longOf(rotated.corners) - longOf(prev.corners)) < 1e-9);
|
||||
assert.ok(Math.abs(longOf(prev.corners) - prev.longSidePx) < 1e-9);
|
||||
// angle normalization to [0, 180)
|
||||
assert.ok(orientedRect(prev, 190).angleDeg >= 0 && orientedRect(prev, 190).angleDeg < 180);
|
||||
});
|
||||
|
||||
test('measure scale uses mask span along the axis, not longSidePx', () => {
|
||||
// Thin slab (20 long, 100 wide): minAreaRect's long side (angleDeg 90) is
|
||||
// the 100-px dimension along +y. Rotate the axis to angleDeg 0 (+x), which
|
||||
// crosses only the 20-px slab width — span 19, not longSidePx 99.
|
||||
const TW = 20, TH = 100;
|
||||
const thin = new Uint8Array(TW * TH).fill(1);
|
||||
const thinBox = minAreaRect(thin, TW, TH);
|
||||
assert.ok(thinBox && thinBox.longSidePx >= 99, `longSide ${thinBox?.longSidePx}`);
|
||||
const rotated = orientedRect(thinBox, 0);
|
||||
const lengthEighths = 24; // 3 in
|
||||
const m = measure(thin, TW, TH, rotated, lengthEighths, 8, TW * TH);
|
||||
// Scale = span along the axis / length. Span ≈ 19 → scale ≈ 6.3 px/in,
|
||||
// far from the old longSidePx/3 ≈ 33.
|
||||
const ex = rotated.corners[0][0] - rotated.corners[3][0];
|
||||
const ey = rotated.corners[0][1] - rotated.corners[3][1];
|
||||
const elen = Math.hypot(ex, ey);
|
||||
const span = maskSpanAlong(thin, TW, TH, ex / elen, ey / elen);
|
||||
assert.ok(Math.abs(m.scale - span / (lengthEighths / 8)) < 1e-9);
|
||||
assert.ok(m.scale < 10, `scale ${m.scale} should be span-based, not ${thinBox.longSidePx / 3}`);
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { ABox, BBox } from '../capture/capture.types';
|
||||
|
||||
export function slabBounds(bitset: Uint8Array, w: number, h: number): ABox {
|
||||
let minX = w, minY = h, maxX = -1, maxY = -1;
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (bitset[row + x]) {
|
||||
if (x < minX) minX = x;
|
||||
if (x > maxX) maxX = x;
|
||||
if (y < minY) minY = y;
|
||||
if (y > maxY) maxY = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (maxX < 0) return { x: 0, y: 0, w: 0, h: 0 };
|
||||
return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
|
||||
}
|
||||
|
||||
// Convex hull (Andrew's monotone chain). Points are [x, y].
|
||||
export function convexHull(pts: [number, number][]): [number, number][] {
|
||||
const p = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
||||
if (p.length < 3) return p;
|
||||
const cross = (o: [number, number], a: [number, number], b: [number, number]) =>
|
||||
(a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
|
||||
const lower: [number, number][] = [];
|
||||
for (const pt of p) {
|
||||
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], pt) <= 0) lower.pop();
|
||||
lower.push(pt);
|
||||
}
|
||||
const upper: [number, number][] = [];
|
||||
for (let i = p.length - 1; i >= 0; i--) {
|
||||
const pt = p[i];
|
||||
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], pt) <= 0) upper.pop();
|
||||
upper.push(pt);
|
||||
}
|
||||
lower.pop();
|
||||
upper.pop();
|
||||
return lower.concat(upper);
|
||||
}
|
||||
|
||||
// Rotating calipers: true minimum-area bounding rectangle of the mask.
|
||||
export function minAreaRect(bitset: Uint8Array, w: number, h: number): BBox | null {
|
||||
const pts: [number, number][] = [];
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) if (bitset[row + x]) pts.push([x, y]);
|
||||
}
|
||||
if (pts.length < 2) return null;
|
||||
const hull = convexHull(pts);
|
||||
|
||||
let best = { area: Infinity, cx: 0, cy: 0, ux: 1, uy: 0, hw: 0, hh: 0 };
|
||||
const n = hull.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const j = (i + 1) % n;
|
||||
const ex = hull[j][0] - hull[i][0];
|
||||
const ey = hull[j][1] - hull[i][1];
|
||||
const len = Math.hypot(ex, ey);
|
||||
if (len === 0) continue;
|
||||
const ux = ex / len, uy = ey / len;
|
||||
const vx = -uy, vy = ux;
|
||||
let minU = Infinity, maxU = -Infinity, minV = Infinity, maxV = -Infinity;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const dx = hull[k][0] - hull[i][0];
|
||||
const dy = hull[k][1] - hull[i][1];
|
||||
const u = dx * ux + dy * uy;
|
||||
const v = dx * vx + dy * vy;
|
||||
if (u < minU) minU = u;
|
||||
if (u > maxU) maxU = u;
|
||||
if (v < minV) minV = v;
|
||||
if (v > maxV) maxV = v;
|
||||
}
|
||||
const rw = maxU - minU;
|
||||
const rh = maxV - minV;
|
||||
const area = rw * rh;
|
||||
if (area < best.area) {
|
||||
best = { area, cx: hull[i][0] + (minU + maxU) / 2 * ux + (minV + maxV) / 2 * vx, cy: hull[i][1] + (minU + maxU) / 2 * uy + (minV + maxV) / 2 * vy, ux, uy, hw: rw / 2, hh: rh / 2 };
|
||||
}
|
||||
}
|
||||
|
||||
// long-side direction: the edge with the larger extent
|
||||
const lu = best.hw >= best.hh ? best.ux : -best.uy;
|
||||
const lv = best.hw >= best.hh ? best.uy : best.ux;
|
||||
const su = best.hw >= best.hh ? -best.uy : best.ux;
|
||||
const sv = best.hw >= best.hh ? -best.ux : -best.uy;
|
||||
const halfL = best.hw >= best.hh ? best.hw : best.hh;
|
||||
const halfS = best.hw >= best.hh ? best.hh : best.hw;
|
||||
const corners: [number, number][] = [];
|
||||
for (const [a, b] of [[1, 1], [1, -1], [-1, -1], [-1, 1]] as const) {
|
||||
corners.push([best.cx + a * halfL * lu + b * halfS * su, best.cy + a * halfL * lv + b * halfS * sv]);
|
||||
}
|
||||
const angleDeg = ((Math.atan2(lv, lu) * 180) / Math.PI + 180) % 180;
|
||||
return { corners, longSidePx: halfL * 2, angleDeg };
|
||||
}
|
||||
|
||||
// Rotate the long side to a new angle, keeping center and half-extents.
|
||||
// Corners are rebuilt in minAreaRect order so corners[3] → corners[0] stays the
|
||||
// long side (the axis arrow direction).
|
||||
export function orientedRect(prev: BBox, angleDeg: number): BBox {
|
||||
const a = ((angleDeg % 180) + 180) % 180;
|
||||
const halfL = prev.longSidePx / 2;
|
||||
const halfS = Math.hypot(prev.corners[0][0] - prev.corners[1][0], prev.corners[0][1] - prev.corners[1][1]) / 2;
|
||||
// corners[i] is a corner point: average of all four = center
|
||||
const cx = (prev.corners[0][0] + prev.corners[1][0] + prev.corners[2][0] + prev.corners[3][0]) / 4;
|
||||
const cy = (prev.corners[0][1] + prev.corners[1][1] + prev.corners[2][1] + prev.corners[3][1]) / 4;
|
||||
const r = (a * Math.PI) / 180;
|
||||
const lu = Math.cos(r), lv = Math.sin(r);
|
||||
const su = -lv, sv = lu;
|
||||
const corners: [number, number][] = [];
|
||||
for (const [aSign, bSign] of [[1, 1], [1, -1], [-1, -1], [-1, 1]] as const) {
|
||||
corners.push([cx + aSign * halfL * lu + bSign * halfS * su, cy + aSign * halfL * lv + bSign * halfS * sv]);
|
||||
}
|
||||
return { corners, longSidePx: prev.longSidePx, angleDeg: a };
|
||||
}
|
||||
|
||||
// Project every slab pixel onto the unit vector (ux, uy); return max − min
|
||||
// extent in px. 0 when the mask is empty.
|
||||
export function maskSpanAlong(bitset: Uint8Array, w: number, h: number, ux: number, uy: number): number {
|
||||
let min = Infinity, max = -Infinity;
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (!bitset[row + x]) continue;
|
||||
const p = x * ux + y * uy;
|
||||
if (p < min) min = p;
|
||||
if (p > max) max = p;
|
||||
}
|
||||
}
|
||||
return max < min ? 0 : max - min;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import App from './App.svelte';
|
||||
|
||||
const root = document.querySelector('#app');
|
||||
if (root) new App({ target: root });
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { blackKeep, greenKeep } from './sheetKeep.ts';
|
||||
|
||||
// --- Black sheet sensitivity (#74) ---
|
||||
|
||||
test('blackKeep: s=0 keeps dark live-edge wood (lum ~25–50), removes near-black sheet (#74)', () => {
|
||||
// Near-black sheet (lum ≈ 5)
|
||||
assert.equal(blackKeep(5, 5, 5, 0), false, 'near-black sheet removed at s=0');
|
||||
assert.equal(blackKeep(0, 0, 0, 0), false, 'pure black sheet removed at s=0');
|
||||
// Dark wood / bark / live edge
|
||||
assert.equal(blackKeep(25, 22, 18, 0), true, 'lum~22 dark wood kept at s=0');
|
||||
assert.equal(blackKeep(40, 35, 30, 0), true, 'lum~35 dark wood kept at s=0');
|
||||
assert.equal(blackKeep(50, 45, 40, 0), true, 'lum~46 wood kept at s=0');
|
||||
// Mid wood always kept
|
||||
assert.equal(blackKeep(120, 90, 60, 0), true, 'mid wood kept at s=0');
|
||||
});
|
||||
|
||||
test('blackKeep: s=100 removes more than s=0; curve monotonic (#74)', () => {
|
||||
// Dark-ish pixel that sits between floors: sheet at high s, wood at low s
|
||||
const darkish = { r: 80, g: 70, b: 60 }; // lum ≈ 72
|
||||
assert.equal(blackKeep(darkish.r, darkish.g, darkish.b, 0), true, 'lum~72 kept at s=0');
|
||||
assert.equal(blackKeep(darkish.r, darkish.g, darkish.b, 100), false, 'lum~72 sheet at s=100');
|
||||
|
||||
// Near-black always sheet
|
||||
assert.equal(blackKeep(2, 2, 2, 0), false);
|
||||
assert.equal(blackKeep(2, 2, 2, 100), false);
|
||||
|
||||
// Bright wood always kept
|
||||
assert.equal(blackKeep(200, 160, 100, 0), true);
|
||||
assert.equal(blackKeep(200, 160, 100, 100), true);
|
||||
|
||||
// Monotonic: once removed, stays removed as s increases
|
||||
const probe = { r: 60, g: 55, b: 50 }; // lum ≈ 56
|
||||
let prevKeep = true;
|
||||
for (const s of [0, 25, 50, 75, 100]) {
|
||||
const keep = blackKeep(probe.r, probe.g, probe.b, s);
|
||||
if (!prevKeep) assert.equal(keep, false, `once sheet at lower s, stay sheet at s=${s}`);
|
||||
prevKeep = keep;
|
||||
}
|
||||
// s=100 must remove more pixels than s=0 for this mid-dark band
|
||||
assert.equal(blackKeep(probe.r, probe.g, probe.b, 0), true);
|
||||
assert.equal(blackKeep(probe.r, probe.g, probe.b, 100), false);
|
||||
});
|
||||
|
||||
test('greenKeep: s=0 does not eat mild wood greens; s=100 widens sheet match (#74)', () => {
|
||||
// Neutral wood
|
||||
assert.equal(greenKeep(140, 110, 80, 0), true);
|
||||
assert.equal(greenKeep(140, 110, 80, 100), true);
|
||||
// Mild green cast on wood (g - max(r,b) ≈ 5) — must keep at s=0
|
||||
assert.equal(greenKeep(100, 105, 90, 0), true, 'mild green cast kept at s=0');
|
||||
// Strong sheet green
|
||||
assert.equal(greenKeep(40, 180, 50, 0), false, 'strong green sheet removed at s=0');
|
||||
assert.equal(greenKeep(40, 180, 50, 100), false);
|
||||
// Borderline: g-max ≈ 20 — may become sheet at high s
|
||||
const border = { r: 80, g: 100, b: 70 }; // delta = 20
|
||||
assert.equal(greenKeep(border.r, border.g, border.b, 0), true, 'delta20 kept at s=0');
|
||||
assert.equal(greenKeep(border.r, border.g, border.b, 100), false, 'delta20 sheet at s=100');
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Sheet-vs-slab keep predicates used by the mask worker.
|
||||
* Extracted so unit tests can cover sensitivity curves without the worker.
|
||||
*/
|
||||
|
||||
/** Keep slab pixels on a green sheet. Higher s widens the green-sheet match. */
|
||||
export function greenKeep(r: number, g: number, b: number, s: number): boolean {
|
||||
const t = Math.max(0, Math.min(100, s)) / 100;
|
||||
// s=0 removes only strongly green sheet; increasing sensitivity widens the match.
|
||||
const isSheet = g - Math.max(r, b) > 45 - 35 * t;
|
||||
return !isSheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep slab pixels on a black sheet.
|
||||
* At s=0 only near-black sheet (very low lum) is removed so dark live-edge /
|
||||
* bark (lum ~25–50) stays. The match widens monotonically toward s=100 (#74).
|
||||
*/
|
||||
export function blackKeep(r: number, g: number, b: number, s: number): boolean {
|
||||
const t = Math.max(0, Math.min(100, s)) / 100;
|
||||
const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
// Old floor 40 ate dark wood at minimum sensitivity. Floor 10 isolates near-black.
|
||||
const isSheet = lum < 10 + 140 * t;
|
||||
return !isSheet;
|
||||
}
|
||||
|
||||
export function autoPickSheet(
|
||||
samples: { r: number; g: number; b: number }[],
|
||||
): 'green' | 'black' {
|
||||
let gr = 0, gl = 0;
|
||||
for (const p of samples) {
|
||||
if (p.g - Math.max(p.r, p.b) > 20) gr++;
|
||||
if (0.2126 * p.r + 0.7152 * p.g + 0.0722 * p.b < 70) gl++;
|
||||
}
|
||||
return gl >= gr ? 'black' : 'green';
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { minAreaRect, orientedRect } from '../geometry/rect.ts';
|
||||
import { measure } from './measure.ts';
|
||||
|
||||
// Uniform slab, 10 px/in: full W×H canvas, axis +x via minAreaRect angle 0.
|
||||
function uniform(W: number, H: number) {
|
||||
const bitset = new Uint8Array(W * H).fill(1);
|
||||
const box = orientedRect(minAreaRect(bitset, W, H)!, 0);
|
||||
return { bitset, box, slabPx: W * H };
|
||||
}
|
||||
|
||||
// Tapered slab, 10 px/in: tips under 6 in and past L−6 in are `tipPx` wide
|
||||
// (centered), the bulk is full canvas height.
|
||||
function tapered(W: number, H: number, lengthEighths: number, tipPx: number) {
|
||||
const inIn = W / 10;
|
||||
const bitset = new Uint8Array(W * H);
|
||||
const half = tipPx / 2;
|
||||
for (let x = 0; x < W; x++) {
|
||||
const p = x / 10;
|
||||
const w = p < 6 || p > inIn - 6 ? tipPx : H;
|
||||
for (let y = (H - w) / 2; y < (H + w) / 2; y++) bitset[y * W + x] = 1;
|
||||
}
|
||||
const box = orientedRect(minAreaRect(bitset, W, H)!, 0);
|
||||
return { bitset, box, slabPx: bitset.reduce((a, c) => a + c, 0), lengthEighths };
|
||||
}
|
||||
|
||||
test('tapered 48in slab: min/max reflect the bulk, tips excluded', () => {
|
||||
const { bitset, box, slabPx, lengthEighths } = tapered(480, 100, 384, 20); // tips 2in, bulk 10in
|
||||
const m = measure(bitset, 480, 100, box, lengthEighths, 8, slabPx);
|
||||
assert.equal(m.widths.every6In.length, 7, `stations ${m.widths.every6In.length} (6..42in)`);
|
||||
for (const e of m.widths.every6In) {
|
||||
assert.ok(e >= 76 && e <= 84, `station ${e / 8}in must be bulk (~10in)`);
|
||||
}
|
||||
assert.ok(m.widths.min >= 76 && m.widths.min <= 84, `min ${m.widths.min / 8}in`);
|
||||
assert.ok(m.widths.max >= 76 && m.widths.max <= 84, `max ${m.widths.max / 8}in`);
|
||||
});
|
||||
|
||||
test('uniform slab: interior stations keep the full width', () => {
|
||||
const { bitset, box, slabPx } = uniform(480, 100);
|
||||
const m = measure(bitset, 480, 100, box, 384, 8, slabPx);
|
||||
assert.equal(m.widths.every6In.length, 7);
|
||||
for (const e of m.widths.every6In) {
|
||||
assert.ok(e >= 72 && e <= 104, `station ${e / 8}in`);
|
||||
}
|
||||
});
|
||||
|
||||
test('short slab L=12in: no interior stations, widths are empty/zero', () => {
|
||||
const { bitset, box, slabPx } = uniform(120, 100);
|
||||
const m = measure(bitset, 120, 100, box, 96, 8, slabPx);
|
||||
assert.deepEqual(m.widths, { min: 0, max: 0, avg: 0, every6In: [] });
|
||||
});
|
||||
|
||||
test('short slab L=10in: no interior stations, widths are empty/zero', () => {
|
||||
const { bitset, box, slabPx } = uniform(100, 100);
|
||||
const m = measure(bitset, 100, 100, box, 80, 8, slabPx);
|
||||
assert.deepEqual(m.widths, { min: 0, max: 0, avg: 0, every6In: [] });
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { BBox, Eighths, Measures, Widths } from '../capture/capture.types';
|
||||
import { maskSpanAlong } from '../geometry/rect';
|
||||
|
||||
// Display / direction: corners[3] → corners[0] is the long side.
|
||||
export function axisEndpoints(bbox: BBox): { start: [number, number]; end: [number, number] } {
|
||||
return { start: bbox.corners[3], end: bbox.corners[0] };
|
||||
}
|
||||
|
||||
// Wood end→end along the approved direction: project the mask onto the axis
|
||||
// unit vector and return the segment on the bbox center line covering that span.
|
||||
function maskAxisSegment(
|
||||
bitset: Uint8Array, w: number, h: number, bbox: BBox,
|
||||
): { start: [number, number]; end: [number, number]; span: number; ux: number; uy: number } {
|
||||
const { start: a, end: b } = axisEndpoints(bbox);
|
||||
const ex = b[0] - a[0];
|
||||
const ey = b[1] - a[1];
|
||||
const elen = Math.hypot(ex, ey) || 1;
|
||||
const ux = ex / elen, uy = ey / elen;
|
||||
const cx = (bbox.corners[0][0] + bbox.corners[1][0] + bbox.corners[2][0] + bbox.corners[3][0]) / 4;
|
||||
const cy = (bbox.corners[0][1] + bbox.corners[1][1] + bbox.corners[2][1] + bbox.corners[3][1]) / 4;
|
||||
const cProj = cx * ux + cy * uy;
|
||||
let minP = Infinity, maxP = -Infinity;
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (!bitset[row + x]) continue;
|
||||
const p = x * ux + y * uy;
|
||||
if (p < minP) minP = p;
|
||||
if (p > maxP) maxP = p;
|
||||
}
|
||||
}
|
||||
if (maxP < minP) return { start: a, end: b, span: 0, ux, uy };
|
||||
return {
|
||||
start: [cx + ux * (minP - cProj), cy + uy * (minP - cProj)],
|
||||
end: [cx + ux * (maxP - cProj), cy + uy * (maxP - cProj)],
|
||||
span: maxP - minP,
|
||||
ux,
|
||||
uy,
|
||||
};
|
||||
}
|
||||
|
||||
// Interior stations only (6, 12, … ≤ L−6). Tips dominate min/max on tapered
|
||||
// boards, so the first and last 6 in are excluded. Each sample is a line
|
||||
// probe perpendicular to the axis; width = max run of slab px across it.
|
||||
function sampleWidths(
|
||||
bitset: Uint8Array, w: number, h: number,
|
||||
start: [number, number], ux: number, uy: number,
|
||||
scale: number, lengthIn: number,
|
||||
): Eighths[] {
|
||||
const px = -uy, py = ux;
|
||||
const stepPx = 6 * scale;
|
||||
const lastPx = lengthIn > 12 ? Math.floor((lengthIn - 6) / 6) * 6 * scale : 0;
|
||||
const out: Eighths[] = [];
|
||||
const half = Math.max(2, Math.round((w + h) / 4));
|
||||
for (let t = stepPx; t <= lastPx; t += stepPx) {
|
||||
const ox = start[0] + ux * t;
|
||||
const oy = start[1] + uy * t;
|
||||
let minP = Infinity, maxP = -Infinity;
|
||||
for (let p = -half; p <= half; p++) {
|
||||
const x = Math.round(ox + px * p);
|
||||
const y = Math.round(oy + py * p);
|
||||
if (x < 0 || y < 0 || x >= w || y >= h) continue;
|
||||
if (bitset[y * w + x]) {
|
||||
if (p < minP) minP = p;
|
||||
if (p > maxP) maxP = p;
|
||||
}
|
||||
}
|
||||
if (maxP < minP) continue;
|
||||
out.push(Math.max(0, Math.round(((maxP - minP + 1) / scale) * 8)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function measure(
|
||||
bitset: Uint8Array, w: number, h: number,
|
||||
bbox: BBox,
|
||||
lengthEighths: Eighths, thicknessEighths: Eighths,
|
||||
slabPx: number,
|
||||
): Omit<Measures, 'inventoryPng'> & { sourceBelowFloor: false } {
|
||||
const lengthIn = lengthEighths / 8;
|
||||
const seg = maskAxisSegment(bitset, w, h, bbox);
|
||||
const scale = (seg.span || maskSpanAlong(bitset, w, h, seg.ux, seg.uy)) / lengthIn;
|
||||
const every6In = sampleWidths(bitset, w, h, seg.start, seg.ux, seg.uy, scale, lengthIn);
|
||||
let widths: Widths;
|
||||
if (every6In.length > 0) {
|
||||
const min = Math.min(...every6In);
|
||||
const max = Math.max(...every6In);
|
||||
const avg = Math.round(every6In.reduce((a, b) => a + b, 0) / every6In.length);
|
||||
widths = { min, max, avg, every6In };
|
||||
} else {
|
||||
widths = { min: 0, max: 0, avg: 0, every6In: [] };
|
||||
}
|
||||
const sqft = Math.round((slabPx / (scale * scale) / 144) * 100) / 100;
|
||||
const bdft = Math.round(sqft * (thicknessEighths / 8) * 100) / 100;
|
||||
return {
|
||||
lengthEighths,
|
||||
thicknessEighths,
|
||||
scale,
|
||||
widths,
|
||||
sqft,
|
||||
bdft,
|
||||
sourceBelowFloor: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { composeInventoryFrame } from './inventory.ts';
|
||||
import type { Mask, Source } from '../capture/capture.types';
|
||||
|
||||
const makePhoto = (w: number, h: number, paint: (x: number, y: number) => [number, number, number, number] = () => [255, 255, 255, 255]) => {
|
||||
const rgba = new Uint8Array(w * h * 4);
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
const [r, g, b, a] = paint(x, y);
|
||||
const i = (y * w + x) * 4;
|
||||
rgba[i] = r; rgba[i + 1] = g; rgba[i + 2] = b; rgba[i + 3] = a;
|
||||
}
|
||||
}
|
||||
return { width: w, height: h, rgba };
|
||||
};
|
||||
|
||||
const maskFor = (bitset: Uint8Array, slabBounds: Mask['slabBounds']): Pick<Mask, 'bitset' | 'slabBounds'> =>
|
||||
({ bitset, slabBounds });
|
||||
|
||||
test('alpha contract: removed pixels transparent, slab pixels keep RGB at alpha 255', () => {
|
||||
const W = 8, H = 8;
|
||||
const bitset = new Uint8Array(W * H);
|
||||
for (let y = 1; y < 5; y++) for (let x = 1; x < 5; x++) bitset[y * W + x] = 1;
|
||||
bitset[2 * W + 2] = 0;
|
||||
bitset[3 * W + 3] = 0;
|
||||
const SLAB = [200, 40, 20, 255] as const;
|
||||
const SHEET = [0, 255, 0, 255] as const;
|
||||
const src = makePhoto(W, H, (x, y) => (bitset[y * W + x] === 1 ? [...SLAB] : [...SHEET]));
|
||||
const source: Pick<Source, 'widthPx' | 'heightPx'> = { widthPx: W, heightPx: H };
|
||||
const out = composeInventoryFrame(src, maskFor(bitset, { x: 1, y: 1, w: 4, h: 4 }), source);
|
||||
|
||||
assert.equal(out.sourceBelowFloor, true);
|
||||
assert.ok(out.width < 800, 'undersized source stays small');
|
||||
|
||||
let opaque = 0;
|
||||
let transparent = 0;
|
||||
for (let i = 0; i < out.rgba.length; i += 4) {
|
||||
const a = out.rgba[i + 3];
|
||||
if (a === 0) {
|
||||
transparent++;
|
||||
assert.equal(out.rgba[i], 0);
|
||||
assert.equal(out.rgba[i + 1], 0);
|
||||
assert.equal(out.rgba[i + 2], 0);
|
||||
continue;
|
||||
}
|
||||
opaque++;
|
||||
assert.equal(a, 255);
|
||||
assert.deepEqual(
|
||||
[out.rgba[i], out.rgba[i + 1], out.rgba[i + 2]],
|
||||
[SLAB[0], SLAB[1], SLAB[2]],
|
||||
'opaque pixel must be slab RGB, never sheet green',
|
||||
);
|
||||
}
|
||||
assert.ok(opaque > 0, 'slab pixels are opaque');
|
||||
assert.ok(transparent > 0, 'frame has transparent pixels');
|
||||
});
|
||||
|
||||
test('3:4 frame at the floor: 2000×1800 slab → 800×1067', () => {
|
||||
const source: Pick<Source, 'widthPx' | 'heightPx'> = { widthPx: 2000, heightPx: 1800 };
|
||||
const bitset = new Uint8Array(source.widthPx * source.heightPx).fill(1);
|
||||
const out = composeInventoryFrame(
|
||||
makePhoto(source.widthPx, source.heightPx),
|
||||
maskFor(bitset, { x: 0, y: 0, w: 2000, h: 1800 }),
|
||||
source,
|
||||
);
|
||||
assert.equal(out.width, 800);
|
||||
assert.equal(out.height, 1067);
|
||||
assert.equal(out.sourceBelowFloor, false);
|
||||
});
|
||||
|
||||
test('mid-band: slab shorter side 1000 (between 800 and 1600) → at floor, not belowFloor', () => {
|
||||
const source: Pick<Source, 'widthPx' | 'heightPx'> = { widthPx: 1200, heightPx: 1000 };
|
||||
const bitset = new Uint8Array(source.widthPx * source.heightPx).fill(1);
|
||||
const out = composeInventoryFrame(
|
||||
makePhoto(source.widthPx, source.heightPx),
|
||||
maskFor(bitset, { x: 0, y: 0, w: 1200, h: 1000 }),
|
||||
source,
|
||||
);
|
||||
assert.equal(out.sourceBelowFloor, false);
|
||||
assert.equal(out.width, 800);
|
||||
});
|
||||
|
||||
test('90% fill: limiting dimension maps to 0.9 × frame side (#68)', () => {
|
||||
const source: Pick<Source, 'widthPx' | 'heightPx'> = { widthPx: 2200, heightPx: 2000 };
|
||||
const bitset = new Uint8Array(source.widthPx * source.heightPx).fill(1);
|
||||
const out = composeInventoryFrame(
|
||||
makePhoto(source.widthPx, source.heightPx),
|
||||
maskFor(bitset, { x: 100, y: 100, w: 2000, h: 1800 }),
|
||||
source,
|
||||
);
|
||||
let minx = out.width, maxx = -1, miny = out.height, maxy = -1;
|
||||
for (let y = 0; y < out.height; y++) {
|
||||
for (let x = 0; x < out.width; x++) {
|
||||
if (out.rgba[(y * out.width + x) * 4 + 3] !== 0) {
|
||||
if (x < minx) minx = x;
|
||||
if (x > maxx) maxx = x;
|
||||
if (y < miny) miny = y;
|
||||
if (y > maxy) maxy = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
const xs = [minx, maxx], ys = [miny, maxy];
|
||||
const wExtent = Math.max(...xs) - Math.min(...xs) + 1;
|
||||
const hExtent = Math.max(...ys) - Math.min(...ys) + 1;
|
||||
assert.ok(Math.abs(wExtent - 720) <= 2, `width extent ${wExtent} ≈ 720 (0.9×800)`);
|
||||
assert.ok(Math.abs(hExtent - 648) <= 2, `height extent ${hExtent} ≈ 648 (1800×0.36)`);
|
||||
});
|
||||
|
||||
test('belowFloor: small slab → sourceBelowFloor, outW capped at floor (no upscale)', () => {
|
||||
const source: Pick<Source, 'widthPx' | 'heightPx'> = { widthPx: 900, heightPx: 700 };
|
||||
const bitset = new Uint8Array(source.widthPx * source.heightPx).fill(1);
|
||||
const out = composeInventoryFrame(
|
||||
makePhoto(source.widthPx, source.heightPx),
|
||||
maskFor(bitset, { x: 0, y: 0, w: 900, h: 700 }),
|
||||
source,
|
||||
);
|
||||
assert.equal(out.sourceBelowFloor, true);
|
||||
assert.ok(out.width <= 800, `outW ${out.width} must not exceed the floor`);
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { Mask, Source } from '../capture/capture.types';
|
||||
|
||||
const FLOOR = 800; // shorter side, px
|
||||
const FILL = 0.9; // 90% fill at the widest and tallest points of the slab
|
||||
const ASPECT_W = 3;
|
||||
const ASPECT_H = 4;
|
||||
|
||||
type MaskPick = Pick<Mask, 'bitset' | 'slabBounds'>;
|
||||
type SourcePick = Pick<Source, 'widthPx' | 'heightPx'>;
|
||||
|
||||
export interface InventoryInput {
|
||||
bitmap: ImageBitmap;
|
||||
mask: MaskPick;
|
||||
source: SourcePick;
|
||||
}
|
||||
|
||||
export interface Frame {
|
||||
width: number;
|
||||
height: number;
|
||||
rgba: Uint8Array;
|
||||
sourceBelowFloor: boolean;
|
||||
}
|
||||
|
||||
export function composeInventoryFrame(
|
||||
src: { width: number; height: number; rgba: Uint8Array | Uint8ClampedArray },
|
||||
mask: MaskPick,
|
||||
source: SourcePick,
|
||||
): Frame {
|
||||
const b = mask.slabBounds;
|
||||
const x0 = Math.max(0, Math.round(b.x));
|
||||
const y0 = Math.max(0, Math.round(b.y));
|
||||
const x1 = Math.min(source.widthPx, x0 + Math.max(1, Math.round(b.w)));
|
||||
const y1 = Math.min(source.heightPx, y0 + Math.max(1, Math.round(b.h)));
|
||||
const sw = x1 - x0;
|
||||
const sh = y1 - y0;
|
||||
const belowFloor = Math.min(sw, sh) < FLOOR;
|
||||
const outW = belowFloor ? Math.max(1, Math.min(sw, FLOOR)) : FLOOR;
|
||||
const outH = Math.round((outW * ASPECT_H) / ASPECT_W);
|
||||
const scale = Math.min((outW * FILL) / Math.max(sw, 1), (outH * FILL) / Math.max(sh, 1));
|
||||
const dw = sw * scale;
|
||||
const dh = sh * scale;
|
||||
const ox = (outW - dw) / 2;
|
||||
const oy = (outH - dh) / 2;
|
||||
const rgba = new Uint8Array(outW * outH * 4);
|
||||
const xEnd = ox + dw;
|
||||
const yEnd = oy + dh;
|
||||
for (let y = 0; y < outH; y++) {
|
||||
for (let x = 0; x < outW; x++) {
|
||||
if (x + 0.5 < ox || x + 0.5 >= xEnd || y + 0.5 < oy || y + 0.5 >= yEnd) continue;
|
||||
const sx = Math.floor(x0 + (x + 0.5 - ox) / scale);
|
||||
const sy = Math.floor(y0 + (y + 0.5 - oy) / scale);
|
||||
if (sx < 0 || sy < 0 || sx >= source.widthPx || sy >= source.heightPx) continue;
|
||||
if (mask.bitset[sy * source.widthPx + sx] !== 1) continue;
|
||||
const si = (sy * source.widthPx + sx) * 4;
|
||||
const di = (y * outW + x) * 4;
|
||||
rgba[di] = src.rgba[si];
|
||||
rgba[di + 1] = src.rgba[si + 1];
|
||||
rgba[di + 2] = src.rgba[si + 2];
|
||||
rgba[di + 3] = 255;
|
||||
}
|
||||
}
|
||||
return { width: outW, height: outH, rgba, sourceBelowFloor: belowFloor };
|
||||
}
|
||||
|
||||
export async function encodeInventoryPng(
|
||||
input: InventoryInput,
|
||||
): Promise<{ blob: Blob; sourceBelowFloor: boolean }> {
|
||||
const { bitmap, mask, source } = input;
|
||||
const srcCanvas = new OffscreenCanvas(source.widthPx, source.heightPx);
|
||||
const srcCtx = srcCanvas.getContext('2d')!;
|
||||
srcCtx.drawImage(bitmap, 0, 0);
|
||||
const img = srcCtx.getImageData(0, 0, source.widthPx, source.heightPx);
|
||||
const frame = composeInventoryFrame(
|
||||
{ width: source.widthPx, height: source.heightPx, rgba: img.data },
|
||||
mask,
|
||||
source,
|
||||
);
|
||||
const out = new OffscreenCanvas(frame.width, frame.height);
|
||||
const ctx = out.getContext('2d')!;
|
||||
ctx.putImageData(new ImageData(new Uint8ClampedArray(frame.rgba), frame.width, frame.height), 0, 0);
|
||||
const blob = await out.convertToBlob({ type: 'image/png' });
|
||||
return { blob, sourceBelowFloor: frame.sourceBelowFloor };
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
import type { BBox } from '../capture/capture.types';
|
||||
import { axisEndpoints } from '../measure/measure';
|
||||
|
||||
/** Width overlay stations: 6, 18, 30, … while ≤ L − 6 (tip-exclusive). */
|
||||
export function overlayWidthStations(lengthIn: number): number[] {
|
||||
if (!(lengthIn > 6)) return [];
|
||||
const last = lengthIn - 6;
|
||||
const out: number[] = [];
|
||||
for (let s = 6; s <= last + 1e-9; s += 12) out.push(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* EXIF-oriented photo bottom = larger canvas y. Pick which end of the approved
|
||||
* length-axis span is bottom; return unit from bottom → top along that span.
|
||||
*/
|
||||
export function pickBottomTowardTop(
|
||||
start: [number, number],
|
||||
end: [number, number],
|
||||
): {
|
||||
bottom: [number, number];
|
||||
top: [number, number];
|
||||
ux: number;
|
||||
uy: number;
|
||||
} {
|
||||
// Larger y is closer to the bottom edge of the oriented photo.
|
||||
// Tie-break (horizontal axis): prefer larger x for a stable choice.
|
||||
const startIsBottom =
|
||||
start[1] > end[1] || (start[1] === end[1] && start[0] >= end[0]);
|
||||
const bottom = startIsBottom ? start : end;
|
||||
const top = startIsBottom ? end : start;
|
||||
const dx = top[0] - bottom[0];
|
||||
const dy = top[1] - bottom[1];
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
return { bottom, top, ux: dx / len, uy: dy / len };
|
||||
}
|
||||
|
||||
/** Screen-space right of travel (canvas y↓): (ux,uy) → (−uy, ux). */
|
||||
export function axisRightUnit(ux: number, uy: number): [number, number] {
|
||||
return [-uy, ux];
|
||||
}
|
||||
|
||||
export interface OverlayWidthMark {
|
||||
stationIn: number;
|
||||
center: [number, number];
|
||||
left: [number, number];
|
||||
right: [number, number];
|
||||
/** Axis-left of the slab, outside the wood edge (opposite of length dim). */
|
||||
labelAt: [number, number];
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface OverlayLengthMark {
|
||||
a: [number, number];
|
||||
b: [number, number];
|
||||
labelAt: [number, number];
|
||||
label: string;
|
||||
/** True when the line sits outside the slab on the axis-right side. */
|
||||
outside: boolean;
|
||||
}
|
||||
|
||||
export interface OverlayPlan {
|
||||
stroke: '#000000';
|
||||
fontPx: number;
|
||||
length: OverlayLengthMark;
|
||||
widths: OverlayWidthMark[];
|
||||
}
|
||||
|
||||
export interface OverlayPlanInput {
|
||||
bitset: Uint8Array;
|
||||
widthPx: number;
|
||||
heightPx: number;
|
||||
bbox: BBox;
|
||||
scale: number; // px per inch
|
||||
lengthIn: number;
|
||||
lengthLabel: string;
|
||||
/** Map source px → inventory PNG px (identity OK for unit tests). */
|
||||
mapToInventory: (x: number, y: number) => [number, number];
|
||||
/** Inventory PNG size — used to clamp labels inside the canvas (#71). */
|
||||
inventoryW?: number;
|
||||
inventoryH?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Min across-width as a fraction of max bin width for an axial bin to count as a tip.
|
||||
* #71 used 0.32 (excluded fringe); #73 lowers to ~0.15 so tapered live-edge tips remain.
|
||||
*/
|
||||
export const BODY_WIDTH_FRAC = 0.15;
|
||||
|
||||
/**
|
||||
* Axial tip stations from across-width profile (#71/#73).
|
||||
* Thin fringe whiskers past the visible body survive 0.2%/99.8% percentiles;
|
||||
* require each axial bin to have meaningful across-width before it counts as a tip.
|
||||
*/
|
||||
function widthAwareAxialRange(
|
||||
bitset: Uint8Array,
|
||||
w: number,
|
||||
h: number,
|
||||
ux: number,
|
||||
uy: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
): { minP: number; maxP: number } | null {
|
||||
const rx = -uy;
|
||||
const ry = ux;
|
||||
const binMin = new Map<number, number>();
|
||||
const binMax = new Map<number, number>();
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (!bitset[row + x]) continue;
|
||||
const along = x * ux + y * uy;
|
||||
const across = (x - cx) * rx + (y - cy) * ry;
|
||||
const bin = Math.round(along);
|
||||
const prevMin = binMin.get(bin);
|
||||
if (prevMin === undefined || across < prevMin) binMin.set(bin, across);
|
||||
const prevMax = binMax.get(bin);
|
||||
if (prevMax === undefined || across > prevMax) binMax.set(bin, across);
|
||||
}
|
||||
}
|
||||
if (binMin.size === 0) return null;
|
||||
let maxWidth = 0;
|
||||
const widths: { bin: number; width: number }[] = [];
|
||||
for (const [bin, minA] of binMin) {
|
||||
const maxA = binMax.get(bin)!;
|
||||
const width = maxA - minA + 1;
|
||||
widths.push({ bin, width });
|
||||
if (width > maxWidth) maxWidth = width;
|
||||
}
|
||||
// Body threshold: exclude ~10% fringe whiskers; keep 15–25% live-edge tapers (#73).
|
||||
const thresh = Math.max(4, maxWidth * BODY_WIDTH_FRAC);
|
||||
widths.sort((a, b) => a.bin - b.bin);
|
||||
let tipLo = widths[0].bin;
|
||||
let tipHi = widths[widths.length - 1].bin;
|
||||
for (const { bin, width } of widths) {
|
||||
if (width >= thresh) {
|
||||
tipLo = bin;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (let i = widths.length - 1; i >= 0; i--) {
|
||||
if (widths[i].width >= thresh) {
|
||||
tipHi = widths[i].bin;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { minP: tipLo, maxP: tipHi };
|
||||
}
|
||||
|
||||
function maskAxisSegment(
|
||||
bitset: Uint8Array,
|
||||
w: number,
|
||||
h: number,
|
||||
bbox: BBox,
|
||||
): {
|
||||
start: [number, number];
|
||||
end: [number, number];
|
||||
/** Actual mask pixels nearest centerline at tip stations. */
|
||||
tipStart: [number, number];
|
||||
tipEnd: [number, number];
|
||||
ux: number;
|
||||
uy: number;
|
||||
span: number;
|
||||
} {
|
||||
const { start: a, end: b } = axisEndpoints(bbox);
|
||||
const ex = b[0] - a[0];
|
||||
const ey = b[1] - a[1];
|
||||
const elen = Math.hypot(ex, ey) || 1;
|
||||
const ux = ex / elen;
|
||||
const uy = ey / elen;
|
||||
const cx = (bbox.corners[0][0] + bbox.corners[1][0] + bbox.corners[2][0] + bbox.corners[3][0]) / 4;
|
||||
const cy = (bbox.corners[0][1] + bbox.corners[1][1] + bbox.corners[2][1] + bbox.corners[3][1]) / 4;
|
||||
const cProj = cx * ux + cy * uy;
|
||||
// Width-aware tips (#71). Fall back to robust percentiles if profile empty.
|
||||
const aware = widthAwareAxialRange(bitset, w, h, ux, uy, cx, cy);
|
||||
let minP: number;
|
||||
let maxP: number;
|
||||
if (aware) {
|
||||
minP = aware.minP;
|
||||
maxP = aware.maxP;
|
||||
} else {
|
||||
const projs: number[] = [];
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (!bitset[row + x]) continue;
|
||||
projs.push(x * ux + y * uy);
|
||||
}
|
||||
}
|
||||
if (projs.length === 0) return { start: a, end: b, tipStart: a, tipEnd: b, ux, uy, span: 0 };
|
||||
projs.sort((p, q) => p - q);
|
||||
const lo = Math.min(Math.floor(projs.length * 0.002), projs.length - 1);
|
||||
const hi = Math.max(Math.floor(projs.length * 0.998), lo);
|
||||
minP = projs[lo];
|
||||
maxP = projs[hi];
|
||||
}
|
||||
// Tip pixel at each station: closest to the axis centerline
|
||||
let tipStart: [number, number] = a;
|
||||
let tipEnd: [number, number] = b;
|
||||
let bestStart = Infinity;
|
||||
let bestEnd = Infinity;
|
||||
const stationTol = Math.max(1.5, (maxP - minP) * 0.001);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (!bitset[row + x]) continue;
|
||||
const p = x * ux + y * uy;
|
||||
const across = Math.abs((x - cx) * -uy + (y - cy) * ux);
|
||||
if (Math.abs(p - minP) <= stationTol && across < bestStart) {
|
||||
bestStart = across;
|
||||
tipStart = [x, y];
|
||||
}
|
||||
if (Math.abs(p - maxP) <= stationTol && across < bestEnd) {
|
||||
bestEnd = across;
|
||||
tipEnd = [x, y];
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
start: [cx + ux * (minP - cProj), cy + uy * (minP - cProj)],
|
||||
end: [cx + ux * (maxP - cProj), cy + uy * (maxP - cProj)],
|
||||
tipStart,
|
||||
tipEnd,
|
||||
ux,
|
||||
uy,
|
||||
span: maxP - minP,
|
||||
};
|
||||
}
|
||||
|
||||
/** Probe slab extent along unit (px, py) through origin (ox, oy). */
|
||||
function probeExtent(
|
||||
bitset: Uint8Array,
|
||||
w: number,
|
||||
h: number,
|
||||
ox: number,
|
||||
oy: number,
|
||||
px: number,
|
||||
py: number,
|
||||
): { minP: number; maxP: number } | null {
|
||||
const half = Math.max(2, Math.round((w + h) / 4));
|
||||
let minP = Infinity;
|
||||
let maxP = -Infinity;
|
||||
for (let p = -half; p <= half; p++) {
|
||||
const x = Math.round(ox + px * p);
|
||||
const y = Math.round(oy + py * p);
|
||||
if (x < 0 || y < 0 || x >= w || y >= h) continue;
|
||||
if (bitset[y * w + x]) {
|
||||
if (p < minP) minP = p;
|
||||
if (p > maxP) maxP = p;
|
||||
}
|
||||
}
|
||||
if (maxP < minP) return null;
|
||||
return { minP, maxP };
|
||||
}
|
||||
|
||||
function fmtInches(inches: number): string {
|
||||
const whole = Math.floor(inches + 1e-9);
|
||||
const rem = Math.round((inches - whole) * 8);
|
||||
if (rem === 0) return `${whole}"`;
|
||||
const frac: Record<number, string> = {
|
||||
1: '1/8', 2: '1/4', 3: '3/8', 4: '1/2', 5: '5/8', 6: '3/4', 7: '7/8', 8: '',
|
||||
};
|
||||
if (rem === 8) return `${whole + 1}"`;
|
||||
const part = frac[rem] ?? `${rem}/8`;
|
||||
return whole > 0 ? `${whole} ${part}"` : `${part}"`;
|
||||
}
|
||||
|
||||
export function buildOverlayPlan(input: OverlayPlanInput): OverlayPlan {
|
||||
const {
|
||||
bitset, widthPx, heightPx, bbox, scale, lengthIn, lengthLabel, mapToInventory,
|
||||
inventoryW, inventoryH,
|
||||
} = input;
|
||||
const seg = maskAxisSegment(bitset, widthPx, heightPx, bbox);
|
||||
// Re-orient span ends so EXIF bottom establishes station origin; axis still
|
||||
// lies on the approved M1 direction (seg ux/uy flipped only when needed).
|
||||
const oriented = pickBottomTowardTop(seg.start, seg.end);
|
||||
const { bottom, top, ux, uy } = oriented;
|
||||
const [rx, ry] = axisRightUnit(ux, uy);
|
||||
|
||||
// Consistent smaller readable font (#71). Cap by inventory size so high
|
||||
// source scale (≈80 px/in) does not dominate the PNG.
|
||||
const fontPx = (() => {
|
||||
if (inventoryW && inventoryH && inventoryW > 0 && inventoryH > 0) {
|
||||
return Math.max(12, Math.min(16, Math.round(Math.min(inventoryW, inventoryH) * 0.016)));
|
||||
}
|
||||
return Math.max(12, Math.min(16, Math.round(scale * 0.18)));
|
||||
})();
|
||||
// Inset for stroke + arrowhead so visual tips sit on/inside edges (#71).
|
||||
const lineW = Math.max(2, Math.round(fontPx / 10));
|
||||
const arrowHead = Math.max(7, fontPx * 0.32);
|
||||
// Width tips retain stroke/arrowhead protection. Length endpoints need only
|
||||
// half-stroke protection: larger arrowhead-derived inset visibly under-reached tips (#73).
|
||||
const widthEdgeInset = Math.max(lineW / 2 + 0.5, arrowHead * 0.15);
|
||||
const lengthEdgeInset = Math.max(0.5, lineW / 2);
|
||||
const pad = Math.max(10, Math.min(28, fontPx * 1.1));
|
||||
const stations = overlayWidthStations(lengthIn);
|
||||
const widths: OverlayWidthMark[] = [];
|
||||
for (const stationIn of stations) {
|
||||
const t = stationIn * scale;
|
||||
const ox = bottom[0] + ux * t;
|
||||
const oy = bottom[1] + uy * t;
|
||||
const extent = probeExtent(bitset, widthPx, heightPx, ox, oy, rx, ry);
|
||||
if (!extent) continue;
|
||||
// left/right on mask edges, then inset in inventory space for stroke/arrowhead
|
||||
const leftMapped = mapToInventory(ox + rx * extent.minP, oy + ry * extent.minP);
|
||||
const rightMapped = mapToInventory(ox + rx * extent.maxP, oy + ry * extent.maxP);
|
||||
const wdx = rightMapped[0] - leftMapped[0];
|
||||
const wdy = rightMapped[1] - leftMapped[1];
|
||||
const wlen = Math.hypot(wdx, wdy) || 1;
|
||||
const wux = wdx / wlen;
|
||||
const wuy = wdy / wlen;
|
||||
const left: [number, number] = [leftMapped[0] + wux * widthEdgeInset, leftMapped[1] + wuy * widthEdgeInset];
|
||||
const right: [number, number] = [rightMapped[0] - wux * widthEdgeInset, rightMapped[1] - wuy * widthEdgeInset];
|
||||
// Width number sits axis-left outside the slab (past left tip).
|
||||
const labelOff = extent.minP - pad - fontPx * 0.85;
|
||||
const labelSrcW: [number, number] = [ox + rx * labelOff, oy + ry * labelOff];
|
||||
const widthIn = (extent.maxP - extent.minP + 1) / scale;
|
||||
widths.push({
|
||||
stationIn,
|
||||
center: mapToInventory(ox, oy),
|
||||
left,
|
||||
right,
|
||||
labelAt: mapToInventory(labelSrcW[0], labelSrcW[1]),
|
||||
label: fmtInches(widthIn),
|
||||
});
|
||||
}
|
||||
|
||||
// Length graphic: beside wood on axis-right, outside max right extent.
|
||||
let maxRight = 0;
|
||||
const samples = Math.max(8, Math.round(lengthIn));
|
||||
for (let i = 0; i <= samples; i++) {
|
||||
const t = (i / samples) * (lengthIn * scale);
|
||||
const ox = bottom[0] + ux * t;
|
||||
const oy = bottom[1] + uy * t;
|
||||
const extent = probeExtent(bitset, widthPx, heightPx, ox, oy, rx, ry);
|
||||
if (extent && extent.maxP > maxRight) maxRight = extent.maxP;
|
||||
}
|
||||
const outward = maxRight + pad;
|
||||
// Classic dimensioning (#70 + #71): width-aware centerline tip stations offset by
|
||||
// pure axis-right (rx,ry)*outward. Length stays || approved (ux,uy); no screen-slide.
|
||||
// Axial inset (inventory space) so arrowhead tips sit on footprint, not past.
|
||||
const aMapped = mapToInventory(bottom[0] + rx * outward, bottom[1] + ry * outward);
|
||||
const bMapped = mapToInventory(top[0] + rx * outward, top[1] + ry * outward);
|
||||
const ldx0 = bMapped[0] - aMapped[0];
|
||||
const ldy0 = bMapped[1] - aMapped[1];
|
||||
const llen0 = Math.hypot(ldx0, ldy0) || 1;
|
||||
const lux = ldx0 / llen0;
|
||||
const luy = ldy0 / llen0;
|
||||
const aInv: [number, number] = [aMapped[0] + lux * lengthEdgeInset, aMapped[1] + luy * lengthEdgeInset];
|
||||
const bInv: [number, number] = [bMapped[0] - lux * lengthEdgeInset, bMapped[1] - luy * lengthEdgeInset];
|
||||
const midInv: [number, number] = [(aInv[0] + bInv[0]) / 2, (aInv[1] + bInv[1]) / 2];
|
||||
// Length label further axis-right of dim line so glyphs stay off the wood (#71).
|
||||
const mapOrigin = mapToInventory(0, 0);
|
||||
const mapR = mapToInventory(rx, ry);
|
||||
const irx = mapR[0] - mapOrigin[0];
|
||||
const iry = mapR[1] - mapOrigin[1];
|
||||
const irlen = Math.hypot(irx, iry) || 1;
|
||||
const nrx = irx / irlen;
|
||||
const nry = iry / irlen;
|
||||
const labelAt: [number, number] = [
|
||||
midInv[0] + nrx * (fontPx * 0.85 + 6),
|
||||
midInv[1] + nry * (fontPx * 0.85 + 6),
|
||||
];
|
||||
|
||||
const lengthMark: OverlayLengthMark = {
|
||||
a: aInv,
|
||||
b: bInv,
|
||||
labelAt,
|
||||
label: lengthLabel,
|
||||
outside: true,
|
||||
};
|
||||
|
||||
// Clamp all labels inside inventory PNG so nothing clips (#71).
|
||||
if (inventoryW && inventoryH && inventoryW > 0 && inventoryH > 0) {
|
||||
const margin = Math.max(8, fontPx * 0.65);
|
||||
const clamp = (pt: [number, number], growLeft: boolean, text: string): [number, number] => {
|
||||
let [x, y] = pt;
|
||||
const glyphW = Math.max(fontPx * 1.2, text.length * fontPx * 0.55);
|
||||
if (growLeft) {
|
||||
// textAlign right — glyphs extend left of anchor
|
||||
x = Math.max(margin + glyphW, Math.min(inventoryW - margin, x));
|
||||
} else {
|
||||
x = Math.max(margin, Math.min(inventoryW - margin, x));
|
||||
}
|
||||
y = Math.max(margin, Math.min(inventoryH - margin, y));
|
||||
return [x, y];
|
||||
};
|
||||
lengthMark.labelAt = clamp(lengthMark.labelAt, false, lengthLabel);
|
||||
for (const w of widths) {
|
||||
const growLeft = w.labelAt[0] <= w.center[0];
|
||||
w.labelAt = clamp(w.labelAt, growLeft, w.label);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stroke: '#000000',
|
||||
fontPx,
|
||||
length: lengthMark,
|
||||
widths,
|
||||
};
|
||||
}
|
||||
|
||||
/** Draw black dimension graphics onto an existing canvas (inventory PNG size). */
|
||||
export function drawOverlayPlan(
|
||||
ctx: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D,
|
||||
plan: OverlayPlan,
|
||||
): void {
|
||||
const { stroke, fontPx } = plan;
|
||||
ctx.save();
|
||||
ctx.strokeStyle = stroke;
|
||||
ctx.fillStyle = stroke;
|
||||
ctx.lineWidth = Math.max(2, Math.round(fontPx / 10));
|
||||
// Butt caps: round caps extend past endpoints and overshoot wood edges (#71).
|
||||
ctx.lineCap = 'butt';
|
||||
ctx.font = `bold ${fontPx}px sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
const arrow = (from: [number, number], to: [number, number]) => {
|
||||
const dx = to[0] - from[0];
|
||||
const dy = to[1] - from[1];
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
const ux = dx / len;
|
||||
const uy = dy / len;
|
||||
const head = Math.max(7, fontPx * 0.32);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(from[0], from[1]);
|
||||
ctx.lineTo(to[0], to[1]);
|
||||
ctx.stroke();
|
||||
// arrow tips at both ends
|
||||
for (const [sx, sy, dir] of [
|
||||
[from[0], from[1], 1],
|
||||
[to[0], to[1], -1],
|
||||
] as const) {
|
||||
const px = -uy;
|
||||
const py = ux;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(sx, sy);
|
||||
ctx.lineTo(sx + dir * ux * head + px * head * 0.4, sy + dir * uy * head + py * head * 0.4);
|
||||
ctx.lineTo(sx + dir * ux * head - px * head * 0.4, sy + dir * uy * head - py * head * 0.4);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
};
|
||||
|
||||
// Length — grow text further axis-right of the dim line (away from wood)
|
||||
arrow(plan.length.a, plan.length.b);
|
||||
{
|
||||
const [lax, lay] = plan.length.a;
|
||||
const [lbx, lby] = plan.length.b;
|
||||
const midX = (lax + lbx) / 2;
|
||||
const midY = (lay + lby) / 2;
|
||||
const outwardX = plan.length.labelAt[0] - midX;
|
||||
const outwardY = plan.length.labelAt[1] - midY;
|
||||
// Prefer left/right align so glyphs extend away from wood when offset is mostly ±x
|
||||
if (Math.abs(outwardX) >= Math.abs(outwardY)) {
|
||||
ctx.textAlign = outwardX >= 0 ? 'left' : 'right';
|
||||
} else {
|
||||
ctx.textAlign = 'center';
|
||||
}
|
||||
}
|
||||
ctx.fillText(plan.length.label, plan.length.labelAt[0], plan.length.labelAt[1]);
|
||||
|
||||
// Widths — grow text away from wood (labelAt is axis-left of left tip)
|
||||
for (const w of plan.widths) {
|
||||
arrow(w.left, w.right);
|
||||
// labelAt is on the axis-left side of the station; align so glyphs extend further out
|
||||
const towardLeft = w.labelAt[0] <= w.center[0];
|
||||
ctx.textAlign = towardLeft ? 'right' : 'left';
|
||||
ctx.fillText(w.label, w.labelAt[0], w.labelAt[1]);
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
export interface InventoryMap {
|
||||
mapToInventory: (x: number, y: number) => [number, number];
|
||||
outW: number;
|
||||
outH: number;
|
||||
}
|
||||
|
||||
/** Same crop math as composeInventoryFrame — source → inventory PNG pixels. */
|
||||
export function inventorySourceMap(
|
||||
slabBounds: { x: number; y: number; w: number; h: number },
|
||||
source: { widthPx: number; heightPx: number },
|
||||
outW: number,
|
||||
outH: number,
|
||||
): InventoryMap {
|
||||
const FILL = 0.9;
|
||||
const x0 = Math.max(0, Math.round(slabBounds.x));
|
||||
const y0 = Math.max(0, Math.round(slabBounds.y));
|
||||
const x1 = Math.min(source.widthPx, x0 + Math.max(1, Math.round(slabBounds.w)));
|
||||
const y1 = Math.min(source.heightPx, y0 + Math.max(1, Math.round(slabBounds.h)));
|
||||
const sw = x1 - x0;
|
||||
const sh = y1 - y0;
|
||||
const scale = Math.min((outW * FILL) / Math.max(sw, 1), (outH * FILL) / Math.max(sh, 1));
|
||||
const dw = sw * scale;
|
||||
const dh = sh * scale;
|
||||
const ox = (outW - dw) / 2;
|
||||
const oy = (outH - dh) / 2;
|
||||
return {
|
||||
outW,
|
||||
outH,
|
||||
mapToInventory: (sx, sy) => [ox + (sx - x0) * scale, oy + (sy - y0) * scale],
|
||||
};
|
||||
}
|
||||
|
||||
export interface EncodeOverlayInput {
|
||||
/** Clean calibration inventory PNG bytes. */
|
||||
inventoryPng: Blob;
|
||||
bitset: Uint8Array;
|
||||
widthPx: number;
|
||||
heightPx: number;
|
||||
bbox: BBox;
|
||||
scale: number;
|
||||
lengthIn: number;
|
||||
lengthLabel: string;
|
||||
slabBounds: { x: number; y: number; w: number; h: number };
|
||||
source: { widthPx: number; heightPx: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* Burn black dimension overlays onto a copy of the clean calibration inventory PNG.
|
||||
* Returns a new image/png blob; never mutates the clean inventory.
|
||||
*/
|
||||
export async function encodeOverlayPng(input: EncodeOverlayInput): Promise<Blob> {
|
||||
const bmp = await createImageBitmap(input.inventoryPng);
|
||||
try {
|
||||
const outW = bmp.width;
|
||||
const outH = bmp.height;
|
||||
const canvas = new OffscreenCanvas(outW, outH);
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
ctx.drawImage(bmp, 0, 0);
|
||||
const { mapToInventory } = inventorySourceMap(input.slabBounds, input.source, outW, outH);
|
||||
const plan = buildOverlayPlan({
|
||||
bitset: input.bitset,
|
||||
widthPx: input.widthPx,
|
||||
heightPx: input.heightPx,
|
||||
bbox: input.bbox,
|
||||
scale: input.scale,
|
||||
lengthIn: input.lengthIn,
|
||||
lengthLabel: input.lengthLabel,
|
||||
mapToInventory,
|
||||
inventoryW: outW,
|
||||
inventoryH: outH,
|
||||
});
|
||||
drawOverlayPlan(ctx, plan);
|
||||
return await canvas.convertToBlob({ type: 'image/png' });
|
||||
} finally {
|
||||
bmp.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { minAreaRect, slabBounds } from '../geometry/rect';
|
||||
import type { MaskParams, WorkerIn, WorkerOut } from '../capture/capture.types';
|
||||
import { decodeOrientedBitmap } from '../decodeOrientedBitmap';
|
||||
import { greenKeep, blackKeep, autoPickSheet } from '../mask/sheetKeep';
|
||||
|
||||
let bitmap: ImageBitmap | null = null;
|
||||
let data: Uint8ClampedArray | null = null;
|
||||
let w = 0, h = 0;
|
||||
let current = 0; // highest job id issued by main; older replies are dropped
|
||||
|
||||
function runMask(params: MaskParams, id: number): WorkerOut {
|
||||
if (!data) return { id, kind: 'failed', reason: 'no source decoded' };
|
||||
let sheet = params.sheet;
|
||||
if (sheet === 'auto') {
|
||||
const samples: { r: number; g: number; b: number }[] = [];
|
||||
for (let y = 0; y < h; y += 16)
|
||||
for (let x = 0; x < w; x += 16) {
|
||||
const i = (y * w + x) * 4;
|
||||
samples.push({ r: data[i], g: data[i + 1], b: data[i + 2] });
|
||||
}
|
||||
sheet = autoPickSheet(samples);
|
||||
}
|
||||
const keep = sheet === 'green' ? greenKeep : blackKeep;
|
||||
const s = Math.max(0, Math.min(100, params.sensitivity));
|
||||
const bitset = new Uint8Array(w * h);
|
||||
let slabPx = 0;
|
||||
for (let i = 0, p = 0; i < data.length; i += 4, p++) {
|
||||
if (keep(data[i], data[i + 1], data[i + 2], s)) {
|
||||
bitset[p] = 1;
|
||||
slabPx++;
|
||||
}
|
||||
}
|
||||
if (slabPx === 0) {
|
||||
return { id, kind: 'ready', slabPx: 0, bitset, bbox: { corners: [], longSidePx: 0, angleDeg: 0 }, slabBounds: { x: 0, y: 0, w: 0, h: 0 } };
|
||||
}
|
||||
const bbox = minAreaRect(bitset, w, h);
|
||||
if (!bbox) {
|
||||
return { id, kind: 'ready', slabPx: 0, bitset, bbox: { corners: [], longSidePx: 0, angleDeg: 0 }, slabBounds: { x: 0, y: 0, w: 0, h: 0 } };
|
||||
}
|
||||
return { id, kind: 'ready', slabPx, bitset, bbox, slabBounds: slabBounds(bitset, w, h) };
|
||||
}
|
||||
|
||||
self.onmessage = (e: MessageEvent<WorkerIn>) => {
|
||||
const msg = e.data;
|
||||
if (msg.id < current) return; // superseded by a newer job
|
||||
current = msg.id;
|
||||
if (msg.kind === 'init') {
|
||||
if (bitmap) {
|
||||
bitmap.close();
|
||||
bitmap = null;
|
||||
}
|
||||
data = null;
|
||||
w = h = 0;
|
||||
decodeOrientedBitmap(msg.blob)
|
||||
.then((bmp) => {
|
||||
w = bmp.width;
|
||||
h = bmp.height;
|
||||
const canvas = new OffscreenCanvas(w, h);
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
ctx.drawImage(bmp, 0, 0);
|
||||
data = ctx.getImageData(0, 0, w, h).data;
|
||||
bitmap = bmp;
|
||||
self.postMessage({ id: msg.id, kind: 'decoded', w, h } as WorkerOut);
|
||||
})
|
||||
.catch((err) => self.postMessage({ id: msg.id, kind: 'failed', reason: String(err) } satisfies WorkerOut));
|
||||
return;
|
||||
}
|
||||
if (msg.kind === 'invalidate') {
|
||||
if (bitmap) {
|
||||
bitmap.close();
|
||||
bitmap = null;
|
||||
}
|
||||
data = null;
|
||||
w = h = 0;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const out = runMask({ sheet: msg.sheet, sensitivity: msg.sensitivity }, msg.id);
|
||||
if (out.kind === 'ready') {
|
||||
self.postMessage(out, [out.bitset.buffer]);
|
||||
} else {
|
||||
self.postMessage(out);
|
||||
}
|
||||
} catch (err) {
|
||||
self.postMessage({ id: msg.id, kind: 'failed', reason: String(err) } satisfies WorkerOut);
|
||||
}
|
||||
};
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,40 @@
|
||||
# E2E visual artifacts (#65)
|
||||
|
||||
Screenshots from `npx playwright test` for Milestone 2 Photos-ready evidence.
|
||||
|
||||
## How to run (local box — not ubudual :10880)
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm ci
|
||||
npx playwright install chromium # once per machine
|
||||
npm run test:e2e
|
||||
```
|
||||
|
||||
Or against an already-running preview:
|
||||
|
||||
```bash
|
||||
npm run build && npm run preview -- --host 127.0.0.1 --port 4173
|
||||
# other terminal:
|
||||
npx playwright test
|
||||
```
|
||||
|
||||
Fixtures: `tests/fixtures/set1-48x2/` (L=48, thickness=2) and `set2-31x2p5/` (L=31, thickness=2.5). Black sheet — e2e selects **Black** and may nudge sensitivity.
|
||||
|
||||
## Expected screenshots (this folder)
|
||||
|
||||
| File | Step |
|
||||
|---|---|
|
||||
| `01-batch.png` | Batch with fixtures loaded |
|
||||
| `02-pick-calibration.png` | Pick calibration |
|
||||
| `03-mask.png` | Mask (Black sheet) ready to approve |
|
||||
| `04-axis.png` | Length axis |
|
||||
| `05-measure.png` | Measure with L / thickness filled |
|
||||
| `06-photos-ready.png` | Photos ready lineup (clean + overlay + siblings) |
|
||||
|
||||
Large regenerating `*.png` and Playwright `test-results/` / `playwright-report/` are gitignored.
|
||||
Committed small evidence JPEGs live in `evidence/` (regenerate with a green `npm run test:e2e`, then re-encode if needed).
|
||||
|
||||
## Unit tests
|
||||
|
||||
`npm test` must still pass separately from Playwright.
|
||||
|
After Width: | Height: | Size: 177 KiB |
|
After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 207 KiB |
|
After Width: | Height: | Size: 186 KiB |
|
After Width: | Height: | Size: 466 KiB |
@@ -0,0 +1,11 @@
|
||||
# Last green e2e run (#71)
|
||||
|
||||
- **When:** 2026-09-15 9:55 PM PT (`2026-09-16T04:55:14Z`)
|
||||
- **Fixture:** `tests/fixtures/set1-48x2/` (L=48, thickness=2)
|
||||
- **Server:** local `vite preview` at `http://127.0.0.1:4173` (not ubudual)
|
||||
- **Result:** 1 passed (~8s test)
|
||||
- **Mask:** Black sheet — Approve enabled
|
||||
- **Fix under test:** width-aware tip stations; stroke/arrowhead edge inset; inventory-capped font; labels clamped in PNG (#71); #70 axis-parallel kept
|
||||
- **Lineup:** Clean calibration → Dimension overlay → Batch photo 2
|
||||
|
||||
Full-resolution PNGs are produced under `../` on each run (gitignored). These JPEGs are commit-sized evidence for review.
|
||||
@@ -0,0 +1,135 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const FIXTURES = path.resolve(__dirname, '../fixtures/set1-48x2');
|
||||
const ARTIFACTS = path.resolve(__dirname, 'artifacts');
|
||||
const FACE_A = path.join(FIXTURES, 'face-a.jpeg');
|
||||
const FACE_B = path.join(FIXTURES, 'face-b.jpeg');
|
||||
|
||||
const shot = async (page: Page, name: string) => {
|
||||
fs.mkdirSync(ARTIFACTS, { recursive: true });
|
||||
await page.screenshot({
|
||||
path: path.join(ARTIFACTS, name),
|
||||
fullPage: true,
|
||||
});
|
||||
};
|
||||
|
||||
/** Discard any device draft so we always start on Batch. */
|
||||
const ensureFreshBatch = async (page: Page) => {
|
||||
await page.goto('/');
|
||||
// resumeProbe is async onMount — wait for either Resume or Batch.
|
||||
const resumeHeading = page.getByRole('heading', { name: /resume/i });
|
||||
const batchHeading = page.getByRole('heading', { name: 'Batch photos' });
|
||||
await expect(resumeHeading.or(batchHeading)).toBeVisible({ timeout: 15_000 });
|
||||
if (await resumeHeading.isVisible().catch(() => false)) {
|
||||
await page.getByRole('button', { name: /start fresh/i }).click();
|
||||
}
|
||||
await expect(batchHeading).toBeVisible();
|
||||
};
|
||||
|
||||
/**
|
||||
* Black-sheet fixtures: Auto may work, but UAT note says prefer Black + sensitivity
|
||||
* tweaks. Do not invent inference — only UI sheet/sensitivity controls.
|
||||
*/
|
||||
const prepareMaskForApprove = async (page: Page) => {
|
||||
await expect(page.getByRole('heading', { name: 'Mask' })).toBeVisible();
|
||||
// Sheet change recomputes immediately (session.setSheet → runPass).
|
||||
await page.getByRole('button', { name: 'Black', exact: true }).click();
|
||||
|
||||
const approve = page.getByRole('button', { name: 'Approve mask' });
|
||||
// First overlay after decode is debounced 2s; Black pass is immediate but
|
||||
// 4K fixtures still need decode + worker time.
|
||||
try {
|
||||
await expect(approve).toBeEnabled({ timeout: 45_000 });
|
||||
return;
|
||||
} catch {
|
||||
/* try sensitivity ladder */
|
||||
}
|
||||
|
||||
// Higher sensitivity widens black sheet match; if still empty, try lower.
|
||||
for (const target of [60, 70, 40, 30, 80]) {
|
||||
const slider = page.locator('input[type="range"]');
|
||||
await slider.fill(String(target));
|
||||
// Sensitivity is debounced 2s — wait past debounce + worker.
|
||||
await page.waitForTimeout(2800);
|
||||
if (await approve.isEnabled()) return;
|
||||
}
|
||||
|
||||
await expect(approve, 'Mask approve stayed disabled after Black + sensitivity tweaks').toBeEnabled({
|
||||
timeout: 15_000,
|
||||
});
|
||||
};
|
||||
|
||||
test.describe('M2 #65 Photos-ready e2e (set1-48x2)', () => {
|
||||
test('batch → pick → mask → axis → measure → photos ready + screenshots', async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
expect(fs.existsSync(FACE_A), 'fixture face-a').toBeTruthy();
|
||||
expect(fs.existsSync(FACE_B), 'fixture face-b').toBeTruthy();
|
||||
|
||||
await ensureFreshBatch(page);
|
||||
|
||||
// Gallery multi-input (not the capture=environment camera input).
|
||||
const gallery = page.locator('input[type="file"][multiple]');
|
||||
await gallery.setInputFiles([FACE_A, FACE_B]);
|
||||
await expect(page.getByAltText('Batch photo 1')).toBeVisible({ timeout: 30_000 });
|
||||
await expect(page.getByAltText('Batch photo 2')).toBeVisible();
|
||||
await shot(page, '01-batch.png');
|
||||
|
||||
await page.getByRole('button', { name: 'Continue' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Pick calibration photo' })).toBeVisible();
|
||||
await shot(page, '02-pick-calibration.png');
|
||||
|
||||
await page.getByRole('button', { name: 'Use photo 1 as calibration' }).click();
|
||||
await prepareMaskForApprove(page);
|
||||
await shot(page, '03-mask.png');
|
||||
await page.getByRole('button', { name: 'Approve mask' }).click();
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Length axis' })).toBeVisible();
|
||||
await shot(page, '04-axis.png');
|
||||
await page.getByRole('button', { name: 'Approve axis' }).click();
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Measure' })).toBeVisible();
|
||||
await page.getByLabel('Length L').fill('48');
|
||||
await page.getByLabel('Thickness').fill('2');
|
||||
// blur/change commits eighths into session before Calculate.
|
||||
await page.getByLabel('Length L').blur();
|
||||
await page.getByLabel('Thickness').blur();
|
||||
await shot(page, '05-measure.png');
|
||||
|
||||
const calc = page.getByRole('button', { name: 'Calculate' });
|
||||
await expect(calc).toBeEnabled();
|
||||
await calc.click();
|
||||
|
||||
// Calculate encodes calibration PNG + overlay + sibling batch apply.
|
||||
await expect(page.getByRole('heading', { name: 'Photos ready' })).toBeVisible({
|
||||
timeout: 120_000,
|
||||
});
|
||||
await expect(page.getByLabel('Photos ready')).toBeVisible();
|
||||
await expect(page.getByText('Clean calibration')).toBeVisible();
|
||||
await expect(page.getByText('Dimension overlay')).toBeVisible();
|
||||
// Sibling face-b should appear as Batch photo 2 (capture order).
|
||||
await expect(page.getByText(/Batch photo 2|Photo 2 failed/)).toBeVisible();
|
||||
|
||||
await shot(page, '06-photos-ready.png');
|
||||
|
||||
// Write a short run log for parent AI visual review (not a substitute for eyes).
|
||||
const logPath = path.join(ARTIFACTS, 'run-log.txt');
|
||||
const shots = ['01-batch.png', '02-pick-calibration.png', '03-mask.png', '04-axis.png', '05-measure.png', '06-photos-ready.png'];
|
||||
const lines = [
|
||||
`M2 #65 Playwright e2e — set1-48x2 (L=48, thickness=2)`,
|
||||
`baseURL: ${page.url().split('/').slice(0, 3).join('/')}`,
|
||||
`finished: ${new Date().toISOString()}`,
|
||||
`artifacts:`,
|
||||
...shots.map((s) => {
|
||||
const p = path.join(ARTIFACTS, s);
|
||||
const st = fs.existsSync(p) ? fs.statSync(p) : null;
|
||||
return ` - ${s} (${st ? `${st.size} bytes` : 'MISSING'})`;
|
||||
}),
|
||||
`assertions: Photos ready heading; Clean calibration; Dimension overlay; batch sibling slot`,
|
||||
];
|
||||
fs.writeFileSync(logPath, lines.join('\n') + '\n', 'utf8');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
# Test photo fixtures
|
||||
|
||||
Matched sets from Ty for Milestone 2 Photos (Playwright + calibration). Black sheet.
|
||||
|
||||
## set1-48x2 — L = 48 in, thickness = 2 in
|
||||
Curly / fiddleback bookmatch pair.
|
||||
- `face-a.jpeg`
|
||||
- `face-b.jpeg`
|
||||
|
||||
## set2-31x2p5 — L = 31 in, thickness = 2.5 in
|
||||
Shorter organic / burl pair.
|
||||
- `face-a.jpeg`
|
||||
- `face-b.jpeg`
|
||||
|
||||
## m1-dji (optional M1 UAT sample)
|
||||
- `162332.JPG` — live-edge on black; historically used on ubudual M1 UAT.
|
||||
|
After Width: | Height: | Size: 760 KiB |
|
After Width: | Height: | Size: 768 KiB |
|
After Width: | Height: | Size: 884 KiB |
|
After Width: | Height: | Size: 856 KiB |
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"],
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"verbatimModuleSyntax": false,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.svelte", "vite.config.ts"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
||||
import sveltePreprocess from 'svelte-preprocess';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [svelte({ preprocess: sveltePreprocess() })],
|
||||
worker: { format: 'es' },
|
||||
});
|
||||