Commit Graph
2026 Commits
Author SHA1 Message Date
maziggy 4440c95976 fix(queue): skip preheat entirely when no loaded filament wants a chamber (issue #3041)
Preheat & Heat Soak delayed every PLA print by five to seven minutes and
    gave nothing back. The filament map correctly derived a chamber target of
    0, and the chamber phase correctly skipped -- but the stage then heated
    the bed, waited for it, and held the full soak anyway, because the soak
    had no idea it was holding for a chamber nobody asked for. The print's
    own G-code sets the bed the moment it starts, so the bed phase only moved
    the warm-up ahead of the FTP upload instead of overlapping with it.

    A 0 that comes out of the filament map now skips the stage before any
    command goes out. The one thing the skip still does is put the airduct
    flap back to cooling on the models that have one -- an H2D left in
    heating mode by the ABS job before it would otherwise cook the PLA that
    follows, and that costs one MQTT command and no waiting.

    Explicit instructions are untouched. A chamber target of 0 typed into a
    print's own override still heats the bed and runs the soak, which is what
    the queue documentation has always promised it does, as does forcing a
    print's Preheat override to On. Prints that want chamber heat are
    unaffected, including the P1S/P1P/A1 tier where the bed and the soak
    timer are the whole mechanism.

    The existing unit tests all ran with soak_seconds=0, which is why the
    production default was never exercised; the PLA test now runs at the real
    default and asserts nothing is dispatched and nothing is slept.

    Surfaced in the UI on the way through: the Settings hint claimed the
    derived 0 skipped "the chamber phase", and the per-print chamber override
    field said nothing about a typed 0 meaning bed-only -- a user reaching
    for 0 to turn preheat off got the delay instead.
2026-09-20 13:30:36 +02:00
maziggy ad09406672 fix(slicer): strip zero-valued filament-index sentinels, and sanitise the preview slice too (issue #3030)
Bambu Studio writes 0 into wall_filament, sparse_infill_filament and
    solid_infill_filament to mean "use whichever filament the object is set
    to". Bambu Studio and OrcaSlicer 2.4 define these min 0 and accept it;
    OrcaSlicer 2.3 and earlier used the 1-based scheme (min 1, default 1)
    and reject it with "0 not in range [1.000000,...]". Sidecar images are
    version-tagged, so an install can be pinned to one of those builds.

    Same shape as the -1 inherit markers from #1201 with a different marker,
    so the allowlist becomes a key-to-marker map rather than one global
    constant. The buckets must not bleed: a -1 on a filament index is a real
    value, and a 0 on a raft field is a setting the user chose.

    The key is removed rather than rewritten, which is what makes it safe on
    every build. The CLI then uses its own default: 0 where 0 was legal
    (unchanged), 1 on the older builds, which is what "the active filament"
    means under that scheme.

    The preview slice never ran the sanitiser at all, so a file that sliced
    fine could still fail its automatic plate preview and fall back to the
    painted-face heuristic. It matters more there than in a real slice: the
    preview runs on the file's own embedded settings, so there is no
    --load-settings pass that could supply a replacement for a field the
    range validator has already rejected. That also explains the reported
    "same error on a later attempt of an unchanged file" without any second
    copy of the keys -- the validator that emits it reads the merged global
    config, which per-object model_settings.config overrides never reach.

    The sanitiser moves to utils/threemf_tools so the service can use it
    without importing a route module, and both preview callers pick it up
    from one place. Drops _strip_3mf_embedded_settings and its constant,
    which have had no callers since the strip-everything experiment was
    reverted.
2026-09-20 13:30:11 +02:00
maziggy 417d03d174 fix(slicer): keep protocol-handler download tokens valid for their whole TTL (issue #3029)
The Slice and Open in Slicer actions mint a short-lived token and put it in
    the URL, because a protocol handler cannot carry an Authorization header.
    That token was spent by the first request to reach the endpoint, which made
    the handoff depend on the slicer fetching the URL exactly once. Nothing
    guarantees that: Bambu Studio's downloader retries three times after a
    failed attempt, transfers get resumed, on-access scanners fetch. The first
    request won and the slicer was handed a 403.

    verify_slicer_download_token takes a keyword-only single_use flag. The
    default still consumes via DELETE...RETURNING; single_use=False verifies
    with a SELECT and leaves the row for the rest of its five-minute TTL. The
    stored row is the same either way, so the endpoint decides, not the mint.

    The three protocol-handler downloads pass single_use=False: a library file,
    an archive's sliced 3MF, an archive's source 3MF. Resource binding and
    expiry are untouched. The two browser downloads keep consuming, because
    what they hand over is itself consumed -- the prepared printer bundle is
    deleted the moment it has been streamed.

    Also: add "/source-dl/" to PUBLIC_API_PATTERNS. Those patterns match by
    substring and the source 3MF route's segment is source-dl, which does not
    contain "/dl/", so with auth enabled the middleware rejected the slicer's
    header-less request before the route's token check ran. Open source 3MF in
    slicer could never work on an install with authentication on.
2026-09-20 13:29:25 +02:00
maziggy e1fad9d68f fix(auth): decouple media routes from the camera stream token (issue #3025)
Thirteen routes with nothing to do with a camera took the camera stream
    token as their credential -- library and archive thumbnails, plate
    previews and plate thumbnails, timelapses, print photos, archive QR
    codes, project covers, print-log thumbnails, printer covers and
    external-link icons. A browser cannot put an Authorization header on an
    <img src>, so these need a credential that fits in the URL, and the
    camera token was the only one that existed. Minting one costs
    camera:view, so a user granted library access to their own files got a
    grid of broken images until they were also handed the live camera.

    Adds a media token: minted by POST /auth/media-token behind plain
    authentication, and identified -- it records the principal the way the
    websocket token does rather than being anonymous the way the camera
    token is. Each route now gates on the permission and ownership rules of
    the resource it serves, through the same _ensure_*_visible helpers its
    header-authenticated siblings already use. The three camera routes keep
    the camera token, and require_camera_stream_token_if_auth_enabled now
    documents that it is for those only.

    The media dependencies accept ordinary Authorization / X-API-Key headers
    as well as ?token=, delegating that path to the existing checkers, so
    API-key scope rules and the per-printer allowlist are unchanged.

    Long-lived camera_stream, camwall and overlay tokens are deliberately
    not accepted on the media routes -- those are handed to kiosks, walls
    and Home Assistant to display video. The cam wall, streaming overlay and
    kiosk views use only the three camera routes and are unaffected.

    Frontend: withMediaToken alongside withStreamToken, and
    useStreamTokenSync fetches a media token for every signed-in user while
    asking for a camera token only when the user can mint one, which also
    stops the 403 that fired on every page load for everyone else.

    Also fixed, same class:
    - /printers/{id}/files/plate-thumbnail/{i} is rendered in an <img> but
      had a header-only guard, so the file manager's plate thumbnails 401'd
      whenever auth was enabled. It now takes a media token too.
    - getProjectCoverImageUrl returned a URL ending in ?token=, and the
      project edit dialog appended its own ?v= cache-buster after it, so the
      second ? landed inside the token value. The version is now a parameter
      applied before the token.

    Tests: 15 integration tests for the token boundary, permission
    enforcement and per-row scoping; 10 frontend tests for the URL split and
    the two-query hook. test_cover_image_get_uses_stream_token_gate is
    renamed and repointed at the media gate -- what it pins, that the
    credential has to fit in a URL, is unchanged.
2026-09-20 13:28:50 +02:00
maziggy ef6446d30a fix(auth): let the sidebar read install flags without settings:read (issue #3023)
cost_centers:read_own exists so a non-admin can see their own wallet, balance
    and cost-centre spend, and the Finance page honoured it -- typing the URL
    worked and rendered their balance. The sidebar never offered the entry.

    It decides whether to show Finance by reading billing_enabled from
    GET /settings, which requires SETTINGS_READ. A non-admin gets 403 there, so
    the value arrived undefined, `undefined !== true` held, and the entry was
    hidden from precisely the users the permission was written for. The permission
    map and the route guard were both already right; only discovery was broken.

    Three more fields came from that same 403, and one of them failed the other way
    up. The Notifications gate tests `=== false`, which undefined never satisfies,
    so an administrator who switched user notifications off still left the entry
    showing to the non-admins it governs. Nobody reported that one, and no
    administrator could have reproduced either: administrators can read /settings.
    The remaining two were quieter -- the sponsor prompt fell back to EUR whatever
    the install uses, and the update check ran where it had been turned off.

    SETTINGS_READ cannot be the price of knowing whether billing is on. It also
    grants sight of the SMTP, LDAP and MQTT credentials, which is the reason
    /settings/ui-preferences exists at all.

    So: a second endpoint, GET /settings/ui-flags, carrying those four fields and
    asking only that the caller be signed in, via the existing
    require_auth_if_enabled. Layout drops its /settings query altogether, which
    closes the class rather than the two instances that happened to be visible.

    Deliberately not four more fields on /ui-preferences. That endpoint is served
    to anyone at all on the recorded grounds that its contents are "public defaults
    that ship with the app" (test_route_auth_coverage.py), and its field set is
    pinned by a test written to make anyone adding to it stop and think. These
    fields are not defaults -- they say how this deployment is configured -- so
    they get their own endpoint at their own trust level instead of stretching that
    charter to fit them. require_auth_if_enabled also keeps the auth-disabled case
    that /ui-preferences was ungated for: "works when there is no auth" and
    "readable by anyone" are different statements, and conflating them is what put
    a settings read in front of a permission that never needed one.

    Twelve tests. Backend pins that the operator can read the flags, that the same
    operator still gets 403 from /settings, that an anonymous caller is refused
    when auth is on, that it answers when auth is off, the exact field set, that no
    credential ever appears, and that the public endpoint did not quietly gain
    these fields. Frontend pins Finance visible for cost_centers:read_own with
    /settings returning 403, and Notifications hidden when the flag is off -- each
    waiting on a positive signal before asserting an absence, so the negative cases
    cannot pass before the query resolves.

    Reported by @lonix, who traced it to the queryKey and the route gate.
2026-09-20 13:28:17 +02:00
maziggy 23a6633f42 fix(queue): say when an unscheduled item runs instead of calling it ASAP (issue #3018)
The print dialog offers ASAP, Queue and Schedule. ASAP and Queue differ only
    in where the item is inserted, and neither is stored on the item -- scheduleType
    is a frontend-only concept, and grep finds no "asap" anywhere in the backend. So
    the queue's time column had nothing to read but scheduled_time, and labelled
    every unscheduled item "ASAP": the name of the one mode the user may well have
    chosen against.

    Someone who picked Queue then watched their row appear as ASAP and start
    immediately, and concluded Bambuddy had overridden them. Two reporters wrote
    that same sentence thirteen months apart, and #2557 was closed as A2L-specific
    after the first of them -- kilrah replied there with an X1C before filing this.

    The column answers when an item runs, so it now says that. The key is renamed
    whenFree rather than just retranslated: left called asap, the next translator
    puts ASAP back.

    The dispatch is unchanged, because it was right. A print scheduled for later
    does not reserve the printer until then; an unscheduled item behind it uses the
    idle printer rather than leaving an X1C dark until 6 AM. Two of the new tests
    pin that, so it does not get "fixed" later on the strength of a report like this
    one.

    What genuinely could not answer the question was the queue's own log. Its
    per-printer line called every entry in busy_printers "not available" -- but that
    set holds both printers that cannot take work and printers the pass has just
    claimed for some, which are opposite facts. It also read printer state at
    logging time rather than at the decision, so #3018's bundle carries

        Queue: printer 1 not available — connected=True, state=IDLE, ...
        Launching 1 upload(s) (pool 0/4 in flight)
        Starting queue item 18

    a printer reported unavailable, evidence that it was available, and a dispatch
    to it, in three consecutive lines. It is the first line anyone greps for "why
    did my item not go out".

    Each of the nine sites that removes a printer from a pass now records why, and
    the summary reports a claim as a reservation and everything else as an
    obstruction with its reason. The live fields stay, since a bundle reader wants
    them next, but are labelled as read now rather than offered as the cause.
    print_scheduler.py:1210 already documented that these two meanings differ -- the
    dispatching_printers snapshot exists for it. This carries that distinction into
    the log.
2026-09-20 13:27:43 +02:00
maziggy eab55cef75 fix(archives): report a refused FTPS handshake as the printer, not the slicer (issue #2780)
The Archives banner picks its wording from a priority list of the causes it
    knows. REASON_FTPS_COOLOFF was added by #2957 and never put in that list, so an
    install whose empty archives all came from a printer refusing the TLS handshake
    matched nothing, got reason: null, and fell to the original wording: the slicer
    did not leave the .gcode.3mf on the card, switch on "Store sent files on
    external storage", here is installation step 4.

    Every clause of that is wrong for this cause. The slicer did write the file --
    reason he read the whole thing as Bambuddy being broken. The setting was
    already on. And there is nothing on his side to change: the printer's file
    service answered port 990 with something that is not TLS, so no lookup ever
    ran and where the file went was never tested. It is #2899's mistake -- an
    error message describing a cause that was ruled out before it was printed --
    in a surface that did not get that pass.

    The slug now leads the list rather than joining the end of it. The other three
    describe an install working as configured and each ends in something the
    operator can change; this one reports a fault nobody can yet explain, which is
    both the more urgent thing to say and the thing that produces a useful report.
    The banner also dismisses one-shot into localStorage, so a reason ranked below
    another is not deferred to next time -- it is never shown to that user again.
    Ranking it first cannot bury a permanent cause in exchange: a successful
    recovery clears the row's markers (#2957), so a row still carrying this slug is
    one whose retry failed too, days after the print.

    New wording in all fourteen languages says the printer refused the connection,
    that this is not a slicer setting and not something the operator did, that
    Bambuddy comes back for the file when the five-minute pause clears so a brief
    episode fills itself in, and that a card still empty means the refusal outlasted
    the retry. It links to the handshake entry in the troubleshooting guide instead
    of to the installation guide.

    The client's getNo3MFWarning type still declared the old three-slug union, which
    made all three new comparisons provably dead -- caught by tsc, not by any test.

    Four tests. One pins the slug reaching the banner, one pins it outranking the
    three settled causes, one pins those three keeping their order behind it, and
    one asserts the rendered wording carries no slicer advice at all.

    Also corrects the wiki page these reports are pointed at. It said to power-cycle
    the printer; the reporter who prompted that advice power-cycled both of his and
    the failure continued unchanged, and bambu_ftp.py has carried the retraction in
    a comment since. The page now states what was actually measured -- that a
    version mismatch reports itself differently, that every printer probed refuses
    TLS 1.3 and completes on 1.2 so there is no version to fall back from, and that
    three P2S units failed while three more on the same switch never did -- says
    plainly that the trigger is unknown, and names the one cleartext-probe line
    worth collecting.
2026-09-20 13:27:10 +02:00
maziggy 58df1cb866 feat(ftp): log how every FTP session closes (issue #3009)
disconnect() and _abandon_connection() logged nothing, at any level. A
    session closed cleanly and a socket genuinely abandoned therefore produced
    identical output -- none -- and the only way to tell them apart was to read
    the source.

    That is how #3009 was filed. Its trace shows a print completion opening two
    FTP connections, deleting one file, and then nothing until the printer was
    powered off 21 minutes later, read as connections left open and offered as a
    mechanism for the 0500-C010 SD-card error that #645 has been chasing since
    April. The two connections are the post-print SD cleanup in main.py walking
    its candidate filenames, each through delete_file_async, which closes in a
    finally; running that against the mock FTPS server shows the server logging
    "FTP session closed (disconnect)" for both the 250 and the 550, holding zero
    sessions afterwards. Nothing in a support bundle could have shown that.

    Both close paths now log one DEBUG line: the printer, whether QUIT was
    acknowledged or the socket had to be dropped without it, why, and how long
    the session was held. Every connect in a debug log now has a matching close.

    The duration comes from a stamp taken when the control socket opens rather
    than after login, so a session that dies during login is accounted for too;
    where no socket was ever established the line says "held unknown" rather
    than claiming a number. The four connect() failure paths pass their own
    reason, so a close line stands on its own next to the warning above it.

    Nine tests, seven of which fail against the unlogged version. The other two
    assert silence -- a bare disconnect(), and a connect skipped by the handshake
    cool-off -- where no socket was opened and a close line would pair with no
    connect.
2026-09-20 13:26:42 +02:00
maziggy 8186ef817e fix(orca-cloud): close the HTTP client when an authenticated build fails
OrcaCloudService owns an httpx client from construction, and every path in
    _build_authenticated_service after that point can raise: no stored refresh
    token, a rejected refresh, an unreachable Orca, and the token-rotation write.
    On success the caller closes the client. On failure nobody is ever handed it,
    so all four paths leaked one into the connection pool.

    That went unnoticed while the only callers were routes, where the trigger is a
    person retrying a broken sign-in a handful of times. It stopped being harmless
    in 9434875f, which added a caller in spool assignment -- one build per
    Orca-referenced spool, failing on every assignment for as long as the stored
    credentials cannot be refreshed.

    The unwind guard catches BaseException rather than Exception: a cancelled
    request leaks the client just as surely as a failed refresh, and cancellation
    during shutdown is exactly when dangling sockets are least welcome. The close
    inside it is guarded in turn, so a failing cleanup cannot replace the error the
    caller needs to see -- least of all a CancelledError, which has to keep
    propagating for cancellation to work at all.

    Six tests. Four fail against the unguarded builder, verified by reverting the
    guard and re-running; the other two pin the surrounding contract (a failing
    close must not mask the real error, and a successful build must leave the
    client open for its caller) and pass either way. The shared _expired_service
    helper now gives the mock an awaitable close(), so the four pre-existing
    refresh tests exercise the same path.

    Also corrects two comments and the changelog entry from 9434875f, which
    overstated what the captures support. They claimed Bambu Cloud returns a
    preset's filament_id in either of two places and only one was read. The
    responses recorded in #1053 show something narrower: a Studio-created preset
    carries it on the envelope, and an Orca-created one has none at all -- the
    envelope says null and `setting` is a delta from the base. The `setting` lookup
    stays as belt-and-braces for a shape no captured response has needed yet, but
    it is not why a custom profile reached the slicer as its base. That is the
    OrcaSlicer preset format having no filament_id field, filed upstream as
    OrcaSlicer PR #13315.

    The eight-character truncation is now evidenced across three models rather than
    one -- an A1 storing PFUS9DDC of PFUS9DDC938FE3AB8F, a P1S storing PFUS7A65 of
    PFUS7A65290D3DADC4, and an H2D storing 8219C45D of an Orca profile UUID.
2026-09-20 13:26:02 +02:00
maziggy a3e6fae5cb fix(ams): resolve a custom filament's own id from every preset source (issue #3003)
A custom filament profile reaches an AMS slot as itself through exactly one
    field, tray_info_idx, and every source we can read that id from was reading it
    from the wrong place or not reading it at all.

    Bambu Cloud returns a preset's own filament_id either on the response envelope
    or inside the preset JSON under `setting`, and only the envelope was read.
    Presets of the second shape fell through to the base_id branch and reached the
    slicer as the Bambu filament they inherit from. filament_type next door already
    handled both spreads; filament_id now does too.

    Orca Cloud was absent from the resolver entirely. A spool stores the bare
    profile UUID, which matched no branch and fell through normalize_slicer_filament
    -- a function that passes anything it does not recognise straight through -- so
    a 36-character UUID went into the field. Orca profiles carry their own
    filament_id in the slicer JSON that OrcaProfileDetail already exposes under
    `setting`, so the lookup is the same one the Bambu branch does. It is
    best-effort: no pairing, a dead token or a missing orca_cloud:auth permission
    degrades to the fallback rather than failing the assignment, and it passes
    clear_on_auth_failure=False because a background caller cannot tell a real
    revocation from a lost refresh-rotation race.

    configure_ams_slot sent the cloud setting_id as tray_info_idx when it found no
    real filament id. That field is 8 characters on the printer -- exactly the width
    of a local preset id, less than half a cloud one. Measured on the reporter's A1:
    sent PFUS9ddc938fe3ab8f, the tray read back PFUS9DDC, acknowledged as a success.
    The slot then resolved to nothing, so the slicer showed Generic anyway and the
    calibration table, keyed by the same field, lost the slot. It now falls back to
    the slot's existing filament id or the generic for the material, and the route's
    guard was aligned with the resolver's so both refuse the same four shapes from
    one shared definition.

    This reverses the contract #1053 pinned. Six tests asserted that the PFUS
    belonged in tray_info_idx; the A1 capture shows it never worked, so they were
    rewritten with the measurement in their docstrings.

    Verified against 874 AMS trays across twelve models in the support archive: 92
    already carry a custom "P" + 7 hex filament id, which is what confirms the
    mechanism works and this is a lookup failure rather than a platform limit. No
    tray on any model carries a setting_id, so a profile with no filament_id of its
    own still cannot be told apart from its base.
2026-09-20 13:25:27 +02:00
maziggy 5584dca898 Bumped version 2026-09-20 13:19:02 +02:00
maziggy 069ee8fc87 fix(queue): skip preheat entirely when no loaded filament wants a chamber (issue #3041)
Preheat & Heat Soak delayed every PLA print by five to seven minutes and
gave nothing back. The filament map correctly derived a chamber target of
0, and the chamber phase correctly skipped -- but the stage then heated
the bed, waited for it, and held the full soak anyway, because the soak
had no idea it was holding for a chamber nobody asked for. The print's
own G-code sets the bed the moment it starts, so the bed phase only moved
the warm-up ahead of the FTP upload instead of overlapping with it.

A 0 that comes out of the filament map now skips the stage before any
command goes out. The one thing the skip still does is put the airduct
flap back to cooling on the models that have one -- an H2D left in
heating mode by the ABS job before it would otherwise cook the PLA that
follows, and that costs one MQTT command and no waiting.

Explicit instructions are untouched. A chamber target of 0 typed into a
print's own override still heats the bed and runs the soak, which is what
the queue documentation has always promised it does, as does forcing a
print's Preheat override to On. Prints that want chamber heat are
unaffected, including the P1S/P1P/A1 tier where the bed and the soak
timer are the whole mechanism.

The existing unit tests all ran with soak_seconds=0, which is why the
production default was never exercised; the PLA test now runs at the real
default and asserts nothing is dispatched and nothing is slept.

Surfaced in the UI on the way through: the Settings hint claimed the
derived 0 skipped "the chamber phase", and the per-print chamber override
field said nothing about a typed 0 meaning bed-only -- a user reaching
for 0 to turn preheat off got the delay instead.
2026-09-07 16:38:36 +02:00
maziggy 9a837d19a1 fix(slicer): strip zero-valued filament-index sentinels, and sanitise the preview slice too (issue #3030)
Bambu Studio writes 0 into wall_filament, sparse_infill_filament and
solid_infill_filament to mean "use whichever filament the object is set
to". Bambu Studio and OrcaSlicer 2.4 define these min 0 and accept it;
OrcaSlicer 2.3 and earlier used the 1-based scheme (min 1, default 1)
and reject it with "0 not in range [1.000000,...]". Sidecar images are
version-tagged, so an install can be pinned to one of those builds.

Same shape as the -1 inherit markers from #1201 with a different marker,
so the allowlist becomes a key-to-marker map rather than one global
constant. The buckets must not bleed: a -1 on a filament index is a real
value, and a 0 on a raft field is a setting the user chose.

The key is removed rather than rewritten, which is what makes it safe on
every build. The CLI then uses its own default: 0 where 0 was legal
(unchanged), 1 on the older builds, which is what "the active filament"
means under that scheme.

The preview slice never ran the sanitiser at all, so a file that sliced
fine could still fail its automatic plate preview and fall back to the
painted-face heuristic. It matters more there than in a real slice: the
preview runs on the file's own embedded settings, so there is no
--load-settings pass that could supply a replacement for a field the
range validator has already rejected. That also explains the reported
"same error on a later attempt of an unchanged file" without any second
copy of the keys -- the validator that emits it reads the merged global
config, which per-object model_settings.config overrides never reach.

The sanitiser moves to utils/threemf_tools so the service can use it
without importing a route module, and both preview callers pick it up
from one place. Drops _strip_3mf_embedded_settings and its constant,
which have had no callers since the strip-everything experiment was
reverted.
2026-09-07 14:37:49 +02:00
maziggy b9bd312826 fix(slicer): keep protocol-handler download tokens valid for their whole TTL (issue #3029)
The Slice and Open in Slicer actions mint a short-lived token and put it in
the URL, because a protocol handler cannot carry an Authorization header.
That token was spent by the first request to reach the endpoint, which made
the handoff depend on the slicer fetching the URL exactly once. Nothing
guarantees that: Bambu Studio's downloader retries three times after a
failed attempt, transfers get resumed, on-access scanners fetch. The first
request won and the slicer was handed a 403.

verify_slicer_download_token takes a keyword-only single_use flag. The
default still consumes via DELETE...RETURNING; single_use=False verifies
with a SELECT and leaves the row for the rest of its five-minute TTL. The
stored row is the same either way, so the endpoint decides, not the mint.

The three protocol-handler downloads pass single_use=False: a library file,
an archive's sliced 3MF, an archive's source 3MF. Resource binding and
expiry are untouched. The two browser downloads keep consuming, because
what they hand over is itself consumed -- the prepared printer bundle is
deleted the moment it has been streamed.

Also: add "/source-dl/" to PUBLIC_API_PATTERNS. Those patterns match by
substring and the source 3MF route's segment is source-dl, which does not
contain "/dl/", so with auth enabled the middleware rejected the slicer's
header-less request before the route's token check ran. Open source 3MF in
slicer could never work on an install with authentication on.
2026-09-07 14:05:25 +02:00
maziggy 816f073a9e fix(auth): decouple media routes from the camera stream token (issue #3025)
Thirteen routes with nothing to do with a camera took the camera stream
token as their credential -- library and archive thumbnails, plate
previews and plate thumbnails, timelapses, print photos, archive QR
codes, project covers, print-log thumbnails, printer covers and
external-link icons. A browser cannot put an Authorization header on an
<img src>, so these need a credential that fits in the URL, and the
camera token was the only one that existed. Minting one costs
camera:view, so a user granted library access to their own files got a
grid of broken images until they were also handed the live camera.

Adds a media token: minted by POST /auth/media-token behind plain
authentication, and identified -- it records the principal the way the
websocket token does rather than being anonymous the way the camera
token is. Each route now gates on the permission and ownership rules of
the resource it serves, through the same _ensure_*_visible helpers its
header-authenticated siblings already use. The three camera routes keep
the camera token, and require_camera_stream_token_if_auth_enabled now
documents that it is for those only.

The media dependencies accept ordinary Authorization / X-API-Key headers
as well as ?token=, delegating that path to the existing checkers, so
API-key scope rules and the per-printer allowlist are unchanged.

Long-lived camera_stream, camwall and overlay tokens are deliberately
not accepted on the media routes -- those are handed to kiosks, walls
and Home Assistant to display video. The cam wall, streaming overlay and
kiosk views use only the three camera routes and are unaffected.

Frontend: withMediaToken alongside withStreamToken, and
useStreamTokenSync fetches a media token for every signed-in user while
asking for a camera token only when the user can mint one, which also
stops the 403 that fired on every page load for everyone else.

Also fixed, same class:
- /printers/{id}/files/plate-thumbnail/{i} is rendered in an <img> but
  had a header-only guard, so the file manager's plate thumbnails 401'd
  whenever auth was enabled. It now takes a media token too.
- getProjectCoverImageUrl returned a URL ending in ?token=, and the
  project edit dialog appended its own ?v= cache-buster after it, so the
  second ? landed inside the token value. The version is now a parameter
  applied before the token.

Tests: 15 integration tests for the token boundary, permission
enforcement and per-row scoping; 10 frontend tests for the URL split and
the two-query hook. test_cover_image_get_uses_stream_token_gate is
renamed and repointed at the media gate -- what it pins, that the
credential has to fit in a URL, is unchanged.
2026-09-07 13:38:15 +02:00
maziggy 93eeb05264 fix(auth): let the sidebar read install flags without settings:read (issue #3023)
cost_centers:read_own exists so a non-admin can see their own wallet, balance
and cost-centre spend, and the Finance page honoured it -- typing the URL
worked and rendered their balance. The sidebar never offered the entry.

It decides whether to show Finance by reading billing_enabled from
GET /settings, which requires SETTINGS_READ. A non-admin gets 403 there, so
the value arrived undefined, `undefined !== true` held, and the entry was
hidden from precisely the users the permission was written for. The permission
map and the route guard were both already right; only discovery was broken.

Three more fields came from that same 403, and one of them failed the other way
up. The Notifications gate tests `=== false`, which undefined never satisfies,
so an administrator who switched user notifications off still left the entry
showing to the non-admins it governs. Nobody reported that one, and no
administrator could have reproduced either: administrators can read /settings.
The remaining two were quieter -- the sponsor prompt fell back to EUR whatever
the install uses, and the update check ran where it had been turned off.

SETTINGS_READ cannot be the price of knowing whether billing is on. It also
grants sight of the SMTP, LDAP and MQTT credentials, which is the reason
/settings/ui-preferences exists at all.

So: a second endpoint, GET /settings/ui-flags, carrying those four fields and
asking only that the caller be signed in, via the existing
require_auth_if_enabled. Layout drops its /settings query altogether, which
closes the class rather than the two instances that happened to be visible.

Deliberately not four more fields on /ui-preferences. That endpoint is served
to anyone at all on the recorded grounds that its contents are "public defaults
that ship with the app" (test_route_auth_coverage.py), and its field set is
pinned by a test written to make anyone adding to it stop and think. These
fields are not defaults -- they say how this deployment is configured -- so
they get their own endpoint at their own trust level instead of stretching that
charter to fit them. require_auth_if_enabled also keeps the auth-disabled case
that /ui-preferences was ungated for: "works when there is no auth" and
"readable by anyone" are different statements, and conflating them is what put
a settings read in front of a permission that never needed one.

Twelve tests. Backend pins that the operator can read the flags, that the same
operator still gets 403 from /settings, that an anonymous caller is refused
when auth is on, that it answers when auth is off, the exact field set, that no
credential ever appears, and that the public endpoint did not quietly gain
these fields. Frontend pins Finance visible for cost_centers:read_own with
/settings returning 403, and Notifications hidden when the flag is off -- each
waiting on a positive signal before asserting an absence, so the negative cases
cannot pass before the query resolves.

Reported by @lonix, who traced it to the queryKey and the route gate.
2026-09-07 12:48:31 +02:00
maziggy 09b4584d5f fix(queue): say when an unscheduled item runs instead of calling it ASAP (issue #3018)
The print dialog offers ASAP, Queue and Schedule. ASAP and Queue differ only
in where the item is inserted, and neither is stored on the item -- scheduleType
is a frontend-only concept, and grep finds no "asap" anywhere in the backend. So
the queue's time column had nothing to read but scheduled_time, and labelled
every unscheduled item "ASAP": the name of the one mode the user may well have
chosen against.

Someone who picked Queue then watched their row appear as ASAP and start
immediately, and concluded Bambuddy had overridden them. Two reporters wrote
that same sentence thirteen months apart, and #2557 was closed as A2L-specific
after the first of them -- kilrah replied there with an X1C before filing this.

The column answers when an item runs, so it now says that. The key is renamed
whenFree rather than just retranslated: left called asap, the next translator
puts ASAP back.

The dispatch is unchanged, because it was right. A print scheduled for later
does not reserve the printer until then; an unscheduled item behind it uses the
idle printer rather than leaving an X1C dark until 6 AM. Two of the new tests
pin that, so it does not get "fixed" later on the strength of a report like this
one.

What genuinely could not answer the question was the queue's own log. Its
per-printer line called every entry in busy_printers "not available" -- but that
set holds both printers that cannot take work and printers the pass has just
claimed for some, which are opposite facts. It also read printer state at
logging time rather than at the decision, so #3018's bundle carries

    Queue: printer 1 not available — connected=True, state=IDLE, ...
    Launching 1 upload(s) (pool 0/4 in flight)
    Starting queue item 18

a printer reported unavailable, evidence that it was available, and a dispatch
to it, in three consecutive lines. It is the first line anyone greps for "why
did my item not go out".

Each of the nine sites that removes a printer from a pass now records why, and
the summary reports a claim as a reservation and everything else as an
obstruction with its reason. The live fields stay, since a bundle reader wants
them next, but are labelled as read now rather than offered as the cause.
print_scheduler.py:1210 already documented that these two meanings differ -- the
dispatching_printers snapshot exists for it. This carries that distinction into
the log.
2026-09-07 12:22:26 +02:00
maziggy 6564c74071 fix(archives): report a refused FTPS handshake as the printer, not the slicer (issue #2780)
The Archives banner picks its wording from a priority list of the causes it
knows. REASON_FTPS_COOLOFF was added by #2957 and never put in that list, so an
install whose empty archives all came from a printer refusing the TLS handshake
matched nothing, got reason: null, and fell to the original wording: the slicer
did not leave the .gcode.3mf on the card, switch on "Store sent files on
external storage", here is installation step 4.

Every clause of that is wrong for this cause. The slicer did write the file --
reason he read the whole thing as Bambuddy being broken. The setting was
already on. And there is nothing on his side to change: the printer's file
service answered port 990 with something that is not TLS, so no lookup ever
ran and where the file went was never tested. It is #2899's mistake -- an
error message describing a cause that was ruled out before it was printed --
in a surface that did not get that pass.

The slug now leads the list rather than joining the end of it. The other three
describe an install working as configured and each ends in something the
operator can change; this one reports a fault nobody can yet explain, which is
both the more urgent thing to say and the thing that produces a useful report.
The banner also dismisses one-shot into localStorage, so a reason ranked below
another is not deferred to next time -- it is never shown to that user again.
Ranking it first cannot bury a permanent cause in exchange: a successful
recovery clears the row's markers (#2957), so a row still carrying this slug is
one whose retry failed too, days after the print.

New wording in all fourteen languages says the printer refused the connection,
that this is not a slicer setting and not something the operator did, that
Bambuddy comes back for the file when the five-minute pause clears so a brief
episode fills itself in, and that a card still empty means the refusal outlasted
the retry. It links to the handshake entry in the troubleshooting guide instead
of to the installation guide.

The client's getNo3MFWarning type still declared the old three-slug union, which
made all three new comparisons provably dead -- caught by tsc, not by any test.

Four tests. One pins the slug reaching the banner, one pins it outranking the
three settled causes, one pins those three keeping their order behind it, and
one asserts the rendered wording carries no slicer advice at all.

Also corrects the wiki page these reports are pointed at. It said to power-cycle
the printer; the reporter who prompted that advice power-cycled both of his and
the failure continued unchanged, and bambu_ftp.py has carried the retraction in
a comment since. The page now states what was actually measured -- that a
version mismatch reports itself differently, that every printer probed refuses
TLS 1.3 and completes on 1.2 so there is no version to fall back from, and that
three P2S units failed while three more on the same switch never did -- says
plainly that the trigger is unknown, and names the one cleartext-probe line
worth collecting.
2026-09-07 11:26:01 +02:00
maziggy 10f0900fbc feat(ftp): log how every FTP session closes (issue #3009)
disconnect() and _abandon_connection() logged nothing, at any level. A
session closed cleanly and a socket genuinely abandoned therefore produced
identical output -- none -- and the only way to tell them apart was to read
the source.

That is how #3009 was filed. Its trace shows a print completion opening two
FTP connections, deleting one file, and then nothing until the printer was
powered off 21 minutes later, read as connections left open and offered as a
mechanism for the 0500-C010 SD-card error that #645 has been chasing since
April. The two connections are the post-print SD cleanup in main.py walking
its candidate filenames, each through delete_file_async, which closes in a
finally; running that against the mock FTPS server shows the server logging
"FTP session closed (disconnect)" for both the 250 and the 550, holding zero
sessions afterwards. Nothing in a support bundle could have shown that.

Both close paths now log one DEBUG line: the printer, whether QUIT was
acknowledged or the socket had to be dropped without it, why, and how long
the session was held. Every connect in a debug log now has a matching close.

The duration comes from a stamp taken when the control socket opens rather
than after login, so a session that dies during login is accounted for too;
where no socket was ever established the line says "held unknown" rather
than claiming a number. The four connect() failure paths pass their own
reason, so a close line stands on its own next to the warning above it.

Nine tests, seven of which fail against the unlogged version. The other two
assert silence -- a bare disconnect(), and a connect skipped by the handshake
cool-off -- where no socket was opened and a close line would pair with no
connect.
2026-09-07 10:54:55 +02:00
maziggy f3b1c59169 fix(orca-cloud): close the HTTP client when an authenticated build fails
OrcaCloudService owns an httpx client from construction, and every path in
_build_authenticated_service after that point can raise: no stored refresh
token, a rejected refresh, an unreachable Orca, and the token-rotation write.
On success the caller closes the client. On failure nobody is ever handed it,
so all four paths leaked one into the connection pool.

That went unnoticed while the only callers were routes, where the trigger is a
person retrying a broken sign-in a handful of times. It stopped being harmless
in 9434875f, which added a caller in spool assignment -- one build per
Orca-referenced spool, failing on every assignment for as long as the stored
credentials cannot be refreshed.

The unwind guard catches BaseException rather than Exception: a cancelled
request leaks the client just as surely as a failed refresh, and cancellation
during shutdown is exactly when dangling sockets are least welcome. The close
inside it is guarded in turn, so a failing cleanup cannot replace the error the
caller needs to see -- least of all a CancelledError, which has to keep
propagating for cancellation to work at all.

Six tests. Four fail against the unguarded builder, verified by reverting the
guard and re-running; the other two pin the surrounding contract (a failing
close must not mask the real error, and a successful build must leave the
client open for its caller) and pass either way. The shared _expired_service
helper now gives the mock an awaitable close(), so the four pre-existing
refresh tests exercise the same path.

Also corrects two comments and the changelog entry from 9434875f, which
overstated what the captures support. They claimed Bambu Cloud returns a
preset's filament_id in either of two places and only one was read. The
responses recorded in #1053 show something narrower: a Studio-created preset
carries it on the envelope, and an Orca-created one has none at all -- the
envelope says null and `setting` is a delta from the base. The `setting` lookup
stays as belt-and-braces for a shape no captured response has needed yet, but
it is not why a custom profile reached the slicer as its base. That is the
OrcaSlicer preset format having no filament_id field, filed upstream as
OrcaSlicer PR #13315.

The eight-character truncation is now evidenced across three models rather than
one -- an A1 storing PFUS9DDC of PFUS9DDC938FE3AB8F, a P1S storing PFUS7A65 of
PFUS7A65290D3DADC4, and an H2D storing 8219C45D of an Orca profile UUID.
2026-09-07 10:39:10 +02:00
maziggy 9434875fa1 fix(ams): resolve a custom filament's own id from every preset source (issue #3003)
A custom filament profile reaches an AMS slot as itself through exactly one
field, tray_info_idx, and every source we can read that id from was reading it
from the wrong place or not reading it at all.

Bambu Cloud returns a preset's own filament_id either on the response envelope
or inside the preset JSON under `setting`, and only the envelope was read.
Presets of the second shape fell through to the base_id branch and reached the
slicer as the Bambu filament they inherit from. filament_type next door already
handled both spreads; filament_id now does too.

Orca Cloud was absent from the resolver entirely. A spool stores the bare
profile UUID, which matched no branch and fell through normalize_slicer_filament
-- a function that passes anything it does not recognise straight through -- so
a 36-character UUID went into the field. Orca profiles carry their own
filament_id in the slicer JSON that OrcaProfileDetail already exposes under
`setting`, so the lookup is the same one the Bambu branch does. It is
best-effort: no pairing, a dead token or a missing orca_cloud:auth permission
degrades to the fallback rather than failing the assignment, and it passes
clear_on_auth_failure=False because a background caller cannot tell a real
revocation from a lost refresh-rotation race.

configure_ams_slot sent the cloud setting_id as tray_info_idx when it found no
real filament id. That field is 8 characters on the printer -- exactly the width
of a local preset id, less than half a cloud one. Measured on the reporter's A1:
sent PFUS9ddc938fe3ab8f, the tray read back PFUS9DDC, acknowledged as a success.
The slot then resolved to nothing, so the slicer showed Generic anyway and the
calibration table, keyed by the same field, lost the slot. It now falls back to
the slot's existing filament id or the generic for the material, and the route's
guard was aligned with the resolver's so both refuse the same four shapes from
one shared definition.

This reverses the contract #1053 pinned. Six tests asserted that the PFUS
belonged in tray_info_idx; the A1 capture shows it never worked, so they were
rewritten with the measurement in their docstrings.

Verified against 874 AMS trays across twelve models in the support archive: 92
already carry a custom "P" + 7 hex filament id, which is what confirms the
mechanism works and this is a lookup failure rather than a platform limit. No
tray on any model carries a setting_id, so a profile with no filament_id of its
own still cannot be told apart from its base.
2026-09-07 10:15:06 +02:00
maziggy 0e0bea1aa7 Bumped version 2026-08-30 08:56:26 +02:00
maziggy 0dfcff5925 Keep the RTSPS proxy's handler set off the server object (issue #3001)
asyncio's Server has a __dict__ and uvloop's, a Cython cdef class, does
not, so the attribute added in 1.2.5.4 raised AttributeError under uvloop.
Every RTSP camera failed before opening a socket, which is the
diagnostic's capture_exception at 0 ms.

Our own unit files all pin --loop asyncio for #1896 and were never
affected. The reports come from units we do not write: the Proxmox VE
Helper-Scripts LXC pins no loop, and installs predating that fix never
gained the flag because update.sh does not rewrite unit files. The loop
is not ours to assume, so fix the code rather than add another flag.

The set moves to a module-level WeakKeyDictionary, keyed weakly so an
abandoned proxy retires its own entry rather than leaking one and later
handing a new server a dead one's handlers.

Pinned on a real uvloop loop and, for hosts without uvloop, against a
__slots__ server; conftest builds its loop from the default policy, so
nothing in the suite had ever run the branch that broke.

Also routes the two external-camera teardowns through close_tls_proxy,
which #2968 introduced and left them out of.

-----

Say so at startup when running on uvloop (issue #3001)

An install on the wrong loop had no way to find out it was. #3001 was
loud enough to notice; the #1896 upload truncation it is also exposed to
is silent, and shows up as a print failing from a file that was corrupt
on arrival.

One WARNING in the lifespan naming the loop, the risk and the flag to
add. A warning and not a refusal: uvicorn has already chosen its loop by
the time any application code runs, and a server that answers requests
beats one that will not boot.

Asks the running loop what it is rather than whether uvloop imports --
uvicorn[standard] installs uvloop everywhere, so its presence says
nothing -- and matches on the module name so the question never imports
uvloop on a host without it.

-----

Repair a service file written before the --loop asyncio pin (issue #3001)

install.sh has pinned the loop since #1896, but nothing has ever
rewritten an existing service file, so every native install created
between 2025-11-28 (when uvicorn[standard] brought uvloop into the venv)
and 2026-07-05 still runs on uvloop no matter how often it is updated.

Both update scripts now add the flag themselves while the service is
stopped, so it takes effect on the same restart -- systemd via sed,
launchd via PlistBuddy, each backing the file up first and inserting
nothing but the flag.

Refuses to edit and explains instead when the shape is not a plain
single-line uvicorn unit: a wrapper script, a continued ExecStart,
several of them, a read-only file, or a service with drop-ins, since a
drop-in may be what defines ExecStart and editing the fragment would
change nothing while reporting success. A deliberate --loop uvloop is
left alone. Reads the effective ExecStart from systemd rather than the
file, so it is idempotent.
2026-08-30 08:01:42 +02:00
maziggy 3f1ed85791 Housekeeping 2026-08-29 16:57:04 +02:00
maziggy 0eb8d4b22f Mark the failure-reason migration's table name for bandit too
The line carried a noqa for ruff's S608 but nothing bandit reads, so the
same rule was silent in one tool and reported as a medium SQL-injection
finding in the other.

Nothing is interpolated but `table`, which the loop takes from a literal
tuple on the next line; the key and the label list are both bound
parameters. A table name cannot be one, which is why it is written into
the string at all.
2026-08-29 14:47:43 +02:00
maziggy 9755e08077 Decide whether a 3MF is sliced by looking inside it (issue #2993)
An archive that showed the green GCODE badge could re-import into the
    File Manager as a source-only project with no Print button, seemingly at
    random.

    Nothing was ever lost from the file. The download serves the stored
    bytes verbatim and the G-code was still in the zip; the two sides simply
    asked different questions. Archives looked inside the file. The library
    looked at the filename. So a sliced 3MF stored as Foo.3mf rather than
    Foo.gcode.3mf earned the badge and lost the Print button, and which one
    you got depended on how the print had reached the printer -- a slicer's
    LAN send names it .gcode.3mf, a per-plate export or a cloud-dispatched
    print does not.

    Both sides now ask one shared predicate about the zip itself, and every
    route into the library classifies on content. Only the central directory
    is read, and only when the name has not already settled it, so ingest
    costs nothing extra -- the external scan opens each 3MF for its
    thumbnail regardless. Rows already stored are re-checked once, internal
    ones only: an external row points at a mount that may be slow or absent,
    and startup is the worst place to discover that.

    The Slice action moves with it. Its refusal to slice an output was as
    name-bound as the Print gate, and without that a file that correctly
    gained a Print button would have offered to re-slice its own G-code.
2026-08-29 14:21:46 +02:00
maziggy f616a6bca9 Show the spool that is in the AMS slot, not the one that was
Pull a Bambu ABS Orange out of A1, put a PLA Matte Dark Blue in, and the
    slot card still read "Bambu ABS" against the new colour until the page
    was reloaded.

    Three things stood between the swap and a correct card.

    The RFID auto-assign rewrites the slot's slot_preset_mappings row and
    then broadcast an event that refreshed everything except the query that
    reads it. Only the manual assign path invalidated that one.

    Those queries then sat behind the 3s cascade debounce, which exists for
    print completion, where one event fans out across half the app. A swap
    touches one slot and the user is standing at the printer looking at the
    card; worse, the timer restarts on every further event, so a busy moment
    could defer it indefinitely. Slot changes now invalidate immediately.

    And the card trusted the stored preset over live telemetry outright.
    That priority is why a hand-picked preset name stays on a slot, but it
    also let a cached row outrank what the printer was reporting. The row is
    now skipped when it names a different official Bambu filament than the
    tray does, so the card is right from the status push alone. User and
    local presets carry ids that genuinely cannot be compared and are left
    exactly as they were.

    Spoolman mode was the worse half of the same bug: its AMS sync writes
    the same row but announced nothing at all, so there was no event to
    refresh on. It now reports each slot it changed or cleared.
2026-08-29 14:21:08 +02:00
maziggy 049afea980 Refuse a same-named 3MF that contradicts the running print (issue #2957)
When a print's own 3MF cannot be fetched the usage tracker borrows one from the
    library or a previous archive, matching on the filename stem. That is far weaker
    evidence than it looks: Bambu Studio writes the printer-side filename from the
    project's Title metadata, so every plate of a project reaches the printer under
    one name however the file was renamed on disk.

    The reporter's single-filament job was handed a previous archive's three-filament
    plate. Three spools were debited for material that was never extruded, and
    nothing on the archive said the numbers were someone else's.

    A candidate is now rejected when it positively contradicts the print - a
    different plate, or a filament count the slicer's ams_mapping disagrees with -
    and the accepted one is logged with both expectations. Only on a contradiction:
    the plate needs firmware that echoes it and the count needs a print command
    Bambuddy saw, and refusing everything uncorroborated would retire the fallback
    recovery this same issue asked for.

    The count is scoped to one plate or not compared at all. Unscoped, the filament
    reader collects every <filament> in the file, and that sum against one plate's
    count would reject every multi-plate library upload on exactly the firmwares
    that cannot tell us the plate.

    -----

    Give a download the time the file needs, and one printer at a time (issue #2957)

    ftp_timeout is handed to every download as both the socket inactivity timeout
    and the whole-transfer deadline, which makes its 30s default a cap on how big a
    file a printer may serve. The reporter measured one 5.4 MB 3MF at 45s off a worn
    P1S SD card and 25s off a new one, and a 15.15 MB 3MF at 105s. None of those
    links were broken - they were slow, which is what the inactivity timeout exists
    to tell apart.

    download_to_file already asks for SIZE. It now reports it, and the total
    deadline follows the file at the 25 KB/s floor _upload_deadline has used since
    do, so #2572's cap on the executor queue wait is untouched. Capped at 300s for a
    reason that is not about FTP: on_print_start holds a pooled DB connection across
    its whole 3MF hunt.

    Downloads also take turns per printer now. He watched Bambu Studio lose its own
    connection while Bambuddy pulled a 12 MB 3MF, and a later log caught two
    Bambuddy downloads of the same file overlapping at print start. The gate is
    soft - whoever cannot have it within 30s goes anyway, because a print losing its
    3MF to queueing is worse than the contention, and a soft gate cannot deadlock.

    It is also meaningful for the first time. The 90s cap on a multi-path lookup
    returned while its worker kept walking the remaining paths, still on the
    printer's socket; that walk is now cancelled and waited out before the printer
    is handed on.

    -----

    Look in the shared 3MF cache again before each cover retry (issue #2957)

    The cover endpoint and the print-start archive flow share a cache so whichever
    fetches the 3MF first hands it to the other (#972). The cover consulted it once
    on the way in, then retried for up to two and a half minutes without looking
    again.

    In the reporter's log the archive flow published the file 42 seconds into that
    sequence and the cover's third attempt still pulled its own 5,250,969-byte copy,
    off a printer that was mid-print on the same SD card.

    A file picked up that way is left alone rather than re-registered under this
    endpoint's own name or deleted on the way out. It is the archive flow's.
2026-08-29 14:20:15 +02:00
maziggy 0eafe312c6 Repair the bed temperature on archives written before the fix (issue #2989)
The forward fix reads the array the fitted plate points at, but only for
    archives made after it. Everything already in the library stays blank, and
    preheat keeps falling back to the keep-warm bed temperature whenever one of
    those jobs is reprinted from the queue - 0 of 455 real 3MFs had resolved.

    A one-shot pass re-reads the 3MF already on disk, gated by a settings flag the
    way #2614's repair is: the rows it cannot fill are exactly the ones it would
    reopen every boot. It fills NULLs only. Nothing recorded is overwritten, an
    archive whose file is gone stays NULL, and a corrupted 3MF is skipped rather
    than failing startup.

    The plate mapping moves to threemf_tools.bed_temperature_from_config so the
    ingest path and the repair cannot read a 3MF differently - the same drift
    move.

    _extract_settings_from_content is deleted. Nothing called it anywhere in the
    repo, and it carried the old bed_temperature mapping this issue fixed.
2026-08-29 14:19:49 +02:00
maziggy 20627b2188 Log ffmpeg's error instead of its build banner
ffmpeg opens every run with ~20 lines of version and build banner and prints
    its diagnosis last, so the stderr[:200] eight of the nine call sites used kept
    the banner and threw the error away. The reporter's twelve capture failures all
    read "ffmpeg version 7.1.4 ... configuration: --prefix=/usr --extra-version=",
    identical on every install; the exit code was the only usable byte.

    The banner-stripping summariser written for #925 lived private to the camera
    route. It now lives in backend/app/utils/ffmpeg_output.py and every ffmpeg and
    ffprobe stderr goes through it. Two things the scattered copies also got wrong:
    four logged the input URL unmasked, publishing a printer access code or camera
    password, and four called a bare .decode() on bytes ffmpeg copies stream
    fragments into.

    -----

    Delete the files a no-3MF archive owns, without taking a printer folder

    Both delete paths derived the directory from file_path, which such an archive
    does not have, so they removed nothing and logged it at ERROR under a SECURITY
    banner. That was true when the archive was an empty row and stopped being true
    once one could hold a timelapse and finish photos in <archive_dir>/<id>/ and an
    uploaded source in archive/no_source/<id>/.

    The two are cleaned up by different means, because <archive_dir>/<id> shares a
    namespace with the per-printer folders: a normal archive lives at
    <archive_dir>/<printer_id>/<timestamp>_<name>/, so archive/1 is printer 1's
    folder and also the directory the shared helper hands archive id 1. Ids come
    from unrelated sequences, so the first few archives collide with the printers
    on every install, and an rmtree there takes every print that printer made --
    measured on a scratch tree. no_source/<id> is a level deeper under a name no
    printer id can take and is removed whole; the id-named directory gives up only
    its photos subdirectory and the video the row records, then goes only if that
    left it empty. The depth guard moves from one to two for the same reason: a
    file_path that lost a path component could point the delete at a printer
    folder, and no archive directory has been one level deep since the first
    commit.

    Hard delete had its own copy of these rules, which the helper's docstring says
    it exists to prevent, and it had diverged -- it skipped the print-log thumbnail
    cleanup whenever a guard tripped.

    -----

    Stop the RTSPS proxy leaving a handler behind at shutdown

    asyncio.start_server keeps only a weak reference to the connection callback's
    task, so a handler still awaiting its forwarders could be collected while
    pending -- "Task was destroyed but it is pending!", at ERROR with a traceback
    into camera.py, once every few hundred snapshots. Teardown had the matching
    gap: server.close() leaves established connections running, so the close waited
    on a handler that only finishes when the peer drops, and ffmpeg has already
    been reaped by then.

    Handlers are held for as long as they run and cancelled at shutdown, which is
    Server.close_clients() by hand -- that landed in 3.13 and Bambuddy supports
    3.10. Both the snapshot path and the streaming endpoint share the shutdown.
2026-08-29 14:19:22 +02:00
maziggy ff9b956156 Read the bed temperature from the plate the project is sliced for (issue #2989)
BambuStudio writes no bed_temperature key. It stores a per-filament array per
    plate type and names the fitted plate in curr_bed_type; bed_temperature is the
    Orca/Prusa spelling, so the lookup matched nothing and every archive from a
    Bambu slice stored NULL - 0 of 455 real 3MFs resolved. Preheat then fell back
    to the keep-warm bed temperature on jobs that had one all along.

    Plate names and the plate-to-key mapping are BambuStudio's own get_bed_temp_key
    and get_bed_temp_1st_layer_key. First-layer value preferred, highest entry in
    the per-filament array taken, an all-zero array left unrecorded.
2026-08-29 14:19:02 +02:00
maziggy ffc55b6a6e Skip the manual K calibration line as an internal printer job (issue #2957 follow-up)
Manual flow dynamics has two shapes and each reports under its own name with
    no auto_ prefix. pa_pattern_calib_mode was already filtered; pa_line_calib_mode
    was not, so it still swept FTP for a 3MF that cannot exist and wrote a no-3MF
    archive named after the calibration.
2026-08-29 14:18:43 +02:00
maziggy 2e405afcd1 Decide whether a 3MF is sliced by looking inside it (issue #2993)
An archive that showed the green GCODE badge could re-import into the
File Manager as a source-only project with no Print button, seemingly at
random.

Nothing was ever lost from the file. The download serves the stored
bytes verbatim and the G-code was still in the zip; the two sides simply
asked different questions. Archives looked inside the file. The library
looked at the filename. So a sliced 3MF stored as Foo.3mf rather than
Foo.gcode.3mf earned the badge and lost the Print button, and which one
you got depended on how the print had reached the printer -- a slicer's
LAN send names it .gcode.3mf, a per-plate export or a cloud-dispatched
print does not.

Both sides now ask one shared predicate about the zip itself, and every
route into the library classifies on content. Only the central directory
is read, and only when the name has not already settled it, so ingest
costs nothing extra -- the external scan opens each 3MF for its
thumbnail regardless. Rows already stored are re-checked once, internal
ones only: an external row points at a mount that may be slow or absent,
and startup is the worst place to discover that.

The Slice action moves with it. Its refusal to slice an output was as
name-bound as the Print gate, and without that a file that correctly
gained a Print button would have offered to re-slice its own G-code.
2026-08-29 14:14:26 +02:00
maziggy 7363d5fd33 Show the spool that is in the AMS slot, not the one that was
Pull a Bambu ABS Orange out of A1, put a PLA Matte Dark Blue in, and the
slot card still read "Bambu ABS" against the new colour until the page
was reloaded.

Three things stood between the swap and a correct card.

The RFID auto-assign rewrites the slot's slot_preset_mappings row and
then broadcast an event that refreshed everything except the query that
reads it. Only the manual assign path invalidated that one.

Those queries then sat behind the 3s cascade debounce, which exists for
print completion, where one event fans out across half the app. A swap
touches one slot and the user is standing at the printer looking at the
card; worse, the timer restarts on every further event, so a busy moment
could defer it indefinitely. Slot changes now invalidate immediately.

And the card trusted the stored preset over live telemetry outright.
That priority is why a hand-picked preset name stays on a slot, but it
also let a cached row outrank what the printer was reporting. The row is
now skipped when it names a different official Bambu filament than the
tray does, so the card is right from the status push alone. User and
local presets carry ids that genuinely cannot be compared and are left
exactly as they were.

Spoolman mode was the worse half of the same bug: its AMS sync writes
the same row but announced nothing at all, so there was no event to
refresh on. It now reports each slot it changed or cleared.
2026-08-29 13:26:09 +02:00
maziggy 7c10412f99 Refuse a same-named 3MF that contradicts the running print (issue #2957)
When a print's own 3MF cannot be fetched the usage tracker borrows one from the
library or a previous archive, matching on the filename stem. That is far weaker
evidence than it looks: Bambu Studio writes the printer-side filename from the
project's Title metadata, so every plate of a project reaches the printer under
one name however the file was renamed on disk.

The reporter's single-filament job was handed a previous archive's three-filament
plate. Three spools were debited for material that was never extruded, and
nothing on the archive said the numbers were someone else's.

A candidate is now rejected when it positively contradicts the print - a
different plate, or a filament count the slicer's ams_mapping disagrees with -
and the accepted one is logged with both expectations. Only on a contradiction:
the plate needs firmware that echoes it and the count needs a print command
Bambuddy saw, and refusing everything uncorroborated would retire the fallback
recovery this same issue asked for.

The count is scoped to one plate or not compared at all. Unscoped, the filament
reader collects every <filament> in the file, and that sum against one plate's
count would reject every multi-plate library upload on exactly the firmwares
that cannot tell us the plate.

-----

Give a download the time the file needs, and one printer at a time (issue #2957)

ftp_timeout is handed to every download as both the socket inactivity timeout
and the whole-transfer deadline, which makes its 30s default a cap on how big a
file a printer may serve. The reporter measured one 5.4 MB 3MF at 45s off a worn
P1S SD card and 25s off a new one, and a 15.15 MB 3MF at 105s. None of those
links were broken - they were slow, which is what the inactivity timeout exists
to tell apart.

download_to_file already asks for SIZE. It now reports it, and the total
deadline follows the file at the 25 KB/s floor _upload_deadline has used since
do, so #2572's cap on the executor queue wait is untouched. Capped at 300s for a
reason that is not about FTP: on_print_start holds a pooled DB connection across
its whole 3MF hunt.

Downloads also take turns per printer now. He watched Bambu Studio lose its own
connection while Bambuddy pulled a 12 MB 3MF, and a later log caught two
Bambuddy downloads of the same file overlapping at print start. The gate is
soft - whoever cannot have it within 30s goes anyway, because a print losing its
3MF to queueing is worse than the contention, and a soft gate cannot deadlock.

It is also meaningful for the first time. The 90s cap on a multi-path lookup
returned while its worker kept walking the remaining paths, still on the
printer's socket; that walk is now cancelled and waited out before the printer
is handed on.

-----

Look in the shared 3MF cache again before each cover retry (issue #2957)

The cover endpoint and the print-start archive flow share a cache so whichever
fetches the 3MF first hands it to the other (#972). The cover consulted it once
on the way in, then retried for up to two and a half minutes without looking
again.

In the reporter's log the archive flow published the file 42 seconds into that
sequence and the cover's third attempt still pulled its own 5,250,969-byte copy,
off a printer that was mid-print on the same SD card.

A file picked up that way is left alone rather than re-registered under this
endpoint's own name or deleted on the way out. It is the archive flow's.
2026-08-29 10:46:36 +02:00
maziggy b0ecb8fd88 Repair the bed temperature on archives written before the fix (issue #2989)
The forward fix reads the array the fitted plate points at, but only for
archives made after it. Everything already in the library stays blank, and
preheat keeps falling back to the keep-warm bed temperature whenever one of
those jobs is reprinted from the queue - 0 of 455 real 3MFs had resolved.

A one-shot pass re-reads the 3MF already on disk, gated by a settings flag the
way #2614's repair is: the rows it cannot fill are exactly the ones it would
reopen every boot. It fills NULLs only. Nothing recorded is overwritten, an
archive whose file is gone stays NULL, and a corrupted 3MF is skipped rather
than failing startup.

The plate mapping moves to threemf_tools.bed_temperature_from_config so the
ingest path and the repair cannot read a 3MF differently - the same drift
move.

_extract_settings_from_content is deleted. Nothing called it anywhere in the
repo, and it carried the old bed_temperature mapping this issue fixed.
2026-08-29 09:23:48 +02:00
maziggy d4477e9b71 Log ffmpeg's error instead of its build banner
ffmpeg opens every run with ~20 lines of version and build banner and prints
its diagnosis last, so the stderr[:200] eight of the nine call sites used kept
the banner and threw the error away. The reporter's twelve capture failures all
read "ffmpeg version 7.1.4 ... configuration: --prefix=/usr --extra-version=",
identical on every install; the exit code was the only usable byte.

The banner-stripping summariser written for #925 lived private to the camera
route. It now lives in backend/app/utils/ffmpeg_output.py and every ffmpeg and
ffprobe stderr goes through it. Two things the scattered copies also got wrong:
four logged the input URL unmasked, publishing a printer access code or camera
password, and four called a bare .decode() on bytes ffmpeg copies stream
fragments into.

-----

Delete the files a no-3MF archive owns, without taking a printer folder

Both delete paths derived the directory from file_path, which such an archive
does not have, so they removed nothing and logged it at ERROR under a SECURITY
banner. That was true when the archive was an empty row and stopped being true
once one could hold a timelapse and finish photos in <archive_dir>/<id>/ and an
uploaded source in archive/no_source/<id>/.

The two are cleaned up by different means, because <archive_dir>/<id> shares a
namespace with the per-printer folders: a normal archive lives at
<archive_dir>/<printer_id>/<timestamp>_<name>/, so archive/1 is printer 1's
folder and also the directory the shared helper hands archive id 1. Ids come
from unrelated sequences, so the first few archives collide with the printers
on every install, and an rmtree there takes every print that printer made --
measured on a scratch tree. no_source/<id> is a level deeper under a name no
printer id can take and is removed whole; the id-named directory gives up only
its photos subdirectory and the video the row records, then goes only if that
left it empty. The depth guard moves from one to two for the same reason: a
file_path that lost a path component could point the delete at a printer
folder, and no archive directory has been one level deep since the first
commit.

Hard delete had its own copy of these rules, which the helper's docstring says
it exists to prevent, and it had diverged -- it skipped the print-log thumbnail
cleanup whenever a guard tripped.

-----

Stop the RTSPS proxy leaving a handler behind at shutdown

asyncio.start_server keeps only a weak reference to the connection callback's
task, so a handler still awaiting its forwarders could be collected while
pending -- "Task was destroyed but it is pending!", at ERROR with a traceback
into camera.py, once every few hundred snapshots. Teardown had the matching
gap: server.close() leaves established connections running, so the close waited
on a handler that only finishes when the peer drops, and ffmpeg has already
been reaped by then.

Handlers are held for as long as they run and cancelled at shutdown, which is
Server.close_clients() by hand -- that landed in 3.13 and Bambuddy supports
3.10. Both the snapshot path and the streaming endpoint share the shutdown.
2026-08-29 08:51:33 +02:00
maziggy c001f596bf Read the bed temperature from the plate the project is sliced for (issue #2989)
BambuStudio writes no bed_temperature key. It stores a per-filament array per
plate type and names the fitted plate in curr_bed_type; bed_temperature is the
Orca/Prusa spelling, so the lookup matched nothing and every archive from a
Bambu slice stored NULL - 0 of 455 real 3MFs resolved. Preheat then fell back
to the keep-warm bed temperature on jobs that had one all along.

Plate names and the plate-to-key mapping are BambuStudio's own get_bed_temp_key
and get_bed_temp_1st_layer_key. First-layer value preferred, highest entry in
the per-filament array taken, an all-zero array left unrecorded.
2026-08-28 14:26:34 +02:00
maziggy 164382b38b Skip the manual K calibration line as an internal printer job (issue #2957 follow-up)
Manual flow dynamics has two shapes and each reports under its own name with
no auto_ prefix. pa_pattern_calib_mode was already filtered; pa_line_calib_mode
was not, so it still swept FTP for a 3MF that cannot exist and wrote a no-3MF
archive named after the calibration.
2026-08-28 13:30:27 +02:00
MartinNYHC 8cce10b60a Skip the manual K calibration the way the automatic one is skipped
Bambuddy already recognises the printer's automatic pressure-advance run,
    auto_pa_line_calib_mode, and leaves no archive and sends no notification
    for it. Started by hand rather than automatically before a print, the
    same calibration reports under a different name: it prints a pattern
    where the automatic one prints a line, and carries no auto_ prefix, so
    pa_pattern_calib_mode matched nothing.

    It arrives exactly the way the automatic one does -- a bare subtask name
    with no /usr/ path -- so it hit the same outcome the module was written
    to prevent: an FTP sweep for a 3MF that cannot exist, six candidate names
    across five directories with retries, and then a no-3MF archive named
    after the calibration, on a printer in the middle of calibrating.

    One entry on INTERNAL_JOB_NAMES covers it. That set is the single place
    both the print-start and print-complete callbacks consult, so archiving,
    the 3MF sweep and the notifications are all handled by the one line.

    Matching stays exact after normalising path, suffix and case. The
    negative cases are extended alongside the positive ones, so a file
    somebody deliberately named pa_pattern_calib_mode_v2.3mf is still
    archived as the print it is.

    The manual PA *line* method, if it reports its own name, is not covered
    here -- the list is deliberately limited to names that have actually been
    observed rather than ones that seem likely.
2026-08-28 12:45:17 +02:00
MartinNYHC 9b83e8eba4 Send AMS tray colours as uppercase hex (issue #2987)
Assigning a spool to an AMS slot unassigned it again seconds later, and
    the slot's colour changed at the same time. It presented as Bambu Studio
    and Bambuddy fighting over the slot. The reporter's log shows Bambuddy
    losing to itself.

    P1S firmware 01.10.00.00 reads every lowercase hex letter in an AMS
    tray_color as a zero, and hides it completely: the command response
    echoes back the value that was sent and reports result "success", so
    only the next AMS push says what was really stored. The spool-assign
    path sent spool.rgba verbatim and that column stores lowercase. From the
    bundle:

      sent 09ff00ff  ->  AMS reports 09000000
      sent ff5100ff  ->  AMS reports 00510000
      sent 090000FF  ->  AMS reports 090000FF

    That is the visible colour change, and it is also what deleted the
    assignment. The auto-unlink sweep asks whether the slot still matches
    the spool assigned to it; the mangled colour no longer did, so the
    assignment Bambuddy had made four seconds earlier was removed.
    colors_similar('09000000', '09FF00FF') is False, which is the whole of
    it.

    Re-assigning could not recover, because the Configure Slot dialog seeds
    its colour from whatever the printer currently reports. It wrote the
    mangled colour back and cemented it, which is the loop the report
    describes in its steps 4 and 5.

    Colours are now uppercased where the command is assembled rather than in
    each of the four routes that configure a slot. A caller that forgets is
    exactly how this arrived. Nothing else changes: no padding, no invented
    alpha, no six-to-eight widening, and tray_type and tray_sub_brands keep
    their case, where it carries meaning -- "PLA Matte" is a product line,
    "PLA MATTE" is not.

    Two paths deliberately left alone. The developer-mode probe re-sends the
    colour the printer itself just reported so that the probe is inert;
    uppercasing there would turn it into a write. And the Virtual Printer
    forwards the slicer's own command verbatim -- Studio could in principle
    hit the same firmware bug, but nothing here evidences that it sends
    lowercase, and rewriting a slicer payload inside a transparent proxy is
    not a change to make on a hunch.

    Two more defects from the same log.

    A spool with a brand and no subtype was configured with the string
    "None" in its name: the branded branch interpolated spool.subtype
    without checking it while the unbranded branch guarded it, so
    "Sunlu PLA Matte None" went on the wire and into Studio's display.

    And the FTP log is readable again. A 426 whose bytes Bambuddy has
    already verified against the printer is how Bambu FTPS normally ends a
    transfer, not a fault, so it drops from WARNING to INFO. It fired 54
    times in this one bundle, every one followed by a completed upload, and
    it was burying the 26 TLS handshake failures in the same log that
    actually cost the reporter two prints. A 426 whose bytes do not verify
    is still an error and still fails the upload.

    The handshake failures themselves are printer-side FTPS cool-off under
    load and are not touched here.
2026-08-28 12:44:49 +02:00
MartinNYHC 450f9a6f20 Derive the chamber target from the trays the print loads (issue #2886)
Preheat took the maximum chamber target across every loaded AMS tray,
    with no reference to the job. The reporter's P2S holds PETG Pro, PLA,
    ASA and PETG; the ASA row of the filament map says 45C, so a PLA-only
    plate was dispatched with chamber_target=45C, the bed driven to 90C to
    reach it, and the full 900s max-wait plus 300s soak burned before the
    upload started. Every time -- a P2S has no chamber heater and its
    chamber tops out around 33C, so the wait can only ever end on the
    timeout. Their log carries fifteen of these.

    The intent was never in doubt. The resolution order documented one
    screen above _derive_chamber_target reads "PLA-only print derives 0 ->
    chamber phase auto-skips", but it was implemented as PLA-only AMS
    rather than PLA-only print, and only misfires on a mixed load.

    The derivation now reads the trays the item's ams_mapping names -- the
    same array the print command puts on the wire, [-1, -1, -1, 1] in their
    case, addressing exactly the PLA slot -- so the ASA two slots over
    contributes nothing and the stage skips outright. Multi-material prints
    are unaffected: the maximum is still taken, across the trays the plate
    actually loads, so an ASA the print does use is still binding.

    An item whose mapping is missing or still unresolved keeps the
    whole-unit scan. That is the only signal left, and narrowing to nothing
    would disable preheat for prints that need it -- the failure mode worth
    avoiding here is the silent one.

    The bed hold between jobs is gated on the same derivation and was
    holding beds at 90C for the same wrong reason. It now reads the next
    item's mapping too, where that item has one.

    The external spool is no longer invisible to this. The scan only ever
    looked at raw_data['ams'], so an ASA print fed from the external feed
    derived 0 and got no preheat at all; a mapping naming 254/255 is now
    honoured. An item with no mapping still derives from the AMS alone, so
    nothing starts preheating that did not before.

    Tray addressing matches _build_loaded_filaments, which is what produced
    the ids in the mapping being read back: ams_id * 4 + tray_id, the bare
    unit id for an AMS-HT from 128, and the firmware's own vt_tray id for
    an external feed. Ids are coerced because this firmware reports them as
    strings.
2026-08-28 12:44:24 +02:00
MartinNYHC 21fd476668 Ask Spoolman which extra fields it has, once (issue #2983)
Bambuddy checked whether one of its four custom spool fields existed with
    GET /field/spool/{name}. Spoolman has never served that. Its API declares
    only POST and DELETE at that path -- confirmed against the live server's
    own OpenAPI document -- so the probe answered 405 Method Not Allowed
    every time and the check could not succeed on any version.

    Every call therefore fell through to POST /field/spool/{name}, and that
    endpoint is an upsert rather than a create. It answers 200 whether or not
    the field is already there, so a field the user had renamed, retyped or
    given a default to in Spoolman's own UI was reset to Bambuddy's version
    of it, and an untrue "Created Spoolman extra field" was logged beside it.
    The reporter's log carried 60 of those lines over three days -- once per
    field per client init, which is every restart and every settings save.

    Existence now comes from GET /field/spool, the listing endpoint, matched
    on each row's `key`. Matching on `key` rather than the display `name` is
    the part that fixes the overwrite: a renamed field is the same field, and
    reading it as a missing one is what re-created it. A field that already
    exists is now left completely alone.

    The listing is read once per client and banked, so registering all four
    fields costs one request instead of four, and a client that has already
    looked makes none at all. Only a successful read is banked -- a client
    that could not reach the listing asks again for the next field it has not
    seen, so one transient failure does not leave it posting blind, and
    overwriting, for the rest of its life.

    An unreadable listing still falls back to attempting the POST. Registration
    is best-effort by contract: it must not turn a write that might still
    succeed into one that never happens, so an unexpected Spoolman build is no
    worse off than before.

    Measured against Spoolman 0.23.1: a field renamed to "Bambu RFID Tag"
    survives a full registration pass that previously reset it, the pass makes
    one GET and one POST for the single genuinely-missing field where it used
    to make four POSTs, and a second pass on the same client makes no requests
    at all.

    The fake in test_spoolman_extra_field_registration_2903 modelled the
    per-field path as a working probe, which is the assumption this bug was
    built on; it now answers 405 as the real server does, and its assertions
    follow the listing. 18 new tests cover the rest, 10 of which fail against
    the old code.
2026-08-28 12:43:58 +02:00
MartinNYHC 112e58e5b9 Match slicer presets on what they declare, not what they are named (issue #2982)
The internal slicer picked PETG for a PLA plate and an A1 process for a
    P1S. Both come from the sidecar's bundled-profile listing, fixed in the
    sidecar repo; this is the consuming half plus the hardening that keeps an
    older sidecar degrading rather than breaking.

    Standard-tier presets now carry the compatible_printers the sidecar
    reports. That list is the only truthful account of which printer a preset
    belongs to, because the bundle ships no process preset named after a P1S,
    an X1, an X1E or an H2D Pro -- all ten of the P1S's are named "@BBL X1C"
    and name the P1S only in that list. Reading the printer out of the preset
    NAME therefore made a P1S look like it had no compatible process at all:
    all 198 hid behind "Show all" and the auto-pick fell through to an
    alphabetically-first 0.06mm Fine @BBL A1 0.2 nozzle the CLI refused. A
    P1S now gets 0.20mm Standard @BBL X1C and 73 filaments instead of 4. An
    older sidecar reports nothing here, which leaves the name matcher in
    place -- degraded as before, not broken.

    Material is now a hard partition in the filament pre-pick rather than a
    +10 bonus. A preset stating a different material than the plate asks for
    is the wrong preset, not a worse one: wrong nozzle temperature, wrong bed
    temperature, wrong flow. A preset stating NO material stays eligible --
    unknown is not wrong, and 32 shipped profiles genuinely have none. The
    same rule reaches the retain path, which held a slot on
    printer-compatibility alone and so cemented a wrong-material pick through
    every re-pick. A preset the user chose themselves is exempt: printing
    PETG on a plate a designer labelled PLA is a legitimate thing to do, and
    this rule exists to correct the auto-pick, not to overrule the user.

    Two more, both found while tracing this and neither reported:

    Among process presets equally valid for the selected printer, the one
    nearest a 0.2mm layer height now wins. Within a tier the list is
    alphabetical and Bambu's naming puts the finest height first, so every
    slice that did not name its own process silently got 0.08mm Extra Fine on
    an X1 Carbon and 0.06mm Fine on an A1 mini -- correct presets, nobody's
    default. Ties break toward the coarser, faster height; a name with no
    readable height is still pickable when it is the only candidate; a
    process the 3MF named still wins outright.

    H2DP is aliased to H2D Pro, the same shape as the A1M rename in #1649 --
    the bundle spells the model one way in preset names and another in the
    printer preset, so an H2D Pro classified all 198 processes as another
    printer's. Deliberately narrow: H2DP and a plain H2D are different
    machines and must not collapse.

    A dropdown the printer filter would empty now shows the unfiltered list
    instead. That state was reachable for four printer models and told the
    user nothing; a visible preset for the wrong printer can be changed, an
    empty dropdown cannot.

    Verified against live Orca 2.4.2 and BambuStudio 02.08.02.61 sidecars
    over the real 1156- and 1792-profile trees: every one of the eight
    printer models tested now auto-picks a 0.20mm process for its own
    printer, a PLA plate draws a PLA preset and a PETG plate a PETG one.
    Each change was confirmed to fail its tests when reverted.
2026-08-28 12:43:29 +02:00
MartinNYHC 26a827ea94 Name an unnamed print stage "Preparing" on the card
New printers report stage numbers before Bambuddy learns their names,
    and the H2C still has several. Those reached the printer card verbatim,
    as "Unknown stage (72)" -- a number that means nothing to the person
    reading it, on the one line that otherwise says what the printer is
    doing.

    Every stage that has turned out to be unnamed so far has been part of
    the run-up to printing, so an unnamed one now reads as "Preparing".
    That is the same literal stage 74 already carries rather than a second
    spelling of the same idea, so a card cannot show two different words
    for the same situation depending on which number the firmware picked.

    Display only, and deliberately not pushed down into get_stage_name.
    That function also feeds the stage-transition log line and the
    once-per-session warning added to capture unnamed stages so they can be
    named in a later release; there the number is the entire diagnostic
    value, and replacing it with "Preparing" would hide the only thing that
    reports these. Both paths are pinned by tests asserting they disagree
    for an unnamed stage and agree for a named one, so a later tidy-up
    cannot quietly collapse them.

    The idle sentinels are untouched: 255 on A1/P1 and -1 on X1 mean "no
    stage", not an unnamed one, and still resolve to nothing rather than
    being swept up by the fallback.

    Nothing keys logic off stg_cur_name -- it is display-only in the printer
    card, the print dialog's printer selector and the stream overlay -- so
    all three improve and none change behaviour. No i18n either way: the
    whole stage table has always been English.
2026-08-28 12:43:09 +02:00
MartinNYHC 2d0eca9354 Paint an AMS slot card with the spool's colours, not the tray's (issue #2967)
A Ziro "Colorful Mist" -- yellow, cyan and pink, effect Tri Color --
    hovered on the printer card as a single flat pink rectangle. A printer
    reports exactly one tray_color hex per tray and nothing else, so
    telemetry cannot describe a gradient or a surface effect and never will.

    The header now paints the bound spool's own swatch whenever that spool
    declares extra colour stops or an effect, through buildFilamentBackground
    -- the builder the Inventory swatches already use, so the two surfaces
    cannot drift apart. A plain single-colour spool keeps the flat
    backgroundColor it has always had, and a slot with nothing bound is
    untouched, so the common case goes nowhere near the gradient path.

    The gate is "any stop at all", not "more than one". buildColorLayer
    ignores rgba the moment stops exist, so a one-stop spool renders that
    stop rather than the slot hex; skipping it would leave this card showing
    a different colour from the Inventory row for the same spool, which is
    the class of disagreement the shared builder exists to prevent.

    isLightColor now tests the colour actually on screen. Once the spool's
    swatch is painted the base is no longer the slot hex -- a single stop
    replaces it outright, and an effect-only spool paints the spool's own
    rgba -- so testing the slot hex would pick the text colour for a
    background that is not there.

    Above one band no single hex can decide legibility, and the name sits
    dead centre where a multi-stop background is likeliest to change under
    it. So a genuinely multi-band header puts the name on the same scrim the
    vendor badge already uses. One stop, or an effect over one colour, still
    vendor badge already uses. One stop, or an effect over one colour, still
    leaves a real base colour to test and keeps the contrast rule it had.

    Spoolman mode gains the gradient in the process. Spoolman has held the
    stops in filament.multi_color_hexes all along and the label renderer has
    been reading them for releases, but _map_spoolman_spool never returned
    them -- so the identical roll registered in Spoolman rendered flat while
    the internally-managed one did not. Both now share one parser rather
    than reading the same field two ways.

    What stays asymmetric is Spoolman's own limitation, and it is pinned by
    a test rather than left to be rediscovered: Spoolman has no field for a
    surface effect at all. Its only neighbouring field,
    multi_color_direction, says how the stops are laid out, not that the
    roll is silk or glitter. effect_type is therefore None for a Spoolman
    spool instead of guessed at, and silk/sparkle/wood remain internal-only.

    The other two halves of the report -- the header naming the colour
    "White" instead of "Colorful Mist", and the print dialog offering
    "A3: PLA (White)" -- were already fixed on dev by #2875 and by the
    slot-naming change that landed the day after this was filed. Neither is
    in 1.2.5.3, which is what the reporter is running.
2026-08-28 12:42:44 +02:00
MartinNYHC b2dda1fa5f Record the colour a slice is actually printed in (issue #2977)
Every file the internal slicer produced came back with filament_colour
    = #00AE42 whatever filament was picked: a green plate thumbnail, green
    metadata, and a "Color mismatch" in the Print dialog against the AMS
    slot the job had just been correctly mapped to.

    A colour is not a property of a filament preset in either slicer. It
    belongs to the project, and Bambu Studio and OrcaSlicer set it from the
    plate in their GUIs -- so nothing was attached to the preset Bambuddy
    sends by name, and the CLI fell back to its own compiled-in default,
    which is Bambu green. None of the shipped BBL filament profiles define
    filament_colour; the whole tree has zero occurrences.

    default_filament_colour is not the answer on its own. Measured against
    a 02.08.02.61 sidecar, a profile carrying only that still slices to
    filament_colour ["#00AE42"] -- Bambu Studio consumes it in the GUI when
    a project is created, not in --load-filaments. So it is read and
    rewritten as filament_colour, which the same sidecar does honour: the
    reporter's exact triplet returns ["#E8B00C"] when patched this way, and
    the colour lands in both project_settings.config and slice_info.config,
    which is what the thumbnail and the AMS mapping actually read.

    Each filament row in the slice dialog gets a colour control, and the
    resolved value flows through a chain: the user's pick, then the preset's
    own default_filament_colour, then the colour that slot was designed with
    in the source 3MF. A slot with none of the three is left untouched
    rather than given a guess.

    The designed colour is read from project_settings.config, not
    slice_info.config. The latter records what the file was last sliced
    with, which for a source that never carried a colour is #00AE42 itself
    -- measured -- so using it would have been circular.

    The control is offered on single-filament sources too, because an STL,
    and equally a mesh-only 3MF exported from CAD, has no colour anywhere
    else to inherit. That is the case this exists for, and it took three
    shapes to make it visible: a swatch in the label row was identical to
    the read-only dot multi-colour rows have carried for releases, and
    adding the hex beside it only made it look like a caption. It now sits
    beside the dropdown, styled like it and the same height, with the
    swatch and hex wrapped in one label bound to the input so a click
    anywhere on it opens the picker.

    An untouched slot with no designed colour submits an empty string
    rather than the control's displayed default. A sent colour outranks the
    preset's own, so pinning the placeholder would silently discard the
    real colour of an imported OrcaSlicer profile that carries one.

    Slicer Pipelines pick up the same chain without carrying a colour of
    their own.

    Also adds a warning for a defect found while investigating this: a
    filament preset whose name the sidecar's bundle cannot resolve is not
    rejected. The CLI inherits nothing, falls back to its defaults for
    every field, and returns a well-formed success -- measured, an
    unresolvable name slices as filament_type ["PLA"] at nozzle_temperature
    ["200"] with filament_ids [""] and filament_vendor ["(Undefined)"], so
    a PETG preset a sidecar image predates prints at PLA temperatures with
    no diagnostic anywhere. Both signals are required together, which keeps
    it off the two legitimate lookalikes: a hand-written profile that never
    named a vendor still carries a real filament id, and a user's own cloud
    preset carries a vendor while legitimately having no bundled id. The
    file is kept rather than refused, unlike the missing start G-code of
    whoever can see the temperatures.
2026-08-28 12:42:15 +02:00
MartinNYHC 659d77c205 Store a failure reason in one vocabulary, not three (issue #2974)
failure_reason was written three different ways and nothing reconciled
    them. derive_failure_reason wrote English display labels ("Layer shift"),
    older builds of the archive editor wrote the translated label in whatever
    locale that user was running, and the two stale-archive paths wrote
    English prose sentences. All three reach one column -- the archive PATCH
    has mirrored the field onto the latest print-log entry since #1444 -- and
    the Failure Analysis widget groups on the raw value, so one real cause
    occupied several buckets. On a live install before this landed:
    print_log_entries held 91 rows reading "User cancelled" beside 1 reading
    "userCancelled".

    In an English UI those two render as the same words twice with different
    counts, which is why nobody spotted it. In any other locale one of them
    stays English, because a stored label has no key for t() to resolve. The
    editor was worse than cosmetic about it: its reverse lookup compared the
    stored value against t() in the current locale, so for a non-English user
    nothing matched and the dropdown opened empty over an archive that
    plainly showed a reason.

    The keys were already canonical and already enforced.
    _FAILURE_REASON_KEYS in api/routes/print_log.py rejects anything else
    with a 400 and explains why in its own comment -- the widget renders
    values back through t(), so an unrecognised one surfaces as a raw string.
    derive_failure_reason had simply never been held to that rule. It now
    produces keys, and the cancel branch returns userCancelled.

    The two "Stale - ..." sentences become one new noStatusUpdate key. Both
    describe the same observation, that no end-of-print status ever arrived;
    which of the two situations occurred is already carried by status --
    cancelled at the stale-cleanup site, the reconciled outcome at the
    reconnect site -- so collapsing them loses nothing and gives Statistics
    one bucket instead of two sentences that could never be translated. It
    had to enter the vocabulary rather than merely be tolerated, because the
    editor discards any value it does not recognise.

    Existing rows are converted by a startup migration folding 168 historical
    labels onto the 12 keys across both columns. It is exact rather than a
    guess: every label across all 14 locales resolves to exactly one key,
    with no collisions. The map is a frozen snapshot rather than something
    read from the locale files at run time -- it maps what was written
    historically, so regenerating it from the current translations would
    silently stop recognising the very rows it exists to convert. A value
    outside the map is left alone; guessing would be worse than leaving one
    honest string in its own bucket. There is no one-shot settings flag, on
    purpose: the statement only matches values in the map and a key is never
    a label, so it is self-terminating, and a flag would permanently skip
    anyone who restores an older database.

    The last part is a data-loss bug that was not in the report. The editor's
    fallback to '' was not merely a wrong-looking dropdown -- the empty
    selection was then saved over the stored text, so opening the editor on
    an archive whose reason was free text and pressing Save destroyed the
    classification. An unrecognised value now keeps its own option and
    survives a save.
2026-08-28 12:41:46 +02:00
MartinNYHC 012d4df3a5 Name an AMS slot after the spool assigned to it
The print dialog described every slot from the printer's own telemetry, and
    a printer cannot describe a spool it did not sell: a tray record carries no
    brand field, tray_sub_brands is left empty for anything that is not a Bambu
    spool, and the colour arrives as a bare hex the client resolves against
    Bambu's own colour catalogue. A Devil Design PLA Basic Orange assigned in
    Bambuddy therefore read as "PLA (Sunflower Yellow)" -- Bambu sell a
    Sunflower Yellow at the same FEC600 -- while the printer card, which reads
    the assignment, named it correctly. Two views of one slot, disagreeing.

    GET /printers/{id}/inventory-remain now carries each bound slot's brand,
    material, subtype, colour name and hex alongside the pooling key it already
    sent, and the dialog prefers that over telemetry. The fallback is per field,
    not all or nothing, so a spool with no stored colour name still gets the
    catalogue lookup it had before while its brand and subtype come from the
    binding. Resolved server-side because the identity rule differs per
    inventory mode -- brand is a column in internal mode and a nested vendor in
    Spoolman's, where the subtype is the filament name with its material prefix
    stripped and the colour name has a three-step read order Spoolman has no
    field for. Spoolman's synthesised colour name, which falls back to the
    subtype, is withheld rather than rendered as "PLA Basic (Basic)".

    Matching is deliberately untouched and still runs on the printer's
    telemetry. The auto-assignment, the colour-mismatch test and the mapping
    that actually gets dispatched all read type, colour hex and tray_info_idx,
    so renaming a slot cannot make the panel and the dispatcher draw different
    conclusions from it. The payload is re-read on every open of the dialog: it
    names the slots now, and a spool assigned moments earlier would otherwise
    keep its old name for the rest of the thirty-second stale window. Done at
    the two readers rather than by invalidating the key from each of the
    eighteen places a binding or a spool can change, half of which are internal
    paths and half Spoolman ones -- covering some would make freshness depend on
    which mode you run.

    Two hardening fixes fall out of putting a mapper on this path.
    build_slot_materials runs before every queue start through
    compute_deficit_for_queue_item, and _map_spoolman_spool walks a dozen nested
    fields off the wire, any of which arriving as the wrong type raises
    AttributeError rather than ValueError. Naming a slot must never cost a
    dispatch, so that call fails soft to no name. The same inputs also reached
    _material_identity_spoolman and _normalize_color_for_id, which have always
    been on this path and would fail a queue start on a Spoolman record whose
    filament is not a dict or whose color_hex is a number; both now read those
    as "nothing to pool with". Behaviour for well-formed input is unchanged --
    the guards only intercept types that previously raised -- so no pooling key
    moves and AMS Filament Backup is untouched.
2026-08-28 12:38:21 +02:00
MartinNYHC 2253afbf45 Key a K profile on its nozzle's flow type
A printer files each calibration under a nozzle id of the form HH00-0.4
    (high flow) or HS00-0.4 (standard) and can hold both for one diameter -- a
    maintainer's H2D carries 102 high-flow entries against 6 standard --
    because the same filament reads a different K through each. Nothing read
    that, so a standard-flow profile could be selected for a high-flow nozzle
    and vice versa.

    The flow is now stored with the profile, shown against each option in the
    picker, and checked before a stored profile is applied. Two spellings have
    to agree for that: a calibration entry says HH00-0.4 while the fitted
    nozzle reports HH01, so the comparison is two characters rather than four
    -- the trailing digits are a hardware variant the calibration table
    normalises to 00.

    Unknown flow on either side matches anything, which is what it has to do.
    Every profile stored before this has none. And an X1C declares none on any
    profile at all -- probed live, all eight come back with an empty nozzle id,
    against a four-digit cali_idx and a populated setting_id -- even though the
    machine really does take either nozzle. supports_nozzle_flow_type is
    therefore the wrong thing to gate on: it returns True for an X1C, and
    treating that silence as Standard would have dropped every X1C profile the
    moment a high-flow nozzle was fitted. What the printer's own table declares
    per profile is the test.

    NozzleInfo.nozzle_type carries two vocabularies by printer generation --
    the nozzle material on legacy printers, the flow code on H2 -- and the
    comment claiming only the former is corrected. Anything that is not HH or
    HS reads as unknown, which is what makes the material spelling harmless.

    Storing both flows for one hotend and diameter is deliberately not done:
    spoolman_k_profile is UNIQUE on (spool, printer, extruder, diameter) with
    no flow column, and allowing a second row in internal mode alone would
    break inventory-mode parity. The picker marks a profile whose flow does not
    match what is fitted instead of letting it look configured while doing
    nothing.
2026-08-28 12:31:39 +02:00