Commit Graph
3277 Commits
Author SHA1 Message Date
maziggy 3fd3ec06b9 fix(ftp): stop a slow upload from being retried on top of itself (#2529)
upload_file_async carried a flat 600s wall-clock deadline and ran the
transfer via asyncio.wait_for(run_in_executor(...)). wait_for cancels the
future, not the executor thread. A 96 MB 3MF to an A1 over WiFi sustains
~75 KB/s and needs ~20 minutes, so the await gave up at ~70 MB, returned
False, and with_ftp_retry started a second STOR of the same file onto the
same printer while the first was still streaming. The reporter filmed two
transfers of one job climbing in parallel at 2% and 72%; the print never
landed and the printer read as having a flaky network.

The deadline is now derived from the file size against a 25 KB/s floor, so a
slow-but-healthy transfer can finish — a link that has actually died is
caught within socket_timeout by the blocking sendall, which is what should be
detecting failure. A deadline expiry now stops the transfer for real: the
worker is signalled, raises UploadCancelled from its progress callback, and
upload_file's existing cancel path breaks the send loop and deletes the
partial file. with_ftp_retry never retries that, and a per-printer lock makes
overlapping uploads impossible however they were triggered.
2026-07-11 09:05:49 +02:00
maziggy 0c44db04dd fix(ams): confirm drying start instead of trusting the firmware ack (#2533)
The Start Drying button gave no feedback at all and reported success on the
strength of the MQTT ack alone. On a P1S the firmware answers
ams_filament_drying with result=success and then silently declines, and
P1-family firmware never publishes dry_sf_reason — so the #971 reason guard
is inert there and the card just sat unchanged.

Both drying mutations now toast. The start toast claims only that the command
was sent, since that is all the ack proves; the amber countdown badge remains
the signal that a cycle is genuinely live. After a start, the card watches the
unit's dry_status/dry_time (straight from the info bitmask, updated on every
push); firmware reaches DryStatus 1 within seconds of a real start, so still
sitting at zero 30s later means the cycle never began. Bambuddy now says so
and names the two causes: AMS power adapter not connected, or the printer not
idle. Unlike the dry_sf_reason guard this is model-agnostic.
2026-07-11 08:43:34 +02:00
maziggy ccbfcfa295 fix(ams): confirm drying start instead of trusting the firmware ack (#2533)
The Start Drying button gave no feedback at all and reported success on the
strength of the MQTT ack alone. On a P1S the firmware answers
ams_filament_drying with result=success and then silently declines, and
P1-family firmware never publishes dry_sf_reason — so the #971 reason guard
is inert there and the card just sat unchanged.

Both drying mutations now toast on success. After a start, the card watches
the unit's dry_status/dry_time (straight from the info bitmask, updated on
every push); firmware reaches DryStatus 1 within seconds of a real start, so
still sitting at zero 30s later means the cycle never began. Bambuddy now
says so and names the two causes: AMS power adapter not connected, or the
printer not idle. Unlike the dry_sf_reason guard this is model-agnostic.
2026-07-11 08:37:57 +02:00
maziggy 50c3e94d33 fix(cloud): log expected preset misses at DEBUG, keep real faults at WARNING
Failed to get cloud preset ... 400 {"message":"missing"} is the expected
answer, not a fault: many official presets are only addressable with a
printer-variant suffix (GFSL05 exists solely as GFSL05_07 @BBL A1), and
personal P-prefixed presets belong to the account that sliced the file.
Phase 3 already resolves both from local presets, so the lookup miss is
routine -- and one WARNING per AMS tray per tooltip refresh teaches
operators to ignore the log.

BambuCloudError now carries the upstream status_code. The preset lookup
logs HTTP 400 at DEBUG; expired tokens, 5xx and transport failures stay
at WARNING.

Not fixed here: resolving the variant suffix. It selects a printer profile
and the response carries that profile's pressure_advance, so guessing a
suffix would report another printer's K value.
2026-07-10 08:24:20 +02:00
maziggy e6136b660b fix(cloud): carry Bambu Cloud credentials across the auth on/off boundary
get_stored_token() reads the global Settings rows when auth is disabled and
User.cloud_token when it is enabled, so completing /auth/setup switched which
store the /cloud/* routes consult without moving the token. An account linked
before enabling auth was stranded: build_authenticated_cloud() returned None,
get_filament_info() skipped its cloud phase and answered 200 from local
fallbacks, and /cloud/devices began returning 401 -- all silently.

setup_auth() now migrates the global token onto the owning admin and deletes
the global rows; disable_auth() mirrors the hand-off back. Neither guesses:
setup migrates only when it creates the admin or exactly one exists, disable
declines to overwrite an existing global token. Region survives both hops.

Instances that already crossed the transition must re-link once.
2026-07-10 08:15:35 +02:00
maziggy 77f8a3a3ff fix(tls): declare TLS 1.2 as the minimum for printer FTPS and MQTT
ssl.create_default_context() leaves minimum_version at MINIMUM_SUPPORTED,
so the floor came from the OpenSSL build rather than from Bambuddy. On
identical OpenSSL 3.5.6, python:3.13-slim-trixie reports TLSv1_2 while a
bare-metal venv reports MINIMUM_SUPPORTED -- Docker installs were floored
at 1.2, bare-metal and appliance installs were not.

Set minimum_version explicitly in ImplicitFTP_TLS and the MQTT client. On
the P2S/X2D profiles that also cap maximum_version this becomes an exact
TLS 1.2 pin. Probed against an X1C and an H2D on :990 and :8883: both
complete only on TLS 1.2 and reject 1.0, 1.1 and 1.3; live FTPS login
through the new path succeeds on both.

Also correct a stale comment in ftp_profiles.py -- X1C and H2D refuse
TLS 1.3, so cap_tls_v1_2 is a no-op there, contrary to what it claimed.
2026-07-10 07:55:14 +02:00
maziggy d29997fa24 Changed .github/workflows/ci.yml 2026-07-09 16:30:06 +02:00
maziggy a3c1878f11 chore(deps): floor-pin sqlalchemy >=2.0.38, pin ruff exactly, align CI lint
sqlalchemy 2.0.38 switched the aiosqlite file-db pool from NullPool to
AsyncAdaptedQueuePool; _create_engine() passes pool_size/max_overflow on the
SQLite branch, so anything older dies at import. Postgres installs are
unaffected -- the branch is dead there.

The CI lint job ran `pip install ruff` (newest) while requirements-dev.txt
said >=0.8.0, so CI and contributors enforced different rule sets: ruff 0.8.4
reports 32 errors on a tree current ruff calls clean, 30 of them the since-
removed UP038. Pin ruff exactly and have CI install that pin.
2026-07-09 16:29:39 +02:00
maziggy e1e2c12d25 fix(library-tags): declare response_model=None on the 204 DELETE route
Under `from __future__ import annotations` the `-> None` return annotation
reaches FastAPI as the string "None", which resolves to NoneType -- truthy,
so APIRoute asserts a 204 may carry no response body and the app fails to
import. fastapi >= 0.116 guards against this; the 0.109-0.115 releases
requirements.txt still allows do not.
2026-07-09 16:29:13 +02:00
maziggy 179b46580f Make uvicorn bind address configurable via HOST env (default 0.0.0.0)
Allows binding loopback-only (HOST=127.0.0.1) when a reverse proxy on the
same host fronts the app. Default behaviour unchanged.
2026-07-09 15:45:57 +02:00
maziggy f6c6cfbad3 fix(ams): show "?" not "Empty" for non-RFID spools using tray_exist_bits (#2527)
A spool with no readable RFID was reported by the standard AMS with an empty
tray_type and state=9 — structurally identical to a truly-empty slot at the
tray level — so the AMS card rendered it "Empty" while Bambu Studio correctly
showed "?". The authoritative "a spool is physically here" signal is firmware's
AMS-level tray_exist_bits bitmask (what Studio uses), but Bambuddy inferred
emptiness from the per-tray state/tray_type. Confirmed from the reporter's
bundle: tray_exist_bits=f (all four slots present) with tray_is_bbl_bits=5
(only slots 0,2 Bambu) — the present-but-non-Bambu slots were the ones shown
Empty. Supersedes closed #1838.

apply_tray_exist_bits() already parses the bitmask to clear stale fields on
absent slots; it now also annotates each slot with an authoritative `exists`
bool, gated behind a new annotate_exists flag so only the printer-card path
sets it. The VP bridge leaves it off, so the `exists` key never reaches the
slicer wire format. `exists` flows through the AMSTray schema/serialization to
the frontend, where getEmptySlotKind() uses it: exists===true + no tray_type
-> "?" (present, unconfigured), exists===false -> "Empty", exists absent ->
the previous state=9/10 heuristic (AMS-HT and missing-bitmask paths unchanged).
H2D/X1C already reported present-unknown slots with a non-9 state and took the
"?" path; with the fix they reach it via `exists` and are unaffected.
2026-07-09 09:27:13 +02:00
maziggy 9e7f6cafd9 fix(backup): preserve NOT NULL/DEFAULT/FK/UNIQUE in Postgres→SQLite backup (#2526)
On a PostgreSQL install, create_backup_zip() exports a portable SQLite copy
so backups move between engines. It rebuilt each table with only column name
+ type + PK, dropping NOT NULL, server_default/DEFAULT, foreign keys, and
unique constraints. Restore onto SQLite page-copies that schema straight onto
the live database, and post-restore init_db() can't repair it (create_all is
CREATE TABLE IF NOT EXISTS). So server_default columns like
spoolbuddy_devices.created_at (server_default=func.now()) ended up with no
DEFAULT: SQLAlchemy omits them on INSERT, the DB wrote NULL, and the next read
500'd on Pydantic validation. Every server_default column was exposed the same
way; the FK/unique loss followed from the same simplified CREATE TABLE.

Build the portable schema with Base.metadata.create_all() against a SQLite
engine instead of the hand-rolled loop, so it emits the exact DDL a native
SQLite install gets (NOT NULL, DEFAULT func.now() -> CURRENT_TIMESTAMP, FKs,
unique constraints, indexes). The data-export insert path is unchanged, and
the #1333 OIDC-icon guard is preserved automatically (LargeBinary -> BLOB),
which lets the now-redundant _sqlalchemy_type_to_sqlite_type() helper be
removed. Fixes newly-created backups; a backup from an older build still
carries the degraded schema, so re-take backups after upgrading.

Replace the #1333 type-mapping unit tests with three that inspect the real
backup schema via metadata.create_all + PRAGMA table_info: icon_data is BLOB,
created_at keeps its CURRENT_TIMESTAMP DEFAULT, a NOT NULL non-PK column stays
NOT NULL.
2026-07-09 09:02:34 +02:00
maziggy 6127e30abf fix(diagnostic): skip external-storage check on P1S/P1P instead of fail (#2524)
P1-series printers have a MicroSD slot but no reachable control to enable
"Store sent files on external storage": current P1 firmware (through
01.10.00.00) never publishes support_save_remote_print_file_to_storage, so
the Bambu Studio toggle never renders, and the P1S has no screen — leaving
store_to_sdcard stuck False with no way for the user to change it. The
external_storage check reported a permanently-unresolvable fail.

Add NO_REMOTE_STORAGE_TOGGLE_MODELS (P1S, P1P) + has_remote_storage_toggle(),
kept distinct from the no-slot NO_EXTERNAL_STORAGE_MODELS. When a model has a
slot but no reachable toggle and the option is off, the check now emits skip
with params reason=unsupported_model rather than fail, and overall no longer
escalates. A P1S reporting the option on still passes. Model-scoped and
default-open, so X1/P2S/H2 (where the fail is actionable) are unaffected; if
a future firmware surfaces the capability, drop the model and it reactivates.
The frontend DiagnosticChecklist renders a reason-specific message variant
(external_storage.skip_unsupported_model) so P1 users see an accurate
explanation instead of the generic "needs a live MQTT connection" skip text.
The fix propagates to the support-bundle diagnostic snapshot automatically.
2026-07-09 08:43:59 +02:00
maziggy 5dd0370397 fix(finish-photo): bank in-print frame for FINISH-state fallback (#1867)
A1 Mini firmware never emits stg_cur=22, so every completion hits the
FINISH-state fallback — which fires after the End G-code (SwapMod plate
swap) runs, capturing the swapped plate. The last-layer edge trigger
depends on catching one transient MQTT packet and is dropped
intermittently, reverting to the post-swap grab.

Bank a rolling in-print camera frame per printer, refreshed on layer
change. Because it's layer-driven it freezes when printing ends (no more
layer increases during the swap), so the last banked frame is the
finished print. The FINISH-state finish-photo path now prefers the
banked frame over a live grab; stage_22/last_layer still live-grab.
2026-07-09 08:17:59 +02:00
maziggy 616cebdf3f Fix P1/A1 camera black screen from fan-out churn on single-connection cams (#2521)
Chamber-image printers came up black on load and only recovered ~20 min
later. Two causes: (1) late fan-out subscribers got an empty queue and
waited for the next frame, so the browser never fired onLoad and the
stall-detector reconnect-looped, churning short-lived viewers; (2) the
churn reopened the port-6000 socket before the old one closed, so the
printer fed an orphaned socket until its TCP keepalive reaped it.

Prime late subscribers with the last pumped frame; make a replacement
broadcaster's pump wait for the predecessor's socket to close before
dialing (bounded 10s); require two consecutive stalled reads before the
frontend reconnects.
2026-07-09 07:59:41 +02:00
maziggy 1603f52a07 Dock Folder README as a collapsible right rail instead of a top block (#2520)
The README panel rendered full-width above the file grid, pushing model
files below the fold with no page scroll to get past it. On lg+ it now
docks as a fixed-width right-hand column beside the list (own full-height
scroll); on mobile it stacks on top and the page scrolls. Added a collapse
toggle (thin strip / slim bar + one-click reopen) with the choice persisted
to localStorage. New i18n keys readme.show/hide/label across 11 locales.
2026-07-09 07:32:24 +02:00
maziggy d03b108965 Fix external-folder scan deleting README.md records; index markdown (#2520)
.md was missing from _SCANNABLE_EXTENSIONS, so scanning an external
folder skipped markdown during the walk and the cleanup pass deleted
its LibraryFile row (assuming it was gone from disk), 404ing the Folder
Readme panel. Add .md to the scannable set so pre-existing markdown is
indexed, and gate cleanup deletion on actual disk presence rather than
absence from the extension-filtered found_paths, so any non-scannable
upload still on disk survives a scan.
2026-07-09 07:20:55 +02:00
maziggy bb3e2a710e Support non-0.4mm nozzles in AMS Slot config + guard dispatch (#1899)
The Configure AMS Slot picker was hardwired to 0.4mm (nozzleDiameter
prop never passed from PrintersPage / SpoolBuddyAmsPage), so a 0.6
machine could only set 0.4 profiles on its trays. Resolve the real
installed nozzle per-AMS (ams_extruder_map on dual-nozzle) and pass it
in. Separately, nothing validated the sliced nozzle against the
installed one, so a mismatch reached the printer as a cryptic HMS
_8012 "Failed to get AMS mapping table". Add a fail-safe pre-dispatch
guard in _start_print that fails the item with an actionable message
before upload; no slice diameter or no reported nozzles = no-op.
2026-07-08 08:57:56 +02:00
maziggy 55ea4b19c9 Updated BACKERS 2026-07-08 08:02:28 +02:00
maziggy e06677b795 Redirect authenticated visitors off /login (#1889)
LoginPage rendered the credentials form for an already-authenticated
session, so a direct visit to /login (browsers autocomplete the origin
to it) looked like "Remember Me" never worked despite a live token.
Read user/loading from the auth context and redirect to / once the
auth check settles, gated on the credentials step so the 2FA and
OIDC-callback branches keep their own navigation.
2026-07-08 07:49:13 +02:00
maziggy a1a0cbdf39 Updated CHANGELOG 2026-07-07 14:26:40 +02:00
maziggy e083861462 Updated CHANGELOG 2026-07-07 13:53:19 +02:00
maziggy 39ce37885e Bumped version 2026-07-07 13:22:13 +02:00
maziggy 05f82f5f76 Updated .gitignore 2026-07-07 12:45:24 +02:00
maziggy 418e8b56b2 Updated CHANGELOG 2026-07-07 12:19:47 +02:00
maziggy 70312b0a11 fix(scheduler): skip per-nozzle filter under FTS so dispatch feeds the right spool (#2186)
On a dual-nozzle H2C with a Filament Track Switch, a queued print targeting
one nozzle fed a same-type wrong-colour spool: the backend mapping
(_match_filaments_to_slots) hard-filtered candidate trays to the requested
extruder, excluding the correct spool loaded in the other nozzle's AMS — which
the FTS can route across. Confirmed from the reporter's captures: same model
mapped to AMS-A slot 2 (black) on the left nozzle but AMS-B slot 3 (red) on the
right. The #1162 FTS-skip existed only in the frontend mapping, never the
queue-dispatch path.

Read fila_switch.installed in _compute_ams_mapping_for_printer and skip the
per-nozzle filter when an FTS is present. Single-nozzle printers are unaffected
(no nozzle_id in the 3MF, no FTS). Regression tests in TestFtsNozzleBypass.
2026-07-07 12:17:46 +02:00
maziggy 5d64935658 Housekeeping 2026-07-07 11:38:24 +02:00
maziggy 2d8b0005cb Housekeeping 2026-07-07 11:11:15 +02:00
maziggy 5cf429f696 feat(labels): scannable QR on 203 dpi thermal printers + monochrome mode (#1870)
The 40x30 mm box label rendered its QR too densely for low-res thermal
    printers — the modules bled together and wouldn't scan. Two causes: the QR
    was 20% of inner width (~7.5 mm on the narrowest template, half of the
    others) and used ERROR_CORRECT_M. Fix adaptively so all templates benefit:
    give the roomy-layout QR a 12 mm minimum size (box_40x30 -> 12 mm, ~3.5
    dots/module at 203 dpi) and switch label QRs to ERROR_CORRECT_L (same
    payload, chunkier modules; a label needs no M-level recovery). Keep the
    quiet-zone border at 2 — the size+L gains suffice without risking scans.

    Also add a Monochrome (black & white printer) option to the label dialog:
    drops the colour swatch (a useless grey block on B&W) and widens the text;
    the hex-code line still carries the colour. Threaded through the renderer,
    route, API client, and modal, with translations in all 11 locales.
2026-07-07 11:07:08 +02:00
maziggy d8d3cde830 fix(scheduler): default require_plate_clear to False to match schema/UI (#1865)
check_queue() read the plate-clear setting with _get_bool_setting(default=True),
    but SettingsSchema.require_plate_clear defaults False and the whole frontend
    treats a missing value as off. Since _get_bool_setting returns its default when
    no DB row exists, installs that never saved the setting enforced the plate-clear
    gate the UI showed as disabled — FINISH-state printers never dispatched and no UI
    control existed to clear awaiting_plate_clear. Read the setting with default=False
    so the enforced behavior matches the schema and the toggle. Both defaults shipped
    together in #752; this aligns them.
2026-07-07 11:06:48 +02:00
maziggy 56185d2bac fix(ui): resolve light-theme low-contrast semantic text app-wide (#1909)
The app was built dark-first, so hundreds of hardcoded Tailwind semantic
    text/icon utilities at light shades (text-amber-400, text-blue-300, ...) had
    no dark: variant. With darkMode:'class' they applied in light theme too,
    producing washed-out text on pale tints and white cards — including the three
    reported spots (AMS Drying banner, Archives no-3MF warning, debug-logging
    banner). Give each a theme-aware pair: a darker readable shade in light theme
    with the original pinned to dark:, so dark theme is unchanged. ~100 files.

    The bambu-* CSS-variable palette (self-correcting) and the dark-only SpoolBuddy
    kiosk are left untouched. Plain text-white is already theme-aware via the
    existing index.css .text-white override, so it needed no changes.
2026-07-07 11:06:27 +02:00
maziggy 85bd68b0cc fix(sponsor): anchor 14-day toast cooldown on show, not just on CTA click (#2477)
The sponsor toast re-fired on every fresh browser session. The backend
    owns the 14-day cooldown but only persists the anchor (last_shown_at) and
    the seen-milestone record inside POST /sponsor-prompt/dismiss, and the hook
    only called dismiss from the "View supporters" CTA onClick. A user who saw
    the toast but never clicked the CTA persisted no state; the per-tab
    sessionStorage guard hid the re-fire within one session, but every new
    session re-checked against empty state and re-showed the same milestone.

    Record the toast as shown the moment it renders (POST /dismiss right after
    showPersistentToast) so display is what arms the cooldown. CTA click stays
    optional and just navigates. Frontend-only; backend cooldown logic unchanged.
2026-07-07 11:06:10 +02:00
maziggy daecfe6ca0 fix(windows): bundle vcruntime140_1.dll so greenlet loads on fresh Win10 (#2474)
A clean Windows 10 install crashed on startup: init_db() -> SQLAlchemy async
    engine -> greenlet failed with "DLL load failed while importing _greenlet:
    The specified module could not be found", so uvicorn never bound :8000 and the
    dashboard refused all connections while the NSSM service still showed running.

    greenlet's _greenlet.pyd is C++ and needs vcruntime140_1.dll, which the
    python.org embeddable distribution does not ship (it includes only
    vcruntime140.dll, enough for the pure-C python313.dll). Machines with the VC++
    2015-2022 redistributable already installed have the DLL in System32, which
    masked the bug in testing.

    Stage vcruntime140_1.dll and msvcp140.dll next to python.exe at build time,
    from a vendored copy or the runner's System32, failing loudly if absent. The
    Inno Setup [Files] step already copies staging\python\* recursively.
2026-07-07 11:05:52 +02:00
maziggy 2119ddd4f9 fix(vp): populate bind-interface list on macOS (route non-Linux to psutil)
get_network_interfaces() only sent Windows to the psutil path; macOS fell into
    the Linux ioctl branch, whose SIOCGIFADDR/SIOCGIFNETMASK ioctls are Linux-only.
    macOS/BSD have fcntl but different ioctl numbers, so every call raised OSError
    and the function returned an empty list — the VP bind-interface dropdown showed
    nothing. Route all non-Linux platforms through the cross-platform psutil path.
2026-07-07 11:05:35 +02:00
maziggy ae7674b3c1 fix(install): make macOS native install rootless (brew + venv permission errors)
macOS mixed root-only steps (default /opt path, sudo git clone) with steps
    that must not run as root: brew refuses to run as root, and a root-owned
    venv/node_modules can't be managed by the launchd agent. The installer now
    refuses sudo on macOS, defaults to ~/bambuddy, and drops sudo from the
    download/venv/frontend/env/dir steps. A --path under a root-owned parent still
    works via a single elevate-and-chown. Linux (service user + systemd) unchanged.
2026-07-07 11:05:17 +02:00
maziggy e3fe2971db fix(camera): transcode non-JPEG external snapshots to JPEG (#1902)
External cameras in HTTP-snapshot mode failed to load with a repeating
    "connection lost" when the endpoint served PNG/WebP/BMP stills instead of
    JPEG (common on IP cameras and reverse-proxied snapshot URLs). The URL
    rendered fine directly in a browser, but Bambuddy's MJPEG stream wraps
    every part in a hard-coded Content-Type: image/jpeg boundary, so a
    non-JPEG payload labelled as JPEG made the browser reject the frame and
    tear down the whole multipart/x-mixed-replace stream.

    _capture_snapshot now transcodes non-JPEG stills to JPEG via OpenCV
    (already a dependency). Genuine JPEG snapshots keep a byte-for-byte fast
    path; truly undecodable responses (HTML error pages, auth redirects) fall
    back to the previous raw-return behaviour with a single clear warning
    instead of a per-frame log flood.
2026-07-07 11:04:58 +02:00
maziggy 33554072ed fix(ui): restore missing per-user Notifications nav item (#1901)
The sidebar-ordering refactor in #1673 accidentally dropped the
    `notifications` entry from `defaultNavItems` and its
    `notifications:user_email` permission mapping, but kept the advanced-auth
    visibility gate that references that id. With no nav entry the id never
    enters the render set, so the /notifications page (route, page, and API
    all intact) became reachable only by typing the URL — users could no
    longer opt in/out of their own print email notifications from the menu.

    Restore both the defaultNavItems entry and the permission gate, matching
    the permission the user-email-preferences API actually requires
    (notifications:user_email, held by both default groups). Add comments so
    the entry isn't dropped again in a future sidebar refactor.
2026-07-07 11:04:33 +02:00
maziggy 6e03ecdb8d fix(vp): stop uvloop from silently truncating VP FTP uploads (#1896)
Native (non-Docker) installs launched uvicorn without --loop asyncio, so
    uvicorn[standard] auto-selected uvloop. uvloop's SSL layer drops
    already-received but still-buffered data when the client closes the data
    connection without a TLS close_notify while the reader is flow-control
    paused on slow storage. cmd_STOR writes each chunk to disk inside the read
    loop, so a slow consumer falls behind, the tail is lost, read() returns a
    clean EOF, and the loop exits with no exception -- the server acked 226 for
    a file it truncated itself, then archived, queued, and forwarded the corrupt
    3MF to the real printer.

    Fix in two independent layers:

    1. Remove the trigger: add --loop asyncio to every native launch path,
       matching the Dockerfile -- deploy/bambuddy.service, install/install.sh
       (systemd + launchd), spoolbuddy/install/install.sh, the Windows NSSM
       service, README, CONTRIBUTING dev command.

    2. Defense in depth (loop-independent): cmd_STOR now validates that a
       received .3mf opens as a ZIP (reads the central directory, no
       decompression) before replying 226. A truncated/corrupt file is dropped
       and answered with 426, and on_file_received never runs -- so a broken
       upload surfaces as an immediate slicer-side send error instead of being
       archived and pushed to the printer. Scoped to .3mf; other filetypes pass
       through unchanged.
2026-07-07 11:04:04 +02:00
maziggy c5b02d9473 fix(auth): let API keys manage projects via new can_manage_projects scope (#1893)
PROJECTS_CREATE/UPDATE/DELETE were in _APIKEY_DENIED_PERMISSIONS with no
    entry in _APIKEY_SCOPE_BY_PERMISSION, so every project mutation returned a
    generic 403 for any API key regardless of granted permissions -- the same
    regression class as archives (#1888) and library (#1832).

    Add a per-key can_manage_projects scope. Project routes gate on plain
    PROJECTS_* (no OWN/ALL split), so all three CRUD permissions map to the one
    scope; membership edits (add-archives) gate on PROJECTS_UPDATE and are
    covered. PROJECTS_READ is unchanged (already under can_read_status).

    Column defaults TRUE for new keys; existing rows backfill to FALSE so the
    upgrade never silently widens scope. Migration is BOOLEAN (SQLite + Postgres
    safe), verified on fresh SQLite and Postgres 17. Bundled SpoolBuddy kiosk key
    set to False. Settings API-key UI gets a Manage Projects toggle + Projects
    badge; 11-locale i18n. RBAC scope matrix + drift guards extended.
2026-07-07 11:03:46 +02:00
maziggy 18dbe63fd5 fix(drying): don't stop a running AMS dry on an unreliable humidity re-check (#1892)
Auto-drying stopped manually started (and pre-restart) AMS drying cycles
    after exactly 30 minutes. The already-drying branch in _check_auto_drying()
    applied a humidity-based auto-stop despite its own "track but don't stop"
    comment, and the humidity re-check is unreliable: RH drops steeply in heated
    air, so the sensor reads ~15-20% within minutes of the dryer starting even
    with saturated filament. humidity <= threshold was thus effectively always
    true, and the _min_drying_seconds=1800 floor pinned the stop to the 30-minute
    mark. This also truncated Bambuddy's own preset-duration dries.

    Remove the humidity-based early-stop entirely: a running dry now runs to its
    configured duration (firmware stops it). Scheduling stops (print priority,
    queue no longer needing the dry) are unchanged via _stop_drying(). Drop the
    now-unused _min_drying_seconds.
2026-07-07 11:03:25 +02:00
maziggy c751047ed8 fix(websocket): stop the ws-token reconnect loop on auth failure
After the GHSA-r2qv gate (b7d7c825), /api/v1/ws needs a token from
    POST /api/v1/auth/ws-token (Permission.WEBSOCKET_CONNECT). When the mint
    failed, useWebSocket swallowed the error, opened a tokenless socket, the
    server closed it 4401, and ws.onclose rescheduled connect() every 3s -
    an endless loop that hammered /auth/ws-token. The dominant trigger is a
    validly-logged-in user whose group lacks WEBSOCKET_CONNECT (mint returns
    403). A secondary leak: the unmount-triggered onclose could schedule a
    post-unmount reconnect.

    Classify the mint failure: 401 (JWT expired; request() already clears it
    and dispatches auth:expired) or 403 (valid session, missing permission;
    degrade to REST polling) now stop the hook - no tokenless socket, no
    reconnect. A 4401 close is terminal. Network/5xx still reconnect. A
    disposedRef set in cleanup before close() prevents the unmount-race
    reconnect. Same 401/403 no-open guard applied to StreamOverlayPage.

    Also surface a one-line hint under the WebSocket permission in the group
    editor (all 11 locales) explaining that live updates need it and fall
    back to polling without it - rather than auto-granting the permission,
    which would partly undo the GHSA-r2qv gate.
2026-07-07 11:03:00 +02:00
maziggy 640c7daaaa fix(auth): don't discard a valid stored token on a transient load-time error (#1889)
On mount, AuthContext.checkAuthStatus restores the persisted "Remember Me"
    token from localStorage and validates it via GET /auth/me. The catch around
    that call cleared the token on ANY failure, not just a definitive 401
    invalid-token — so a brief backend-not-ready or reverse-proxy hiccup during
    page load (plausible right after a container restart, e.g. on Unraid) would
    delete a still-valid token. Because the token was deleted, a reload couldn't
    recover it and the user was bounced to the login screen.

    Token validation now retries transient failures (up to 3 attempts with short
    backoff) and only discards the token on a definitive 401 — which request()
    already handles (clears the token and dispatches auth:expired). Transient /
    5xx / network errors leave the persisted token intact so the session survives
    a slow load. "Remember Me" stays client-storage only; it does not extend the
    server-side JWT lifetime (session_max_hours, default 24h).

    Adds AuthContext tests: transient /auth/me failure keeps the token, a
    definitive 401 clears it, and a valid token loads the user. Rebuilt frontend
    bundle.
2026-07-07 11:02:40 +02:00
maziggy 1fd1825b71 fix(smart-plug): don't cut power when a print restarts, honor per-plug cooldown setting (#1890)
The print-queue "auto off after this job" trigger used a second, inline
    auto-off implementation (main.py, print_scheduler.py, print_queue.py)
    that hardcoded wait_for_cooldown(50C, 600s) — ignoring each plug's
    configured off_delay_mode / off_delay_minutes / off_temp_threshold — and
    ignored the return value, powering off on the 600s timeout regardless of
    print state. A print that failed and was reprinted from the touchscreen
    got its power cut mid-print. The inline tasks were also uncancellable, so
    a reprint couldn't abort a pending off.

    Consolidate all three into SmartPlugManager.schedule_off_after_queue_job,
    which schedules via the plug's configured strategy (shared with
    on_print_complete through _schedule_off_per_mode) and is cancellable via
    _pending_off. Add printer_manager.is_print_active() and guard the actual
    power-off in _delayed_off and _temp_based_off so no path cuts power on a
    loaded print. Move the on_print_start cancellation ahead of the auto_on
    gate so a reprint always aborts a pending off.
2026-07-07 11:02:21 +02:00
maziggy 99d06f3cd1 fix(auth): allow API keys to delete/edit archives via new can_manage_archives scope (#1888)
DELETE /api/v1/archives/{id} rejected every API key with 403
    "API keys cannot be used for administrative operations", regardless of
    the print's owner or the key's scopes. ARCHIVES_DELETE_ALL/_OWN (and the
    create/update variants) were on the denylist and absent from the scope
    allowlist, so require_ownership_permission fell through to the generic
    admin-denied 403 — the whole archive-management surface was unreachable
    for API keys. Same regression class as the #1832 library/maintenance
    carve-outs.

    Add a can_manage_archives per-key scope: ARCHIVES_CREATE, ARCHIVES_
    UPDATE_OWN/_ALL and ARCHIVES_DELETE_OWN/_ALL move from the denylist to
    the allowlist under it (OWN and ALL fold into the same scope, matching
    can_manage_library). ARCHIVES_PURGE stays admin-only — it drops the
    print's Quick Stats contribution, mirroring LIBRARY_PURGE. Column
    defaults TRUE for UI-created keys; existing rows backfill to FALSE so the
    upgrade never silently widens scope. Bundled SpoolBuddy kiosk key stays
    minimally scoped (False). Migration is dialect-agnostic and verified on
    fresh SQLite and Postgres 17.

    Adds the Settings API-key toggle + badge (11-locale i18n) and extends the
    RBAC scope matrix to cover all five archive-management permissions.
2026-07-07 11:01:57 +02:00
maziggy 11d73b0a64 fix(slicer): preserve PVA-for-support intent across re-slice of source 3MF (#1881)
Three bugs on the same PLA-model + PVA-support flow, discovered in
    sequence:

    (A) substitute_unused_plate_filaments inspected only object geometry
        (per-object extruder metadata + paint_color triangles) so a support-
        only slot was silently treated as "unused" and the user's PVA profile
        got overwritten with slot 1's PLA.

    (B) _extract_filament_info stripped filament_is_support==1 entries,
        hiding PVA from unsliced source archive cards even when the project
        explicitly configured it.

    (C) --load-settings is authoritative over the source's project_settings.
        config, and Bambu's shipped process presets ship enable_support=0
        (supports are a per-print decision, not per-quality). So even with
        (A) fixed, the sliced output had supports disabled and the PVA slot
        loaded but never consumed. Inverts BambuStudio GUI's semantics where
        the project overrides the preset.

    Fixes:
    - New extract_support_filament_slots_from_3mf reads enable_support +
      support_filament + support_interface_filament from project_settings.
      config; substitute_unused_plate_filaments unions it into the geometry-
      derived set.
    - _extract_filament_info returns all configured filament types + colours.
    - New _patch_process_support_settings overlays four fields (enable_
      support, support_filament, support_interface_filament, support_type)
      from the source 3MF onto the picked process preset JSON before
      --load-settings sees it. Deliberately targeted to what fixes #1881
      without widening to a full project-over-preset merge.
2026-07-07 11:01:25 +02:00
maziggy b6da148890 fix(vp): evict MQTT clients on drain timeout + tighten TCP keepalive (#1872)
Reporter (H2C + macOS 26.5.1 + BS 2.8.0.50): after every Mac sleep/wake
    cycle, Bambu Studio couldn't see the VP or connect to it. Only fix was
    quit BS + reboot Bambuddy. The physical printer's own cloud/LAN link
    recovered in ~5 s from the same sleep — the delta was in VP session
    handling.

    Log evidence (bug-report-assets/logs/ddf1ede75df045cd94ad223d0f08f88a):

    - 14:04:06 healthy `1Hz status push: 60 pushes/min to :54698`
    - 14:04:06 → 14:09:16: five minutes of SSDP-only, no push summary for
      :54698, no OSError, no disconnect line
    - 14:09:16: new source port :54861 connects and authenticates fine —
      the server was not rejecting reconnects
    - 14:10:17 first DEBUG line: `MQTT drain timeout for
      device/…/report — client may be busy` — smoking gun

    Root cause: `_publish_to_report:1149` caught `asyncio.wait_for(drain,
    timeout=5)` TimeoutError at DEBUG and returned silently. TimeoutError
    is not OSError, so the push loop's `except OSError` at :441 never saw
    it — the zombie writer sat in self._clients until the kernel's default
    TCP keepalive detected the dead peer (Linux default: ~2 h 11 min).

    Two hunks:

    1. `_publish_to_report`: on drain TimeoutError, close the writer (best
       effort, catch Exception so an already-broken close() doesn't mask
       the raise) and raise BrokenPipeError, which IS OSError. Push loop
       evicts on the same tick.

    2. `_handle_client`: after SO_KEEPALIVE=1, set TCP_KEEPIDLE=60,
       TCP_KEEPINTVL=15, TCP_KEEPCNT=4 — dead-peer detection in ~2 min
       instead of ~2 h. `getattr(socket, ...)` guards keep it cross-
       platform (macOS uses TCP_KEEPALIVE not TCP_KEEPIDLE, other kernels
       may not expose all three — skip whichever is missing).

    What I got wrong first pass and corrected on log-read: hypothesised
    "missing MQTT session takeover on same client_id". Wrong. _handle_connect
    parses the protocol client_id but discards it (assignment commented out
    at :762), and self._clients is keyed on `f"{addr[0]}:{addr[1]}"` (socket
    peer), so every reconnect gets a distinct key. No takeover race exists.
    The log fixed this: the "not seen" symptom is BS-side (macOS UDP
    receive after sleep + BS holding the pre-sleep socket state), but the
    server-side amplifier was the zombie writer.
2026-07-07 11:00:55 +02:00
maziggy 6d10e3ff89 fix(vp): route non-proxy camera passthrough by target model — 6000 for A1/P1 (#1868)
Non-proxy VP mode hardcoded the camera-passthrough TCPProxy to
    listen_port=322 / target_port=322 regardless of the target printer's
    model. That port is correct for RTSPS models (X1/X2/H2/P2S), but A1 /
    A1 Mini / P1P / P1S use Bambu's proprietary chamber-image protocol on
    port 6000. Result: A1/P1 targets got a 322 listener with no upstream,
    OrcaSlicer Liveview failed with [2:-10061], BambuStudio's camera button
    timed out.

    Reporter confirmed a raw socat forwarder `<VP-IP>:6000 → <P1S-IP>:6000`
    restored the stream — the target camera works, the VP just wasn't
    publishing it.

    Proxy mode was unaffected because SlicerProxyManager already opens 6000
    (nominally file-transfer; Bambu reuses the port for chamber-image), so
    the passthrough coincidentally works there.

    Fix: read the target's model from
    `printer_manager.get_client(target_id).model` at the same point we read
    target_ip, then use `get_camera_port(target_model)` — the same source of
    truth as routes/camera.py — to pick 322 or 6000. Model comes from the
    physical printer, NOT self.model (the VP's spoofed identity has no
    bearing on how the real device serves its camera).

    Renamed the log tag from "RTSP" to f"Camera-{camera_port}" so support
    bundles show which protocol the VP is fronting at a glance. Kept the
    _rtsp_proxy attribute name to keep the diff tight; the block comment
    spells out that it doubles as chamber-image passthrough on A1/P1.
2026-07-07 11:00:32 +02:00
maziggy 0c7480f9ea fix(queue): edit modal shows printer/model selection for model-assigned items
Editing a queue item that was created with "Any of model X" left the
    printer selection area completely blank — the assignmentMode was
    initialised to 'model' from queueItem.target_model, but the three
    model-mode props (onAssignmentModeChange, onTargetModelChange,
    onTargetLocationChange) were gated behind !isEditing. That flipped
    modelAssignmentAvailable to false in PrinterSelector and hid the mode
    toggle, the model dropdown, AND the location filter; combined with the
    assignmentMode === 'printer' gate on the printer list, the whole
    selector rendered empty.

    Users hit this whenever they queued something to "Any of model X" and
    then wanted to change the target model / location — the only workaround
    was delete + re-queue.

    Fix: drop the !isEditing gate on all three PrinterSelector props. The
    submit path already handles both flavours (target_model+target_location
    with printer_id=null vs. printer_id with the target fields nulled), so
    un-gating the UI just surfaces the machinery that was already there.
    Edit is still only offered on pending items, so the mode-flip can't race
    an in-flight dispatch.
2026-07-07 11:00:08 +02:00
maziggy 8b49edf811 fix(mqtt): capture finish photo on last-layer edge, not FINISH state (#1867)
A1 Mini firmware skips stg_cur=22 entirely, so the finish-photo fallback
    fires at gcode_state=FINISH — which runs AFTER Bambu Studio has already
    executed the user's End G-code. Users with SwapMod plate-swap injected
    into End G-code always got a photo of the swapped (empty) plate.

    Add a layer_num >= total_layer_num edge trigger in _parse_print_data so
    the pre-capture fires the moment the last object layer completes, on
    every printer variant. Guarded by the existing _finish_photo_captured
    one-shot so stage-22 and FINISH-state hooks become no-ops for the same
    print — no framing regression on AMS printers without custom end G-code.
2026-07-07 10:59:36 +02:00
maziggy 703dc693d7 feat(currency): add Indonesian Rupiah (IDR) support (#1869)
Adds IDR with Rp symbol to the supported currencies list, available
    in Settings → Cost Tracking.
2026-07-07 10:59:06 +02:00