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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
409 changes: 409 additions & 0 deletions apps/windows-studio/src/packlab_studio/design_library_view.py

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions apps/windows-studio/src/packlab_studio/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,38 @@ def translate_widget_tree(root: QWidget) -> None:
"Create: cancelling the section fit…": "Oluştur: kesit uydurma iptal ediliyor…",
"Shipping Case": "Koli",
"Warehouse": "Depo",
"Design Library": "Tasarım Kütüphanesi",
"Server drafts: check out, edit, save without overwriting others, and release.": "Sunucu taslakları: kullanıma al, düzenle, başkalarının üzerine yazmadan kaydet ve yayınla.",
"Refresh list": "Listeyi yenile",
"Version": "Sürüm",
"Draft revision": "Taslak revizyon",
"Checked out by": "Kullanımda olan",
"Kind (e.g. bottle)": "Tür (ör. şişe)",
"New draft": "Yeni taslak",
"Design note for this draft": "Bu taslak için tasarım notu",
"Check out": "Kullanıma al",
"Check in": "Kullanımı bırak",
"Save draft": "Taslağı kaydet",
"Reload latest": "En yenisini yükle",
"Design nominal": "Tasarım nominal",
"Metric unverified": "Ölçü doğrulanmamış",
"Release": "Yayınla",
"Enter the server address and the company sign-in.": "Sunucu adresini ve şirket girişini girin.",
"Connected as {who}.": "{who} olarak bağlandı.",
"Connected.": "Bağlandı.",
"Not changed: {who} has this item checked out.": "Değiştirilmedi: bu öğe {who} kullanımında.",
"The server did not answer ({reason}). Press the same button again: a retry is applied only once.": "Sunucu yanıt vermedi ({reason}). Aynı düğmeye yeniden basın: yeniden deneme yalnızca bir kez uygulanır.",
"Enter a kind and a name.": "Bir tür ve ad girin.",
"Choose an item first.": "Önce bir öğe seçin.",
"Your role can only read released items.": "Rolünüz yalnızca yayınlanmış öğeleri okuyabilir.",
"The server refused: {reason}": "Sunucu reddetti: {reason}",
"Loaded version {version}. Your unsaved note was: {note}": "Sürüm {version} yüklendi. Kaydedilmemiş notunuz: {note}",
"Released revision {revision}; it can no longer change.": "Revizyon {revision} yayınlandı; artık değiştirilemez.",
"Saved as version {version}.": "Sürüm {version} olarak kaydedildi.",
"Checked out to you.": "Kullanımınıza alındı.",
"Checked in.": "Kullanım bırakıldı.",
"Not saved: {who} has this item checked out.": "Kaydedilmedi: bu öğe {who} kullanımında.",
"Not saved: someone saved version {version} first. Press Reload latest, then apply your change again.": "Kaydedilmedi: başka biri önce sürüm {version} kaydetti. En yenisini yükle'ye basın, sonra değişikliğinizi yeniden uygulayın.",
"Released packaging from the PackLab Server and warehouse observations.": "PackLab Sunucusundaki yayınlanmış ambalajlar ve depo gözlemleri.",
"Sign in": "Giriş yap",
"Sync now": "Şimdi eşitle",
Expand Down
17 changes: 16 additions & 1 deletion apps/windows-studio/src/packlab_studio/navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@

from .build_model import DEFAULT_BUILD_QUALITY, SUPPORTED_COLMAP_VERSIONS, BuildModelView
from .capture_inbox import CaptureInboxView
from .design_library_view import DesignLibraryView
from .design_workbench import DesignWorkbench
from .engine_config import discover_engines
from .engineering_export import EngineeringExportView
Expand Down Expand Up @@ -74,6 +75,7 @@ class Route(StrEnum):
PACKAGE_FAMILIES = "package-families"
SHIPPING_CASE = "shipping-case"
WAREHOUSE = "warehouse"
DESIGN_LIBRARY = "design-library"


# Navigation label / page title, one-line plain-language description, standard Qt icon.
Expand Down Expand Up @@ -138,6 +140,11 @@ class Route(StrEnum):
"Design a corrugated shipping case around the product and export its dieline.",
QStyle.StandardPixmap.SP_DriveHDIcon,
),
Route.DESIGN_LIBRARY: (
"Design Library",
"Server drafts: check out, edit, save without overwriting others, and release.",
QStyle.StandardPixmap.SP_DriveNetIcon,
),
Route.WAREHOUSE: (
"Warehouse",
"Released packaging from the PackLab Server and warehouse observations.",
Expand All @@ -160,7 +167,13 @@ class Route(StrEnum):
),
(
"Design",
(Route.MEASURE_DESIGN, Route.LABELS, Route.PACKAGE_FAMILIES, Route.LIBRARY),
(
Route.MEASURE_DESIGN,
Route.LABELS,
Route.PACKAGE_FAMILIES,
Route.LIBRARY,
Route.DESIGN_LIBRARY,
),
),
("Production", (Route.SHIPPING_CASE, Route.EXPORTS)),
("Warehouse", (Route.WAREHOUSE,)),
Expand Down Expand Up @@ -583,6 +596,8 @@ def _project_root(project_manager: Any) -> Path | None:
),
Route.SHIPPING_CASE: lambda s: ShippingCaseView(s.get("case_destination_provider")),
Route.WAREHOUSE: lambda s: WarehouseView(s.get("warehouse_data_root")),
# same data root: the server address and issuer typed on either page are shared
Route.DESIGN_LIBRARY: lambda s: DesignLibraryView(s.get("warehouse_data_root")),
}


Expand Down
34 changes: 34 additions & 0 deletions apps/windows-studio/src/packlab_studio/server_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""``server.json``: the server address, sign-in and ERP settings shared by the server pages."""

from __future__ import annotations

import json
import os
import tempfile
from pathlib import Path


def load_settings(root: Path) -> dict[str, str]:
try:
value = json.loads((Path(root) / "server.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return {k: str(v) for k, v in value.items()} if isinstance(value, dict) else {}


def save_settings(root: Path, values: dict[str, str]) -> None:
"""Merge ``values`` in (keeps the other page's keys); a crash never leaves half a file."""
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
merged = {**load_settings(root), **values}
fd, tmp = tempfile.mkstemp(dir=root, prefix=".server-", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(merged, handle)
os.replace(tmp, root / "server.json")
finally:
if os.path.exists(tmp):
os.unlink(tmp)


__all__ = ["load_settings", "save_settings"]
14 changes: 3 additions & 11 deletions apps/windows-studio/src/packlab_studio/warehouse_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from packlab_core.sync_loop import SyncLoop, SyncStatus

from .i18n import tr
from .server_settings import load_settings, save_settings
from .warehouse_erp import ErpPanel, _emit, revoke_later, revoke_token

OBSERVATION_KINDS = { # server kind -> label ("Fit" alone is the 3D view's fit button)
Expand Down Expand Up @@ -421,20 +422,11 @@ def _show_failure(self, text: str) -> None:
def _signin_path(self) -> Path:
return self.data_root / "signin.dpapi"

def _settings_path(self) -> Path:
return self.data_root / "server.json"

def _load_settings(self) -> dict[str, str]:
try:
value = json.loads(self._settings_path().read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return {k: str(v) for k, v in value.items()} if isinstance(value, dict) else {}
return load_settings(self.data_root)

def _save_settings(self, values: dict[str, str]) -> None:
merged = {**self._load_settings(), **values} # keeps the ERP settings too
self.data_root.mkdir(parents=True, exist_ok=True)
self._settings_path().write_text(json.dumps(merged), encoding="utf-8")
save_settings(self.data_root, values) # merged: keeps the ERP settings too

def _erp_settings(self) -> dict[str, str]:
typed = {"issuer": self.issuer.text().strip(), "app_client": self.app_client.text().strip()}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# CLAUDE_PEER_REVIEW PL-0504 Studio Design Library client, V01

Reviewer: Claude Code independent source reviewer (subagent), not the builder. PR #109, branch `feat/pl-0504-studio-design-client`, head 3910c537ea64179b5de6cab7729821d75ebde03a, base 962e6f62.
Verdict: PASS_WITH_FIXES. Fix M1 and M2 before `[x]`.

## Checklist
1. Idempotency-Key: keyed on exact (method, path, body), kept only for status 0 or >= 500, dropped on any definite answer; server stores the answer in the same transaction. OK, except the M2 race.
2. expected_version: always from the loaded editor state; `_show_items` never refreshes the editor; 409/423 become DesignConflict. OK.
3. Qt threading: worker closures capture only library, bridge and plain values; bridge parented; `_emit` tolerates a deleted bridge; answers of an earlier connection dropped. OK.
4. Tokens: in memory only; server.json gets server_url and issuer only; no logging added. OK.
5. Release authority: UI offers only DESIGN_NOMINAL / METRIC_UNVERIFIED; server refuses METRIC_VERIFIED. OK (see L4).
6. Role checks: server refusals shown verbatim. OK.

## Findings
- MEDIUM M1 design_library.py:65, design_library_view.py:206-208: `save()` always sends `"assets": []`, so a note save from the page deletes the draft's assets (probe: assets ['82d98f12…'] -> []). Fix: `assets` parameter, view passes the head revision's assets; test.
- MEDIUM M2 design_library.py:79,81: concurrent identical writes share a key; the first finisher deletes it and the others raise KeyError (probe: 8 concurrent saves, server applied once, 7 KeyErrors shown as refusals). Fix: `self._keys.pop(request, None)`; optionally disable action buttons while a request runs.
- LOW L1: a lost answer (status 0 / 5xx) reads as "The server refused"; say it can be retried safely.
- LOW L2: "Not saved:" also shown for check-out / check-in refusals; word it by action.
- LOW L3: status line shows the issuer instead of the user.
- LOW L4: `DesignLibrary.release` accepts any metric_status; guard against RELEASE_METRIC_STATUSES.
- LOW L5: server.json load/save duplicated from warehouse_view.py and not atomic; share a helper, write via temp file + os.replace.
- LOW L6: no tests for asset preservation, concurrent identical writes, or the lost-answer path through the page.

## Evidence (reviewer runs, detached worktree at PR head)
- tests/core/test_design_library.py tests/studio/test_design_library_view.py tests/core/test_reconstruction_orchestrator.py: 25 passed.
- tests/core/test_reconstruction_orchestrator.py tests/studio: 676 passed, 3 skipped.
- tests/server + design_library + desktop_signin + erp_sync: 91 passed.
- ruff check core apps server tools tests: pass; ruff format --check (line-ending auto) on the 6 files: formatted; mypy --no-incremental core apps server tools: 0 issues / 347 files.
- Probes against a real local PackLabServer reproduced M1 and M2.

## Limits
Not checked in the real Studio window; no real IdP sign-in; final CI not observed. PL-0504 stays `[ ]`.

## Addendum V01-R1: re-review of the fixes (2026-12-04)
Reviewer: independent subagent, not the builder. Base 882f6022 -> head a7d6b117 (one commit, 7 files). Verdict: PASS (M1, M2, L1-L6 resolved).
- M1 fixed: save sends the head revision's assets; probe on a real server keeps the files.
- M2 fixed: `pop(request, None)`; page runs one request at a time (buttons disabled while busy). Probe: 8 identical saves at once, 0 errors, applied once, no keys left.
- L1 no-answer message; L2 wording by action; L3 user label from unverified ID-token claims (label only); L4 client release guard; L5 shared atomic server_settings.py (warehouse erp_* keys kept, failed write leaves the old file, no temp left); L6 tests.
- Mutation checks: reverting each fix fails its test (view/core assets, pop->del, busy buttons, no-answer message, release guard).
- Reviewer runs at a7d6b117 with worktree src paths: 772 passed, 3 skipped (orchestrator + tests/studio + design_library + server + desktop_signin + erp_sync); ruff pass; format clean; mypy 0 issues / 348 files.
- Optional Lows: JWT body decoding duplicated with warehouse_view._subject; no test for L2 wording or _shown_name.
- Limits: not checked in the real Studio window; no real IdP sign-in; CI not observed at review time.
111 changes: 111 additions & 0 deletions core/src/packlab_core/design_library.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""Design department edits on the PackLab Server (PL-0504): drafts, checkout, release.

Every write carries an Idempotency-Key. A key belongs to one logical edit: the same request
sent again after a lost answer (no answer, a 5xx) reuses its key, so the server applies it
once; a new edit gets a new key. Edits and releases carry ``expected_version``: when someone
else changed the item first, or holds its checkout, the server refuses and the caller gets a
``DesignConflict`` saying who or which version. Nothing is ever overwritten silently.
Released revisions are immutable on the server: a save after a release starts a new draft.
"""

from __future__ import annotations

import json
import re
import uuid
from typing import Any

from .server_sync import PackLabServerClient, ServerError

RELEASE_METRIC_STATUSES = ("DESIGN_NOMINAL", "METRIC_UNVERIFIED") # METRIC_VERIFIED: PL-0510


class DesignConflict(ServerError):
"""The server refused an edit: a newer version exists, or another user holds checkout."""

def __init__(self, error: ServerError) -> None:
super().__init__(error.status, error.code, error.detail)
self.holder: str | None = None
self.server_version: int | None = None
if error.code == "checked_out_by_other":
self.holder = error.detail or None
else:
found = re.search(r"\d+", error.detail)
self.server_version = int(found.group()) if found else None


_CONFLICTS = frozenset({"version_conflict", "checked_out_by_other"})


class DesignLibrary:
def __init__(self, client: PackLabServerClient) -> None:
self.client = client
self._keys: dict[str, str] = {} # request -> its key, until the server answered

# --- reads -------------------------------------------------------------------------------
def items(self) -> list[dict[str, Any]]:
"""Every item this role may see (drafts too for design/admin; released for others)."""
return list(self.client.call("GET", "/v1/items")[1]["items"])

def item(self, item_id: str) -> dict[str, Any]:
return self.client.item(item_id)

# --- writes ------------------------------------------------------------------------------
def create(self, kind: str, name: str, payload: dict[str, Any]) -> dict[str, Any]:
body = {"kind": kind, "name": name, "payload": payload, "assets": []}
return self._write("POST", "/v1/items", body)

def checkout(self, item_id: str) -> dict[str, Any]:
return self._call("POST", f"{_path(item_id)}/checkout", {})

def checkin(self, item_id: str) -> None:
self._call("POST", f"{_path(item_id)}/checkin", {})

def save(
self,
item_id: str,
expected_version: int,
payload: dict[str, Any],
assets: list[str] | None = None,
) -> dict[str, Any]:
"""``assets`` replaces the draft's list: pass the loaded ones to keep them."""
body = {"expected_version": expected_version, "payload": payload, "assets": assets or []}
return self._write("PUT", f"{_path(item_id)}/draft", body)

def release(
self, item_id: str, expected_version: int, metric_status: str = "DESIGN_NOMINAL"
) -> dict[str, Any]:
if metric_status not in RELEASE_METRIC_STATUSES:
raise ValueError(f"metric_status must be one of {RELEASE_METRIC_STATUSES}")
body = {"expected_version": expected_version, "metric_status": metric_status}
return self._write("POST", f"{_path(item_id)}/release", body)

def _write(self, method: str, path: str, body: dict[str, Any]) -> dict[str, Any]:
request = json.dumps([method, path, body], sort_keys=True)
key = self._keys.setdefault(request, str(uuid.uuid4()))
try:
answer = self._call(method, path, body, key=key)
except ServerError as error:
if error.status == 0 or error.status >= 500:
raise # no definite answer: the retry of this same edit reuses the key
self._keys.pop(request, None) # a concurrent identical write may have answered
raise
self._keys.pop(request, None)
return answer

def _call(
self, method: str, path: str, body: object, *, key: str | None = None
) -> dict[str, Any]:
try:
return dict(self.client.call(method, path, body, key=key)[1] or {})
except ServerError as error:
if error.code in _CONFLICTS:
raise DesignConflict(error) from None
raise


def _path(item_id: str) -> str:
return f"/v1/items/{uuid.UUID(item_id)}" # an id is a UUID: nothing else reaches the URL


__all__ = ["RELEASE_METRIC_STATUSES", "DesignConflict", "DesignLibrary"]
Loading