Commit Graph
1081 Commits
Author SHA1 Message Date
maziggy 1677efb2c6 fix(labels): replace incorrect ams_30x15 preset with correct AMS holder sizes (#1426)
Reporter — the same person who originally requested the labels
  feature in #809 — discovered that the ams_30x15 preset's 30x15 mm
  dimension didn't actually fit any variant of the MakerWorld AMS
  Filament Label Holder (model 752566) it advertised. Two new
  presets replace it:

  - ams_holder_74x33 (74 x 33 mm) matches the printable label STL
    bundled in the MakerWorld project
  - ams_holder_75x55 (75 x 55 mm) fits the cardstock-insert variant
    the reporter validated on bench

  Both cross the 20 mm height threshold so they land in the roomy
  layout branch — swatch on the left, QR on the right, multi-line
  text (brand, material, hex code, spool ID) in the middle. The
  old 30x15 mm preset couldn't fit a QR code; the new ones do.

  No DB migration: the preset name was never persisted. Callers
  scripting the old ams_30x15 value get a clean 422 at the route's
  Literal validator with the new valid values listed.

  i18n: replaced inventory.labels.templates.ams.{label,hint} with
  amsHolderSmall and amsHolderLarge across all 8 locales with real
  translations; parity guard cleaned of the stale English-fallback
  cognate entries. Parity holds at 4856 leaves per locale.

  Tests: backend label renderer + integration tests cover both new
  presets; LabelTemplatePickerModal test updated for the 6-button
  grid and the new template value in the API-call assertion.
2026-05-19 13:14:03 +02:00
dependabot[bot] 18975b0dc2 chore(deps-dev): bump brace-expansion (#1421)
Bumps the npm_and_yarn group with 1 update in the /frontend directory: [brace-expansion](https://github.com/juliangruber/brace-expansion).
2026-05-19 12:21:43 +02:00
maziggy 9bcaafbc1a fix(assign-spool): refresh printer status after assignment so card updates without manual Force-refresh (#1414 follow-up)
Reporter (@snozzlebert on A1 mini external slot) saw the
  Filament page Location column update correctly after Assign
  Spool, but the Printer card kept showing "Empty slot" until
  they manually pressed Force-refresh. MQTT command was going
  through fine; gap was client-side.

  AssignSpoolModal's two onSuccess callbacks invalidated the
  inventory / slot-assignment queries but never invalidated
  ['printerStatus', printerId] and never issued a pushall. For
  Bambu RFID-tagged spools the printer echoes the new tray_type
  on its own; for non-RFID spools and A1 mini external slots
  the firmware doesn't volunteer that state change.

  Added nudgePrinterRepublish() helper called from both onSuccess
  paths: api.refreshPrinterStatus(printerId) to issue the pushall
  (same call the Force-refresh button uses) plus invalidate
  printerStatus so the refetch lands. Refresh failures are
  swallowed — the assignment itself succeeded; a stale-cache
  nudge that didn't go through shouldn't surface as "assign
  failed". Same pattern as ConfigureAmsSlotModal since #1235,
  with the extra pushall because assign-spool affects firmware-
  side state.
2026-05-19 11:41:53 +02:00
maziggy e2df0fc601 fix(ams): physically-empty slots report state=9 and render distinctly from reset slots (#1322 follow-up)
Two-part fix for the #1322 follow-up by @RosdasHH.

  Data layer.
  The previous narrow heuristic in printer_manager.py only caught
  the bare {"id": N} payload firmware sends right after a printer
  restart. In steady-state operation — and on the more common
  post-Reset-Slot path on P1S and A1 Mini BMCU — firmware sends a
  populated payload and signals emptiness via the tray_exist_bits
  bitmask. We already parse that bitmask and use it to wipe stale
  tray_type / tray_color / tag_uid fields, but never touched the
  state field, so downstream readers (printers.py API serializer,
  inventory.py's tray_state in {9, 10} short-circuit, AMS card)
  saw state: null and had to guess from absent payload fields.

  Fix lifts tray["state"] = 9 (int — not "9"; inventory.py:1358
  uses == not `in {...}` so a string would silently miss and the
  reporter's deadlock would come back) to the outer `if not
  slot_exists` branch, so the bitmask path now writes the
  canonical "no spool" code for every empty slot regardless of
  stale fields. The narrow heuristic in printer_manager.py:797
  stays as belt-and-suspenders for any MQTT path that doesn't
  flow through _handle_ams_data.

  UI layer.
  With the data flow now consistent, the AMS slot card renders
  physically-empty slots distinctly from reset slots, per
  reporter's mockup. New helper getEmptySlotKind(tray) returns
  "physical" (state ∈ {9, 10}), "reset" (any other empty state),
  or null (loaded). The inline label below the slot circle reads
  "Empty" for physical and "Reset" for reset; pre-fix both showed
  an em-dash. FilamentSlotCircle gains an emptyKind prop that
  picks a quieter dashed border colour for reset slots so the
  visual hierarchy reads loaded > reset > physically empty.
  EmptySlotHoverCard gains a kind prop and switches between
  "Empty slot" and "Slot reset — no spool assigned".
2026-05-19 11:21:03 +02:00
maziggy fc32b388de fix(stats): align Filament Used / By Time / Success Rate with Total Consumed and Total Prints (#1390 follow-up)
Three independent root causes behind the divergences the reporter
  flagged after the archived-spool fix shipped — fixed together.

  (1) Filament Used vs Total Consumed.
  _compute_run_filament_grams returned the slicer estimate for completed
  prints even when inventory had measured the actual AMS weight delta.
  That made Stats and Inventory two different sources of truth: Stats
  showed slicer-estimate grams, Inventory showed AMS-tracked grams, and
  the two never agreed. Reordered the helper so the tracked spool delta
  (same source that drives weight_used behind Total Consumed) takes
  priority for every status. Slicer estimate stays as the fallback when
  no inventory was tracked; partial-progress scale stays as the fallback
  for failed/cancelled with no tracker. The _run_cost block right next
  to it was already tracker-first; only filament_used_grams was
  inconsistent.

  (2) Printer Stats By Time vs Quick Stats Print Time.
  /archives/slim only set actual_time_seconds when status == "completed".
  For failed/cancelled rows the frontend fell back to print_time_seconds
  (the slicer's full-print estimate — wrong number for a print that
  failed at 15%). Quick Stats already summed elapsed duration across
  all statuses, so the two halves of the page disagreed by the
  (estimate - actual-elapsed) gap on every non-completed event. Dropped
  the completed-only gate; failed/cancelled now report measured elapsed.

  (3) Success Rate %.
  Was successful / (successful + failed), excluding cancelled / stopped
  from the denominator. With "Total Prints: N" displayed right above
  the gauge that produced confusing numbers — 4 successful, 0 failed,
  48 cancelled showed 100% out of an apparent 52 prints. Switched to
  successful / total_prints — matches the count the user reads from
  the widget header.
2026-05-19 10:53:36 +02:00
maziggy 43510b9fc6 fix(inventory): Total Consumed includes archived spools and eraser works on archived (#1390 follow-up)
Reporter (@IndividualGhost1905) saw archived spools' consumption
  silently drop out of the Total Consumed running total — un-archiving
  put it back. The stat is lifetime-since-reset, not currently-
  available, so archived consumption belongs in it.

  InventoryPage.tsx stats loop split: totalConsumed sums over all
  spools (active + archived); totalWeight, lowStock, byMaterial,
  activeCount keep their archived-skip.

  Also fixes two adjacent UX gaps the reporter surfaced:

  - Per-spool eraser button was gated on !archived_at && weight_used
    > 0. Dropped the archived gate so an archived spool's tracking
    counter can be zeroed without un-archiving first.
  - activeSpoolIds (target of "Reset all usage" bulk action) excluded
    archived. Renamed to resetableSpoolIds and broadened to include
    archived so Reset-all genuinely zeroes the now-broader stat in
    one click. Backend reset endpoints already accept archived IDs.
2026-05-18 13:06:07 +02:00
maziggy fcd1801aab feat(inventory): sort-by-colour toggle in label-print modal (#1410)
Reporter asked for an option to order printed label sheets by colour
  instead of spool number so multi-colour rolls group related colours
  together physically on the sheet.

  Backend (labels.py) already preserves caller order, so this is
  frontend-only. LabelTemplatePickerModal gains a "Sort: By ID / By
  colour" chip pair next to the material filter. Colour mode converts
  each spool's rgba to HSL: chromatic colours (s >= 0.1) cluster in
  bucket 0 ordered by hue 0..360, achromatic colours go in bucket 1
  ordered by lightness so neutrals trail the rainbow black -> white.
  Stable tiebreaker on spool ID.

  Also fixes a latent issue exposed by the same code: the submit was
  always re-sorting selected IDs ascending, which would have clobbered
  any frontend order. Submit now uses sortedSpools.filter().map() so
  the visible order flows through to the PDF.

  Session-only state; toggle resets to "By ID" each time the modal
  opens. 3 new i18n keys translated across all 8 locales (parity 4852
  leaves). 2 new modal tests pin the colour-sort payload order and
  the unchanged ID-default. 17 modal tests + i18n parity + build all
  green.
2026-05-18 12:53:07 +02:00
Chanakyan ed5af66839 feat(inventory): show spool ID in edit modal and AMS hover card (#1385) (#1402)
feat(inventory): show spool ID in edit modal and AMS hover card (#1385)
2026-05-18 12:34:42 +02:00
Ben Halverson feb44a9dc1 Merge pull request #1416 from benhalverson/fix/open-in-slicer
Fix library Open in Slicer URLs for extensionless filenames
2026-05-18 11:59:34 +02:00
maziggy 134847a3bd feat(camera): in-app diagnostic for "Connection lost" (#1395 follow-up)
Step 2 of the camera architecture overhaul agreed after #1395. When
  the camera viewer hits its error state OR before a print at any
  time, a Diagnose button runs a staged check against the printer and
  renders the result inline: which stage failed, how long it took,
  and a translated remediation hint. Cuts off the "user opens a
  'camera broken' ticket → ask for support bundle → triage" loop at
  the user's screen.

  Backend

  - New `backend/app/services/camera_diagnose.py` orchestrator with
    CameraDiagnoseResult / CameraDiagnoseStage dataclasses.
  - New POST /printers/{id}/camera/diagnose route in camera.py.
  - Stages:
      tcp_reachable — TCP socket open to 322 (RTSP) / 6000 (chamber)
        with 3 s timeout. Distinguishes timeout, refused, and host-
        unreachable into distinct summary codes so the frontend can
        show a precise remediation (firewall vs LAN-only off vs
        wrong IP).
      first_frame — captures one JPEG end-to-end via the existing
        capture_camera_frame_bytes pipeline. Auth + RTSP handshake +
        first keyframe collapse into one stage; the user-facing
        answer is the same regardless of which sub-layer failed.
  - Live-stream shortcut: when a viewer is currently watching the
    camera with a buffered frame < 10 s old, the diagnostic skips
    the real test and returns live_stream_active_healthy. Opening a
    fresh socket would kick the live viewer off on single-camera-
    connection firmwares (the #1348 reconnect-storm trigger), so we
    trust the real-world evidence instead.
  - Response surfaces protocol, port, and profile name for support
    triage — lets us ask "what does your modal say?" instead of
    "send the support bundle".

  Frontend

  - New CameraDiagnoseModal renders one row per stage with green-
    check / red-X / grey-skipped icons, the per-stage duration in
    ms, a remediation banner styled by overall status, and a Run
    again button.
  - Two entry points:
      1. The viewer's error overlay grows a Diagnose button next to
         Retry. Retry stays the primary action; Diagnose is the
         escape hatch for users who can't see what's wrong.
      2. A stethoscope icon in the viewer's always-visible control
         bar, between Refresh and Fullscreen. Pre-flight testing
         ("did my firmware update break the camera?", "is the
         camera up before I send a print?") doesn't require waiting
         for the stream to fail first.
  - Also lifted the previously-hard-coded "Camera unavailable" /
    "Retry" strings into camera.unavailable / camera.retry so the
    error UI is fully translated alongside the new keys.
2026-05-18 10:52:02 +02:00
maziggy b9340389d3 fix(archives): print-log filename column expands instead of clipping at 200px (#1406)
Reporter on a 27" monitor saw long filenames truncated even though
  the Print Log table had plenty of unused horizontal space. The
  print-name `<span>` had a hard `truncate max-w-[200px]` cap that
  ignored viewport width entirely.

  Replaced with `break-words` + a `title` attribute, dropping the
  explicit max-width so the column auto-sizes to content. On wide
  screens the full name shows on a single line; on narrow ones it
  wraps inside the cell instead of forcing horizontal scroll. The
  `title` hover preserves the original tooltip affordance for the
  edge case where a really long name still gets wrapped.
2026-05-18 10:03:41 +02:00
maziggy 8d52c713ef fix(inventory): hex colour field accepts character-by-character typing (#1407)
Reporter typed into the Add Spool modal's hex colour input and only
  the first character stuck - everything after that defaulted to "0"
  with no way to override except by pasting the full hex.

  Pre-fix, the #1055 fix aggressively normalized the input to a valid
  8-char rgba on every keystroke. After typing the first char the
  controlled input value snapped to e.g. "A00000", the browser placed
  the cursor at the end, and the user's next keystroke landed at
  position 7. The #1055 fix's 7-char branch then truncated that byte
  away, leaving the form state unchanged - so the user appeared to
  type nothing.

  Fix splits the typing-state from the backend-state:

  - The hex input gets its own `hexDraft` useState holding 0-6 chars
    freely. Typing one char at a time works naturally because the
    controlled value matches what the user typed.
  - `updateField('rgba', ...)` fires only when the draft reaches a
    complete 6-char RGB (commits as `<6chars>FF`). Below that, the
    form state stays untouched - no mid-keystroke snap.
  - On blur, a partial 1-5 char draft is right-padded with `0` and
    committed. Keeps the #1055 invariant: anything reaching the
    backend is exactly 8 hex chars matching /^[0-9A-F]{8}$/.
  - A `useEffect` resyncs the draft when an external action (color
    picker, swatch click, edit-mode load) changes the canonical hex.
  - Paste of 7-/8-char strings truncates to the leading RGB. Bambu
    filaments are opaque; the UI never exposed an alpha affordance,
    so dropping the (undocumented) paste-with-alpha case is fine.
2026-05-18 09:57:07 +02:00
maziggy e61a454a0f fix(inventory): "Reset usage to 0" preserves remaining in both modes (#1390)
Reporter saw a 544 g spool jump to 1000 g after pressing the eraser.
  "Spools and remaining weights are not changed" - the dialog promised
  this; the implementation did the opposite. Root cause was an
  architectural conflation: `weight_used` did double duty as the
  resettable "consumed since tracking started" counter AND as the basis
  for the displayed remaining (`label_weight - weight_used`), so zeroing
  it correctly cleared the stat but unavoidably reset remaining to full.

  Spoolman has separate `used_weight` and `remaining_weight` fields, so
  the API call there was correct - but Bambuddy's frontend was also
  computing remaining as `label_weight - weight_used` for Spoolman
  spools (ignoring Spoolman's real `remaining_weight` field), so the
  same visual bug bit there too. Inventory-mode parity required fixing
  both halves in one drop.

  Internal mode

  - New `weight_used_baseline` column (Float DEFAULT 0) on `spool`.
  - Reset stamps `baseline = weight_used` and leaves `weight_used` alone.
  - Displayed consumed = `weight_used - baseline`; remaining =
    `label_weight - weight_used` (unchanged).
  - Subsequent prints continue to grow `weight_used`, so the resettable
    counter naturally tracks post-reset delta and remaining keeps
    decrementing across the reset.

  Spoolman mode

  - `_map_spoolman_spool` now reads Spoolman's `remaining_weight` field
    and returns a synthetic `weight_used = label - remaining` so the
    frontend's remaining calc matches Spoolman's real stored value;
    `weight_used_baseline = synthetic - real_used_weight` so the consumed
    counter (`weight_used - baseline`) matches Spoolman's `used_weight`.
  - Fallback path (no `remaining_weight` set) preserves the old behavior.
  - Related fix: `update_spool` (Spoolman PATCH) was deriving the default
    `weight_used` from `used_weight`, so editing unrelated fields AFTER
    a reset would patch Spoolman with `remaining_weight = label - 0 =
    label`, trampling the real value. Now derives from
    `remaining_weight` so non-weight edits preserve physical state.

  Frontend

  - `InventoryPage` `totalConsumed` aggregate switched to
    `Math.max(0, weight_used - (weight_used_baseline ?? 0))`.
  - `ForecastPanel` `computeDeltaRate`, `totalUsedG`, and the per-spool
    "consumed" table cell got the same treatment so forecast and
    inventory aggregates stay coherent across a reset.
  - `?? 0` keeps pre-migration installs rendering correctly until
    `init_db()` runs the idempotent ALTER TABLE.

  Migration

  - `ALTER TABLE spool ADD COLUMN weight_used_baseline REAL DEFAULT 0`
    via `_safe_execute` - SQLite and Postgres both accept it; verified
    end-to-end on Postgres 16.
2026-05-18 08:51:27 +02:00
maziggy b51598ea69 fix(printers): refuse to add a printer when the MQTT probe fails (#empty-card-reports)
Several support reports traced back to one root cause: a mistyped access
  code in Add Printer left an empty card on the dashboard. POST /printers/
  was persisting the row first, then firing connect_printer() fire-and-forget.

  Now we test_connection() BEFORE the insert; failure returns HTTP 400 and
  the row is never written.

  Structured error response -- detail={"code", "message"} -- so the toast
  shows the localized message instead of the English fallback. New
  ApiError.code field on the frontend; printers.toast.connectionFailedNotAdded
2026-05-17 15:42:19 +02:00
maziggy 48a7024b96 security(github-backup): refuse to save against a non-private repository
While auditing real-world Bambuddy backup repos on GitHub I found
  several left public. That's a serious leak: the settings backup only
  filters bambu_cloud_token and auth_secret_key, so mqtt_username,
  mqtt_password, ha_token, prometheus_token, bambu_cloud_email,
  external_url, and the printer access codes (via K-profiles) were going
  to whatever visibility the user picked.

  Hard guard at every save and re-checked on every push:

  - POST /github-backup/config and PATCH /github-backup/config (when URL,
    token, or provider changes) run a connection test internally and
    return 400 unless is_private comes back True.
  - run_backup() re-checks before each scheduled or manual push, so a
    repository that flipped from private to public gets a clear
    "Backup aborted: the target repository is no longer private" failure.

  Each provider's test_connection now returns is_private (GitHub /
  Gitea / Forgejo read data.private, GitLab reads visibility=="private";
  "internal" is treated as non-private). None means "couldn't determine"
  and is also rejected -- safer to fail closed.

  Frontend renders visibility inline on Test Connection: green check when
  private, red warning panel listing every credential at risk when public,
  yellow when unknown.

---

  ui(github-backup): show save-failure messages inline on the card

  The new "repository is not private" rejection message is ~250 characters
  listing every credential the backup carries (MQTT password, HA token,
  Prometheus token, Bambu Cloud email, printer access codes), which clips
  badly in a toast.

  Both the initial-setup save and the debounced autosave now stash the
  backend's error message into a saveError state and render it as a red
  inline banner above the test-result block, with whitespace-pre-wrap so
  the full message stays readable. The banner clears on success, on the
  next save attempt, and when the user starts editing URL / token / provider
  -- the three fields whose changes invalidate the privacy check -- so it
  doesn't linger after the user has already addressed the cause.

  Short success toasts (Settings saved, Token updated, Backup enabled) are
  unchanged.
2026-05-17 15:30:05 +02:00
maziggy b07122e395 fix(inventory): "Print labels..." works in Spoolman mode (#1390 follow-up)
The LabelTemplatePickerModal correctly branches on a spoolmanMode prop
  and the /spoolman/labels backend endpoint exists, but InventoryPage was
  instantiating the modal with spoolmanMode={false} hard-coded. Every
  click in Spoolman mode resolved to /inventory/labels with Spoolman spool
  IDs and returned 404 "Spool(s) not found".

  The hard-coded value came with a stale comment from the original label
  printing PR that said "Spoolman path hands users an iframe to Spoolman
  so the per-spool button never shows in that context" -- that assumption
  stopped being true when the unified inventory UI shipped.

  Pass the actual spoolmanMode value through, drop the stale comment.

  The existing LabelTemplatePickerModal.test.tsx already covers both
  branches at the component level (line 209: "routes to the Spoolman
  endpoint when spoolmanMode is true"). The gap was that no test exercised
  the InventoryPage wiring.
2026-05-17 15:11:42 +02:00
maziggy 8b9efd0160 fix(inventory): "Reset usage to 0" works in Spoolman mode too (#1390)
First cut of this action only wired the built-in inventory path, so the
  eraser buttons vanished when the user switched to Spoolman mode. Mirror
  the endpoints on the Spoolman router:

  - POST /spoolman/inventory/spools/{id}/reset-usage
  - POST /spoolman/inventory/spools/reset-usage-bulk

  Both route to a new SpoolmanClient.reset_spool_usage() helper that PATCHes
  /spool/{id} with used_weight=0. The bulk variant keeps the same typo-wipe
  guard (rejects empty/missing spool_ids), and individual Spoolman failures
  are logged + counted out without aborting the batch.

  InventoryPage mutations now switch on spoolmanMode to pick the right
  client method, and the three "spoolmanMode ? undefined : ..." gates on
  the eraser buttons are gone.
2026-05-17 15:04:31 +02:00
maziggy 74dcaf5142 refactor(settings): Spool Catalog now identical in internal and Spoolman modes
Drop the Spoolman-mode hijack that replaced the local spool tare catalog
  with an inline filament editor — two unrelated concepts that should never
  have shared a card. Spool Catalog now renders the same way in both modes;
  Spoolman users edit filament name and spool_weight in Spoolman's own UI.

  Also eliminates the GET /spoolman/inventory/filaments 400 probe that fired
  on the Filament settings page whenever Spoolman was disabled.

  - frontend/src/components/SpoolCatalogSettings.tsx rewritten (752 -> 444 lines)
  - frontend/src/components/SpoolWeightUpdateModal.tsx deleted (orphan)
  - SpoolCatalogSettings test file rewritten to match the simplified component
  - PATCH /spoolman/inventory/filaments/{id} backend route left in place
2026-05-17 13:48:05 +02:00
maziggy bff240e90a fix(uploads): pre-flight validation for 3MF/gcode + visible upload errors (#1401)
Reporter @iitazz uploaded slicer output to Bambuddy, clicked Print,
  and the printer rejected every job with "Printing stopped because
  the printer was unable to parse the 3mf file". Support bundle showed
  the stored library file ended in .gcode (not .gcode.3mf), and
  background_dispatch.py appends ".3mf" to filenames that don't
  already end in .gcode.3mf/.3mf — so raw gcode shipped to the printer
  named .gcode.3mf and the firmware's 3MF parser choked. Same shape
  also surfaced as "File is not a zip file" on Bambuddy's own plate
  parser.

  New validate_print_file_upload() helper in library.py runs at upload
  time:
    - Reject filenames ending in .gcode (but not .gcode.3mf) with a
      clear message — Bambu printers need .gcode.3mf zip containers,
      not raw gcode.
    - For .3mf / .gcode.3mf uploads, verify body starts with PK\x03\x04
      (ZIP magic); reject otherwise pointing at the slicer's "Export
      Plate Sliced File" action.

  Applied to every relevant upload route: POST /library/files (covers
  File Manager + printer-card drag-drop), POST /archives/upload,
  POST /archives/upload-bulk (rejects per-row so one bad file doesn't
  abort the batch), POST /archives/{id}/source, POST /archives/upload-source.
  Runs after _resolve_upload_destination so folder-permission errors
  (403 readonly, 400 missing-path, 409 collision) still take precedence.
  STL / image / other non-print uploads bypass the validator.

  FileUploadModal frontend fix: the modal auto-closed after every
  batch regardless of per-file results, so a 400 rejection was captured
  but invisible. Now:
    - Errors render inline as red text under the file row instead of
      as a hover-only title tooltip.
    - Modal stays open if any file ended with status='error', so the
      user can read the backend's remediation message before closing.
    - Successful-only batches still auto-close as before.

  UploadModal (bulk archive) was already showing inline errors and
  not auto-closing — no change needed there.
2026-05-17 13:09:58 +02:00
maziggy 4ccde42e39 feat(inventory): storage location filter chip (#1400)
Reporter pgladel manages multiple physical filament storage
  locations and wanted to narrow the inventory list to a specific
  location without typing a search query each time.

  Adds a new Storage Location dropdown chip on the inventory page,
  next to the existing Material / Brand / Category / Spool Name
  filters. Distinct values are pulled from the spool list with
  .trim() so accidental trailing whitespace doesn't render as a
  separate option. A "No location set" entry appears when at least
  one spool has an empty storage_location (mirrors the categoryNone
  group). Chip self-hides when no spool has a storage location set.

  Same shape as the Category chip from #729 — clear-all-filters and
  hasActiveFilters both include the new state.

  i18n: reuses existing inventory.storageLocation label, adds
  inventory.storageLocationNone in all 8 locales. Parity check
  holds at 4818 leaves per locale. 24 InventoryPage tests still
  pass, frontend build clean.
2026-05-17 12:34:46 +02:00
maziggy 6f2cec5eb3 feat(smart-plugs): auto-off after AMS drying completes (#1349)
Reporter Kyobinoyo asked for the equivalent of the existing
  print-finish auto-off but triggered when AMS drying ends.

  Two new SmartPlug columns: auto_off_after_drying (default false),
  off_delay_after_drying_minutes (default 10 — AMS chamber is hot
  post-cycle so longer cooldown than the print-finish default of 5).
  SQLite + Postgres migrations both idempotent.

  Trigger lives in BambuMQTTClient — per-AMS _previous_dry_times
  tracks the dry_time > 0 → 0 falling edge and fires a new
  on_drying_complete(ams_id) callback. Plumbed through
  PrinterManager.set_drying_complete_callback to
  SmartPlugManager.on_drying_complete(printer_id, db), which walks
  linked plugs and respects the per-plug toggle. Catches queue,
  ambient and manual drying identically because it observes firmware
  state, not scheduler intent.

  Frontend: single "Auto Off After Drying" toggle + delay input on
  the smart plug card, next to the existing print-finish auto-off
  section.

  Per-AMS plug routing (separate plug for AMS only, per-AMS targeting
  on dual-AMS printers) deferred — Bambuddy's plug model is
  plug→printer, so the trigger fires whenever any AMS on the linked
  printer finishes a cycle.
2026-05-17 12:26:42 +02:00
maziggy e7045597bc fix(archives): bulk and auto purge now honour the soft / hard delete choice from #1343 (#1390 follow-up)
Reporter IndividualGhost1905 followed up after the #1378 / #1343
  backfill landed and pointed at the next inconsistency: the per-
  archive delete dialog has had a "Also remove this print from Quick
  Stats" checkbox since #1343, but the "Purge Old" button and the
  scheduled daily auto-purge sweeper both ignored that choice and
  hard-deleted unconditionally. From the user side this looked like
  "automatically deleted from statistics without any warning" — half-
  true, and the inconsistency was real either way.

  The actual current shape (before this fix):

    - POST /archives/purge -> archive_purge_service.purge_older_than
      -> ArchiveService.delete_archive (hard). Archive row dropped.
      Linked PrintLogEntry rows have ON DELETE SET NULL so they
      survive as orphans with archive_id=NULL. Quick Stats keeps the
      filament / cost / energy contribution because the log rows are
      still there, but the archive-list-iterating widgets (Filament
      Trends, By Material, Color Distribution, Printer Stats) lose
      the row, and Time Accuracy loses its join target. Visibly
      inconsistent.
    - Scheduled _maybe_run_auto_purge -> same code path, same effect.
    - Single-archive DELETE /archives/{id} -> already takes
      purge_stats=true|false (default false=soft) and routes either
      soft_delete_archive (keeps everything, flips deleted_at) or
      deletes PrintLogEntry rows first + hard-deletes archive.

  The fix threads the same purge_stats flag through every bulk surface
  with soft as the default, matching the single-archive default:

  Backend:
    - archive_purge_service.purge_older_than(..., purge_stats=False)
      -> per-row soft_delete_archive when False, per-row
      PrintLogEntry deletion + delete_archive when True. Each runs in
      its own session (same pattern the sweeper already used).
    - preview_purge gains the same kwarg so the eligible-count
      matches what an actual run would touch: soft mode excludes
      already-soft-deleted rows, hard mode counts them as eligible
      for promotion.
    - get_settings / set_settings now persist archive_auto_purge_stats
      (default False). _maybe_run_auto_purge reads it on every tick.
    - ArchivePurgeRequest / ArchivePurgeResponse / ArchivePurgeSettings
      schemas extended.
    - Route /archives/purge accepts the body flag, /purge/preview
      accepts the query param, /purge/settings GET + PUT echo the
      setting.

  Frontend:
    - "Purge old archives" modal: new "Also remove from statistics"
      checkbox under the preview, unchecked by default. Plumbed into
      the preview query key + the execute mutation.
    - Settings -> Archives auto-purge card: matching toggle next to
      the days slider, disabled when auto-purge itself is off.
    - api.previewArchivePurge / api.executeArchivePurge accept the
      flag; ArchivePurgeSettings type gains purge_stats.
    - All 8 locales (en, de, fr, it, ja, pt-BR, zh-CN, zh-TW) get
      new purgeStatsLabel / purgeStatsHint / purgeStatsDescription
      keys, plus rewritten effect / warning copy in archivePurge and
      archiveAutoPurge to reflect that the default no longer
      "permanently removes from the database" but instead hides the
      row + removes files while keeping Quick Stats intact. i18n
      parity check clean: 4814 keys across all 8 locales, no fallback.

  Behaviour change for existing users on auto-purge: the sweeper used
  to hard-delete by default and now soft-deletes by default. After
  the upgrade those installs start *preserving* more data in Quick
  Stats rather than losing it — safer direction of the two, but worth
  the explicit call-out. Anyone who wants the old behaviour ticks the
  new toggle once and it persists.
2026-05-17 10:54:28 +02:00
maziggy 0ddf0925b7 chore(cloud): clarify access-token hint and document the MakerWorld cookie path for China-region accounts (#1396)
Reporter wintsa123 (China-region user, bambulab.cn) couldn't log
  into Bambuddy. Looked like a code bug; turned out the code is fine
  and only the docs were wrong.

  What's already there (no change needed):

  - PR #1013 (April) added the China region selector to the
    token-login flow and routes validation to api.bambulab.cn instead
    of api.bambulab.com. The selector is in the form
    (frontend/src/pages/ProfilesPage.tsx:204-205) and the backend
    dispatch is in backend/app/services/bambu_cloud.py:15 +
    backend/app/api/routes/cloud.py:174.

  What was wrong:

  - The in-app `accessTokenHint` said "Paste your Bambu Lab access
    token (from Bambu Studio)" in all 8 locales. Bambu Studio never
    exposed the token in any UI, and the profile page on
    bambulab.com that used to show it has been removed. The hint was
    pointing users at sources that don't exist.
  - For China-region accounts the email / password flow is
    fundamentally unusable because those accounts are bound to phone
    numbers, not email — token login is the only working path. The
    hint didn't say so, so reporters kept trying email login first
    and getting confused.
  - The wiki's "Access Token Login" section in
    features/cloud-profiles.md only described the dead profile-page
    method and a Python-script alternative that only works against
    the global API. No mention of the China-region selector and no
    mention of the MakerWorld-cookie method that actually works
    today.

  What this change does:

  - Rewrites `accessTokenHint` in all 8 locales (en, de, fr, it, ja,
    pt-BR, zh-CN, zh-TW) to state that China-region accounts must
    use the token path and point at the wiki for the cookie
    retrieval procedure. zh-CN and zh-TW translations were written
    for the audience that actually needs this.
  - Rewrites the wiki's Access Token Login section: adds a
    "Region: China must use token login" callout, replaces the
    dead profile-page guidance with the MakerWorld cookie method
    (both makerworld.com and makerworld.com.cn, with the browser
    DevTools steps), keeps the Python-script alternative explicitly
    scoped to global-region accounts, and warns that the cookie
    value is sensitive and shouldn't be pasted into screenshots or
    threads.

  No backend changes. Once a user has the token + Region: China
  selected, the existing flow works.
2026-05-17 10:29:14 +02:00
maziggy 84ed28d5fa fix(queue): cancel pending items and hide stale archive surface when archive soft-deleted (#1348)
Opening the Print Queue page fired 404s on /archives/{id}/thumbnail,
  /archives/{id}/plates, and /archives/{id}/plate-thumbnail/{n} for any
  row pointing at a soft-deleted archive. Two underlying problems wearing
  one mask:

  1. Cosmetic: the queue API was copying item.archive.thumbnail_path into
     archive_thumbnail without checking deleted_at. Soft-delete leaves the
     row (so the relationship resolves) but removes the file from disk, so
     the cached path was always stale.

  2. Functional: a queue item whose 3MF was removed can never dispatch.
     Without an explicit cancel, the item sits in 'pending' forever with
     no indication to the user about why nothing is printing.

  Fix in three parts:

  - New _cancel_pending_queue_items() helper, called from soft_delete_archive
    alongside the existing print-log thumbnail cleanup. Sets status='cancelled'
    + waiting_reason='Source archive deleted' on every pending queue item
    linked to the archive. Only 'pending' is touched - completed/failed/
    cancelled rows are historical and untouched. Hard-delete is already
    covered by ON DELETE CASCADE on print_queue.archive_id.

  - Queue API serializer now checks item.archive.deleted_at before
    populating any archive-derived field. New archive_deleted: bool field
    on PrintQueueItemResponse signals the soft-deleted state.

  - Frontend's getArchivePlates query in QueuePage was gated on archive_id
    only - archive_id is the real FK and stays exposed for dispatch/audit,
    so added an explicit && !item.archive_deleted clause to respect the
    new flag. Thumbnail render and CompactHistoryRow/QueueTimelineView
    already gate on archive_thumbnail so the backend suppression alone
    covers them.

  Regression tests pin cancel-only-pending behavior, soft-deleted
  suppression + archive_deleted=True flag, and the sanity guard that
  live-archive fields keep flowing through unchanged.
2026-05-16 12:58:21 +02:00
maziggy f5f7531ece i18n: strengthen parity check + translate accumulated debt across 7 locales
The "leaf-key parity" gate counted KEYS, not VALUES — so for months new
  features could ship by copy-pasting English text into non-English locale
  files just to make the key count match. ~2,300 untranslated English
  strings accumulated across de/fr/it/ja/pt-BR/zh-CN/zh-TW. Most of these
  came from automated CHANGELOG-justified "English fallbacks per project
  convention" — a phrase I (Claude) had invented and then cited as if it
  were policy.

  Two structural fixes so it can't happen again:

  1. New Check 4 in check-i18n-parity.mjs flags any leaf whose value is
     identical to en.ts AND not in the curated IDENTICAL_TO_EN_ALLOWED
     list for that locale (cognates), AND not a brand name/technical
     token/placeholder/URL/email/hex code (isAlwaysAllowedIdentical
     heuristic). Future English-into-non-English shortcuts fail CI loudly.

  2. Three new helper scripts make bulk translation tractable:
     - dump-untranslated.mjs: list every flagged (locale, key)
     - expand-translations.mjs: unique-source table → per-(locale, key) JSON
     - apply-translations.mjs: AST-based in-place rewrites

  Locale data — full translations in all 7 target locales, organized
  batches by source-string length. Cognates that legitimately match en
  (Status/Firmware/Tag/etc. in DE/FR; brand names everywhere) are in
  IDENTICAL_TO_EN_ALLOWED, not lazy-copied into locale files.
2026-05-16 12:16:30 +02:00
maziggy 856b849ffa fix(stats): per-event aggregation so reprints add to Quick Stats instead of overwriting (#1378)
Statistics now aggregate over PrintLogEntry (one row per print event,
  the same table backing the global Print Log) rather than PrintArchive
  (one row per file). A reprint creates a new PrintLogEntry instead of
  overwriting the source archive's runtime fields, so:

  - a 100 g successful print + a 10 g failed reprint correctly sums to
    110 g / 2 prints / 1 successful / 1 failed in Quick Stats and the
    Prometheus /metrics endpoint (previously the failed reprint silently
    replaced the source archive's data; totals dropped from 100 g to 10 g)
  - the archive's card cost/energy_kwh are preserved on reprints (only
    the first run writes them); per-run actuals live on PrintLogEntry
  - failed/cancelled/stopped reprints record partial-aware filament: sum
    of tracked spool deltas when inventory is set up, else estimate
    scaled to progress%, else None — prevents the full slicer estimate
    from inflating totals on a print that stopped at 10 % progress

  PrintLogEntry gains six columns: archive_id (nullable FK, ON DELETE
  SET NULL so log entries survive archive deletion preserving #1343
  soft-delete-vs-stats decoupling), cost, energy_kwh, energy_cost,
  failure_reason, created_by_id. Idempotent SQLite + Postgres migrations.

  New per-archive surface:

  - archive list response carries run_count / last_run_at /
    total_filament_actual_grams / successful_run_count / failed_run_count
    via a single batch JOIN, no N+1
  - new GET /archives/{id}/runs endpoint returns every PrintLogEntry for
    the archive (ARCHIVES_READ permission, newest-first ordering)
  - archive cards render an orange "N prints" badge for archives with
    more than one run; clicking the badge opens a dedicated PrintLogModal
    with date/status/duration/filament/cost columns plus failure_reason
    under failed runs. Also reachable via the context menu's new "Print
    Log" entry (works for single-run archives too), and embedded at the
    top of the Edit Archive modal for context.

  The purge_stats=true delete path now hard-deletes linked PrintLogEntry
  rows up front so the archive's contribution truly leaves the totals;
  without it, ON DELETE SET NULL would orphan the runs and leave them
  counting toward stats.
2026-05-16 11:34:40 +02:00
maziggy 29379e3be7 fix(camera): plate-detection UI now uses the external camera when configured (#1359)
Reporter @Andlar94 hit a permanent "Build plate not empty" on every print
  start on an A1 with an external RTSP camera. The runtime auto-check at
  main.py:1819 called check_plate_empty with use_external=external_camera_enabled,
  but the manual UI routes (camera.py) declared use_external: bool = False
  and the frontend client always sent use_external=false. So calibration
  captured a built-in frame and stamped it as the reference; the runtime
  check captured an external frame and diffed it against that reference --
  a permanent mismatch.

  Centralise the default on the backend: both routes now take bool | None,
  deriving the default from the printer's external_camera_enabled +
  external_camera_url + external_camera_type. The frontend client stops
  sending the flag unless the caller explicitly sets it, so the existing
  UI call sites immediately benefit and any future caller gets the right
  camera automatically. Explicit overrides still win.

  Adds 4 regression tests pinning the new default for both the
  external-enabled and external-disabled cases, plus the explicit override
  path so a future "always built-in" caller stays supported.
2026-05-15 14:32:18 +02:00
maziggy ae29a7dcd3 fix(api-keys): expose narrowly-scoped "Update electricity price" toggle (#1356)
Reporter @maziggy followed the Energy Tracking wiki literally - "create a
  key with Write Settings permission, PATCH /api/v1/settings with
  {energy_cost_per_kwh: ...}" - and hit:
  {"detail":"API keys cannot be used for administrative operations"}.

  Triage showed three independent drifts:
  1. Wiki listed nine fictional API-key permissions (Read Printers / Write
     Settings / Admin / ...) but the UI only ever exposed four toggles
     (Read Status, Manage Queue, Control Printer, Allow Cloud Access).
     There was no Write Settings toggle to tick.
  2. Even if it had existed, the backend hard-denies SETTINGS_UPDATE for
     every API key via _APIKEY_DENIED_PERMISSIONS - intentional protection
     because PATCH /settings can rewrite SMTP/LDAP/MQTT credentials and the
     HA access token. Wider surface than any documented use case needs.
  3. So the wiki had been promising a workflow that was never deliverable.

  Fix: introduce a narrowly-scoped door rather than relax the deny list.

    - New column can_update_energy_cost (default FALSE - existing keys
      never silently gain settings-write capability on upgrade).
    - New route POST /api/v1/settings/electricity-price accepting
      {"energy_cost_per_kwh": <float >= 0>}. Field name matches what the
      wiki already documented so the HA rest_command example needs only a
      URL+method change, not a payload change.
    - Custom dependency require_energy_cost_update() bypasses
      _APIKEY_DENIED_PERMISSIONS for this one route for API keys with the
      flag set. JWT users still go through standard SETTINGS_UPDATE.
    - General PATCH /settings remains denied for API keys - flipping the
      narrow flag does NOT widen general settings-write access. Pinned by
      test_patch_settings_still_denied_with_energy_flag.

  Frontend: fifth "Update electricity price" toggle on the create-API-key
  card + amber "Energy" badge on existing keys with the flag set. Three
  new i18n keys across all 8 locales (German translated, English fallbacks
  elsewhere).
2026-05-15 13:12:41 +02:00
maziggy f2e3de0a63 fix(camera): start layer timelapse for queue/VP-dispatched prints (#1353)
Reporter @Andlar94 ran the external-camera flow on an A1 dispatched via the
  print queue and got no MP4 output even though the log said "Stitching layer
  timelapse for printer 1" after each print. Support bundle confirmed the
  external camera was working (Obico was polling the snapshot URL fine for
  plate detection).

  Root cause: start_session() only ran in the two new-archive paths in
  on_print_start (fallback_archive at main.py:2510 and regular new-archive at
  2600). The expected-archive branch at main.py:1981-2052 — where every
  reprint and every queue/VP-dispatched print lands — updated the existing
  archive row to status=printing but never started a timelapse session.

  So _background_layer_timelapse ran at print complete, called tl_complete(),
  found nothing in _active_sessions, returned None silently, and the wrapper
  at main.py:3917 produced no log message for the no-session case. Every
  print through the queue silently lost its timelapse — likely the reason
  this hasn't been caught before (direct slice-and-send-to-printer prints
  take the new-archive path and work fine).

  Fix: mirror the same start_session() call in the expected-archive branch,
  guarded by the same external_camera_enabled + external_camera_url check the
  other two paths use.

  Also reworded the snapshot URL help text across all 8 locales to make clear
  that timelapse and plate detection each require their own per-printer
  toggle — the URL is just the image source they pull from when active. The
  previous wording read as if filling in the URL was sufficient.
2026-05-15 12:46:59 +02:00
maziggy d6364646f8 feat(auth): manual LDAP user provisioning from the UI (#1298)
Reporter @Fuechslein flagged that disabling LDAP auto-provision left admins
  with no UI path to onboard new users — the create-user form had zero LDAP
  awareness and the only workaround was hand-editing the database.

  Add a Local / LDAP tab toggle to the create-user modal (hidden when LDAP is
  disabled). The LDAP tab is a debounced directory search (≥2 chars, 300ms)
  that returns up to 25 matches via the service-account bind, annotated with
  already_provisioned so existing usernames render disabled. Clicking
  "Provision user" re-resolves via the service bind and creates the user
  through the same _provision_ldap_user helper the auto-provision login path
  uses, so group mapping, default-group fallback, and email sync are identical
  regardless of which path created the user.

  The picker component is shared across all four create-user modal paths
  (UsersPage basic + advanced, SettingsPage basic + advanced).

  Two ldap3 schema-check workarounds were needed for OpenLDAP installs:
  - Open the search connection with check_names=False so ldap3 doesn't reject
    the cross-schema OR filter (sAMAccountName/displayName are AD-only)
  - Request attributes=["*"] because ldap3's build_attribute_selection
    validates each named attribute against the server schema regardless of
    check_names, and only the * wildcard is in its hard-coded exclusion list

  Login/lookup paths keep check_names=True so typos in user_filter still fail
  loudly.

  Backend
  - New routes: GET /auth/ldap/search, POST /auth/ldap/provision (both gated
    by USERS_CREATE; 503 details include ldap3 exception class + message)
  - Extract _open_service_connection + _extract_user_info helpers so
    authenticate_ldap_user, lookup_ldap_user, and search_ldap_users share the
    bind and attribute-extraction logic

  Frontend
  - New LdapUserPicker component (debounced search, result list, provision
    mutation, already-provisioned guard, error surface)
  - Tab toggle wired into UsersPage and SettingsPage modals, plus
    CreateUserAdvancedAuthModal props
  - 14 i18n keys added to en.ts (other locales fall back to English)
2026-05-15 12:05:43 +02:00
maziggy f7c94cbc7b fix(inventory): add CF/GF to subtype dropdown on the Add/Edit Spool form (#1345)
Adding a third-party PETG-CF spool via the Material=PETG + Subtype=CF
  flow (same shape as the existing PETG HF) hit a missing option: KNOWN_VARIANTS
  in spool-form/constants.ts didn't list CF or GF. Users had to type it
  freehand into the "create new" tail of the dropdown.

  Added both: CF (matches PETG-CF / PLA-CF / ASA-CF / PA-CF) and GF (the
  natural pair for ABS-GF / PA6-GF). parsePresetName is unaffected — its
  materials list is iterated longest-first, so cloud presets like
  "Bambu PETG-CF Black" still resolve to material=PETG-CF with empty
  afterMaterial.
2026-05-15 09:47:21 +02:00
maziggy 7d7267e9cb fix(ui): z-index / stacking-context follow-ups to #1336
Two latent issues surfaced after the original AssignSpoolModal z-50 →
  z-[100] bump landed:

  1. Material-mismatch ConfirmModal hidden behind AssignSpoolModal.
     ConfirmModal's overlay was hardcoded to z-50 in its wrapper, so once
     the parent moved to z-[100] the nested confirmation dialog sat
     behind it. Added an optional overlayZIndex prop to ConfirmModal
     (defaults to z-50 — none of the 82 other call sites change), and
     the mismatch site in AssignSpoolModal passes z-[110] so the warning
     stacks above its parent.

  2. FilamentHoverCard / EmptySlotHoverCard covered by sibling printer
     cards on the dashboard. The popovers used position:absolute with
     z-[60] inside the trigger, but every printer card creates its own
     stacking context (drop-shadow filter on the slot tiles is enough),
     and z-index doesn't cross stacking-context boundaries — the next
     sibling card always wins by DOM order. Visible as the "Jade White
     · Bambu PETG HF" tooltip getting half-eaten by the neighbour card's
     AMS column.

     Fixed by portaling both hover cards to document.body with
     position:fixed and screen-space coordinates from
     triggerRef.getBoundingClientRect(). Coords recompute on visibility
     change, scroll (capture), and resize so the popover follows the
     trigger when the viewport moves; a requestAnimationFrame re-measure
     after the first paint avoids a one-frame flicker before the card
     has its rendered dimensions. Hover handlers are wired on both the
     trigger AND the portaled card so moving the cursor from slot to
     popover doesn't auto-dismiss after 100 ms. Top/bottom placement
     and arrow-pointer logic preserved.
2026-05-15 09:41:26 +02:00
maziggy 9ba1e34729 fix(archives): keep Quick Stats contribution when deleting a print (#1343)
Reported by @IndividualGhost1905: printing the same model ten times and
  then deleting nine archive entries (to keep the file list tidy) silently
  rewound the totals on the Statistics page — total prints, filament,
  cost, and per-print energy all dropped back to whatever the surviving
  row contributed, as if the other nine prints had never happened.

  Root cause: every metric in get_archive_stats is recomputed live from
  PrintArchive rows via COUNT / SUM, so removing a row removes its
  contribution. Energy in the default "Total" mode already survived
  deletion because it reads the smart-plug lifetime counters — that's
  the architectural shape we now generalise to the rest.

  Fix: soft delete with opt-in hard purge.

  Backend:
  - New nullable, indexed deleted_at column on print_archives, dialect-
    conditional migration (DATETIME on SQLite, TIMESTAMP on PostgreSQL).
  - ArchiveService.soft_delete_archive flips deleted_at and removes the
    files from disk (still reclaims storage); the path-safety checks were
    extracted into _resolve_archive_dir_for_delete so soft and hard delete
    share the rules.
  - DELETE /archives/{id} accepts ?purge_stats=true; default is soft.
  - Listings filter deleted_at IS NULL: list_archives, search FTS + LIKE
    fallback, GET /{id} (404 on soft-deleted), tag listing, duplicate
    detection (so a 1-live + 9-soft-deleted group no longer marks the
    survivor as a duplicate), and ArchiveComparisonService's "similar"
    suggestions. GET /stats and GET /slim deliberately do NOT filter so
    Quick Stats and the dashboard widgets keep counting deleted prints.

  Frontend:
  - ConfirmModal gained an optional children slot.
  - ArchivesPage (both card and detail views) own a per-instance
    deletePurgeStats boolean and render an opt-in checkbox in the delete
    dialog; resets to off on every close so the destructive option is
    never sticky.
  - api.deleteArchive(id, purgeStats?) appends ?purge_stats=true only
    when the box is ticked.
  - One new i18n key archives.modal.deletePurgeStats added across all 8
    locales (full German, English fallbacks elsewhere).
2026-05-15 09:21:43 +02:00
Sn0rrii 8a7598f6b5 feat(auth): proxy OIDC provider icons server-side (#1333) (#1342)
* feat(auth): proxy OIDC provider icons server-side (#1333)

Strict img-src CSP blocked external OIDC icon hosts on the login page.
Loosening CSP was rejected via the MakerWorld precedent, so icons are
proxied: admin sets icon_url, backend fetches and caches the bytes in a
deferred BLOB column, the SPA renders from a same-origin
/api/v1/auth/oidc/providers/{id}/icon endpoint.
2026-05-15 08:50:37 +02:00
maziggy dd3e3f8039 fix(inventory): make AMS slot config land cleanly for spools with no k-profile
The assign flow was sending slicer-invalid values for tray_info_idx and an
  empty setting_id, which the slicer rejected — slot detail modal showed
  empty fields. With a stored k-profile the realignment path masked the
  issue; without one, garbage hit MQTT.

  Backend (apply_spool_to_slot_via_mqtt):
  - Discard tray_info_idx values that aren't real preset IDs: literal
    material names ("PLA", "PETG-CF") AND PFUS-prefix cloud setting_ids
    (valid as setting_id but rejected as tray_info_idx). Same check applied
    to current_tray_info_idx so stale slot values don't get reused as
    garbage.
  - Local-preset path now reads the printer-recognized filament_id from
    the preset's setting JSON (e.g. P4d64437) instead of falling through
    to a generic material ID.
  - Derive setting_id from filament_id_to_setting_id when empty so
    ams_filament_setting always carries a matched pair.
  - No stored k-profile: always send cali_idx=-1 (Default K), regardless
    of the live cali_idx on the slot. The live value belongs to whatever
    filament was there before, so reusing it would apply the wrong K to
    the new spool.

  Frontend (spool-form/utils.ts):
  - Local preset options use String(preset.id) as the unique code instead
    of preset.filament_type — every PLA local preset was collapsing onto
    the same "PLA" code, so picking any of them saved slicer_filament=
    "PLA" and lost the specific preset identity.

  Spoolman counterpart in spoolman_inventory.py mirrors the cali_idx=-1
  reset.
2026-05-14 19:20:58 +02:00
maziggy 5150a5a0fa fix(inventory): raise AssignSpoolModal z-index so it sits above the mobile sidebar drawer (#1336)
Both used z-50, so DOM stacking-order let the sidebar bleed over the
  modal on narrow viewports. Bumped to z-[100] to match the convention
  used by GitHubBackupSettings, FilamentHoverCard, and the Layout
  confirmation modal.
2026-05-14 17:07:48 +02:00
Chanakyan 0e3de29fbe fix(settings): show backup tab indicator dot for scheduled backups (#1338)
fix(settings): show backup tab indicator dot for scheduled backups
 fix(settings): invalidate settings cache when toggling scheduled backups
2026-05-14 15:32:57 +02:00
maziggy ccf985abfc feat(slicing): build-plate override in the SliceModal (#1337)
Slicing an STL via the integrated slicer always defaulted to whatever
  curr_bed_type lived in the chosen process preset (typically "Cool
  Plate"), which the slicer CLI rejected for high-temp filaments with
  "Plate 1: Cool Plate does not support filament 1". The user had no
  way to switch plates without cloning the preset in BambuStudio.

  The Slice modal now exposes a Build plate dropdown with the six
  canonical BambuStudio / OrcaSlicer plates (Cool Plate, Cool Plate
  SuperTack, Engineering Plate, High Temp Plate, Textured PEI Plate,
  Smooth PEI Plate) plus an "Auto (use process preset)" option that
  preserves the previous behavior. Positioned between Process profile
  and Filament rows so a long filament list never pushes it off the
  modal's scrolled viewport, and always enabled regardless of whether
  the user picked a Printer Preset Bundle.

  A new bed_type field on SliceRequest flows through both dispatch
  paths:
  - Resolved-preset path: _patch_process_bed_type overwrites
    curr_bed_type on the process JSON before forwarding to the sidecar.
    Works end-to-end today, no sidecar change needed.
  - Bundle dispatch path: slice_with_bundle adds a bedType form field
    to the sidecar multipart. The sidecar (maziggy/orca-slicer-api
    fork) needs a matching change to honor it as --curr_bed_type on
    the CLI invocation; until then the field is silently ignored and
    the slice runs with the bundle's default plate.
2026-05-14 15:28:41 +02:00
maziggy b51ef33472 fix(inventory): apply catalog color's gradient + effect, not just hex (#1340)
Picking a color preset from the catalog only copied color_name and
  rgba onto the spool — extra_colors (gradient stops) and effect_type
  (sparkle / wood / etc.) were silently dropped at three layers above
  the API: the SpoolFormModal state shape, the CatalogDisplayColor
  mapping in ColorSection, and the selectColor handler itself. All
  three widened to carry both fields through.

  Picking a catalog swatch now writes both fields from the entry, so
  solid presets cleanly replace previous gradients. Recent-colors and
  the hardcoded-fallback palette stay as plain hex pickers — they
  don't touch extras/effect since they aren't full presets.

  Also fixed the en-US `colour` → `color` drift in 8 locale files
  that the reporter flagged.
2026-05-14 14:52:18 +02:00
maziggy 5c17cd4973 fix(inventory): restore Spoolman spool ID search + Unassign button (#1336)
Two regressions reported in #1336:

  1. spoolMatchesQuery did not include spool.id in the predicate, so
     typing a numeric Spoolman ID into the Assign Spool dialog or the
     Inventory page search returned no matches. Predicate now also
     tests String(spool.id).includes(q).

  2. The Unassign button in the spool edit modal was permanently
     disabled for Spoolman-mode spools. The modal only ever queried
     the legacy spool_assignments table (keyed by spool_id), but in
     Spoolman mode the assignment lives in spoolman_slot_assignments
     (keyed by spoolman_spool_id). Both the lookup query and the
     unassign mutation now branch on the spoolmanMode prop and call
     the Spoolman-flavored endpoints.
2026-05-14 14:19:12 +02:00
maziggy b8e350c3bf fix(spoolman): persist color_name edits and stop form round-tripping the subtype synth fallback (#1319)
Editing a spool's color name on Spoolman-backed inventory appeared to
  accept the new value but the inventory list column and the next edit
  showed it back to the subtype. Three layers stacked to produce this:

  1. find_or_create_filament matches by material/name/color_hex/vendor —
     color_name is intentionally not part of the match key, but on a
     match it returned the existing filament's id unchanged, silently
     dropping the new value.
  2. The read helper falls back to subtype when filament.color_name is
     empty (kept on purpose: without it Spoolman installs that don't
     fill the field render every spool as "Unknown color").
  3. The edit form prefilled color_name from spool.color_name — which
     on those installs was the synth value. Changing subtype but not
     color_name silently round-tripped the OLD subtype back to Spoolman
     as if it were a real user-set color_name.

  Fixes:
  - find_or_create_filament now patches the matched filament's
    color_name via the existing patch_filament wrapper when the request
    differs. Parameter convention: None = don't touch, "" = explicit
    clear, any other string = set/update. A patch failure is logged but
    does not block the match.
  - The PATCH route uses model_fields_set to distinguish "field omitted"
    from "field explicitly set to null" (mirrors the existing
    storage_location pattern at the same site).
  - The map helper returns color_name_is_synthesized: bool. The edit
    form leaves the input blank when true, so the user sees the real
    stored state and can't accidentally round-trip the synth value back.
2026-05-14 08:27:06 +02:00
maziggy 1303cd2701 test(password): replace realistic fixtures with obviously-synthetic strings
GitGuardian flagged "Bambuddy1!" and "LongerP@ssw0rd!" in password.test.ts
  as potential leaked credentials. Replace with patterned placeholders
  ("Aa1!aaaa", "Aa1!Aa1!Aa1!") that still satisfy every complexity rule
  (upper/lower/digit/special, >=8 chars) but won't trip secret scanners.
2026-05-13 11:13:49 +02:00
maziggy d08183278f fix(users): show password rules in form + match FE check to BE (#1303)
Create/Edit User modal previously had no hint about backend password
  complexity, and the FE pre-check was only length>=6 — so any weak
  password got bounced as a bare "HTTP 422" toast after the round-trip.

  - New checkPasswordComplexity util mirroring backend's validator order
  - Helper text under password inputs in both modals
  - Submit disabled until every rule passes
  - client.ts 422 parser falls back to JSON.stringify(detail) when the
    mapped array is empty, so a bare status code never masks the real
    Pydantic detail again
  - i18n keys added in all 8 locales (EN/DE fully translated, others
    per project's English-seed convention)
  - 7 unit tests pinning the validator contract, including the
    reporter's "12345678" input
2026-05-13 09:50:42 +02:00
maziggy a42ec820f6 fix(makerworld): point Open Cloud settings link to /profiles (#1300)
The "Open Cloud settings" link in the MakerWorld sign-in-required banner
  pointed at /settings?tab=cloud, but Settings has no cloud tab so the URL
  fell back to the General tab. Bambu Cloud login lives on /profiles, which
  already defaults its sub-tab to cloud.
2026-05-13 09:08:30 +02:00
maziggy e2e567f4dd fix(i18n): add settings.ldap.advanced key in all 8 locales (#1297)
The "Advanced" section header in LDAP settings was always
  rendering the hardcoded English fallback because the translation
  key was never defined. Added in en/de/fr/it/ja/pt-BR/zh-CN/zh-TW.
2026-05-12 16:38:56 +02:00
maziggy 8a6fcf5cbd fix(settings): expose UI rendering fields without requiring SETTINGS_READ (#1293)
The Clear Plate button (and 4 other features on the Printers page) read
  their state from /settings, which requires SETTINGS_READ. Granting that
  permission also adds the Settings nav item and leaks SMTP/LDAP/MQTT
  credentials — exactly what users were trying to avoid by giving an
  operator only printers:clear_plate.

  New /settings/ui-preferences endpoint returns a curated, opt-in subset
  of non-sensitive fields. Matches the existing /default-sidebar-order
  precedent. PrintersPage switched to the new endpoint; admin pages still
  use /settings for full access.
2026-05-12 16:30:28 +02:00
Ed 14a6d294f4 Merge pull request #1272 from EdwardChamberlain/feat-page-icons
[Feature] Update page icons for consistent UI style
2026-05-12 14:01:37 +02:00
maziggy bf2b34ebcf fix(ui): round smart-plug live wattage on printer card (#1266)
Plugs reporting fractional watts (Kauf PLF12 / ESPHome via MQTT)
  overflowed the card width. SmartPlugCard and SwitchbarPopover
  already round the same field; only the printer-card badge was raw.
2026-05-12 07:37:13 +02:00
maziggy b4875fd5d6 fix(ci): ruff format spoolbuddy.py; raise SettingsPage test timeout
- backend/app/api/routes/spoolbuddy.py: re-formatted via ruff (lambda
    conditional wrapped in parens — the formatter check fires when the
    expression spans multiple lines without grouping)
  - frontend/src/__tests__/pages/SettingsPage.test.tsx: per-test timeout
    raised to 15s for the external_camera_snapshot_url PATCH test; the
    default 5s was tight enough on GitHub Actions runners that user.type()
    of the 49-char URL + 800ms debounce occasionally blew past it
2026-05-11 13:43:41 +02:00
maziggy 90c3efece9 Housekeeping 2026-05-11 10:43:43 +02:00