Commit Graph
2689 Commits
Author SHA1 Message Date
maziggy 6bc6a1d683 feat(virtual-printer): setup diagnostic + one-click slicer-certificate export
Two recurring virtual-printer support pains, both on the Virtual Printers
  settings page.

  Setup check: a stethoscope action on each VP card runs a pass/fail/warn/skip
  checklist — VP enabled, services running, bind interface still exists, access
  code set, target printer (proxy mode), and a live TCP probe of the FTP / MQTT
  / discovery ports on the bind IP. start_server swallows per-service bind
  errors, so a service object can exist while nothing is listening; probing the
  bind IP from outside is the only reliable signal and it catches the common
  "VP not visible in the slicer" bind-IP-conflict and stale-interface cases.

  Slicer certificate: virtual printers present a TLS cert signed by a shared CA
  the slicer must trust. Until now users had to docker exec in and cat
  bbl_ca.crt. A "Slicer certificate" row on the settings card now offers Copy
  and Download (bambuddy-virtual-printer-ca.crt) plus the SHA-256 fingerprint.
  GET /virtual-printers/ca-certificate returns only the public certificate; the
  CA private key never leaves the backend. The CA is generated on demand so the
  button works before the first VP is enabled.

  Backend:
  - services/virtual_printer/diagnostic.py — run_vp_diagnostic + port probes
  - schemas/virtual_printer.py — VPDiagnosticResult
  - CertificateService.get_ca_certificate_info() + manager helper
  - routes: GET /virtual-printers/ca-certificate, /{vp_id}/diagnostic

  Frontend:
  - VirtualPrinterDiagnosticModal.tsx; stethoscope button on VirtualPrinterCard
  - caCert row on VirtualPrinterList; utils/clipboard.ts (shared copy w/
    non-secure-context fallback + downloadTextFile), de-duplicating the
    existing FQDN-copy logic
  - vpDiagnostic.* + virtualPrinter.caCert.* across all 9 locales

  9 backend unit tests + 4 route integration tests + 6 frontend tests.
  Backend ruff clean, frontend build clean, i18n parity green.
2026-05-22 13:24:35 +02:00
maziggy ed31b8f4a4 fix(ui): collapse bug-report connection diagnostic for multi-printer setups
The "Report a Bug" panel scans every configured printer on open and shows
  connection problems inline. The first cut rendered a full ~6-row checklist
  per problem printer, stacked — on a large fleet that pushed the description
  box and Submit button below the fold in the max-w-md / max-h-80vh panel.

  The diagnostic section is now a compact summary: one "N of M printers have
  connection issues" line plus the affected printers as collapsed rows
  (healthy printers count toward M, render no detail). Each row expands on
  demand to that printer's full checklist via the shared Collapsible widget;
  a single problem auto-expands since that's the case where inline detail is
  wanted without a click. Panel height is now fixed regardless of fleet size.

  - BugReportBubble.tsx: diagnostic query pairs each result with the printer
    name (new DiagnosticEntry type); render block uses Collapsible rows
  - i18n: new bugReport.diagnosticSummary ({{problems}}/{{total}}) replaces
    static diagnosticHeading; diagnosticIntro reworded count-neutral — all 9
    locales
  - 2 new BugReportBubble tests (collapsed-then-expand; single auto-expand)
2026-05-22 12:48:21 +02:00
maziggy 4925b4c830 fix(slice): re-slice correctness — model label, honest errors, filament usage, nozzle guard
Five follow-up fixes to cross-printer re-slicing, all surfaced while
  testing archive re-slices.

  1. Re-sliced archive now records the printer it was sliced FOR.
     slice_and_persist_as_archive copied sliced_for_model from the source
     archive, so re-slicing X1C->H2D still showed "X1C sliced". Read it
     from the freshly-sliced 3MF's parsed metadata instead, falling back
     to the source only when absent.

  2. Real slicer rejections are surfaced instead of silently masked.
     _run_slicer_with_fallback retried with the 3MF's embedded settings on
     any sidecar 5xx — including genuine content rejections (object off
     the bed, incompatible filament temps), which "succeeded" only by
     re-slicing for the source's original printer. A new
     _slicer_rejection_message detects the slicer's own error string and
     surfaces it as a 400; the embedded-settings fallback is kept only for
     true CLI crashes.

  3. A failed slice opens an error modal, not a 3s toast. The slicer's
     reason is actionable and a toast hides it before it can be read. New
     AlertModal (acknowledge-only); SliceJobTrackerContext shows it on a
     failed job. New slice.failedTitle key in all 9 locales.

  4. Sliced files no longer report "0 g" filament usage. The sidecar
     doesn't always populate the X-Filament-Used-* headers;
     ThreeMFParser._parse_gcode_header now also reads the slicer's own
     "total filament weight/length" from the G-code header, and both
     slice-persist paths fall back to it when the sidecar reports 0.

  5. Nozzle-class re-slice guard. Re-slicing across the single-nozzle <->
     dual-nozzle boundary (e.g. X1C -> H2D) fails BambuStudio's
     multi-extruder validation; both slice routes now reject it up front
     with a clear 400. The dual-nozzle model classification — previously
     an inline tuple duplicated across start_print and the K-profile
     routes — is centralized into DUAL_NOZZLE_MODELS / is_dual_nozzle_model
     in printer_models.py, consumed by all three sites and the guard.

  Full cross-nozzle-class re-slicing (dual-nozzle project_settings
  reconciliation) remains separately tracked.

  Tests: _slicer_rejection_message, _canonical_printer_model,
  guard_nozzle_class_reslice, is_dual_nozzle_model, the G-code-header
  filament parse, AlertModal, and end-to-end slice-API coverage including
  an X1C-archive-to-H2D 400. Backend ruff + i18n parity clean; frontend
  build clean.
2026-05-22 12:34:08 +02:00
maziggy 16da533c9a fix(static): serve /fonts/*.woff2 — self-hosted Inter font (#1460 follow-up)
The browser console logged "downloadable font: rejected by sanitizer"
  for inter-latin.woff2 on every load. The #1460 PWA fix added @font-face
  rules pointing at /fonts/inter-latin.woff2 and bundled the woff2 files
  into static/fonts/, but main.py only mounts /assets, /img and /icons as
  static directories. With no /fonts mount, /fonts/*.woff2 fell through to
  the SPA catch-all and returned index.html with 200 OK; the browser's
  OpenType sanitizer rejected the HTML-as-a-font.

  Add a /fonts StaticFiles mount alongside /img and /icons. The woff2
  files themselves are valid (verified — Inter variable, latin and
  latin-ext subsets).

  Also bump the service worker STATIC_CACHE version (v26 -> v27). sw.js
  lists the two font URLs in STATIC_ASSETS, and cache.addAll() treats the
  200 OK HTML as a successful fetch — so it had cached index.html under
  the font URLs and served it cache-first. The version bump makes the
  activate handler purge the poisoned cache and re-fetch the real fonts.
2026-05-22 10:43:27 +02:00
maziggy 71e58e6cf1 fix(library): show the filename, not the embedded 3MF Title (#1489)
File Manager cards, search and sort keyed off file_metadata.print_name,
  which ThreeMFParser lifts from the 3MF's <metadata name="Title">. That
  title is the in-app project title — generic "Exported 3D Model" for any
  Bambu Studio "Save As", a marketing title for a MakerWorld download —
  and almost never the filename the user saved as. A card for
  Whatever.3mf showed "Exported 3D Model"; correcting it needed a rename
  round-trip, since the Rename dialog disables Save while the name is
  unchanged.

  The slicer-output write path already dropped print_name for this exact
  reason; the four other paths that store parsed 3MF metadata onto a
  LibraryFile did not — external-folder scan, managed multipart upload,
  the multi-file ZIP-upload branch, and MakerWorld import.

  Add a shared _without_print_name() helper and apply it at all four
  import paths; switch the slicer path to it so there is one rule. A
  LibraryFile's display name is its filename — only PrintArchive carries
  a real print_name, which is untouched. Remove the now-redundant
  filename->print_name mirroring in the rename route.

  Add a one-time idempotent data migration (_migrate_drop_library_print_name,
  SQLite json_remove / PostgreSQL jsonb key-removal branched on
  is_sqlite()) so libraries imported before the fix correct themselves
  without the rename workaround. No frontend change: print_name || filename
  yields the filename once print_name is gone.

  Tests: 6 new in test_library_print_name.py cover _without_print_name and
  the migration (incl. idempotency, siblings preserved, null metadata).
  SQLite migration branch verified by test; PostgreSQL branch verified
  against a real Postgres instance.
2026-05-22 10:22:14 +02:00
maziggy 056f06a396 fix(camera): capture ffmpeg stderr when an RTSP stream stalls (#1395)
A P2S support bundle on 0.2.5b1 — per-model probesize fix already
  applied — showed the camera still failing: ffmpeg connects, stays alive
  30+ seconds, emits zero JPEG bytes, the 30s stdout.read times out,
  reconnect loop repeats. No ffmpeg stderr appeared anywhere in the log to
  explain why.

  The cause was a diagnostic bug, not the camera path. _read_ffmpeg_stderr
  called process.stderr.read() — read-to-EOF. A stalled-but-still-alive
  ffmpeg (the P2S RTSP failure mode) never closes stderr, so the read
  blocked until the 2s wait_for timeout and returned None, discarding the
  banner + stream-analysis lines ffmpeg had already printed. ffmpeg stderr
  was captured only when it fully exited; once the probesize bump turned
  the earlier crash into a hang, the diagnostic went dark.

  Drain stderr incrementally in bounded 8KB chunks (64KB cap), returning
  whatever ffmpeg printed so far whether or not it has exited. Also log
  the resolved per-model probesize/analyzeduration on the info-level
  "Starting RTSP camera stream" line, and log the full ffmpeg argv at
  debug level with only the credential-bearing camera URL redacted
  instead of hiding the entire command.

  No behaviour change to streaming — this makes the unresolved P2S RTSP
  stall diagnosable in the next support bundle.
2026-05-22 10:02:41 +02:00
maziggy 51b0d28b05 fix(camera): show diagnostic in window-mode camera page (#1395)
The #1395 camera-diagnostic follow-up (stethoscope control-bar icon,
  Diagnose button in the stream-error state, CameraDiagnoseModal) shipped
  wired into EmbeddedCameraViewer.tsx only — the embedded camera mode.
  CameraPage.tsx, the standalone window opened at /camera/{id} when
  camera_view_mode is "window" (the default), never got it.

  A reporter on window mode could not see the stethoscope regardless of
  container rebuilds or cache clears: the camera.diagnose strings are in
  the bundle but come from EmbeddedCameraViewer, which never renders in
  window mode. Switching to overlay mode surfaced it instantly.

  Port the diagnostic into CameraPage.tsx: Stethoscope control-bar button
  between Refresh and Fullscreen, a Diagnose button next to Retry in the
  streamError block, and the CameraDiagnoseModal render. No new i18n keys
  — camera.diagnose.* already exist in all 9 locales. The backend
  per-model camera-profile fix from the same issue is view-mode-agnostic
  and unaffected.
2026-05-22 09:53:14 +02:00
maziggy 774eba73c8 feat(diagnostics): event-loop stall watchdog to catch silent backend freezes
Several "container hangs after adding a printer" reports (#1486) share a
  signature with nothing to act on: HTTP goes silent, /health hangs, the
  process may ignore SIGTERM, and the log just stops mid-stream - a frozen
  asyncio loop cannot log a thing.

  loop_watchdog re-arms faulthandler.dump_traceback_later() from an async
  heartbeat. While the loop ticks the timer is cancelled and re-armed before
  it can fire; if the loop stalls for 30s the heartbeat can't re-arm and
  faulthandler's C-level timer thread dumps every thread's stack to stderr,
  so the blocked frame shows up in `docker compose logs`.
2026-05-22 09:28:43 +02:00
maziggy 745ed847e6 fix(archive): stop duplicating the job on a backend restart mid-print (#1485)
A restart during an active print duplicated the running job in the
  archive, and every further restart spawned another. on_print_start
  re-attaches by subtask_id, falling back to a name match plus a 4-hour
  staleness cutoff that cancelled + recreated any name-matched 'printing'
  archive older than 4h - destroying the live archive of every long print.

  Two fixes:
  - start_print records the minted subtask_id (last_dispatch_subtask_id);
    on_print_start falls back to it when the printer hasn't echoed one
    yet, so queue/scheduled archives persist a restart-stable id.
  - Replace the 4h cutoff with a progress-aware check: a name-matched
    'printing' archive resumes whenever the printer reports real (or
    unknown) progress; it is stale only when the printer shows a
    freshly-started print (<1%) on an archive over 2h old.
2026-05-22 09:05:25 +02:00
maziggy 3286ccd7d2 fix(inventory): send honest Bambuddy User-Agent on FilamentColors.xyz sync
The Color Catalog sync built its httpx.AsyncClient with no User-Agent, so
  it leaked httpx's default python-httpx/x.y string - the only outbound
  client that did; bambu_cloud, makerworld and firmware_check all send
  Bambuddy/1.0 (+https://github.com/maziggy/bambuddy). It now sends the
  same honest UA.

  Found while investigating an issue - a Cloudflare 403 on the sync that
  turned out to be the reporter's network/IP reputation, not Bambuddy. The
  UA leak was a separate inconsistency found in passing; this change does
  not by itself resolve a Cloudflare IP block.
2026-05-22 08:34:54 +02:00
maziggy 50d1984820 fix(printer): stop the File Manager polling the printer over FTPS every 30s (#1480)
FileManagerModal ran its file-listing query with refetchInterval 30000,
  opening a fresh FTPS connection (full TLS handshake) to the printer every
  30s while the modal was open. On fragile controllers like the P1S that
  load tipped MQTT, FTP and the camera into simultaneous timeouts. Drop the
  interval; the listing still refreshes on open, directory change, after
  upload/delete, and via the manual Refresh button.

  Also log STL thumbnail failures with a traceback (exc_info) so a
  data-specific "str / str" TypeError can be located from a support bundle.
2026-05-22 08:26:50 +02:00
maziggy e0247fc6a6 fix(slicer): filter process/filament presets by uploaded bundles, not preset names (#1325)
The process dropdown still mixed @BBL P2S presets into an X1C list:
  slicerPrinterMatch matched cloud/standard presets by parsing the
  @BBL <model> name suffix against a hardcoded model-code allow-list
  that was missing P2S, H2C and X2D — so those presets resolved to
  "unknown" and stayed in the main list instead of "Other printers".

  Drop both hardcoded model tables. Compatibility now comes from the
  user's uploaded Slicer Bundles: a bundle is scoped to one printer and
  lists the presets it ships, so a preset matches a printer exactly when
  some bundle for that printer contains it. New models are covered the
  moment their bundle is uploaded.
2026-05-22 08:01:42 +02:00
maziggy 17e39921bb fix(pwa): add in-app install button and self-host the Inter font (#1460)
Bambuddy installed as a PWA on desktop but not on Android. Two causes:

  - Chrome for Android removed the automatic install banner in Chrome 108.
    With no beforeinstallprompt handler, Android had no install path. New
    InstallAppButton captures the event and re-fires it from the sidebar.
  - index.css pulled Inter from fonts.googleapis.com: breaks offline, trips
    CSP, and the service worker answered the failed cross-origin request
    with cached index.html. Inter is now self-hosted; the SW skips all
    cross-origin requests and caches the font; CSP drops the Google hosts.
2026-05-22 07:40:44 +02:00
maziggy 379b1c14bc fix(printer): Flow Calibration was silently skipped — wrong project_file fields (#1478)
The H2S never ran flow-dynamics calibration even with the print option
  enabled, because start_print built the project_file command wrong:

  - extrude_cali_flag was hardcoded to 0. A BambuStudio request-topic
    capture from a real H2D (plus X1C/P2S captures) shows it is always 1
    (run calibration) or 2 (skip, reuse stored PA), paired with flow_cali,
    never 0 — so the printer skipped calibration regardless of the toggle.
  - flow_cali and the other calibration/leveling fields were integer-
    encoded for the H2 family on a mistaken belief that H2 firmware
    requires 0/1. The same capture sends plain JSON booleans for every
    model; the belief conflated these fields with use_ams (which does
    need to stay boolean — the actual #1386 cause).

  Fix: extrude_cali_flag = 1 if flow_cali else 2; send timelapse,
  bed_leveling, flow_cali, vibration_cali and layer_inspect as booleans
  for all models; drop the is_h_family integer-conversion branch.
  use_ams is unchanged.

  Corrected the two tests that asserted the integer format and renamed
  them; all three model tests now also assert extrude_cali_flag.
2026-05-21 14:50:29 +02:00
maziggy 7aad3fb395 fix(inventory): show group totals on collapsed grouped rows (issue #1368)
With "Group similar" enabled, the collapsed group row showed a single
  member's values — a group of five 1 kg spools displayed 1000 g instead
  of 5 kg (#1368).

  The group header now aggregates across all members: the table view's
  Label / Net / Gross / Used / Remaining columns and the grid card's
  weight figure show group totals. Identity columns (Material, Brand,
  Colour) and the Cost/kg rate stay per-spool-correct since they are the
  group key; per-spool-only fields with no meaningful total (dates,
  location, note, tag ID) keep the representative member's value. The
  expanded per-spool rows are unchanged.

  New aggregateGroupSpool helper with 4 unit tests; the table group
  component's header prop is renamed representative -> headerSpool.
  Frontend-only — all data was already in the spool list.
2026-05-21 14:00:43 +02:00
maziggy e738645b0d feat(slicer): filter slice profiles by printer + default from the 3MF (issue #1325)
The Slice dialog listed every process / filament preset regardless of
  the chosen printer, and always defaulted to the first listed preset
  rather than what the 3MF was prepared with (#1325).
  Matching uses the slicer's own compatible_printers list for imported
  (local) presets and falls back to the "@BBL <model>" name suffix for
  cloud / standard presets. Compatibility-unknown presets are never
  hidden.

  Defaults: the printer and process dropdowns default to the preset
  names embedded in the source 3MF's project_settings.config when those
  presets are available; the per-slot filament and process pre-picks
  prefer a printer-compatible preset, and switching the printer re-picks
  any selection left incompatible.

  - UnifiedPreset gains compatible_printers, exposed for the local tier
  - plates endpoints return embedded_printer / embedded_process
  - new frontend util slicerPrinterMatch.ts; extract_embedded_presets_from_3mf
  - slice.otherPrinters added across all 9 locales
2026-05-21 13:49:20 +02:00
maziggy 7eba29624b feat(slicer): filter process & filament profiles by selected printer (issue #1325)
The Slice dialog listed every process / filament preset regardless of
  the chosen printer (#1325). Picking a printer profile now filters both
  dropdowns to compatible presets; presets resolving to a different Bambu
  model move into a trailing "Other printers" group.

  Matching uses the slicer's own compatible_printers list for imported
  (local) presets, and falls back to the "@BBL <model>" name suffix for
  cloud / standard presets where no compatibility metadata is available,
  so all three tiers are covered. Compatibility-unknown presets (custom
  or untagged) are never hidden. The pre-pick and printer-switch paths
  follow the same rule.

  - UnifiedPreset gains compatible_printers, exposed for the local tier
  - new frontend util slicerPrinterMatch.ts with the matching logic
  - slice.otherPrinters added across all 9 locales
2026-05-21 13:33:13 +02:00
maziggy a51d59eabf feat(i18n): add Spanish (es) locale
Full European Spanish translation — frontend/src/i18n/locales/es.ts
  covers all 4899 keys with placeholders, plural forms, and inline
  markup preserved. Registered in i18n/index.ts (resources,
  supportedLngs, availableLanguages) and selectable as "Español".

  check-i18n-parity.mjs auto-discovers the new file; added an
  ES_COGNATES allow-list for genuine Spanish cognates and brand/format
  tokens so Check 4 does not flag them as untranslated leaks. Brings the
  supported-language count to 9.
2026-05-21 13:13:55 +02:00
maziggy 76e327f4a1 feat: connection diagnostic for "printer won't connect" triage
A triage review of the last 200 closed issues found ~1/3 were
  user-side setup errors — printer not in LAN developer mode, blocked
  ports, Docker bridge networking, wrong access code, cross-subnet —
  each costing a multi-round-trip support exchange.

  Add a Connection Diagnostic that runs those checks automatically:
  - backend/app/services/printer_diagnostic.py: TCP probes of MQTT
    8883 / FTPS 990 / RTSPS 322, LAN developer mode, Docker network
    mode, printer/host subnet match, MQTT credential class; each
    check returns pass/fail/warn/skip with a localized fix.
  - Routes: GET /printers/{id}/diagnostic (saved printer) and
    POST /printers/diagnostic (pre-save Add-Printer flow).
  - ConnectionDiagnostic.tsx: modal + shared checklist, surfaced from
    the printer card actions menu, an offline-printer quick button,
    the Add-Printer dialog, and a new System-page section.
  - The in-app bug reporter scans configured printers when the form
    opens and always shows the result inline — a healthy confirmation,
    or the detected problem and its fix.
  - config.yml troubleshooting link repointed to the rendered wiki
    page; bug_report.yml gains a diagnostic checkbox.

  Diagnostic strings translated across all 8 locales. Backend service
  unit tests (15) + frontend modal tests (3). Ruff clean, frontend
  build clean, i18n parity green.
2026-05-21 11:00:59 +02:00
maziggy e1a236e408 fix(spoolman): decide spool assignability from the slot-assignment ledger, not extra.tag (#1122)
GET /spoolman/spools/unlinked hid any spool with a non-empty
  extra.tag from the AMS-slot assignment picker. extra.tag is only an
  RFID/NFC matching key -- OpenSpoolman writes its own NFC tag value
  into that same Spoolman field -- so every OpenSpoolman-tagged spool
  became un-assignable in Bambuddy even when it occupied no slot.

  get_unlinked_spools now determines assignability from the
  spoolman_slot_assignments table (the documented source of truth for
  slot assignments) and ignores extra.tag entirely. Both link_spool and
  the AMS auto-sync upsert a row there for every occupied slot, so the
  ledger is complete. get_linked_spools and find_spool_by_tag still use
  extra.tag -- they are genuine tag-match maps and are unaffected.

  Internal-inventory mode needs no parallel change: it stores tags in
  its own DB with no Spoolman extra collision.

  Updates test_get_unlinked_spools_success and adds
  test_get_unlinked_spools_excludes_slot_assigned.
2026-05-21 09:33:47 +02:00
maziggy b06f8f6951 fix(spool-assignments): union both assignment tables in the missing-spool check + symmetric mode-switch clear (#1473)
notify_missing_spool_assignments_on_print_start queried only the legacy
  SpoolAssignment table. In Spoolman mode that table is empty -- bindings
  live in spoolman_slot_assignments -- so every used tray was flagged
  missing, firing a false-positive notification on every print.

  - spool_assignment_notifications.py: the assigned-tray set is now the
    union of SpoolAssignment + SpoolmanSlotAssignment rows. Union-only,
    so legacy-mode behavior cannot regress.
  - settings.py: the Spoolman toggle cleared SpoolAssignment on switch-on
    but never cleared SpoolmanSlotAssignment on switch-off. Added the
    symmetric clear so stale Spoolman rows can't leak into a later
    internal-mode session and mask a real missing-assignment warning.

  Adds 3 notification tests + 1 mode-switch integration test. An audit
  of the remaining SpoolAssignment consumers confirmed usage_tracker,
  spool_tag_matcher and routes/inventory are correctly internal-mode-only.
2026-05-21 09:15:10 +02:00
maziggy 305529f483 fix(notifications): missing-spool-assignment check now unions both assignment tables (#1473)
notify_missing_spool_assignments_on_print_start queried only the legacy
  SpoolAssignment table. In Spoolman mode that table is empty -- bindings
  live in spoolman_slot_assignments -- so assigned_global_trays came back
  empty and every used tray was flagged missing, firing a false-positive
  notification on every print.

  Union SpoolAssignment + SpoolmanSlotAssignment rows for the printer
  before computing the missing set. Both tables expose printer_id /
  ams_id / tray_id identically, so _global_tray_from_assignment is
  unchanged. Union-only, so legacy-mode behavior cannot regress.
2026-05-21 09:02:18 +02:00
maziggy 016e01781a fix(profiles): keep the Local Profiles search bar mounted when nothing matches (#1470)
The search bar was rendered only when totalCount > 0, but totalCount is
  the sum of the post-filter preset lists. A query that matched nothing
  dropped it to 0 and unmounted the search bar along with the columns,
  so the user couldn't clear the query without a page refresh.

  Gate the search bar on hasAnyPresets (pre-filter count) instead, so it
  stays visible as long as any preset is imported. Split the empty state:
  "No local presets yet" when nothing is imported, vs a new "No presets
  match your search" message when a query filtered everything out.
2026-05-21 08:51:55 +02:00
maziggy 5b3962e3e6 fix(obico): Failure Detection status panel shows thresholds for the selected sensitivity (#1469)
The Status panel's Low / High thresholds readout was stuck at 0.38 /
  0.78 regardless of the Sensitivity dropdown, so the setting looked
  dead. Detection itself was correct -- classify() always used the real
  sensitivity -- but get_status() computed the displayed thresholds with
  a hardcoded thresholds("medium").

  get_status() now takes an optional sensitivity argument and the
  /obico/status route passes settings["sensitivity"] (it already loads
  settings fresh). The readout updates as soon as the change is saved.
2026-05-21 08:45:59 +02:00
maziggy 01787eb1e6 fix(printers): normalize serial numbers + diagnose connect-but-no-reports (#1465)
Reporter's H2C connected over MQTT+TLS but every status field stayed
  unknown. Root cause was layer-8: the MQTT broker is the printer, it
  authenticates on the access code and SUBACKs any topic string, so a
  wrong or mis-cased serial connects fine and silently receives nothing
  (the report topic device/<serial>/report is case-sensitive; Bambu
  serials are uppercase). Bambuddy stored and used the serial verbatim.

  - schemas/printer.py: field_validator strip()+upper()s serial_number on
    create, rejects blank-after-strip. The subscribed topic now always
    matches the printer's correctly-cased one.
  - bambu_mqtt.py: count report-topic messages per connection; when a
    stale reconnect fires with zero reports received, log a one-shot
    hint pointing at the serial number instead of looping silently.
2026-05-21 08:30:17 +02:00
maziggy 76582298b5 fix(drying): stop false "drying complete" from killing the printer via smart-plug auto-off (#1462)
Reporter on X2D set a 1h AMS dry; the printer powered off seconds in.
  Support log: every "Sent drying command duration=1" was followed 3-9s
  later by "AMS 0 drying complete (dry_time 60 -> 0)" -- the completion
  callback fired right after drying started, arming smart-plug auto-off.

  Root cause: the tray-bearing branch of the AMS partial-update merge
  rebuilt the unit as {**ams_unit, "tray": merged_trays}, never spreading
  existing_unit. Tray-bearing partials carry no drying fields, so dry_time
  (and info) was dropped; the falling-edge detector read the absent field
  as 0 and saw a false 60->0 edge.

  - Merge: tray branch now spreads existing_unit first, preserving
    dry_time / info / humidity / temp across tray-only partials. Matches
    the no-tray branch. Also fixes dry_status/dry_sub_status UI flapping.
  - Detector: only evaluate the falling edge when dry_time is explicitly
    present and parseable; skip otherwise without updating state.
2026-05-21 08:13:44 +02:00
maziggy 8cff425c8d fix(printers): AMS drying popover scrolls instead of clipping the Start button (#1458)
#1447 added computePopoverPosition() to flip the drying popover above
  the trigger when below would overflow. Its degraded branch (popover
  taller than the viewport) keeps the popover below and its comment
  promised "the user can scroll inside it" -- but the popover div was
  overflow-hidden with no max-height, so the Start button stayed
  unreachable on short viewports.

  Make the promise true: the popover is now a flex column capped at
  calc(100vh - top - 8px); the body scrolls (overflow-y-auto) and the
  header/footer are shrink-0, so the Start button is pinned and always
  reachable. Covers the MacBook + iPhone 15 Pro Max PWA cases in #1458.
2026-05-21 07:57:22 +02:00
maziggy 2b8887c4d5 chore(ci): also ignore disputed PyJWT CVE-2025-45768 in ci.yml
security.yml had this ignore added in 9d440beb but ci.yml runs its
  own pip-audit step with a separate ignore list. CI was still failing
  on main + dev. Reasoning identical to the security.yml comment —
  disputed by PyJWT maintainers, no fix exists, Bambuddy uses
  secrets.token_urlsafe(64) and rejects short secrets.
2026-05-20 13:21:59 +02:00
maziggy 4910a0fb86 Updated .gitignore 2026-05-20 12:43:10 +02:00
maziggy 39a2a79524 This reverts commit 929aae7202. 2026-05-20 12:42:37 +02:00
maziggy 929aae7202 Added scripts/pip-audit.sh 2026-05-20 12:41:40 +02:00
maziggy 9d440beb80 chore(security): bump idna >=3.15 (CVE-2026-45409) + ignore disputed PyJWT advisory
- requirements.txt: pin idna>=3.15 to clear ReDoS in idna.encode() on
    crafted Unicode payloads. Transitive via anyio/httpx/requests/yarl,
    so the explicit floor stops a future downstream loosening from
    silently downgrading us.
  - security.yml: permanently --ignore-vuln CVE-2025-45768 (PyJWT). The
    advisory is disputed by the maintainers — "key length is chosen by
    the application" — and no fix version exists. Bambuddy is safe:
    auto-generates secrets via secrets.token_urlsafe(64) and rejects
    file-loaded secrets shorter than 32 chars (auth.py:177, :184).
  - security.yml: drop the stale Pygments --ignore-vuln CVE-2026-4539.
    Pygments has been patched upstream; the ignore no longer matches
    anything.
2026-05-20 12:36:32 +02:00
maziggy ed27b27adb feat(slice): cross-printer re-slicing — drop the gate, the banner, and the dead plumbing
Step 0 empirical test on 2026-05-20 disproved the "CLI cannot re-slice a
  3MF for a different printer" assumption: feeding an 18-color H2D-bound
  Trent900.3mf to the X1C bundle via /slice produces valid X1C G-code in
  1.8s, with bed (256x256), kinematics, nozzle count, machine_start_gcode,
  and bed_exclude_area all coming from the target bundle.

  - SliceModal: drop !printerMismatch from isReady; remove the banner and
    the sourcePrinterModel / printerProfileName / printerMismatch state
    entirely. Cross-printer slicing is now indistinguishable from a normal
    slice; the picker already shows the target printer.
  - Remove slice.printerMismatch from all 8 locales.
  - API cleanup: drop source_printer_model from /library/files/{id}/plates
    and /archives/{id}/plates responses, drop the field from
    frontend/src/types/plates.ts (PlateMetadata + LibraryFilePlatesResponse),
    delete extract_source_printer_model_from_3mf from threemf_tools.py and
    its 6 unit tests. Zero remaining consumers.
  - i18n discipline cleanup in SliceModal.tsx (same drop): strip every
    inline English defaultValue / positional fallback from t() calls (22
    sites). Add slice.bundle / slice.bundleNone / slice.bundleAllRequired
    to all 8 locales — they had no entry in any locale file and were being
    served from the inline English fallback for every non-English user.
  - Tests: rewrite the mismatch-warning test to assert "no banner, Slice
    enabled" when models differ (regression guard); delete 2 obsolete
    tests covering gate states that no longer exist.
2026-05-20 12:21:33 +02:00
maziggy 787ce9e146 Updated BACKERS.md 2026-05-20 11:39:44 +02:00
maziggy fd620df3d6 feat(currency): add Belize Dollars (BZD) to currency dropdown (#1454)
Adds BZD with symbol BZ$ to the Settings cost-currency picker so
  users in Belize can track filament costs in their local currency
  without doing 2:1 USD mental conversions.
2026-05-20 11:35:04 +02:00
Seb 14919a80a5 Merge pull request #1440 from Person2099/fix/filament-override-ams-mapping-dispatch
fix: compute AMS mapping from force-colour overrides when 3MF reqs unavailable
2026-05-20 11:25:45 +02:00
maziggy d3f0e9ac73 fix(spoolman): per-print weight tracker falls back to local slot-assignment table for tag-less spools (#1459)
Reporter on Postgres + Spoolman saw weight never decremented after
  prints. Traced to _report_spool_usage_for_slots calling only
  client.find_spool_by_tag() — which returns None when extra.tag is empty.
  Non-RFID spools assigned via the Bambuddy UI intentionally leave
  extra.tag empty (per #1457 — we don't want fallback tags polluting
  Spoolman), so tag-less spools never got matched and weight tracking
  silently no-op'd. The tracker never consulted the local
  spoolman_slot_assignments table that has the binding.

  Adds _resolve_spool_id_via_slot_assignment() as stage 2 of the
  resolution chain. Stage 1 (existing tag-lookup) wins when present so
  RFID auto-sync remains unchanged. (ams_id, tray_id) derived from
  global_tray_id via the existing _global_tray_id_to_ams_slot helper,
  so external slots and AMS-HT slots resolve correctly. Threaded
  printer_id through the three callers (partial G-code, partial linear,
  final-usage report). Resolution path is logged ("via tag" vs "via
  slot-assignment") so support bundles confirm the fix is live.

  extra.tag is deliberately NOT auto-populated — that would re-introduce
  the exact pollution #1457 cleaned up. Slot-assignment table is the
  source of truth for non-RFID; extra.tag is reserved for hardware RFID.
2026-05-20 11:16:56 +02:00
maziggy 12b0c138f7 fix(spoolman): clear stale fallback-tag links on assign + link, prefer slot-assignment over tag-link in UI (#1457)
Reporter on a P1S with non-RFID spools saw an old, almost-empty spool in
  the AMS hover card's "Spulen-ID" block while the "Zugewiesen" block
  correctly showed the freshly assigned full spool. Two layers compounded:

    (1) Non-RFID slots fall back to a deterministic per-slot tag
        (hash(serial) + ams_id + tray_id). The Link / Assign routes wrote
        that tag to Spoolman extra.tag but never cleared it from the
        previous holder on re-binding.

    (2) The frontend's hover-card resolver preferred the (stale) tag-link
        over the user's explicit slot-assignment. Same precedence bug in
        SpoolBuddy's fill-bar resolver and slot-action picker.

  Frontend: swap precedence at 5 sites — slot-assignment outranks tag-link
  everywhere. FilamentHoverCard's existing match-dedupe then collapses the
  two "Open in Inventory" buttons back into one.

  Backend: new _clear_stale_tag_links() in spoolman_inventory.py, called
  from POST /spoolman/inventory/slot-assignments (with the slot's
  deterministic fallback tag) and POST /spoolman/spools/{id}/link (with
  the literal tag being bound — works for RFID and fallback). Best-effort:
  Spoolman 5xx and per-spool patch failures log + continue, never wedge
  the bind. get_fallback_spool_tag_for_slot promoted to a public helper
  mirroring the frontend's signature exactly.
2026-05-20 11:00:54 +02:00
maziggy fbaf219094 Fix: AMS drying popover positioning + diagnostic logging (#1447)
Two bugs in one report, both shipped here.

  (1) Popover positioning. The flame-icon onClick on PrintersPage
  computed popover position as a fixed { top: rect.bottom + 4,
  left: Math.max(8, rect.right - 240) } with no viewport-overflow
  check. The flame icon sits at the bottom of the AMS info section
  on the printer card, so on most realistic viewports
  rect.bottom + 4 + popover_height (~320px) overruns viewport.height
  and the popover renders partially or entirely off-screen with the
  Start button unreachable. Reporter worked around it via DevTools to
  confirm the popover was actually there, just clipped.

  Extract a computePopoverPosition() helper in utils/popoverPosition.ts:
  - defaults to below + right-aligned to the trigger (preserves the
    original visual layout when there's room),
  - flips ABOVE the trigger when below would overflow AND above fits,
  - stays below in the degraded case (popover taller than viewport) —
    at least the top is visible and the user can scroll inside; flipping
    to a top-clipped position would lose the action buttons too,
  - clamps the left coordinate so a trigger near either viewport edge
    can't push the popover off-screen horizontally either.

  Both PrintersPage callsites (compact AMS row at :3498 and dual-nozzle
  layout at :4011) route through the helper.

  (2) Diagnostic logging for the silent-drying-ignore. Reporter's
  support bundle shows the printer receives every ams_filament_drying
  command (P1S 01.10.00.00 firmware, AMS-HT at ams_id=128) and ACKs
  each one, but the AMS info field never changes — drying neither
  starts nor stops on Bambuddy's request, while pressing Start on the
  printer's touchscreen works immediately. The command JSON matches
  the format documented as working on H2D, all required fields present.
  Diagnosing the silent rejection needs the printer's actual response
  payload — result/reason — but bambu_mqtt.py:918 was only logging the
  response command name, not the body. The existing extrusion_cali_* /
  ams_filament_setting debug path at :919-920 was the template; this
  PR extends it to ams_filament_drying at INFO level (not DEBUG like
  its siblings) because drying responses are rare (user-initiated only)
  and INFO ensures the body lands in support bundles by default without
  the user having to bump log level first. Paired with an outgoing-side
  INFO log inside send_drying_command that captures the full wire JSON,
  so the next bundle has both halves of the conversation.

  No guessing on the command-side. Mutating a field that matches the
  documented-working H2D shape (e.g. flipping close_power_conflict)
  could break currently-working installs. When the reporter retries on
  this build and re-attaches a bundle, the rejection reason is visible
  and the command-side fix follows from real data.
2026-05-20 10:04:41 +02:00
maziggy 0f68039416 Fix: AMS drying popover no longer renders off the bottom of the viewport (#1447 part 1)
The flame-icon onClick on PrintersPage computed popover position as a
  fixed { top: rect.bottom + 4, left: Math.max(8, rect.right - 240) }
  with no viewport-overflow check. The flame icon sits at the bottom of
  the AMS info section on the printer card, so on most realistic viewports
  rect.bottom + 4 + popover_height (~320px) overruns viewport.height and
  the popover renders partially or entirely off-screen with the Start
  button unreachable. Reporter (kleinweby, P1S + AMS-HT) worked around it
  via DevTools to confirm the popover was actually there, just clipped.

  Extract a computePopoverPosition() helper in utils/popoverPosition.ts:
  - defaults to below + right-aligned to the trigger (preserves the
    original visual layout when there's room),
  - flips ABOVE the trigger when below would overflow AND above fits,
  - stays below in the degraded case (popover taller than the viewport) —
    at least the top is visible and the user can scroll inside the
    popover; flipping to a top-clipped position would lose the action
    buttons too,
  - clamps the left coordinate so a trigger near either viewport edge
    can't push the popover off-screen horizontally either.

  Both PrintersPage callsites (the compact AMS row at :3498 and the
  dual-nozzle layout at :4011) route through the helper.

  This is part 1 of #1447. The functional drying bug — printer receives
  the ams_filament_drying MQTT command, ACKs it, but never starts/stops
  drying on Bambuddy's request while the printer's own touchscreen works
  — is NOT addressed here. Diagnosing it needs the printer's actual
  response payload (whether result: "fail" and the specific reason code),
  which bambu_mqtt.py:918 currently doesn't log for ams_filament_drying.
  Punted to a follow-up where I'll extend the existing extrusion_cali_* /
  ams_filament_setting payload-logging path at :919-920 to cover
  ams_filament_drying too, ask the reporter to retry, and fix the
  command side based on what the printer actually returns.
2026-05-20 10:00:15 +02:00
maziggy fcee1a6f7e Fix: Print Activity heatmap buckets by local date, not UTC date (#1446)
PrintCalendar.tsx had three instances of the same UTC-shortcut anti-pattern:

  1. Bucketing input dates via `date.split('T')[0]` — gives the UTC day
     while the cell tooltip rendered local via `toLocaleDateString`. Same
     data, two renderers, only one was tz-correct. Reporter on CDT (UTC-5)
     saw evening prints jump to "tomorrow's" cell.

  2. Per-cell lookup key built via `day.toISOString().split('T')[0]`. The
     `day` Date objects produced by the calendar-generation loop are
     local-tz (constructed via `new Date()` + `setDate`), so `toISOString`
     shifted them back to UTC before the lookup — would have re-broken the
     join even after the bucketing fix.

  3. "Today" ring comparison used `new Date().toISOString().split('T')[0]`
     too — at 23:00 local the ring would have moved to UTC-tomorrow's cell.

  Fix adds a `localDateKey(input: string | Date): string` helper to
  utils/date.ts that wraps parseUTCDate and formats via the local-tz
  getters (`getFullYear` / `getMonth` / `getDate` with two-digit padding),
  returning a stable comparable YYYY-MM-DD. PrintCalendar.tsx uses it in
  all three spots so the buckets, the cell join, and the today ring share
  the same local-tz axis as the user's tooltip label.

  Backend stays UTC. Bucketing is a presentation concern and the browser
  already knows the user's tz.

  Stragglers flagged for follow-up: StatsPage.computeDateRange builds
  dateFrom/dateTo for backend stats queries using getUTC* getters, so a
  "this week" picked at 23:00 local on Sunday in CDT sends UTC-Monday-based
  ranges to the backend. Fixing it properly also needs the backend to
  filter on a tz-shifted UTC range, and Bambuddy has no user-tz setting
  model today. localDateKey is in place for reuse when that work lands.
2026-05-20 09:45:28 +02:00
maziggy 0406487eb3 Fix: Add Printer no longer hangs the container on P1S (#1445)
The pre-insert MQTT probe added in 0.2.4.2 (b51598ea) had two bugs that
  compounded on P1S firmware specifically:

  1. Fixed 2-second sleep was too short. P1S broker + TLS handshake
  routinely needs 3-5s to surface CONNACK on a cold MQTT session (same
  firmware family with the documented "broker stops publishing but TCP
  stays alive" quirk at bambu_mqtt.py:3181), so the probe falsely rejected
  a printer that would have connected fine. H2C's broker is snappier and
  cleared the 2s window without trouble — which is why the reporter's
  H2C added without issue and only the P1S misbehaved.

  2. client.disconnect() ran synchronously on the asyncio thread.
  BambuMQTTClient.disconnect() ends in paho's loop_stop() which joins
  the network thread; if that thread was still mid-TLS-handshake to the
  slow P1S socket when teardown ran, the join blocked the asyncio thread
  for as long as the handshake took to complete or fail. POST /printers
  wedged, every other HTTP request queued behind it, Docker healthcheck
  timed out — user-visible symptom: "the container hangs."

  Fix:
  - Replace the fixed sleep with a polling loop (8s budget, 200ms tick,
    early-returns the moment state.connected flips True). Slow brokers
    get the headroom they need; happy-path connects still finish in
    ~1-2s. Constants exposed as PROBE_TIMEOUT_SECONDS / PROBE_POLL_
    INTERVAL_SECONDS class attributes so tests can dial them down.
  - Move client.disconnect() to await asyncio.to_thread(...) so paho's
    thread-join can never block the event loop.

  The empty-card-report-prevention goal of the original probe stays
  intact: a genuinely wrong access code still results in connected=False
  after the 8s budget, the 400 with code=printer_connection_failed
  still fires, the row is still never persisted.
2026-05-20 09:39:10 +02:00
maziggy badf0bed04 Fix: Failure Analysis widget honours edited failure_reason / status (#1444)
PrintLogEntry.failure_reason is captured once at print-completion time
  (main.py:3641) by copying archive.failure_reason — which is NULL while
  the user hasn't classified the failure yet. The PATCH /archives/{id}
  route then writes only to print_archives via a generic setattr loop,
  so the log entry stays NULL and failure_analysis.py keeps grouping the
  print as "Unknown". Same desync hits status — flipping it in the modal
  never reached the entry either.

  Mirror failure_reason and status from the PATCH payload to the latest
  PrintLogEntry for that archive (highest id). Latest-only because
  archive.failure_reason / status already reflect the latest run's outcome
  (each reprint clears the archive value at main.py:2195 and rewrites it
  at completion), so the Edit Archive modal is implicitly editing the
  latest run — reprints of an archive that succeeded on the second attempt
  keep the earlier failed run's original classification intact.

  Scoped to those two fields only. cost / print_name / printer_id stay
  unmirrored because per-run values legitimately diverge from archive
  ones (partial-print cost on a failed run vs source archive's full-print
  cost — see _compute_run_filament_grams at main.py:596).
2026-05-20 09:26:56 +02:00
maziggy a4e8ae3ab4 Fix: SpoolBuddy Write-Tag page honours Spoolman mode + complete ID surface (#1439)
Two bugs surfaced by @flom89 in the same thread:

  (1) The Write-Tag page hardcoded api.getSpools and friends regardless of
  inventory backend. Users in Spoolman mode saw internal spools they never
  created and a successful tag write would have bound the NFC tag to the
  wrong backend (the backend write-tag route is mode-aware; the frontend
  was driving it with the wrong IDs). Fix follows the InventoryPageRouter
  pattern: detect spoolmanMode from getSpoolmanSettings, gate the spool
  fetch on spoolmanModeReady to avoid the initial wrong-backend request,
  and branch all 6 API call sites (list, autocomplete, untag, K-profile
  save, single create, bulk create — the bulk variant returns a different
  envelope shape so the duck-typed check from SpoolFormModal is mirrored).

  (2) The spool ID was missing from three more SpoolBuddy components
  beyond the first round of #1439 work — SpoolInfoCard (the dashboard's
  right-side found-tag panel — the "main screen" view the reporter named),
  InventorySpoolInfoCard, and SpoolBuddyAmsPage's assigned-spool block.
  Same #1385 pattern (#<id> in muted small monospace with shrink-0).
2026-05-20 09:19:25 +02:00
maziggy 6f050708da Fix: cap TLS to v1.2 for P2S FTPS to dodge vsFTPd session-reuse bug (#1401)
Python 3.13 negotiates TLS 1.3 by default. The P2S firmware 01.02.00.00
  vsFTPd build doesn't tolerate TLS 1.3's async session-ticket model on
  the FTPS data channel — session resumption races, the data channel gets
  torn down mid-stream, uploads land truncated at a chunk boundary, and
  the printer replies 426 instead of 226. Visible to the user as "unable
  to parse 3mf file" 30 s into the print.

  Capping the SSL context's maximum_version to TLS 1.2 makes session
  resumption synchronous and uploads complete normally.

  Follow the per-model pattern established by camera_profiles.py in the
  #1395 follow-up: add backend/app/services/ftp_profiles.py with a frozen
  FTPProfile dataclass and a per-model registry. Only P2S (display name
  + N7 SSDP code) gets the cap today. X1C, H2D, P1S, A1 stay on negotiated
  TLS 1.3 — the maintainer's dogfooded printers see zero behaviour change.
2026-05-20 08:52:10 +02:00
maziggy 235a189e31 Fix: 3D preview no longer freezes the page on complex multi-part 3MFs (#1412)
The browser-side 3MF parser in ModelViewer.tsx runs entirely on the main
  thread (JSZip extract + DOMParser + vertex/triangle iteration), and Bambu's
  external-component shape chains one of these per part. Multi-color parted
  statues from MakerWorld can spend tens of seconds in straight-line JS,
  during which the modal close button can't fire and the browser shows
  "page unresponsive".

  Add nextTick() yields at four hot spots:
  - every 20 000 vertex iterations inside parseMeshFromDoc
  - every 20 000 triangle iterations inside parseMeshFromDoc
  - the matching loops in parse3MF's direct-mesh path
  - once per top-level <object> iteration in parse3MF
  - once per <component> iteration in parse3MF

  This doesn't make parsing faster — it surrenders control to the browser
  between batches so the modal stays interactive. Proper Web Worker refactor
  is a tracked follow-up.
2026-05-20 08:31:09 +02:00
maziggy bfd3fc755d Fix: capture timelapse baseline on expected-archive on_print_start branch (#1403 follow-up)
The snapshot-diff strategy in _scan_for_timelapse_with_retries needs
  _timelapse_baselines[printer_id] populated at print start so the
  completion-time scan can find the new MP4 by set-difference (mtime is
  unreliable — LAN-only printers don't sync NTP).

  The baseline-capture call was only in on_print_start's new-archive branch.
  Queue / VP-dispatched / reprinted jobs take the expected-archive branch
  which returns earlier, so the dict stayed empty and the completion-time
  scan fell into the "take baseline now" fallback that snapshots after the
  new file has already landed — no diff ever matches.

  Extract the snapshot into _capture_timelapse_baseline_at_start and call
  it from both branches.
2026-05-20 08:12:17 +02:00
maziggy 74f759468c Bumped version 2026-05-19 15:11:38 +02:00
maziggy d6d3fa2f99 chore(security): nosec false-positive Bandit findings in tests
PR #1434 CI flagged 5 B402 (ftplib import) in test_bambu_ftp.py and 2
  B108 (hardcoded /tmp) in test_print_start_assigns_printer_id_to_vp_archive.py.
  Both are intentional in tests: the FTP client tests need real ftplib
  exception classes to construct mock 426 responses, and the /tmp path is
  a MagicMock attribute never written to. Marked with `# nosec B402` /
  `# nosec B108` plus a one-line justification each, matching the
  convention from c2630399.
2026-05-19 14:23:38 +02:00
MartinNYHC 12a352e5b8 Merge branch 'main' into dev 2026-05-19 14:12:50 +02:00