Adds a passive log-health check that complements the active Connection
Diagnostic. Scans Bambuddy's recent app log against a curated allowlist
catalog of known failure signatures (rejected access code, FTPS :990
timeout, FTPS TLS failure, flapping MQTT, unreachable camera, SQLite
"database is locked" contention), dedupes and classifies each finding
as layer8/environment/bug, and deep-links to the troubleshooting wiki.
Sample log lines are sanitized before they leave the process. Exposed
via GET /system/health and surfaced on two surfaces sharing one
SystemHealthPanel component: a System Health section on the System
page, and inline in the bug reporter when the form opens.
The Add-Printer and Edit-Printer dialogs gained a setup-time pre-flight:
saving runs the connection diagnostic and, on a failed check, warns with
a "save anyway" escape hatch instead of silently saving a printer that
will immediately show offline.
Log read/parse/sanitize primitives extracted from routes/support.py into
a shared services/log_reader.py (behaviour-preserving); affected support
tests repointed accordingly.
Tests: test_log_health.py (11), test_system_api.py (2 new),
SystemHealthPanel + BugReportBubble + AddPrinterPreflight +
EditPrinterPreflight (8 frontend). All strings translated across the 9
locales. Backend ruff clean, full unit suite green, frontend build +
eslint clean, i18n parity green.
An archive's filament_color was parsed verbatim from the print job's
3MF (filament_colour in project_settings.config) — the slicer's
filament-slot colour, which a user picks independently of the exact
hex they curate on the Bambuddy inventory spool. So a print from a
#000000 inventory spool showed #161616 (the slicer's near-black) in
the archive card and the Color Distribution graph, even though usage
tracking correctly decremented the right spool.
Once usage tracking has resolved the print's filament slots to
inventory spools, the spool colours are authoritative. _track_from_3mf
(built-in inventory) and report_usage (Spoolman mode) now overwrite
the archive's filament_color with the slot-ordered, de-duplicated
colours of the matched spools.
The rewrite is all-or-nothing: it only applies when every used slot
resolved to a spool carrying a colour, so a partially-mapped
multi-colour print keeps the 3MF colour rather than silently dropping
the unmatched slots.
Shipped for both inventory modes: built-in spools read Spool.rgba,
Spoolman spools read the spool's filament.color_hex (fetched via
get_spool for tag-less slot-assignment matches). New helpers
_spool_color_to_hex / _archive_colors_from_spools in usage_tracker.py,
reused by spoolman_tracking.py via _apply_spool_colors_to_archive.
Tests: 12 new in test_usage_tracker.py (hex normalisation, the
all-or-nothing rule across single/multi/partial/no-colour/AMS-fallback
cases, end-to-end rewrite), 4 in test_spoolman_tracking.py (Spoolman
rewrite + empty/partial/missing-archive no-ops). 70 tracking tests
green; backend ruff clean.
A fresh P2S support bundle showed ffmpeg's reason for the stall:
`frame=1 time=00:00:00.06 dup=0 drop=526 speed=0.0037x`. ffmpeg
connects and frames arrive (drop counter climbs ~15/s), but it emits
one output frame and the output clock freezes.
The streaming command ends with `-r 15`, putting ffmpeg in CFR mode:
it drops/dupes input frames to hit 15 fps based on the source's
timestamps. P2S firmware 01.02.00.00 sends an RTSP stream whose RTP
timestamps don't advance, so CFR treats every frame after the first
as a same-timestamp duplicate and drops it. Snapshot capture works on
the same printer because that path has no `-r` (no CFR conversion);
X1/H2 are unaffected because their firmware timestamps are correct.
The earlier probesize fix was masking this second bug.
Add `-use_wallclock_as_timestamps 1` to the P2S camera profile via
the existing extra_ffmpeg_input_args hook. ffmpeg rebuilds each
packet's PTS from arrival wall-clock time, the output clock advances,
and CFR conversion works. No dataclass change, no other model touched.
Tests: 2 new in test_camera_profiles.py (P2S splices the flag+value
pair; default profile keeps extra_ffmpeg_input_args empty so the
override never leaks to X1/H2).
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.
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.
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.
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.
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.
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`.
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.
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.
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.
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.
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.
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
VP-queue archives are created with printer_id=None at queue-add
time because the scheduler hasn't picked a printer yet (and even
for explicit-printer queue items, the archive predates dispatch).
on_print_start's expected-archive branch updated status,
started_at, and subtask_id but never assigned printer_id, so
VP-queue-dispatched archives stayed permanently unassigned.
That broke every UI/API path gated on archive.printer_id —
critically the post-print "Scan for timelapse" action: the
H.264 file is on the printer's SD card and reachable via the
file browser, but the archive's scan endpoint refused the request
and the button stayed greyed out forever.
One-line fix: archive.printer_id = printer_id in the
expected-archive branch. Guarded against clobbering an
already-correct value so library-file queue items (which create
their archive with the printer pre-assigned) are idempotent.
Cover endpoint had no negative cache: when every FTP path returned
550 for a print whose 3MF wasn't on the printer (typical SD-card
print), each frontend refresh re-ran the full 8-path fan-out. Add
_cover_404_cache keyed by (subtask_name, view_key) and short-circuit
to 404 on hit; clear alongside _cover_cache on print start. Only
populated on genuine 404 paths, not transient FTP errors, so flaky
network doesn't lock out future retries.
GitHub update-check had no backoff on 403 rate-limit. Add module-
level _github_rate_limit_until plus three helpers; check before
every api.github.com call in /updates/check and
_discover_target_release. Read X-RateLimit-Reset from the 403 with a
1-hour fallback when the header is absent and a 60-second floor to
guard against container/GitHub clock skew. Route surfaces
retry_after_seconds so the UI can display real wait time.
The "ffmpeg didn't terminate gracefully" line the reporter quoted
is the standard SIGTERM/SIGKILL pattern in camera.py and unrelated
to the FTP loop; it goes away on its own once the cover endpoint
stops hammering the printer.
Previous daily build (1fac0276) tightened the post-STOR voidresp
handler to fail on any ftplib.Error, stopping Bambuddy from
sending a print command for a truncated 3MF. Reporter
(@enjoylifenow on a P2S) then confirmed — after a clean SD-card
filesystem check, reformat, and power cycle — that v0.2.4.1
worked on the same hardware. That proves the 426 returned by
this firmware revision is noise: the TLS data-channel close
races the 226 confirmation, server reports failure, file is in
fact on the SD card.
Reverting wholesale would re-introduce the silent-truncation
bug from the original fix. Narrow the rule instead: after an
ftplib.Error from voidresp, run an FTP SIZE against the upload
path. SIZE matches the local file size → warn and proceed
(the reporter's case). SIZE mismatch, or SIZE itself raises →
fail loudly with full diagnostics (the original tightened
behavior — preserved).
Applied identically to upload_file() and upload_bytes() so the
A1-compatibility manual-transfer path is covered.
Tests: two regressions from the previous round renamed and
split into intact / truncated / size-check-fails. Intact-file
tests inject SIZE explicitly because pyftpdlib only flushes on
a clean voidresp — which can't happen when we monkeypatch
voidresp to raise. Docstring spells that out. 87 FTP unit tests
green; 118 FTP-touching tests across unit+integration green;
ruff clean.
The View-Timelapse-greyed-out behavior #1417 was originally
about stays untouched; once the reporter confirms upload
reliability is back, that diagnosis continues on a healthy
install.
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".
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.
Editing a Spoolman spool used to mint a brand-new filament every time
a match-key field (subtype/material/brand/color_hex) changed, orphan
the previous one, and re-link the spool. The reporter ended up with
dozens of duplicate "Amazon Basics / PLA Glow" filament rows.
PATCH /spoolman/inventory/spools/{id} now:
- Reuses the current filament_id when no filament-shaping field
changed (a note/weight_used edit never touches the catalogue).
- PATCHes the existing filament in place when it's a singleton
(only this spool points at it, archived spools included).
- Falls back to find_or_create_filament only when the filament is
genuinely shared with another spool.
Mirrors internal-inventory behaviour where editing a spool updates
the thing the spool points at instead of proliferating new entities.
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.
Reporter on a P2S running firmware 01.02.00.00 saw the camera connect
for a few seconds then time out, repeating. P1S on the same install
worked fine — different protocol (chamber-image port 6000 vs RTSP via
ffmpeg).
The P2S RTSP path was running ffmpeg with `-probesize 32
-analyzeduration 0`, tuned for X1/H2 fast startup. The P2S's slower
keyframe pacing means ffmpeg can't lock onto the stream within 32
bytes — its own stderr says "consider increasing probesize" before
giving up after ~2s. Bambuddy reconnects, cycle repeats.
Instead of bumping the globals (which would regress every other RTSP
model's startup latency), this lifts the per-model tuning into a new
`camera_profiles` registry. CameraProfile dataclass holds the
previously-global knobs (probesize, analyzeduration, rtsp_reconnect_max,
rtsp_reconnect_delay, plus an extra_ffmpeg_input_args hook for future
per-model flags). get_camera_profile(model) returns the model's profile
or DEFAULT_PROFILE.
Default profile preserves the historical X1/H2 fast-startup values
verbatim — X1, X1C, X1E, X2D, H2C, H2D, H2D Pro, H2S all see no
behaviour change. P2S is the only override:
P2S: probesize=1_000_000, analyzeduration=500_000
SSDP internal codes (N7→P2S) resolve via an alias map so the camera
path works during the early-connect window before the display name
is settled.
This is the first step of the camera-architecture overhaul agreed
after #1395. Adding the next quirky model is a config entry, not
another module-level constant.
Reporter sliced in OrcaSlicer with timelapse on, sent the job to a VP
queue, started from the queue, and got no timelapse video. Their
dispatch chain itself was correct (queue item -> scheduler -> MQTT
command honors `timelapse`); the gap was at queue-add time.
The VP's `_add_to_print_queue` reads `default_timelapse` (and the four
other print-option settings) from the workflow settings card. That was
introduced in #1235 to stop column-level defaults from winning. But it
also discarded the slicer's actual choice carried on the MQTT
`project_file` command, which all the slicers (Studio / Handy / Orca)
ship as `timelapse: true|1`. Result: a user with the new-install value
`default_timelapse=false` had to either flip the global setting or
edit every queue item by hand, even though their slicer's "Print
options" UI clearly said "record timelapse".
Investigation went wider than #1403 because Martin's hypothesis was
"the print options modal isn't respected either." Cross-checking
86 captured P1S `project_file` commands across the support packages
shows 46 from the queue scheduler and 33 from background_dispatch
emitting `"timelapse": true` correctly to real printers - the modal +
re-print path is intact end-to-end. The slicer-side gap was the only
real bug. Two unrelated dead-code issues turned up in the same dig and
are folded in below.
Fix (VP queue inheritance)
- `on_print_command` in the VP manager now stashes the slicer's
project_file dict keyed by filename, then signals an asyncio.Event.
- `_add_to_print_queue` checks the dict first; if empty, creates the
event and waits up to 2 s for it before reading the settings
fallback. Each option flows through per-field - slicer value wins
if present, else the existing settings default (so users who
explicitly set `default_timelapse=true` in their VP workflow card
still get that on slicers that don't send a print command).
- MQTT field naming preserved exactly: `bed_leveling` (single L) on
the wire stays mapped to `bed_levelling` (double L) on the Bambuddy
column. Integer 0/1 from H-family slicers and bool true/false from
P1/X1 slicers both coerce via `bool()`.
- Capture is gated on `mode == "print_queue"` so immediate / review /
proxy modes keep their pre-fix no-op `on_print_command` and don't
accumulate stashed entries over the VP's uptime.
- Wait is also skipped when there's no MQTT server attached
(`self._mqtt is None`), so unit tests that invoke
`_add_to_print_queue` directly don't pay the 2 s tax.
- Capture is consumed on use so the dict stays bounded.
- `printer_manager.get_status(...).get(...)` against a `PrinterState`
dataclass that has no `.get()` method.
- Every print option discarded (timelapse, bed_levelling, AMS mapping).
The route 500'd before ever reaching the printer. Rewritten to mirror
`POST /print-queue/{item_id}/start`: clear `manual_start=False` on the
next pending queue item and let the scheduler dispatch with the
queue's stored options intact. Response shape preserved.
Side-bug b: vibration_cali default drift in background_dispatch
- `ReprintRequest.vibration_cali` and `FilePrintRequest.vibration_cali`
both default to `True` (matches Bambu Studio behavior for X1/P1).
- Both `_process_job` call sites read
`job.options.get("vibration_cali", False)`.
Cosmetic today because the frontend always sends the field, but a
latent landmine for any future caller that bypasses the schema. Both
sites flipped to `True`.
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.
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
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.
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.