diff --git a/apps/windows-studio/src/packlab_studio/design_library_view.py b/apps/windows-studio/src/packlab_studio/design_library_view.py new file mode 100644 index 00000000..197cc2af --- /dev/null +++ b/apps/windows-studio/src/packlab_studio/design_library_view.py @@ -0,0 +1,409 @@ +"""Design library route (PL-0504): server drafts, checkout, conflict-safe saves and releases. + +A designer signs in at the company IdP (same server address and issuer as the Warehouse +page, from ``server.json``), sees every item including drafts, checks one out, edits its +note, saves it with the version they loaded, and releases it. When someone else saved first +or holds the checkout, the server refuses and the page says who or which version; "Reload +latest" loads the newer version. The server enforces all of it; the page only shows it. +""" + +from __future__ import annotations + +import base64 +import json +import threading +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +from PySide6.QtCore import QObject, QStandardPaths, Qt, Signal +from PySide6.QtWidgets import ( + QComboBox, + QHBoxLayout, + QLabel, + QLineEdit, + QPushButton, + QTableWidget, + QTableWidgetItem, + QVBoxLayout, + QWidget, +) + +from packlab_core.design_library import RELEASE_METRIC_STATUSES, DesignConflict, DesignLibrary +from packlab_core.desktop_signin import TokenSet, TokenSource, discover, sign_in +from packlab_core.server_sync import PackLabServerClient, ServerError + +from .i18n import tr +from .server_settings import load_settings, save_settings +from .warehouse_erp import _emit + +METRIC_LABELS = {"DESIGN_NOMINAL": "Design nominal", "METRIC_UNVERIFIED": "Metric unverified"} + + +class _Bridge(QObject): + """Worker threads only emit; the GUI thread updates widgets (queued).""" + + done = Signal(object) + + +class DesignLibraryView(QWidget): + def __init__(self, data_root: Path | None = None) -> None: + super().__init__() + self.setObjectName("packlab.design_library") + root = data_root or Path( + QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation) + ) + self.data_root = Path(root) + self.library: DesignLibrary | None = None + self.identity = "" + self.bridge = _Bridge(self) # destroyed with the page, on the GUI thread + self.bridge.done.connect(self._finished) + self.allow_loopback_http = False # tests only: a local http IdP and server + self._items: list[dict[str, Any]] = [] + self._running = 0 # requests in flight + self._editing: dict[str, Any] | None = None # the item as loaded into the editor + + settings = load_settings(self.data_root) # shared with the Warehouse page + self.server_url = QLineEdit(settings.get("server_url", ""), self) + self.server_url.setPlaceholderText("https://packlab.example.com") + self.issuer = QLineEdit(settings.get("issuer", ""), self) + self.issuer.setPlaceholderText("https://login.example.com/realms/povu") + self.app_client = settings.get("app_client", "packlab-desktop") + self.sign_in_button = QPushButton(tr("Sign in"), self) + self.sign_in_button.clicked.connect(self.start_sign_in) + self.refresh_button = QPushButton(tr("Refresh list"), self) + self.refresh_button.clicked.connect(self.refresh) + self.server_url.setToolTip(tr("Server address")) + self.issuer.setToolTip(tr("Company sign-in (issuer)")) + connection = QHBoxLayout() + connection.addWidget(self.server_url, 1) + connection.addWidget(self.issuer, 1) + connection.addWidget(self.sign_in_button) + connection.addWidget(self.refresh_button) + self.status_label = QLabel(tr("Not connected."), self) + self.status_label.setWordWrap(True) + + self.table = QTableWidget(0, 6, self) + self.table.setObjectName("packlab.design_library.items") + self.table.setHorizontalHeaderLabels( + [ + tr("Name"), + tr("Kind"), + tr("Version"), + tr("Draft revision"), + tr("Released revision"), + tr("Checked out by"), + ] + ) + self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) + self.table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection) + self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + self.table.horizontalHeader().setStretchLastSection(True) + self.table.itemSelectionChanged.connect(self._selection_changed) + + self.new_kind = QLineEdit(self) + self.new_kind.setPlaceholderText(tr("Kind (e.g. bottle)")) + self.new_name = QLineEdit(self) + self.new_name.setPlaceholderText(tr("Name")) + self.create_button = QPushButton(tr("New draft"), self) + self.create_button.clicked.connect(self.create_item) + create = QHBoxLayout() + create.addWidget(self.new_kind) + create.addWidget(self.new_name, 1) + create.addWidget(self.create_button) + + self.note = QLineEdit(self) + self.note.setPlaceholderText(tr("Design note for this draft")) + self.checkout_button = QPushButton(tr("Check out"), self) + self.checkout_button.clicked.connect(self.checkout) + self.checkin_button = QPushButton(tr("Check in"), self) + self.checkin_button.clicked.connect(self.checkin) + self.save_button = QPushButton(tr("Save draft"), self) + self.save_button.clicked.connect(self.save) + self.reload_button = QPushButton(tr("Reload latest"), self) + self.reload_button.clicked.connect(self.reload_latest) + self.metric_status = QComboBox(self) + for status in RELEASE_METRIC_STATUSES: + self.metric_status.addItem(tr(METRIC_LABELS[status]), status) + self.release_button = QPushButton(tr("Release"), self) + self.release_button.clicked.connect(self.release) + edit = QHBoxLayout() # two rows: the Turkish labels must fit 1280 px + for widget in (self.checkout_button, self.checkin_button, self.reload_button): + edit.addWidget(widget) + edit.addStretch(1) + publish = QHBoxLayout() + for part in (self.save_button, self.metric_status, self.release_button): + publish.addWidget(part) + publish.addStretch(1) + self.message = QLabel("", self) + self.message.setObjectName("packlab.design_library.message") + self.message.setWordWrap(True) + + layout = QVBoxLayout(self) + layout.addLayout(connection) + layout.addWidget(self.status_label) + layout.addWidget(self.table, 1) + layout.addLayout(create) + layout.addWidget(self.note) + layout.addLayout(edit) + layout.addLayout(publish) + layout.addWidget(self.message) + self._set_connected(False) + + # --- connection -------------------------------------------------------------------------- + def start_sign_in(self) -> None: + server, issuer = self.server_url.text().strip(), self.issuer.text().strip() + if not (server and issuer): + self.status_label.setText(tr("Enter the server address and the company sign-in.")) + return + save_settings(self.data_root, {"server_url": server, "issuer": issuer}) + self.sign_in_button.setEnabled(False) + self.status_label.setText(tr("Signing in: finish in your browser.")) + bridge, loopback, app = self.bridge, self.allow_loopback_http, self.app_client + + def work() -> None: + # ponytail: the sign-in lives for this session only (not saved); the Warehouse + # page keeps the saved one, so two pages never rotate the same refresh token + try: + endpoints = discover(issuer, allow_loopback_http=loopback) + tokens = sign_in(endpoints, app) + source = TokenSource(endpoints, app, tokens) + _emit(bridge.done, ("signed_in", None, (server, source, _shown_name(tokens)))) + except Exception as error: # noqa: BLE001 - any failure re-enables Sign in + _emit(bridge.done, ("signed_in", None, error)) + + threading.Thread(target=work, name="packlab-design-signin", daemon=True).start() + + def connect_with( + self, + server: str, + token: Callable[[], str], + identity: str, + *, + allow_loopback_http: bool = False, + ) -> None: + """Use the server as ``identity`` (after sign-in; tests pass a fixed token).""" + try: + client = PackLabServerClient( + server, token, allow_loopback_http=allow_loopback_http or self.allow_loopback_http + ) + except ServerError as error: + self.status_label.setText(tr("Not connected: {reason}").format(reason=str(error))) + return + self.library, self.identity, self._editing = DesignLibrary(client), identity, None + self._set_connected(True) + self.status_label.setText( + tr("Connected as {who}.").format(who=identity) if identity else tr("Connected.") + ) + self.refresh() + + def _set_connected(self, connected: bool) -> None: + self.sign_in_button.setEnabled(True) + self._running = 0 + self._enable_actions(connected) + + def _enable_actions(self, enabled: bool) -> None: + for button in ( + self.refresh_button, + self.create_button, + self.checkout_button, + self.checkin_button, + self.save_button, + self.reload_button, + self.release_button, + ): + button.setEnabled(enabled) + + # --- actions ----------------------------------------------------------------------------- + def refresh(self) -> None: + self._run("list", lambda lib: lib.items()) + + def create_item(self) -> None: + kind, name = self.new_kind.text().strip(), self.new_name.text().strip() + if not (kind and name): + self.message.setText(tr("Enter a kind and a name.")) + return + self._run("created", lambda lib: lib.create(kind, name, {})) + + def checkout(self) -> None: + if (item := self._needs_item()) is not None: + self._run("checked_out", lambda lib: lib.checkout(item["id"])) + + def checkin(self) -> None: + if (item := self._needs_item()) is not None: + self._run("checked_in", lambda lib: lib.checkin(item["id"])) + + def save(self) -> None: + if (item := self._needs_item()) is None: + return + payload = {**_head(item).get("payload", {}), "note": self.note.text()} + assets = list(_head(item).get("assets", [])) # a note edit keeps the draft's files + version = int(item["version"]) # the version this person loaded: never a newer one + self._run("saved", lambda lib: lib.save(item["id"], version, payload, assets)) + + def release(self) -> None: + if (item := self._needs_item()) is None: + return + version, status = int(item["version"]), str(self.metric_status.currentData()) + self._run("released", lambda lib: lib.release(item["id"], version, status)) + + def reload_latest(self) -> None: + if (item := self._needs_item()) is not None: + self._run("reloaded", lambda lib: lib.item(item["id"])) + + def _needs_item(self) -> dict[str, Any] | None: + if self.library is None or self._editing is None: + self.message.setText(tr("Choose an item first.")) + return None + if self._editing.get("version") is None: # the server hides versions from readers + self.message.setText(tr("Your role can only read released items.")) + return None + return self._editing + + def _run(self, action: str, call: Callable[[DesignLibrary], Any]) -> None: + library, bridge = self.library, self.bridge # never the page: workers hold no widget + if library is None: + return + self._running += 1 + self._enable_actions(False) # one request at a time: no double click, no double write + + def work() -> None: + try: + result: object = call(library) + except Exception as error: # noqa: BLE001 - shown to the user + result = error + _emit(bridge.done, (action, library, result)) + + threading.Thread(target=work, name=f"packlab-design-{action}", daemon=True).start() + + # --- answers (GUI thread) ---------------------------------------------------------------- + def _finished(self, tagged: object) -> None: + action, library, result = cast(tuple[str, Any, Any], tagged) + if action == "signed_in": + if isinstance(result, Exception): + self.sign_in_button.setEnabled(True) + self.status_label.setText( + tr("Not connected: {reason}").format( + reason=str(result) or type(result).__name__ + ) + ) + else: + server, source, identity = result + self.connect_with(server, source, identity) + return + if library is not self.library: # an answer for an earlier connection + return + self._running = max(0, self._running - 1) + if self._running == 0: + self._enable_actions(True) + if isinstance(result, DesignConflict): + self._show_conflict(action, result) + return + if isinstance(result, ServerError) and (result.status == 0 or result.status >= 500): + self.message.setText( + tr( + "The server did not answer ({reason}). Press the same button again: " + "a retry is applied only once." + ).format(reason=result.code) + ) + return + if isinstance(result, Exception): + self.message.setText(tr("The server refused: {reason}").format(reason=str(result))) + return + if action == "list": + self._show_items(cast(list[dict[str, Any]], result)) + return + if action == "reloaded": + unsaved = self.note.text() + self._load_editor(cast(dict[str, Any], result)) + self.message.setText( + tr("Loaded version {version}. Your unsaved note was: {note}").format( + version=result["version"], note=unsaved + ) + ) + elif action == "released": + self._load_editor(cast(dict[str, Any], result)) + self.message.setText( + tr("Released revision {revision}; it can no longer change.").format( + revision=result["released_revision"] + ) + ) + elif action in ("created", "saved"): + self._load_editor(cast(dict[str, Any], result)) + self.message.setText( + tr("Saved as version {version}.").format(version=result["version"]) + ) + elif action == "checked_out": + self.message.setText(tr("Checked out to you.")) + elif action == "checked_in": + self.message.setText(tr("Checked in.")) + self.refresh() + + def _show_conflict(self, action: str, conflict: DesignConflict) -> None: + if conflict.holder and action in ("checked_out", "checked_in"): + text = tr("Not changed: {who} has this item checked out.").format(who=conflict.holder) + elif conflict.holder: + text = tr("Not saved: {who} has this item checked out.").format(who=conflict.holder) + else: + text = tr( + "Not saved: someone saved version {version} first. " + "Press Reload latest, then apply your change again." + ).format(version=conflict.server_version or "?") + self.message.setText(text) + + def _show_items(self, items: list[dict[str, Any]]) -> None: + self._items = items + editing = None if self._editing is None else self._editing["id"] + self.table.blockSignals(True) # a refresh never replaces what is in the editor + self.table.clearSelection() + self.table.setRowCount(len(items)) + for row, item in enumerate(items): + head = item.get("head_revision") + draft = head if head is not None and head != item.get("released_revision") else None + values = ( + item.get("name", ""), + item.get("kind", ""), + item.get("version"), + draft, + item.get("released_revision"), + item.get("checked_out_by"), + ) + for column, value in enumerate(values): + cell = QTableWidgetItem("" if value is None else str(value)) + cell.setData(Qt.ItemDataRole.UserRole, item.get("id")) + self.table.setItem(row, column, cell) + if item.get("id") == editing: + self.table.selectRow(row) + self.table.blockSignals(False) + + def _selection_changed(self) -> None: + row = self.table.currentRow() + cell = self.table.item(row, 0) if row >= 0 else None + chosen = None if cell is None else cell.data(Qt.ItemDataRole.UserRole) + item = next((i for i in self._items if i.get("id") == chosen), None) + if item is not None and (self._editing is None or self._editing["id"] != chosen): + self._load_editor(item) + self.message.setText("") + + def _load_editor(self, item: dict[str, Any]) -> None: + self._editing = item + self.note.setText(str(_head(item).get("payload", {}).get("note", ""))) + + +def _shown_name(tokens: TokenSet) -> str: + """The person's name from the ID token, for the status line only: read WITHOUT + verification and never used for access (the server checks the access token).""" + try: + body = (tokens.id_token or "").split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4))) + return str(claims.get("preferred_username") or claims.get("name") or "") + except (IndexError, ValueError, TypeError, AttributeError): + return "" + + +def _head(item: dict[str, Any]) -> dict[str, Any]: + revisions = item.get("revisions") or [] + return cast(dict[str, Any], revisions[-1]) if revisions else {} + + +__all__ = ["DesignLibraryView"] diff --git a/apps/windows-studio/src/packlab_studio/i18n.py b/apps/windows-studio/src/packlab_studio/i18n.py index 98299494..13e94ca5 100644 --- a/apps/windows-studio/src/packlab_studio/i18n.py +++ b/apps/windows-studio/src/packlab_studio/i18n.py @@ -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", diff --git a/apps/windows-studio/src/packlab_studio/navigation.py b/apps/windows-studio/src/packlab_studio/navigation.py index 5fcc8abb..c0eff567 100644 --- a/apps/windows-studio/src/packlab_studio/navigation.py +++ b/apps/windows-studio/src/packlab_studio/navigation.py @@ -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 @@ -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. @@ -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.", @@ -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,)), @@ -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")), } diff --git a/apps/windows-studio/src/packlab_studio/server_settings.py b/apps/windows-studio/src/packlab_studio/server_settings.py new file mode 100644 index 00000000..4225e800 --- /dev/null +++ b/apps/windows-studio/src/packlab_studio/server_settings.py @@ -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"] diff --git a/apps/windows-studio/src/packlab_studio/warehouse_view.py b/apps/windows-studio/src/packlab_studio/warehouse_view.py index ffbbcd5c..89ef0d93 100644 --- a/apps/windows-studio/src/packlab_studio/warehouse_view.py +++ b/apps/windows-studio/src/packlab_studio/warehouse_view.py @@ -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) @@ -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()} diff --git a/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0504_STUDIO_V01.md b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0504_STUDIO_V01.md new file mode 100644 index 00000000..66e95520 --- /dev/null +++ b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0504_STUDIO_V01.md @@ -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. diff --git a/core/src/packlab_core/design_library.py b/core/src/packlab_core/design_library.py new file mode 100644 index 00000000..5bb0f9be --- /dev/null +++ b/core/src/packlab_core/design_library.py @@ -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"] diff --git a/tests/core/test_design_library.py b/tests/core/test_design_library.py new file mode 100644 index 00000000..235e442e --- /dev/null +++ b/tests/core/test_design_library.py @@ -0,0 +1,172 @@ +"""PL-0504: design drafts, checkout and conflicts against a real local PackLab Server.""" + +from __future__ import annotations + +import threading +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any + +import pytest + +from packlab_core.design_library import DesignConflict, DesignLibrary +from packlab_core.server_sync import PackLabServerClient, ServerError +from packlab_server.api import PackLabServer +from packlab_server.auth import TokenRegistry +from packlab_server.store import LibraryStore + +USERS = { + "design-token": ("dee", "design"), + "design2-token": ("dan", "design"), + "wh-token": ("wally", "warehouse"), +} + + +@pytest.fixture() +def server(tmp_path: Path) -> Iterator[str]: + registry = TokenRegistry( + {TokenRegistry.hash_token(t): {"user": u, "role": r} for t, (u, r) in USERS.items()} + ) + store = LibraryStore(tmp_path / "server-data") + httpd = PackLabServer(("127.0.0.1", 0), store, registry) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{httpd.server_address[1]}" + finally: + httpd.shutdown() + httpd.server_close() + store.close() + + +def library(base: str, token: str) -> DesignLibrary: + return DesignLibrary(PackLabServerClient(base, lambda: token, allow_loopback_http=True)) + + +def test_second_editor_gets_a_conflict_never_an_overwrite(server: str) -> None: + dee, dan = library(server, "design-token"), library(server, "design2-token") + item = dee.create("bottle", "Bottle 500 ml", {"note": "v1"}) + seen_by_dan = dan.item(item["id"]) + saved = dee.save(item["id"], item["version"], {"note": "dee"}) + assert saved["version"] == item["version"] + 1 + with pytest.raises(DesignConflict) as conflict: + dan.save(item["id"], seen_by_dan["version"], {"note": "dan"}) + assert conflict.value.code == "version_conflict" + assert conflict.value.server_version == saved["version"] + assert dee.item(item["id"])["revisions"][-1]["payload"] == {"note": "dee"} + + +def test_checkout_held_by_another_user_is_refused(server: str) -> None: + dee, dan = library(server, "design-token"), library(server, "design2-token") + item = dee.create("cap", "Cap 28 mm", {}) + assert dee.checkout(item["id"])["holder"] == "dee" + with pytest.raises(DesignConflict) as refused: + dan.checkout(item["id"]) + assert refused.value.holder == "dee" + with pytest.raises(DesignConflict) as edit: + dan.save(item["id"], item["version"], {"note": "dan"}) + assert edit.value.holder == "dee" + dee.checkin(item["id"]) + assert dan.checkout(item["id"])["holder"] == "dan" + + +class _LosesFirstAnswer(PackLabServerClient): + """The server applies the first write but its answer never arrives.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.keys: list[str | None] = [] + self.lost = False + + def call(self, method: str, path: str, body: object = None, **kw: Any) -> tuple[int, Any]: + answer = super().call(method, path, body, **kw) + if method == "PUT": + self.keys.append(kw.get("key")) + if not self.lost: + self.lost = True + raise ServerError(0, "unreachable", "answer lost") + return answer + + +def test_a_retry_with_the_same_key_is_applied_once(server: str) -> None: + client = _LosesFirstAnswer(server, lambda: "design-token", allow_loopback_http=True) + dee = DesignLibrary(client) + item = dee.create("jar", "Jar", {}) + with pytest.raises(ServerError): + dee.save(item["id"], item["version"], {"note": "once"}) + again = dee.save(item["id"], item["version"], {"note": "once"}) # the user retries + assert client.keys[0] == client.keys[1] and client.keys[0] + assert again["version"] == item["version"] + 1 # not +2 + assert dee.item(item["id"])["version"] == item["version"] + 1 + next_edit = dee.save(item["id"], again["version"], {"note": "twice"}) + assert client.keys[2] != client.keys[0] # a new edit, a new key + assert next_edit["version"] == again["version"] + 1 + + +def test_released_revision_is_immutable(server: str) -> None: + dee = library(server, "design-token") + item = dee.create("tray", "Tray", {"note": "released"}) + released = dee.release(item["id"], item["version"], "METRIC_UNVERIFIED") + rev = released["released_revision"] + after = dee.save(item["id"], released["version"], {"note": "next draft"}) + assert after["head_revision"] == rev + 1 and after["released_revision"] == rev + first = next(r for r in after["revisions"] if r["revision"] == rev) + assert first["state"] == "RELEASED" and first["payload"] == {"note": "released"} + assert first["metric_status"] == "METRIC_UNVERIFIED" + with pytest.raises(DesignConflict): # a stale version cannot release over it either + dee.release(item["id"], released["version"]) + + +def test_observer_role_sees_no_drafts_and_cannot_edit(server: str) -> None: + dee, wally = library(server, "design-token"), library(server, "wh-token") + draft = dee.create("label", "Draft label", {}) + item = dee.create("case", "Case", {}) + dee.release(item["id"], item["version"]) + assert [i["name"] for i in wally.items()] == ["Case"] + with pytest.raises(ServerError) as hidden: + wally.item(draft["id"]) + assert hidden.value.status == 404 + with pytest.raises(ServerError) as forbidden: + wally.save(item["id"], 1, {"note": "x"}) + assert forbidden.value.status == 403 + assert {i["name"] for i in dee.items()} == {"Case", "Draft label"} + + +def test_a_note_save_can_keep_the_draft_files(server: str) -> None: + dee = library(server, "design-token") + sha = dee.client.call("POST", "/v1/objects", raw=b"mesh bytes")[1]["sha256"] + body = {"kind": "bottle", "name": "With mesh", "payload": {}, "assets": [sha]} + item = dee.client.call("POST", "/v1/items", body, key="create-with-mesh")[1] + kept = dee.save(item["id"], item["version"], {"note": "n"}, [sha]) + assert kept["revisions"][-1]["assets"] == [sha] + + +class _SendTogether(PackLabServerClient): + """Every PUT waits until all eight are about to be sent: they truly overlap.""" + + gate = threading.Barrier(8) + + def call(self, method: str, path: str, body: object = None, **kw: Any) -> tuple[int, Any]: + if method == "PUT": + self.gate.wait(timeout=10) + return super().call(method, path, body, **kw) + + +def test_concurrent_identical_saves_apply_once_without_errors(server: str) -> None: + dee = DesignLibrary(_SendTogether(server, lambda: "design-token", allow_loopback_http=True)) + item = dee.create("jar", "Jar", {}) + with ThreadPoolExecutor(8) as pool: + answers = list( + pool.map(lambda _: dee.save(item["id"], item["version"], {"note": "same"}), range(8)) + ) + assert {a["version"] for a in answers} == {item["version"] + 1} + assert dee.item(item["id"])["version"] == item["version"] + 1 + + +def test_release_refuses_an_unknown_metric_status_before_sending(server: str) -> None: + dee = library(server, "design-token") + item = dee.create("jar", "Jar", {}) + with pytest.raises(ValueError, match="metric_status"): + dee.release(item["id"], item["version"], "METRIC_VERIFIED") + assert dee.item(item["id"])["released_revision"] is None diff --git a/tests/studio/test_design_library_view.py b/tests/studio/test_design_library_view.py new file mode 100644 index 00000000..0452c7b5 --- /dev/null +++ b/tests/studio/test_design_library_view.py @@ -0,0 +1,147 @@ +"""PL-0504: the Design library page against a real local PackLab Server (static tokens).""" + +# ruff: noqa: F811 - pytest fixture "server" is imported and used as an argument + +from __future__ import annotations + +import time +from pathlib import Path + +import pytest +from tests.core.test_design_library import ( # noqa: F401 - fixture + _LosesFirstAnswer, + library, + server, +) + +from packlab_core.design_library import DesignLibrary +from packlab_studio.app import create_application +from packlab_studio.design_library_view import DesignLibraryView + + +@pytest.fixture() +def qt_app(monkeypatch): # noqa: ANN201 + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + return create_application(["packlab-design-library-test"]) + + +def _wait(app, condition, seconds: float = 15.0) -> None: # noqa: ANN001 + deadline = time.monotonic() + seconds + while not condition() and time.monotonic() < deadline: + app.processEvents() + time.sleep(0.02) + assert condition() + + +def _click(app, button) -> None: # noqa: ANN001 + _wait(app, button.isEnabled) # the page runs one request at a time + button.click() + assert not button.isEnabled() # busy: a second click cannot send a second write + + +def _row(view: DesignLibraryView, name: str) -> int: + return next(r for r in range(view.table.rowCount()) if view.table.item(r, 0).text() == name) + + +def test_designers_get_conflicts_not_overwrites(qt_app, server: str, tmp_path: Path) -> None: # noqa: ANN001 + dan = library(server, "design2-token") + view = DesignLibraryView(tmp_path) + view.connect_with(server, lambda: "design-token", "dee", allow_loopback_http=True) + view.new_kind.setText("bottle") + view.new_name.setText("Bottle 500 ml") + _click(qt_app, view.create_button) + _wait(qt_app, lambda: view.table.rowCount() == 1 and "version 1" in view.message.text()) + item_id = view._editing["id"] # type: ignore[index] + assert view.table.item(0, 3).text() == "1" and view.table.item(0, 4).text() == "" + + _click(qt_app, view.checkout_button) + _wait(qt_app, lambda: view.table.item(0, 5).text() == "dee") + with pytest.raises(Exception, match="checked_out_by_other"): + dan.checkout(item_id) + + view.note.setText("thinner neck") + _click(qt_app, view.save_button) + _wait(qt_app, lambda: "version 2" in view.message.text()) + _click(qt_app, view.checkin_button) + _wait(qt_app, lambda: view.table.item(0, 5).text() == "") + + dan.save(item_id, 2, {"note": "dan was first"}) # behind dee's back: version 3 + view.note.setText("dee again") + _click(qt_app, view.save_button) + _wait(qt_app, lambda: "someone saved version 3" in view.message.text()) + assert dan.item(item_id)["revisions"][-1]["payload"]["note"] == "dan was first" + + _click(qt_app, view.reload_button) + _wait(qt_app, lambda: "Loaded version 3" in view.message.text()) + assert view.note.text() == "dan was first" and "dee again" in view.message.text() + _click(qt_app, view.release_button) + _wait(qt_app, lambda: "Released revision 1" in view.message.text()) + _wait(qt_app, lambda: view.table.item(0, 4).text() == "1") + + dan.checkout(item_id) + _click(qt_app, view.save_button) + _wait(qt_app, lambda: "dan has this item checked out" in view.message.text()) + + +def test_observer_sees_released_items_only(qt_app, server: str, tmp_path: Path) -> None: # noqa: ANN001 + dee = library(server, "design-token") + dee.create("label", "Draft label", {}) + item = dee.create("case", "Case", {}) + dee.release(item["id"], item["version"]) + view = DesignLibraryView(tmp_path) + view.connect_with(server, lambda: "wh-token", "wally", allow_loopback_http=True) + _wait(qt_app, lambda: view.table.rowCount() == 1) + assert view.table.item(_row(view, "Case"), 0).text() == "Case" + view.table.selectRow(0) + view.note.setText("x") + _wait(qt_app, view.save_button.isEnabled) + view.save_button.click() + assert "only read released items" in view.message.text() # the server also says 403 + + +def test_actions_need_a_connection_and_an_item(qt_app, tmp_path: Path) -> None: # noqa: ANN001 + view = DesignLibraryView(tmp_path) + assert not view.save_button.isEnabled() + view.save() + assert "Choose an item" in view.message.text() + view.server_url.setText("") + view.start_sign_in() + assert "Enter the server address" in view.status_label.text() + + +def test_a_note_save_keeps_the_draft_files(qt_app, server: str, tmp_path: Path) -> None: # noqa: ANN001 + dee = library(server, "design-token") + sha = dee.client.call("POST", "/v1/objects", raw=b"mesh bytes")[1]["sha256"] + body = {"kind": "bottle", "name": "With mesh", "payload": {}, "assets": [sha]} + item = dee.client.call("POST", "/v1/items", body, key="create-with-mesh")[1] + view = DesignLibraryView(tmp_path) + view.connect_with(server, lambda: "design-token", "dee", allow_loopback_http=True) + _wait(qt_app, lambda: view.table.rowCount() == 1) + view.table.selectRow(0) + view.note.setText("note only") + _click(qt_app, view.save_button) + _wait(qt_app, lambda: "version 2" in view.message.text()) + head = dee.item(item["id"])["revisions"][-1] + assert head["payload"] == {"note": "note only"} and head["assets"] == [sha] + + +def test_a_lost_answer_is_retried_once_from_the_page( + qt_app, + server: str, + tmp_path: Path, # noqa: ANN001 +) -> None: + dee = library(server, "design-token") + item = dee.create("jar", "Jar", {}) + view = DesignLibraryView(tmp_path) + view.connect_with(server, lambda: "design-token", "dee", allow_loopback_http=True) + _wait(qt_app, lambda: view.table.rowCount() == 1 and view.save_button.isEnabled()) + client = _LosesFirstAnswer(server, lambda: "design-token", allow_loopback_http=True) + view.library = DesignLibrary(client) + view.table.selectRow(0) + view.note.setText("once") + _click(qt_app, view.save_button) + _wait(qt_app, lambda: "did not answer" in view.message.text()) + _click(qt_app, view.save_button) # the same edit again + _wait(qt_app, lambda: "version 2" in view.message.text()) + assert client.keys[0] == client.keys[1] + assert dee.item(item["id"])["version"] == 2 # applied once