Browse Source

Merge pull request #3644 from maziggy/1.3.2

**Bambuddy 1.3.2**

**What this is**

A fix release on top of 1.3.1: four new features, three changes and 29 fixes. Eight community PRs went in, and 26 people are credited.

The headline is a fix for everyone signed in to **Bambu Cloud** on the **Profiles** page: the Profiles page's cloud list failed to load, and the Slice dialog showed "Failed to load presets" and offered no presets at all, local ones included (#3593). Bambu Cloud answers with an empty value instead of an empty list for a preset type the account has none of, and Bambuddy did not handle that. Such a type now reads as empty, the cloud presets the account has are listed, and slicing works again.

Also new: a maintenance log with a comment on every reset, a choice of which printer an "Any model" job takes, more printer status in the MQTT relay for Home Assistant, and slicer-specific material types in the profile editor. A slice sent again from the slicer now adds a print to its archive instead of a new archive.

New tables and columns are added automatically on both SQLite and PostgreSQL. There are no breaking API changes.

If you are coming from 1.3.0 or earlier, read the 1.3.1 release notes first; their upgrade callouts apply to you as well.

**Before you update**

- **Update the slicer sidecar images** if your sidecars run as a non-root user, for example in Kubernetes with `runAsNonRoot` (#3524). Since 1.3.1 they failed with `bambu-studio: Permission denied`. The sidecar compose file also has a new optional `SIDECAR_BIND` setting in `slicer-api/.env`, to publish the slicer ports on one address only.

- **Users who are not in Administrators lose the old admin role (#3533).** On the first start after the update, the groups decide who is an admin. A user with the old admin role outside Administrators, such as a setup account moved to Operators, is no longer an admin. If they are the only admins, they are added to Administrators instead.

- **MQTT smart plugs with a daily energy counter** (Tasmota's `ENERGY.Today`) lost a print's energy across midnight (#3582). Set the new **Energy JSON Path (lifetime)** on the plug (Tasmota: `ENERGY.Total`) to fix it. Without it, nothing changes.

- **AMS slots set to a support filament before this release** keep PLA (or PA) as their type until they are configured again (#3559).

- **On an iPhone**, remove Bambuddy from the Home Screen and add it again to get the new icon (#3607).

---

**How to update**

**Docker**

```bash
docker compose pull
docker compose up -d
```

**Native install - recommended path**

```bash
sudo BRANCH=main /opt/bambuddy/install/update.sh
```

**Native install - manual path**

```bash
sudo systemctl stop bambuddy
cd /opt/bambuddy
sudo -u bambuddy git fetch --prune --tags --force origin
sudo -u bambuddy git checkout main
sudo -u bambuddy git reset --hard origin/main
sudo /opt/bambuddy/venv/bin/pip install -r requirements.lock
cd frontend && sudo npm i
sudo systemctl start bambuddy
```

**Windows install**

Download `bambuddy-1.3.2-windows-x64-setup.exe` from this release page (or the unversioned `bambuddy-windows-x64-setup.exe` alias). Existing Windows installs upgrade in place via the in-app Install Update flow.

---

**New**

- **A maintenance log for each printer, with a comment on every reset** (#3557, requested and contributed by @Alphakilo in #3569) - resetting a maintenance task asks first and takes an optional comment. Every reset is logged with the task, who did it, when and the print hours at the time. The **Log** button on each printer of the Maintenance page lists its resets, and **Export CSV** downloads them; **Export log** downloads every printer's log, deleted printers included. Earlier resets are copied into the log once, on upgrade.
- **The MQTT relay's printer status has the door, extruder, filament and HMS errors, and the broker gets a Last Will** (#3401, requested by @Tomat0r; #1850, requested by @DingoPD, contributed by @Keybored02 in #3541) - `bambuddy/printers/{serial}/status` now carries `door_open`, `active_extruder`, `tray_now`, `ams`, `vt_tray` and `hms_errors`, so Home Assistant no longer has to poll REST for them. A crash or a killed container now publishes `{"status": "offline"}` on `bambuddy/status`.
- **The profile editor offers the material types of the preferred slicer** (#2928, requested by @doncaruana, contributed by @Keybored02 in #3544) - the **Filament Type** dropdown lists Bambu Studio's or OrcaSlicer's types, whichever is chosen under Settings > Slicer. Existing profiles keep their type.
- **The slicer sidecars can be published on one address only** (suggested by @pleasantone) - see **Before you update**.

**Changed**

- **Choose which printer an "Any model" job takes** (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547) - **Settings > Workflow > Printer Order for Any-Model Jobs**: the fewest print hours (the default, as before), the most, the printer idle the longest, or the printers' own priority, set in **Edit Printer**.
- **A slice sent again from the slicer adds a print to its archive** (#1634, requested by @d3nn3s08, contributed by @Keybored02 in #3508) - a print sent from Bambu Studio or OrcaSlicer, or started on the printer, always got a new archive. A print whose G-code matches an archive now adds a run to it, which keeps its photos, timelapses, notes and tags. Existing archives are read once in the background after the update.
- **The debug log shows what a command the printer reports back contains** (#3531) - so a support package captures exactly what a touchscreen action sends.

**Fixes**

**Slicing and Bambu Cloud:**

- With a Bambu Cloud sign-in, the Slice dialog showed "Failed to load presets" and offered no presets at all, local ones included, and the Profiles page's cloud list failed the same way (#3593, reported by @KevinMidboe). A preset type the account has none of now reads as empty.
- A failed slice for another printer came back as completed, with G-code for the printer the file was made for (#3535, reported by @Jesse-Cachai). The slice now fails with the slicer's error.
- The slicer sidecars failed to slice when run as a non-root user (#3524, reported by @cubic3d). Needs the updated sidecar images.

**Queue and printers:**

- "Any model" queue jobs went to the first free printer without looking at its nozzle, and then failed the nozzle check (#3536, reported and fixed by @Eifel-Joe in #3554). A printer whose nozzle doesn't fit is now passed over, and if none fits the job waits instead of failing.
- Long uploads to an A1 could end in a failed or unreadable print (#3538, reported by @SaadShaya7). Bambuddy now waits for the complete file before the print command, and silence during an upload no longer counts as a dead connection.
- A printer that reconnected still waited out its upload backoff, up to an hour (#3563, reported by @Costyv95). It is now tried again on the next pass.
- Spool assignments were lost when a printer reconnected mid-print and briefly reported a blank slot (#3526, reported by @SaadShaya7). The support package also no longer contains a virtual printer's serial number.
- When the connection check in Add or Edit Printer failed, correcting the IP address, serial number or access code left only **Save anyway** (#3624, reported by @balin77). A corrected value now clears the warning, **Back** is now **Check again**, and the access code can be shown.
- The H2 series' and the H3C's exhaust fan was labelled "Chamber Fan" (#3521, reported by @Spegeli).

**Inventory, AMS and labels:**

- A slot set to a support filament was written as plain PLA or PETG, so it was offered to every PLA part and to nothing that needed support (#3559). It now gets Bambu's type, PLA-S or PA-S. See **Before you update**.
- A spool with a custom cloud preset got Generic PLA when assigned from a SpoolBuddy client or another API key (#3519, reported by @pleasantone).
- Spoolman mode read a filament named after its product, like "Matte Scarlet Red", as a subtype with no colour (#3561, reported by @ARGACE), and renamed the Spoolman filament on every save.
- A spool's slicer preset could not be removed, and clicking into the field could lose the preset's name (#3596, reported by @dertbv).
- Spools got new ids when the inventory moved to another instance by CSV, so printed labels found the wrong spool (#3520, reported by @hurr1k4ne). The export now writes the ids and the import keeps them.
- The spool CSV import read nothing from files saved by Excel with European regional settings (#3523, reported and fixed by @jayhemnani9910 in #3529).
- A group of weighed spools always showed a weight mismatch.
- Spool labels printed empty boxes for Polish, Czech, Cyrillic and Greek letters (#3553, reported by @wsciekly83) and for Chinese, Japanese and Korean (#3560, reported by @mohan456-wqs).
- A long colour or filament name was cut off on a label line even with room below it (#3621, reported by @mohan456-wqs). It now continues on up to three lines.
- **Take photo** could not read the QR code of a small spool label (#3616, reported by @balin77).

**Archives, energy and backup:**

- An archive printed more than once showed the first print's energy next to all plates' filament and cost (#3609, reported by @RafalHo). It now shows the totals of all its prints, as Statistics does.
- An MQTT plug with a daily energy counter lost a print's energy across midnight (#3582, reported by @paulleonartcalvo). See **Before you update**.
- Monitor-only MQTT plugs were switched by automation, which could hold a queue job with "the smart plug could not power it on" (#3583, reported by @paulleonartcalvo). Automation now leaves them alone.
- Making or restoring a backup froze Bambuddy for as long as the files took to copy, half a minute or more with a large archive, and a restore logged a long list of thread stack traces although it succeeded.
- A first Git backup to an empty GitHub repository failed with "Failed to get branch ref" (#3565, reported by @pike00).

**Users and app:**

- A user moved out of Administrators stayed an admin (#3533). See **Before you update**.
- On a phone, a tap on a button could select its label instead of pressing it, and an AMS slot's card opened only on hover (#3577, reported by @balin77). A tap anywhere on a slot now opens its card.
- iOS and Android clipped the home screen icon (#3607, contributed by @pietbrauer in #3617).

**Install:**

- The arm64 Docker image built its frontend under emulation, where the build ran for hours or hung. It is now built natively. Nothing changes for running installs.

**Merged community PRs in this release**

- #3508 by @Keybored02 - a slice sent again from the slicer adds a print to its archive.
- #3529 by @jayhemnani9910 - the spool CSV import reads European Excel files.
- #3541 by @Keybored02 - door, extruder, filament and HMS errors in the MQTT relay, and a Last Will.
- #3544 by @Keybored02 - material types of the preferred slicer.
- #3547 by @Keybored02 - choose which printer an "Any model" job takes.
- #3554 by @Eifel-Joe - "Any model" jobs only go to a printer whose nozzle fits.
- #3569 by @Alphakilo - a maintenance log for each printer.
- #3617 by @pietbrauer - home screen icon padding.

**Thanks**

To everyone who requested, reported, captured logs, or contributed: @Alphakilo, @ARGACE, @balin77, @bryanmahin, @Costyv95, @cubic3d, @d3nn3s08, @dertbv, @DingoPD, @doncaruana, @Eifel-Joe, @hurr1k4ne, @jayhemnani9910, @Jesse-Cachai, @KevinMidboe, @Keybored02, @mohan456-wqs, @paulleonartcalvo, @pietbrauer, @pike00, @pleasantone, @RafalHo, @SaadShaya7, @Spegeli, @Tomat0r, @wsciekly83.

---
**Sponsors**

Bambuddy is sustainable thanks to people who put their money where their use is. If this release saved you time or kept your farm running, the project runs on recurring contributions - there's no paid tier, no telemetry, no upsell, just sustainable maintenance.

- GitHub Sponsors (recurring, 5 tiers from $5/mo to $300/mo) - https://github.com/sponsors/maziggy
- Ko-fi (one-time or recurring) - https://ko-fi.com/maziggy
MartinNYHC 12 hours ago
parent
commit
b7d894b57c
100 changed files with 7237 additions and 726 deletions
  1. 0 120
      .basedpyright/baseline.json
  2. 6 1
      .pre-commit-config.yaml
  3. 57 3
      CHANGELOG.md
  4. 4 2
      Dockerfile
  5. 67 7
      backend/app/api/routes/_spoolman_helpers.py
  6. 38 5
      backend/app/api/routes/archives.py
  7. 2 0
      backend/app/api/routes/auth.py
  8. 41 3
      backend/app/api/routes/cloud.py
  9. 15 1
      backend/app/api/routes/groups.py
  10. 87 26
      backend/app/api/routes/inventory.py
  11. 21 0
      backend/app/api/routes/library.py
  12. 223 6
      backend/app/api/routes/maintenance.py
  13. 1 0
      backend/app/api/routes/mfa.py
  14. 7 1
      backend/app/api/routes/printers.py
  15. 123 80
      backend/app/api/routes/settings.py
  16. 19 3
      backend/app/api/routes/smart_plugs.py
  17. 5 1
      backend/app/api/routes/spoolman.py
  18. 15 5
      backend/app/api/routes/spoolman_inventory.py
  19. 51 42
      backend/app/api/routes/users.py
  20. 1 1
      backend/app/core/config.py
  21. 103 1
      backend/app/core/database.py
  22. 14 0
      backend/app/core/sqlite_fk.py
  23. BIN
      backend/app/data/fonts/DroidSansFallbackFull.ttf
  24. 208 0
      backend/app/data/fonts/LICENSE_DROID
  25. 101 0
      backend/app/data/fonts/LICENSE_LIBERATION
  26. 99 0
      backend/app/data/fonts/LICENSE_NOTO_KR
  27. BIN
      backend/app/data/fonts/LiberationSans-Bold.ttf
  28. BIN
      backend/app/data/fonts/LiberationSans-Italic.ttf
  29. BIN
      backend/app/data/fonts/LiberationSans-Regular.ttf
  30. BIN
      backend/app/data/fonts/NotoSansKR-Hangul.ttf
  31. 121 0
      backend/app/data/slicer_filament_types.json
  32. 428 186
      backend/app/main.py
  33. 2 1
      backend/app/models/__init__.py
  34. 4 0
      backend/app/models/archive.py
  35. 36 0
      backend/app/models/maintenance.py
  36. 4 1
      backend/app/models/printer.py
  37. 7 0
      backend/app/models/smart_plug.py
  38. 4 0
      backend/app/models/spool_assignment.py
  39. 14 1
      backend/app/models/user.py
  40. 7 0
      backend/app/schemas/archive.py
  41. 40 2
      backend/app/schemas/maintenance.py
  42. 4 0
      backend/app/schemas/printer.py
  43. 8 0
      backend/app/schemas/settings.py
  44. 9 0
      backend/app/schemas/smart_plug.py
  45. 146 5
      backend/app/services/archive.py
  46. 134 0
      backend/app/services/archive_gcode_hash.py
  47. 3 0
      backend/app/services/archive_merge.py
  48. 25 1
      backend/app/services/bambu_cloud.py
  49. 64 17
      backend/app/services/bambu_ftp.py
  50. 37 2
      backend/app/services/bambu_mqtt.py
  51. 78 6
      backend/app/services/export.py
  52. 32 30
      backend/app/services/firmware_update.py
  53. 103 1
      backend/app/services/git_providers/github.py
  54. 1 0
      backend/app/services/github_backup.py
  55. 14 0
      backend/app/services/github_restore.py
  56. 171 34
      backend/app/services/label_renderer.py
  57. 16 2
      backend/app/services/log_reader.py
  58. 26 2
      backend/app/services/mqtt_relay.py
  59. 27 1
      backend/app/services/mqtt_smart_plug.py
  60. 4 3
      backend/app/services/obico_actions.py
  61. 1 0
      backend/app/services/oidc_group_sync.py
  62. 20 5
      backend/app/services/plug_energy.py
  63. 242 35
      backend/app/services/print_scheduler.py
  64. 18 1
      backend/app/services/printer_manager.py
  65. 18 9
      backend/app/services/slicer_filament_resolver.py
  66. 53 16
      backend/app/services/smart_plug_manager.py
  67. 73 2
      backend/app/services/spool_csv.py
  68. 52 0
      backend/app/utils/filament_types.py
  69. 29 14
      backend/app/utils/printer_models.py
  70. 276 0
      backend/tests/integration/test_admin_role_follows_groups_3533.py
  71. 5 5
      backend/tests/integration/test_ams_slot_material_2902.py
  72. 368 0
      backend/tests/integration/test_ams_slot_support_type_3559.py
  73. 20 0
      backend/tests/integration/test_archive_merge.py
  74. 315 0
      backend/tests/integration/test_assign_preset_cloud_user_3519.py
  75. 166 0
      backend/tests/integration/test_backup_restore_off_event_loop.py
  76. 156 0
      backend/tests/integration/test_cloud_fields_slicer_types_2928.py
  77. 3 0
      backend/tests/integration/test_external_print_confirmation_1898.py
  78. 245 0
      backend/tests/integration/test_gcode_hash_paths_1634.py
  79. 137 0
      backend/tests/integration/test_inventory_assign.py
  80. 138 1
      backend/tests/integration/test_inventory_csv.py
  81. 41 8
      backend/tests/integration/test_library_slice_api.py
  82. 425 0
      backend/tests/integration/test_maintenance_log.py
  83. 99 0
      backend/tests/integration/test_mqtt_plug_lifetime_energy_3582.py
  84. 1 0
      backend/tests/integration/test_pause_load_paths_2984.py
  85. 2 1
      backend/tests/integration/test_printers_api.py
  86. 359 0
      backend/tests/integration/test_slicer_resend_joins_archive_1634.py
  87. 75 0
      backend/tests/integration/test_spoolman_filament_name_save_3561.py
  88. 25 7
      backend/tests/unit/services/test_bambu_ftp.py
  89. 53 0
      backend/tests/unit/services/test_command_response_content_3531.py
  90. 149 6
      backend/tests/unit/services/test_label_renderer.py
  91. 105 8
      backend/tests/unit/services/test_label_renderer_fields.py
  92. 2 0
      backend/tests/unit/services/test_mqtt_smart_plug_subscribe.py
  93. 26 5
      backend/tests/unit/services/test_p2s_accessory_fans.py
  94. 80 0
      backend/tests/unit/test_archive_run_aggregation.py
  95. 97 0
      backend/tests/unit/test_cloud_preset_listing_nulls_3593.py
  96. 59 0
      backend/tests/unit/test_dispatch_priority_migration_2915.py
  97. 82 0
      backend/tests/unit/test_export_spreadsheet_cells.py
  98. 175 0
      backend/tests/unit/test_github_empty_repo_backup_3565.py
  99. 45 0
      backend/tests/unit/test_maintenance_log_actor.py
  100. 125 0
      backend/tests/unit/test_maintenance_log_backfill.py

+ 0 - 120
.basedpyright/baseline.json

@@ -1627,110 +1627,6 @@
                     "lineCount": 1
                 }
             },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 65,
-                    "endColumn": 67,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 74,
-                    "endColumn": 76,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 38,
-                    "endColumn": 40,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 46,
-                    "endColumn": 56,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 44,
-                    "endColumn": 52,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 46,
-                    "endColumn": 56,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 42,
-                    "endColumn": 48,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 43,
-                    "endColumn": 45,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportArgumentType",
-                "range": {
-                    "startColumn": 35,
-                    "endColumn": 53,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 43,
-                    "endColumn": 53,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 45,
-                    "endColumn": 49,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 39,
-                    "endColumn": 45,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 49,
-                    "endColumn": 62,
-                    "lineCount": 1
-                }
-            },
             {
                 "code": "reportAttributeAccessIssue",
                 "range": {
@@ -2299,14 +2195,6 @@
                     "lineCount": 1
                 }
             },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 19,
-                    "endColumn": 23,
-                    "lineCount": 1
-                }
-            },
             {
                 "code": "reportOptionalMemberAccess",
                 "range": {
@@ -2330,14 +2218,6 @@
                     "endColumn": 16,
                     "lineCount": 1
                 }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 26,
-                    "endColumn": 30,
-                    "lineCount": 1
-                }
             }
         ],
         "./backend/app/services/external_camera.py": [

+ 6 - 1
.pre-commit-config.yaml

@@ -43,7 +43,12 @@ repos:
         # weighted at ~89 ms and the balance it exists to provide degrades.
         # It compresses to ~314 kB in the object store. Regenerate with
         # --store-durations; see the backend test job in .github/workflows/ci.yml.
-        exclude: ^(static/assets/|CHANGELOG\.md$|backend/tests/\.test_durations$)
+        #
+        # The label fonts in backend/app/data/fonts are embedded in label PDFs.
+        # The CJK fallbacks (#3560) cannot fit under the guard: Droid Sans
+        # Fallback is 4 MB of mostly Chinese, and Noto Sans KR is already cut
+        # down to Hangul alone (2.4 MB). A PDF embeds only the glyphs it uses.
+        exclude: ^(static/assets/|CHANGELOG\.md$|backend/tests/\.test_durations$|backend/app/data/fonts/[^/]+\.ttf$)
       - id: check-merge-conflict
       - id: debug-statements
       - id: detect-private-key

+ 57 - 3
CHANGELOG.md

@@ -2,6 +2,50 @@
 
 All notable changes to Bambuddy will be documented in this file.
 
+## [1.3.2] - 2026-11-20
+
+### Added
+- **The MQTT relay's printer status has the door, extruder, filament and HMS errors, and the broker gets a Last Will (#3401, requested by @Tomat0r; #1850, requested by @DingoPD, contributed by @Keybored02 in #3541)** — Home Assistant had to poll REST for these. `bambuddy/printers/{serial}/status` now carries `door_open`, `active_extruder` (which nozzle prints on a dual-nozzle printer), `tray_now`, `ams`, `vt_tray` (the loaded filaments, with their type and colour) and `hms_errors`, in the shape the REST status has. The relay also tells the broker to publish `{"status": "offline"}` on `bambuddy/status` if the connection drops without a clean disconnect, so a crash or a killed container no longer leaves the retained `online` standing, and a printer dropping is published even when a regular update went out less than a second before.
+- **The profile editor offers the material types of the preferred slicer (#2928, requested by @doncaruana, contributed by @Keybored02 in #3544)** — The **Filament Type** dropdown of a filament profile was one list kept in Bambuddy, with types a slicer does not know (and without ones it does), so a profile could be valid here and not in the slicer. It now offers the types of the slicer chosen under Settings → Slicer: Bambu Studio's or OrcaSlicer's, which differ (Orca has SBS and the PA11/PA12 families, Bambu Studio has TPU-AMS). A profile keeps the type it has, imported or cloud-synced, even if the list does not have it, and changing the preferred slicer changes no existing profile.
+- **The slicer sidecars can be published on one address only (suggested by @pleasantone)** — The sidecar compose file published the slicer ports on every network interface, and the sidecars have no login. The new `SIDECAR_BIND` setting in `slicer-api/.env` limits them to one address: `127.0.0.1` when Bambuddy runs on the same host with its default `network_mode: host`. Left unset, nothing changes, so Bambuddy in bridge mode or on another host still reaches the sidecars
+- **A maintenance log for each printer, with a comment on every reset (#3557, requested and contributed by @Alphakilo in #3569)** — Resetting a maintenance task now asks first and takes an optional comment (what was done, parts used, up to 10,000 characters). Every reset is logged with the task, the printer, who did it (when authentication is on) and when, with the print hours at the time. The **Log** button on each printer of the Maintenance page lists its resets, newest first, and **Export CSV** downloads them; **Export log** at the top downloads the log of every printer as one CSV, including printers that have since been deleted. Entries keep the printer, task and user names as they were, so the log outlives a deleted printer, custom task or user. Earlier resets are copied into the log once, on upgrade, without a user, as none was recorded. Entries are kept until deleted: **Clean up** in a printer's log, or **Clean up log** at the top for every printer, deletes the entries older than a chosen number of days (at least one), and a single entry, such as a reset made by mistake, can be deleted from the log (the task stays reset). A deleted entry is gone with its comment, from the task's reset history too. The log is read with the maintenance read permission and cleaned up with the maintenance delete permission, and a user limited to some printers sees and cleans up only theirs. Comments that look like spreadsheet formulas are exported as text.
+### Changed
+- **The debug log shows what a command the printer reports back contains (#3531)** — The printer reports every command it receives back to Bambuddy, also the ones sent from its own touchscreen, and the debug log kept only their names. It now records their content too, so a support package captures exactly what a touchscreen action sends, such as the H3C's Unload All. Status updates and print starts stay name-only: the first arrives every second, the second may carry a signed download link.
+- **A slice sent again from the slicer adds a print to its archive (#1634, requested by @d3nn3s08, contributed by @Keybored02 in #3508)** — A print from the File Manager or the queue already joined the archive of its file, but a print sent from Bambu Studio or OrcaSlicer, or started on the printer, always got a new archive: the slicer writes a new 3MF each time it sends, so the file never matched, and the archive's print count stayed at one. Bambuddy now also keeps the hash of each archive's G-code, and a print whose G-code matches an archive nobody owns, in no project and not from a File Manager file adds a run to that archive. The archive takes the new 3MF in place of its old one and keeps its photos, timelapses, notes, tags and earlier runs; a name set by hand stays, and a name taken from the file follows the new file. While another print of it is running, the archive keeps its file and only gets the run. A model sliced again with other settings gets an archive of its own. OrcaSlicer writes the slicing time into the G-code, so with it only the same slice sent again matches. Archives made before are read once in the background after the update. Wiki updated.
+- **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
+
+### Fixed
+- **Making or restoring a backup no longer freezes Bambuddy** — Unpacking a backup, copying the archive and other folders back, and writing a backup ZIP ran in the part of Bambuddy that answers every page, live update and printer message, so with a large archive folder nothing else happened for half a minute or more. A restore then wrote a long list of thread stack traces starting with "Timeout (0:00:30)!" to the log, although it succeeded. A backup, scheduled or by hand, held up the printers' live status the same way. These steps now run alongside, and Bambuddy keeps responding while they work.
+- **The arm64 Docker image builds its frontend natively** — The arm64 image built its frontend under QEMU emulation, where the build ran for hours or hung. The frontend is the same JavaScript and CSS on every architecture, so it is now built once on the build host; the Python part and the final image are still built for each architecture. Nothing changes for running installs.
+- **The home screen icon has padding, so iOS and Android no longer clip the logo (#3607, contributed by @pietbrauer in #3617)** — Bambuddy's home screen icons were the bare logo on a transparent background, filling it edge to edge. iOS fills transparent pixels with black and rounds the corners itself, so on an iPhone the logo ran into the edges and its corners were cut off. On Android the same images were also the icons the launcher crops to its own shape, so it cut into the logo too. The logo, unchanged, now sits on a dark tile with room around it, and Android gets icons of its own for cropping, with the logo inside the part it always shows. On an iPhone, which keeps the icon it was added with, remove Bambuddy from the Home Screen and add it again to see the new one.
+- **Add and Edit Printer: a corrected value clears the failed connection check, and the access code can be shown (#3624, reported by @balin77)** — When the connection check on save failed, its warning stayed on screen after the IP address, serial number or access code was corrected. The only way to save was **Save anyway**, which saved without checking the corrected value, and the way to check again was **Back**, which did not say so. Changing one of those fields now clears the warning, so the normal button comes back and the next save checks the new values. **Back** is now **Check again**, which runs the check at once, for a printer that has just been switched on; **Save anyway** stays. The access code field has an eye button to show what was typed, hidden by default. Translated in all locales.
+- **A tap on a phone presses the button instead of selecting its label, and opens an AMS slot's card anywhere on the slot (#3577, reported by @balin77)** — On a phone or tablet, a tap on a button that lasted a little long or moved a little selected its label as text, with handles and the copy menu, instead of pressing it. That happened all over the app, as buttons never turned text selection off. Button labels can no longer be selected, and iOS no longer offers its long-press menu on them; text in fields and the rest of the page can still be selected and copied. An AMS slot on the printer card opened its card on hover only, which a phone only fakes after a tap, so a tap on the material name selected the word and the card stayed shut. A slot (AMS, AMS-HT or external spool, filled or empty) now opens its card on a tap anywhere on it, and a second tap, a tap elsewhere or Escape closes it, so only one is open at a time. Enter or Space opens it from the keyboard. A mouse still opens it on hover. Wiki updated.
+- **A long colour or filament name continues on the next line of a spool label (#3621, reported by @mohan456-wqs)** — Every line of a label got one line of text, cut off with "…" when it was too wide, also where the label had room below it. On the 40 × 30 box label the column beside the QR code holds only five to seven Chinese characters, so a Chinese filament name was cut after a few. A line that is too wide now continues on up to three lines, as long as every line ticked below it still gets its own; only what still doesn't fit is cut. Lines break at spaces, and between Chinese or Japanese characters, which have none, without separating a closing bracket or comma from the word before it. Labels whose lines fit look as before.
+- **The QR scanner reads a photo of a small spool label (#3616, reported by @balin77)** — **Take photo** answered "No QR code found in the photo" when the label filled only a small part of the photo, although the phone's camera app read it at once. Where the browser has no QR decoder of its own (every iPhone, and every phone with Bambuddy opened over plain HTTP, where the photo is the only way to scan), the photo was scaled down to 1600 pixels before it was read, and a small label lost too much detail. When that finds nothing, the photo is now read again at its own size, up to 4096 pixels on the long side, which phone browsers can still handle. This takes under a second more, and only for a photo the first read could not read.
+- **An archive printed more than once shows what all its prints cost (#3609, reported by @RafalHo)** — Each plate of a multi-plate file printed one at a time is a print of the same archive, and so is a reprint. The archive card showed the file's filament and cost (all plates together) next to the first print's energy, so a seven-plate print showed the electricity of plate 1 only and matched neither one plate nor Statistics. An archive with more than one print now shows the totals of all of them: the filament they used, its cost, the energy and the wear, as Statistics adds them up, with "Total of N prints" on hover. An energy total is left out when no print was measured by a smart plug. Each print's own figures stay in the Print Log behind the prints badge; archives printed once are unchanged.
+- **A spool's slicer preset can be removed, and opening the field no longer loses its name (#3596, reported by @dertbv)** — the Slicer Preset field in the spool form had no way to remove a preset, so a configured spool could not go back to Stock, in an edit or a copy. Clicking into the field also emptied it, and saving then kept the preset but stored no name for it when the preset was not in the current list, for example a Bambu Cloud preset while the cloud list was unavailable. The spool then showed the raw preset code. The field now has a remove button, closing the list without picking shows the preset again, and text typed to search is never saved as the preset's name. The same applies to the SpoolBuddy write-tag page.
+- **The Slice dialog lists presets when a Bambu Cloud account has none of one type (#3593, reported by @KevinMidboe)** — Bambu Cloud answers "nothing here" for a preset type with an empty value instead of an empty list, for example on an account with no filament presets of its own. Bambuddy did not handle that, so with a Bambu Cloud sign-in on the Profiles page the Slice dialog showed "Failed to load presets" and offered no presets at all, local ones included, and the Profiles page's cloud list failed the same way. Such a type now reads as empty, and the presets the account does have are listed.
+- **Monitor-only MQTT plugs are no longer switched by automation (#3583, reported by @paulleonartcalvo)** — Bambuddy only listens to an MQTT plug, so it cannot turn one on or off, but its Auto On and Auto Off were on by default, hidden in the plug's settings, and every automation tried anyway. With an MQTT plug for metering and a switchable plug on the same printer, the queue could pick the MQTT plug to power the printer on, fail, and hold the job with "the smart plug could not power it on". A printer whose only plug was an MQTT plug counted as one the queue could switch on, so its job said "Offline" instead of that it has no Auto On plug. Auto-off at print end, "auto off after this job", auto-off after drying, plug schedules and the AI failure detection's power-off all logged a failed turn-off for it. All of them now leave MQTT plugs alone, and an auto-off still pending on one from an earlier version is cleared at startup. Home Assistant scripts linked to a printer still run at print start as before.
+- **An MQTT plug keeps a print's energy across midnight (#3582, reported by @paulleonartcalvo)** — A print's energy is what the plug's counter went up by between its start and its end, and an MQTT plug had one energy value that Bambuddy used as both today's and the lifetime counter. Many devices publish a daily counter there (Tasmota's `ENERGY.Today`), which drops back to zero at midnight: a print that ran past midnight came out negative and got no energy or energy cost, or ended above its start and silently lost everything before midnight. MQTT plugs now have an **Energy JSON Path (lifetime)** and its own multiplier, read from the energy topic, for the counter that never resets (Tasmota's `ENERGY.Total`, in the same message). With it set, per-print energy and cost use the lifetime counter, the plug feeds the hourly snapshots behind the Statistics date filters and the all-time total, and the energy summary under Settings > Smart Plugs counts it in the lifetime total. A topic with only the lifetime counter still gets a Today, worked out from the snapshots. Without it, a plug reads its one energy value as before, so nothing changes for a topic that already carries a lifetime counter. Translated in all locales; wiki updated. Covered by backend and frontend tests.
+- **A first Git backup to an empty GitHub repository works (#3565, reported by @pike00)** — GitHub answers a repository with no commits with HTTP 409 "Git Repository is empty", and Bambuddy stopped there with "Failed to get branch ref", although Test Connection passed. Its fallback for an empty repository could not have helped either: it builds the first commit from blobs and trees, and GitHub refuses those too until the repository has a commit. The first backup now makes that commit through GitHub's Contents API, which writes one file, and pushes the rest on top, so no README or placeholder file is needed. Any other 409 is still reported as an error. Wiki updated.
+- **A printer that reconnects no longer waits out its upload backoff (#3563, reported by @Costyv95)** — When a printer's file service stops answering, Bambuddy sends it no jobs for a while, five minutes after the first refused upload and doubling up to an hour. Restarting the printer fixed its file service, but the queue still waited out the rest of that hour, and only restarting Bambuddy sent the job. A printer that reconnects is now tried again on the next pass, and the FTP cool-off from before the reconnect no longer blocks that try. If it still refuses, the next wait is the longer one and no second Job Waiting notification is sent. Wiki updated.
+- **Spoolman mode reads the subtype and colour from a filament named after its product (#3561, reported by @ARGACE)** — Spoolman has no subtype or colour-name field, so Bambuddy reads both from the filament's name, and it only understood names it writes itself ("PLA Matte"). A filament named "Matte Scarlet Red", "Silk+ Baby Blue" or "Gold - Basic PLA" got its whole name as the subtype and no colour, so the spool form left the colour blank. The finish words (Basic, Matte, Silk, HF, ...) are now the subtype and the rest of the name is the colour, wherever the material stands in it. Saving a spool also renamed its Spoolman filament to "material subtype" on every save; the name is now only rebuilt when the material or subtype is changed.
+- **Spool labels print Chinese, Japanese and Korean (#3560, reported by @mohan456-wqs)** — Since labels embed Liberation Sans (#3553), every character was drawn in that font, which has no Chinese, Japanese or Korean, so names in those languages came out as empty boxes in the PDF and in the preview. Installing fonts in the container could not help, because labels only use the fonts Bambuddy embeds. A character Liberation Sans lacks is now drawn in Droid Sans Fallback (Chinese and Japanese) or Noto Sans KR (Korean), and only the characters a label uses are embedded. Long names are shortened by their real printed width. These fonts have no bold or italic, so CJK text on a bold or italic line prints in regular weight.
+- **A slot set to a support filament is a support slot (#3559)** — BambuStudio puts a support filament into an AMS slot as **PLA-S** (or **PA-S**), and a plate sliced with one asks for that type. Bambuddy wrote plain **PLA** instead, whether the slot was set with **Configure**, by assigning a spool or by linking a Spoolman spool, so a slot holding Support For PLA was offered to every PLA part and to nothing that needed support. Support W and Support For PLA/PETG came out as PLA and PETG. Bambu's support filaments now get Bambu's type, and a third-party or user preset whose name says "Support" gets PLA-S or PA-S over PLA or PA. Slots set up before this keep PLA until they are configured again. The spool form's built-in list, shown when no other preset source is available, also had wrong filament ids for most entries (Bambu PLA-CF was filed under Support W); they now match Bambu's.
+- **A group of weighed spools no longer shows a false weight mismatch** — With **Group** on, the collapsed row of a group compared the first spool's scale reading with the weight of the whole group, so a group of two or more weighed spools always showed a mismatch, and its **Sync** button re-synced only the first spool. The group row now shows no weight check; each spool in the expanded group keeps its own.
+- **"Any model" queue jobs only go to a printer whose nozzle fits (#3536, reported and fixed by @Eifel-Joe in #3554)** — A job queued for any printer of a model went to the first free one without looking at its nozzle, and the nozzle check before the start then failed it, even when another printer of the model had the right nozzle. With two A1s (0.4 mm and 0.6 mm), a file sliced for 0.6 mm could fail on the 0.4 mm one. Now a printer whose nozzles, including the nozzle rack on an H2C, don't fit the file is passed over. If no printer of the model fits, the job waits with "No A1 has a 0.6mm nozzle: ..." instead of failing, and starts by itself once a matching nozzle is fitted. A file or printer without a known nozzle size counts as fitting, as before. Waking a printer with its smart plug, moving a job held for low filament and auto-drying use the same check. A job for one specific printer is unchanged.
+- **Spool labels print Polish, Czech, Cyrillic and Greek letters (#3553, reported by @wsciekly83)** — Label PDFs used the PDF base font Helvetica, which only has Western European characters, so letters like ą, ę, ł, ś or ż and any Cyrillic or Greek text came out as empty boxes, although the inventory showed them correctly. Labels now embed Liberation Sans, which has the same letter widths, so the layout is unchanged. Chinese and Japanese characters are not covered yet
+- **The spool CSV import reads files saved by Excel with European regional settings (#3523, reported and fixed by @jayhemnani9910 in #3529)** — Excel in a comma-decimal locale (German, French, Dutch, Italian, ...) saves CSV with `;` between the fields and `,` as the decimal mark. The import only read commas, so the whole header became one unknown column and nothing was imported ("Required column 'material' is missing"). The separator is now taken from the header line, and in a `;` file a decimal comma in `cost_per_kg` and `weight_used` is read as a decimal point, so `24,99` imports as 24.99. Comma-separated files are read as before. Wiki updated.
+- **Long uploads to an A1 no longer end in a failed or unreadable print (#3538, reported by @SaadShaya7)** — Two problems at the handoff from a slow upload to the print command, seen with a 19 MB file that took three minutes. When the printer didn't confirm the upload, Bambuddy read the file size back, logged that the file was incomplete, and sent the print command anyway: the printer was still writing the file and either stayed idle or reported that it could not parse it. Bambuddy now keeps reading the size for up to two minutes, sends the print command once the file is complete, and otherwise retries the upload. And because the A1 sends no status while it receives a file, Bambuddy took the silence for a dead connection and reconnected just before the print command, which then failed the job. Silence during an upload, and in the minute after it, no longer counts as a dead connection; this also applies to firmware uploads.
+- **A failed slice for another printer is reported as failed (#3535, reported by @Jesse-Cachai)** — When the slicer failed on a 3MF with the picked printer, process and filament profiles, Bambuddy retried with the settings saved in the file and reported the slice as completed. Those settings are for the printer the file was made for, so a P1S project sliced for another printer came back as P1S G-code, with a believable print time and filament estimate. The retry now runs only when the file was made for the picked printer. For any other printer, or when either printer can't be told from the file or the profile, the slice fails with the slicer's error.
+- **A user moved out of Administrators is no longer an admin (#3533)** — Users carry an older admin role next to their groups, and either one made them an admin. The account created during setup has both, so moving it from Administrators to Operators left it with every admin right, still showing the Admin badge, and the user settings had no way to remove the role. The groups now decide: the role follows them wherever they change, in the user settings, on the groups, through the API and at LDAP or OIDC sign-in. Removing the last admin from Administrators is refused, as deactivating them already was. On the first start after the update, users who are not in Administrators lose the old admin role. If they are the only admins, they are added to Administrators instead.
+- **Spool assignments survive a printer reconnecting mid-print (#3526, reported by @SaadShaya7)** — After a short network drop, the first report of a reconnecting printer can show a slot with no filament type and colour `00000000`. Bambuddy only recognised an empty colour as a blank slot, so it read this as a different spool and removed the inventory assignment, even during a print. All four assignments on an A1 mini's AMS lite and an A2L's external spool were lost that way and had to be made again. A slot reporting `00000000` with no type now counts as blank: during a print the assignment is kept as a possible runout, otherwise it is unlinked only if the slot stays blank for two minutes. A clear filament, which also reports `00000000` but with its type, is not affected. The support package also no longer contains a virtual printer's serial number: for the A2L, P2S, H2 series and X2D models it appeared in full in the certificate log lines.
+- **The slicer sidecars run as a non-root user again (#3524, reported by @cubic3d)** — Since 1.3.1, both the Bambu Studio and the OrcaSlicer sidecar failed to slice when the container runs as another user than root, as in a Kubernetes pod with `runAsNonRoot`: the log showed `bambu-studio: Permission denied`. The new slicer releases unpack with folders only root can open; the images now open them to every user, and the image build stops if any folder stays closed. Needs the updated sidecar images.
+- **The H2 series' and the H3C's exhaust fan is labelled Exhaust (#3521, reported by @Spegeli)** — The printer card called fan 3 "Chamber Fan" on the H2D, H2D Pro, H2C, H2S and H3C. On these printers it is the exhaust fan in the back wall, which Bambu Studio names "Exhaust", as on the P2S and X2D. Only the X1 series and P1S call it the chamber fan. The badge is still always shown on these printers, since the fan is built in, and the confirmation after setting the fan names it the exhaust fan too.
+- **Spools keep their ids when the inventory moves by CSV (#3520, reported by @hurr1k4ne)** — The CSV export had no id column, so importing it on another instance numbered the spools anew, in the order of the file, and every printed label, whose QR code carries the spool's id, found the wrong spool or none. The export now writes each spool's id, and the import keeps it when that instance has never used it, which on a fresh instance is every id. An id already used there, also by a deleted spool, or named twice in the file gets a new one, and the preview says how many. The preview shows the id each spool keeps. A CSV without the column imports as before.
+- **A spool with a custom cloud preset gets it from a SpoolBuddy client too (#3519, reported by @pleasantone)** — With login on, each user signs in to Bambu Cloud separately. Assigning a spool from an API key, as a SpoolBuddy client does, had no signed-in user, so its custom preset (PFUS or PFCN) could not be looked up and the slot got Generic PLA, while the same assign from the web UI got the preset's own filament. Configuring a pre-assigned slot when the spool is inserted had the same problem, even for assignments made in the web UI. Both now use a user's sign-in: the API key's owner, and whoever made the assignment. A custom preset that still can't be looked up is now named in the log.
+
+
 ## [1.3.1] - 2026-11-11
 
 ### Added
@@ -11,13 +55,25 @@ All notable changes to Bambuddy will be documented in this file.
 - **Cam Wall tiles show temperatures and finish time, and can pause, stop and switch the light (#3479, sponsor vote Q4 2026)** — With the **Full** status overlay, every connected tile shows its nozzle (both on a dual-nozzle printer), bed and chamber temperatures, and a printing tile adds its finish time beside the time left. Hovering over a tile shows **Pause/Resume** and **Stop**, with the same confirmations as the printer card, and a **chamber light** switch; **Tile controls: Always** in the wall settings keeps them on screen, and a touch screen always shows them. The controls need the `printers:control` permission; a user without it, an offline printer and a Cam Wall token (kiosk) wall get none.
 - **The H2C shows how long each nozzle has printed (#1908, contributed by @Keybored02 in #3507)** — Recent H2C firmware counts the print time of every nozzle, which says more about a nozzle's use than the wear estimate. Hovering over a nozzle on the printer card, in the nozzle rack or on the left and right hotend, now shows its **Print time** next to **Wear**. Firmware that does not report it, and other printers, show no print time. Wiki updated.
 
+- **The profile editor offers the material types of the preferred slicer (#2928, requested by @doncaruana, contributed by @Keybored02 in #3544)** — The **Filament Type** dropdown of a filament profile was one list kept in Bambuddy, with types a slicer does not know (and without ones it does), so a profile could be valid here and not in the slicer. It now offers the types of the slicer chosen under Settings → Slicer: Bambu Studio's or OrcaSlicer's, which differ (Orca has SBS and the PA11/PA12 families, Bambu Studio has TPU-AMS). A profile keeps the type it has, imported or cloud-synced, even if the list does not have it, and changing the preferred slicer changes no existing profile.
+- **The slicer sidecars can be published on one address only (suggested by @pleasantone)** — The sidecar compose file published the slicer ports on every network interface, and the sidecars have no login. The new `SIDECAR_BIND` setting in `slicer-api/.env` limits them to one address: `127.0.0.1` when Bambuddy runs on the same host with its default `network_mode: host`. Left unset, nothing changes, so Bambuddy in bridge mode or on another host still reaches the sidecars
 ### Changed
+- **A slice sent again from the slicer adds a print to its archive (#1634, requested by @d3nn3s08, contributed by @Keybored02 in #3508)** — A print from the File Manager or the queue already joined the archive of its file, but a print sent from Bambu Studio or OrcaSlicer, or started on the printer, always got a new archive: the slicer writes a new 3MF each time it sends, so the file never matched, and the archive's print count stayed at one. Bambuddy now also keeps the hash of each archive's G-code, and a print whose G-code matches an archive nobody owns, in no project and not from a File Manager file adds a run to that archive. The archive takes the new 3MF in place of its old one and keeps its photos, timelapses, notes, tags and earlier runs; a name set by hand stays, and a name taken from the file follows the new file. While another print of it is running, the archive keeps its file and only gets the run. A model sliced again with other settings gets an archive of its own. OrcaSlicer writes the slicing time into the G-code, so with it only the same slice sent again matches. Archives made before are read once in the background after the update. Wiki updated.
 - **SpoolBuddy writes OpenTag3D 2.004 on NTAG215 and NTAG216 tags (#3500, suggested by @pleasantone)** — SpoolBuddy wrote the first version of the OpenTag3D layout. The current version moved every field, so a reader that only knows it read the brand, colour, weight and temperatures from the wrong places. Tags with room for it now get version 2.004, with material, brand, colour name, up to four colours, minimum and maximum print temperature, net weight and empty spool weight. Version 2 no longer fits on an NTAG213, so those keep the first version. SpoolBuddy picks by the size the tag reports, and falls back to the first version if it can't read it; a SpoolBuddy that hasn't been updated keeps writing the first version. Bambuddy does not track density or bed temperature, so a version 2 tag leaves them unset. Wiki updated.
 - **Profile defaults is compact and has Apply all** — Settings → Filament → Profile defaults showed every default as a large box with all its presets and K profiles, so a few products already filled the page. Each default is now one line (product, colour, slicer preset, and how many printer presets and K profiles it has), sorted by product, with a search box; click a line to see its presets and K profiles. The list scrolls on its own. **Apply all** applies every default to the spools in stock in one go, and like Apply to existing spools it only fills in what a spool doesn't have yet. Wiki updated.
 - **Slicer sidecars on Bambu Studio 02.09.01.70 and OrcaSlicer 2.5.0 (#3442)** — The Bambu Studio sidecar now ships the H3C printer presets (0.2, 0.4, 0.6 and 0.8 mm nozzle). OrcaSlicer has no H3C presets yet. OrcaSlicer 2.5.0 ships its bundled presets in a new packed format, so the sidecar image now fetches the same release's presets as JSON for its preset handling. Slicing with a printer preset saved under a name of its own keeps working on 2.5.0; the sliced file then names the Bambu preset it was saved from as its printer preset. Sidecar images built for older slicer versions work as before.
 - **"Any model" jobs go to the printer with the fewest print hours (#3480, sponsor vote Q4 2026)** — When several printers of a model can take a job, the queue used to pick the first one in its list, so on a farm the same printer got most of the work. It now picks the one with the fewest print hours (the Maintenance counter, including baseline hours entered there), so jobs and wear spread across the farm. Preferred colours still come first, and the queue powers on the least used printer too when it has to switch one on with an Auto Power On plug.
+- **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **Long uploads to an A1 no longer end in a failed or unreadable print (#3538, reported by @SaadShaya7)** — Two problems at the handoff from a slow upload to the print command, seen with a 19 MB file that took three minutes. When the printer didn't confirm the upload, Bambuddy read the file size back, logged that the file was incomplete, and sent the print command anyway: the printer was still writing the file and either stayed idle or reported that it could not parse it. Bambuddy now keeps reading the size for up to two minutes, sends the print command once the file is complete, and otherwise retries the upload. And because the A1 sends no status while it receives a file, Bambuddy took the silence for a dead connection and reconnected just before the print command, which then failed the job. Silence during an upload, and in the minute after it, no longer counts as a dead connection; this also applies to firmware uploads.
+- **A failed slice for another printer is reported as failed (#3535, reported by @Jesse-Cachai)** — When the slicer failed on a 3MF with the picked printer, process and filament profiles, Bambuddy retried with the settings saved in the file and reported the slice as completed. Those settings are for the printer the file was made for, so a P1S project sliced for another printer came back as P1S G-code, with a believable print time and filament estimate. The retry now runs only when the file was made for the picked printer. For any other printer, or when either printer can't be told from the file or the profile, the slice fails with the slicer's error.
+- **A user moved out of Administrators is no longer an admin (#3533)** — Users carry an older admin role next to their groups, and either one made them an admin. The account created during setup has both, so moving it from Administrators to Operators left it with every admin right, still showing the Admin badge, and the user settings had no way to remove the role. The groups now decide: the role follows them wherever they change, in the user settings, on the groups, through the API and at LDAP or OIDC sign-in. Removing the last admin from Administrators is refused, as deactivating them already was. On the first start after the update, users who are not in Administrators lose the old admin role. If they are the only admins, they are added to Administrators instead.
+- **Spool assignments survive a printer reconnecting mid-print (#3526, reported by @SaadShaya7)** — After a short network drop, the first report of a reconnecting printer can show a slot with no filament type and colour `00000000`. Bambuddy only recognised an empty colour as a blank slot, so it read this as a different spool and removed the inventory assignment, even during a print. All four assignments on an A1 mini's AMS lite and an A2L's external spool were lost that way and had to be made again. A slot reporting `00000000` with no type now counts as blank: during a print the assignment is kept as a possible runout, otherwise it is unlinked only if the slot stays blank for two minutes. A clear filament, which also reports `00000000` but with its type, is not affected. The support package also no longer contains a virtual printer's serial number: for the A2L, P2S, H2 series and X2D models it appeared in full in the certificate log lines.
+- **The slicer sidecars run as a non-root user again (#3524, reported by @cubic3d)** — Since 1.3.1, both the Bambu Studio and the OrcaSlicer sidecar failed to slice when the container runs as another user than root, as in a Kubernetes pod with `runAsNonRoot`: the log showed `bambu-studio: Permission denied`. The new slicer releases unpack with folders only root can open; the images now open them to every user, and the image build stops if any folder stays closed. Needs the updated sidecar images.
+- **The H2 series' and the H3C's exhaust fan is labelled Exhaust (#3521, reported by @Spegeli)** — The printer card called fan 3 "Chamber Fan" on the H2D, H2D Pro, H2C, H2S and H3C. On these printers it is the exhaust fan in the back wall, which Bambu Studio names "Exhaust", as on the P2S and X2D. Only the X1 series and P1S call it the chamber fan. The badge is still always shown on these printers, since the fan is built in, and the confirmation after setting the fan names it the exhaust fan too.
+- **Spools keep their ids when the inventory moves by CSV (#3520, reported by @hurr1k4ne)** — The CSV export had no id column, so importing it on another instance numbered the spools anew, in the order of the file, and every printed label, whose QR code carries the spool's id, found the wrong spool or none. The export now writes each spool's id, and the import keeps it when that instance has never used it, which on a fresh instance is every id. An id already used there, also by a deleted spool, or named twice in the file gets a new one, and the preview says how many. The preview shows the id each spool keeps. A CSV without the column imports as before.
+- **A spool with a custom cloud preset gets it from a SpoolBuddy client too (#3519, reported by @pleasantone)** — With login on, each user signs in to Bambu Cloud separately. Assigning a spool from an API key, as a SpoolBuddy client does, had no signed-in user, so its custom preset (PFUS or PFCN) could not be looked up and the slot got Generic PLA, while the same assign from the web UI got the preset's own filament. Configuring a pre-assigned slot when the spool is inserted had the same problem, even for assignments made in the web UI. Both now use a user's sign-in: the API key's owner, and whoever made the assignment. A custom preset that still can't be looked up is now named in the log.
 - **Closing a camera view no longer leaves a CPU core at 100% (#3515, reported by @BrainDeLook)** — A viewer leaving while its stream was reading from the SQLite database could leave that connection's close waiting forever, on a bug in aiosqlite (omnilib/aiosqlite#403). Bambuddy then kept one CPU core fully busy, even with every viewer closed, and other pages such as Projects and Spool Inventory became very slow until a restart. Bambuddy now works around the aiosqlite bug, for every database connection, not only the camera's, and the camera stream's short reads (the chamber light settings and the periodic access check) finish before a leaving viewer ends the stream. PostgreSQL was not affected.
 - **The external spool keeps its filament after Configure Slot on an A1 or A1 mini (#3513, reported by @SaadShaya7)** — These printers report a change to the external spool with only what changed, often just the colour. Bambuddy stored that as the whole slot, so after a colour or preset change the spool showed as empty, with no filament type, until the printer's next full update. The check that the printer took the new preset also could not find the slot and reported it as not confirmed. A partial update now changes only what it carries, and the check confirms the new preset as soon as the printer reports it.
 - **A print that fails before its first layer no longer charges a whole spool (#3511)** — When a print failed or was cancelled before its first layer, Bambuddy worked out from the sliced file that no filament was used, but still let the AMS remaining % decide for that slot. The AMS can read 0% for a moment as the filament unloads, so a new spool at 100% was charged in full: 1000 g and its cost for a print stopped after five minutes, which then topped the Stats page as the heaviest and most expensive print. A slot whose spool the sliced file already accounts for is now left to that figure, so such a print charges nothing. Prints without a sliced file still use the AMS remaining %.
@@ -41,6 +97,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **A camera window no longer opens a dozen streams to the printer at once (#3431, reported by @buffdriver)** — When the floating camera window was open while the page loaded (after a refresh, for example), Bambuddy opened about twenty camera streams for it. Only one was shown. The browser kept the rest open until the tab was closed, and they filled its six connections to the server. The page started each stream while still preparing to draw the window. It prepared the window several times before showing it, and every attempt left a stream behind. Streams now start only once the window is on the page. The camera page, the camera wall and the stream overlay start their streams the same way.
 - **A printer whose file service hangs during a print is no longer asked again and again until it refuses every upload (#3474, reported by @F9mm)** — When the card could not be read at print start, the timelapse baseline was read again every two minutes for the whole print, and each round walked the card twice: up to eight new FTPS connections, each hanging for 30 s against a hung printer. An H2S kept a session for every one of them, then answered every connection with "421 There are too many connections", and no queued job could reach it until the printer was restarted. The card is now read once per round. It is read again only while the print records a timelapse, the wait doubles after each failed round (up to 30 minutes), and it stops after five. A connection or listing that times out now pauses the background timelapse scans of that printer for five minutes. Opening files and sending prints are not held up by this. A printer that answers "421 too many connections" now gets its own message in the queue, saying it may need a restart, instead of "Bambuddy will retry automatically". Wiki updated.
 
+
 ## [1.3.0] - 2026-10-06
 
 ### Added
@@ -206,9 +263,6 @@ All notable changes to Bambuddy will be documented in this file.
 - **Camera settings have their own tab, and the settings menu is sorted alphabetically** — Camera settings were split across two tabs: external cameras under General, and camera tokens and the Streaming Overlay builder under API Keys. A new **Camera** tab now holds all three: **External Cameras**, **Camera API Tokens** and **Streaming Overlay**. Old links to the tokens or the overlay builder, including `/camera-tokens`, open the Camera tab. API Keys keeps API keys, webhooks, Connected Apps and the API browser, and is no longer shown to a user who may see none of them; before, such a user only went there for their camera tokens, so an API Keys link now opens the Camera tab for them. Settings search finds the Streaming Overlay builder. The settings menu now lists **General** first and the other tabs alphabetically in the interface language. In Connected Apps, the **Add app** button no longer runs past the edge of the card on mid-sized screens, and the Brazilian Portuguese camera button on the printer card reads "Câmera" again instead of "âmera". Wiki updated. Covered by frontend tests.
 
 ### Fixed
-- **The log says which auto-archive switch skipped a print (#3477, reported by @Fuzzylog2x)** — Since 1.3.0 the global **Auto-archive prints** switch (Settings > General > Archive Settings) takes effect for prints started outside Bambuddy. Before, it was saved and never read, so an install upgraded with it off stopped archiving, and the statistics stopped updating. The log only said "auto_archive: False", the same as for a printer's own switch. It now names the global switch or the printer, whichever turned archiving off.
-- **A camera window no longer opens a dozen streams to the printer at once (#3431, reported by @buffdriver)** — When the floating camera window was open while the page loaded (after a refresh, for example), Bambuddy opened about twenty camera streams for it. Only one was shown. The browser kept the rest open until the tab was closed, and they filled its six connections to the server. The page started each stream while still preparing to draw the window. It prepared the window several times before showing it, and every attempt left a stream behind. Streams now start only once the window is on the page. The camera page, the camera wall and the stream overlay start their streams the same way.
-- **A printer whose file service hangs during a print is no longer asked again and again until it refuses every upload (#3474, reported by @F9mm)** — When the card could not be read at print start, the timelapse baseline was read again every two minutes for the whole print, and each round walked the card twice: up to eight new FTPS connections, each hanging for 30 s against a hung printer. An H2S kept a session for every one of them, then answered every connection with "421 There are too many connections", and no queued job could reach it until the printer was restarted. The card is now read once per round. It is read again only while the print records a timelapse, the wait doubles after each failed round (up to 30 minutes), and it stops after five. A connection or listing that times out now pauses the background timelapse scans of that printer for five minutes. Opening files and sending prints are not held up by this. A printer that answers "421 too many connections" now gets its own message in the queue, saying it may need a restart, instead of "Bambuddy will retry automatically". Wiki updated.
 - **Obico failure detection scores like Obico, and a resumed print isn't paused again (#3459, reported by @jasoncronje)** — Bambuddy's port of Obico's scoring left out the step that subtracts the long-term average, so whatever the camera always sees (plate texture, labels) added straight into the score, and the configured action ran as soon as that score passed High. The decision is now Obico's own: the score is the smoothed value minus the printer's long-term average, which carries over between prints on the same printer, so a background that is always in view no longer builds up. Between Low and High a slow build-up is not failing. **Notify only** fires at Obico's alert level, while **Pause print** and **Pause and cut power** wait for its pause level, which takes a clearly stronger signal and is now shown in the Status panel. A detection that appears suddenly and stays is still treated as a failure, as in Obico. Pausing a print no longer resets detection, so a print Bambuddy paused is not paused again after you resume it; the next print starts fresh. Wiki updated.
 - **A dropped printer connection no longer replays old commands and cancels the print (#3454, reported and diagnosed by @SaadShaya7)** — When the connection to a printer dropped and came back by itself, every command still waiting for the printer's acknowledgement was sent again. Bambu printers often don't acknowledge, so that could be a Stop or a print start from hours earlier: a print 4 hours in was cancelled seconds after the reconnect, and an old print start raised "Device is busy and cannot start new task". Commands from the previous connection are now dropped when it comes back, also when a printer that was switched off is turned on again, and the log says how many. A command sent in the seconds before a drop isn't sent again; click it once more.
 - **Finish photo: the plate is no longer driven to the bottom after a tall print** — With **Restore plate for finish photo** on, Bambuddy lowered the plate after the photo to the print's height + 100 mm, whatever the printer. On a 238 mm print on an H2C that is Z338, past the bottom of its travel: Bambu's own end G-code stops at the print's height + 2 mm when +100 doesn't fit, and the printer does not stop G-code sent over the network at its limits. The plate now goes back exactly where the print's end G-code left it, read from the archived file, and is only raised for the photo when the end G-code left it lower than just above the print (the H2C's doesn't, so its plate stays put). A file whose end position can't be read is not moved at all. Wiki updated.

+ 4 - 2
Dockerfile

@@ -1,5 +1,7 @@
-# Build frontend
-FROM node:22-bookworm-slim AS frontend-builder
+# Build frontend. Its output is plain JS/CSS, the same on every architecture,
+# so it is built natively on the build host: under QEMU emulation the arm64
+# vite build ran for hours or hung.
+FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS frontend-builder
 
 WORKDIR /app/frontend
 

+ 67 - 7
backend/app/api/routes/_spoolman_helpers.py

@@ -14,6 +14,7 @@ from typing import Any
 from typing_extensions import TypedDict
 
 from backend.app.api.routes._url_safety import assert_safe_lan_service_url
+from backend.app.utils.filament_finish import KNOWN_FINISHES, finishes
 
 logger = logging.getLogger(__name__)
 
@@ -109,6 +110,66 @@ def assert_safe_spoolman_url(url: str) -> None:
 # Six characters, or eight when the filament carries an alpha byte. The write
 # side stores eight only for genuinely translucent spools (#2912); rejecting
 # them here turned every clear spool into neutral grey on read.
+# Spoolman has no subtype or colour-name field, only the filament's name, so
+# both are read out of it. Finish phrases longest first, so "Dual Color" is
+# taken before anything inside it.
+_FINISH_PHRASES: tuple[tuple[str, ...], ...] = tuple(
+    sorted((tuple(f.split()) for f in KNOWN_FINISHES), key=len, reverse=True)
+)
+# Punctuation that only separates parts of a name: "Gold - Basic PLA".
+_NAME_PUNCT = "-\u2013\u2014,/|()[]:;"
+
+
+def split_spoolman_filament_name(material: str | None, name: str | None) -> tuple[str | None, str | None]:
+    """(subtype, colour name) from a Spoolman filament's name (#3561).
+
+    Bambuddy writes a filament as ``"<material> <subtype>"`` ("PLA Matte"), and
+    that is all this used to read: the material came off the front and the
+    rest was the subtype. Spoolman users name a filament after the product --
+    "Matte Scarlet Red", "Silk+ Baby Blue", "Gold - Basic PLA" -- and then the
+    whole name became the subtype and the colour was left unnamed.
+
+    The material is removed wherever it stands. The finishes Bambuddy knows
+    (``KNOWN_FINISHES``: Basic, Matte, Silk, ...) are the subtype, as written,
+    and the rest is the colour. A name with no finish keeps the old reading
+    when it starts with the material, so a subtype Bambuddy wrote that is no
+    finish ("PLA Engineering") still comes back as the subtype -- unless the
+    material already carries the finish ("PLA Matte" / "PLA Matte Grey"), where
+    what follows can only be the colour.
+    """
+    mat = (material or "").strip()
+    text = (name or "").strip()
+    starts_with_material = bool(mat) and bool(re.match(rf"{re.escape(mat)}(?![\w-])", text, flags=re.IGNORECASE))
+    if starts_with_material:
+        rest = text[len(mat) :]
+    elif mat:
+        rest = re.sub(rf"(?<![\w-]){re.escape(mat)}(?![\w-])", " ", text, count=1, flags=re.IGNORECASE)
+    else:
+        rest = text
+
+    tokens = [t.strip(_NAME_PUNCT) for t in rest.split()]
+    tokens = [t for t in tokens if t and any(ch.isalnum() for ch in t)]
+    finish_words: list[str] = []
+    colour_words: list[str] = []
+    i = 0
+    while i < len(tokens):
+        for phrase in _FINISH_PHRASES:
+            window = tokens[i : i + len(phrase)]
+            if tuple(t.lower().rstrip("+") for t in window) == phrase:
+                finish_words.extend(window)
+                i += len(phrase)
+                break
+        else:
+            colour_words.append(tokens[i])
+            i += 1
+
+    if finish_words:
+        return " ".join(finish_words), " ".join(colour_words) or None
+    if starts_with_material and not finishes(mat):
+        return rest.strip() or None, None
+    return None, " ".join(colour_words) or None
+
+
 _COLOR_HEX_RE = re.compile(r"^[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$")
 _TAG_HEX_RE = re.compile(r"^[0-9A-F]+$")
 
@@ -400,13 +461,10 @@ def _map_spoolman_spool(spool: dict) -> MappedSpoolFields:
         elif 8 <= len(uid) <= 30:
             tag_uid = tag_uid or uid
 
-    # Subtype = filament name with material prefix stripped
+    # Subtype and colour from the filament's name (#3561).
     material: str = (filament.get("material") or "").strip()
     filament_name: str = (filament.get("name") or "").strip()
-    if material and filament_name.upper().startswith(material.upper()):
-        subtype: str | None = filament_name[len(material) :].strip() or None
-    else:
-        subtype = filament_name or None
+    subtype, name_color = split_spoolman_filament_name(material, filament_name)
 
     # Colour: validate as 6- or 8-char hex; fall back to neutral grey for invalid
     # values. An 8-char value already carries its alpha, so appending the opaque
@@ -487,14 +545,16 @@ def _map_spoolman_spool(spool: dict) -> MappedSpoolFields:
     #   2. filament.color_name (forward-compat — picks up the value if a
     #      future Spoolman release adds the field, or if an admin populated
     #      it via a custom extra-field they registered themselves)
-    #   3. subtype (synth fallback so the inventory list isn't a sea of
+    #   3. the colour named in the filament's name ("Matte Scarlet Red" ->
+    #      "Scarlet Red", #3561). The user wrote it, so it counts as set.
+    #   4. subtype (synth fallback so the inventory list isn't a sea of
     #      "Unknown color" entries on installs with neither field set)
     #
     # color_name_is_synthesized = True only when we fell back to subtype.
     # The edit form uses it to leave the input blank, so the user doesn't
     # round-trip the synth value back as if they had set it.
     extra_color_name = _extract_extra_str(extra, "bambu_color_name") or None
-    stored_color_name = extra_color_name or (filament.get("color_name") or None)
+    stored_color_name = extra_color_name or (filament.get("color_name") or None) or name_color
     color_name: str | None = stored_color_name or subtype or None
     color_name_is_synthesized: bool = stored_color_name is None and color_name is not None
 

+ 38 - 5
backend/app/api/routes/archives.py

@@ -386,13 +386,18 @@ def compute_time_accuracy(archive: PrintArchive, run_aggregate: dict | None = No
     return result
 
 
+def _rounded(value, digits: int) -> float | None:
+    return None if value is None else round(float(value), digits)
+
+
 async def _load_run_aggregates(
     db: AsyncSession, archive_ids: list[int], printer_scope: PrinterScope | None = None, printer_id: int | None = None
 ) -> dict[int, dict]:
     """Batch-load per-archive run aggregates from PrintLogEntry.
 
     Returns ``{archive_id: {run_count, last_run_at, total_filament_actual_grams,
-    successful_run_count, failed_run_count, unmeasured_run_count, latest_run_id}}``. Archives with no logged runs are
+    successful_run_count, failed_run_count, unmeasured_run_count, total_cost,
+    total_energy_kwh, total_energy_cost, total_wear_cost, latest_run_id}}``. Archives with no logged runs are
     absent from the map; callers should treat that as zero/none.
 
     With ``printer_scope``, only the runs on its printers count: a caller
@@ -413,6 +418,11 @@ async def _load_run_aggregates(
             func.sum(case((PrintLogEntry.status == "completed", 1), else_=0)).label("successful"),
             func.sum(case((PrintLogEntry.status.in_(("failed", "aborted")), 1), else_=0)).label("failed"),
             func.sum(case((PrintLogEntry.duration_unmeasured.is_(True), 1), else_=0)).label("estimated"),
+            # NULL when no run has the figure (no plug, no price): unknown, not 0.
+            func.sum(PrintLogEntry.cost).label("total_cost"),
+            func.sum(PrintLogEntry.energy_kwh).label("total_energy_kwh"),
+            func.sum(PrintLogEntry.energy_cost).label("total_energy_cost"),
+            func.sum(PrintLogEntry.wear_cost).label("total_wear_cost"),
         )
         .where(
             PrintLogEntry.archive_id.in_(archive_ids),
@@ -426,7 +436,19 @@ async def _load_run_aggregates(
         .group_by(PrintLogEntry.archive_id)
     )
     aggregates: dict[int, dict] = {}
-    for archive_id, run_count, last_run_at, total_filament, successful, failed, estimated in rows.all():
+    for (
+        archive_id,
+        run_count,
+        last_run_at,
+        total_filament,
+        successful,
+        failed,
+        estimated,
+        total_cost,
+        total_energy_kwh,
+        total_energy_cost,
+        total_wear_cost,
+    ) in rows.all():
         aggregates[archive_id] = {
             "run_count": int(run_count or 0),
             "last_run_at": last_run_at,
@@ -434,6 +456,11 @@ async def _load_run_aggregates(
             "successful_run_count": int(successful or 0),
             "failed_run_count": int(failed or 0),
             "unmeasured_run_count": int(estimated or 0),
+            # What all its prints cost, as Statistics adds it up (#3609).
+            "total_cost": _rounded(total_cost, 2),
+            "total_energy_kwh": _rounded(total_energy_kwh, 3),
+            "total_energy_cost": _rounded(total_energy_cost, 3),
+            "total_wear_cost": _rounded(total_wear_cost, 2),
         }
     # The latest print of each (by start), which the archive shows: a print
     # running now included, as the archive shows it while it runs.
@@ -637,6 +664,8 @@ def archive_to_response(
         data["successful_run_count"] = run_aggregate.get("successful_run_count", 0)
         data["failed_run_count"] = run_aggregate.get("failed_run_count", 0)
         data["latest_run_id"] = run_aggregate.get("latest_run_id")
+        for key in ("total_cost", "total_energy_kwh", "total_energy_cost", "total_wear_cost"):
+            data[key] = run_aggregate.get(key)
 
     return data
 
@@ -1942,6 +1971,7 @@ async def _sum_live_plug_totals(db: AsyncSession) -> float:
     from backend.app.models.smart_plug import SmartPlug
     from backend.app.services.homeassistant import homeassistant_service
     from backend.app.services.mqtt_relay import mqtt_relay
+    from backend.app.services.plug_energy import mqtt_has_lifetime_counter
     from backend.app.services.rest_smart_plug import rest_smart_plug_service
     from backend.app.services.tasmota import tasmota_service
 
@@ -1962,10 +1992,13 @@ async def _sum_live_plug_totals(db: AsyncSession) -> float:
             if energy and energy.get("total") is not None:
                 total += energy["total"]
         elif plug.plug_type == "mqtt":
-            # MQTT plugs only expose today's counter, not lifetime.
+            # The lifetime counter when the plug has one (#3582), else its one
+            # energy value, as before.
             mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
-            if mqtt_data and mqtt_data.energy is not None:
-                total += mqtt_data.energy
+            if mqtt_data:
+                value = mqtt_data.energy_total if mqtt_has_lifetime_counter(plug) else mqtt_data.energy
+                if value is not None:
+                    total += value
         elif plug.plug_type == "rest":
             # A REST device that exposes only a lifetime counter (Shelly
             # ``aenergy.total`` via ``rest_energy_total_path``) returns no

+ 2 - 0
backend/app/api/routes/auth.py

@@ -1491,6 +1491,7 @@ async def _provision_ldap_user(db: AsyncSession, ldap_user, ldap_config) -> User
     if mapped_group_names:
         groups_result = await db.execute(select(Group).where(Group.name.in_(mapped_group_names)))
         new_user.groups = list(groups_result.scalars().all())
+    new_user.sync_role_to_groups()
 
     db.add(new_user)
     await db.flush()
@@ -1556,6 +1557,7 @@ async def _sync_ldap_user(db: AsyncSession, user: User, ldap_user, ldap_config)
     groups_changed = current_group_ids != new_group_ids
     if groups_changed:
         user.groups = new_groups
+        user.sync_role_to_groups()
         changed = True
 
     if changed:

+ 41 - 3
backend/app/api/routes/cloud.py

@@ -1312,6 +1312,40 @@ def _load_fields(preset_type: str) -> dict:
     return data
 
 
+def _with_slicer_material_types(data: dict, preferred_slicer: str | None) -> dict:
+    """The filament field definitions with the Material type dropdown of the preferred slicer (#2928).
+
+    The two slicers do not accept the same ``filament_type`` values (Orca has
+    SBS, Bambu Studio has TPU-AMS), so a profile made here starts from what the
+    slicer the user picked understands. A preferred slicer that is not set
+    counts as Bambu Studio, as everywhere else; one that is not known leaves the
+    list as the field file has it. Only this dropdown changes, and a profile's
+    own ``filament_type`` is never rewritten (the editor adds the value a profile
+    already has when it is not in the list).
+    """
+    if "slicer_filament_types" not in _fields_cache:
+        with open(FIELDS_DATA_DIR / "slicer_filament_types.json", encoding="utf-8") as f:
+            _fields_cache["slicer_filament_types"] = json.load(f)
+    entry = _fields_cache["slicer_filament_types"].get(preferred_slicer or "bambu_studio")
+    if not isinstance(entry, dict):
+        return data
+    options = [{"value": value, "label": value} for value in entry["values"]]
+    fields = [
+        {**field, "options": options} if field.get("key") == "filament_type" else field
+        for field in data.get("fields", [])
+    ]
+    return {**data, "fields": fields}
+
+
+async def _preset_fields(db: AsyncSession, preset_type: str) -> dict:
+    from backend.app.api.routes.settings import get_setting
+
+    data = _load_fields(preset_type)
+    if preset_type != "filament":
+        return data
+    return _with_slicer_material_types(data, await get_setting(db, "preferred_slicer"))
+
+
 @router.get("/builtin-filaments")
 async def get_builtin_filaments(
     _: User | None = RequirePermissionIfAuthEnabled(Permission.FILAMENTS_READ),
@@ -1424,11 +1458,15 @@ async def _build_filament_id_map(user: User | None, account: int | None) -> dict
 @router.get("/fields/{preset_type}")
 async def get_preset_fields(
     preset_type: Literal["filament", "print", "process", "printer"],
+    db: AsyncSession = Depends(get_db, scope="function"),
     _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
 ):
     """
     Get field definitions for a preset type.
 
+    For ``filament`` the Material type options are those of the preferred
+    slicer (Settings → Slicer): Bambu Studio's or OrcaSlicer's.
+
     Returns a list of field definitions including:
     - key: The setting key name
     - label: Human-readable label
@@ -1439,12 +1477,12 @@ async def get_preset_fields(
     - unit: Unit of measurement (if applicable)
     - min/max/step: For number fields, validation constraints
     """
-    data = _load_fields(preset_type)
-    return data
+    return await _preset_fields(db, preset_type)
 
 
 @router.get("/fields")
 async def get_all_preset_fields(
+    db: AsyncSession = Depends(get_db, scope="function"),
     _: User | None = RequirePermissionIfAuthEnabled(Permission.CLOUD_AUTH),
 ):
     """
@@ -1453,7 +1491,7 @@ async def get_all_preset_fields(
     Returns field definitions organized by type.
     """
     return {
-        "filament": _load_fields("filament"),
+        "filament": await _preset_fields(db, "filament"),
         "process": _load_fields("process"),
         "printer": _load_fields("printer"),
     }

+ 15 - 1
backend/app/api/routes/groups.py

@@ -16,7 +16,7 @@ from backend.app.core.printer_scope import group_location_names, group_printer_i
 from backend.app.core.websocket import ws_manager
 from backend.app.models.group import Group, group_locations, group_printers
 from backend.app.models.printer import Printer
-from backend.app.models.user import User
+from backend.app.models.user import ADMIN_GROUP_NAME, User
 from backend.app.schemas.group import (
     GroupCreate,
     GroupDetailResponse,
@@ -407,6 +407,9 @@ async def add_user_to_group(
         )
 
     group.users.append(user)
+    # The legacy role follows Administrators membership (#3533).
+    if group.name == ADMIN_GROUP_NAME:
+        user.role = "admin"
     await db.commit()
     await ws_manager.refresh_printer_scopes()
 
@@ -445,6 +448,17 @@ async def remove_user_from_group(
             detail="User is not in this group",
         )
 
+    if group.name == ADMIN_GROUP_NAME:
+        # Leaving Administrators takes the admin rights with it, so the role
+        # follows (#3533) -- unless that leaves no active admin.
+        from backend.app.api.routes.users import _other_active_admins
+
+        if user.is_active and not await _other_active_admins(db, user.id):
+            raise HTTPException(
+                status_code=status.HTTP_400_BAD_REQUEST,
+                detail="Cannot remove admin rights from the last admin user",
+            )
+        user.role = "user"
     group.users.remove(user)
     await db.commit()
     # They may lose printers, or websocket:connect itself

+ 87 - 26
backend/app/api/routes/inventory.py

@@ -7,12 +7,14 @@ import httpx
 from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
 from fastapi.responses import Response, StreamingResponse
 from pydantic import BaseModel, Field, field_validator
-from sqlalchemy import case, delete, func, select
+from sqlalchemy import case, delete, func, select, text
 from sqlalchemy.exc import IntegrityError
 from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.orm import selectinload
 
 from backend.app.core.auth import (
+    ApiKeyActor,
+    RequestActor,
     RequestPrinterScope,
     RequireAnyPermissionIfAuthEnabled,
     RequirePermissionIfAuthEnabled,
@@ -20,7 +22,7 @@ from backend.app.core.auth import (
     require_auth_if_enabled,
 )
 from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG, DEFAULT_SPOOL_CATALOG
-from backend.app.core.database import get_db
+from backend.app.core.database import get_db, is_sqlite
 from backend.app.core.permissions import Permission
 from backend.app.core.printer_scope import PrinterScope
 from backend.app.core.websocket import ws_manager
@@ -89,6 +91,7 @@ from backend.app.services.spool_csv import (
     MAX_CSV_IMPORT_BYTES,
     ImportPreview,
     ImportResult,
+    ImportRowResult,
     parse_and_validate,
     serialize,
 )
@@ -102,7 +105,7 @@ from backend.app.utils.filament_ids import (
     filament_id_to_setting_id,
     normalize_slicer_filament,
 )
-from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type
+from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type, support_filament_type
 from backend.app.utils.local_time import day_zone, local_date_end, local_date_start
 from backend.app.utils.natural_sort import natural_sort_key
 from backend.app.utils.tag_normalization import normalize_tag_uid, normalize_tray_uuid
@@ -127,6 +130,23 @@ def spool_response_loads():
     )
 
 
+async def load_preset_lookup_user(db: AsyncSession, user_id: int | None) -> User | None:
+    """The user whose cloud sign-in resolves a spool's preset, by id (#3519).
+
+    For callers that have no signed-in user of their own: an API key (its
+    owner) and the replay on insert (whoever made the assignment). Without
+    one, a custom cloud preset (PFUS/PFCN) can't be looked up when each user
+    signs in to the cloud separately, and the slot gets a generic filament.
+    None for no id or a deactivated user. Groups are loaded because the
+    resolver asks the user for permissions.
+    """
+    if user_id is None:
+        return None
+    result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
+    user = result.scalar_one_or_none()
+    return user if user is not None and user.is_active else None
+
+
 # Bounded read size for the CSV import body so a chunked upload with no
 # Content-Length can't stream past the cap into memory before we notice.
 _CSV_UPLOAD_CHUNK_BYTES = 64 * 1024
@@ -220,6 +240,9 @@ async def apply_spool_to_slot_via_mqtt(
     # the spool has a preset, its answer wins (issue #2902, @doncaruana).
     if type_override:
         tray_type = printer_filament_type(type_override)
+    # A support material keeps the slicer's suffix ("PLA-S"), which neither the
+    # material column nor most presets' type carries (#3559).
+    tray_type = support_filament_type(tray_type, tray_info_idx, f"{slot_slicer_filament_name or ''} {tray_sub_brands}")
 
     if not tray_info_idx:
         reused = reusable_slot_filament_id(
@@ -1475,6 +1498,22 @@ async def export_spools_csv(
     )
 
 
+async def _continue_spool_ids_after(db: AsyncSession, highest: int) -> None:
+    """Make the next new spool's id follow the ids an import kept (#3520).
+
+    The kept rows are flushed first. SQLite's AUTOINCREMENT then already
+    continues after them; a PostgreSQL sequence knows nothing of ids given
+    explicitly and would hand out one of them next. Only ever raised: every
+    kept id is above what the sequence has given out (``_decide_ids``).
+    """
+    await db.flush()
+    if is_sqlite():
+        return
+    sequence = (await db.execute(text("SELECT pg_get_serial_sequence('spool', 'id')"))).scalar()
+    if sequence:
+        await db.execute(text("SELECT setval(:s, :v)"), {"s": sequence, "v": highest})
+
+
 @router.post("/spools/import", response_model=ImportPreview | ImportResult)
 async def import_spools_csv(
     file: UploadFile = File(...),
@@ -1516,29 +1555,42 @@ async def import_spools_csv(
     if dry_run:
         return preview
 
-    created = 0
-    for row in preview.rows:
-        if row.status == "valid" and row.spool is not None:
-            # Deliberately no material-number inheritance here (#2870), unlike
-            # the other create paths: the file is authoritative. A CSV that
-            # leaves the column blank is stating "no number", not asking for
-            # one to be guessed from whatever else is in the inventory.
-            # The file has no lock column: a used weight in it is locked.
-            spool = Spool(**_lock_entered_weight(dict(row.spool), set()))
-            db.add(spool)
-            # Supplier assignments resolved by name during parsing (#2988).
-            # Flush first so the spool has an id to hang the links on.
-            if row.supplier_ids:
-                await db.flush()
-                for supplier_id in row.supplier_ids:
-                    db.add(
-                        SpoolSupplier(
-                            spool_id=spool.id,
-                            supplier_id=supplier_id,
-                            is_purchase_source=supplier_id == row.purchase_supplier_id,
-                        )
+    async def add_spool(row: ImportRowResult) -> None:
+        # Deliberately no material-number inheritance here (#2870), unlike
+        # the other create paths: the file is authoritative. A CSV that
+        # leaves the column blank is stating "no number", not asking for
+        # one to be guessed from whatever else is in the inventory.
+        # The file has no lock column: a used weight in it is locked.
+        spool = Spool(**_lock_entered_weight(dict(row.spool or {}), set()))
+        if row.keeps_id is not None:
+            spool.id = row.keeps_id
+        db.add(spool)
+        # Supplier assignments resolved by name during parsing (#2988).
+        # Flush first so the spool has an id to hang the links on.
+        if row.supplier_ids:
+            await db.flush()
+            for supplier_id in row.supplier_ids:
+                db.add(
+                    SpoolSupplier(
+                        spool_id=spool.id,
+                        supplier_id=supplier_id,
+                        is_purchase_source=supplier_id == row.purchase_supplier_id,
                     )
-            created += 1
+                )
+
+    valid_rows = [row for row in preview.rows if row.status == "valid" and row.spool is not None]
+    # Rows keeping their id go in first (#3520): a row without one takes the
+    # next free id, which could be one a later row in the file still needs.
+    kept_ids = [row.keeps_id for row in valid_rows if row.keeps_id is not None]
+    for row in valid_rows:
+        if row.keeps_id is not None:
+            await add_spool(row)
+    if kept_ids:
+        await _continue_spool_ids_after(db, max(kept_ids))
+    for row in valid_rows:
+        if row.keeps_id is None:
+            await add_spool(row)
+    created = len(valid_rows)
 
     if created:
         await db.commit()
@@ -2427,12 +2479,20 @@ async def assign_spool(
     db: AsyncSession = Depends(get_db, scope="function"),
     current_user: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_UPDATE),
     printer_scope: PrinterScope = RequestPrinterScope,
+    actor: User | ApiKeyActor | None = RequestActor,
 ):
     """Assign a spool to an AMS slot and auto-configure via MQTT."""
     from backend.app.services.printer_manager import printer_manager
 
     printer_scope.ensure(data.printer_id)
 
+    # An API key (a SpoolBuddy client) has no signed-in user, so its owner's
+    # cloud sign-in resolves a custom preset; without it the slot got Generic
+    # PLA where the web UI got the preset's own filament (#3519).
+    preset_user = current_user
+    if preset_user is None and isinstance(actor, ApiKeyActor):
+        preset_user = await load_preset_lookup_user(db, actor.id)
+
     # 1. Validate spool exists and is not archived
     result = await db.execute(select(Spool).options(*spool_response_loads()).where(Spool.id == data.spool_id))
     spool = result.scalar_one_or_none()
@@ -2555,6 +2615,7 @@ async def assign_spool(
                 tray_id=data.tray_id,
                 fingerprint_color=fingerprint_color,
                 fingerprint_type=fingerprint_type,
+                assigned_by_user_id=preset_user.id if preset_user is not None else None,
             )
             db.add(assignment)
             await spool_swaps.record_assignment(
@@ -2636,7 +2697,7 @@ async def assign_spool(
         try:
             configured = await apply_spool_to_slot_via_mqtt(
                 db=db,
-                current_user=current_user,
+                current_user=preset_user,
                 spool=spool,
                 printer_id=data.printer_id,
                 ams_id=data.ams_id,

+ 21 - 0
backend/app/api/routes/library.py

@@ -4569,6 +4569,9 @@ async def _run_slicer_with_fallback(
     # orthogonal so this decision doesn't interact with the #1337 build-
     # plate override.
     cross_class_arrange = False
+    # Also read by the embedded-settings fallback below (#3535).
+    source_model: str | None = None
+    target_model: str | None = None
     if is_3mf:
         from backend.app.services.slicer_3mf_convert import (
             extract_source_printer_model,
@@ -4819,6 +4822,20 @@ async def _run_slicer_with_fallback(
                 # user asked to slice as N, which reads as a Bambuddy bug
                 # rather than a slicer failure. Surface the error instead.
                 raise
+            if not source_model or source_model != target_model:
+                # The embedded settings are for the printer the file was
+                # sliced for. On any other target -- or when either side is
+                # unknown -- the fallback hands back G-code for the wrong
+                # printer as a completed slice (#3535). Surface the error.
+                logger.warning(
+                    "Slicer CLI failed on the --load-settings path for %s (%s); no fallback to embedded "
+                    "settings, which are for %s, not %s",
+                    model_filename,
+                    exc,
+                    source_model or "an unknown printer",
+                    target_model or "an unknown printer",
+                )
+                raise
             logger.warning(
                 "Slicer CLI failed on the --load-settings path for %s (%s); retrying with embedded settings",
                 model_filename,
@@ -5327,6 +5344,10 @@ async def slice_and_persist_as_archive(
     from backend.app.services.print_cost_estimate import refresh_plate_estimates
 
     refresh_plate_estimates(new_archive)
+    # Its G-code, so a print of this slice sent from the slicer joins it (#1634)
+    from backend.app.services.archive_gcode_hash import refresh_gcode_hash_async
+
+    await refresh_gcode_hash_async(new_archive)
     db.add(new_archive)
     await db.commit()
     await db.refresh(new_archive)

+ 223 - 6
backend/app/api/routes/maintenance.py

@@ -1,15 +1,19 @@
 """Maintenance tracking API routes."""
 
 import logging
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
+from typing import cast
 
-from fastapi import APIRouter, Depends, HTTPException
-from sqlalchemy import select
+from fastapi import APIRouter, Depends, HTTPException, Query, Response
+from sqlalchemy import delete, func, select
+from sqlalchemy.engine import CursorResult
 from sqlalchemy.exc import IntegrityError
 from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.orm import selectinload
 
 from backend.app.core.auth import (
+    ApiKeyActor,
+    RequestActor,
     RequestPrinterScope,
     RequirePermissionIfAuthEnabled,
     RequirePrinterPermissionIfAuthEnabled,
@@ -17,11 +21,18 @@ from backend.app.core.auth import (
 from backend.app.core.database import get_db
 from backend.app.core.permissions import Permission
 from backend.app.core.printer_scope import PrinterScope
-from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
+from backend.app.models.maintenance import (
+    MaintenanceHistory,
+    MaintenanceLogEntry,
+    MaintenanceType,
+    PrinterMaintenance,
+)
 from backend.app.models.printer import Printer
 from backend.app.models.user import User
 from backend.app.schemas.maintenance import (
     MaintenanceHistoryResponse,
+    MaintenanceLogEntryResponse,
+    MaintenanceLogPage,
     MaintenanceStatus,
     MaintenanceTypeCreate,
     MaintenanceTypeResponse,
@@ -31,7 +42,10 @@ from backend.app.schemas.maintenance import (
     PrinterMaintenanceResponse,
     PrinterMaintenanceUpdate,
 )
+from backend.app.services.export import ExportService
 from backend.app.services.notification_service import notification_service
+from backend.app.utils.http import build_content_disposition
+from backend.app.utils.local_time import utcnow_naive
 from backend.app.utils.printer_models import get_rod_type, normalize_printer_model_id
 
 logger = logging.getLogger(__name__)
@@ -820,8 +834,9 @@ async def perform_maintenance(
     db: AsyncSession = Depends(get_db, scope="function"),
     _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
     printer_scope: PrinterScope = RequestPrinterScope,
+    actor: User | ApiKeyActor | None = RequestActor,
 ):
-    """Mark maintenance as performed (reset the counter)."""
+    """Mark maintenance as performed (reset the counter) and log it."""
     result = await db.execute(
         select(PrinterMaintenance)
         .where(PrinterMaintenance.id == item_id)
@@ -838,16 +853,39 @@ async def perform_maintenance(
     # Get current hours
     current_hours = await get_printer_total_hours(db, item.printer_id)
 
+    now_utc = datetime.now(timezone.utc)
+    # Stored naive, as UTC, like every other time in the database.
+    now = now_utc.replace(tzinfo=None)
+
     # Create history entry
     history = MaintenanceHistory(
         printer_maintenance_id=item.id,
+        performed_at=now,
         hours_at_maintenance=current_hours,
         notes=data.notes,
     )
     db.add(history)
+    await db.flush()
+
+    # The audit log entry, which outlives the printer, the task and the user.
+    performed_by_id, performed_by_username = _actor_identity(actor)
+    db.add(
+        MaintenanceLogEntry(
+            printer_id=printer.id,
+            printer_name=printer.name,
+            maintenance_type_id=item.maintenance_type_id,
+            maintenance_type_name=item.maintenance_type.name,
+            hours_at_maintenance=current_hours,
+            notes=data.notes,
+            performed_by_id=performed_by_id,
+            performed_by_username=performed_by_username,
+            performed_at=now,
+            history_id=history.id,
+        )
+    )
 
     # Update item
-    item.last_performed_at = datetime.now(timezone.utc)
+    item.last_performed_at = now_utc
     item.last_performed_hours = current_hours
 
     await db.commit()
@@ -915,6 +953,185 @@ async def get_maintenance_history(
     return result.scalars().all()
 
 
+# ============== Maintenance Log ==============
+
+
+def _actor_identity(actor: User | ApiKeyActor | None) -> tuple[int | None, str | None]:
+    """Who to log a reset as: the user, an API key's owner, or a legacy key by its name.
+
+    Nobody (None, None) when authentication is off. An ``ApiKeyActor`` has its
+    owner's id and username, both None for a key without an owner.
+    """
+    if actor is None:
+        return None, None
+    if isinstance(actor, ApiKeyActor) and actor.username is None:
+        return None, f"API key: {actor.api_key.name}"[:100]
+    return actor.id, actor.username
+
+
+_NEWEST_FIRST = (MaintenanceLogEntry.performed_at.desc(), MaintenanceLogEntry.id.desc())
+
+
+async def _ensure_printer(db: AsyncSession, printer_id: int) -> Printer:
+    printer = await db.get(Printer, printer_id)
+    if printer is None:
+        raise HTTPException(status_code=404, detail="Printer not found")
+    return printer
+
+
+@router.get("/printers/{printer_id}/log", response_model=MaintenanceLogPage)
+async def get_printer_maintenance_log(
+    printer_id: int,
+    limit: int = Query(50, ge=1, le=500),
+    offset: int = Query(0, ge=0),
+    db: AsyncSession = Depends(get_db, scope="function"),
+    _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
+):
+    """A printer's maintenance log, newest first."""
+    await _ensure_printer(db, printer_id)
+    where = MaintenanceLogEntry.printer_id == printer_id
+    total = await db.scalar(select(func.count()).select_from(MaintenanceLogEntry).where(where)) or 0
+    result = await db.execute(
+        select(MaintenanceLogEntry).where(where).order_by(*_NEWEST_FIRST).limit(limit).offset(offset)
+    )
+    items = [MaintenanceLogEntryResponse.model_validate(entry) for entry in result.scalars().all()]
+    return MaintenanceLogPage(items=items, total=total)
+
+
+def _csv_response(file_bytes: bytes, filename: str) -> Response:
+    return Response(
+        content=file_bytes,
+        media_type="text/csv; charset=utf-8",
+        headers={"Content-Disposition": build_content_disposition(filename)},
+    )
+
+
+@router.get("/printers/{printer_id}/log/export")
+async def export_printer_maintenance_log(
+    printer_id: int,
+    db: AsyncSession = Depends(get_db, scope="function"),
+    _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
+):
+    """A printer's maintenance log as CSV."""
+    printer = await _ensure_printer(db, printer_id)
+    result = await db.execute(
+        select(MaintenanceLogEntry).where(MaintenanceLogEntry.printer_id == printer_id).order_by(*_NEWEST_FIRST)
+    )
+    file_bytes, filename = ExportService.export_maintenance_log(result.scalars().all(), printer.name)
+    return _csv_response(file_bytes, filename)
+
+
+@router.get("/log/export")
+async def export_maintenance_log(
+    db: AsyncSession = Depends(get_db, scope="function"),
+    _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
+    printer_scope: PrinterScope = RequestPrinterScope,
+):
+    """The maintenance log of every printer the caller may see, as CSV.
+
+    Entries of deleted printers are in it only for callers who see every
+    printer: a printer-scoped caller can't tell whose they were.
+    """
+    query = select(MaintenanceLogEntry).order_by(*_NEWEST_FIRST)
+    if (in_scope := printer_scope.where_strict(MaintenanceLogEntry.printer_id)) is not None:
+        query = query.where(in_scope)
+    result = await db.execute(query)
+    file_bytes, filename = ExportService.export_maintenance_log(result.scalars().all(), "all")
+    return _csv_response(file_bytes, filename)
+
+
+# A cleanup keeps at least the last day: no age can empty the log by accident.
+_OLDER_THAN_DAYS = Query(ge=1, le=36500, description="Delete the entries older than this many days")
+
+
+def _older_than(days: int):
+    # performed_at is naive UTC, like every timestamp the app writes.
+    return MaintenanceLogEntry.performed_at < utcnow_naive() - timedelta(days=days)
+
+
+async def _delete_log_entries(db: AsyncSession, *conditions) -> int:
+    """Delete the log entries matching ``conditions``, and the history rows of the same resets.
+
+    Each reset is written to maintenance_history too, comment included; left
+    there, a deleted entry would still be in the database and its backups.
+    """
+    # Read first: on SQLite the history delete clears the entries' history_id
+    # before it runs (sqlite_fk), and a subquery would then find nothing.
+    copied_from = list(
+        await db.scalars(
+            select(MaintenanceLogEntry.history_id).where(*conditions, MaintenanceLogEntry.history_id.is_not(None))
+        )
+    )
+    # In chunks: a fleet cleanup may match more ids than one statement can bind.
+    for start in range(0, len(copied_from), 500):
+        chunk = copied_from[start : start + 500]
+        await db.execute(delete(MaintenanceHistory).where(MaintenanceHistory.id.in_(chunk)))
+    result = cast(CursorResult, await db.execute(delete(MaintenanceLogEntry).where(*conditions)))
+    await db.commit()
+    return result.rowcount
+
+
+@router.delete("/printers/{printer_id}/log")
+async def clean_up_printer_maintenance_log(
+    printer_id: int,
+    older_than_days: int = _OLDER_THAN_DAYS,
+    db: AsyncSession = Depends(get_db, scope="function"),
+    _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
+):
+    """Delete a printer's maintenance log entries older than ``older_than_days``."""
+    await _ensure_printer(db, printer_id)
+    deleted = await _delete_log_entries(db, MaintenanceLogEntry.printer_id == printer_id, _older_than(older_than_days))
+    logger.info(
+        "Deleted %d maintenance log entries of printer %d older than %d days", deleted, printer_id, older_than_days
+    )
+    return {"deleted": deleted}
+
+
+@router.delete("/log")
+async def clean_up_maintenance_log(
+    older_than_days: int = _OLDER_THAN_DAYS,
+    db: AsyncSession = Depends(get_db, scope="function"),
+    _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
+    printer_scope: PrinterScope = RequestPrinterScope,
+):
+    """Delete the maintenance log entries older than ``older_than_days`` of every
+    printer the caller may see.
+
+    Entries of deleted printers go too, but only for callers who see every
+    printer, as in the export.
+    """
+    conditions = [_older_than(older_than_days)]
+    if (in_scope := printer_scope.where_strict(MaintenanceLogEntry.printer_id)) is not None:
+        conditions.append(in_scope)
+    deleted = await _delete_log_entries(db, *conditions)
+    logger.info("Deleted %d maintenance log entries older than %d days", deleted, older_than_days)
+    return {"deleted": deleted}
+
+
+@router.delete("/log/{entry_id}")
+async def delete_maintenance_log_entry(
+    entry_id: int,
+    db: AsyncSession = Depends(get_db, scope="function"),
+    _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
+    printer_scope: PrinterScope = RequestPrinterScope,
+):
+    """Delete one maintenance log entry, e.g. of a task reset by mistake.
+
+    The task's last reset stays as it is: deleting the entry does not undo it.
+    """
+    entry = await db.get(MaintenanceLogEntry, entry_id)
+    # An entry of a deleted printer is reachable only by a caller who sees
+    # every printer; ``allows`` alone lets any caller at rows with no printer.
+    out_of_scope = entry is not None and (
+        not printer_scope.allows(entry.printer_id) or (entry.printer_id is None and not printer_scope.is_unrestricted)
+    )
+    if entry is None or out_of_scope:
+        raise HTTPException(status_code=404, detail="Maintenance log entry not found")
+    await _delete_log_entries(db, MaintenanceLogEntry.id == entry_id)
+    logger.info("Maintenance log entry %d deleted", entry_id)
+    return {"status": "deleted", "id": entry_id}
+
+
 @router.get("/summary")
 async def get_maintenance_summary(
     db: AsyncSession = Depends(get_db, scope="function"),

+ 1 - 0
backend/app/api/routes/mfa.py

@@ -2102,6 +2102,7 @@ async def oidc_callback(
                         is_active=True,
                         groups=[default_group] if default_group else [],
                     )
+                    new_user.sync_role_to_groups()
                     db.add(new_user)
                     await db.flush()
 

+ 7 - 1
backend/app/api/routes/printers.py

@@ -115,7 +115,7 @@ from backend.app.utils.filament_ids import (
     filament_id_to_setting_id,
     setting_id_to_filament_id,
 )
-from backend.app.utils.filament_types import is_material_name, printer_filament_type
+from backend.app.utils.filament_types import is_material_name, printer_filament_type, support_filament_type
 from backend.app.utils.fts_routing import slot_extruder
 from backend.app.utils.http import build_content_disposition, download_error_response, safe_download_filename
 from backend.app.utils.kprofile_lookup import build_slot_k_resolver
@@ -3065,6 +3065,12 @@ async def configure_ams_slot(
         logger.info("[configure_ams_slot] tray_info_idx %r is a setting id → %r", tray_info_idx, converted)
         setting_id = setting_id or tray_info_idx
         tray_info_idx = converted
+    # A support preset arrives as plain "PLA" -- the dialog reads the type off
+    # the preset name -- where the slicer writes "PLA-S" (#3559).
+    support_type = support_filament_type(tray_type, tray_info_idx, tray_sub_brands)
+    if support_type != tray_type:
+        logger.info("[configure_ams_slot] support filament: tray_type %r → %r", tray_type, support_type)
+        tray_type = support_type
     # The K profile's filament id: it becomes the slot's when they differ
     # (the realignment below), and the printer's calibration table is keyed
     # by filament ids as well.

+ 123 - 80
backend/app/api/routes/settings.py

@@ -1,3 +1,4 @@
+import asyncio
 import io
 import json
 import logging
@@ -913,6 +914,120 @@ async def get_homeassistant_settings(db: AsyncSession) -> dict:
     }
 
 
+# The file steps of a backup and a restore run in a worker thread. On the
+# event loop they froze the whole server for as long as they took -- no page,
+# no websocket, no printer message -- and with a large archive folder that was
+# over half a minute, long enough for the loop watchdog to dump every thread.
+
+
+def _copy_backup_dirs(dirs_to_backup: list[tuple[str, Path]], temp_path: Path) -> None:
+    """Copy each data directory that has anything in it into the backup folder."""
+    import shutil
+
+    for name, src_dir in dirs_to_backup:
+        if src_dir.exists() and any(src_dir.iterdir()):
+            try:
+                shutil.copytree(
+                    src_dir, temp_path / name
+                )  # SEC-PATH-OK: name iterates the dirs_to_backup tuple of constant strings ("archive", "virtual_printer", ...)
+            except shutil.Error as e:
+                logger.warning("Some files in %s could not be copied: %s", name, e)
+            except PermissionError as e:
+                logger.warning("Permission denied copying %s: %s", name, e)
+
+
+def _write_backup_zip(temp_path: Path, zip_file: Path) -> None:
+    """Zip every file under temp_path into zip_file, paths relative to temp_path."""
+    with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
+        for file_path in temp_path.rglob("*"):
+            if file_path.is_file():
+                arcname = file_path.relative_to(temp_path)
+                zf.write(file_path, arcname)
+
+
+def _extract_backup_zip(content: bytes, temp_path: Path) -> None:
+    """Extract a backup ZIP into temp_path, refusing any entry that escapes it.
+
+    Raises HTTPException(400) for an unsafe path or a file that is not a ZIP.
+    """
+    from fastapi import HTTPException
+
+    try:
+        with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
+            for name in zf.namelist():
+                # Reject path-traversal payloads: any entry whose resolved
+                # path escapes temp_path would allow writing arbitrary files
+                # on the host (ZipSlip / CVE-2006-5456).
+                dest = (
+                    temp_path / name
+                ).resolve()  # SEC-PATH-OK: is_relative_to containment check below before extractall
+                # is_relative_to (Python 3.9+) covers both relative
+                # path-traversal (../etc/passwd) and absolute-path overrides
+                # (/etc/passwd) — str.startswith was vulnerable to
+                # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
+                # a /tmp/abc prefix check).
+                if not dest.is_relative_to(temp_path.resolve()):
+                    raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
+            zf.extractall(temp_path)
+    except zipfile.BadZipFile:
+        raise HTTPException(400, "Invalid backup file: not a valid ZIP")
+
+
+def _restore_data_dirs(dirs_to_restore: list[tuple[str, Path]], temp_path: Path) -> list[str]:
+    """Replace each data directory's contents with the backup's.
+
+    Clears the contents, not the directory itself, which may be a Docker
+    mount. Returns the names of the directories that could not be restored.
+    """
+    import shutil
+
+    skipped_dirs = []
+    for name, dest_dir in dirs_to_restore:
+        src_dir = (
+            temp_path / name
+        )  # SEC-PATH-OK: name iterates the dirs_to_restore tuple of constant strings ("archive", "virtual_printer", ...)
+        if src_dir.exists():
+            logger.info("Restoring %s directory...", name)
+            try:
+                if dest_dir.exists():
+                    for item in dest_dir.iterdir():
+                        try:
+                            if item.is_dir():
+                                shutil.rmtree(item)
+                            else:
+                                item.unlink()
+                        except OSError as e:
+                            logger.warning("Could not delete %s: %s", item, e)
+                else:
+                    dest_dir.mkdir(parents=True, exist_ok=True)
+                # Copy contents from backup
+                for item in src_dir.iterdir():
+                    dest_item = dest_dir / item.name
+                    if item.is_dir():
+                        shutil.copytree(item, dest_item)
+                    else:
+                        shutil.copy2(item, dest_item)
+            except OSError as e:
+                logger.warning("Could not restore %s directory: %s", name, e)
+                skipped_dirs.append(name)
+    return skipped_dirs
+
+
+def _restore_sqlite_db(backup_db: Path, db_path: Path) -> None:
+    """Copy the backup into the live SQLite database with the online backup API."""
+    import sqlite3
+
+    src_conn = sqlite3.connect(str(backup_db))
+    try:
+        dst_conn = sqlite3.connect(str(db_path))
+        try:
+            src_conn.backup(dst_conn)
+        finally:
+            dst_conn.close()
+    finally:
+        src_conn.close()
+
+
 async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
     """Create a complete backup ZIP (database + all data directories).
 
@@ -942,8 +1057,9 @@ async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]
             async with engine.begin() as conn:
                 await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
 
-            # Copy database file
-            shutil.copy2(db_path, temp_path / "bambuddy.db")
+            # Copy database file. Off the event loop, like every file step
+            # below: a large file blocked the whole server while it copied.
+            await asyncio.to_thread(shutil.copy2, db_path, temp_path / "bambuddy.db")
         else:
             # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
             # This makes backups restorable on both SQLite and Postgres installs.
@@ -1007,16 +1123,7 @@ async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]
             ("overlay-branding", base_dir / "overlay-branding"),
         ]
 
-        for name, src_dir in dirs_to_backup:
-            if src_dir.exists() and any(src_dir.iterdir()):
-                try:
-                    shutil.copytree(
-                        src_dir, temp_path / name
-                    )  # SEC-PATH-OK: name iterates the dirs_to_backup tuple of constant strings ("archive", "virtual_printer", ...)
-                except shutil.Error as e:
-                    logger.warning("Some files in %s could not be copied: %s", name, e)
-                except PermissionError as e:
-                    logger.warning("Permission denied copying %s: %s", name, e)
+        await asyncio.to_thread(_copy_backup_dirs, dirs_to_backup, temp_path)
 
         # Say which version made this, so a restore that cannot import it can
         # name the versions rather than a list of columns. Backups from before
@@ -1060,11 +1167,7 @@ async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]
             os.close(fd)
             zip_file = Path(tmp)
 
-        with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
-            for file_path in temp_path.rglob("*"):
-                if file_path.is_file():
-                    arcname = file_path.relative_to(temp_path)
-                    zf.write(file_path, arcname)
+        await asyncio.to_thread(_write_backup_zip, temp_path, zip_file)
 
     return zip_file, filename
 
@@ -1519,7 +1622,6 @@ async def restore_backup(
     Replaces the database and all data directories from the backup ZIP.
     Requires a restart after restore.
     """
-    import shutil
     import tempfile
 
     from fastapi import HTTPException
@@ -1540,25 +1642,7 @@ async def restore_backup(
         if not file.filename or not file.filename.endswith(".zip"):
             raise HTTPException(400, "Invalid backup file: must be a .zip file")
 
-        try:
-            with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
-                for name in zf.namelist():
-                    # Reject path-traversal payloads: any entry whose resolved
-                    # path escapes temp_path would allow writing arbitrary files
-                    # on the host (ZipSlip / CVE-2006-5456).
-                    dest = (
-                        temp_path / name
-                    ).resolve()  # SEC-PATH-OK: is_relative_to containment check below before extractall
-                    # is_relative_to (Python 3.9+) covers both relative
-                    # path-traversal (../etc/passwd) and absolute-path overrides
-                    # (/etc/passwd) — str.startswith was vulnerable to
-                    # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
-                    # a /tmp/abc prefix check).
-                    if not dest.is_relative_to(temp_path.resolve()):
-                        raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
-                zf.extractall(temp_path)
-        except zipfile.BadZipFile:
-            raise HTTPException(400, "Invalid backup file: not a valid ZIP")
+        await asyncio.to_thread(_extract_backup_zip, content, temp_path)
 
         # 2. Validate backup
         backup_db = temp_path / "bambuddy.db"
@@ -1590,8 +1674,6 @@ async def restore_backup(
                 raise HTTPException(400, f"Invalid backup: bambuddy.db is not readable ({exc})") from exc
 
         try:
-            import asyncio
-
             # 3. Stop the virtual printers if running (releases file locks).
             # stop_all, not the legacy configure(): that ignores its arguments
             # and re-syncs from the database not yet replaced, so their FTP,
@@ -1710,17 +1792,7 @@ async def restore_backup(
                 # own WAL — so concurrent open sessions see their own
                 # snapshot until they close (transaction isolation) but
                 # can't corrupt the restored state.
-                import sqlite3
-
-                src_conn = sqlite3.connect(str(backup_db))
-                try:
-                    dst_conn = sqlite3.connect(str(db_path))
-                    try:
-                        src_conn.backup(dst_conn)
-                    finally:
-                        dst_conn.close()
-                finally:
-                    src_conn.close()
+                await asyncio.to_thread(_restore_sqlite_db, backup_db, db_path)
             else:
                 # Import SQLite backup into PostgreSQL
                 logger.info("Importing SQLite backup into PostgreSQL...")
@@ -1737,36 +1809,7 @@ async def restore_backup(
                 ("overlay-branding", base_dir / "overlay-branding"),
             ]
 
-            skipped_dirs = []
-            for name, dest_dir in dirs_to_restore:
-                src_dir = (
-                    temp_path / name
-                )  # SEC-PATH-OK: name iterates the dirs_to_restore tuple of constant strings ("archive", "virtual_printer", ...)
-                if src_dir.exists():
-                    logger.info("Restoring %s directory...", name)
-                    try:
-                        # Clear destination contents (not the dir itself - may be Docker mount)
-                        if dest_dir.exists():
-                            for item in dest_dir.iterdir():
-                                try:
-                                    if item.is_dir():
-                                        shutil.rmtree(item)
-                                    else:
-                                        item.unlink()
-                                except OSError as e:
-                                    logger.warning("Could not delete %s: %s", item, e)
-                        else:
-                            dest_dir.mkdir(parents=True, exist_ok=True)
-                        # Copy contents from backup
-                        for item in src_dir.iterdir():
-                            dest_item = dest_dir / item.name
-                            if item.is_dir():
-                                shutil.copytree(item, dest_item)
-                            else:
-                                shutil.copy2(item, dest_item)
-                    except OSError as e:
-                        logger.warning("Could not restore %s directory: %s", name, e)
-                        skipped_dirs.append(name)
+            skipped_dirs = await asyncio.to_thread(_restore_data_dirs, dirs_to_restore, temp_path)
 
             # 7. Reset the encryption singleton so the migration that runs
             # inside init_db() picks up the restored key file (if a new one

+ 19 - 3
backend/app/api/routes/smart_plugs.py

@@ -43,6 +43,7 @@ from backend.app.services.discovery import tasmota_scanner
 from backend.app.services.homeassistant import homeassistant_service
 from backend.app.services.mqtt_relay import mqtt_relay
 from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
+from backend.app.services.plug_energy import mqtt_has_lifetime_counter
 from backend.app.services.plug_energy_history import fill_derived_energy
 from backend.app.services.printer_manager import printer_manager
 from backend.app.services.rest_smart_plug import rest_smart_plug_service
@@ -55,7 +56,12 @@ from backend.app.services.secret_fields import (
     reject_placeholder,
     same_value,
 )
-from backend.app.services.smart_plug_manager import publish_plug_state, run_linked_scripts, smart_plug_manager
+from backend.app.services.smart_plug_manager import (
+    can_turn_off,
+    publish_plug_state,
+    run_linked_scripts,
+    smart_plug_manager,
+)
 from backend.app.services.tasmota import tasmota_service
 from backend.app.utils.local_time import utcnow_naive
 
@@ -218,7 +224,7 @@ def _can_be_switched(plug: SmartPlug) -> bool:
       is exactly the kind that reports watts, so without this it would win the
       power tiebreak below and take the row off a plug that can be switched.
     """
-    return not _is_script_plug(plug) and plug.plug_type != "mqtt"
+    return can_turn_off(plug)
 
 
 def _reports_power(plug: SmartPlug) -> bool:
@@ -675,6 +681,8 @@ async def update_smart_plug(
         "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
         "energy_path": plug.mqtt_energy_path,
         "energy_multiplier": plug.mqtt_energy_multiplier,
+        "energy_total_path": plug.mqtt_energy_total_path,
+        "energy_total_multiplier": plug.mqtt_energy_total_multiplier,
         "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
         "state_path": plug.mqtt_state_path,
         "state_on_value": plug.mqtt_state_on_value,
@@ -699,6 +707,8 @@ async def update_smart_plug(
             "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
             "energy_path": plug.mqtt_energy_path,
             "energy_multiplier": plug.mqtt_energy_multiplier,
+            "energy_total_path": plug.mqtt_energy_total_path,
+            "energy_total_multiplier": plug.mqtt_energy_total_multiplier,
             "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
             "state_path": plug.mqtt_state_path,
             "state_on_value": plug.mqtt_state_on_value,
@@ -864,7 +874,13 @@ async def get_plug_status(
                 await db.commit()
 
             energy_data = None
-            if data.power is not None or data.energy is not None:
+            if mqtt_has_lifetime_counter(plug):
+                # Today and Yesterday come from the hourly snapshots when the
+                # topic carries only the lifetime counter (#3582).
+                if data.power is not None or data.energy is not None or data.energy_total is not None:
+                    energy = {"power": data.power, "today": data.energy, "total": data.energy_total}
+                    energy_data = SmartPlugEnergy(**await fill_derived_energy(db, plug.id, energy))
+            elif data.power is not None or data.energy is not None:
                 energy_data = SmartPlugEnergy(
                     power=data.power,
                     today=data.energy,

+ 5 - 1
backend/app/api/routes/spoolman.py

@@ -49,7 +49,7 @@ from backend.app.utils.filament_ids import (
     filament_id_to_setting_id,
     normalize_slicer_filament,
 )
-from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type
+from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type, support_filament_type
 
 logger = logging.getLogger(__name__)
 
@@ -1077,6 +1077,10 @@ async def link_spool(
                     tray_sub_brands = sub_brand_override
                 if type_override:
                     tray_type = printer_filament_type(type_override)
+                # A support material keeps the slicer's suffix ("PLA-S") (#3559).
+                tray_type = support_filament_type(
+                    tray_type, tray_info_idx, f"{slot_slicer_filament_name or ''} {tray_sub_brands}"
+                )
 
                 # The spool's own wording is tried first and the reduced type
                 # only as a further fallback, so a material that already

+ 15 - 5
backend/app/api/routes/spoolman_inventory.py

@@ -34,6 +34,7 @@ from backend.app.api.routes._spoolman_helpers import (
     _safe_optional_float,
     assert_safe_spoolman_url,
     cost_per_kg_to_spoolman_price,
+    split_spoolman_filament_name,
     spoolman_cost_per_kg,
     spoolman_net_weight,
     spoolman_price_weight,
@@ -91,7 +92,7 @@ from backend.app.utils.filament_ids import (
     filament_id_to_setting_id,
     normalize_slicer_filament,
 )
-from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type
+from backend.app.utils.filament_types import nozzle_temp_range, printer_filament_type, support_filament_type
 from backend.app.utils.tray_ids import external_tray_id
 
 logger = logging.getLogger(__name__)
@@ -873,10 +874,9 @@ async def update_spool(
     cur_vendor: dict = cur_filament.get("vendor") or {}
     cur_mat: str = (cur_filament.get("material") or "").strip()
     cur_name: str = (cur_filament.get("name") or "").strip()
-    if cur_mat and cur_name.upper().startswith(cur_mat.upper()):
-        cur_subtype: str = cur_name[len(cur_mat) :].strip()
-    else:
-        cur_subtype = cur_name
+    # Read the same way the inventory shows it, so an untouched subtype is
+    # recognised as untouched below (#3561).
+    cur_subtype: str = split_spoolman_filament_name(cur_mat, cur_name)[0] or ""
 
     # Resolve final values: use request value if provided, else keep current
     material = data.material if data.material is not None else cur_mat
@@ -944,6 +944,12 @@ async def update_spool(
     # filament in place when it's a singleton.
     cur_filament_id = cur_filament.get("id")
     desired_name = f"{material} {subtype}".strip() if subtype else material
+    # The filament keeps the name it has unless its material or subtype was
+    # actually changed. The name is the user's own wording in Spoolman --
+    # "Matte Scarlet Red" carries the colour too -- and rebuilding it from the
+    # two fields renamed it on every save of anything at all (#3561).
+    if cur_name and material.strip() == cur_mat and (subtype or "").strip() == cur_subtype:
+        desired_name = cur_name
     # Compare the stored shapes, not raw strings and not bare RGB prefixes. Raw
     # strings make an opaque spool's six characters differ from an incoming eight
     # and PATCH the filament on every no-op edit; bare prefixes make an
@@ -2114,6 +2120,10 @@ async def assign_spoolman_slot(
             # spool has one (issue #2902, @doncaruana).
             if type_override:
                 tray_type = printer_filament_type(type_override)
+            # A support material keeps the slicer's suffix ("PLA-S") (#3559).
+            tray_type = support_filament_type(
+                tray_type, tray_info_idx, f"{slot_slicer_filament_name or ''} {tray_sub_brands}"
+            )
 
             material_upper = material.upper().strip()
             # Without a preset, the slot's own filament id where it fits, as in

+ 51 - 42
backend/app/api/routes/users.py

@@ -36,7 +36,7 @@ from backend.app.models.print_batch import PrintBatch
 from backend.app.models.print_log import PrintLogEntry
 from backend.app.models.print_queue import PrintQueueItem
 from backend.app.models.settings import Settings
-from backend.app.models.user import User
+from backend.app.models.user import ADMIN_GROUP_NAME, User
 from backend.app.models.user_otp_code import UserOTPCode
 from backend.app.models.user_totp import UserTOTP
 from backend.app.schemas.auth import (
@@ -197,6 +197,13 @@ async def create_user(
                 detail="One or more group IDs are invalid",
             )
         new_user.groups = list(groups)
+    elif user_data.role == "admin":
+        admin_group = (await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))).scalar_one_or_none()
+        new_user.groups = [admin_group] if admin_group else []
+    else:
+        new_user.groups = []
+    # As in update_user: the groups decide, role follows (#3533).
+    new_user.sync_role_to_groups()
 
     db.add(new_user)
     await db.flush()
@@ -267,6 +274,19 @@ async def get_user(
     return _user_to_response(user)
 
 
+async def _other_active_admins(db: AsyncSession, user_id: int) -> bool:
+    """Is there an active admin other than this user, by role or by group?"""
+    role_admin = await db.scalar(
+        select(User.id).where(User.role == "admin", User.is_active.is_(True), User.id != user_id).limit(1)
+    )
+    if role_admin is not None:
+        return True
+    admin_group = (
+        await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME).options(selectinload(Group.users)))
+    ).scalar_one_or_none()
+    return any(u.is_active and u.id != user_id for u in (admin_group.users if admin_group else []))
+
+
 @router.patch("/{user_id}", response_model=UserResponse)
 async def update_user(
     user_id: int,
@@ -286,35 +306,39 @@ async def update_user(
             detail="User not found",
         )
 
-    # Prevent deactivating the last admin
-    if user_data.is_active is False and user.is_admin:
-        # Count admins by role or Administrators group membership
-        admin_count_result = await db.execute(select(User).where(User.role == "admin", User.is_active.is_(True)))
-        role_admins = admin_count_result.scalars().all()
-
-        # Also check for users in Administrators group
-        admin_group_result = await db.execute(
-            select(Group).where(Group.name == "Administrators").options(selectinload(Group.users))
+    # The groups decide who is an admin, and role follows them (#3533). With
+    # both sent, the groups win; role alone moves the user in or out of
+    # Administrators.
+    if user_data.role is not None and user_data.role not in ["admin", "user"]:
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail="Role must be 'admin' or 'user'",
         )
-        admin_group = admin_group_result.scalar_one_or_none()
-        group_admins = [u for u in (admin_group.users if admin_group else []) if u.is_active]
-
-        # Combine unique admins
-        all_admins = {u.id for u in role_admins} | {u.id for u in group_admins}
-        if len(all_admins) <= 1 and user.id in all_admins:
+    new_groups: list[Group] | None = None
+    if user_data.group_ids is not None:
+        groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
+        new_groups = list(groups_result.scalars().all())
+        if len(new_groups) != len(user_data.group_ids):
             raise HTTPException(
                 status_code=status.HTTP_400_BAD_REQUEST,
-                detail="Cannot deactivate the last admin user",
+                detail="One or more group IDs are invalid",
             )
-
-    # Prevent changing role of last admin
-    if user_data.role and user_data.role != "admin" and user.role == "admin":
-        admin_count_result = await db.execute(select(User).where(User.role == "admin", User.is_active.is_(True)))
-        admin_count = len(admin_count_result.scalars().all())
-        if admin_count <= 1:
+    elif user_data.role is not None:
+        admin_group = (await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))).scalar_one_or_none()
+        others = [g for g in user.groups if g.name != ADMIN_GROUP_NAME]
+        new_groups = others + [admin_group] if user_data.role == "admin" and admin_group else others
+
+    # Prevent leaving no active admin: by deactivation, or by taking the
+    # admin rights away.
+    stays_active = user.is_active if user_data.is_active is None else user_data.is_active
+    stays_admin = user.is_admin if new_groups is None else any(g.name == ADMIN_GROUP_NAME for g in new_groups)
+    if user.is_admin and user.is_active and not (stays_active and stays_admin):
+        if not await _other_active_admins(db, user.id):
             raise HTTPException(
                 status_code=status.HTTP_400_BAD_REQUEST,
-                detail="Cannot change role of the last admin user",
+                detail="Cannot deactivate the last admin user"
+                if not stays_active
+                else "Cannot remove admin rights from the last admin user",
             )
 
     if user_data.username is not None:
@@ -385,14 +409,6 @@ async def update_user(
         user.password_changed_at = utcnow_naive()
         close_sockets = True
 
-    if user_data.role is not None:
-        if user_data.role not in ["admin", "user"]:
-            raise HTTPException(
-                status_code=status.HTTP_400_BAD_REQUEST,
-                detail="Role must be 'admin' or 'user'",
-            )
-        user.role = user_data.role
-
     if user_data.is_active is not None:
         if user.is_active and not user_data.is_active:
             # Deactivated: their printers go at the scope refresh below, but
@@ -410,16 +426,9 @@ async def update_user(
             close_sockets = True
         user.is_active = user_data.is_active
 
-    # Handle group assignments
-    if user_data.group_ids is not None:
-        groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
-        groups = groups_result.scalars().all()
-        if len(groups) != len(user_data.group_ids):
-            raise HTTPException(
-                status_code=status.HTTP_400_BAD_REQUEST,
-                detail="One or more group IDs are invalid",
-            )
-        user.groups = list(groups)
+    if new_groups is not None:
+        user.groups = new_groups
+        user.sync_role_to_groups()
 
     await ensure_user_finance_defaults(db, user)
 

+ 1 - 1
backend/app/core/config.py

@@ -7,7 +7,7 @@ from pydantic import Field
 from pydantic_settings import BaseSettings
 
 # Application version - single source of truth
-APP_VERSION = "1.3.1"
+APP_VERSION = "1.3.2"
 GITHUB_REPO = "maziggy/bambuddy"
 BUG_REPORT_RELAY_URL = os.environ.get("BUG_REPORT_RELAY_URL", "https://bambuddy.cool/api/bug-report")
 

+ 103 - 1
backend/app/core/database.py

@@ -6006,6 +6006,10 @@ async def _run_migrations(conn):
     await _safe_execute(conn, f"ALTER TABLE print_log_entries ADD COLUMN wear_cost {float_type}")
     await _safe_execute(conn, f"ALTER TABLE print_archives ADD COLUMN wear_cost {float_type}")
 
+    # Migration: a printer's place in the pick order of "Any model" jobs (#2915).
+    # Nullable: no printer has one until the order setting is "priority" and one is set.
+    await _safe_execute(conn, "ALTER TABLE printers ADD COLUMN dispatch_priority INTEGER")
+
     # Migration: when each spool was last dried, at what temperature and for
     # how long (#2863). Nullable: no spool has a drying record until one ends.
     datetime_type = "DATETIME" if is_sqlite() else "TIMESTAMP"
@@ -6107,6 +6111,33 @@ async def _run_migrations(conn):
     # (``print_cost_estimate.fill_plate_estimates``).
     await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN plate_estimates JSON")
 
+    # Migration: the G-code fingerprint of the archive's file (#1634), so a
+    # slice sent again from the slicer adds a run to its archive. Nullable, no
+    # default; filled from the archived file after startup
+    # (``archive_gcode_hash.fill_gcode_hashes``).
+    await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN gcode_hash VARCHAR(64)")
+    await _safe_execute(conn, "CREATE INDEX IF NOT EXISTS ix_print_archives_gcode_hash ON print_archives (gcode_hash)")
+
+    # Migration: who assigned a spool to a slot, whose cloud sign-in the replay
+    # on insert resolves a custom preset with (#3519). Nullable, no backfill:
+    # earlier assignments replay as before.
+    await _safe_execute(
+        conn,
+        "ALTER TABLE spool_assignment ADD COLUMN assigned_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL",
+    )
+
+    # Migration: an MQTT plug's lifetime energy counter, separate from its daily
+    # one (#3582). A print's energy is the difference of two readings, so a
+    # daily counter that resets at midnight lost any print running across it.
+    # Nullable path, no backfill: existing plugs read their one energy value as
+    # before. The multiplier is NOT NULL with the model's server default, and
+    # gets the model's float type on Postgres from the start.
+    float_type = "REAL" if is_sqlite() else "DOUBLE PRECISION"
+    await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_total_path VARCHAR(100)")
+    await _safe_execute(
+        conn, f"ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_total_multiplier {float_type} NOT NULL DEFAULT '1.0'"
+    )
+
     await _backfill_archive_run_photos(conn)
     await _migrate_h3c_queue_tray_ids(conn)
 
@@ -6117,6 +6148,7 @@ async def _run_migrations(conn):
     await _migrate_spool_usage_outlives_its_archive(conn)
     await _migrate_spool_usage_outlives_its_spool(conn)
     await _backfill_pipeline_job_final_status(conn)
+    await _backfill_maintenance_log(conn)
     await _release_stuck_budget_reservations(conn)
     await _release_slots_of_archived_spools(conn)
     await _migrate_pg_column_types(conn)
@@ -6635,6 +6667,46 @@ async def _backfill_pipeline_job_final_status(conn) -> None:
         logger.info("Stored the final status of %d pipeline job(s) from their queue entry", result.rowcount)
 
 
+async def _backfill_maintenance_log(conn) -> None:
+    """Copy maintenance history into the maintenance log.
+
+    The log (maintenance_log_entries) is written with each reset and outlives
+    the printer and its tasks; resets before it existed are only in
+    maintenance_history, which goes with them. Who reset them was never
+    recorded and stays unknown.
+
+    Once only, gated by a settings flag: entries deleted from the log later
+    (cleanup, a mistaken reset) still have their history row, and a second
+    pass would bring them back. Rows the log already has an entry for
+    (``history_id``) are skipped either way.
+    """
+    from sqlalchemy import text
+
+    flag = "_backfill_maintenance_log_done"
+    async with conn.begin_nested():
+        already = (
+            await conn.execute(text('SELECT value FROM settings WHERE "key" = :k'), {"k": flag})
+        ).scalar_one_or_none()
+        if already is not None:
+            return
+        result = await conn.execute(
+            text(
+                "INSERT INTO maintenance_log_entries (printer_id, printer_name, maintenance_type_id, "
+                "maintenance_type_name, hours_at_maintenance, notes, performed_at, history_id) "
+                "SELECT pm.printer_id, p.name, pm.maintenance_type_id, t.name, "
+                "COALESCE(h.hours_at_maintenance, 0), h.notes, h.performed_at, h.id "
+                "FROM maintenance_history h "
+                "JOIN printer_maintenance pm ON pm.id = h.printer_maintenance_id "
+                "JOIN printers p ON p.id = pm.printer_id "
+                "JOIN maintenance_types t ON t.id = pm.maintenance_type_id "
+                "WHERE NOT EXISTS (SELECT 1 FROM maintenance_log_entries l WHERE l.history_id = h.id)"
+            )
+        )
+        await conn.execute(text('INSERT INTO settings ("key", value) VALUES (:k, :v)'), {"k": flag, "v": "true"})
+    if result.rowcount:
+        logger.info("Copied %d maintenance history row(s) into the maintenance log", result.rowcount)
+
+
 async def _release_stuck_budget_reservations(conn) -> None:
     """Release print reservations whose queue entry has finished or is gone.
 
@@ -7916,7 +7988,7 @@ async def seed_default_groups():
     from backend.app.core.permissions import ALL_PERMISSIONS, DEFAULT_GROUPS
     from backend.app.models.group import Group
     from backend.app.models.settings import Settings
-    from backend.app.models.user import User
+    from backend.app.models.user import ADMIN_GROUP_NAME, User
 
     logger = logging.getLogger(__name__)
 
@@ -8297,6 +8369,36 @@ async def seed_default_groups():
 
             await session.commit()
 
+        # #3533: a user moved out of Administrators kept role "admin", and with
+        # it every admin right. The role follows the groups now; this lines up
+        # the users demoted before that. Should they be the only admins left,
+        # they stay admins and join Administrators instead. One-shot.
+        role_flag = "_backfill_3533_admin_role_follows_groups_done"
+        if (await session.execute(select(Settings).where(Settings.key == role_flag))).scalar_one_or_none() is None:
+            admin_group = (
+                await session.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))
+            ).scalar_one_or_none()
+            stray = [
+                u
+                for u in (await session.execute(select(User).where(User.role == "admin"))).scalars().all()
+                if all(g.name != ADMIN_GROUP_NAME for g in u.groups)
+            ]
+            if stray and admin_group:
+                group_admins = [
+                    u
+                    for u in (await session.execute(select(User))).scalars().all()
+                    if u.is_active and any(g.name == ADMIN_GROUP_NAME for g in u.groups)
+                ]
+                for user in stray:
+                    if group_admins:
+                        user.role = "user"
+                        logger.info("User '%s' is not in Administrators: admin role removed (#3533)", user.username)
+                    else:
+                        user.groups.append(admin_group)
+                        logger.info("User '%s' is the only admin: added to Administrators (#3533)", user.username)
+            session.add(Settings(key=role_flag, value="true"))
+            await session.commit()
+
 
 async def seed_spool_catalog():
     """Seed the spool catalog with default entries if empty."""

+ 14 - 0
backend/app/core/sqlite_fk.py

@@ -99,10 +99,20 @@ APPLIED: frozenset[tuple[str, str]] = frozenset(
         # A profile default's K profile would select a calibration slot on
         # the next printer given the id (#1326).
         ("filament_profile_default_k_profile", "printer_id"),
+        # The maintenance log outlives its printer; the next printer given the
+        # id would take over its history.
+        ("maintenance_log_entries", "printer_id"),
         # filament_profile_default: the next default given the id would take
         # over its presets and K profiles (#1326).
         ("filament_profile_default_k_profile", "profile_default_id"),
         ("filament_profile_default_preset", "profile_default_id"),
+        # maintenance_types: the log keeps a deleted custom task's entries; the
+        # next task given the id would take them over.
+        ("maintenance_log_entries", "maintenance_type_id"),
+        # maintenance_history goes with its printer task; the next reset given
+        # the id, maybe on another printer, would have its history deleted
+        # with this entry.
+        ("maintenance_log_entries", "history_id"),
         # external_links: the next link given the id would show the count an
         # app reported for the deleted one.
         ("external_link_badges", "link_id"),
@@ -123,6 +133,7 @@ APPLIED: frozenset[tuple[str, str]] = frozenset(
         ("library_files", "created_by_id"),
         ("library_folders", "created_by_id"),
         ("long_lived_tokens", "user_id"),
+        ("maintenance_log_entries", "performed_by_id"),
         ("pipeline_runs", "created_by"),
         ("print_archives", "created_by_id"),
         ("print_batches", "created_by_id"),
@@ -130,6 +141,9 @@ APPLIED: frozenset[tuple[str, str]] = frozenset(
         ("print_queue", "created_by_id"),
         ("scheduled_dryings", "created_by_id"),
         ("slicer_pipelines", "created_by"),
+        # A new user given the id would have their cloud sign-in used for the
+        # slot's preset (#3519).
+        ("spool_assignment", "assigned_by_user_id"),
         ("sponsor_toast_state", "user_id"),
         ("user_email_preferences", "user_id"),
         ("user_groups", "user_id"),

BIN
backend/app/data/fonts/DroidSansFallbackFull.ttf


+ 208 - 0
backend/app/data/fonts/LICENSE_DROID

@@ -0,0 +1,208 @@
+Droid Sans Fallback (DroidSansFallbackFull.ttf)
+Copyright 2006-2010 Google Corp.
+Source: https://android.googlesource.com/platform/frameworks/base/ (as packaged by Debian, fonts-droid-fallback)
+
+Licensed under the Apache License, Version 2.0:
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 101 - 0
backend/app/data/fonts/LICENSE_LIBERATION

@@ -0,0 +1,101 @@
+Digitized data copyright (c) 2010 Google Corporation
+	with Reserved Font Arimo, Tinos and Cousine.
+Copyright (c) 2012 Red Hat, Inc.
+	with Reserved Font Name Liberation.
+
+This Font Software is licensed under the SIL Open Font License,
+Version 1.1.
+
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+
+PREAMBLE The goals of the Open Font License (OFL) are to stimulate
+worldwide development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to provide
+a free and open framework in which fonts may be shared and improved in
+partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves.
+The fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works.  The fonts and derivatives,
+however, cannot be released under any other type of license.  The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such.
+This may include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components
+as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting ? in part or in whole ?
+any of the components of the Original Version, by changing formats or
+by porting the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical writer
+or other person who contributed to the Font Software.
+
+
+PERMISSION & CONDITIONS
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,in
+   Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+   redistributed and/or sold with any software, provided that each copy
+   contains the above copyright notice and this license. These can be
+   included either as stand-alone text files, human-readable headers or
+   in the appropriate machine-readable metadata fields within text or
+   binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+   Name(s) unless explicit written permission is granted by the
+   corresponding Copyright Holder. This restriction only applies to the
+   primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+   Software shall not be used to promote, endorse or advertise any
+   Modified Version, except to acknowledge the contribution(s) of the
+   Copyright Holder(s) and the Author(s) or with their explicit written
+   permission.
+
+5) The Font Software, modified or unmodified, in part or in whole, must
+   be distributed entirely under this license, and must not be distributed
+   under any other license. The requirement for fonts to remain under
+   this license does not apply to any document created using the Font
+   Software.
+
+
+
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+
+
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.  IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
+DEALINGS IN THE FONT SOFTWARE.

+ 99 - 0
backend/app/data/fonts/LICENSE_NOTO_KR

@@ -0,0 +1,99 @@
+Noto Sans KR (NotoSansKR-Hangul.ttf)
+Source: https://github.com/google/fonts/tree/main/ofl/notosanskr
+Modified for Bambuddy: the variable font fixed at weight 400 (Regular) and
+subset to the Hangul blocks (U+1100-11FF, U+3130-318F, U+A960-A97F,
+U+AC00-D7FF), as Droid Sans Fallback covers Chinese and Japanese.
+
+Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.

BIN
backend/app/data/fonts/LiberationSans-Bold.ttf


BIN
backend/app/data/fonts/LiberationSans-Italic.ttf


BIN
backend/app/data/fonts/LiberationSans-Regular.ttf


BIN
backend/app/data/fonts/NotoSansKR-Hangul.ttf


+ 121 - 0
backend/app/data/slicer_filament_types.json

@@ -0,0 +1,121 @@
+{
+  "description": "Values of the `filament_type` option (the Type dropdown of a filament preset) in each slicer, keyed by the preferred_slicer setting. Read from the slicers' source: Bambu Studio's PrintConfig.cpp, OrcaSlicer's MaterialType.cpp (which PrintConfig.cpp loops over). A slicer release can differ.",
+  "bambu_studio": {
+    "source": "https://github.com/bambulab/BambuStudio/blob/master/src/libslic3r/PrintConfig.cpp (filament_type)",
+    "values": [
+      "PLA",
+      "ABS",
+      "ASA",
+      "ASA-CF",
+      "PETG",
+      "PCTG",
+      "TPU",
+      "TPU-AMS",
+      "PC",
+      "PA",
+      "PA-CF",
+      "PA-GF",
+      "PA6-CF",
+      "PLA-CF",
+      "PET-CF",
+      "PETG-CF",
+      "PVA",
+      "HIPS",
+      "PLA-AERO",
+      "PPS",
+      "PPS-CF",
+      "PPA-CF",
+      "PPA-GF",
+      "ABS-GF",
+      "ASA-AERO",
+      "PE",
+      "PP",
+      "EVA",
+      "PHA",
+      "BVOH",
+      "PE-CF",
+      "PP-CF",
+      "PP-GF"
+    ]
+  },
+  "orcaslicer": {
+    "source": "https://github.com/SoftFever/OrcaSlicer/blob/main/src/libslic3r/MaterialType.cpp (MaterialType::all)",
+    "values": [
+      "ABS",
+      "ABS-CF",
+      "ABS-GF",
+      "ASA",
+      "ASA-CF",
+      "ASA-GF",
+      "ASA-AERO",
+      "BVOH",
+      "CoPE",
+      "EVA",
+      "FLEX",
+      "HIPS",
+      "PA",
+      "PA-CF",
+      "PA-GF",
+      "PA6",
+      "PA6-CF",
+      "PA6-GF",
+      "PA11",
+      "PA11-CF",
+      "PA11-GF",
+      "PA12",
+      "PA12-CF",
+      "PA12-GF",
+      "PAHT",
+      "PAHT-CF",
+      "PAHT-GF",
+      "PC",
+      "PC-ABS",
+      "PC-CF",
+      "PC-PBT",
+      "PCL",
+      "PCTG",
+      "PE",
+      "PE-CF",
+      "PE-GF",
+      "PEI-1010",
+      "PEI-1010-CF",
+      "PEI-1010-GF",
+      "PEI-9085",
+      "PEI-9085-CF",
+      "PEI-9085-GF",
+      "PEEK",
+      "PEEK-CF",
+      "PEEK-GF",
+      "PEKK",
+      "PEKK-CF",
+      "PES",
+      "PET",
+      "PET-CF",
+      "PET-GF",
+      "PETG",
+      "PETG-CF",
+      "PETG-GF",
+      "PHA",
+      "PI",
+      "PLA",
+      "PLA-AERO",
+      "PLA-CF",
+      "POM",
+      "PP",
+      "PP-CF",
+      "PP-GF",
+      "PPA-CF",
+      "PPA-GF",
+      "PPS",
+      "PPS-CF",
+      "PPSU",
+      "PSU",
+      "PVA",
+      "PVB",
+      "PVDF",
+      "SBS",
+      "TPI",
+      "TPU"
+    ]
+  }
+}

+ 428 - 186
backend/app/main.py

@@ -183,7 +183,7 @@ from backend.app.services.telegram_reactions import telegram_reaction_poller
 from backend.app.services.wled import wled_manager
 from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
 from backend.app.utils.ams_humidity import ams_humidity_percent
-from backend.app.utils.filament_types import printer_filament_type
+from backend.app.utils.filament_types import printer_filament_type, support_filament_type
 from backend.app.utils.fts_routing import extruder_for_inlet
 from backend.app.utils.local_time import to_naive_utc, utcnow_naive
 from backend.app.utils.print_jobs import is_internal_printer_job
@@ -1693,6 +1693,23 @@ async def _fill_plate_estimates() -> None:
         logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
 
 
+_gcode_hashes_task: asyncio.Task | None = None
+
+
+async def _fill_gcode_hashes() -> None:
+    from backend.app.services.archive_gcode_hash import fill_gcode_hashes
+
+    try:
+        filled = await fill_gcode_hashes(async_session)
+    except asyncio.CancelledError:
+        raise
+    except Exception as exc:
+        logging.getLogger(__name__).warning("[ARCHIVE] Reading G-code fingerprints failed: %s", exc)
+        return
+    if filled:
+        logging.getLogger(__name__).info("[ARCHIVE] Read the G-code fingerprints of %d archive(s)", filled)
+
+
 def _partial_progress_scale(progress: int | float | None) -> float:
     """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
 
@@ -2303,6 +2320,12 @@ async def on_printer_status_change(printer_id: int, state: PrinterState):
                 name=f"printer-offline-notify-{printer_id}",
             )
     elif state.connected:
+        if prev_connected is False:
+            # A printer back from a dropped connection, often a restart, may
+            # take files again: don't hold it to an upload backoff from
+            # before (#3563). Not on Bambuddy's own start (no previous state).
+            client = printer_manager.get_client(printer_id)
+            print_scheduler.printer_reconnected(printer_id, client.ip_address if client else None)
         # Kept until the relay can actually send online: with its broker down
         # now, the next status update after the reconnect sends it.
         if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
@@ -2800,6 +2823,18 @@ def _slot_feeds_print(printer_id: int, ams_id: int, tray_id: int) -> bool:
     return any(slot.has_filament and slot.holds(ams_id, tray_id) for slot in slots.values())
 
 
+def _tray_reports_no_filament(color: str, tray_type: str) -> bool:
+    """Does this tray report carry no filament data at all?
+
+    No type, and a colour that is either empty or ``00000000``: firmware sends
+    both for a blank slot, and ``00000000`` is what Bambuddy's own slot reset
+    writes. A reconnect mid-print brought it in that form and got past every
+    guard that only knew the empty string (#3526). A clear spool also reports
+    ``00000000``, but always with a type, so it is not blank.
+    """
+    return not tray_type.strip() and color.strip().upper() in ("", "00000000")
+
+
 async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
     """Unlink built-in inventory assignments whose slot no longer holds their spool.
 
@@ -2995,11 +3030,21 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         try:
                             from backend.app.api.routes.inventory import (
                                 apply_spool_to_slot_via_mqtt,
+                                load_preset_lookup_user,
                             )
+                            from backend.app.core.auth import is_auth_enabled
+
+                            # Whoever made the assignment: their cloud sign-in
+                            # resolves a custom preset, which nobody's did here,
+                            # so the slot got Generic PLA on insert (#3519). With
+                            # login off the shared sign-in applies, as before.
+                            replay_user = None
+                            if assignment.assigned_by_user_id is not None and await is_auth_enabled(db):
+                                replay_user = await load_preset_lookup_user(db, assignment.assigned_by_user_id)
 
                             configured = await apply_spool_to_slot_via_mqtt(
                                 db=db,
-                                current_user=None,
+                                current_user=replay_user,
                                 spool=assignment.spool,
                                 printer_id=printer_id,
                                 ams_id=assignment.ams_id,
@@ -3044,7 +3089,7 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         # firmware clears colour and type when it unloads a spool
                         # it just emptied. Unlinking here would erase the record
                         # of which spool fed the print so far.
-                        if printing_now and not cur_color.strip() and not cur_type.strip():
+                        if printing_now and _tray_reports_no_filament(cur_color, cur_type):
                             logger.info(
                                 "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
                                 "(runout?)",
@@ -3068,8 +3113,7 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         # rather than cancelling it (#3186).
                         if (
                             spool_present(current_tray) is True
-                            and not cur_color.strip()
-                            and not cur_type.strip()
+                            and _tray_reports_no_filament(cur_color, cur_type)
                             and not slot_unlink_grace.is_held(
                                 printer_id,
                                 ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
@@ -3088,7 +3132,7 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                         # unit's bits, colour and type for a moment and lost
                         # four saved assignments that way (#3186); unlink only
                         # if the slot is still blank after the grace period.
-                        if not cur_color.strip() and not cur_type.strip():
+                        if _tray_reports_no_filament(cur_color, cur_type):
                             hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
                             if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
                                 held.add(hold_key)
@@ -3147,6 +3191,17 @@ async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_no
                                 lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
                                 if lp_type:
                                     spool_types.add(printer_filament_type(lp_type).upper())
+                            # A support spool went in with the slicer's suffix
+                            # ("PLA-S") that none of the above carries (#3559).
+                            # A spool made from a support RFID tray has its
+                            # material as "Support For PLA", so that counts too.
+                            support_name = (
+                                f"{spool.slicer_filament_name or ''} {spool.material or ''} {spool.subtype or ''}"
+                            )
+                            spool_types |= {
+                                support_filament_type(t, spool.slicer_filament, support_name).upper()
+                                for t in spool_types
+                            }
                             if (
                                 _colors_similar(cur_color, spool_color)
                                 and printer_filament_type(cur_type).upper() in spool_types
@@ -4979,6 +5034,277 @@ async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, sub
     )
 
 
+async def _adopt_archive_for_run(
+    db: AsyncSession,
+    archive,
+    printer_id: int,
+    *,
+    starting_plate_id: int | None,
+    effective_subtask_id: str | None,
+    logger: logging.Logger,
+    started_at: datetime | None = None,
+) -> bool:
+    """Start a print's run on an archive that already exists: a reprint, a
+    queue print of a file printed before, or the same slice sent again from the
+    slicer (#1634). The archive says "printing" from now, without the previous
+    run's outcome, answer or timelapse, and on this printer with this print's
+    job id. False when the printer was deleted meanwhile: the adoption is
+    undone or was refused, the printer is forgotten, and the caller stops.
+    """
+    from backend.app.models.archive import PrintArchive
+
+    # As it was before this adoption: put back if the printer turns
+    # out to have been deleted while it was adopted (below).
+    before_adoption = {
+        attr.columns[0].name: getattr(archive, attr.key)
+        for attr in sa_inspect(PrintArchive).column_attrs
+        if attr.key != "id"
+    }
+
+    # Update archive status to printing
+    archive.status = "printing"
+    archive.started_at = started_at or datetime.now(timezone.utc)
+    # The previous run's outcome is not this one's: a reprint that
+    # completes must not keep showing why the last one failed.
+    archive.failure_reason = None
+    archive.completed_at = None
+
+    # The previous run's answer is still on this row and the
+    # completion prompt is gated on ``user_verdict is None`` (#1898),
+    # so without a reset the second run inherits the first run's
+    # verdict: no prompt at all, and a green "good" badge on a run
+    # nobody ever judged.
+    if archive.confirm_requested:
+        archive.user_verdict = None
+        archive.user_verdict_source = None
+        archive.user_verdict_at = None
+        archive.confirm_token = None
+        archive.confirm_token_used_at = None
+
+    # Reprint of an archive reuses the source row. Without resetting
+    # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
+    # ("already has timelapse") and _capture_finish_photo_from_timelapse
+    # extracts the *original* print's last frame, which then ships in
+    # the completion notification (#1707). Clear the path so the
+    # scanner runs fresh; also unlink the old video file so reprints
+    # don't accumulate orphans in the archive directory. Photos list
+    # is left alone — accumulating one finish photo per run is fine.
+    # The print-start baseline (#2704) is stale for the same reason:
+    # it describes the printer before the previous run. The capture
+    # below overwrites it, but clear it here too so an early failure
+    # can't leave the scan diffing against the wrong snapshot.
+    #
+    # Unlinked only when it is the same plate printing again. Every
+    # plate of a Send All shares this archive, and the video on it
+    # can be the only copy of another plate's run -- the printer's
+    # was deleted once it attached (#3275). That one is left in the
+    # archive directory, which goes with the archive. A video whose
+    # plate is not on record (attached by hand, or before the
+    # column existed) is kept too where the 3MF has other plates,
+    # or cannot be read: nothing tells it apart from another plate's,
+    # and keeping costs one file where deleting can cost the only
+    # copy. On an archive with exactly one plate it is that plate's.
+    archive.timelapse_baseline = None
+    stale_timelapse_relpath = archive.timelapse_path
+    stale_timelapse_plate_id = archive.timelapse_plate_id
+    if stale_timelapse_relpath:
+        archive.timelapse_path = None
+        archive.timelapse_plate_id = None
+    stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
+    if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
+        from backend.app.services.archive import plate_indexes_in_3mf
+
+        plates = await asyncio.to_thread(
+            plate_indexes_in_3mf,
+            app_settings.base_dir / archive.file_path,  # SEC-PATH-OK: stored relative archive path
+        )
+        stale_is_this_plates = len(plates) == 1
+    if stale_timelapse_relpath and not stale_is_this_plates:
+        logger.info(
+            "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
+            stale_timelapse_relpath,
+            stale_timelapse_plate_id,
+            archive.id,
+            starting_plate_id,
+        )
+    # The video is deleted once the adoption stands (below).
+    delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
+    # Update on first-set OR on reprint (the queue dispatcher mints
+    # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
+    # the rewrite for reprints leaves the archive holding the FIRST
+    # run's id; if MQTT then reconnects mid-print, the reconciler
+    # (#1542) compares the stale stored id against the printer's
+    # live id, sees a mismatch, and synthesises a bogus PRINT
+    # COMPLETE — exactly the false-positive "Print Stopped" reported
+    # in #1807. Inequality check preserves the noop-on-stable-push
+    # behaviour the earlier `not archive.subtask_id` guard provided.
+    if effective_subtask_id and archive.subtask_id != effective_subtask_id:
+        archive.subtask_id = effective_subtask_id
+    # #1403 follow-up: VP-queue archives are created with
+    # printer_id=None at queue-add time (we don't know which
+    # printer will run the job yet). When the print actually
+    # starts on a specific printer the expected-archive lookup
+    # used to skip this assignment, leaving printer_id=None
+    # forever — which then disables the "Scan for timelapse"
+    # button in ArchivesPage (gated on !archive.printer_id).
+    if archive.printer_id != printer_id:
+        archive.printer_id = printer_id
+    adopting_id = archive.id  # a rollback expires the object
+    try:
+        await db.commit()
+    except (IntegrityError, StaleDataError):
+        # The archive stays unchanged, or is gone: "delete archives"
+        # removed the row under the adoption, which then matched no
+        # row (StaleDataError) rather than being refused.
+        if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
+            return False
+        raise
+
+    # The printer can be deleted between the check above and this
+    # commit (the route's transaction lasts seconds), and the commit
+    # then adopted the archive anyway: status, verdict and timelapse
+    # changed, and the deleted printer's id written on a row the
+    # route had detached or never touched. Undo the adoption.
+    if await _printer_gone(db, printer_id):
+        logger.info(
+            "Printer %s was deleted while archive %s was adopted; undoing the adoption",
+            printer_id,
+            archive.id,
+        )
+        # Everything as before this adoption. The printer it had
+        # then stays, unless it was the deleted one: the route
+        # detached that row (kept) or deleted it (no row matches).
+        previous_printer = before_adoption["printer_id"]
+        await db.execute(
+            update(PrintArchive)
+            .where(PrintArchive.id == archive.id)
+            .values(
+                {
+                    **before_adoption,
+                    "printer_id": None if previous_printer == printer_id else previous_printer,
+                }
+            )
+        )
+        await db.commit()
+        await forget_printer(printer_id)
+        return False
+
+    await _drop_replaced_plate_videos(
+        db,
+        archive.id,
+        starting_plate_id,
+        stale_timelapse_relpath if delete_stale_video else None,
+        logger,
+    )
+    return True
+
+
+async def _claim_slicer_resend_archive(db: AsyncSession, printer_id: int, source: Path):
+    """The archive a print sent from the slicer adds its run to, or None for a
+    new one (#1634): the same G-code, so the same slice sent again in a new 3MF.
+
+    As a queue print of a file printed before (``_claim_reusable_archive`` in
+    the scheduler): the same owner (who started the print, nobody for a print
+    from the slicer) and no project, and no File Manager file, whose own prints
+    find its archive by the file's bytes. Not one a merge is moving. Held in
+    ``archive_work`` from here, with no await between, until the caller
+    releases it once the run is open.
+
+    Returns the archive and whether something else holds it already: a queue
+    dispatch uploading or printing its file, which the file must stay for.
+    """
+    from backend.app.models.archive import PrintArchive
+    from backend.app.services import archive_work
+    from backend.app.services.archive_gcode_hash import gcode_fingerprint
+
+    # Unzipping a large 3MF takes seconds: off the event loop.
+    fingerprint = await asyncio.to_thread(gcode_fingerprint, source)
+    if not fingerprint:
+        return None
+    owner_id = await _print_user_id_if_still_there(db, printer_manager.get_current_print_user(printer_id))
+    owner = PrintArchive.created_by_id.is_(None) if owner_id is None else PrintArchive.created_by_id == owner_id
+    candidates = (
+        await db.scalars(
+            select(PrintArchive)
+            .where(
+                PrintArchive.gcode_hash == fingerprint,
+                owner,
+                PrintArchive.project_id.is_(None),
+                PrintArchive.library_file_id.is_(None),
+                PrintArchive.deleted_at.is_(None),
+            )
+            .order_by(PrintArchive.id.desc())
+        )
+    ).all()
+    for candidate in candidates:
+        if archive_work.is_merging(candidate.id):
+            continue
+        in_use = archive_work.is_held(candidate.id)
+        archive_work.hold(candidate.id)
+        return candidate, in_use
+    return None
+
+
+async def _start_slicer_resend_run(
+    db: AsyncSession,
+    archive,
+    printer_id: int,
+    *,
+    source: Path,
+    print_data: dict,
+    subtask_id: str | None,
+    started_at: datetime | None,
+    original_filename: str | None,
+    logger: logging.Logger,
+    file_in_use: bool = False,
+):
+    """Start this print's run on the archive ``_claim_slicer_resend_archive``
+    found (#1634). The archive takes the new file in place of its own, unless
+    another print of it is running, or a queue dispatch holds it
+    (``file_in_use``): that one still reads the file (its upload, pauses,
+    objects and estimate), and the G-code is the same. None when the printer
+    was deleted meanwhile; the caller stops.
+    """
+    from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
+
+    printing_elsewhere = file_in_use or (
+        await db.scalar(
+            select(PrintLogEntry.id)
+            .where(PrintLogEntry.archive_id == archive.id, PrintLogEntry.status == RUN_OPEN)
+            .limit(1)
+            .execution_options(**{INCLUDE_OPEN_RUNS: True})
+        )
+        is not None
+    )
+    if not printing_elsewhere:
+        replaced = await ArchiveService(db).archive_print(
+            printer_id=printer_id,
+            source_file=source,
+            print_data=print_data,
+            subtask_id=subtask_id,
+            original_filename=original_filename,
+            replace_archive_id=archive.id,
+        )
+        if replaced is not None:
+            archive = replaced
+        else:
+            # The copy failed its check, or the printer is gone (the adoption
+            # below says so): the run still joins, on the file it has.
+            logger.warning("Archive %s keeps its file: the one sent again could not be taken", archive.id)
+    client = printer_manager.get_client(printer_id)
+    if not await _adopt_archive_for_run(
+        db,
+        archive,
+        printer_id,
+        starting_plate_id=resolve_plate_id(client.state) if client else None,
+        effective_subtask_id=subtask_id,
+        logger=logger,
+        started_at=started_at,
+    ):
+        return None
+    return archive
+
+
 async def on_print_start(printer_id: int, data: dict):
     """Handle print start - archive the 3MF file immediately."""
     logger = logging.getLogger(__name__)
@@ -5374,83 +5700,6 @@ async def on_print_start(printer_id: int, data: dict):
                 return
 
             if archive:
-                # As it was before this adoption: put back if the printer turns
-                # out to have been deleted while it was adopted (below).
-                before_adoption = {
-                    attr.columns[0].name: getattr(archive, attr.key)
-                    for attr in sa_inspect(PrintArchive).column_attrs
-                    if attr.key != "id"
-                }
-
-                # Update archive status to printing
-                archive.status = "printing"
-                archive.started_at = datetime.now(timezone.utc)
-                # The previous run's outcome is not this one's: a reprint that
-                # completes must not keep showing why the last one failed.
-                archive.failure_reason = None
-                archive.completed_at = None
-
-                # The previous run's answer is still on this row and the
-                # completion prompt is gated on ``user_verdict is None`` (#1898),
-                # so without a reset the second run inherits the first run's
-                # verdict: no prompt at all, and a green "good" badge on a run
-                # nobody ever judged.
-                if archive.confirm_requested:
-                    archive.user_verdict = None
-                    archive.user_verdict_source = None
-                    archive.user_verdict_at = None
-                    archive.confirm_token = None
-                    archive.confirm_token_used_at = None
-
-                # Reprint of an archive reuses the source row. Without resetting
-                # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
-                # ("already has timelapse") and _capture_finish_photo_from_timelapse
-                # extracts the *original* print's last frame, which then ships in
-                # the completion notification (#1707). Clear the path so the
-                # scanner runs fresh; also unlink the old video file so reprints
-                # don't accumulate orphans in the archive directory. Photos list
-                # is left alone — accumulating one finish photo per run is fine.
-                # The print-start baseline (#2704) is stale for the same reason:
-                # it describes the printer before the previous run. The capture
-                # below overwrites it, but clear it here too so an early failure
-                # can't leave the scan diffing against the wrong snapshot.
-                #
-                # Unlinked only when it is the same plate printing again. Every
-                # plate of a Send All shares this archive, and the video on it
-                # can be the only copy of another plate's run -- the printer's
-                # was deleted once it attached (#3275). That one is left in the
-                # archive directory, which goes with the archive. A video whose
-                # plate is not on record (attached by hand, or before the
-                # column existed) is kept too where the 3MF has other plates,
-                # or cannot be read: nothing tells it apart from another plate's,
-                # and keeping costs one file where deleting can cost the only
-                # copy. On an archive with exactly one plate it is that plate's.
-                archive.timelapse_baseline = None
-                stale_timelapse_relpath = archive.timelapse_path
-                stale_timelapse_plate_id = archive.timelapse_plate_id
-                starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
-                if stale_timelapse_relpath:
-                    archive.timelapse_path = None
-                    archive.timelapse_plate_id = None
-                stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
-                if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
-                    from backend.app.services.archive import plate_indexes_in_3mf
-
-                    plates = await asyncio.to_thread(
-                        plate_indexes_in_3mf,
-                        app_settings.base_dir / archive.file_path,  # SEC-PATH-OK: stored relative archive path
-                    )
-                    stale_is_this_plates = len(plates) == 1
-                if stale_timelapse_relpath and not stale_is_this_plates:
-                    logger.info(
-                        "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
-                        stale_timelapse_relpath,
-                        stale_timelapse_plate_id,
-                        expected_archive_id,
-                        starting_plate_id,
-                    )
-                # The video is deleted once the adoption stands (below).
-                delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
                 # Persist a restart-stable id so a later restart resumes this
                 # archive by subtask_id instead of name-matching + duplicating
                 # it (#1485). The printer often hasn't echoed subtask_id back
@@ -5466,73 +5715,16 @@ async def on_print_start(printer_id: int, data: dict):
                     _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
                     if _dispatched:
                         effective_subtask_id = str(_dispatched).strip() or None
-                # Update on first-set OR on reprint (the queue dispatcher mints
-                # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
-                # the rewrite for reprints leaves the archive holding the FIRST
-                # run's id; if MQTT then reconnects mid-print, the reconciler
-                # (#1542) compares the stale stored id against the printer's
-                # live id, sees a mismatch, and synthesises a bogus PRINT
-                # COMPLETE — exactly the false-positive "Print Stopped" reported
-                # in #1807. Inequality check preserves the noop-on-stable-push
-                # behaviour the earlier `not archive.subtask_id` guard provided.
-                if effective_subtask_id and archive.subtask_id != effective_subtask_id:
-                    archive.subtask_id = effective_subtask_id
-                # #1403 follow-up: VP-queue archives are created with
-                # printer_id=None at queue-add time (we don't know which
-                # printer will run the job yet). When the print actually
-                # starts on a specific printer the expected-archive lookup
-                # used to skip this assignment, leaving printer_id=None
-                # forever — which then disables the "Scan for timelapse"
-                # button in ArchivesPage (gated on !archive.printer_id).
-                if archive.printer_id != printer_id:
-                    archive.printer_id = printer_id
-                adopting_id = archive.id  # a rollback expires the object
-                try:
-                    await db.commit()
-                except (IntegrityError, StaleDataError):
-                    # The archive stays unchanged, or is gone: "delete archives"
-                    # removed the row under the adoption, which then matched no
-                    # row (StaleDataError) rather than being refused.
-                    if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
-                        return
-                    raise
-
-                # The printer can be deleted between the check above and this
-                # commit (the route's transaction lasts seconds), and the commit
-                # then adopted the archive anyway: status, verdict and timelapse
-                # changed, and the deleted printer's id written on a row the
-                # route had detached or never touched. Undo the adoption.
-                if await _printer_gone(db, printer_id):
-                    logger.info(
-                        "Printer %s was deleted while archive %s was adopted; undoing the adoption",
-                        printer_id,
-                        archive.id,
-                    )
-                    # Everything as before this adoption. The printer it had
-                    # then stays, unless it was the deleted one: the route
-                    # detached that row (kept) or deleted it (no row matches).
-                    previous_printer = before_adoption["printer_id"]
-                    await db.execute(
-                        update(PrintArchive)
-                        .where(PrintArchive.id == archive.id)
-                        .values(
-                            {
-                                **before_adoption,
-                                "printer_id": None if previous_printer == printer_id else previous_printer,
-                            }
-                        )
-                    )
-                    await db.commit()
-                    await forget_printer(printer_id)
-                    return
-
-                await _drop_replaced_plate_videos(
+                starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
+                if not await _adopt_archive_for_run(
                     db,
-                    archive.id,
-                    starting_plate_id,
-                    stale_timelapse_relpath if delete_stale_video else None,
-                    logger,
-                )
+                    archive,
+                    printer_id,
+                    starting_plate_id=starting_plate_id,
+                    effective_subtask_id=effective_subtask_id,
+                    logger=logger,
+                ):
+                    return
 
                 # Track as active print
                 _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
@@ -6567,26 +6759,50 @@ async def on_print_start(printer_id: int, data: dict):
                     await _send_print_start_notification(printer_id, data, logger=logger)
                 return
 
+        # The archive of the same slice sent before, which this print adds a
+        # run to instead of a new archive (#1634). Held until its run is open.
+        joined_archive_id: int | None = None
         try:
             # Archive the file with status "printing"
             service = ArchiveService(db)
+            start_print_data = {
+                **data,
+                "status": "printing",
+                # Where the 3MF came from when the printer had none to
+                # give (#3307), for whoever reads this archive later.
+                **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
+            }
+            # The reused copy's temp name carries the printer id; a
+            # download's is the file's own name, as before.
+            start_filename = downloaded_filename if reused_3mf_from is not None else None
             try:
-                archive = await service.archive_print(
-                    printer_id=printer_id,
-                    source_file=temp_path,
-                    print_data={
-                        **data,
-                        "status": "printing",
-                        # Where the 3MF came from when the printer had none to
-                        # give (#3307), for whoever reads this archive later.
-                        **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
-                    },
-                    subtask_id=subtask_id,
-                    started_at=detected_at,
-                    # The reused copy's temp name carries the printer id; a
-                    # download's is the file's own name, as before.
-                    original_filename=downloaded_filename if reused_3mf_from is not None else None,
-                )
+                claimed = await _claim_slicer_resend_archive(db, printer_id, temp_path)
+                if claimed is not None:
+                    joined, file_in_use = claimed
+                    joined_archive_id = joined.id
+                    archive = await _start_slicer_resend_run(
+                        db,
+                        joined,
+                        printer_id,
+                        source=temp_path,
+                        print_data=start_print_data,
+                        subtask_id=subtask_id,
+                        started_at=detected_at,
+                        original_filename=start_filename,
+                        logger=logger,
+                        file_in_use=file_in_use,
+                    )
+                    if archive is None:
+                        return
+                else:
+                    archive = await service.archive_print(
+                        printer_id=printer_id,
+                        source_file=temp_path,
+                        print_data=start_print_data,
+                        subtask_id=subtask_id,
+                        started_at=detected_at,
+                        original_filename=start_filename,
+                    )
             except IntegrityError:
                 # archive_print removed the folder it had copied the 3MF into.
                 if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
@@ -6622,41 +6838,55 @@ async def on_print_start(printer_id: int, data: dict):
                         logger.warning(
                             "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
                         )
+                    if archive is None:
+                        # Deleted meanwhile: nothing to register the print for.
+                        return
 
-                if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
+                # Not a joined archive: it is not this print's to remove, and
+                # its adoption already checked the printer.
+                if joined_archive_id is None and await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
                     return
 
                 # Track this active print (use both original filename and downloaded filename)
                 _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
                 await _open_run_for(archive_id, printer_id, subtask_id)
 
-                logger.info("Created archive %s for %s", archive.id, downloaded_filename)
+                if joined_archive_id is not None:
+                    logger.info(
+                        "Added the print of %s to archive %s: the same G-code was sent again",
+                        downloaded_filename,
+                        archive_id,
+                    )
+                else:
+                    logger.info("Created archive %s for %s", archive.id, downloaded_filename)
 
                 _maybe_start_layer_timelapse(printer, printer_id, archive.id)
 
                 # Record starting energy from smart plug if available (#941: persisted column)
                 await _record_energy_start(archive, printer_id, db, context="auto-archive")
 
-                await ws_manager.send_archive_created(
-                    {
-                        "id": archive.id,
-                        "printer_id": archive.printer_id,
-                        "filename": archive.filename,
-                        "print_name": archive.print_name,
-                        "status": archive.status,
-                    }
-                )
+                archive_event = {
+                    "id": archive.id,
+                    "printer_id": archive.printer_id,
+                    "filename": archive.filename,
+                    "print_name": archive.print_name,
+                    "status": archive.status,
+                }
+                if joined_archive_id is not None:
+                    await ws_manager.send_archive_updated(archive_event)
+                else:
+                    await ws_manager.send_archive_created(archive_event)
 
-                # MQTT relay - publish archive created
-                try:
-                    await mqtt_relay.on_archive_created(
-                        archive_id=archive.id,
-                        print_name=archive.print_name,
-                        printer_name=printer.name,
-                        status=archive.status,
-                    )
-                except Exception:
-                    pass  # Don't fail if MQTT fails
+                    # MQTT relay - publish archive created
+                    try:
+                        await mqtt_relay.on_archive_created(
+                            archive_id=archive.id,
+                            print_name=archive.print_name or "",
+                            printer_name=printer.name if printer else "",
+                            status=archive.status,
+                        )
+                    except Exception:
+                        pass  # Don't fail if MQTT fails
 
                 # Send notification with archive data (new archive created)
                 if not notification_sent:
@@ -6726,6 +6956,10 @@ async def on_print_start(printer_id: int, data: dict):
                 await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
                 await _forget_if_printer_gone(printer_id)
         finally:
+            if joined_archive_id is not None:
+                from backend.app.services import archive_work
+
+                archive_work.release(joined_archive_id)
             # Keep temp_path around until print completes so the cover endpoint
             # can reuse it (#972). Cache eviction in on_print_complete deletes
             # the file. If the cache entry was evicted early (file vanished),
@@ -12080,6 +12314,12 @@ async def lifespan(app: FastAPI):
     global _plate_estimates_task
     _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
 
+    # The G-code fingerprint of archives made before it was kept (#1634), read
+    # from their files in the background: until then a slice sent again from
+    # the slicer archives anew, as before.
+    global _gcode_hashes_task
+    _gcode_hashes_task = asyncio.create_task(_fill_gcode_hashes())
+
     # Register an app-scoped httpx client for Bambu Cloud services so
     # per-request BambuCloudService instances reuse the same connection pool
     # (important for routes like /cloud/filament-info that chain many
@@ -12571,6 +12811,8 @@ async def lifespan(app: FastAPI):
     stop_auth_cleanup()
     if _plate_estimates_task is not None and not _plate_estimates_task.done():
         _plate_estimates_task.cancel()
+    if _gcode_hashes_task is not None and not _gcode_hashes_task.done():
+        _gcode_hashes_task.cancel()
     from backend.app.services import announcements as announcements_service
 
     announcements_service.stop()

+ 2 - 1
backend/app/models/__init__.py

@@ -22,7 +22,7 @@ from backend.app.models.local_preset import LocalPreset
 from backend.app.models.location import Location
 from backend.app.models.location_ha_sensor import LocationHASensor
 from backend.app.models.long_lived_token import LongLivedToken
-from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
+from backend.app.models.maintenance import MaintenanceHistory, MaintenanceLogEntry, MaintenanceType, PrinterMaintenance
 from backend.app.models.notification import NotificationLog
 from backend.app.models.notification_live_activity import NotificationLiveActivity
 from backend.app.models.notification_lock_screen_widget import NotificationLockScreenWidget
@@ -68,6 +68,7 @@ __all__ = [
     "MaintenanceType",
     "PrinterMaintenance",
     "MaintenanceHistory",
+    "MaintenanceLogEntry",
     "KProfileNote",
     "NotificationTemplate",
     "NotificationLog",

+ 4 - 0
backend/app/models/archive.py

@@ -29,6 +29,10 @@ class PrintArchive(Base):
     file_path: Mapped[str] = mapped_column(String(500))
     file_size: Mapped[int] = mapped_column(Integer)
     content_hash: Mapped[str | None] = mapped_column(String(64))  # SHA256 hash for duplicate detection
+    # SHA256 of the file's G-code only (#1634): a slice sent again from the
+    # slicer, in a new 3MF, adds a run to this archive. "" = read, no G-code;
+    # NULL = not read yet. See services/archive_gcode_hash.
+    gcode_hash: Mapped[str | None] = mapped_column(String(64), index=True)
     thumbnail_path: Mapped[str | None] = mapped_column(String(500))
     timelapse_path: Mapped[str | None] = mapped_column(String(500))
     # The plate whose run produced ``timelapse_path`` (#3275). Every plate of a

+ 36 - 0
backend/app/models/maintenance.py

@@ -78,5 +78,41 @@ class MaintenanceHistory(Base):
     printer_maintenance: Mapped["PrinterMaintenance"] = relationship(back_populates="history")
 
 
+class MaintenanceLogEntry(Base):
+    """One maintenance reset, kept as the audit log of a printer.
+
+    Unlike ``maintenance_history`` (which goes with its printer task), an entry
+    outlives the printer, the task and the user: their names are stored as
+    they were at the reset, and the links to them are SET NULL on delete. An
+    entry whose printer is gone is still in the fleet-wide export.
+    """
+
+    __tablename__ = "maintenance_log_entries"
+
+    id: Mapped[int] = mapped_column(primary_key=True)
+    printer_id: Mapped[int | None] = mapped_column(
+        ForeignKey("printers.id", ondelete="SET NULL"), nullable=True, index=True
+    )
+    printer_name: Mapped[str] = mapped_column(String(255))
+    maintenance_type_id: Mapped[int | None] = mapped_column(
+        ForeignKey("maintenance_types.id", ondelete="SET NULL"), nullable=True, index=True
+    )
+    maintenance_type_name: Mapped[str] = mapped_column(String(100))
+    hours_at_maintenance: Mapped[float] = mapped_column(Float, default=0.0)
+    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
+    performed_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
+    # NULL when authentication is off.
+    performed_by_username: Mapped[str | None] = mapped_column(String(100), nullable=True)
+    performed_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), index=True)
+    # The maintenance_history row written with it. That row goes with its
+    # printer task, so the link is SET NULL: left dangling, SQLite would give
+    # its id to the next reset, possibly another printer's, and deleting this
+    # entry would delete that reset's history. The upgrade copies history rows
+    # not yet here.
+    history_id: Mapped[int | None] = mapped_column(
+        ForeignKey("maintenance_history.id", ondelete="SET NULL"), nullable=True, index=True
+    )
+
+
 # Import at end to avoid circular imports
 from backend.app.models.printer import Printer  # noqa: E402

+ 4 - 1
backend/app/models/printer.py

@@ -1,6 +1,6 @@
 from datetime import datetime
 
-from sqlalchemy import JSON, Boolean, DateTime, Float, String, false, func
+from sqlalchemy import JSON, Boolean, DateTime, Float, Integer, String, false, func
 from sqlalchemy.orm import Mapped, mapped_column, relationship
 
 from backend.app.core.database import Base
@@ -25,6 +25,9 @@ class Printer(Base):
     # What an hour of printing costs in wear on this machine (#694). Empty or 0
     # leaves wear cost off for the printer.
     wear_cost_per_hour: Mapped[float | None] = mapped_column(Float, nullable=True)
+    # Place in the order "Any model" jobs pick printers when Settings > Queue >
+    # printer order is "priority" (#2915): lowest first, empty last, ties by id.
+    dispatch_priority: Mapped[int | None] = mapped_column(Integer, nullable=True)
     runtime_seconds: Mapped[int] = mapped_column(
         default=0
     )  # Accumulated active runtime (RUNNING state only — see #1521)

+ 7 - 0
backend/app/models/smart_plug.py

@@ -39,6 +39,13 @@ class SmartPlug(Base):
     mqtt_energy_topic: Mapped[str | None] = mapped_column(String(200), nullable=True)  # Topic for energy data
     mqtt_energy_path: Mapped[str | None] = mapped_column(String(100), nullable=True)  # e.g., "energy_l1"
     mqtt_energy_multiplier: Mapped[float] = mapped_column(Float, default=1.0)  # Unit conversion for energy
+    # Lifetime counter that never resets, read from the energy topic (#3582).
+    # A Tasmota publishes ENERGY.Today and ENERGY.Total in the same SENSOR
+    # message. Per-print energy is the difference of two readings, so it needs
+    # this counter: a daily one drops back to zero at midnight and loses the
+    # print. Unset, the energy path is still used as both, as before.
+    mqtt_energy_total_path: Mapped[str | None] = mapped_column(String(100), nullable=True)
+    mqtt_energy_total_multiplier: Mapped[float] = mapped_column(Float, nullable=False, server_default="1.0")
 
     # State monitoring
     mqtt_state_topic: Mapped[str | None] = mapped_column(String(200), nullable=True)  # Topic for state data

+ 4 - 0
backend/app/models/spool_assignment.py

@@ -18,6 +18,10 @@ class SpoolAssignment(Base):
     tray_id: Mapped[int] = mapped_column(Integer)  # 0-3
     fingerprint_color: Mapped[str | None] = mapped_column(String(8))  # tray_color snapshot
     fingerprint_type: Mapped[str | None] = mapped_column(String(50))  # tray_type snapshot
+    # Who assigned it from the inventory route: the signed-in user, or an API
+    # key's owner. The replay on insert resolves a custom cloud preset with this
+    # user's cloud sign-in; it has none of its own (#3519).
+    assigned_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
     created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
 
     spool: Mapped["Spool"] = relationship(back_populates="assignments")

+ 14 - 1
backend/app/models/user.py

@@ -13,6 +13,9 @@ if TYPE_CHECKING:
     from backend.app.models.group import Group
     from backend.app.models.user_email_pref import UserEmailPreference
 
+# The system group whose members are admins.
+ADMIN_GROUP_NAME = "Administrators"
+
 
 class User(Base):
     """User model for authentication and authorization.
@@ -100,7 +103,17 @@ class User(Base):
         """
         if self.role == "admin":
             return True
-        return any(g.name == "Administrators" for g in self.groups)
+        return any(g.name == ADMIN_GROUP_NAME for g in self.groups)
+
+    def sync_role_to_groups(self) -> None:
+        """Make the legacy ``role`` say what the groups say.
+
+        ``is_admin`` honours either, so a user moved out of Administrators
+        whose role still read "admin" stayed an admin, with nothing in the UI
+        to change it (#3533). Call after every change to ``groups``; needs
+        them loaded.
+        """
+        self.role = "admin" if any(g.name == ADMIN_GROUP_NAME for g in self.groups) else "user"
 
     def get_permissions(self) -> set[str]:
         """Get all permissions from all groups the user belongs to.

+ 7 - 0
backend/app/schemas/archive.py

@@ -180,6 +180,13 @@ class ArchiveResponse(BaseModel):
     total_filament_actual_grams: float | None = None
     successful_run_count: int = 0
     failed_run_count: int = 0
+    # What all its runs cost, summed as Statistics does (#3609). The archive's
+    # own cost / energy_cost stay the file's and the first run's (#1378,
+    # #2614). None where no run has the figure.
+    total_cost: float | None = None
+    total_energy_kwh: float | None = None
+    total_energy_cost: float | None = None
+    total_wear_cost: float | None = None
 
     @model_validator(mode="after")
     def compute_object_count(self) -> "ArchiveResponse":

+ 40 - 2
backend/app/schemas/maintenance.py

@@ -2,7 +2,7 @@
 
 from datetime import datetime
 
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, field_validator
 
 from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
 
@@ -128,7 +128,45 @@ class PrinterMaintenanceOverview(BaseModel):
     warning_count: int
 
 
+# Generous: the endpoint took notes of any length before the maintenance log,
+# and automations (Home Assistant) post whole reports; this only bounds a row.
+MAINTENANCE_NOTES_MAX_LENGTH = 10000
+
+
 class PerformMaintenanceRequest(BaseModel):
     """Request to mark maintenance as performed."""
 
-    notes: str | None = None
+    # The optional comment logged with the reset.
+    notes: str | None = Field(default=None, max_length=MAINTENANCE_NOTES_MAX_LENGTH)
+
+    @field_validator("notes", mode="before")
+    @classmethod
+    def _trim_notes(cls, value: object) -> object:
+        """Trimmed before the length check, so surrounding whitespace never
+        counts against the limit; blank is no comment."""
+        if isinstance(value, str):
+            return value.strip() or None
+        return value
+
+
+class MaintenanceLogEntryResponse(BaseModel):
+    """One reset in a printer's maintenance log."""
+
+    id: int
+    printer_id: int | None  # None once the printer is deleted
+    printer_name: str
+    maintenance_type_id: int | None  # None once the custom task is deleted
+    maintenance_type_name: str
+    hours_at_maintenance: float
+    notes: str | None
+    performed_by_id: int | None
+    performed_by_username: str | None  # None when authentication was off
+    performed_at: datetime
+
+    class Config:
+        from_attributes = True
+
+
+class MaintenanceLogPage(BaseModel):
+    items: list[MaintenanceLogEntryResponse]
+    total: int

+ 4 - 0
backend/app/schemas/printer.py

@@ -181,6 +181,9 @@ class PrinterUpdate(IgnoresNullForRequiredColumns):
     print_hours_offset: float | None = None
     # Wear cost per printing hour (#694); null or 0 turns it off.
     wear_cost_per_hour: float | None = Field(default=None, ge=0, le=100000)
+    # Place in the pick order of "Any model" jobs when the order setting is "priority"
+    # (#2915); lowest first, null last.
+    dispatch_priority: int | None = Field(default=None, ge=0, le=100000)
     external_camera_url: str | None = None
     external_camera_type: str | None = None
     external_camera_enabled: bool | None = None
@@ -204,6 +207,7 @@ class PrinterResponse(PrinterBase):
     supports_nozzle_flow_type: bool = True
     print_hours_offset: float = 0.0
     wear_cost_per_hour: float | None = None  # #694
+    dispatch_priority: int | None = None  # #2915
     external_camera_url: str | None = None
     external_camera_type: str | None = None
     external_camera_enabled: bool = False

+ 8 - 0
backend/app/schemas/settings.py

@@ -491,6 +491,13 @@ class AppSettings(BaseModel):
         default=False,
         description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
     )
+    model_dispatch_order: Literal["fewest_hours", "most_hours", "least_recently_used", "priority"] = Field(
+        default="fewest_hours",
+        description=(
+            "Which printer an 'Any model' job takes when several can run it (#2915): the one with the fewest "
+            "print hours, the most, the one idle the longest, or the first by the printers' own priority."
+        ),
+    )
     queue_max_concurrent_uploads: int = Field(
         default=4,
         ge=1,
@@ -825,6 +832,7 @@ class AppSettingsUpdate(BaseModel):
     # Capped by camera_light.MAX_DELAY_SECONDS: the finish photo's budget
     # has no more to spare.
     camera_light_delay: float | None = Field(default=None, ge=0, le=5)
+    model_dispatch_order: Literal["fewest_hours", "most_hours", "least_recently_used", "priority"] | None = None
     preferred_slicer: str | None = None
     open_in_slicer: str | None = None
     slice_engine: str | None = None

+ 9 - 0
backend/app/schemas/smart_plug.py

@@ -47,6 +47,10 @@ class SmartPlugBase(BaseModel):
     mqtt_energy_topic: str | None = Field(default=None, max_length=200)  # Topic for energy data
     mqtt_energy_path: str | None = Field(default=None, max_length=100)  # e.g., "energy_l1"
     mqtt_energy_multiplier: float = Field(default=1.0, gt=0, le=10000)  # Unit conversion for energy
+    # Lifetime counter on the energy topic that never resets (#3582), e.g.
+    # Tasmota's ENERGY.Total. Per-print energy reads it when set.
+    mqtt_energy_total_path: str | None = Field(default=None, max_length=100)
+    mqtt_energy_total_multiplier: float = Field(default=1.0, gt=0, le=10000)
 
     # State monitoring
     mqtt_state_topic: str | None = Field(default=None, max_length=200)  # Topic for state data
@@ -125,6 +129,9 @@ class SmartPlugBase(BaseModel):
             # At least one data source must be configured (path is optional)
             if not has_power and not has_energy and not has_state:
                 raise ValueError("At least one MQTT topic must be configured for power, energy, or state monitoring")
+            # The lifetime counter is read from the energy topic's JSON.
+            if (self.mqtt_energy_total_path or "").strip() and not (self.mqtt_energy_topic or self.mqtt_topic):
+                raise ValueError("The lifetime energy path needs an energy topic")
         if self.plug_type == "rest":
             if not self.rest_on_url and not self.rest_off_url:
                 raise ValueError("At least one of ON URL or OFF URL is required for REST plugs")
@@ -156,6 +163,8 @@ class SmartPlugUpdate(IgnoresNullForRequiredColumns):
     mqtt_energy_topic: str | None = None
     mqtt_energy_path: str | None = None
     mqtt_energy_multiplier: float | None = Field(default=None, gt=0, le=10000)
+    mqtt_energy_total_path: str | None = None
+    mqtt_energy_total_multiplier: float | None = Field(default=None, gt=0, le=10000)
     # MQTT state fields
     mqtt_state_topic: str | None = None
     mqtt_state_path: str | None = None

+ 146 - 5
backend/app/services/archive.py

@@ -1,3 +1,4 @@
+import asyncio
 import hashlib
 import html
 import json
@@ -1315,6 +1316,7 @@ class ArchiveService:
         slicer_ams_mapping_printer_id: int | None = None,
         update_archive_id: int | None = None,
         started_at: datetime | None = None,
+        replace_archive_id: int | None = None,
     ) -> PrintArchive | None:
         """Archive a 3MF file with metadata.
 
@@ -1365,6 +1367,14 @@ class ArchiveService:
                 better to say about them.
             started_at: When the print started, for a "printing" archive whose 3MF
                 was downloaded after the start (#3327). Defaults to now.
+            replace_archive_id: Put this file in place of an existing archive's: the
+                same slice sent again from the slicer (#1634, same G-code in a new
+                3MF). The file goes into the archive's own folder, where its photos
+                and timelapses are, and the old one is deleted. Everything read from
+                the file is the new one's; what belongs to the archive (owner,
+                project, notes, tags, photos, runs, a saved AMS mapping) stays, and so
+                does a name set by hand. Status and start are the caller's: the run
+                is opened as for any print of an existing archive.
         """
         # Verify printer exists if specified
         if printer_id is not None:
@@ -1382,6 +1392,18 @@ class ArchiveService:
         archive_dir = (
             settings.archive_dir / printer_folder / archive_name
         )  # SEC-PATH-OK: printer_folder = str(int|None) → digits or "unassigned"; archive_name = f"{timestamp}_{display_stem}" where resolve_display_stem strips path components via Path(filename).name
+        # A slicer resend replacing an archive's file (#1634): into that
+        # archive's folder, which holds its photos and timelapses and which
+        # deleting it removes. One without a file (restored from a backup, a
+        # fallback) gets a new folder, as a fallback given its 3MF does.
+        replacing: PrintArchive | None = None
+        if replace_archive_id is not None:
+            replacing = await self.db.get(PrintArchive, replace_archive_id)
+            if replacing is None:
+                logger.warning("archive_print: archive %s to replace the file of no longer exists", replace_archive_id)
+                return None
+            if replacing.file_path:
+                archive_dir = resolve_archive_dir(replacing)
         # Removed again if the row is not written (below); only a folder this
         # call created, never another archive's of the same name.
         created_archive_dir = not archive_dir.exists()
@@ -1391,7 +1413,12 @@ class ArchiveService:
         # short-read quirk that silently truncated 3MF archives on some
         # platforms — see _copy_and_fsync and #1032).
         dest_file = archive_dir / source_file.name
-        _copy_and_fsync(source_file, dest_file)
+        # Over the replaced archive's file of the same name only once the copy
+        # is whole and checked, so a failed copy leaves the archive its file.
+        copy_target = dest_file
+        if replacing is not None and dest_file.exists():
+            copy_target = archive_dir / f".replacing-{source_file.name}"
+        _copy_and_fsync(source_file, copy_target)
 
         # If we just archived a 3MF, verify the dest is a valid ZIP before
         # going any further. Staying quiet here is how #1032 escaped review —
@@ -1400,18 +1427,18 @@ class ArchiveService:
         if (
             source_file.suffix.lower() == ".3mf"
             and zipfile.is_zipfile(source_file)
-            and not zipfile.is_zipfile(dest_file)
+            and not zipfile.is_zipfile(copy_target)
         ):
             try:
                 src_size = source_file.stat().st_size
-                dst_size = dest_file.stat().st_size
+                dst_size = copy_target.stat().st_size
             except OSError:
                 src_size = dst_size = -1
             logger.error(
                 "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
                 source_file,
                 src_size,
-                dest_file,
+                copy_target,
                 dst_size,
             )
             # Narrow cleanup: remove only the truncated file and the archive
@@ -1419,7 +1446,7 @@ class ArchiveService:
             # exist_ok=True so it could in theory pre-date this call (e.g.
             # same-second same-filename collision); rmtree would be too broad.
             try:
-                dest_file.unlink()
+                copy_target.unlink()
             except OSError:
                 pass
             try:
@@ -1428,8 +1455,16 @@ class ArchiveService:
                 pass  # directory not empty — leave untouched
             return None
 
+        if copy_target != dest_file:
+            os.replace(copy_target, dest_file)
+
         # Compute content hash for duplicate detection
         content_hash = self.compute_file_hash(dest_file)
+        # And of its G-code alone, so the same slice sent again in a new 3MF
+        # adds a run to this archive (#1634). Off the event loop: it unzips.
+        from backend.app.services.archive_gcode_hash import NO_GCODE, gcode_fingerprint
+
+        gcode_hash = await asyncio.to_thread(gcode_fingerprint, dest_file) or NO_GCODE
 
         # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
         plate_number = None
@@ -1503,6 +1538,25 @@ class ArchiveService:
 
         # Recovery of an existing fallback row: assign the freshly-parsed values
         # onto it rather than adding a second archive for the same print (#2957).
+        if replacing is not None:
+            return await self._take_replacement_file(
+                replacing,
+                dest_file=dest_file,
+                filename=original_filename or source_file.name,
+                print_name=(
+                    clean_display_name(display_stem)
+                    if prefer_filename_for_name
+                    else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
+                ),
+                content_hash=content_hash,
+                gcode_hash=gcode_hash,
+                thumbnail_path=thumbnail_path,
+                metadata=metadata,
+                cost=cost,
+                quantity=quantity,
+                plate_id=plate_id,
+            )
+
         if update_archive_id is not None:
             existing = await self.db.get(PrintArchive, update_archive_id)
             if existing is None:
@@ -1526,6 +1580,7 @@ class ArchiveService:
             existing.file_path = str(dest_file.relative_to(settings.base_dir))
             existing.file_size = dest_file.stat().st_size
             existing.content_hash = content_hash
+            existing.gcode_hash = gcode_hash
             existing.thumbnail_path = thumbnail_path
             existing.print_name = (
                 clean_display_name(display_stem)
@@ -1576,6 +1631,7 @@ class ArchiveService:
             file_path=str(dest_file.relative_to(settings.base_dir)),
             file_size=dest_file.stat().st_size,
             content_hash=content_hash,
+            gcode_hash=gcode_hash,
             thumbnail_path=thumbnail_path,
             # clean_display_name because the 3MF's own metadata reaches this
             # verbatim, and a control character in it renders nowhere and
@@ -1633,6 +1689,91 @@ class ArchiveService:
 
         return archive
 
+    async def _take_replacement_file(
+        self,
+        archive: PrintArchive,
+        *,
+        dest_file: Path,
+        filename: str,
+        print_name: str | None,
+        content_hash: str,
+        gcode_hash: str,
+        thumbnail_path: str | None,
+        metadata: dict,
+        cost: float | None,
+        quantity: int,
+        plate_id: int | None,
+    ) -> PrintArchive:
+        """Give ``archive`` the file just placed at ``dest_file`` in place of its
+        own (``archive_print(replace_archive_id=...)``, #1634), and delete the
+        old one once that is committed."""
+        old_file = (
+            settings.base_dir / archive.file_path if archive.file_path else None
+        )  # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
+        old_extra = archive.extra_data or {}
+
+        # A name the old file gave follows the file; one set by hand stays.
+        # Both ways archive_print names a file: its 3MF title, or its file name.
+        generated = {
+            clean_display_name(old_extra.get("print_name")),
+            clean_display_name(resolve_display_stem(archive.filename)) if archive.filename else None,
+        } - {None}
+        if print_name and (not archive.print_name or archive.print_name in generated):
+            archive.print_name = print_name
+
+        archive.filename = filename
+        archive.file_path = str(dest_file.relative_to(settings.base_dir))
+        archive.file_size = dest_file.stat().st_size
+        archive.content_hash = content_hash
+        archive.gcode_hash = gcode_hash
+        # Earlier runs point at the old thumbnail by path: one of another name
+        # stays in the folder for them, one of the same name now shows the new
+        # file's (the same slice).
+        if thumbnail_path is not None:
+            archive.thumbnail_path = thumbnail_path
+        # The same G-code, so what the new 3MF leaves out the old one said.
+        for field in (
+            "print_time_seconds",
+            "filament_used_grams",
+            "filament_type",
+            "filament_color",
+            "layer_height",
+            "total_layers",
+            "nozzle_diameter",
+            "bed_temperature",
+            "bed_type",
+            "nozzle_temperature",
+            "sliced_for_model",
+            "makerworld_url",
+            "designer",
+        ):
+            value = metadata.get(field)
+            if value is not None:
+                setattr(archive, field, value)
+        if cost is not None:
+            archive.cost = cost
+        archive.quantity = quantity
+        # The new file's description. Of what is not the file's, only the saved
+        # AMS pick is the archive's (a pause warning is its last run's).
+        extra = dict(metadata)
+        if "slicer_ams_mapping" in old_extra:
+            extra["slicer_ams_mapping"] = old_extra["slicer_ams_mapping"]
+        archive.extra_data = extra
+        if plate_id is not None:
+            archive.plate_id = plate_id
+        from backend.app.services.print_cost_estimate import refresh_plate_estimates
+
+        refresh_plate_estimates(archive)
+        await self.db.commit()
+        await self.db.refresh(archive)
+
+        if old_file is not None and old_file != dest_file:
+            try:
+                old_file.unlink(missing_ok=True)
+            except OSError as exc:
+                logger.warning("Could not delete the replaced file %s of archive %s: %s", old_file, archive.id, exc)
+        return archive
+
     async def get_archive(self, archive_id: int) -> PrintArchive | None:
         """Get an archive by ID with relationships loaded."""
         from sqlalchemy.orm import selectinload

+ 134 - 0
backend/app/services/archive_gcode_hash.py

@@ -0,0 +1,134 @@
+"""The G-code fingerprint of an archive's file (#1634).
+
+``content_hash`` is the SHA256 of the archived file's bytes. A slicer that sends
+the same slice again writes a new 3MF around it (zip entry times, metadata), so
+the two files differ in every byte but their G-code. ``gcode_hash`` is the
+SHA256 of the G-code alone: every ``Metadata/plate_N.gcode`` of a 3MF in plate
+order, each with its name and size, or the bytes of a plain ``.gcode`` file.
+
+A print sent from the slicer whose G-code matches an archive adds a run to that
+archive instead of archiving the file again (``main._claim_slicer_resend_archive``).
+A file sliced again with other settings has other G-code and stays separate.
+OrcaSlicer writes the slicing time into the G-code header, so with it only the
+same slice sent again matches, not the same model sliced again.
+
+``NO_GCODE`` ("") marks an archive read without G-code (no file, not a sliced
+file, unreadable), so it is read once; NULL is not read yet. Reading unzips the
+file, which takes seconds for a large 3MF: callers on the event loop go through
+``asyncio.to_thread`` (``refresh_gcode_hash_async``).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import logging
+import re
+import zipfile
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select, update
+
+from backend.app.core.config import settings
+from backend.app.models.archive import PrintArchive
+
+logger = logging.getLogger(__name__)
+
+NO_GCODE = ""
+
+_PLATE_GCODE = re.compile(r"^Metadata/plate_(\d+)\.gcode$")
+_CHUNK = 1 << 20
+
+
+def gcode_fingerprint(path: Path) -> str | None:
+    """SHA256 of the G-code in the file at ``path``, or None when it holds none
+    or cannot be read."""
+    try:
+        if zipfile.is_zipfile(path):
+            with zipfile.ZipFile(path) as zf:
+                plates = sorted(
+                    (int(m.group(1)), info)
+                    for info in zf.infolist()
+                    if (m := _PLATE_GCODE.match(info.filename)) and not info.is_dir()
+                )
+                if not plates:
+                    return None
+                digest = hashlib.sha256()
+                for _number, info in plates:
+                    # Name and length first: two files splitting the same bytes
+                    # over other plates are not one.
+                    digest.update(f"{info.filename}\0{info.file_size}\0".encode())
+                    with zf.open(info) as handle:
+                        for chunk in iter(lambda: handle.read(_CHUNK), b""):
+                            digest.update(chunk)
+                return digest.hexdigest()
+        if path.suffix.lower() == ".gcode":
+            digest = hashlib.sha256()
+            with path.open("rb") as handle:
+                for chunk in iter(lambda: handle.read(_CHUNK), b""):
+                    digest.update(chunk)
+            return digest.hexdigest()
+    except (OSError, zipfile.BadZipFile, zipfile.LargeZipFile, RuntimeError, ValueError) as exc:
+        logger.debug("G-code fingerprint of %s failed: %s", path, exc)
+    return None
+
+
+def read_gcode_hash(archive: Any) -> str | None:
+    """The G-code fingerprint of the archive's file on disk: ``NO_GCODE`` for a
+    file without readable G-code, None when there is no file to read."""
+    if not archive.file_path:
+        return None
+    path = settings.base_dir / archive.file_path  # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
+    if not path.is_file():
+        return None
+    return gcode_fingerprint(path) or NO_GCODE
+
+
+def refresh_gcode_hash(archive: PrintArchive) -> None:
+    """Read the G-code fingerprint of the archive's file into it: when the
+    archive is made, or given a file. Does not commit."""
+    fingerprint = read_gcode_hash(archive)
+    if fingerprint is not None:
+        archive.gcode_hash = fingerprint
+
+
+async def refresh_gcode_hash_async(archive: PrintArchive) -> None:
+    """``refresh_gcode_hash`` with the read off the event loop."""
+    fingerprint = await asyncio.to_thread(read_gcode_hash, archive)
+    if fingerprint is not None:
+        archive.gcode_hash = fingerprint
+
+
+async def fill_gcode_hashes(session_factory, batch: int = 100) -> int:
+    """Give every archive not yet read its G-code fingerprint, from its file.
+    An archive whose file is missing or unreadable gets ``NO_GCODE``: it is
+    read once. Returns how many were read.
+
+    Each is written only while it is still unread: an archive given its file
+    meanwhile (``refresh_gcode_hash``) keeps what that read."""
+    filled = 0
+    last_id = 0
+    while True:
+        async with session_factory() as db:
+            rows = (
+                await db.execute(
+                    select(PrintArchive.id, PrintArchive.file_path)
+                    .where(PrintArchive.gcode_hash.is_(None), PrintArchive.id > last_id)
+                    .order_by(PrintArchive.id)
+                    .limit(batch)
+                )
+            ).all()
+            if not rows:
+                return filled
+            for row in rows:
+                fingerprint = await asyncio.to_thread(read_gcode_hash, row)
+                written = await db.execute(
+                    update(PrintArchive)
+                    .where(PrintArchive.id == row.id, PrintArchive.gcode_hash.is_(None))
+                    .values(gcode_hash=fingerprint if fingerprint is not None else NO_GCODE)
+                    .execution_options(synchronize_session=False)
+                )
+                filled += written.rowcount or 0
+            last_id = rows[-1].id
+            await db.commit()

+ 3 - 0
backend/app/services/archive_merge.py

@@ -42,6 +42,7 @@ from backend.app.models.archive_alias import ArchiveAlias
 from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
 from backend.app.models.print_queue import PrintQueueItem
 from backend.app.services import archive_work
+from backend.app.services.archive_gcode_hash import refresh_gcode_hash_async
 from backend.app.services.print_cost_estimate import refresh_plate_estimates
 from backend.app.utils.archive_paths import archive_dir, archive_photos_dir, find_archive_photo
 from backend.app.utils.local_time import utcnow_naive
@@ -542,6 +543,8 @@ async def _merge(
             # The same file (one hash), but the survivor's was missing: its
             # plates are read from the one it takes over (#3375).
             refresh_plate_estimates(survivor)
+            # And its G-code, which the missing file could not give (#1634).
+            await refresh_gcode_hash_async(survivor)
         for run in runs[archive.id]:
             if run.photos:
                 run.photos = [photos[p] for p in run.photos if p in photos]

+ 25 - 1
backend/app/services/bambu_cloud.py

@@ -272,6 +272,30 @@ def _cloud_json(response: httpx.Response):
         ) from None
 
 
+# The preset types in the cloud's listing, under the names it uses for them.
+_SLICER_SETTING_TYPES = ("filament", "printer", "print")
+
+
+def _slicer_settings_listing(data: object) -> dict:
+    """The cloud's preset listing with every type a dict and its ``private``
+    and ``public`` lists always lists of dicts (#3593).
+
+    The cloud sends ``null`` for a type, or for one of its lists, when the
+    account has nothing there. Every caller reads the listing as nested dicts,
+    so a null here took down the Slice dialog's preset list for an account
+    with no presets of one type.
+    """
+    listing = dict(data) if isinstance(data, dict) else {}
+    for key in _SLICER_SETTING_TYPES:
+        section = listing.get(key)
+        section = dict(section) if isinstance(section, dict) else {}
+        for tier in ("private", "public"):
+            entries = section.get(tier)
+            section[tier] = [e for e in entries if isinstance(e, dict)] if isinstance(entries, list) else []
+        listing[key] = section
+    return listing
+
+
 _shared_http_client: httpx.AsyncClient | None = None
 
 
@@ -836,7 +860,7 @@ class BambuCloudService:
             if await self._note_response(response):
                 raise BambuCloudAuthError("Bambu Cloud session expired")
             if response.status_code == 200:
-                return data
+                return _slicer_settings_listing(data)
 
             raise BambuCloudError(f"Failed to get settings: {response.status_code}")
 

+ 64 - 17
backend/app/services/bambu_ftp.py

@@ -705,6 +705,15 @@ class BambuFTPClient:
             return False
         return True
 
+    @classmethod
+    def clear_handshake_cooloff(cls, ip_address: str) -> None:
+        """End *ip_address*'s handshake cool-off early, for a printer that has
+        just reconnected (#3563): a cool-off from before a restart says nothing
+        about the printer now."""
+        cls._handshake_blocked_until.pop(ip_address, None)
+        cls._handshake_skip_logged.pop(ip_address, None)
+        cls._cleartext_reply.pop(ip_address, None)
+
     def _record_stall(self, what: str) -> None:
         if self.records_handshake_cooloff:
             _record_ftps_stall(self.ip_address, what)
@@ -1300,9 +1309,16 @@ class BambuFTPClient:
                     e,
                     type(e).__name__,
                 )
-                if callback_exception is None:
-                    # A cancelled upload is deleted below; its size says nothing.
-                    self._check_unconfirmed_upload(remote_path, file_size)
+                # A cancelled upload is deleted below; its size says nothing.
+                if callback_exception is None and not self._check_unconfirmed_upload(remote_path, file_size):
+                    # Not complete on the printer: no print command for it.
+                    # NETWORK, so the caller's retry uploads it again (#3538).
+                    self.last_failure = FtpFailure(
+                        FtpFailureKind.NETWORK,
+                        f"{remote_path} did not reach its full size on the printer",
+                        None,
+                    )
+                    return False
 
             if callback_exception is not None:
                 cleanup_result: DeleteResult = DeleteResult.FAILED
@@ -1369,25 +1385,56 @@ class BambuFTPClient:
             self.last_failure = FtpFailure(kind, str(e), code)
             return False
 
-    def _check_unconfirmed_upload(self, remote_path: str, expected_size: int) -> None:
-        """Read an upload's size back when its 226 never came.
-
-        The upload still counts (an H2D can take 30+ s to answer), but a
-        printer that kept a partial file should not go unnoticed. A fresh
-        connection, because this one may be waiting for that late reply.
+    # How long an unconfirmed upload's size is watched for the printer to
+    # finish writing it out (#3538).
+    UNCONFIRMED_SIZE_POLL_INTERVAL = 5.0
+    UNCONFIRMED_SIZE_POLL_TIMEOUT = 120.0
+
+    def _check_unconfirmed_upload(self, remote_path: str, expected_size: int) -> bool:
+        """Read an upload's size back when its 226 never came. True if it may print.
+
+        A fresh connection, because this one may be waiting for that late
+        reply. An A1 can still be writing a large file out when the reply
+        times out: it read 0 bytes 2 s later and the full size minutes after,
+        and the print command sent in between made it refuse the file
+        (#3538). So a short size is read again until it matches or the time
+        runs out; only then is the upload a failure. A size that cannot be
+        read at all says nothing, and the upload counts as before.
         """
         server_size = _size_on_new_connection(self, remote_path)
         if server_size is None:
             logger.warning("FTP upload of %s could not be read back to check its size", remote_path)
-        elif server_size != expected_size:
-            logger.error(
-                "FTP upload of %s is %s bytes on the printer, expected %s: the file may be incomplete",
-                remote_path,
-                server_size,
-                expected_size,
-            )
-        else:
+            return True
+        if server_size == expected_size:
             logger.info("FTP upload of %s verified on a new connection (%s bytes)", remote_path, server_size)
+            return True
+        logger.info(
+            "FTP upload of %s is %s of %s bytes on the printer; waiting for it to finish writing",
+            remote_path,
+            server_size,
+            expected_size,
+        )
+        started = time.monotonic()
+        while time.monotonic() - started < self.UNCONFIRMED_SIZE_POLL_TIMEOUT:
+            time.sleep(self.UNCONFIRMED_SIZE_POLL_INTERVAL)
+            size = _size_on_new_connection(self, remote_path)
+            if size is not None:
+                server_size = size
+            if server_size == expected_size:
+                logger.info(
+                    "FTP upload of %s complete on the printer after %.0fs (%s bytes)",
+                    remote_path,
+                    time.monotonic() - started,
+                    server_size,
+                )
+                return True
+        logger.error(
+            "FTP upload of %s is %s bytes on the printer, expected %s: incomplete, not printing it",
+            remote_path,
+            server_size,
+            expected_size,
+        )
+        return False
 
     def delete_file(self, remote_path: str) -> DeleteResult:
         """Delete a file from the printer.

+ 37 - 2
backend/app/services/bambu_mqtt.py

@@ -1039,6 +1039,11 @@ _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
 # "0500_0007", which matches nothing in any catalog.
 HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
 
+# Command responses whose content the debug log leaves out (#3531). push_status
+# is the printer's status, arriving every second and logged field by field;
+# project_file carries the download URL of a print, which may be a signed one.
+_COMMANDS_LOGGED_BY_NAME_ONLY: frozenset[str] = frozenset({"push_status", "project_file"})
+
 
 @dataclass
 class KProfile:
@@ -1726,6 +1731,10 @@ class BambuMQTTClient:
         self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
         self._logging_enabled: bool = False
         self._last_message_time: float = 0.0  # Track when we last received a message
+        # Bambuddy's own FTP uploads to this printer (#3538): an A1 publishes
+        # nothing while it receives a large file, which is not a stale link.
+        self._uploads_in_flight: int = 0
+        self._last_upload_end: float = 0.0
         # Count of report-topic messages received since the last (re)connect.
         # Lets check_staleness() distinguish "printer never sent a status
         # report" (typically a wrong / mis-cased serial) from a normal quiet
@@ -1906,11 +1915,29 @@ class BambuMQTTClient:
     # Maximum time (seconds) without a message before considering connection stale
     STALE_TIMEOUT = 60.0
 
+    def begin_upload(self) -> None:
+        """Bambuddy starts an FTP upload to this printer (#3538)."""
+        self._uploads_in_flight += 1
+
+    def end_upload(self) -> None:
+        """The upload is over; the printer gets STALE_TIMEOUT from now to speak."""
+        self._uploads_in_flight = max(0, self._uploads_in_flight - 1)
+        self._last_upload_end = time.time()
+
     def is_stale(self) -> bool:
-        """Check if the connection is stale (no messages for too long)."""
+        """Check if the connection is stale (no messages for too long).
+
+        Not while Bambuddy is uploading to the printer, nor within
+        STALE_TIMEOUT after: an A1 says nothing over MQTT while it receives a
+        large file, and the forced reconnect that silence used to trigger
+        landed just before the print command, which then found the printer
+        disconnected and failed the job (#3538).
+        """
         if self._last_message_time == 0:
             return False  # Never received a message yet
-        time_since_last = time.time() - self._last_message_time
+        if self._uploads_in_flight > 0:
+            return False
+        time_since_last = time.time() - max(self._last_message_time, self._last_upload_end)
         return time_since_last > self.STALE_TIMEOUT
 
     def mark_power_off(self) -> bool:
@@ -2845,6 +2872,14 @@ class BambuMQTTClient:
             if "command" in print_data:
                 cmd = print_data.get("command")
                 logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
+                if cmd not in _COMMANDS_LOGGED_BY_NAME_ONLY:
+                    # The printer reports back commands sent from its own
+                    # screen too, and this is the only place their content can
+                    # be seen: H3C Unload All is one command whose fields are
+                    # not documented anywhere (#3531).
+                    logger.debug(
+                        "[%s] %s content: %s", self.serial_number, cmd, json.dumps(print_data, default=str)[:4000]
+                    )
                 if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
                     # INFO, not debug: this is the printer's verdict on a write
                     # the user just made, and it was invisible in support

+ 78 - 6
backend/app/services/export.py

@@ -1,7 +1,9 @@
 import csv
 import io
-from datetime import datetime
-from typing import Any
+import re
+from collections.abc import Sequence
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any
 
 from sqlalchemy import select
 from sqlalchemy.ext.asyncio import AsyncSession
@@ -11,6 +13,36 @@ from backend.app.core.printer_scope import PrinterScope
 from backend.app.models.archive import PrintArchive
 from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
 
+if TYPE_CHECKING:
+    from backend.app.models.maintenance import MaintenanceLogEntry
+
+# A cell starting with one of these is read as a formula by spreadsheet apps,
+# including the full-width forms (= + - @) some normalise to ASCII.
+_FORMULA_PREFIXES = ("=", "+", "-", "@", "=", "+", "-", "@")
+
+
+def _spreadsheet_text(value: Any) -> Any:
+    """A CSV cell as typed: text that starts like a formula gets a leading quote, so it stays text.
+
+    Leading whitespace is looked past (spreadsheets trim it on import), and a
+    value starting with a tab or line break is quoted too. Anything that isn't
+    text is left alone.
+    """
+    if not isinstance(value, str) or not value:
+        return value
+    if value[0] in "\t\r\n" or value.lstrip().startswith(_FORMULA_PREFIXES):
+        return f"'{value}"
+    return value
+
+
+def _xlsx_cell(ws: Any, row: int, column: int, value: Any) -> Any:
+    """Write a worksheet cell; text that starts with "=" is stored as text, not as a formula."""
+    cell = ws.cell(row=row, column=column, value=value)
+    if isinstance(value, str) and cell.data_type == "f":
+        cell.data_type = "s"
+    return cell
+
+
 # What one print of an archive has of its own (archive redesign): in the
 # export, its run's. Everything else is the file's, the archive's.
 _PER_PRINT_FIELDS = frozenset(
@@ -35,6 +67,15 @@ _PER_PRINT_FIELDS = frozenset(
 )
 
 
+def _utc_iso(value: datetime | None) -> str:
+    """A stored (naive UTC) time as ISO 8601 with its zone."""
+    if value is None:
+        return ""
+    if value.tzinfo is not None:
+        value = value.astimezone(timezone.utc).replace(tzinfo=None)
+    return value.replace(microsecond=0).isoformat() + "Z"
+
+
 class ExportService:
     """Service for exporting archive data to CSV/Excel formats."""
 
@@ -363,19 +404,50 @@ class ExportService:
             row.append(value)
         return row
 
+    MAINTENANCE_LOG_HEADERS = ["Performed at (UTC)", "Printer", "Task", "Performed by", "Print hours", "Comment"]
+
+    @classmethod
+    def export_maintenance_log(cls, entries: Sequence["MaintenanceLogEntry"], scope_label: str) -> tuple[bytes, str]:
+        """The maintenance log as CSV, and its file name.
+
+        ``scope_label`` names what the file holds (a printer's name, or
+        "all") in the file name. Text that people typed is written so that a
+        spreadsheet shows it as text, never runs it as a formula; the BOM makes
+        Excel read the file as UTF-8.
+        """
+        rows = [
+            [
+                _utc_iso(entry.performed_at),
+                _spreadsheet_text(entry.printer_name),
+                _spreadsheet_text(entry.maintenance_type_name),
+                _spreadsheet_text(entry.performed_by_username),
+                round(entry.hours_at_maintenance or 0.0, 1),
+                _spreadsheet_text(entry.notes),
+            ]
+            for entry in entries
+        ]
+        output = io.StringIO()
+        output.write("\ufeff")
+        writer = csv.writer(output)
+        writer.writerow(cls.MAINTENANCE_LOG_HEADERS)
+        writer.writerows(rows)
+        slug = re.sub(r"[^\w-]+", "_", scope_label, flags=re.UNICODE).strip("_") or "printer"
+        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+        return output.getvalue().encode("utf-8"), f"maintenance_log_{slug}_{timestamp}.csv"
+
     def _generate_csv(self, headers: list[str], rows: list[list]) -> bytes:
         """Generate CSV file content."""
         output = io.StringIO()
         writer = csv.writer(output)
         writer.writerow(headers)
-        writer.writerows(rows)
+        writer.writerows([[_spreadsheet_text(value) for value in row] for row in rows])
         return output.getvalue().encode("utf-8")
 
     def _generate_csv_simple(self, rows: list[list]) -> bytes:
         """Generate CSV file content from simple rows (no separate headers)."""
         output = io.StringIO()
         writer = csv.writer(output)
-        writer.writerows(rows)
+        writer.writerows([[_spreadsheet_text(value) for value in row] for row in rows])
         return output.getvalue().encode("utf-8")
 
     def _generate_xlsx(self, headers: list[str], rows: list[list], fields: list[str]) -> bytes:
@@ -406,7 +478,7 @@ class ExportService:
         # Write data
         for row_idx, row in enumerate(rows, 2):
             for col_idx, value in enumerate(row, 1):
-                ws.cell(row=row_idx, column=col_idx, value=value)
+                _xlsx_cell(ws, row_idx, col_idx, value)
 
         # Auto-adjust column widths
         for col_idx, _field in enumerate(fields, 1):
@@ -441,7 +513,7 @@ class ExportService:
 
         for row_idx, row in enumerate(rows, 1):
             for col_idx, value in enumerate(row, 1):
-                cell = ws.cell(row=row_idx, column=col_idx, value=value)
+                cell = _xlsx_cell(ws, row_idx, col_idx, value)
                 # Bold section headers
                 if col_idx == 1 and value and isinstance(value, str) and value.endswith(":"):
                     cell.font = bold_font

+ 32 - 30
backend/app/services/firmware_update.py

@@ -353,36 +353,38 @@ class FirmwareUpdateService:
             # Get FTP retry settings
             ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
 
-            if ftp_retry_enabled:
-                success = await with_ftp_retry(
-                    upload_file_async,
-                    ip_address,
-                    access_code,
-                    firmware_path,
-                    remote_path,
-                    progress_callback=on_upload_progress,
-                    socket_timeout=ftp_timeout,
-                    printer_model=model,
-                    # Someone pressed "update firmware" and is watching a
-                    # progress bar. Bounded and user-initiated, like a print
-                    # dispatch, so it does not spend its retries on a cool-off
-                    # meant for the background sweeps (#2898).
-                    respect_handshake_cooloff=False,
-                    max_retries=ftp_retry_count,
-                    retry_delay=ftp_retry_delay,
-                    operation_name=f"Upload firmware to printer {printer_id}",
-                )
-            else:
-                success = await upload_file_async(
-                    ip_address,
-                    access_code,
-                    firmware_path,
-                    remote_path,
-                    progress_callback=on_upload_progress,
-                    socket_timeout=ftp_timeout,
-                    printer_model=model,
-                    respect_handshake_cooloff=False,
-                )
+            # Quiet MQTT while the printer receives the file is no stale link (#3538).
+            with printer_manager.uploading(printer_id):
+                if ftp_retry_enabled:
+                    success = await with_ftp_retry(
+                        upload_file_async,
+                        ip_address,
+                        access_code,
+                        firmware_path,
+                        remote_path,
+                        progress_callback=on_upload_progress,
+                        socket_timeout=ftp_timeout,
+                        printer_model=model,
+                        # Someone pressed "update firmware" and is watching a
+                        # progress bar. Bounded and user-initiated, like a print
+                        # dispatch, so it does not spend its retries on a cool-off
+                        # meant for the background sweeps (#2898).
+                        respect_handshake_cooloff=False,
+                        max_retries=ftp_retry_count,
+                        retry_delay=ftp_retry_delay,
+                        operation_name=f"Upload firmware to printer {printer_id}",
+                    )
+                else:
+                    success = await upload_file_async(
+                        ip_address,
+                        access_code,
+                        firmware_path,
+                        remote_path,
+                        progress_callback=on_upload_progress,
+                        socket_timeout=ftp_timeout,
+                        printer_model=model,
+                        respect_handshake_cooloff=False,
+                    )
 
             if not success:
                 raise Exception("Failed to upload firmware to printer")

+ 103 - 1
backend/app/services/git_providers/github.py

@@ -5,6 +5,7 @@ import json
 import logging
 import re
 from datetime import datetime, timezone
+from urllib.parse import quote
 
 import httpx
 
@@ -378,7 +379,8 @@ class GitHubBackend(GitProviderBackend):
 
             ref_response = await client.get(f"{api_base}/repos/{owner}/{repo}/git/refs/heads/{branch}", headers=headers)
 
-            if ref_response.status_code == 404:
+            empty = self._is_empty_repository(ref_response)
+            if ref_response.status_code == 404 or empty:
                 if not _allow_branch_create:
                     return {
                         "status": "failed",
@@ -387,6 +389,10 @@ class GitHubBackend(GitProviderBackend):
                             "The next scheduled backup will retry."
                         ),
                     }
+                if empty:
+                    return await self._seed_empty_repository(
+                        client, headers, api_base, owner, repo, branch, files, repo_url, token
+                    )
                 return await self._create_branch_and_push(
                     client, headers, api_base, owner, repo, branch, files, repo_url, token
                 )
@@ -565,6 +571,10 @@ class GitHubBackend(GitProviderBackend):
             ref_response = await client.get(
                 f"{api_base}/repos/{owner}/{repo}/git/refs/heads/{default_branch}", headers=headers
             )
+            if self._is_empty_repository(ref_response):
+                return await self._seed_empty_repository(
+                    client, headers, api_base, owner, repo, branch, files, repo_url, token
+                )
             if ref_response.status_code != 200:
                 return await self._create_initial_commit(client, headers, api_base, owner, repo, branch, files)
 
@@ -591,6 +601,98 @@ class GitHubBackend(GitProviderBackend):
             logger.exception("_create_branch_and_push failed for %s/%s branch=%s", owner, repo, branch)
             return {"status": "failed", "message": str(e), "error": str(e)}
 
+    @staticmethod
+    def _is_empty_repository(response: httpx.Response) -> bool:
+        """Whether GitHub refused a Git Data call because the repository has no commits (#3565)."""
+        if response.status_code != 409:
+            return False
+        try:
+            body = response.json()
+        except ValueError:
+            return False
+        message = body.get("message") if isinstance(body, dict) else None
+        return isinstance(message, str) and "repository is empty" in message.lower()
+
+    async def _seed_empty_repository(
+        self,
+        client: httpx.AsyncClient,
+        headers: dict,
+        api_base: str,
+        owner: str,
+        repo: str,
+        branch: str,
+        files: dict,
+        repo_url: str,
+        token: str,
+    ) -> dict:
+        """Give a repository with no commits its first one, then push the rest (#3565).
+
+        GitHub answers every Git Data call -- refs, blobs, trees -- with 409 until a
+        repository has a commit, so the blob/tree path cannot make the first one.
+        The Contents API can: it writes one file and creates the commit and the
+        branch. The other files then go through push_files like any later backup.
+        """
+        if not files:
+            return {"status": "skipped", "message": "No changes to commit", "commit_sha": None, "files_changed": 0}
+        try:
+            path = next(iter(files))
+            content_bytes = json.dumps(files[path], indent=2, default=str).encode("utf-8")
+            payload = {
+                "message": f"Initial Bambuddy backup - {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}",
+                "content": base64.b64encode(content_bytes).decode(),
+                "branch": branch,
+            }
+            url = f"{api_base}/repos/{owner}/{repo}/contents/{quote(path)}"
+            response = await client.put(url, headers=headers, json=payload)
+            on_backup_branch = True
+            if response.status_code in (404, 422):
+                # Should GitHub not create a named branch in a repository that
+                # has none yet, the first commit goes to the default branch and
+                # push_files then branches the backup branch off it.
+                logger.info(
+                    "_seed_empty_repository %s/%s: branch %s refused (HTTP %s), seeding the default branch",
+                    owner,
+                    repo,
+                    branch,
+                    response.status_code,
+                )
+                default_branch_payload = {k: v for k, v in payload.items() if k != "branch"}
+                response = await client.put(url, headers=headers, json=default_branch_payload)
+                on_backup_branch = False
+            if response.status_code != 201:
+                msg = f"Failed to create the first commit (HTTP {response.status_code}): {self._truncated_response_text(response)}"
+                logger.warning("_seed_empty_repository %s/%s: %s", owner, repo, msg)
+                return {"status": "failed", "message": msg}
+
+            commit_sha, err = self._read_sha(response, "commit", "sha")
+            if err:
+                msg = f"Malformed contents response ({err}): {self._truncated_response_text(response)}"
+                logger.warning("_seed_empty_repository %s/%s: %s", owner, repo, msg)
+                return {"status": "failed", "message": msg}
+
+            seeded = {
+                "status": "success",
+                "message": f"Initial backup created - {len(files)} files",
+                "commit_sha": commit_sha,
+                "files_changed": len(files),
+            }
+            if len(files) == 1 and on_backup_branch:
+                return seeded
+
+            logger.info("Re-entering push_files after seeding %s/%s", owner, repo)
+            result = await self.push_files(
+                repo_url, token, branch, files, client, _allow_branch_create=not on_backup_branch
+            )
+            if result.get("status") == "skipped":
+                return seeded
+            if result.get("status") == "success":
+                return {**seeded, "commit_sha": result.get("commit_sha")}
+            return result
+
+        except Exception as e:
+            logger.exception("_seed_empty_repository failed for %s/%s branch=%s", owner, repo, branch)
+            return {"status": "failed", "message": str(e), "error": str(e)}
+
     async def _create_initial_commit(
         self,
         client: httpx.AsyncClient,

+ 1 - 0
backend/app/services/github_backup.py

@@ -901,6 +901,7 @@ class GitHubBackupService:
                 "filename": a.filename,
                 "file_size": a.file_size,
                 "content_hash": a.content_hash,
+                "gcode_hash": a.gcode_hash,
                 "print_name": a.print_name,
                 "print_time_seconds": a.print_time_seconds,
                 "filament_used_grams": a.filament_used_grams,

+ 14 - 0
backend/app/services/github_restore.py

@@ -1686,6 +1686,11 @@ class GitHubRestoreService:
                 file_path="",
                 file_size=entry.get("file_size") or 0,
                 content_hash=entry.get("content_hash"),
+                # The file is not in the backup, so its G-code cannot be read
+                # here: the backup's fingerprint lets a print of the same slice
+                # sent from the slicer join this archive and give it the file
+                # (#1634). Older backups have none, and the fill marks it read.
+                gcode_hash=_gcode_hash_of(entry),
                 **fields,
             )
             created_at = _parse_dt(entry.get("created_at"))
@@ -2740,3 +2745,12 @@ class GitHubRestoreService:
 
 # Singleton instance
 github_restore_service = GitHubRestoreService()
+
+
+_GCODE_HASH = re.compile(r"^[0-9a-f]{64}$")
+
+
+def _gcode_hash_of(entry: dict) -> str | None:
+    """The backed-up G-code fingerprint (#1634), when it is one."""
+    value = entry.get("gcode_hash")
+    return value if isinstance(value, str) and _GCODE_HASH.match(value) else None

+ 171 - 34
backend/app/services/label_renderer.py

@@ -44,16 +44,104 @@ for label-printer software that takes images.
 from __future__ import annotations
 
 import io
+import unicodedata
 from dataclasses import dataclass
 from datetime import date
+from pathlib import Path
 from typing import Literal
 
 import qrcode
 from reportlab.lib.colors import Color, HexColor, black, white
 from reportlab.lib.pagesizes import A4, letter
 from reportlab.lib.units import mm
+from reportlab.pdfbase import pdfmetrics
+from reportlab.pdfbase.ttfonts import TTFont
 from reportlab.pdfgen import canvas as rl_canvas
 
+# Label text is printed in Liberation Sans, embedded in the PDF (#3553). The
+# PDF base fonts (Helvetica) only cover Western European characters, so names
+# in Polish, Czech, Cyrillic or Greek lost letters. Liberation Sans has the
+# same letter widths as Helvetica, so the layout and truncation are unchanged.
+#
+# Liberation Sans has no Chinese, Japanese or Korean, so a name written in one
+# printed as empty boxes, in the PDF and in the preview rasterised from it
+# (#3560). A character the label font lacks is drawn in a fallback font
+# instead: Droid Sans Fallback for Chinese and Japanese, and Noto Sans KR --
+# cut down to Hangul, which Droid lacks -- for Korean. Only the characters a
+# label uses are embedded. Neither has a bold or italic face, so CJK text in a
+# bold or italic line prints regular.
+_FONT_DIR = Path(__file__).resolve().parent.parent / "data" / "fonts"
+FONT_REGULAR = "LabelSans"
+FONT_BOLD = "LabelSans-Bold"
+FONT_ITALIC = "LabelSans-Italic"
+FONT_CJK = "LabelCJK"
+FONT_HANGUL = "LabelHangul"
+# Tried in this order for a character the label font cannot draw.
+_FALLBACK_FONTS = (FONT_CJK, FONT_HANGUL)
+
+
+def _register_fonts() -> None:
+    registered = set(pdfmetrics.getRegisteredFontNames())
+    for name, filename in (
+        (FONT_REGULAR, "LiberationSans-Regular.ttf"),
+        (FONT_BOLD, "LiberationSans-Bold.ttf"),
+        (FONT_ITALIC, "LiberationSans-Italic.ttf"),
+        (FONT_CJK, "DroidSansFallbackFull.ttf"),
+        (FONT_HANGUL, "NotoSansKR-Hangul.ttf"),
+    ):
+        if name not in registered:
+            pdfmetrics.registerFont(TTFont(name, str(_FONT_DIR / filename)))
+
+
+_register_fonts()
+
+
+def _has_glyph(font: str, ch: str) -> bool:
+    # A TrueType font's character map, as reportlab parsed it on registration.
+    return ord(ch) in pdfmetrics.getFont(font).face.charToGlyph  # pyright: ignore[reportAttributeAccessIssue]
+
+
+def _font_runs(text: str, font: str) -> list[tuple[str, str]]:
+    """Split ``text`` into (font, piece) runs: ``font`` wherever it has the
+    character, else the first fallback that does (#3560). A character no font
+    has stays with ``font``, which draws its missing-glyph box as before."""
+    runs: list[tuple[str, str]] = []
+    for ch in text:
+        use = font
+        if not _has_glyph(font, ch):
+            use = next((f for f in _FALLBACK_FONTS if _has_glyph(f, ch)), font)
+        if runs and runs[-1][0] == use:
+            runs[-1] = (use, runs[-1][1] + ch)
+        else:
+            runs.append((use, ch))
+    return runs
+
+
+def _text_width(text: str, font: str, size: float) -> float:
+    return sum(pdfmetrics.stringWidth(piece, f, size) for f, piece in _font_runs(text, font))
+
+
+def _draw_text(c: rl_canvas.Canvas, x: float, y: float, text: str, font: str, size: float) -> None:
+    """``drawString`` that switches to a fallback font for the characters
+    ``font`` cannot draw, and leaves ``font`` set afterwards."""
+    for f, piece in _font_runs(text, font):
+        c.setFont(f, size)
+        c.drawString(x, y, piece)
+        x += pdfmetrics.stringWidth(piece, f, size)
+    c.setFont(font, size)
+
+
+def _new_canvas(buf: io.BytesIO, pagesize: tuple[float, float]) -> rl_canvas.Canvas:
+    """A canvas whose default font is the label font, so the PDF does not
+    carry an unused Helvetica resource."""
+    # types-reportlab declares initialFontName as a float; reportlab takes a font name.
+    return rl_canvas.Canvas(
+        buf,
+        pagesize=pagesize,
+        initialFontName=FONT_REGULAR,  # pyright: ignore[reportArgumentType]
+    )
+
+
 TemplateName = Literal[
     "ams_holder_74x33",
     "ams_holder_75x55",
@@ -269,15 +357,58 @@ def _draw_qr(c: rl_canvas.Canvas, x: float, y: float, size: float, payload: str)
 
 
 def _truncate_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, max_w: float) -> str:
-    """Truncate ``text`` with an ellipsis so it fits within ``max_w`` points."""
-    if c.stringWidth(text, font, size) <= max_w:
+    """Truncate ``text`` with an ellipsis so it fits within ``max_w`` points,
+    measured in the fonts it will be drawn in."""
+    if _text_width(text, font, size) <= max_w:
         return text
     ell = "…"
-    while text and c.stringWidth(text + ell, font, size) > max_w:
+    while text and _text_width(text + ell, font, size) > max_w:
         text = text[:-1]
     return text + ell if text else ell
 
 
+def _is_wide(ch: str) -> bool:
+    return unicodedata.east_asian_width(ch) in ("W", "F")
+
+
+# Punctuation that never starts a line, nor ends one, in Chinese and Japanese.
+_NO_LINE_START = frozenset("、。,.,.:;!?)】」』〉》〕}ー々")
+_NO_LINE_END = frozenset("(【「『〈《〔{")
+
+
+def _breaks_before(text: str, p: int) -> bool:
+    """Whether a line may break before ``text[p]``."""
+    if text[p] == " ":
+        return True
+    if text[p] in _NO_LINE_START or text[p - 1] in _NO_LINE_END:
+        return False
+    return _is_wide(text[p - 1]) or _is_wide(text[p])
+
+
+def _wrap_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, max_w: float, max_lines: int) -> list[str]:
+    """Break ``text`` into at most ``max_lines`` lines of ``max_w`` points
+    (#3621). A line breaks at its last space, or next to a Chinese, Japanese
+    or Korean character, which run on without spaces; a word too long for a
+    line breaks inside it. What is left after the last line is cut with an
+    ellipsis."""
+    lines: list[str] = []
+    rest = text
+    while len(lines) < max_lines - 1 and _text_width(rest, font, size) > max_w:
+        cut = 1  # at least one character a line, however narrow the column
+        while cut < len(rest) and _text_width(rest[: cut + 1], font, size) <= max_w:
+            cut += 1
+        at = next((p for p in range(cut, 0, -1) if _breaks_before(rest, p)), cut)
+        lines.append(rest[:at].rstrip())
+        rest = rest[at:].lstrip()
+    if rest:
+        lines.append(_truncate_to_width(c, rest, font, size, max_w))
+    return lines
+
+
+# The most lines one row of the roomy layout may take.
+_ROW_MAX_LINES = 3
+
+
 def _draw_label(
     c: rl_canvas.Canvas,
     x: float,
@@ -361,18 +492,18 @@ def _draw_label_tight(
     # easiest thing to read on a small AMS holder at arm's length.
     brand_size = 6.5
     if data.brand and "brand" in fields:
-        c.setFont("Helvetica-Bold", brand_size)
-        brand = _truncate_to_width(c, data.brand, "Helvetica-Bold", brand_size, text_w)
-        c.drawString(text_x, y + h - pad - brand_size, brand)
+        c.setFont(FONT_BOLD, brand_size)
+        brand = _truncate_to_width(c, data.brand, FONT_BOLD, brand_size, text_w)
+        _draw_text(c, text_x, y + h - pad - brand_size, brand, FONT_BOLD, brand_size)
 
     # Second line: material + subtype, small
     sub_size = 5
     sub_line = " ".join(filter(None, [data.material, data.subtype])) if "material" in fields else ""
     sub_y_baseline = y + h - pad - brand_size - 0.6 - sub_size
     if sub_line:
-        c.setFont("Helvetica", sub_size)
-        sub_line = _truncate_to_width(c, sub_line, "Helvetica", sub_size, text_w)
-        c.drawString(text_x, sub_y_baseline, sub_line)
+        c.setFont(FONT_REGULAR, sub_size)
+        sub_line = _truncate_to_width(c, sub_line, FONT_REGULAR, sub_size, text_w)
+        _draw_text(c, text_x, sub_y_baseline, sub_line, FONT_REGULAR, sub_size)
 
     # Third line (when there's room): hex code, tiny — useful when the user
     # has multiple near-identical colours in the same material family.
@@ -382,15 +513,15 @@ def _draw_label_tight(
         hex_y = sub_y_baseline - 0.4 - hex_size
         # Don't render if it'd collide with the spool ID at the bottom.
         if hex_y > inner_y + 13:
-            c.setFont("Helvetica", hex_size)
+            c.setFont(FONT_REGULAR, hex_size)
             c.drawString(text_x, hex_y, hex_code)
 
     # Bottom: BIG spool ID — the killer field at-a-glance.
     if "spool_id" not in fields:
         return
     id_size = 13
-    c.setFont("Helvetica-Bold", id_size)
-    id_text = _truncate_to_width(c, f"#{data.spool_id}", "Helvetica-Bold", id_size, text_w)
+    c.setFont(FONT_BOLD, id_size)
+    id_text = _truncate_to_width(c, f"#{data.spool_id}", FONT_BOLD, id_size, text_w)
     c.drawString(text_x, inner_y + 0.5, id_text)
 
 
@@ -456,34 +587,40 @@ def _draw_label_roomy(
     # are what the label has always used; the rest share the location's.
     rows: list[tuple[LabelField, str, str, float, float]] = [
         # Brand — bumped to bold + larger per the #809 follow-up.
-        ("brand", data.brand or "", "Helvetica-Bold", 8, 1.2),
-        ("material", " · ".join(filter(None, [data.material, data.subtype])), "Helvetica", 7, 1.5),
+        ("brand", data.brand or "", FONT_BOLD, 8, 1.2),
+        ("material", " · ".join(filter(None, [data.material, data.subtype])), FONT_REGULAR, 7, 1.5),
         # Hex colour code — useful for telling near-identical material+colour
         # spools apart when the swatch is small or the user is colour-blind.
-        ("hex", _hex_code_label(data.rgba), "Helvetica", 6.5, 1.2),
-        ("name", name if name not in repeats else "", "Helvetica-Bold", 9, 1.2),
-        ("location", data.storage_location or "", "Helvetica-Oblique", 6.5, 1.2),
-        ("material_number", data.material_number or "", "Helvetica", 6.5, 1.2),
-        ("temps", _temps_text(data), "Helvetica", 6.5, 1.2),
-        ("weight", _weight_text(data), "Helvetica", 6.5, 1.2),
-        ("note", data.note or "", "Helvetica-Oblique", 6.5, 1.2),
-        ("added", data.added.isoformat() if data.added else "", "Helvetica", 6.5, 1.2),
+        ("hex", _hex_code_label(data.rgba), FONT_REGULAR, 6.5, 1.2),
+        ("name", name if name not in repeats else "", FONT_BOLD, 9, 1.2),
+        ("location", data.storage_location or "", FONT_ITALIC, 6.5, 1.2),
+        ("material_number", data.material_number or "", FONT_REGULAR, 6.5, 1.2),
+        ("temps", _temps_text(data), FONT_REGULAR, 6.5, 1.2),
+        ("weight", _weight_text(data), FONT_REGULAR, 6.5, 1.2),
+        ("note", data.note or "", FONT_ITALIC, 6.5, 1.2),
+        ("added", data.added.isoformat() if data.added else "", FONT_REGULAR, 6.5, 1.2),
     ]
 
+    active = [row for row in rows if row[0] in fields and row[1]]
     cursor_y = y + h - pad
-    for field, text, font, size, gap in rows:
-        if field not in fields or not text:
-            continue
+    for i, (_field, text, font, size, gap) in enumerate(active):
         if cursor_y - size < floor_y:
             break
-        c.setFont(font, size)
-        cursor_y -= size
-        c.drawString(text_x, cursor_y, _truncate_to_width(c, text, font, size, text_w))
-        cursor_y -= gap
+        # A row too wide for the column continues on further lines, as long
+        # as every row below it still gets a line of its own (#3621).
+        below = sum(s + g for _f, _t, _fo, s, g in active[i + 1 :])
+        room = 1
+        while room < _ROW_MAX_LINES and cursor_y - (room + 1) * (size + gap) - below >= floor_y:
+            room += 1
+        for line in _wrap_to_width(c, text, font, size, text_w, room):
+            c.setFont(font, size)
+            cursor_y -= size
+            _draw_text(c, text_x, cursor_y, line, font, size)
+            cursor_y -= gap
 
     if show_id:
-        c.setFont("Helvetica-Bold", id_size)
-        id_text = _truncate_to_width(c, f"#{data.spool_id}", "Helvetica-Bold", id_size, text_w)
+        c.setFont(FONT_BOLD, id_size)
+        id_text = _truncate_to_width(c, f"#{data.spool_id}", FONT_BOLD, id_size, text_w)
         c.drawString(text_x, inner_y + 0.5, id_text)
 
 
@@ -599,7 +736,7 @@ def _render_single_label_pdf(
     page_w, page_h = w_mm * mm, h_mm * mm
 
     buf = io.BytesIO()
-    c = rl_canvas.Canvas(buf, pagesize=(page_w, page_h))
+    c = _new_canvas(buf, (page_w, page_h))
     c.setTitle(f"Bambuddy spool labels ({template})")
 
     for data in data_list:
@@ -660,7 +797,7 @@ def _render_sheet_pdf(
     row_gap = layout.row_gap_mm * mm
 
     buf = io.BytesIO()
-    c = rl_canvas.Canvas(buf, pagesize=page_size)
+    c = _new_canvas(buf, page_size)
     c.setTitle(f"Bambuddy spool labels ({title})")
 
     per_page = layout.capacity
@@ -737,7 +874,7 @@ def render_label_preview_pdf(
     w_mm, h_mm = label_size_mm(template)
     page_w, page_h = w_mm * mm, h_mm * mm
     buf = io.BytesIO()
-    c = rl_canvas.Canvas(buf, pagesize=(page_w, page_h))
+    c = _new_canvas(buf, (page_w, page_h))
     _draw_label(c, 0, 0, page_w, page_h, data, monochrome, fields)
     c.showPage()
     c.save()

+ 16 - 2
backend/app/services/log_reader.py

@@ -25,6 +25,7 @@ from backend.app.core.logging_filters import (
 from backend.app.models.printer import Printer
 from backend.app.models.settings import Settings
 from backend.app.models.user import User
+from backend.app.models.virtual_printer import VirtualPrinter
 from backend.app.utils.printer_models import PRINTER_MODEL_ID_MAP, PRINTER_MODEL_MAP
 
 logger = logging.getLogger(__name__)
@@ -266,8 +267,8 @@ def _is_model_name(name: str, model: str | None) -> bool:
 async def collect_sensitive_strings(db: AsyncSession) -> dict[str, str]:
     """Collect known sensitive values from the database for log redaction.
 
-    Covers printer names, serial numbers, IP addresses, access codes, auth
-    usernames, and the Bambu Cloud email. Pass the result to
+    Covers printer names, serial numbers (virtual printers' too), IP
+    addresses, access codes, auth usernames, and the Bambu Cloud email. Pass the result to
     :func:`sanitize_log_content`.
     """
     sensitive_strings: dict[str, str] = {}
@@ -286,6 +287,19 @@ async def collect_sensitive_strings(db: AsyncSession) -> dict[str, str]:
         if access_code:
             sensitive_strings[access_code] = "[ACCESS_CODE]"
 
+    # Virtual printer serials. Stored only as a suffix: the serial is the
+    # model's prefix plus it, and many prefixes (A2L, P2S, H2D, X2D) are past
+    # what the serial pattern below matches, so the certificate log lines
+    # carried them whole (#3526). Every prefix, so a log written before the
+    # VP's model was changed is covered as well.
+    from backend.app.services.virtual_printer.manager import MODEL_SERIAL_PREFIXES, _get_serial_for_model
+
+    result = await db.execute(select(VirtualPrinter.serial_suffix))
+    for (suffix,) in result.all():
+        if suffix:
+            for model in (*MODEL_SERIAL_PREFIXES, ""):
+                sensitive_strings[_get_serial_for_model(model, suffix)] = "[SERIAL]"
+
     # Auth usernames
     result = await db.execute(select(User.username))
     for (username,) in result.all():

+ 26 - 2
backend/app/services/mqtt_relay.py

@@ -20,6 +20,11 @@ from backend.app.utils.paho_teardown import retire_paho_client
 logger = logging.getLogger(__name__)
 
 
+# Fields the printer status topic takes from the same dict the REST status and the
+# WebSocket send, so a subscriber reads them in the shape it already knows (#3401).
+_STATUS_FIELDS_FROM_STATE = ("door_open", "active_extruder", "tray_now", "ams", "vt_tray", "hms_errors")
+
+
 class MQTTRelayService:
     """Publishes BamBuddy events to an external MQTT broker."""
 
@@ -36,6 +41,7 @@ class MQTTRelayService:
         self._broker = ""
         self._port = 1883
         self._last_printer_status: dict[int, float] = {}  # printer_id -> last publish timestamp
+        self._last_printer_connected: dict[int, bool] = {}  # printer_id -> `connected` in the last publish
         self._smart_plug_service = None  # Lazy import to avoid circular dependency
         self._settings: dict = {}  # Store settings for smart plug service
         self._disconnection_event: threading.Event | None = None
@@ -113,6 +119,11 @@ class MQTTRelayService:
                 protocol=mqtt.MQTTv311,
             )
 
+            # Last Will: the broker publishes this when the connection drops without a
+            # clean disconnect (crash, killed container), which would otherwise leave the
+            # retained "online" in place for good (#3401). It replaces that retained message.
+            self.client.will_set(f"{self.topic_prefix}/status", json.dumps({"status": "offline"}), qos=1, retain=True)
+
             # Set up callbacks
             self.client.on_connect = self._on_connect
             self.client.on_disconnect = self._on_disconnect
@@ -250,16 +261,28 @@ class MQTTRelayService:
         printer_serial: str,
         awaiting_plate_clear: bool = False,
     ):
-        """Publish printer status change (throttled to 1 update/sec per printer)."""
+        """Publish printer status change (throttled to 1 update/sec per printer).
+
+        A change of ``connected`` is never throttled: the update that says a printer
+        dropped is retained, and held back it would leave the previous status
+        standing for as long as the printer stays quiet (#3401).
+        """
         if not self.enabled or not self.connected:
             return
 
         # Throttle status updates to avoid flooding MQTT broker
         now = time.time()
         last_publish = self._last_printer_status.get(printer_id, 0)
-        if now - last_publish < self.STATUS_THROTTLE_SECONDS:
+        last_connected = self._last_printer_connected.get(printer_id)
+        connected_changed = last_connected is not None and last_connected != state.connected
+        if not connected_changed and now - last_publish < self.STATUS_THROTTLE_SECONDS:
             return  # Skip this update, too soon since last publish
         self._last_printer_status[printer_id] = now
+        self._last_printer_connected[printer_id] = state.connected
+
+        from backend.app.services.printer_manager import printer_state_to_dict
+
+        snapshot = printer_state_to_dict(state, printer_id)
 
         # Build status payload from PrinterState
         payload = {
@@ -286,6 +309,7 @@ class MQTTRelayService:
             "heatbreak_fan_speed": state.heatbreak_fan_speed,
             "left_aux_fan_speed": state.left_aux_fan_speed,
             "exhaust_fan_present": state.exhaust_fan_present,
+            **{field: snapshot[field] for field in _STATUS_FIELDS_FROM_STATE},
             # Bambuddy-side gate, not printer telemetry (#2525). Mirrors what the
             # Web UI already receives via printer_state_to_dict, so an external
             # automation can tell "finished" from "finished and still waiting for

+ 27 - 1
backend/app/services/mqtt_smart_plug.py

@@ -25,6 +25,7 @@ class SmartPlugMQTTData:
     plug_id: int
     power: float | None = None  # Current power in watts
     energy: float | None = None  # Energy in kWh (today)
+    energy_total: float | None = None  # Lifetime kWh, never resets (#3582)
     state: str | None = None  # "ON" or "OFF"
     # Aware, like the value a received message sets: is_reachable subtracts it
     # from an aware now, which raised TypeError before the first message.
@@ -51,7 +52,8 @@ class MQTTSmartPlugService:
         self.client: mqtt.Client | None = None
         self.connected = False
         self._lock = threading.Lock()
-        # topic -> list of (plug_id, data_type) where data_type is "power", "energy", or "state"
+        # topic -> list of (plug_id, data_type) where data_type is "power",
+        # "energy", "energy_total" or "state"
         self.subscriptions: dict[str, list[tuple[int, str]]] = {}
         # plug_id -> {data_type: MQTTDataSourceConfig}
         self.plug_configs: dict[int, dict[str, MQTTDataSourceConfig]] = {}
@@ -279,6 +281,13 @@ class MQTTSmartPlugService:
                     except (ValueError, TypeError):
                         pass  # Ignore unparseable energy reading from MQTT
 
+                elif data_type == "energy_total":
+                    try:
+                        data.energy_total = float(raw_value) * config.multiplier
+                        logger.debug("MQTT smart plug %s: energy_total=%s", plug_id, data.energy_total)
+                    except (ValueError, TypeError):
+                        pass  # Ignore unparseable energy reading from MQTT
+
                 elif data_type == "state":
                     state_str = str(raw_value)
                     # Check against configured ON value if set
@@ -343,6 +352,9 @@ class MQTTSmartPlugService:
         energy_topic: str | None = None,
         energy_path: str | None = None,
         energy_multiplier: float = 1.0,
+        # Lifetime energy counter, read from the energy topic (#3582)
+        energy_total_path: str | None = None,
+        energy_total_multiplier: float = 1.0,
         # State source
         state_topic: str | None = None,
         state_path: str | None = None,
@@ -390,6 +402,17 @@ class MQTTSmartPlugService:
                 self.plug_configs[plug_id]["energy"] = config
                 self._add_subscription(plug_id, effective_energy_topic, "energy")
 
+            # The lifetime counter sits beside the daily one in the same message
+            # (Tasmota's ENERGY.Total next to ENERGY.Today), so it needs a path:
+            # a raw payload can only be one of the two.
+            if effective_energy_topic and energy_total_path:
+                self.plug_configs[plug_id]["energy_total"] = MQTTDataSourceConfig(
+                    topic=effective_energy_topic,
+                    path=energy_total_path,
+                    multiplier=energy_total_multiplier,
+                )
+                self._add_subscription(plug_id, effective_energy_topic, "energy_total")
+
             # Configure state subscription (path is optional - empty means use raw payload)
             if effective_state_topic:
                 config = MQTTDataSourceConfig(
@@ -408,6 +431,7 @@ class MQTTSmartPlugService:
                 f"MQTT smart plug {plug_id}: configured with "
                 f"power={effective_power_topic if power_path else None}, "
                 f"energy={effective_energy_topic if energy_path else None}, "
+                f"energy_total={effective_energy_topic if energy_total_path else None}, "
                 f"state={effective_state_topic if state_path else None}"
             )
 
@@ -518,6 +542,8 @@ def subscribe_plug_to_mqtt(service: "MQTTSmartPlugService", plug: Any) -> list[s
         energy_topic=energy_topic,
         energy_path=plug.mqtt_energy_path,
         energy_multiplier=plug.mqtt_energy_multiplier or legacy_mult,
+        energy_total_path=(plug.mqtt_energy_total_path or "").strip() or None,
+        energy_total_multiplier=plug.mqtt_energy_total_multiplier or 1.0,
         state_topic=state_topic,
         state_path=plug.mqtt_state_path,
         state_on_value=plug.mqtt_state_on_value,

+ 4 - 3
backend/app/services/obico_actions.py

@@ -63,7 +63,7 @@ def _pause_print(printer_id: int) -> None:
 
 async def _turn_off_linked_plugs(printer_id: int) -> None:
     from backend.app.services.smart_plug_manager import (
-        _is_script_plug,
+        can_turn_off,
         publish_plug_state,
         run_linked_scripts_after_automatic_switch,
         smart_plug_manager,
@@ -74,8 +74,9 @@ async def _turn_off_linked_plugs(printer_id: int) -> None:
         plugs = await smart_plug_manager._get_plugs_for_printer(printer_id, db)
         for plug in plugs:
             # A script can only be run, not turned off; the "printer turns
-            # off" ones run below, after the plug that feeds the printer.
-            if not plug.enabled or _is_script_plug(plug):
+            # off" ones run below, after the plug that feeds the printer. An
+            # MQTT plug cannot be switched at all (#3583).
+            if not plug.enabled or not can_turn_off(plug):
                 continue
             try:
                 service = await smart_plug_manager.get_service_for_plug(plug, db)

+ 1 - 0
backend/app/services/oidc_group_sync.py

@@ -141,6 +141,7 @@ async def sync_oidc_user_groups(
             return
 
         user.groups = new_groups
+        user.sync_role_to_groups()
         await db.commit()
         # The user's open dashboards may now see other printers (#1727)
         from backend.app.core.websocket import ws_manager

+ 20 - 5
backend/app/services/plug_energy.py

@@ -17,6 +17,11 @@ async def _configured_homeassistant(db: AsyncSession):
     return homeassistant_service
 
 
+def mqtt_has_lifetime_counter(plug: SmartPlug) -> bool:
+    """Whether an MQTT plug reads a lifetime counter beside its daily one (#3582)."""
+    return bool((plug.mqtt_energy_total_path or "").strip())
+
+
 async def get_plug_energy(plug: SmartPlug, db: AsyncSession) -> dict | None:
     """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
 
@@ -27,16 +32,26 @@ async def get_plug_energy(plug: SmartPlug, db: AsyncSession) -> dict | None:
     if plug.plug_type == "homeassistant":
         return await (await _configured_homeassistant(db)).get_energy(plug)
     elif plug.plug_type == "mqtt":
-        # MQTT plugs report "today" energy, not lifetime total
-        # For per-print tracking, we use "today" as the counter (resets at midnight)
         mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
-        if mqtt_data:
+        if not mqtt_data:
+            return None
+        if mqtt_has_lifetime_counter(plug):
+            # Per-print energy is the difference of two "total" readings, so it
+            # must come from the counter that never resets (#3582). None until
+            # the first message, so the plug is not picked as the counter.
             return {
                 "power": mqtt_data.power,
                 "today": mqtt_data.energy,
-                "total": mqtt_data.energy,  # Use today as total for per-print calculations
+                "total": mqtt_data.energy_total,
             }
-        return None
+        # One energy value and no telling which counter it is: used as both,
+        # as always. Right for a lifetime counter; a daily one loses a print
+        # across midnight, which is what the lifetime path is for.
+        return {
+            "power": mqtt_data.power,
+            "today": mqtt_data.energy,
+            "total": mqtt_data.energy,
+        }
     elif plug.plug_type == "rest":
         return await rest_smart_plug_service.get_energy(plug)
     else:

+ 242 - 35
backend/app/services/print_scheduler.py

@@ -35,6 +35,7 @@ from backend.app.models.spool_assignment import SpoolAssignment
 from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
 from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
 from backend.app.services.bambu_ftp import (
+    BambuFTPClient,
     FtpFailureKind,
     FtpFailureReport,
     UploadCancelled,
@@ -67,7 +68,7 @@ from backend.app.services.printer_manager import (
 )
 from backend.app.services.queue_item_printer import drop_printer_resolved
 from backend.app.services.slot_nozzle import reports_two_nozzles
-from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
+from backend.app.services.smart_plug_manager import is_monitor_only, publish_plug_state, smart_plug_manager
 from backend.app.services.spool_assignment_notifications import (
     _global_tray_from_assignment,
     _slot_label_from_global_tray,
@@ -496,6 +497,8 @@ class _ModelCandidate:
     required_filament_types: str | None
     filament_overrides: str | None
     variant: "PrintQueueVariant | None" = None
+    # Nozzle diameter (mm) the file was sliced for, None when unknown (#3536).
+    sliced_nozzle: float | None = None
 
 
 def _sliced_for_model(archive, library_file) -> str | None:
@@ -507,6 +510,26 @@ def _sliced_for_model(archive, library_file) -> str | None:
     return None
 
 
+def _sliced_nozzle(archive, library_file) -> float | None:
+    """Nozzle diameter (mm) a 3MF was sliced for, None when unknown (#3536).
+
+    Fail-safe: a missing, unparsable or non-positive value means "unknown", and
+    unknown never excludes a printer. Not rounded here; the tolerance lives in
+    ``_nozzle_mismatch_message``.
+    """
+    if archive is not None:
+        raw = archive.nozzle_diameter
+    elif library_file is not None and library_file.file_metadata:
+        raw = library_file.file_metadata.get("nozzle_diameter")
+    else:
+        return None
+    try:
+        value = float(raw)
+    except (TypeError, ValueError):
+        return None
+    return value if value > 0 else None
+
+
 def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
     """The filament a candidate needs, as ``(types, overrides)``.
 
@@ -593,6 +616,7 @@ def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
                 sliced_for=_sliced_for_model(item.archive, item.library_file),
                 required_filament_types=item.required_filament_types,
                 filament_overrides=item.filament_overrides,
+                sliced_nozzle=_sliced_nozzle(item.archive, item.library_file),
             )
         ]
 
@@ -611,6 +635,7 @@ def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
             required_filament_types=v.required_filament_types,
             filament_overrides=v.filament_overrides,
             variant=v,
+            sliced_nozzle=_sliced_nozzle(None, v.library_file),
         )
         for v in ordered
     ]
@@ -1130,6 +1155,28 @@ def _nozzle_mismatch_message(
     )
 
 
+def _wrong_nozzle_label(printer_name: str, status, sliced_nozzle: float | None) -> str | None:
+    """Label of a printer that cannot print a *sliced_nozzle* file, else None (#3536).
+
+    Used by the "Any <model>" pick, which before #3536 ignored the nozzle and
+    handed a 0.6 file to a 0.4 printer that then failed in ``_start_print``.
+    None means "fits or unknown" (no status, no sliced diameter, no reported
+    nozzles), so a printer is only ever skipped on a POSITIVE mismatch. The
+    decision stays in ``_nozzle_mismatch_message`` (same tolerance, same rack
+    rule as the start guard); this only formats the name for the wait reason.
+    """
+    if status is None:
+        return None
+    installed = _installed_nozzle_diameters(status)
+    rack = _rack_nozzle_diameters(status)
+    if _nozzle_mismatch_message(sliced_nozzle, installed, rack) is None:
+        return None
+    where = _format_diameters(installed) if installed else "no nozzle mounted"
+    if rack:
+        where += f", rack {_format_diameters(rack)}"
+    return f"{printer_name} ({where})"
+
+
 def _describe_filament(entry: dict, nozzle_key: str) -> str:
     """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
 
@@ -1265,6 +1312,44 @@ def _wear_order(printer: Printer) -> tuple[float, int]:
     return hours, printer.id
 
 
+def _hours_of(printer: Printer) -> float:
+    return (printer.runtime_seconds or 0) / 3600.0 + (printer.print_hours_offset or 0.0)
+
+
+def _order_printers(
+    printers: list[Printer], order: str, last_finished: dict[int, datetime] | None = None
+) -> list[Printer]:
+    """Sort the printers an "Any model" job could take into the order they are picked (#2915).
+
+    Whatever the strategy, ties fall back to the printer id, so the outcome is
+    reproducible.
+
+    * ``fewest_hours`` (the default, #3480): the least worn machine first.
+    * ``most_hours``: the most worn first, to use up the machines already near
+      replacement.
+    * ``least_recently_used``: the printer that finished a print longest ago;
+      one that never has goes first.
+    * ``priority``: the printers' own ``dispatch_priority``, lowest first; one
+      without goes last.
+    """
+    if order == "most_hours":
+        return sorted(printers, key=lambda p: (-_hours_of(p), p.id))
+    if order == "least_recently_used":
+        finished = last_finished or {}
+        never = datetime.min
+        return sorted(printers, key=lambda p: (finished.get(p.id, never), p.id))
+    if order == "priority":
+        return sorted(
+            printers,
+            key=lambda p: (
+                p.dispatch_priority is None,
+                p.dispatch_priority if p.dispatch_priority is not None else 0,
+                p.id,
+            ),
+        )
+    return sorted(printers, key=_wear_order)
+
+
 class PrintScheduler:
     """Background scheduler that processes the print queue."""
 
@@ -1681,6 +1766,25 @@ class PrintScheduler:
         for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
             del self._sent_unstarted_print[item_id]
 
+    def printer_reconnected(self, printer_id: int, ip_address: str | None) -> None:
+        """Let a printer that has just reconnected take an upload on the next pass (#3563).
+
+        A printer whose file service stopped answering is often fixed by a
+        restart, but its upload backoff ran on for up to an hour, and nothing
+        but the timer ended it. A reconnect ends the window. The refusal count
+        and the notified text stay: a printer that still refuses gets the next,
+        longer window and no second "job waiting", and a successful upload
+        resets them as before.
+
+        The FTP client's handshake cool-off for the printer goes too. It dates
+        from before the reconnect, and inside it the first retry would fail
+        without reaching the printer and count as another refusal.
+        """
+        if self._upload_backoff.pop(printer_id, None) is not None:
+            logger.info("Printer %s reconnected; retrying uploads to it without waiting for the backoff", printer_id)
+        if ip_address:
+            BambuFTPClient.clear_handshake_cooloff(ip_address)
+
     async def check_queue(self) -> bool:
         """Check for prints ready to start.
 
@@ -2207,7 +2311,7 @@ class PrintScheduler:
                     # If printer not connected, try to power on via smart plug
                     if not printer_connected:
                         plugs = await self._get_smart_plugs(db, item.printer_id)
-                        auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
+                        auto_on_plugs = self._auto_on_plugs(plugs)
                         if auto_on_plugs:
                             logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
                             # Power on using the plug that actually feeds the printer, and
@@ -2493,6 +2597,7 @@ class PrintScheduler:
                                 drying_ids=drying_held,
                                 unmatched_on=unmatched_on,
                                 refused_uploads={pid: self._upload_refusal_kind.get(pid) for pid in backoff_printers},
+                                sliced_nozzle=candidate.sliced_nozzle,
                             )
                             # "Only if the previous print succeeded" is about the
                             # printer the job lands on: one whose last print failed
@@ -3284,7 +3389,8 @@ class PrintScheduler:
         only be woken onto a printer the matcher would also have considered.
         ``printer_scope`` is the job creator's (#1727).
 
-        Fewest print hours first (#3480): both take the first printer that
+        In the order of Settings > Queue > printer order (#2915), fewest print
+        hours first by default (#3480): both take the first printer that
         fits, so an "Any" job goes to the least worn machine and a farm's jobs
         spread by wear instead of all landing on the lowest id. The hours are
         the maintenance counter's (runtime plus the baseline offset), which
@@ -3302,7 +3408,34 @@ class PrintScheduler:
         if (clause := printer_scope.where_strict(Printer.id)) is not None:
             query = query.where(clause)
         result = await db.execute(query)
-        return sorted(result.scalars().all(), key=_wear_order)
+        printers = list(result.scalars().all())
+        order = await self._get_model_dispatch_order(db)
+        last_finished: dict[int, datetime] | None = None
+        if order == "least_recently_used" and printers:
+            last_finished = await self._last_finished_by_printer(db, [p.id for p in printers])
+        return _order_printers(printers, order, last_finished)
+
+    async def _get_model_dispatch_order(self, db: AsyncSession) -> str:
+        """The order setting (#2915); anything unknown reads as the default."""
+        result = await db.execute(select(Settings).where(Settings.key == "model_dispatch_order"))
+        setting = result.scalar_one_or_none()
+        value = (setting.value if setting else "") or ""
+        return value if value in ("most_hours", "least_recently_used", "priority") else "fewest_hours"
+
+    async def _last_finished_by_printer(self, db: AsyncSession, printer_ids: list[int]) -> dict[int, datetime]:
+        """When each printer last finished a print, from the Print Log; none for one that never has."""
+        from backend.app.models.print_log import PrintLogEntry
+
+        result = await db.execute(
+            select(PrintLogEntry.printer_id, func.max(PrintLogEntry.completed_at))
+            .where(PrintLogEntry.printer_id.in_(printer_ids), PrintLogEntry.completed_at.is_not(None))
+            .group_by(PrintLogEntry.printer_id)
+        )
+        return {
+            printer_id: finished
+            for printer_id, finished in result.all()
+            if printer_id is not None and finished is not None
+        }
 
     async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
         """Printer IDs that at least one enabled ``auto_on`` plug can power on.
@@ -3318,6 +3451,8 @@ class PrintScheduler:
             .where(SmartPlug.printer_id.is_not(None))
             .where(SmartPlug.enabled == True)  # noqa: E712
             .where(SmartPlug.auto_on == True)  # noqa: E712
+            # Same rule as _auto_on_plugs: an MQTT plug cannot power a printer on (#3583).
+            .where(SmartPlug.plug_type != "mqtt")
         )
         return {pid for (pid,) in result.all() if pid is not None}
 
@@ -3361,6 +3496,8 @@ class PrintScheduler:
         rather than woken (#2876): the colours are readable while it is off, so
         switching a farm on one machine at a time to discover them wakes
         printers that could never have taken the job.
+        A printer whose last known nozzle cannot print the file is passed over
+        the same way (#3536).
 
         Deliberately does NOT go on to match the job once a printer is up: AMS
         trays arrive with the first status push after connect, so a filament
@@ -3400,6 +3537,23 @@ class PrintScheduler:
                     )
                     continue
 
+                # #3536: the matcher rejects a printer whose nozzle cannot print
+                # the file, so waking one only spends this pass's single wake and
+                # the boot wait. A powered-off printer keeps its last status, so
+                # the nozzle is readable here. Fail-safe: no status or no reported
+                # nozzle means "fits" (None) and the printer is woken as before.
+                label = _wrong_nozzle_label(
+                    printer.name, printer_manager.get_status(printer.id), candidate.sliced_nozzle
+                )
+                if label:
+                    logger.info(
+                        "Not powering on printer %s for a %s job: its nozzle cannot print the file (%s)",
+                        printer.id,
+                        candidate.target_model,
+                        label,
+                    )
+                    continue
+
                 shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
                 if shortfall:
                     logger.info(
@@ -3411,7 +3565,7 @@ class PrintScheduler:
                     continue
 
                 plugs = await self._get_smart_plugs(db, printer.id)
-                auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
+                auto_on_plugs = self._auto_on_plugs(plugs)
                 if not auto_on_plugs:
                     # wakeable_ids said otherwise — the plug changed under us
                     # mid-pass. Nothing to do but move on.
@@ -3464,6 +3618,7 @@ class PrintScheduler:
         drying_ids: set[int] | None = None,
         unmatched_on: Callable[[int], Awaitable[list[str]]] | None = None,
         refused_uploads: Mapping[int, FtpFailureKind | None] | None = None,
+        sliced_nozzle: float | None = None,
     ) -> tuple[int | None, str | None]:
         """Find an idle, connected printer matching the model with compatible filaments.
 
@@ -3496,6 +3651,9 @@ class PrintScheduler:
             refused_uploads: Excluded printers out of dispatch after a refused upload,
                              with why (#3409). Each is named with the reason its own
                              queue rows show, not as "Busy".
+            sliced_nozzle: Nozzle diameter the file was sliced for (#3536). A printer
+                           without that nozzle is passed over; None (unknown) passes
+                           every printer, as before.
 
         Returns:
             Tuple of (printer_id, waiting_reason):
@@ -3521,12 +3679,23 @@ class PrintScheduler:
         printers_offline = []
         printers_offline_no_plug = []
         printers_missing_filament: list[tuple[str, list[str]]] = []
+        printers_wrong_nozzle: list[str] = []
         candidates: list[tuple[int, int]] = []  # (printer_id, color_match_count)
         # The first eligible printer that is short on filament, kept in case
         # every eligible printer is (#3137).
         short_fallback: int | None = None
 
         for printer in printers:
+            # #3536: the pick ignored the nozzle, so a job sliced for 0.6 mm went to a
+            # 0.4 mm printer and the #1899 guard then failed it in _start_print instead
+            # of trying another printer. Fail-safe: no diameter or no reported nozzle
+            # fits (_wrong_nozzle_label returns None). Checked first on purpose: a
+            # wrong-nozzle printer that is busy, excluded or offline must not read as
+            # "Busy"/"Offline", which would hold the job silently forever.
+            wrong_nozzle = _wrong_nozzle_label(printer.name, printer_manager.get_status(printer.id), sliced_nozzle)
+            if wrong_nozzle:
+                printers_wrong_nozzle.append(wrong_nozzle)
+                continue
             if printer.id in exclude_ids and refused_uploads and printer.id in refused_uploads:
                 printers_refused.append(_refused_upload_hold_reason(printer.name, refused_uploads[printer.id]))
                 continue
@@ -3670,6 +3839,21 @@ class PrintScheduler:
         if short_fallback is not None:
             return short_fallback, None
 
+        # #3536: nothing else is in the way, so the nozzle is the whole reason. Named
+        # per printer; when something else also waits, the wrong ones stay out so
+        # that reason (e.g. "Busy") is not drowned by a printer that cannot help.
+        if printers_wrong_nozzle and not (
+            printers_busy
+            or printers_refused
+            or printers_offline
+            or printers_offline_no_plug
+            or printers_missing_filament
+        ):
+            return None, (
+                f"No {normalized_model}{location_suffix} has a {sliced_nozzle:g}mm nozzle: "
+                f"{', '.join(printers_wrong_nozzle)}"
+            )
+
         # Build waiting reason from what we found
         reasons = []
         if printers_missing_filament:
@@ -6143,7 +6327,10 @@ class PrintScheduler:
         of each of its candidate models, in its location, that its creator may use.
 
         ``cache`` holds one lookup per model, location and creator for the pass,
-        so a long queue of model jobs does not query once per job."""
+        so a long queue of model jobs does not query once per job.
+
+        A printer whose last known nozzle cannot print the file is left out
+        (#3536): the job stays pending there, so it must not hold drying off."""
         printer_ids: set[int] = set()
         for candidate in _candidates_for(item):
             if not candidate.target_model:
@@ -6152,7 +6339,16 @@ class PrintScheduler:
             if key not in cache:
                 printers = await self._printers_for_model(db, candidate.target_model, item.target_location, scope)
                 cache[key] = {printer.id for printer in printers}
-            printer_ids |= cache[key]
+            # #3536: a job with no fitting nozzle now stays pending instead of
+            # failing at once, so it must not count for a printer whose last
+            # known nozzle cannot print it (it would block or trigger drying
+            # there for good). Unknown nozzle fits (fail-safe). The cache stays
+            # per model; the filter runs per candidate, not per cache entry.
+            printer_ids |= {
+                pid
+                for pid in cache[key]
+                if _wrong_nozzle_label("", printer_manager.get_status(pid), candidate.sliced_nozzle) is None
+            }
         return printer_ids
 
     async def _check_auto_drying(
@@ -7077,6 +7273,13 @@ class PrintScheduler:
         result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
         return list(result.scalars().all())
 
+    @staticmethod
+    def _auto_on_plugs(plugs: list[SmartPlug]) -> list[SmartPlug]:
+        """The plugs that may power a printer on: enabled, auto on, and not a
+        monitor-only MQTT plug, which Bambuddy cannot switch (#3583). Must
+        match the query in :meth:`_wakeable_printer_ids`."""
+        return [p for p in plugs if p.auto_on and p.enabled and not is_monitor_only(p)]
+
     @staticmethod
     def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
         """Pick the plug to power-cycle a printer back online with (#2629).
@@ -8584,6 +8787,7 @@ class PrintScheduler:
                 printer_scope=printer_scope,
                 is_short=is_short,
                 unmatched_on=unmatched_on,
+                sliced_nozzle=candidates[0].sliced_nozzle,
             )
             # Every idle printer short comes back as the first of them.
             if match_id is None or await is_short(match_id):
@@ -9568,34 +9772,37 @@ class PrintScheduler:
         upload_failure = FtpFailureReport()
 
         try:
-            if ftp_retry_enabled:
-                uploaded = await with_ftp_retry(
-                    upload_file_async,
-                    printer.ip_address,
-                    printer.access_code,
-                    file_path,
-                    remote_path,
-                    socket_timeout=ftp_timeout,
-                    printer_model=printer.model,
-                    progress_callback=progress_bridge,
-                    respect_handshake_cooloff=False,
-                    failure=upload_failure,
-                    max_retries=ftp_retry_count,
-                    retry_delay=ftp_retry_delay,
-                    operation_name=f"Upload print to {printer.name}",
-                )
-            else:
-                uploaded = await upload_file_async(
-                    printer.ip_address,
-                    printer.access_code,
-                    file_path,
-                    remote_path,
-                    socket_timeout=ftp_timeout,
-                    printer_model=printer.model,
-                    progress_callback=progress_bridge,
-                    respect_handshake_cooloff=False,
-                    failure=upload_failure,
-                )
+            # The printer's MQTT goes quiet while it receives the file; the
+            # stale check must not reconnect it under the print command (#3538).
+            with printer_manager.uploading(item.printer_id):
+                if ftp_retry_enabled:
+                    uploaded = await with_ftp_retry(
+                        upload_file_async,
+                        printer.ip_address,
+                        printer.access_code,
+                        file_path,
+                        remote_path,
+                        socket_timeout=ftp_timeout,
+                        printer_model=printer.model,
+                        progress_callback=progress_bridge,
+                        respect_handshake_cooloff=False,
+                        failure=upload_failure,
+                        max_retries=ftp_retry_count,
+                        retry_delay=ftp_retry_delay,
+                        operation_name=f"Upload print to {printer.name}",
+                    )
+                else:
+                    uploaded = await upload_file_async(
+                        printer.ip_address,
+                        printer.access_code,
+                        file_path,
+                        remote_path,
+                        socket_timeout=ftp_timeout,
+                        printer_model=printer.model,
+                        progress_callback=progress_bridge,
+                        respect_handshake_cooloff=False,
+                        failure=upload_failure,
+                    )
         except UploadCancelled as e:
             uploaded = False
             upload_error = (

+ 18 - 1
backend/app/services/printer_manager.py

@@ -3,7 +3,8 @@ import logging
 import math
 import re
 import traceback
-from collections.abc import Callable
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
 
 from sqlalchemy import select
 from sqlalchemy.ext.asyncio import AsyncSession
@@ -982,6 +983,22 @@ class PrinterManager:
         """Get the MQTT client for a printer."""
         return self._clients.get(printer_id)
 
+    @contextmanager
+    def uploading(self, printer_id: int | None) -> Iterator[None]:
+        """Bambuddy is uploading to this printer: its MQTT silence is expected (#3538).
+
+        Ends on the client it began on, so a client replaced meanwhile is
+        neither left counting nor decremented.
+        """
+        client = self._clients.get(printer_id) if printer_id is not None else None
+        if client is not None:
+            client.begin_upload()
+        try:
+            yield
+        finally:
+            if client is not None:
+                client.end_upload()
+
     def mark_printer_offline(self, printer_id: int):
         """Mark a printer as offline and trigger status callback.
 

+ 18 - 9
backend/app/services/slicer_filament_resolver.py

@@ -24,11 +24,12 @@ Resolver outcomes:
 
 The resolver is async because the GFS / PFUS / PFCN branches need cloud
 authentication and the local-preset branch reads ``LocalPreset`` from the
-DB. Pass ``current_user=None`` to skip cloud auth (the on_ams_change
-replay path uses this); cloud-prefix presets then fall back to a static
-``normalize_slicer_filament`` parse, which is correct when the slot was
-already configured by an earlier authenticated assign and the printer's
-calibration table preserves the real filament_id.
+DB. ``current_user=None`` reads the shared cloud sign-in, the one used with
+login off. With login on that one is usually empty, so a caller without a
+user of its own (tag auto-assign, the Spoolman link) gets no cloud lookup, and
+cloud-prefix presets fall back to a static ``normalize_slicer_filament``
+parse. API-key assigns and the replay on insert pass the key's owner or the
+assigning user instead (#3519).
 """
 
 from __future__ import annotations
@@ -445,6 +446,15 @@ async def resolve_slicer_filament(
                     await cloud.close()
             elif cloud is not None:
                 await cloud.close()
+            elif not base_sf.startswith("GFS"):
+                # A custom preset has no static form; without a sign-in the slot
+                # falls back to a generic filament, which nothing else reports
+                # (#3519). An official GFS one parses fine without the cloud.
+                logger.warning(
+                    "Slicer-filament resolve: custom preset %r not looked up, no Bambu Cloud sign-in "
+                    "for this caller; the slot may get a generic filament",
+                    sf,
+                )
         except Exception as e:
             logger.warning("Slicer-filament resolve: cloud lookup failed for %r: %s", sf, e)
 
@@ -522,10 +532,9 @@ async def resolve_slicer_filament(
     #      by the slicer as tray_info_idx (the printer's calibration table
     #      indexes by filament_id, and a PFUS isn't one). This normally gets
     #      realigned to a P-prefix local id via the caller's printer_kp
-    #      lookup, but on the replay path in main.py.on_ams_change
-    #      current_user=None skips cloud auth and leaves the raw PFUS in
-    #      tray_info_idx — overwriting the correctly-configured slot from
-    #      the original assign.
+    #      lookup, but a caller with no cloud sign-in (see the module
+    #      docstring) gets no cloud lookup and would leave the raw PFUS in
+    #      tray_info_idx — overwriting a correctly-configured slot.
     #   3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's
     #      "(Custom)" H2D variants, #1648) — same shape problem as PFUS.
     #   4. Orca Cloud profile UUIDs, when the branch above could not reach the

+ 53 - 16
backend/app/services/smart_plug_manager.py

@@ -12,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
 from backend.app.core.tasks import spawn_background_task
 from backend.app.services.homeassistant import homeassistant_service
 from backend.app.services.mqtt_relay import mqtt_relay
-from backend.app.services.plug_energy import get_plug_energy
+from backend.app.services.plug_energy import get_plug_energy, mqtt_has_lifetime_counter
 from backend.app.services.printer_manager import printer_manager
 from backend.app.services.rest_smart_plug import rest_smart_plug_service
 from backend.app.services.tasmota import tasmota_service
@@ -70,6 +70,23 @@ def _is_script_plug(plug) -> bool:
     )
 
 
+def is_monitor_only(plug) -> bool:
+    """An MQTT plug: Bambuddy subscribes to it and never publishes, so it can
+    be neither turned on nor off (#3583). Its auto on / auto off default to on
+    and the UI hides both, so every switching path must skip it itself."""
+    return getattr(plug, "plug_type", None) == "mqtt"
+
+
+def can_turn_off(plug) -> bool:
+    """Whether an automatic turn-off can switch this plug off (#3583).
+
+    Not a Home Assistant script, which can only be run, and not a monitor-only
+    MQTT plug. Turning on is narrower on purpose: a script linked to a printer
+    is run by the auto-on paths, so they skip only :func:`is_monitor_only`.
+    """
+    return not _is_script_plug(plug) and not is_monitor_only(plug)
+
+
 async def run_linked_scripts(printer_id: int, plug_state: str, db: AsyncSession) -> None:
     """Run the HA scripts linked to a printer after its power plug switched.
 
@@ -329,14 +346,18 @@ class SmartPlugManager:
             price = await current_price(db, remember=True)
             captured = 0
             for plug in plugs:
-                # MQTT plugs only publish a "today" counter that resets at midnight —
-                # they can never feed cumulative snapshots, so skip them outright to
-                # avoid a noisy tasmota-service fallback attempt on an IP-less plug.
-                if plug.plug_type == "mqtt":
+                # An MQTT plug feeds the snapshots only with its lifetime counter
+                # (#3582); its one legacy energy value may be a daily counter that
+                # resets at midnight. Read through get_plug_energy, not the
+                # service lookup, which would fall back to Tasmota on an IP-less plug.
+                if plug.plug_type == "mqtt" and not mqtt_has_lifetime_counter(plug):
                     continue
                 try:
-                    service = await self.get_service_for_plug(plug, db)
-                    energy = await service.get_energy(plug)
+                    if plug.plug_type == "mqtt":
+                        energy = await get_plug_energy(plug, db)
+                    else:
+                        service = await self.get_service_for_plug(plug, db)
+                        energy = await service.get_energy(plug)
                 except Exception as e:
                     logger.debug("Snapshot: failed to read energy from plug %s: %s", plug.id, e)
                     continue
@@ -375,6 +396,9 @@ class SmartPlugManager:
             plugs = result.scalars().all()
 
             for plug in plugs:
+                # A schedule cannot switch a monitor-only MQTT plug (#3583).
+                if is_monitor_only(plug):
+                    continue
                 service = await self.get_service_for_plug(plug, db)
 
                 # Check if we should turn on
@@ -441,6 +465,10 @@ class SmartPlugManager:
                 logger.debug("Smart plug '%s' auto_on is disabled", plug.name)
                 continue
 
+            if is_monitor_only(plug):
+                logger.debug("Smart plug '%s' is monitor-only, skipping auto-on", plug.name)
+                continue
+
             # Turn on the plug
             logger.info("Print started on printer %s, turning on plug '%s'", printer_id, plug.name)
             try:
@@ -488,9 +516,10 @@ class SmartPlugManager:
                 logger.debug("Smart plug '%s' auto_off is disabled", plug.name)
                 continue
 
-            # Skip auto-off for HA script entities (scripts can only be triggered, not turned off)
-            if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
-                logger.debug("Smart plug '%s' is a HA script entity, skipping auto-off", plug.name)
+            # Skip auto-off for HA script entities (scripts can only be triggered,
+            # not turned off) and monitor-only MQTT plugs (#3583).
+            if not can_turn_off(plug):
+                logger.debug("Smart plug '%s' cannot be switched off, skipping auto-off", plug.name)
                 continue
 
             logger.info(
@@ -535,8 +564,8 @@ class SmartPlugManager:
             if not plug.enabled:
                 logger.debug("Smart plug '%s' is disabled, skipping queue auto-off", plug.name)
                 continue
-            if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
-                logger.debug("Smart plug '%s' is a HA script entity, skipping queue auto-off", plug.name)
+            if not can_turn_off(plug):
+                logger.debug("Smart plug '%s' cannot be switched off, skipping queue auto-off", plug.name)
                 continue
             logger.info(
                 "Queue job finished on printer %s, scheduling turn-off for plug '%s'",
@@ -570,10 +599,10 @@ class SmartPlugManager:
                 logger.debug("Smart plug '%s' auto_off_after_drying is disabled, skipping", plug.name)
                 continue
 
-            # HA script entities can only be triggered, not turned off — same
-            # guard the print-finish path uses.
-            if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
-                logger.debug("Smart plug '%s' is a HA script entity, skipping drying auto-off", plug.name)
+            # HA script entities can only be triggered, not turned off, and MQTT
+            # plugs not switched at all — same guard the print-finish path uses.
+            if not can_turn_off(plug):
+                logger.debug("Smart plug '%s' cannot be switched off, skipping drying auto-off", plug.name)
                 continue
 
             logger.info(
@@ -918,6 +947,14 @@ class SmartPlugManager:
                 pending_plugs = result.scalars().all()
 
                 for plug in pending_plugs:
+                    # A pending off left on an MQTT plug by an earlier version
+                    # can never run (#3583): clear it.
+                    if is_monitor_only(plug):
+                        plug.auto_off_pending = False
+                        plug.auto_off_pending_since = None
+                        await db.commit()
+                        continue
+
                     # Check how long it's been pending (timeout after 2 hours)
                     if plug.auto_off_pending_since:
                         pending_since = to_naive_utc(plug.auto_off_pending_since)

+ 73 - 2
backend/app/services/spool_csv.py

@@ -17,9 +17,10 @@ import io
 from datetime import datetime, timezone
 
 from pydantic import BaseModel, ValidationError
-from sqlalchemy import select
+from sqlalchemy import func, select, text
 from sqlalchemy.ext.asyncio import AsyncSession
 
+from backend.app.core.database import is_sqlite
 from backend.app.models.color_catalog import ColorCatalogEntry
 from backend.app.models.spool import Spool
 from backend.app.models.supplier import Supplier, supplier_name_key
@@ -38,6 +39,11 @@ from backend.app.schemas.spool import SpoolCreate
 # `material_number` (#2870) are SpoolCreate fields included so a round-trip
 # preserves them (they'd otherwise be lost).
 CSV_COLUMNS = [
+    # The spool's id (#3520): a printed label's QR code carries it, so moving
+    # the inventory to another install must not renumber the spools. Import
+    # keeps it when this install never handed it out (see `_decide_ids`), and
+    # gives the spool a new one otherwise; an empty cell is a new spool.
+    "id",
     "material",
     "brand",
     "subtype",
@@ -102,6 +108,8 @@ class ImportRowResult(BaseModel):
 
     row_number: int  # 1-based data row (header is not counted)
     status: str  # "valid" | "error" | "skipped"
+    # The id the spool is created with (#3520); None gets the next free one.
+    keeps_id: int | None = None
     reason: str | None = None
     material: str | None = None
     brand: str | None = None
@@ -319,7 +327,11 @@ async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPrevie
     except UnicodeDecodeError:
         return _empty_preview(["File is not valid UTF-8 text."])
 
-    reader = csv.reader(io.StringIO(text))
+    # Excel in a comma-decimal locale (de, fr, nl, it, ...) saves "CSV" with
+    # ";" between fields and "," as the decimal mark.
+    first_line = text.split("\n", 1)[0]
+    delimiter = ";" if first_line.count(";") > first_line.count(",") else ","
+    reader = csv.reader(io.StringIO(text), delimiter=delimiter)
     try:
         header = next(reader)
     except StopIteration:
@@ -390,6 +402,16 @@ async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPrevie
 
         row_error: str | None = None
 
+        requested_id: int | None = None
+        id_cell = cell(raw_row, "id")
+        if id_cell:
+            try:
+                requested_id = int(id_cell)
+            except ValueError:
+                requested_id = 0
+            if requested_id < 1:
+                row_error = f"id must be a positive whole number (got '{id_cell}')"
+
         # Plain text passthrough columns.
         for field in (
             "subtype",
@@ -417,6 +439,8 @@ async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPrevie
             for field in _FLOAT_COLUMNS:
                 value = cell(raw_row, field)
                 if value:
+                    if delimiter == ";":
+                        value = value.replace(",", ".")
                     try:
                         data[field] = float(value)
                     except ValueError:
@@ -543,6 +567,7 @@ async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPrevie
                 resolved_color=resolved_color,
                 cross_material_color=cross_material_color,
                 duplicate_of_existing=_spool_key(material, brand, color_name) in existing_keys,
+                keeps_id=requested_id,
                 spool=spool_data,
                 supplier_ids=supplier_ids,
                 purchase_supplier_id=purchase_supplier_id,
@@ -550,6 +575,8 @@ async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPrevie
         )
         valid += 1
 
+    await _decide_ids(db, rows, warnings)
+
     return ImportPreview(
         columns=CSV_COLUMNS,
         total=valid + error + skipped,
@@ -561,6 +588,50 @@ async def parse_and_validate(raw_bytes: bytes, db: AsyncSession) -> ImportPrevie
     )
 
 
+async def highest_spool_id_given_out(db: AsyncSession) -> int:
+    """The highest spool id this install has ever handed out, deleted ones included.
+
+    Spool ids are never reused (old print logs and usage records may still
+    name one), so only an id above this is free to give an imported spool.
+    """
+    highest = (await db.execute(select(func.max(Spool.id)))).scalar() or 0
+    if is_sqlite():
+        seq = (await db.execute(text("SELECT seq FROM sqlite_sequence WHERE name = 'spool'"))).scalar()
+        return max(highest, seq or 0)
+    sequence = (await db.execute(text("SELECT pg_get_serial_sequence('spool', 'id')"))).scalar()
+    if sequence:
+        state = (await db.execute(text(f"SELECT last_value, is_called FROM {sequence}"))).first()  # noqa: S608  # nosec B608 -- name from pg_get_serial_sequence
+        if state is not None:
+            last_value, is_called = state
+            highest = max(highest, last_value if is_called else last_value - 1)
+    return highest
+
+
+async def _decide_ids(db: AsyncSession, rows: list[ImportRowResult], warnings: list[str]) -> None:
+    """Keep each valid row's id when this install never handed it out (#3520).
+
+    On a fresh install every id qualifies. An id already given out here, or
+    one the file names twice, would merge two spools' records, so that row
+    gets a new id instead: one warning for all of them, not one per row.
+    """
+    highest = await highest_spool_id_given_out(db)
+    taken: set[int] = set()
+    renumbered = 0
+    for row in rows:
+        if row.keeps_id is None:
+            continue
+        if row.status != "valid" or row.keeps_id <= highest or row.keeps_id in taken:
+            if row.status == "valid":
+                renumbered += 1
+            row.keeps_id = None
+            continue
+        taken.add(row.keeps_id)
+    if renumbered:
+        warnings.append(
+            f"{renumbered} spool(s) get a new id: their id is already used on this install or appears twice in the file"
+        )
+
+
 def serialize(spools: list[Spool]) -> bytes:
     """Render spools to CSV bytes using the fixed schema (export side).
 

+ 52 - 0
backend/app/utils/filament_types.py

@@ -116,6 +116,14 @@ _PRINTER_TYPES: tuple[str, ...] = (
     "PP-CF",
     "PP-GF",
     "PE-CF",
+    # Bambu's support materials. BambuStudio writes a support preset's type
+    # with this suffix (see ``support_filament_type``) and the 3MF declares it
+    # the same way, so the suffix is part of the type, not decoration to strip:
+    # a slot reduced to "PLA" offers Support for PLA to every plain PLA part
+    # and to nothing that asks for support (#3559).
+    "PLA-S",
+    "ABS-S",
+    "PA-S",
     "PCTG",
     "PETG",
     "BVOH",
@@ -225,6 +233,50 @@ def printer_filament_type(material: str | None) -> str:
     return text
 
 
+# Bambu's own support filaments, by id, and the type BambuStudio's
+# ``get_filament_type`` (libslic3r/PrintConfig.cpp) gives each: Support W and
+# Support G by their id, the rest by adding the suffix to the preset's base
+# type -- For PLA and For PLA/PETG are PLA presets, For PA/PET a PA one, and
+# Support for ABS is the one left as it is. The id decides on its own because
+# the wording cannot: "Support for PLA/PETG" reads as PETG.
+_SUPPORT_TYPE_BY_ID: dict[str, str] = {
+    "GFS00": "PLA-S",
+    "GFS01": "PA-S",
+    "GFS02": "PLA-S",
+    "GFS03": "PA-S",
+    "GFS05": "PLA-S",
+    "GFS06": "ABS",
+}
+# Without a Bambu id, BambuStudio adds the suffix to these two types only.
+_SUPPORT_SUFFIXED = {"PLA": "PLA-S", "PA": "PA-S"}
+_SUPPORT_WORD = re.compile(r"\bSUPPORT\b", re.IGNORECASE)
+
+
+def support_filament_type(tray_type: str | None, filament_id: str | None, preset_name: str | None) -> str:
+    """The slot type for ``tray_type`` when the filament is a support material.
+
+    BambuStudio writes a support preset into a slot as "PLA-S" or "PA-S", and
+    a plate sliced with one declares the same, so the slot has to say so for a
+    print to find it (#3559). Every path that configures a slot reaches this
+    point holding a plain "PLA": the Configure dialog reads the type from the
+    preset name, and a spool's material column rarely says more.
+
+    The rule is BambuStudio's. A Bambu support id decides the type outright.
+    Otherwise -- a third-party or user preset with an id of its own -- a PLA
+    or PA filament whose preset name says "Support" gets the suffix. Any other
+    type is returned unchanged: "PLA Support for PETG" is a PETG preset and
+    stays PETG, as it does in the slicer.
+    """
+    fid = (filament_id or "").strip().upper()
+    if fid in _SUPPORT_TYPE_BY_ID:
+        return _SUPPORT_TYPE_BY_ID[fid]
+    text = (tray_type or "").strip()
+    suffixed = _SUPPORT_SUFFIXED.get(text.upper())
+    if suffixed and _SUPPORT_WORD.search(preset_name or ""):
+        return suffixed
+    return tray_type or ""
+
+
 def nozzle_temp_range(material: str | None, tray_type: str | None) -> tuple[int, int]:
     """The nozzle range to send with a slot, given a spool's material and the
     type the slot will carry.

+ 29 - 14
backend/app/utils/printer_models.py

@@ -282,34 +282,53 @@ NOZZLE_RACK_MODELS = frozenset(
 )
 
 
-# Models where Bambu's own firmware/UI names the enclosure fan (big_fan2 /
-# airduct part id 3) "Exhaust" rather than "Chamber". On these the printer's
-# touchscreen and Bambu Studio both call it the exhaust fan, and on the P2S it
-# is an add-on kit rather than built-in hardware. Other enclosed models
-# (X1 / P1S / H2 series) keep the "Chamber" naming.
+# Models where Bambu names the enclosure fan (big_fan2 / airduct part id 3)
+# "Exhaust" rather than "Chamber". Bambu Studio calls part 3 "Exhaust" unless a
+# printer's file renames it, and only the X1 Carbon, X1, X1E and P1S files
+# rename it to "Chamber". On the P2S it is an add-on kit rather than built-in
+# hardware. The H2 series and the H3C were missing (#3521). Must match
+# MODELS_WITH_EXHAUST_LABEL in frontend PrintersPage.tsx (a test checks).
 EXHAUST_FAN_LABEL_MODELS = frozenset(
     [
-        # Display names (uppercase, no spaces)
+        # Display names, as the printer card spells them
         "P2S",
         "X2D",
+        "H2D",
+        "H2D Pro",
+        "H2C",
+        "H2S",
+        "H3C",
         # Internal codes
         "N7",  # P2S
         "N6",  # X2D
+        "O1D",  # H2D
+        "O1E",  # H2D Pro
+        "O2D",  # H2D Pro
+        "O1C",  # H2C
+        "O1C2",  # H2C
+        "O1S",  # H2S
+        "N10",  # H3C
     ]
 )
 
 
+def _model_key(model: str | None) -> str:
+    return model.strip().upper().replace(" ", "").replace("-", "") if isinstance(model, str) else ""
+
+
+_EXHAUST_FAN_LABEL_KEYS = frozenset(_model_key(m) for m in EXHAUST_FAN_LABEL_MODELS)
+
+
 def uses_exhaust_fan_label(model: str | None) -> bool:
     """Return True if this model calls the big_fan2 enclosure fan "Exhaust".
 
-    P2S/X2D name that fan "Exhaust" in Bambu's firmware/UI; everything else
-    enclosed calls it the chamber fan. Used so the UI badge and the API
+    The models in EXHAUST_FAN_LABEL_MODELS name that fan "Exhaust"; the X1
+    series and P1S call it the chamber fan. Used so the UI badge and the API
     response message agree on what the user sees.
     """
     if not model:
         return False
-    normalized = model.strip().upper().replace(" ", "").replace("-", "")
-    return normalized in EXHAUST_FAN_LABEL_MODELS
+    return _model_key(model) in _EXHAUST_FAN_LABEL_KEYS
 
 
 # Models whose airduct part 10 is the RIGHT auxiliary fan and part 2 the left
@@ -397,10 +416,6 @@ PROGRESS_INCLUDES_START_SEQUENCE_MODELS = frozenset(["H3C", "N10"])
 AMS3H_MODELS = frozenset(["H3C", "N10"])
 
 
-def _model_key(model: str | None) -> str:
-    return model.strip().upper().replace(" ", "").replace("-", "") if isinstance(model, str) else ""
-
-
 def progress_includes_start_sequence(model: str | None) -> bool:
     """True when the printer's progress percent counts its start sequence (H3C)."""
     return _model_key(model) in PROGRESS_INCLUDES_START_SEQUENCE_MODELS

+ 276 - 0
backend/tests/integration/test_admin_role_follows_groups_3533.py

@@ -0,0 +1,276 @@
+"""Moving a user out of Administrators takes their admin rights (#3533).
+
+The setup admin is created with role "admin" and in Administrators, and
+``is_admin`` honours either. Moving them to Operators changed only the groups,
+the role kept them an admin, and the UI had no field for it. The groups decide
+now and the role follows them, from every path that changes them.
+"""
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.orm import selectinload
+
+from backend.app.models.group import Group
+from backend.app.models.settings import Settings
+from backend.app.models.user import User
+
+
+async def _groups(db_session) -> tuple[Group, Group]:
+    """The seeded system groups, created when the database has none yet."""
+    found = []
+    for name in ("Administrators", "Operators"):
+        group = await db_session.scalar(select(Group).where(Group.name == name))
+        if group is None:
+            group = Group(name=name, permissions=[], is_system=True)
+            db_session.add(group)
+            await db_session.commit()
+        found.append(group)
+    return found[0], found[1]
+
+
+async def _user(db_session, name: str, role: str, groups: list[Group], active: bool = True) -> int:
+    from backend.app.core.auth import get_password_hash
+
+    user = User(username=name, password_hash=get_password_hash("Whatever1!"), role=role, is_active=active)
+    user.groups = list(groups)
+    db_session.add(user)
+    await db_session.commit()
+    return user.id
+
+
+async def _load(db_session, user_id: int) -> User:
+    db_session.expire_all()
+    return (
+        await db_session.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
+    ).scalar_one()
+
+
+@pytest.mark.asyncio
+async def test_moving_an_admin_to_operators_takes_the_admin_rights(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    await _user(db_session, "admin", "admin", [admins])
+    demoted = await _user(db_session, "mike", "admin", [admins])
+
+    # What the edit form sent: the new groups, and the old role back.
+    response = await async_client.patch(f"/api/v1/users/{demoted}", json={"group_ids": [operators.id], "role": "admin"})
+
+    assert response.status_code == 200, response.text
+    assert response.json()["is_admin"] is False
+    user = await _load(db_session, demoted)
+    assert user.role == "user"
+    assert not user.is_admin
+
+
+@pytest.mark.asyncio
+async def test_moving_a_user_into_administrators_makes_them_admin(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    promoted = await _user(db_session, "jane", "user", [operators])
+
+    response = await async_client.patch(f"/api/v1/users/{promoted}", json={"group_ids": [admins.id]})
+
+    assert response.status_code == 200, response.text
+    assert (await _load(db_session, promoted)).role == "admin"
+
+
+@pytest.mark.asyncio
+async def test_role_alone_moves_the_user_out_of_administrators(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    await _user(db_session, "admin", "admin", [admins])
+    demoted = await _user(db_session, "mike", "admin", [admins, operators])
+
+    response = await async_client.patch(f"/api/v1/users/{demoted}", json={"role": "user"})
+
+    assert response.status_code == 200, response.text
+    user = await _load(db_session, demoted)
+    assert [g.name for g in user.groups] == ["Operators"]
+    assert not user.is_admin
+
+
+@pytest.mark.asyncio
+async def test_the_last_admin_cannot_be_moved_out_of_administrators(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    only = await _user(db_session, "admin", "admin", [admins])
+
+    response = await async_client.patch(f"/api/v1/users/{only}", json={"group_ids": [operators.id]})
+
+    assert response.status_code == 400
+    assert "last admin" in response.json()["detail"]
+    assert (await _load(db_session, only)).is_admin
+
+
+@pytest.mark.asyncio
+async def test_leaving_administrators_through_the_group_takes_the_admin_rights(async_client: AsyncClient, db_session):
+    admins, _ = await _groups(db_session)
+    await _user(db_session, "admin", "admin", [admins])
+    demoted = await _user(db_session, "mike", "admin", [admins])
+
+    response = await async_client.delete(f"/api/v1/groups/{admins.id}/users/{demoted}")
+
+    assert response.status_code == 204, response.text
+    user = await _load(db_session, demoted)
+    assert user.role == "user"
+    assert not user.is_admin
+
+
+@pytest.mark.asyncio
+async def test_the_last_admin_cannot_leave_administrators_through_the_group(async_client: AsyncClient, db_session):
+    admins, _ = await _groups(db_session)
+    only = await _user(db_session, "admin", "admin", [admins])
+
+    response = await async_client.delete(f"/api/v1/groups/{admins.id}/users/{only}")
+
+    assert response.status_code == 400
+    assert (await _load(db_session, only)).is_admin
+
+
+@pytest.mark.asyncio
+async def test_joining_administrators_through_the_group_sets_the_role(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+    promoted = await _user(db_session, "jane", "user", [operators])
+
+    response = await async_client.post(f"/api/v1/groups/{admins.id}/users/{promoted}")
+
+    assert response.status_code == 204, response.text
+    assert (await _load(db_session, promoted)).role == "admin"
+
+
+@pytest.mark.asyncio
+async def test_a_new_user_gets_the_role_of_their_groups(async_client: AsyncClient, db_session):
+    admins, operators = await _groups(db_session)
+
+    as_operator = await async_client.post(
+        "/api/v1/users", json={"username": "op", "password": "Whatever1!", "role": "admin", "group_ids": [operators.id]}
+    )
+    as_admin = await async_client.post(
+        "/api/v1/users", json={"username": "ad", "password": "Whatever1!", "role": "admin"}
+    )
+
+    assert as_operator.status_code == 201, as_operator.text
+    assert as_operator.json()["is_admin"] is False
+    assert as_admin.status_code == 201, as_admin.text
+    assert [g["name"] for g in as_admin.json()["groups"]] == ["Administrators"]
+
+
+class TestBackfill:
+    """Users demoted before the fix are lined up once at startup."""
+
+    FLAG = "_backfill_3533_admin_role_follows_groups_done"
+
+    @classmethod
+    async def _rearm(cls, db_session):
+        """The app's own startup in the fixture has already run it once."""
+        from sqlalchemy import delete
+
+        await db_session.execute(delete(Settings).where(Settings.key == cls.FLAG))
+        await db_session.commit()
+
+    @staticmethod
+    async def _run(db_session):
+        from backend.app.core.database import seed_default_groups
+
+        await seed_default_groups()
+        db_session.expire_all()
+
+    @pytest.mark.asyncio
+    async def test_a_demoted_admin_loses_the_admin_role(self, async_client: AsyncClient, db_session):
+        admins, operators = await _groups(db_session)
+        await _user(db_session, "admin", "admin", [admins])
+        demoted = await _user(db_session, "mike", "admin", [operators])
+        await self._rearm(db_session)
+
+        await self._run(db_session)
+
+        user = await _load(db_session, demoted)
+        assert user.role == "user"
+        assert not user.is_admin
+        flag = await db_session.scalar(select(Settings.value).where(Settings.key == self.FLAG))
+        assert flag == "true"
+
+    @pytest.mark.asyncio
+    async def test_the_only_admin_joins_administrators_instead(self, async_client: AsyncClient, db_session):
+        _, operators = await _groups(db_session)
+        only = await _user(db_session, "admin", "admin", [operators])
+        await self._rearm(db_session)
+
+        await self._run(db_session)
+
+        user = await _load(db_session, only)
+        assert user.is_admin
+        assert "Administrators" in [g.name for g in user.groups]
+
+    @pytest.mark.asyncio
+    async def test_runs_once(self, async_client: AsyncClient, db_session):
+        admins, operators = await _groups(db_session)
+        await _user(db_session, "admin", "admin", [admins])
+        await self._rearm(db_session)
+        db_session.add(Settings(key=self.FLAG, value="true"))
+        await db_session.commit()
+        kept = await _user(db_session, "mike", "admin", [operators])
+
+        await self._run(db_session)
+
+        assert (await _load(db_session, kept)).role == "admin"
+
+
+class TestIdentityProviderSync:
+    """LDAP and OIDC logins set the groups too, so the role follows there."""
+
+    @pytest.mark.asyncio
+    async def test_an_ldap_login_that_drops_administrators_drops_the_role(self, db_session):
+        from types import SimpleNamespace
+
+        from backend.app.api.routes.auth import _sync_ldap_user
+
+        admins, operators = await _groups(db_session)
+        user_id = await _user(db_session, "alice", "admin", [admins])
+        user = await _load(db_session, user_id)
+        user.auth_source = "ldap"
+        user.email = "alice@example.invalid"
+        await db_session.commit()
+
+        await _sync_ldap_user(
+            db_session,
+            user,
+            SimpleNamespace(username="alice", email="alice@example.invalid", groups=["cn=ops"]),
+            SimpleNamespace(group_mapping={"cn=admins": "Administrators", "cn=ops": "Operators"}, default_group=""),
+        )
+
+        user = await _load(db_session, user_id)
+        assert [g.name for g in user.groups] == ["Operators"]
+        assert user.role == "user"
+        assert not user.is_admin
+
+    @pytest.mark.asyncio
+    async def test_an_oidc_login_into_administrators_sets_the_role(self, db_session):
+        from backend.app.services.oidc_group_sync import sync_oidc_user_groups
+
+        admins, operators = await _groups(db_session)
+        user_id = await _user(db_session, "bob", "user", [operators])
+        user = await _load(db_session, user_id)
+
+        await sync_oidc_user_groups(
+            db_session,
+            user,
+            group_claim="groups",
+            group_mapping={"staff": "Administrators"},
+            claims={"groups": ["staff"]},
+        )
+
+        assert (await _load(db_session, user_id)).role == "admin"
+
+    @pytest.mark.asyncio
+    async def test_an_ldap_user_created_into_administrators_gets_the_role(self, db_session):
+        from types import SimpleNamespace
+
+        from backend.app.api.routes.auth import _provision_ldap_user
+
+        await _groups(db_session)
+
+        user = await _provision_ldap_user(
+            db_session,
+            SimpleNamespace(username="carol", email="carol@example.invalid", groups=["cn=admins"]),
+            SimpleNamespace(group_mapping={"cn=admins": "Administrators"}, default_group=""),
+        )
+
+        assert (await _load(db_session, user.id)).role == "admin"

+ 5 - 5
backend/tests/integration/test_ams_slot_material_2902.py

@@ -312,10 +312,10 @@ class TestSpoolmanInventoryAssign:
 
         assert sent["tray_type"] == "PLA"
         assert sent["tray_info_idx"] == "GFL99"
-        # Exactly, not just "contains PLA+": the filament's own name is in this
-        # string too, so a substring check would pass even if the material had
-        # been reduced before it was built.
-        assert sent["tray_sub_brands"] == "eSUN PLA+ Cool White"
+        # Exactly, not just "contains PLA+", so a reduced material would show.
+        # The filament's name "Cool White" is its colour (#3561), which is not
+        # part of the sub-brand.
+        assert sent["tray_sub_brands"] == "eSUN PLA+"
 
     @pytest.mark.asyncio
     @pytest.mark.integration
@@ -440,7 +440,7 @@ class TestSpoolmanLink:
 
         assert sent["tray_type"] == "PLA"
         assert sent["tray_info_idx"] == "GFL99"
-        assert sent["tray_sub_brands"] == "eSUN PLA+ Cool White"
+        assert sent["tray_sub_brands"] == "eSUN PLA+"  # "Cool White" is the colour (#3561)
         assert (sent["nozzle_temp_min"], sent["nozzle_temp_max"]) == (190, 230)
 
     @pytest.mark.asyncio

+ 368 - 0
backend/tests/integration/test_ams_slot_support_type_3559.py

@@ -0,0 +1,368 @@
+"""A support filament has to reach its AMS slot as a support type (#3559).
+
+The reporter set a slot to "Bambu Support For PLA" and every PLA part still
+matched it. BambuStudio writes a support preset into a slot as "PLA-S" (or
+"PA-S"), and a plate sliced with one declares the same; Bambuddy wrote "PLA".
+The Configure dialog reads the type off the preset name, and the reduction
+every slot-writing route runs (#2902) then cut "PLA-S" itself back to "PLA" --
+so the slot offered support filament to every plain PLA part, and to nothing
+that asked for support.
+
+All four routes that configure a slot are covered, plus the auto-unlink check
+that has to recognise the slot it just wrote.
+"""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from backend.app.models.spool import Spool
+from backend.app.utils.filament_types import printer_filament_type, support_filament_type
+from backend.tests.integration.test_ams_slot_material_2902 import (
+    _mqtt_mock,
+    _spoolman_client,
+    _spoolman_spool,
+    _status,
+)
+
+
+class TestTheTypeRule:
+    """BambuStudio's ``get_filament_type`` (libslic3r/PrintConfig.cpp)."""
+
+    @pytest.mark.parametrize("support_type", ["PLA-S", "PA-S", "ABS-S"])
+    def test_a_support_type_is_not_reduced_to_its_base(self, support_type):
+        assert printer_filament_type(support_type) == support_type
+        assert printer_filament_type(support_type.lower()) == support_type
+
+    @pytest.mark.parametrize(
+        ("filament_id", "expected"),
+        [
+            ("GFS00", "PLA-S"),  # Support W
+            ("GFS01", "PA-S"),  # Support G
+            ("GFS02", "PLA-S"),  # Support For PLA
+            ("GFS03", "PA-S"),  # Support For PA/PET
+            ("GFS05", "PLA-S"),  # Support For PLA/PETG
+            ("GFS06", "ABS"),  # Support for ABS: the one Bambu leaves alone
+        ],
+    )
+    def test_a_bambu_support_id_decides_the_type(self, filament_id, expected):
+        # Whatever the name made of it: "Support For PLA/PETG" reads as PETG,
+        # and Support W / G name no material at all.
+        for guessed in ("PLA", "PETG", "PA"):
+            assert support_filament_type(guessed, filament_id, "") == expected
+
+    @pytest.mark.parametrize(
+        ("tray_type", "name", "expected"),
+        [
+            ("PLA", "Bambu Support For PLA", "PLA-S"),
+            ("PLA", "Sunlu Support for PLA @BBL X1C", "PLA-S"),
+            ("PA", "Acme Support for PA", "PA-S"),
+            # A third-party "X Support for Y" preset is a Y preset; the slicer
+            # keeps its declared type, and so does this (330d77198).
+            ("PETG", "PLA Support for PETG PETG Basic", "PETG"),
+            ("ABS", "Acme Support for ABS", "ABS"),
+            # A word, not a fragment of one.
+            ("PLA", "PolySupport PLA", "PLA"),
+            ("PLA", "Bambu PLA Basic", "PLA"),
+            ("PLA", "", "PLA"),
+        ],
+    )
+    def test_without_a_bambu_id_the_preset_name_says_whether_it_is_support(self, tray_type, name, expected):
+        assert support_filament_type(tray_type, "P4d64437", name) == expected
+
+    def test_an_unrelated_id_is_left_alone(self):
+        assert support_filament_type("PLA", "GFA00", "Bambu PLA Basic") == "PLA"
+        assert support_filament_type("PLA-S", "", "") == "PLA-S"
+
+
+class TestConfigureSlotModal:
+    async def _configure(self, async_client, printer_factory, **params):
+        printer = await printer_factory(model="X1C")
+        client = _mqtt_mock()
+        with patch("backend.app.api.routes.printers.printer_manager") as pm:
+            pm.get_client.return_value = client
+            pm.get_status.return_value = _status()
+            response = await async_client.post(
+                f"/api/v1/printers/{printer.id}/slots/0/3/configure",
+                params={
+                    "tray_color": "E1E9E9FF",
+                    "nozzle_temp_min": 190,
+                    "nozzle_temp_max": 230,
+                    **params,
+                },
+            )
+        assert response.status_code == 200
+        return client.ams_set_filament_setting.call_args.kwargs
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_reported_case_a_bambu_support_preset(self, async_client: AsyncClient, printer_factory):
+        """What the dialog sends for "Bambu Support For PLA": the type it read off
+        the name, and the preset's filament id."""
+        sent = await self._configure(
+            async_client,
+            printer_factory,
+            tray_info_idx="GFS02",
+            tray_type="PLA",
+            tray_sub_brands="Bambu Support For PLA",
+        )
+
+        assert sent["tray_type"] == "PLA-S"
+        assert sent["tray_info_idx"] == "GFS02"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_support_for_pla_petg_is_pla_s_not_petg(self, async_client: AsyncClient, printer_factory):
+        sent = await self._configure(
+            async_client,
+            printer_factory,
+            tray_info_idx="GFS05",
+            tray_type="PETG",
+            tray_sub_brands="Bambu Support For PLA/PETG",
+        )
+
+        assert sent["tray_type"] == "PLA-S"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_user_preset_of_its_own_by_its_name(self, async_client: AsyncClient, printer_factory):
+        """A non-Bambu support filament on a user preset: its own id, so only the
+        name can say it is support -- the reporter's case."""
+        sent = await self._configure(
+            async_client,
+            printer_factory,
+            tray_info_idx="P4d64437",
+            tray_type="PLA",
+            tray_sub_brands="Jade White Support For PLA",
+        )
+
+        assert sent["tray_type"] == "PLA-S"
+        assert sent["tray_info_idx"] == "P4d64437"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_plain_pla_preset_is_untouched(self, async_client: AsyncClient, printer_factory):
+        sent = await self._configure(
+            async_client,
+            printer_factory,
+            tray_info_idx="GFA00",
+            tray_type="PLA",
+            tray_sub_brands="Bambu PLA Basic",
+        )
+
+        assert sent["tray_type"] == "PLA"
+
+
+class TestInternalInventoryAssign:
+    async def _assign(self, async_client, db_session, **spool_kwargs):
+        from backend.app.models.printer import Printer
+
+        printer = Printer(
+            name="X1C",
+            serial_number="SUP3559INV",
+            ip_address="192.168.1.80",
+            access_code="12345678",
+        )
+        db_session.add(printer)
+        spool = Spool(rgba="FFFFFFFF", label_weight=500, weight_used=0, **spool_kwargs)
+        db_session.add(spool)
+        await db_session.commit()
+        await db_session.refresh(printer)
+        await db_session.refresh(spool)
+
+        client = _mqtt_mock()
+        with patch("backend.app.services.printer_manager.printer_manager") as pm:
+            pm.get_client.return_value = client
+            pm.get_status.return_value = _status()
+            response = await async_client.post(
+                "/api/v1/inventory/assignments",
+                json={"spool_id": spool.id, "printer_id": printer.id, "ams_id": 0, "tray_id": 1},
+            )
+        assert response.status_code == 200
+        return client.ams_set_filament_setting.call_args.kwargs
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_spool_made_from_a_support_rfid_tray(self, async_client: AsyncClient, db_session: AsyncSession):
+        """A Bambu support spool read by RFID is stored with the tray's
+        sub-brand as its material. Moved to another slot by Bambuddy, it used to
+        go in as plain PLA."""
+        sent = await self._assign(
+            async_client, db_session, material="Support For PLA", brand="Bambu Lab", slicer_filament="GFS02"
+        )
+
+        assert sent["tray_type"] == "PLA-S"
+        assert sent["tray_info_idx"] == "GFS02"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_spool_whose_material_already_says_pla_s(self, async_client: AsyncClient, db_session: AsyncSession):
+        sent = await self._assign(async_client, db_session, material="PLA-S", brand="Sunlu")
+
+        assert sent["tray_type"] == "PLA-S"
+        # The slot still gets a filament id the printer can resolve.
+        assert sent["tray_info_idx"] == "GFL99"
+
+
+class TestSpoolmanRoutes:
+    @pytest.fixture
+    async def settings(self, db_session):
+        from backend.app.models.settings import Settings
+
+        db_session.add(Settings(key="spoolman_enabled", value="true"))
+        db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
+        await db_session.commit()
+
+    @pytest.fixture
+    async def printer(self, db_session):
+        from backend.app.models.printer import Printer
+
+        p = Printer(
+            name="Spoolman X1C",
+            serial_number="SUP3559SM",
+            ip_address="192.168.1.81",
+            access_code="12345678",
+        )
+        db_session.add(p)
+        await db_session.commit()
+        await db_session.refresh(p)
+        return p
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_slot_assignment_route(self, async_client: AsyncClient, settings, printer):
+        mqtt = _mqtt_mock()
+        spool = _spoolman_spool("Support For PLA")
+        with (
+            patch("backend.app.api.routes.spoolman_inventory.printer_manager") as pm,
+            patch(
+                "backend.app.api.routes.spoolman_inventory.get_spoolman_client",
+                AsyncMock(return_value=_spoolman_client(spool)),
+            ),
+        ):
+            pm.get_client.return_value = mqtt
+            pm.get_status.return_value = _status()
+            response = await async_client.post(
+                "/api/v1/spoolman/inventory/slot-assignments",
+                json={"spoolman_spool_id": 11, "printer_id": printer.id, "ams_id": 0, "tray_id": 2},
+            )
+        assert response.status_code == 200
+        assert mqtt.ams_set_filament_setting.call_args.kwargs["tray_type"] == "PLA-S"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_tag_link_route(self, async_client: AsyncClient, settings, printer):
+        client = _spoolman_client(_spoolman_spool("Support For PLA", spool_id=12))
+        mqtt = _mqtt_mock()
+        with (
+            patch("backend.app.api.routes.spoolman.get_spoolman_client", AsyncMock(return_value=client)),
+            patch("backend.app.api.routes.spoolman.init_spoolman_client", AsyncMock(return_value=client)),
+            patch("backend.app.api.routes.spoolman.printer_manager") as pm,
+        ):
+            pm.get_client.return_value = mqtt
+            pm.get_status.return_value = _status()
+            response = await async_client.post(
+                "/api/v1/spoolman/spools/12/link",
+                json={
+                    "tray_uuid": "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4",
+                    "printer_id": printer.id,
+                    "ams_id": 0,
+                    "tray_id": 3,
+                },
+            )
+        assert response.status_code == 200
+        assert mqtt.ams_set_filament_setting.call_args.kwargs["tray_type"] == "PLA-S"
+
+
+class TestTheAssignmentSurvivesTheSlotItJustConfigured:
+    """on_ams_change unlinks an assignment whose slot no longer looks like its
+    spool. The slot now carries "PLA-S", which no spool column says."""
+
+    async def _push(self, db_session, printer_factory, reported_type, **spool_kwargs):
+        from backend.app.main import on_ams_change
+        from backend.app.models.spool_assignment import SpoolAssignment
+
+        printer = await printer_factory(name="X1C")
+        spool = Spool(rgba="FFFFFFFF", label_weight=500, weight_used=0, **spool_kwargs)
+        db_session.add(spool)
+        await db_session.commit()
+        await db_session.refresh(spool)
+
+        assignment = SpoolAssignment(
+            spool_id=spool.id,
+            printer_id=printer.id,
+            ams_id=0,
+            tray_id=2,
+            fingerprint_color="FFFFFFFF",
+            fingerprint_type="PETG",
+        )
+        db_session.add(assignment)
+        await db_session.commit()
+        assignment_id = assignment.id
+
+        ams_data = [{"id": 0, "tray": [{"id": 2, "tray_type": reported_type, "tray_color": "FFFFFFFF", "state": 11}]}]
+        status = _status(ams_data)
+        status.state = "IDLE"
+
+        with (
+            patch("backend.app.main.printer_manager") as pm,
+            patch("backend.app.main.mqtt_relay") as relay,
+            patch("backend.app.main.ws_manager") as ws,
+        ):
+            pm.get_printer.return_value = MagicMock(name="X1C", serial_number="00M00A000000001")
+            pm.get_status.return_value = status
+            pm.get_model.return_value = "X1C"
+            relay.on_ams_change = AsyncMock()
+            ws.send_printer_status = AsyncMock()
+            ws.broadcast = AsyncMock()
+
+            await on_ams_change(printer.id, ams_data)
+
+        db_session.expunge_all()
+        return await db_session.get(SpoolAssignment, assignment_id)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_support_spool_stays_on_the_pla_s_slot_it_configured(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory
+    ):
+        surviving = await self._push(
+            db_session, printer_factory, "PLA-S", material="PLA", slicer_filament_name="Bambu Support For PLA"
+        )
+
+        assert surviving is not None
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_so_does_one_made_from_a_support_rfid_tray(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory
+    ):
+        surviving = await self._push(db_session, printer_factory, "PLA-S", material="Support For PLA")
+
+        assert surviving is not None
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_and_a_slot_an_older_version_configured_as_pla(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory
+    ):
+        """Slots configured before this fix still report "PLA" until someone
+        reconfigures them; their spools must not be unlinked meanwhile."""
+        surviving = await self._push(
+            db_session, printer_factory, "PLA", material="PLA", slicer_filament_name="Bambu Support For PLA"
+        )
+
+        assert surviving is not None
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_but_a_plain_pla_spool_on_a_support_slot_is_a_swap(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory
+    ):
+        surviving = await self._push(
+            db_session, printer_factory, "PLA-S", material="PLA", slicer_filament_name="Bambu PLA Basic"
+        )
+
+        assert surviving is None

+ 20 - 0
backend/tests/integration/test_archive_merge.py

@@ -7,6 +7,7 @@ alias, their money untouched.
 
 from __future__ import annotations
 
+import zipfile
 from datetime import datetime, timedelta
 from pathlib import Path
 from types import SimpleNamespace
@@ -583,6 +584,25 @@ async def test_the_survivor_reads_its_plates_from_the_file_it_takes_over(async_c
     assert archive.plate_estimates == PLATES
 
 
+async def test_the_survivor_reads_the_gcode_of_the_file_it_takes_over(async_client, db_session, files, dupes):
+    """#1634: a slice sent again from the slicer finds the survivor by it."""
+    from backend.app.services.archive_gcode_hash import NO_GCODE, gcode_fingerprint
+
+    (dupes.x_dir / "file.3mf").unlink()
+    for folder in (dupes.y_dir, dupes.z_dir):
+        with zipfile.ZipFile(folder / "file.3mf", "w") as zf:
+            zf.writestr("Metadata/plate_1.gcode", "G28\n")
+    survivor = await db_session.get(PrintArchive, dupes.x)
+    survivor.gcode_hash = NO_GCODE  # read while its file was missing
+    await db_session.commit()
+
+    await async_client.post("/api/v1/archives/merge", json={"survivor_ids": [dupes.x]})
+
+    archive = await _row(db_session, PrintArchive, dupes.x)
+    assert archive.gcode_hash == gcode_fingerprint(files / archive.file_path)
+    assert archive.gcode_hash not in (None, NO_GCODE)
+
+
 async def test_a_copy_that_fails_leaves_no_partial_file(files):
     from backend.app.services.archive_merge import _Files
 

+ 315 - 0
backend/tests/integration/test_assign_preset_cloud_user_3519.py

@@ -0,0 +1,315 @@
+"""A custom cloud preset resolves the same way from an API key and on insert (#3519).
+
+With login on, each user signs in to Bambu Cloud separately and the shared
+sign-in is empty. An API key (a SpoolBuddy client) has no signed-in user, and
+the replay on insert has none either, so both looked the PFUS preset up with
+nobody's sign-in and sent Generic PLA (GFL99) where the web UI sent the
+preset's own filament. Both now use a user: the key's owner, and whoever made
+the assignment.
+"""
+
+import logging
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from backend.app.models.spool import Spool
+from backend.app.models.spool_assignment import SpoolAssignment
+
+PFUS = "PFUSdfae86e31579cb"
+
+
+def _status(ams_data):
+    status = MagicMock()
+    status.raw_data = {"ams": {"ams": ams_data}}
+    status.nozzles = [MagicMock(nozzle_diameter="0.4")]
+    status.ams_extruder_map = None
+    return status
+
+
+def _fake_cloud(seen: list):
+    """build_authenticated_cloud stand-in: records whose sign-in was asked for.
+
+    Only a user's own sign-in finds the preset, as on a per-user install
+    where the shared one is empty.
+    """
+    cloud = MagicMock()
+    cloud.is_authenticated = True
+    cloud.get_setting_detail = AsyncMock(return_value={"filament_id": "SUN20011", "name": "SUNLU PLA META"})
+    cloud.close = AsyncMock()
+
+    async def build(_db, user):
+        seen.append(user.id if user is not None else None)
+        return cloud if user is not None else None
+
+    return build
+
+
+@pytest.fixture
+async def auth_on(db_session: AsyncSession):
+    from backend.app.models.settings import Settings
+
+    db_session.add(Settings(key="auth_enabled", value="true"))
+    await db_session.commit()
+
+
+@pytest.fixture
+async def owner(db_session: AsyncSession):
+    from backend.app.models.user import User
+
+    user = User(username="spoolowner", password_hash="x", role="admin", is_active=True)
+    db_session.add(user)
+    await db_session.commit()
+    await db_session.refresh(user)
+    return user
+
+
+@pytest.fixture
+async def spool(db_session: AsyncSession):
+    row = Spool(
+        material="PLA",
+        subtype="Basic",
+        brand="SUNLU",
+        rgba="FF0000FF",
+        label_weight=1000,
+        weight_used=0,
+        slicer_filament=PFUS,
+    )
+    db_session.add(row)
+    await db_session.commit()
+    await db_session.refresh(row)
+    return row
+
+
+async def _owned_key(db_session: AsyncSession, user_id: int | None) -> str:
+    from backend.app.core.auth import generate_api_key
+    from backend.app.models.api_key import APIKey
+
+    full_key, key_hash, key_prefix = generate_api_key()
+    db_session.add(
+        APIKey(
+            name="espoolbuddy",
+            key_hash=key_hash,
+            key_prefix=key_prefix,
+            user_id=user_id,
+            can_manage_inventory=True,
+            can_read_status=True,
+            enabled=True,
+        )
+    )
+    await db_session.commit()
+    return full_key
+
+
+async def _assign_with_key(async_client: AsyncClient, key: str, printer_id: int, spool_id: int, seen: list):
+    mock_client = MagicMock()
+    mock_client.ams_set_filament_setting.return_value = True
+    mock_client.extrusion_cali_sel.return_value = True
+    status = _status([{"id": 0, "tray": [{"id": 0, "tray_info_idx": "", "tray_type": "PLA", "state": 11}]}])
+    with (
+        patch("backend.app.services.printer_manager.printer_manager") as mock_pm,
+        patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud(seen)),
+    ):
+        mock_pm.get_client.return_value = mock_client
+        mock_pm.get_status.return_value = status
+        response = await async_client.post(
+            "/api/v1/inventory/assignments",
+            json={"spool_id": spool_id, "printer_id": printer_id, "ams_id": 0, "tray_id": 0},
+            headers={"X-API-Key": key},
+        )
+    return response, mock_client
+
+
+async def _replay(printer_id: int, seen: list):
+    from backend.app.main import on_ams_change
+
+    ams_data = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF", "state": 11}]}]
+    mock_client = MagicMock()
+    mock_client.ams_set_filament_setting.return_value = True
+    mock_client.extrusion_cali_sel.return_value = True
+    status = _status(ams_data)
+    with (
+        patch("backend.app.main.printer_manager") as mock_pm_main,
+        patch("backend.app.services.printer_manager.printer_manager") as mock_pm_inv,
+        patch("backend.app.main.mqtt_relay") as mock_relay,
+        patch("backend.app.main.ws_manager") as mock_ws,
+        patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud(seen)),
+    ):
+        mock_pm_main.get_printer.return_value = MagicMock(name="H2C", serial_number="0948BB540200427")
+        mock_pm_main.get_status.return_value = status
+        mock_pm_main.get_client.return_value = mock_client
+        mock_pm_main.get_model.return_value = "H2C"
+        mock_pm_inv.get_client.return_value = mock_client
+        mock_pm_inv.get_status.return_value = status
+        mock_relay.on_ams_change = AsyncMock()
+        mock_ws.send_printer_status = AsyncMock()
+        mock_ws.broadcast = AsyncMock()
+        await on_ams_change(printer_id, ams_data)
+    return mock_client
+
+
+class TestApiKeyAssign:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_keys_owner_resolves_the_preset(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        printer = await printer_factory(name="H2C")
+        key = await _owned_key(db_session, owner.id)
+        seen: list = []
+
+        response, mock_client = await _assign_with_key(async_client, key, printer.id, spool.id, seen)
+
+        assert response.status_code == 200
+        assert seen == [owner.id]
+        kwargs = mock_client.ams_set_filament_setting.call_args.kwargs
+        assert kwargs["tray_info_idx"] == "SUN20011"
+        assert kwargs["setting_id"] == PFUS
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_assignment_remembers_the_owner(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        printer = await printer_factory(name="H2C")
+        key = await _owned_key(db_session, owner.id)
+
+        response, _ = await _assign_with_key(async_client, key, printer.id, spool.id, [])
+
+        assert response.status_code == 200
+        row = await db_session.get(SpoolAssignment, response.json()["id"])
+        await db_session.refresh(row)
+        assert row.assigned_by_user_id == owner.id
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_an_ownerless_key_still_assigns(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, spool
+    ):
+        """A key from before keys had owners has no sign-in to use: generic, as before."""
+        printer = await printer_factory(name="H2C")
+        key = await _owned_key(db_session, None)
+        seen: list = []
+
+        response, mock_client = await _assign_with_key(async_client, key, printer.id, spool.id, seen)
+
+        assert response.status_code == 200
+        assert seen == [None]
+        assert mock_client.ams_set_filament_setting.call_args.kwargs["tray_info_idx"] == "GFL99"
+
+
+class TestReplayOnInsert:
+    async def _pre_assigned(self, db_session: AsyncSession, printer_id: int, spool_id: int, user_id: int | None):
+        db_session.add(
+            SpoolAssignment(
+                spool_id=spool_id,
+                printer_id=printer_id,
+                ams_id=0,
+                tray_id=0,
+                fingerprint_color=None,
+                fingerprint_type=None,
+                assigned_by_user_id=user_id,
+            )
+        )
+        await db_session.commit()
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_assigning_user_resolves_the_preset(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        printer = await printer_factory(name="H2C")
+        await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
+        seen: list = []
+
+        mock_client = await _replay(printer.id, seen)
+
+        assert seen == [owner.id]
+        assert mock_client.ams_set_filament_setting.call_args.kwargs["tray_info_idx"] == "SUN20011"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_with_login_off_the_shared_sign_in_applies(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, owner, spool
+    ):
+        """A user id kept from when login was on doesn't pick a per-user sign-in."""
+        printer = await printer_factory(name="H2C")
+        await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
+        seen: list = []
+
+        await _replay(printer.id, seen)
+
+        assert seen == [None]
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_deactivated_user_is_not_used(
+        self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
+    ):
+        owner.is_active = False
+        await db_session.commit()
+        printer = await printer_factory(name="H2C")
+        await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
+        seen: list = []
+
+        await _replay(printer.id, seen)
+
+        assert seen == [None]
+
+
+class TestUnresolvedPresetIsLogged:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_custom_preset_without_a_sign_in_warns(self, db_session: AsyncSession, caplog):
+        from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
+
+        with (
+            patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud([])),
+            caplog.at_level(logging.WARNING, logger="backend.app.services.slicer_filament_resolver"),
+        ):
+            await resolve_slicer_filament(
+                db=db_session, current_user=None, slicer_filament=PFUS, slicer_filament_name=None, material="PLA"
+            )
+
+        assert any("not looked up" in r.getMessage() and PFUS in r.getMessage() for r in caplog.records)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_an_official_preset_does_not(self, db_session: AsyncSession, caplog):
+        """A GFS id parses without the cloud, so nothing is lost."""
+        from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
+
+        with (
+            patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud([])),
+            caplog.at_level(logging.WARNING, logger="backend.app.services.slicer_filament_resolver"),
+        ):
+            await resolve_slicer_filament(
+                db=db_session, current_user=None, slicer_filament="GFSL05", slicer_filament_name=None, material="PLA"
+            )
+
+        assert not any("not looked up" in r.getMessage() for r in caplog.records)
+
+
+class TestDeletedUser:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_deleting_the_user_clears_the_assignment_s_user(
+        self, db_session: AsyncSession, printer_factory, owner, spool
+    ):
+        """Or the next user given the freed id would lend the slot their sign-in."""
+        from sqlalchemy import select
+
+        printer = await printer_factory(name="H2C")
+        db_session.add(
+            SpoolAssignment(spool_id=spool.id, printer_id=printer.id, ams_id=0, tray_id=0, assigned_by_user_id=owner.id)
+        )
+        await db_session.commit()
+
+        await db_session.delete(owner)
+        await db_session.commit()
+
+        db_session.expire_all()
+        row = (await db_session.execute(select(SpoolAssignment))).scalar_one()
+        assert row.assigned_by_user_id is None

+ 166 - 0
backend/tests/integration/test_backup_restore_off_event_loop.py

@@ -0,0 +1,166 @@
+"""Backup and restore do their file work off the event loop.
+
+Unzipping a backup, copying the data directories back and writing a backup ZIP
+ran on the event loop. With a large archive folder that froze the whole server
+for over half a minute -- no page, no websocket, no printer message -- and the
+loop watchdog dumped every thread's stack in the middle of a restore that then
+succeeded.
+
+Each test makes one step slow and counts how often a ticker on the loop gets to
+run meanwhile. On the loop, the step starves it; in a worker thread it ticks on.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import io
+import sqlite3
+import time
+import zipfile
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from backend.app.api.routes import settings as settings_routes
+from backend.app.core.config import settings as app_settings
+
+STEP_SECONDS = 0.5
+TICK_SECONDS = 0.02
+# Off the loop the ticker runs ~25 times during the step; on it, not at all.
+MIN_TICKS = 8
+
+
+class _Ticker:
+    """Counts loop ticks, and how many happened while the slow step ran."""
+
+    def __init__(self):
+        self.ticks = 0
+        self.during_step: list[int] = []
+
+    def slow(self, fn):
+        def wrapper(*args, **kwargs):
+            before = self.ticks
+            time.sleep(STEP_SECONDS)
+            self.during_step.append(self.ticks - before)
+            return fn(*args, **kwargs)
+
+        return wrapper
+
+    async def run_while(self, coro):
+        done = False
+
+        async def tick():
+            while not done:
+                await asyncio.sleep(TICK_SECONDS)
+                self.ticks += 1
+
+        task = asyncio.create_task(tick())
+        try:
+            return await coro
+        finally:
+            done = True
+            await task
+
+
+def _data_dir(monkeypatch, tmp_path):
+    db_path = tmp_path / "bambuddy.db"
+    with sqlite3.connect(db_path) as db:
+        db.execute("CREATE TABLE backup_marker (id INTEGER PRIMARY KEY)")
+    (tmp_path / "archive" / "1").mkdir(parents=True)
+    (tmp_path / "archive" / "1" / "print.3mf").write_bytes(b"x" * 1024)
+    monkeypatch.setenv("DATA_DIR", str(tmp_path))
+    monkeypatch.setattr(app_settings, "base_dir", tmp_path)
+    monkeypatch.setattr(app_settings, "database_url", f"sqlite+aiosqlite:///{db_path}")
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+@pytest.mark.sqlite_only  # copies the app's own SQLite database file
+@pytest.mark.parametrize("step", ["_copy_backup_dirs", "_write_backup_zip", "shutil.copy2"])
+async def test_a_slow_backup_step_does_not_block_the_loop(async_client, monkeypatch, tmp_path, step):
+    import shutil
+
+    _data_dir(monkeypatch, tmp_path)
+    ticker = _Ticker()
+    if step == "shutil.copy2":
+        monkeypatch.setattr(shutil, "copy2", ticker.slow(shutil.copy2))
+    else:
+        monkeypatch.setattr(settings_routes, step, ticker.slow(getattr(settings_routes, step)))
+
+    out = tmp_path / "out"
+    out.mkdir()
+    zip_path, _ = await ticker.run_while(settings_routes.create_backup_zip(output_path=out))
+
+    with zipfile.ZipFile(zip_path) as zf:
+        names = zf.namelist()
+    assert "bambuddy.db" in names
+    assert "archive/1/print.3mf" in names
+    assert ticker.during_step, f"{step} was not called"
+    assert min(ticker.during_step) >= MIN_TICKS, f"{step} blocked the event loop: {ticker.during_step}"
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+@pytest.mark.sqlite_only  # restores into the app's own SQLite database file
+@pytest.mark.parametrize("step", ["_extract_backup_zip", "_restore_sqlite_db", "_restore_data_dirs"])
+async def test_a_slow_restore_step_does_not_block_the_loop(async_client, monkeypatch, tmp_path, step):
+    _data_dir(monkeypatch, tmp_path)
+    out = tmp_path / "out"
+    out.mkdir()
+    zip_path, _ = await settings_routes.create_backup_zip(output_path=out)
+    payload = zip_path.read_bytes()
+    # The restore must put the archive back, so take it away first.
+    (tmp_path / "archive" / "1" / "print.3mf").unlink()
+
+    ticker = _Ticker()
+    monkeypatch.setattr(settings_routes, step, ticker.slow(getattr(settings_routes, step)))
+    with (
+        patch("backend.app.core.database.close_all_connections", new_callable=AsyncMock),
+        patch("backend.app.core.database.reinitialize_database", new_callable=AsyncMock),
+        patch("backend.app.core.database.init_db", new_callable=AsyncMock),
+        patch("backend.app.core.database.invalidate_all_sessions", new_callable=AsyncMock),
+        patch("backend.app.services.backup_paths.convert_windows_paths", new_callable=AsyncMock),
+        patch("backend.app.services.print_scheduler.scheduler.stop"),
+        patch("backend.app.services.smart_plug_manager.smart_plug_manager.stop_scheduler"),
+        patch("backend.app.services.notification_service.notification_service.stop_digest_scheduler"),
+    ):
+        response = await ticker.run_while(
+            async_client.post(
+                "/api/v1/settings/restore",
+                files={"file": ("backup.zip", payload, "application/zip")},
+            )
+        )
+
+    assert response.status_code == 200, response.text
+    assert (tmp_path / "archive" / "1" / "print.3mf").read_bytes() == b"x" * 1024
+    assert ticker.during_step, f"{step} was not called"
+    assert min(ticker.during_step) >= MIN_TICKS, f"{step} blocked the event loop: {ticker.during_step}"
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_an_unsafe_path_is_still_refused(async_client):
+    buffer = io.BytesIO()
+    with zipfile.ZipFile(buffer, "w") as zf:
+        zf.writestr("../evil.txt", "x")
+        zf.writestr("bambuddy.db", "x")
+
+    response = await async_client.post(
+        "/api/v1/settings/restore",
+        files={"file": ("backup.zip", buffer.getvalue(), "application/zip")},
+    )
+
+    assert response.status_code == 400
+    assert "unsafe path" in response.json()["detail"]
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_a_file_that_is_not_a_zip_is_still_refused(async_client):
+    response = await async_client.post(
+        "/api/v1/settings/restore",
+        files={"file": ("backup.zip", b"not a zip", "application/zip")},
+    )
+
+    assert response.status_code == 400
+    assert "not a valid ZIP" in response.json()["detail"]

+ 156 - 0
backend/tests/integration/test_cloud_fields_slicer_types_2928.py

@@ -0,0 +1,156 @@
+"""The profile editor's Material type follows the preferred slicer (#2928).
+
+Bambu Studio and OrcaSlicer do not accept the same ``filament_type`` values
+(Orca has SBS, Bambu Studio has TPU-AMS), so GET /cloud/fields/filament offers
+those of the slicer chosen in Settings -> Slicer, and nothing else about the
+field definitions changes.
+"""
+
+import json
+from pathlib import Path
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy import update
+
+from backend.app.api.routes.cloud import _load_fields
+from backend.app.models.settings import Settings
+
+DATA = Path(__file__).resolve().parents[2] / "app" / "data"
+
+
+def _type_field(fields: dict) -> dict:
+    return next(f for f in fields["fields"] if f["key"] == "filament_type")
+
+
+def _values(fields: dict) -> list[str]:
+    return [option["value"] for option in _type_field(fields)["options"]]
+
+
+async def _prefer(db_session, slicer: str) -> None:
+    """Set the preferred slicer, whether or not the setting exists yet."""
+    changed = await db_session.execute(update(Settings).where(Settings.key == "preferred_slicer").values(value=slicer))
+    if not changed.rowcount:
+        db_session.add(Settings(key="preferred_slicer", value=slicer))
+    await db_session.commit()
+
+
+class TestFilamentFieldsFollowThePreferredSlicer:
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_bambu_studio_is_the_default(self, async_client: AsyncClient):
+        response = await async_client.get("/api/v1/cloud/fields/filament")
+
+        assert response.status_code == 200
+        values = _values(response.json())
+        assert "TPU-AMS" in values
+        assert "SBS" not in values
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_bambu_studio_offers_its_own_types(self, async_client: AsyncClient, db_session):
+        await _prefer(db_session, "bambu_studio")
+
+        values = _values((await async_client.get("/api/v1/cloud/fields/filament")).json())
+
+        assert (
+            values
+            == json.loads((DATA / "slicer_filament_types.json").read_text(encoding="utf-8"))["bambu_studio"]["values"]
+        )
+        assert {"TPU-AMS", "ASA-AERO", "PE-CF"} <= set(values)
+        assert {"SBS", "PA6-GF", "PEEK"}.isdisjoint(values)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_orcaslicer_offers_its_own_types(self, async_client: AsyncClient, db_session):
+        await _prefer(db_session, "orcaslicer")
+
+        values = _values((await async_client.get("/api/v1/cloud/fields/filament")).json())
+
+        assert (
+            values
+            == json.loads((DATA / "slicer_filament_types.json").read_text(encoding="utf-8"))["orcaslicer"]["values"]
+        )
+        assert {"SBS", "PA6-GF", "PEEK"} <= set(values)
+        assert "TPU-AMS" not in values
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_changing_the_slicer_changes_the_list_on_the_next_request(
+        self, async_client: AsyncClient, db_session
+    ):
+        await _prefer(db_session, "orcaslicer")
+        assert "SBS" in _values((await async_client.get("/api/v1/cloud/fields/filament")).json())
+
+        await _prefer(db_session, "bambu_studio")
+
+        assert "SBS" not in _values((await async_client.get("/api/v1/cloud/fields/filament")).json())
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_an_unknown_slicer_leaves_the_list_as_the_field_file_has_it(
+        self, async_client: AsyncClient, db_session
+    ):
+        await _prefer(db_session, "someslicer")
+
+        values = _values((await async_client.get("/api/v1/cloud/fields/filament")).json())
+
+        assert values == _values(_load_fields("filament"))
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_only_the_material_type_dropdown_changes(self, async_client: AsyncClient, db_session):
+        await _prefer(db_session, "orcaslicer")
+
+        served = (await async_client.get("/api/v1/cloud/fields/filament")).json()
+
+        static = _load_fields("filament")
+        assert [f["key"] for f in served["fields"]] == [f["key"] for f in static["fields"]]
+        others = [
+            (f, s) for f, s in zip(served["fields"], static["fields"], strict=True) if f["key"] != "filament_type"
+        ]
+        assert all(f == s for f, s in others)
+        served_type = _type_field(served)
+        static_type = _type_field(static)
+        assert {k: v for k, v in served_type.items() if k != "options"} == {
+            k: v for k, v in static_type.items() if k != "options"
+        }
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_other_preset_types_are_not_touched(self, async_client: AsyncClient, db_session):
+        await _prefer(db_session, "orcaslicer")
+
+        for preset_type in ("process", "printer"):
+            served = (await async_client.get(f"/api/v1/cloud/fields/{preset_type}")).json()
+            assert served == _load_fields(preset_type)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_the_all_fields_route_follows_the_slicer_too(self, async_client: AsyncClient, db_session):
+        await _prefer(db_session, "orcaslicer")
+
+        served = (await async_client.get("/api/v1/cloud/fields")).json()
+
+        assert "SBS" in _values(served["filament"])
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_serving_one_slicer_does_not_change_the_next(self, async_client: AsyncClient, db_session):
+        """The field file is cached; the list swap must work on a copy."""
+        await _prefer(db_session, "orcaslicer")
+        await async_client.get("/api/v1/cloud/fields/filament")
+
+        await _prefer(db_session, "someslicer")
+        values = _values((await async_client.get("/api/v1/cloud/fields/filament")).json())
+
+        assert "SBS" not in values
+
+
+def test_the_lists_are_well_formed():
+    data = json.loads((DATA / "slicer_filament_types.json").read_text(encoding="utf-8"))
+    for slicer in ("bambu_studio", "orcaslicer"):
+        values = data[slicer]["values"]
+        assert len(values) == len(set(values)), f"{slicer} lists a type twice"
+        assert "PLA" in values and "PETG" in values and "ABS" in values and "TPU" in values
+        assert data[slicer]["source"].startswith("https://")

+ 3 - 0
backend/tests/integration/test_external_print_confirmation_1898.py

@@ -141,6 +141,9 @@ async def _drive_print_start(
         pm.get_status = MagicMock(return_value=state)
         pm.get_printer = MagicMock(return_value=MagicMock(serial_number="TEST1898"))
         pm.get_client = MagicMock(return_value=None)  # else its mock dispatch id is stored
+        pm.get_current_print_user = MagicMock(return_value=None)  # a print nobody started in Bambuddy
+        mocks["ws_manager"] = ws
+        mocks["mqtt_relay"] = relay
 
         from backend.app.main import on_print_start
 

+ 245 - 0
backend/tests/integration/test_gcode_hash_paths_1634.py

@@ -0,0 +1,245 @@
+"""The G-code fingerprint every archive keeps (#1634).
+
+A print sent from the slicer joins the archive with the same G-code, so each
+way an archive gets a file reads it: a new archive, a fallback given its 3MF, a
+re-slice, a merge survivor that takes over a file. A restore has no file and
+takes the backup's; archives made before are read once after startup. All of
+them read it off the event loop: unzipping a large 3MF takes seconds.
+"""
+
+from __future__ import annotations
+
+import json
+import zipfile
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+from sqlalchemy import delete, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from backend.app.core.config import settings as app_settings
+from backend.app.models.archive import PrintArchive
+from backend.app.services import archive_gcode_hash
+from backend.app.services.archive_gcode_hash import NO_GCODE, fill_gcode_hashes, gcode_fingerprint
+
+pytestmark = pytest.mark.integration
+
+DIR = "archives/gcode"
+GCODE = b"; HEADER_BLOCK_START\nG28\nG1 X10 Y10 F3000\n"
+
+
+def _three_mf(path, plates: dict[int, bytes] | None = None, *, model: str = "<model/>", when=(2026, 1, 1, 0, 0, 0)):
+    """A sliced 3MF; ``when`` and ``model`` stand for what a new export changes."""
+    path.parent.mkdir(parents=True, exist_ok=True)
+    with zipfile.ZipFile(path, "w") as zf:
+        zf.writestr(zipfile.ZipInfo("3D/3dmodel.model", date_time=when), model)
+        for number, gcode in (plates if plates is not None else {1: GCODE}).items():
+            zf.writestr(zipfile.ZipInfo(f"Metadata/plate_{number}.gcode", date_time=when), gcode)
+    return path
+
+
+@pytest.fixture
+def files(tmp_path, monkeypatch):
+    monkeypatch.setattr(app_settings, "base_dir", tmp_path)
+    monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
+    return tmp_path
+
+
+@pytest.fixture
+def off_the_loop(monkeypatch):
+    """Records what is read through asyncio.to_thread."""
+    import asyncio
+
+    calls: list = []
+    real = asyncio.to_thread
+
+    async def to_thread(fn, *args, **kwargs):
+        calls.append(fn)
+        return await real(fn, *args, **kwargs)
+
+    monkeypatch.setattr(asyncio, "to_thread", to_thread)
+    return calls
+
+
+class TestFingerprint:
+    def test_a_new_export_of_the_same_slice_has_the_same_fingerprint(self, tmp_path):
+        first = _three_mf(tmp_path / "a.3mf")
+        again = _three_mf(tmp_path / "b.3mf", model="<model changed='1'/>", when=(2026, 2, 2, 12, 0, 0))
+
+        assert first.read_bytes() != again.read_bytes()
+        assert gcode_fingerprint(first) == gcode_fingerprint(again)
+
+    def test_another_slice_has_another(self, tmp_path):
+        first = _three_mf(tmp_path / "a.3mf")
+        resliced = _three_mf(tmp_path / "b.3mf", {1: GCODE + b"G1 Z0.2\n"})
+
+        assert gcode_fingerprint(first) != gcode_fingerprint(resliced)
+
+    def test_the_same_gcode_on_another_plate_is_another_file(self, tmp_path):
+        assert gcode_fingerprint(_three_mf(tmp_path / "a.3mf", {1: GCODE})) != gcode_fingerprint(
+            _three_mf(tmp_path / "b.3mf", {2: GCODE})
+        )
+
+    def test_every_plate_counts_in_plate_order(self, tmp_path):
+        both = _three_mf(tmp_path / "a.3mf", {1: GCODE, 2: b"G28\n"})
+        swapped = _three_mf(tmp_path / "b.3mf", {2: b"G28\n", 1: GCODE})
+        one = _three_mf(tmp_path / "c.3mf", {1: GCODE})
+
+        assert gcode_fingerprint(both) == gcode_fingerprint(swapped)
+        assert gcode_fingerprint(both) != gcode_fingerprint(one)
+
+    def test_a_plain_gcode_file_is_its_bytes(self, tmp_path):
+        import hashlib
+
+        path = tmp_path / "cube.gcode"
+        path.write_bytes(GCODE)
+
+        assert gcode_fingerprint(path) == hashlib.sha256(GCODE).hexdigest()
+
+    @pytest.mark.parametrize(
+        "write",
+        [
+            lambda p: _three_mf(p, {}),  # a project, not sliced
+            lambda p: p.write_bytes(b"PK\x03\x04 not really a zip"),
+            lambda p: p.write_bytes(b"solid cube\nendsolid\n"),
+        ],
+    )
+    def test_a_file_without_readable_gcode_has_none(self, tmp_path, write):
+        path = tmp_path / "f.3mf"
+        write(path)
+
+        assert gcode_fingerprint(path) is None
+
+
+class TestNewArchives:
+    async def test_an_archived_print_keeps_its_fingerprint(self, files, db_session, printer_factory, off_the_loop):
+        from backend.app.services.archive import ArchiveService
+
+        printer = await printer_factory()
+        source = _three_mf(files / "upload" / "a.gcode.3mf")
+
+        archive = await ArchiveService(db_session).archive_print(printer.id, source)
+
+        assert archive.gcode_hash == gcode_fingerprint(source)
+        assert gcode_fingerprint in off_the_loop
+
+    async def test_a_file_without_gcode_is_marked_read(self, files, db_session, printer_factory):
+        from backend.app.services.archive import ArchiveService
+
+        printer = await printer_factory()
+        source = _three_mf(files / "upload" / "project.3mf", {})
+
+        archive = await ArchiveService(db_session).archive_print(printer.id, source)
+
+        assert archive.gcode_hash == NO_GCODE
+
+    async def test_a_print_given_its_3mf_later_reads_its_fingerprint(self, files, db_session, printer_factory):
+        from backend.app.services.archive import ArchiveService
+
+        printer = await printer_factory()
+        fallback = PrintArchive(printer_id=printer.id, filename="a.3mf", file_path="", file_size=0, status="printing")
+        db_session.add(fallback)
+        await db_session.commit()
+        source = _three_mf(files / "upload" / "a.gcode.3mf")
+
+        archive = await ArchiveService(db_session).archive_print(printer.id, source, update_archive_id=fallback.id)
+
+        assert (archive.id, archive.gcode_hash) == (fallback.id, gcode_fingerprint(source))
+
+    async def test_a_reslice_reads_its_fingerprint(
+        self, files, db_session, archive_factory, printer_factory, off_the_loop
+    ):
+        from backend.tests.integration.test_slice_archive_output_path_2832 import _slice, _stub_slicer
+
+        printer = await printer_factory()
+        source = await archive_factory(printer.id, print_name="Bracket", filename="Bracket.3mf")
+        sliced = _three_mf(files / "sliced.3mf").read_bytes()
+
+        # _slice stubs the slicer with a file that is not a 3MF: this one is.
+        with patch(
+            "backend.tests.integration.test_slice_archive_output_path_2832._stub_slicer", lambda: _stub_slicer(sliced)
+        ):
+            response = await _slice(db_session, source, "Bracket.3mf")
+
+        archive = await db_session.get(PrintArchive, response.archive_id)
+        assert archive.gcode_hash == gcode_fingerprint(files / "sliced.3mf")
+        assert archive_gcode_hash.read_gcode_hash in off_the_loop
+
+
+class TestBackupAndRestore:
+    async def test_a_restored_archive_keeps_its_fingerprint(self, db_session, printer_factory):
+        """A restore brings back no file to read it from."""
+        from backend.app.schemas.github_backup import RestoreCategory
+        from backend.app.services.github_backup import github_backup_service
+        from backend.app.services.github_restore import GitHubRestoreService
+
+        printer = await printer_factory()
+        db_session.add(
+            PrintArchive(
+                printer_id=printer.id,
+                filename="a.3mf",
+                file_path="archives/t/a.3mf",
+                file_size=1,
+                content_hash="hash-a",
+                gcode_hash="a" * 64,
+                print_name="A",
+                status="completed",
+            )
+        )
+        await db_session.commit()
+        backup: dict = {}
+        await github_backup_service._collect_archives(db_session, backup)
+        backup = json.loads(json.dumps(backup))
+        await db_session.execute(delete(PrintArchive))
+        await db_session.commit()
+
+        await GitHubRestoreService()._apply(db_session, backup, [RestoreCategory.ARCHIVES], False)
+
+        restored = (await db_session.scalars(select(PrintArchive))).one()
+        assert (restored.file_path, restored.gcode_hash) == ("", "a" * 64)
+
+    @pytest.mark.parametrize("value", [None, "", "not-a-hash", 42])
+    def test_a_backup_without_one_restores_none(self, value):
+        from backend.app.services.github_restore import _gcode_hash_of
+
+        assert _gcode_hash_of({"gcode_hash": value} if value is not None else {}) is None
+
+
+class TestFill:
+    async def test_archives_made_before_get_theirs_once(self, files, db_session, test_engine, off_the_loop):
+        _three_mf(files / DIR / "a.gcode.3mf")
+        older = PrintArchive(filename="a.gcode.3mf", file_path=f"{DIR}/a.gcode.3mf", file_size=1)
+        gone = PrintArchive(filename="gone.3mf", file_path=f"{DIR}/gone.3mf", file_size=1)
+        read = PrintArchive(filename="r.3mf", file_path=f"{DIR}/a.gcode.3mf", file_size=1, gcode_hash=NO_GCODE)
+        db_session.add_all([older, gone, read])
+        await db_session.commit()
+
+        sessions = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
+        assert await fill_gcode_hashes(sessions, batch=1) == 2
+        assert await fill_gcode_hashes(sessions) == 0
+
+        for row in (older, gone, read):
+            await db_session.refresh(row)
+        fingerprint = gcode_fingerprint(files / DIR / "a.gcode.3mf")
+        assert (older.gcode_hash, gone.gcode_hash, read.gcode_hash) == (fingerprint, NO_GCODE, NO_GCODE)
+        assert archive_gcode_hash.read_gcode_hash in off_the_loop
+
+    async def test_an_archive_read_meanwhile_keeps_what_was_read(self, files, db_session, test_engine, monkeypatch):
+        racing = PrintArchive(filename="a.gcode.3mf", file_path="", file_size=0)
+        db_session.add(racing)
+        await db_session.commit()
+        sessions = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
+
+        async def meanwhile(fn, row):
+            # Its 3MF recovered and read while the fill reads it.
+            async with sessions() as other:
+                (await other.get(PrintArchive, racing.id)).gcode_hash = "f" * 64
+                await other.commit()
+            return fn(row)
+
+        monkeypatch.setattr(archive_gcode_hash, "asyncio", SimpleNamespace(to_thread=meanwhile))
+
+        assert await fill_gcode_hashes(sessions) == 0
+        await db_session.refresh(racing)
+        assert racing.gcode_hash == "f" * 64

+ 137 - 0
backend/tests/integration/test_inventory_assign.py

@@ -2568,3 +2568,140 @@ class TestSpoolmanSlotAssignmentDuringRunout:
 
         db_session.expunge_all()
         assert await db_session.get(SpoolmanSlotAssignment, row_id) is None
+
+
+class TestAutoUnlinkZeroColourIsBlank:
+    """#3526: a blank tray can arrive as colour ``00000000`` rather than "".
+
+    Four printers lost MQTT for a minute or two; on reconnect an A1 mini's AMS
+    lite and an A2L's external spool first reported ``00000000`` with no type,
+    mid-print, and four assignments were deleted as fingerprint mismatches. The
+    runout guard, the presence-bit guard and the grace hold all only knew an
+    empty colour as blank.
+    """
+
+    BLANK = {"tray_type": "", "tray_color": "00000000"}
+
+    @staticmethod
+    async def _assignment(db_session, printer, spool, ams_id=0, tray_id=1):
+        from backend.app.models.spool_assignment import SpoolAssignment
+
+        assignment = SpoolAssignment(
+            spool_id=spool.id,
+            printer_id=printer.id,
+            ams_id=ams_id,
+            tray_id=tray_id,
+            fingerprint_color="91202BFF",
+            fingerprint_type="PLA",
+        )
+        db_session.add(assignment)
+        await db_session.commit()
+        return assignment.id
+
+    @staticmethod
+    async def _exists(db_session, assignment_id):
+        from backend.app.models.spool_assignment import SpoolAssignment
+
+        db_session.expunge_all()
+        return await db_session.get(SpoolAssignment, assignment_id) is not None
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_mid_print_keeps_the_assignment(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        """Held past the grace period too: during a print it is a runout, never
+        a removal, however long it lasts."""
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, **self.BLANK, "state": 3}]}]
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="PAUSE"))
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="PAUSE"))
+
+        assert await self._exists(db_session, assignment_id), "a blank report mid-print is a runout, not a swap"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_on_the_external_spool_mid_print_keeps_the_assignment(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A2L")
+        spool = await spool_factory(material="PLA+", rgba="E1E4E5FF")
+        assignment_id = await self._assignment(db_session, printer, spool, ams_id=255, tray_id=0)
+
+        status = _make_mock_status(ams_data=[], vt_tray=[{"id": "254", **self.BLANK}])
+        status.state = "RUNNING"
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, [], status)
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, [], status)
+
+        assert await self._exists(db_session, assignment_id)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_from_an_occupied_slot_keeps_the_assignment(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, "exists": True, **self.BLANK, "state": 3}]}]
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+
+        assert await self._exists(db_session, assignment_id)
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_zero_colour_blank_while_idle_is_held_for_the_grace_period(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        from backend.app.services import slot_unlink_grace
+
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, **self.BLANK, "state": 3}]}]
+        clock = [1000.0]
+        with patch.object(slot_unlink_grace, "_now", lambda: clock[0]):
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+            assert await self._exists(db_session, assignment_id), "one blank push is not a removal"
+
+            clock[0] += slot_unlink_grace.GRACE_SECONDS
+            await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="IDLE"))
+
+        assert not await self._exists(db_session, assignment_id), "a slot that stays blank is still unlinked"
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_a_clear_spool_reporting_zero_colour_is_not_blank(
+        self, async_client: AsyncClient, printer_factory, spool_factory, db_session: AsyncSession
+    ):
+        """A clear filament reports ``00000000`` too, but with its type: a clear
+        PETG in place of the assigned PLA is a swap, even mid-print."""
+        printer = await printer_factory(name="A1 mini")
+        spool = await spool_factory(material="PLA+", rgba="91202BFF")
+        assignment_id = await self._assignment(db_session, printer, spool)
+
+        ams_data = [{"id": 0, "tray": [{"id": 1, "tray_type": "PETG", "tray_color": "00000000", "state": 11}]}]
+        await TestAutoUnlinkOccupiedSlot._run(printer.id, ams_data, _make_printing_status(ams_data, state="RUNNING"))
+
+        assert not await self._exists(db_session, assignment_id)

+ 138 - 1
backend/tests/integration/test_inventory_csv.py

@@ -35,7 +35,7 @@ class TestInventoryCsvExport:
         body = response.text
         lines = body.strip().splitlines()
         # Header row uses the fixed schema.
-        assert lines[0].split(",")[0] == "material"
+        assert lines[0].split(",")[:2] == ["id", "material"]
         assert "rgba" in lines[0]
         # Data row present, rgba written without leading '#'.
         assert "Polymaker" in body
@@ -141,6 +141,19 @@ class TestInventoryCsvImportReal:
         spool = result.scalars().one()
         assert spool.color_name == "Snow"
 
+    async def test_semicolon_file_with_decimal_commas(self, async_client: AsyncClient, db_session: AsyncSession):
+        # What Excel saves as CSV in a comma-decimal locale (de, fr, nl, ...).
+        csv_text = "material;brand;color_name;label_weight;cost_per_kg\r\nPLA;Polymaker;Jade White;1000;24,99\r\n"
+
+        response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
+
+        assert response.status_code == 200, response.text
+        assert response.json()["created"] == 1
+        result = await db_session.execute(select(Spool))
+        spool = result.scalars().one()
+        assert (spool.brand, spool.color_name, spool.label_weight) == ("Polymaker", "Jade White", 1000)
+        assert spool.cost_per_kg == 24.99
+
 
 @pytest.mark.asyncio
 @pytest.mark.integration
@@ -535,3 +548,127 @@ class TestInventoryCsvDuplicateWarning:
         assert real.json()["created"] == 2
         all_spools = (await db_session.execute(select(Spool))).scalars().all()
         assert len(all_spools) == 3  # 1 pre-existing + 2 imported
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+class TestInventoryCsvKeepsIds:
+    """A moved inventory keeps its spool ids: printed labels' QR codes carry them (#3520)."""
+
+    async def _base(self, db_session: AsyncSession) -> int:
+        from backend.app.services.spool_csv import highest_spool_id_given_out
+
+        return await highest_spool_id_given_out(db_session)
+
+    async def _ids_by_color(self, db_session: AsyncSession) -> dict[str, int]:
+        db_session.expire_all()
+        rows = (await db_session.execute(select(Spool))).scalars().all()
+        return {s.color_name: s.id for s in rows}
+
+    async def test_export_writes_the_id(self, async_client: AsyncClient, db_session: AsyncSession):
+        spool = Spool(material="PLA", brand="B", color_name="Red", rgba="ff0000ff")
+        db_session.add(spool)
+        await db_session.commit()
+
+        response = await async_client.get("/api/v1/inventory/spools/export")
+
+        header, row = response.text.strip().splitlines()[:2]
+        assert header.split(",")[0] == "id"
+        assert row.split(",")[0] == str(spool.id)
+
+    async def test_import_keeps_ids_and_their_gaps(self, async_client: AsyncClient, db_session: AsyncSession):
+        base = await self._base(db_session)
+        # Out of order, with gaps, and a row without an id ahead of them: it
+        # must not take an id a later row still needs.
+        csv_text = f"id,material,color_name\n,PLA,New\n{base + 5},PLA,Five\n{base + 1},PETG,One\n{base + 3},PLA,Three\n"
+
+        response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
+
+        assert response.status_code == 200, response.text
+        assert response.json()["created"] == 4
+        ids = await self._ids_by_color(db_session)
+        assert ids["Five"] == base + 5
+        assert ids["One"] == base + 1
+        assert ids["Three"] == base + 3
+        assert ids["New"] == base + 6
+
+    async def test_the_next_spool_continues_after_the_kept_ids(
+        self, async_client: AsyncClient, db_session: AsyncSession
+    ):
+        """Only kept ids in the file: the next spool still gets a fresh id (PostgreSQL's sequence)."""
+        base = await self._base(db_session)
+        csv_text = f"id,material,color_name\n{base + 4},PLA,Four\n"
+        await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
+
+        response = await async_client.post("/api/v1/inventory/spools", json={"material": "PLA", "color_name": "Later"})
+
+        assert response.status_code == 200, response.text
+        assert response.json()["id"] == base + 5
+
+    async def test_dry_run_shows_the_id_each_spool_keeps(self, async_client: AsyncClient, db_session: AsyncSession):
+        base = await self._base(db_session)
+        csv_text = f"id,material\n{base + 2},PLA\n,PETG\n"
+
+        response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
+
+        rows = response.json()["rows"]
+        assert [r["keeps_id"] for r in rows] == [base + 2, None]
+        assert response.json()["warnings"] == []
+
+    async def test_an_id_in_use_gets_a_new_one(self, async_client: AsyncClient, db_session: AsyncSession):
+        existing = Spool(material="PLA", color_name="Existing")
+        db_session.add(existing)
+        await db_session.commit()
+        csv_text = f"id,material,color_name\n{existing.id},PETG,Imported\n"
+
+        preview = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
+        await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
+
+        assert preview.json()["rows"][0]["keeps_id"] is None
+        assert any("1 spool(s) get a new id" in w for w in preview.json()["warnings"])
+        ids = await self._ids_by_color(db_session)
+        assert ids["Existing"] == existing.id
+        assert ids["Imported"] > existing.id
+
+    async def test_a_deleted_spools_id_is_not_reused(self, async_client: AsyncClient, db_session: AsyncSession):
+        """Old print logs and usage records may still name it."""
+        gone = Spool(material="PLA", color_name="Gone")
+        db_session.add(gone)
+        await db_session.commit()
+        gone_id = gone.id
+        await db_session.delete(gone)
+        await db_session.commit()
+        csv_text = f"id,material,color_name\n{gone_id},PLA,Imported\n"
+
+        await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
+
+        assert (await self._ids_by_color(db_session))["Imported"] > gone_id
+
+    async def test_an_id_named_twice_is_kept_once(self, async_client: AsyncClient, db_session: AsyncSession):
+        base = await self._base(db_session)
+        csv_text = f"id,material,color_name\n{base + 2},PLA,First\n{base + 2},PLA,Second\n"
+
+        response = await async_client.post("/api/v1/inventory/spools/import", files=_csv_upload(csv_text))
+
+        assert response.json()["created"] == 2
+        ids = await self._ids_by_color(db_session)
+        assert ids["First"] == base + 2
+        assert ids["Second"] == base + 3
+
+    @pytest.mark.parametrize("bad", ["abc", "0", "-3", "1.5"])
+    async def test_a_bad_id_is_a_row_error(self, async_client: AsyncClient, bad: str):
+        csv_text = f"id,material\n{bad},PLA\n"
+
+        response = await async_client.post("/api/v1/inventory/spools/import?dry_run=true", files=_csv_upload(csv_text))
+
+        row = response.json()["rows"][0]
+        assert row["status"] == "error"
+        assert "id must be a positive whole number" in row["reason"]
+
+    async def test_a_csv_without_an_id_column_still_imports(self, async_client: AsyncClient, db_session: AsyncSession):
+        response = await async_client.post(
+            "/api/v1/inventory/spools/import", files=_csv_upload("material,color_name\nPLA,Plain\n")
+        )
+
+        assert response.json()["created"] == 1
+        assert response.json()["errors"] == 0

+ 41 - 8
backend/tests/integration/test_library_slice_api.py

@@ -587,14 +587,30 @@ class TestSliceLibraryFile:
 
     @pytest.mark.asyncio
     @pytest.mark.integration
-    async def test_3mf_falls_back_to_embedded_settings_on_cli_failure(
-        self, async_client: AsyncClient, db_session, slice_test_setup
+    @pytest.mark.parametrize(
+        ("source_model", "target_model", "falls_back"),
+        [
+            # Same printer: the file's own settings are a valid slice for it.
+            ("Bambu Lab X1 Carbon", "Bambu Lab X1 Carbon", True),
+            # #3535: another printer, or one side unknown -- the fallback would
+            # hand back G-code for the file's printer as a completed slice.
+            ("Bambu Lab P1S", "Bambu Lab X1 Carbon", False),
+            (None, "Bambu Lab X1 Carbon", False),
+            ("Bambu Lab X1 Carbon", None, False),
+        ],
+    )
+    async def test_3mf_falls_back_to_embedded_settings_on_cli_failure_only_for_its_own_printer(
+        self, async_client: AsyncClient, db_session, slice_test_setup, source_model, target_model, falls_back
     ):
         # When the slicer CLI fails on the --load-settings path (segfault
         # on complex H2D models), Bambuddy retries with no profile triplet
-        # so the CLI uses the file's embedded settings.
+        # so the CLI uses the file's embedded settings -- which describe the
+        # printer the file was sliced for, so only when that is the target.
+        settings = {"prime_tower_brim_width": "-1"}
+        if source_model:
+            settings["printer_model"] = source_model
         src_3mf_path = slice_test_setup["tmp_path"] / "library" / "files" / "complex.3mf"
-        src_3mf_path.write_bytes(_make_3mf_with_settings({"prime_tower_brim_width": "-1"}))
+        src_3mf_path.write_bytes(_make_3mf_with_settings(settings))
         threemf = LibraryFile(
             filename="complex.3mf",
             file_path=str(src_3mf_path.relative_to(slice_test_setup["tmp_path"])),
@@ -602,8 +618,20 @@ class TestSliceLibraryFile:
             file_size=src_3mf_path.stat().st_size,
         )
         db_session.add(threemf)
+        printer_id = slice_test_setup["printer_id"]
+        if target_model:
+            target = LocalPreset(
+                name="# Target printer 0.4 nozzle",
+                preset_type="printer",
+                source="orcaslicer",
+                setting=json.dumps({"name": "Target printer 0.4 nozzle", "printer_model": target_model}),
+            )
+            db_session.add(target)
         await db_session.commit()
         await db_session.refresh(threemf)
+        if target_model:
+            await db_session.refresh(target)
+            printer_id = target.id
 
         call_count = {"n": 0}
 
@@ -632,7 +660,7 @@ class TestSliceLibraryFile:
         response = await async_client.post(
             f"/api/v1/library/files/{threemf.id}/slice",
             json={
-                "printer_preset_id": slice_test_setup["printer_id"],
+                "printer_preset_id": printer_id,
                 "process_preset_id": slice_test_setup["process_id"],
                 "filament_preset_id": slice_test_setup["filament_id"],
             },
@@ -640,9 +668,14 @@ class TestSliceLibraryFile:
         assert response.status_code == 202
 
         final = await _wait_for_job(async_client, response.json()["job_id"])
-        assert final["status"] == "completed", final
-        assert final["result"]["used_embedded_settings"] is True
-        assert call_count["n"] == 2  # primary + fallback retry
+        if falls_back:
+            assert final["status"] == "completed", final
+            assert final["result"]["used_embedded_settings"] is True
+            assert call_count["n"] == 2  # primary + fallback retry
+        else:
+            assert final["status"] == "failed", final
+            assert final["error_status"] == 502
+            assert call_count["n"] == 1  # no retry with another printer's settings
 
     @pytest.mark.asyncio
     @pytest.mark.integration

+ 425 - 0
backend/tests/integration/test_maintenance_log.py

@@ -0,0 +1,425 @@
+"""The maintenance log: every reset with its comment, who did it, on which printer and when.
+
+Entries outlive the printer, the custom task and the user (their names are
+kept as they were), so the log stays an audit trail. It is read per printer
+and exported as CSV per printer or for the whole fleet; a printer-scoped
+caller sees only their printers, and not the entries of deleted ones.
+Entries can be deleted, by age or one at a time, with the history row of the
+same reset, so a deleted comment is gone from the database.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+from datetime import datetime, timedelta, timezone
+
+import pytest
+from httpx import AsyncClient
+
+from backend.app.models.maintenance import MaintenanceHistory, MaintenanceLogEntry
+from backend.tests.integration.test_archives_last_per_printer import _admin_token, _auth, _user
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
+
+BASE = "/api/v1/maintenance"
+
+
+async def _first_item(async_client: AsyncClient, printer_id: int) -> dict:
+    overview = (await async_client.get(f"{BASE}/printers/{printer_id}")).json()
+    return overview["maintenance_items"][0]
+
+
+async def _perform(async_client: AsyncClient, item_id: int, notes: str | None = None, headers=None):
+    body = {} if notes is None else {"notes": notes}
+    return await async_client.post(f"{BASE}/items/{item_id}/perform", json=body, headers=headers)
+
+
+async def _log(async_client: AsyncClient, printer_id: int, headers=None, **params) -> dict:
+    response = await async_client.get(f"{BASE}/printers/{printer_id}/log", params=params, headers=headers)
+    assert response.status_code == 200, response.text
+    return response.json()
+
+
+def _csv_rows(response) -> list[list[str]]:
+    assert response.status_code == 200, response.text
+    assert response.headers["content-type"].startswith("text/csv")
+    assert "attachment" in response.headers["content-disposition"]
+    text = response.content.decode("utf-8")
+    assert text.startswith(""), "Excel needs the BOM to read UTF-8"
+    return list(csv.reader(io.StringIO(text[1:])))
+
+
+async def _entry(db_session, entry_id: int) -> MaintenanceLogEntry:
+    db_session.expire_all()
+    entry = await db_session.get(MaintenanceLogEntry, entry_id)
+    assert entry is not None
+    return entry
+
+
+async def _age(db_session, entry_id: int, days: int) -> int:
+    """Move an entry ``days`` into the past; returns its history row's id."""
+    entry = await _entry(db_session, entry_id)
+    entry.performed_at = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=days)
+    history_id = entry.history_id
+    await db_session.commit()
+    assert history_id is not None
+    return history_id
+
+
+async def _history_exists(db_session, history_id: int) -> bool:
+    db_session.expire_all()
+    return await db_session.get(MaintenanceHistory, history_id) is not None
+
+
+async def _logged(async_client, printer_factory, name: str, *notes: str) -> tuple[int, list[int]]:
+    """A printer with one reset per note; returns its id and the entry ids, oldest first."""
+    printer_id = (await printer_factory(name=name)).id
+    item = await _first_item(async_client, printer_id)
+    for note in notes:
+        await _perform(async_client, item["id"], note)
+    entries = (await _log(async_client, printer_id))["items"]
+    return printer_id, [e["id"] for e in reversed(entries)]
+
+
+class TestLogging:
+    async def test_a_reset_logs_the_task_the_printer_and_the_comment(self, async_client, printer_factory):
+        printer = await printer_factory(name="Log Printer")
+        item = await _first_item(async_client, printer.id)
+
+        response = await _perform(async_client, item["id"], "  Rails cleaned, new grease  ")
+
+        assert response.status_code == 200, response.text
+        log = await _log(async_client, printer.id)
+        assert log["total"] == 1
+        entry = log["items"][0]
+        assert entry["printer_id"] == printer.id
+        assert entry["printer_name"] == "Log Printer"
+        assert entry["maintenance_type_id"] == item["maintenance_type_id"]
+        assert entry["maintenance_type_name"] == item["maintenance_type_name"]
+        assert entry["notes"] == "Rails cleaned, new grease"
+        assert entry["performed_at"] is not None
+        # Authentication is off: nobody to name.
+        assert entry["performed_by_id"] is None
+        assert entry["performed_by_username"] is None
+
+    async def test_the_comment_is_optional_and_blank_is_none(self, async_client, printer_factory):
+        printer = await printer_factory(name="No Comment Printer")
+        item = await _first_item(async_client, printer.id)
+
+        assert (await _perform(async_client, item["id"])).status_code == 200
+        assert (await _perform(async_client, item["id"], "   ")).status_code == 200
+
+        notes = [e["notes"] for e in (await _log(async_client, printer.id))["items"]]
+        assert notes == [None, None]
+
+    async def test_a_comment_over_the_limit_is_refused(self, async_client, printer_factory):
+        printer = await printer_factory(name="Long Comment Printer")
+        item = await _first_item(async_client, printer.id)
+
+        response = await _perform(async_client, item["id"], "x" * 10001)
+
+        assert response.status_code == 422
+        assert (await _log(async_client, printer.id))["total"] == 0
+
+    async def test_a_long_report_fits(self, async_client, printer_factory):
+        """Automations post whole reports; the endpoint took any length before."""
+        printer = await printer_factory(name="Report Printer")
+        item = await _first_item(async_client, printer.id)
+
+        response = await _perform(async_client, item["id"], "x" * 10000)
+
+        assert response.status_code == 200, response.text
+        assert len((await _log(async_client, printer.id))["items"][0]["notes"]) == 10000
+
+    async def test_surrounding_whitespace_does_not_count_against_the_limit(self, async_client, printer_factory):
+        printer = await printer_factory(name="Padded Printer")
+        item = await _first_item(async_client, printer.id)
+
+        response = await _perform(async_client, item["id"], "x" * 9995 + " " * 20 + "\n")
+
+        assert response.status_code == 200, response.text
+        assert (await _log(async_client, printer.id))["items"][0]["notes"] == "x" * 9995
+
+    async def test_the_log_is_newest_first_and_paged(self, async_client, printer_factory):
+        printer = await printer_factory(name="Paged Printer")
+        item = await _first_item(async_client, printer.id)
+        for n in range(3):
+            await _perform(async_client, item["id"], f"reset {n}")
+
+        first = await _log(async_client, printer.id, limit=2)
+        rest = await _log(async_client, printer.id, limit=2, offset=2)
+
+        assert first["total"] == rest["total"] == 3
+        assert [e["notes"] for e in first["items"]] == ["reset 2", "reset 1"]
+        assert [e["notes"] for e in rest["items"]] == ["reset 0"]
+
+    async def test_another_printer_s_resets_are_not_in_its_log(self, async_client, printer_factory):
+        mine, other = await printer_factory(name="Mine"), await printer_factory(name="Other")
+        await _perform(async_client, (await _first_item(async_client, other.id))["id"], "other's")
+
+        assert (await _log(async_client, mine.id))["total"] == 0
+
+    async def test_the_log_of_an_unknown_printer_is_not_found(self, async_client):
+        response = await async_client.get(f"{BASE}/printers/999999/log")
+
+        assert response.status_code == 404
+
+
+class TestOutlivingDeletes:
+    async def test_entries_outlive_their_printer(self, async_client, printer_factory, db_session):
+        printer = await printer_factory(name="Doomed Printer")
+        await _perform(async_client, (await _first_item(async_client, printer.id))["id"], "before the end")
+        entry_id = (await _log(async_client, printer.id))["items"][0]["id"]
+
+        deleted = await async_client.delete(f"/api/v1/printers/{printer.id}")
+
+        assert deleted.status_code == 200, deleted.text
+        entry = await _entry(db_session, entry_id)
+        assert entry.printer_id is None
+        assert entry.printer_name == "Doomed Printer"
+        assert entry.notes == "before the end"
+        rows = _csv_rows(await async_client.get(f"{BASE}/log/export"))
+        assert ["Doomed Printer", "before the end"] in [[r[1], r[5]] for r in rows[1:]]
+
+    async def test_entries_outlive_a_deleted_custom_task(self, async_client, printer_factory, db_session):
+        printer_id = (await printer_factory(name="Custom Task Printer")).id
+        task = (
+            await async_client.post(
+                f"{BASE}/types",
+                json={"name": "Replace Hotend", "default_interval_hours": 500, "interval_type": "hours"},
+            )
+        ).json()
+        item = (await async_client.post(f"{BASE}/printers/{printer_id}/assign/{task['id']}")).json()
+        await _perform(async_client, item["id"], "0.4 mm hardened")
+        entry_id = (await _log(async_client, printer_id))["items"][0]["id"]
+
+        assert (await async_client.delete(f"{BASE}/types/{task['id']}")).status_code == 200
+
+        entry = await _entry(db_session, entry_id)
+        assert entry.maintenance_type_id is None
+        assert entry.maintenance_type_name == "Replace Hotend"
+        assert (await _log(async_client, printer_id))["total"] == 1
+
+
+class TestExport:
+    async def test_a_printer_s_log_exports_as_csv(self, async_client, printer_factory):
+        printer = await printer_factory(name="Drucker Übung")
+        item = await _first_item(async_client, printer.id)
+        await _perform(async_client, item["id"], "Düse gewechselt")
+
+        response = await async_client.get(f"{BASE}/printers/{printer.id}/log/export")
+
+        rows = _csv_rows(response)
+        assert rows[0] == ["Performed at (UTC)", "Printer", "Task", "Performed by", "Print hours", "Comment"]
+        assert len(rows) == 2
+        performed_at, name, task, by, hours, comment = rows[1]
+        assert performed_at.endswith("Z")
+        assert (name, task, by, comment) == ("Drucker Übung", item["maintenance_type_name"], "", "Düse gewechselt")
+        assert float(hours) == pytest.approx(0.0)
+        assert "maintenance_log_Drucker" in response.headers["content-disposition"]
+
+    async def test_a_formula_in_a_comment_stays_text(self, async_client, printer_factory):
+        printer = await printer_factory(name="Formula Printer")
+        await _perform(async_client, (await _first_item(async_client, printer.id))["id"], '=HYPERLINK("x")')
+
+        rows = _csv_rows(await async_client.get(f"{BASE}/printers/{printer.id}/log/export"))
+
+        assert rows[1][5] == '\'=HYPERLINK("x")'
+
+    async def test_the_fleet_export_has_every_printer(self, async_client, printer_factory):
+        a, b = await printer_factory(name="Fleet A"), await printer_factory(name="Fleet B")
+        for printer in (a, b):
+            await _perform(async_client, (await _first_item(async_client, printer.id))["id"], printer.name)
+
+        rows = _csv_rows(await async_client.get(f"{BASE}/log/export"))
+
+        assert {r[1] for r in rows[1:]} >= {"Fleet A", "Fleet B"}
+
+
+class TestCleanup:
+    async def test_a_printer_s_old_entries_go_with_their_history(self, async_client, printer_factory, db_session):
+        printer_id, (old, recent, _today) = await _logged(
+            async_client, printer_factory, "Cleanup", "old", "recent", "today"
+        )
+        other_id, (other_old,) = await _logged(async_client, printer_factory, "Cleanup Other", "other old")
+        old_history = await _age(db_session, old, 400)
+        recent_history = await _age(db_session, recent, 10)
+        other_history = await _age(db_session, other_old, 400)
+
+        response = await async_client.delete(f"{BASE}/printers/{printer_id}/log", params={"older_than_days": 30})
+
+        assert response.status_code == 200, response.text
+        assert response.json() == {"deleted": 1}
+        assert [e["notes"] for e in (await _log(async_client, printer_id))["items"]] == ["today", "recent"]
+        assert not await _history_exists(db_session, old_history)
+        assert await _history_exists(db_session, recent_history)
+        # Another printer's entries are not touched.
+        assert (await _log(async_client, other_id))["total"] == 1
+        assert await _history_exists(db_session, other_history)
+
+    async def test_the_age_must_be_given_and_at_least_a_day(self, async_client, printer_factory):
+        printer_id, _ = await _logged(async_client, printer_factory, "Cleanup Age", "kept")
+
+        for params in ({}, {"older_than_days": 0}, {"older_than_days": -5}):
+            assert (await async_client.delete(f"{BASE}/printers/{printer_id}/log", params=params)).status_code == 422
+            assert (await async_client.delete(f"{BASE}/log", params=params)).status_code == 422
+        assert (await _log(async_client, printer_id))["total"] == 1
+
+    async def test_cleaning_up_an_unknown_printer_is_not_found(self, async_client):
+        response = await async_client.delete(f"{BASE}/printers/999999/log", params={"older_than_days": 1})
+
+        assert response.status_code == 404
+
+    async def test_the_fleet_cleanup_covers_every_printer_and_deleted_ones(
+        self, async_client, printer_factory, db_session
+    ):
+        a_id, (a_old, a_new) = await _logged(async_client, printer_factory, "Fleet Clean A", "a old", "a new")
+        b_id, (b_old,) = await _logged(async_client, printer_factory, "Fleet Clean B", "b old")
+        gone_id, (gone_old,) = await _logged(async_client, printer_factory, "Fleet Clean Gone", "gone old")
+        for entry_id in (a_old, b_old, gone_old):
+            await _age(db_session, entry_id, 100)
+        assert (await async_client.delete(f"/api/v1/printers/{gone_id}")).status_code == 200
+
+        response = await async_client.delete(f"{BASE}/log", params={"older_than_days": 30})
+
+        assert response.status_code == 200, response.text
+        assert response.json() == {"deleted": 3}
+        assert [e["id"] for e in (await _log(async_client, a_id))["items"]] == [a_new]
+        assert (await _log(async_client, b_id))["total"] == 0
+        db_session.expire_all()
+        assert await db_session.get(MaintenanceLogEntry, gone_old) is None
+
+    async def test_one_entry_goes_with_its_history_and_the_reset_stays(self, async_client, printer_factory, db_session):
+        printer_id, (kept, mistaken) = await _logged(async_client, printer_factory, "Mistake", "kept", "by mistake")
+        history_id = (await _entry(db_session, mistaken)).history_id
+        before = await _first_item(async_client, printer_id)
+
+        response = await async_client.delete(f"{BASE}/log/{mistaken}")
+
+        assert response.status_code == 200, response.text
+        assert [e["id"] for e in (await _log(async_client, printer_id))["items"]] == [kept]
+        assert history_id is not None
+        assert not await _history_exists(db_session, history_id)
+        # Deleting the entry does not undo the reset.
+        assert (await _first_item(async_client, printer_id))["last_performed_at"] == before["last_performed_at"]
+
+    async def test_an_entry_whose_history_is_gone_leaves_a_later_reset_s_history_alone(
+        self, async_client, printer_factory, db_session
+    ):
+        # The deleted printer's history row had the highest id, so on SQLite the
+        # next reset is given it. Deleting the old entry must not take that
+        # reset's history with it.
+        doomed = (await printer_factory(name="Doomed")).id
+        await _perform(async_client, (await _first_item(async_client, doomed))["id"], "before the end")
+        old_entry = (await _log(async_client, doomed))["items"][0]["id"]
+        old_history = (await _entry(db_session, old_entry)).history_id
+        assert (await async_client.delete(f"/api/v1/printers/{doomed}")).status_code == 200
+        assert (await _entry(db_session, old_entry)).history_id is None
+
+        survivor_id, (new_entry,) = await _logged(async_client, printer_factory, "Survivor", "after")
+        new_history = (await _entry(db_session, new_entry)).history_id
+        assert new_history is not None
+
+        assert (await async_client.delete(f"{BASE}/log/{old_entry}")).status_code == 200
+
+        assert await _history_exists(db_session, new_history)
+        assert (await _log(async_client, survivor_id))["total"] == 1
+        if db_session.bind.dialect.name == "sqlite":
+            # The case this is about: SQLite gave the later reset the freed id.
+            # PostgreSQL never reuses one, so there it can only pass.
+            assert new_history == old_history
+
+    async def test_deleting_an_unknown_entry_is_not_found(self, async_client):
+        assert (await async_client.delete(f"{BASE}/log/999999")).status_code == 404
+
+
+class TestWithAuthentication:
+    PERMISSIONS = ["maintenance:read", "maintenance:update", "printers:read"]
+
+    async def test_the_log_names_who_reset(self, async_client, printer_factory):
+        printer = await printer_factory(name="Auth Printer")
+        admin = await _admin_token(async_client)
+        jwt, user_id = await _user(async_client, admin, "mechanic", self.PERMISSIONS)
+        overview = (await async_client.get(f"{BASE}/printers/{printer.id}", headers=_auth(jwt))).json()
+        item = overview["maintenance_items"][0]
+
+        response = await _perform(async_client, item["id"], "done", headers=_auth(jwt))
+
+        assert response.status_code == 200, response.text
+        entry = (await _log(async_client, printer.id, headers=_auth(jwt)))["items"][0]
+        assert (entry["performed_by_id"], entry["performed_by_username"]) == (user_id, "mechanic")
+        rows = _csv_rows(await async_client.get(f"{BASE}/printers/{printer.id}/log/export", headers=_auth(jwt)))
+        assert rows[1][3] == "mechanic"
+
+    async def test_a_scoped_user_exports_only_their_printers(self, async_client, printer_factory):
+        mine, theirs, gone = (
+            await printer_factory(name="Scoped Mine"),
+            await printer_factory(name="Scoped Theirs"),
+            await printer_factory(name="Scoped Gone"),
+        )
+        for printer in (mine, theirs, gone):
+            await _perform(async_client, (await _first_item(async_client, printer.id))["id"], printer.name)
+        assert (await async_client.delete(f"/api/v1/printers/{gone.id}")).status_code == 200
+        admin = await _admin_token(async_client)
+        jwt, _ = await _user(async_client, admin, "scoped", self.PERMISSIONS, printer_ids=[mine.id])
+
+        rows = _csv_rows(await async_client.get(f"{BASE}/log/export", headers=_auth(jwt)))
+        admin_rows = _csv_rows(await async_client.get(f"{BASE}/log/export", headers=_auth(admin)))
+
+        assert [r[1] for r in rows[1:]] == ["Scoped Mine"]
+        assert {"Scoped Mine", "Scoped Theirs", "Scoped Gone"} <= {r[1] for r in admin_rows[1:]}
+
+    async def test_a_scoped_user_cannot_read_another_printer_s_log(self, async_client, printer_factory):
+        mine, theirs = await printer_factory(name="Scope A"), await printer_factory(name="Scope B")
+        admin = await _admin_token(async_client)
+        jwt, _ = await _user(async_client, admin, "scoped_reader", self.PERMISSIONS, printer_ids=[mine.id])
+
+        log = await async_client.get(f"{BASE}/printers/{theirs.id}/log", headers=_auth(jwt))
+        export = await async_client.get(f"{BASE}/printers/{theirs.id}/log/export", headers=_auth(jwt))
+
+        assert log.status_code in (403, 404)
+        assert export.status_code in (403, 404)
+
+    async def test_cleanup_needs_the_delete_permission(self, async_client, printer_factory):
+        printer_id, (entry_id,) = await _logged(async_client, printer_factory, "No Delete", "kept")
+        admin = await _admin_token(async_client)
+        jwt, _ = await _user(async_client, admin, "no_delete", self.PERMISSIONS)
+
+        for path, params in (
+            (f"{BASE}/printers/{printer_id}/log", {"older_than_days": 1}),
+            (f"{BASE}/log", {"older_than_days": 1}),
+            (f"{BASE}/log/{entry_id}", {}),
+        ):
+            response = await async_client.delete(path, params=params, headers=_auth(jwt))
+            assert response.status_code == 403, (path, response.text)
+        assert (await _log(async_client, printer_id, headers=_auth(admin)))["total"] == 1
+
+    async def test_a_scoped_user_cleans_up_only_their_printers(self, async_client, printer_factory, db_session):
+        mine, (mine_old,) = await _logged(async_client, printer_factory, "Clean Mine", "mine")
+        theirs, (theirs_old,) = await _logged(async_client, printer_factory, "Clean Theirs", "theirs")
+        gone, (gone_old,) = await _logged(async_client, printer_factory, "Clean Gone", "gone")
+        for entry_id in (mine_old, theirs_old, gone_old):
+            await _age(db_session, entry_id, 100)
+        assert (await async_client.delete(f"/api/v1/printers/{gone}")).status_code == 200
+        admin = await _admin_token(async_client)
+        jwt, _ = await _user(
+            async_client, admin, "scoped_cleaner", [*self.PERMISSIONS, "maintenance:delete"], printer_ids=[mine]
+        )
+
+        fleet = await async_client.delete(f"{BASE}/log", params={"older_than_days": 30}, headers=_auth(jwt))
+        other_printer = await async_client.delete(
+            f"{BASE}/printers/{theirs}/log", params={"older_than_days": 30}, headers=_auth(jwt)
+        )
+        other_entry = await async_client.delete(f"{BASE}/log/{theirs_old}", headers=_auth(jwt))
+        deleted_printer_entry = await async_client.delete(f"{BASE}/log/{gone_old}", headers=_auth(jwt))
+
+        assert fleet.status_code == 200, fleet.text
+        assert fleet.json() == {"deleted": 1}
+        assert other_printer.status_code in (403, 404)
+        assert other_entry.status_code == 404
+        assert deleted_printer_entry.status_code == 404
+        db_session.expire_all()
+        assert await db_session.get(MaintenanceLogEntry, mine_old) is None
+        assert await db_session.get(MaintenanceLogEntry, theirs_old) is not None
+        assert await db_session.get(MaintenanceLogEntry, gone_old) is not None

+ 99 - 0
backend/tests/integration/test_mqtt_plug_lifetime_energy_3582.py

@@ -0,0 +1,99 @@
+"""#3582: the MQTT plug's lifetime energy path through the smart plug API."""
+
+import pytest
+from httpx import AsyncClient
+
+from backend.app.services.mqtt_smart_plug import SmartPlugMQTTData
+
+TOPIC = "tele/tasmota_plug/SENSOR"
+
+
+def _payload(**overrides) -> dict:
+    data = {
+        "name": "Tasmota MQTT",
+        "plug_type": "mqtt",
+        "mqtt_energy_topic": TOPIC,
+        "mqtt_energy_path": "ENERGY.Today",
+        "mqtt_energy_total_path": "ENERGY.Total",
+        "mqtt_energy_total_multiplier": 0.001,
+        "enabled": True,
+    }
+    data.update(overrides)
+    return data
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_create_stores_and_subscribes_the_lifetime_path(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    response = await async_client.post("/api/v1/smart-plugs/", json=_payload())
+
+    assert response.status_code == 200, response.text
+    body = response.json()
+    assert body["mqtt_energy_total_path"] == "ENERGY.Total"
+    assert body["mqtt_energy_total_multiplier"] == 0.001
+    kwargs = mock_mqtt_smart_plug_service.smart_plug_service.subscribe.call_args.kwargs
+    assert kwargs["energy_topic"] == TOPIC
+    assert kwargs["energy_total_path"] == "ENERGY.Total"
+    assert kwargs["energy_total_multiplier"] == 0.001
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_create_without_energy_topic_is_refused(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    response = await async_client.post(
+        "/api/v1/smart-plugs/",
+        json=_payload(mqtt_energy_topic=None, mqtt_power_topic="p/power"),
+    )
+
+    assert response.status_code == 422
+    assert "lifetime energy path needs an energy topic" in response.text
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_changing_only_the_lifetime_path_resubscribes(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    service = mock_mqtt_smart_plug_service.smart_plug_service
+    created = (await async_client.post("/api/v1/smart-plugs/", json=_payload(mqtt_energy_total_path=None))).json()
+    assert service.subscribe.call_args.kwargs["energy_total_path"] is None
+    service.subscribe.reset_mock()
+
+    response = await async_client.patch(
+        f"/api/v1/smart-plugs/{created['id']}", json={"mqtt_energy_total_path": "ENERGY.Total"}
+    )
+
+    assert response.status_code == 200, response.text
+    service.unsubscribe.assert_called_once_with(created["id"])
+    assert service.subscribe.call_args.kwargs["energy_total_path"] == "ENERGY.Total"
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_status_reports_today_and_lifetime_separately(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    service = mock_mqtt_smart_plug_service.smart_plug_service
+    created = (await async_client.post("/api/v1/smart-plugs/", json=_payload())).json()
+    service.get_plug_data.return_value = SmartPlugMQTTData(
+        plug_id=created["id"], power=150.0, energy=0.3, energy_total=843.4, state="ON"
+    )
+    service.is_reachable.return_value = True
+
+    response = await async_client.get(f"/api/v1/smart-plugs/{created['id']}/status")
+
+    assert response.status_code == 200, response.text
+    energy = response.json()["energy"]
+    assert energy["today"] == pytest.approx(0.3)
+    assert energy["total"] == pytest.approx(843.4)
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_status_without_lifetime_path_is_unchanged(async_client: AsyncClient, mock_mqtt_smart_plug_service):
+    service = mock_mqtt_smart_plug_service.smart_plug_service
+    created = (await async_client.post("/api/v1/smart-plugs/", json=_payload(mqtt_energy_total_path=None))).json()
+    service.get_plug_data.return_value = SmartPlugMQTTData(plug_id=created["id"], power=150.0, energy=4.8, state="ON")
+    service.is_reachable.return_value = True
+
+    response = await async_client.get(f"/api/v1/smart-plugs/{created['id']}/status")
+
+    energy = response.json()["energy"]
+    assert energy["today"] == pytest.approx(4.8)
+    assert energy["total"] is None

+ 1 - 0
backend/tests/integration/test_pause_load_paths_2984.py

@@ -54,6 +54,7 @@ async def _start_from_cache(test_engine, printer_id: int, cached) -> None:
         pm.get_status = MagicMock(return_value=state)
         pm.get_printer = MagicMock(return_value=MagicMock(serial_number="TESTAP2"))
         pm.get_client = MagicMock(return_value=None)
+        pm.get_current_print_user = MagicMock(return_value=None)  # a print nobody started in Bambuddy
 
         from backend.app.main import on_print_start
 

+ 2 - 1
backend/tests/integration/test_printers_api.py

@@ -4919,7 +4919,8 @@ class TestSetFanSpeedAPI:
             ("X2D", "Exhaust fan"),
             ("X1C", "Chamber fan"),
             ("P1S", "Chamber fan"),
-            ("H2D", "Chamber fan"),
+            ("H2D", "Exhaust fan"),
+            ("H3C", "Exhaust fan"),
         ],
     )
     async def test_chamber_fan_message_matches_model_label(

+ 359 - 0
backend/tests/integration/test_slicer_resend_joins_archive_1634.py

@@ -0,0 +1,359 @@
+"""The same slice sent again from the slicer adds a run to its archive (#1634).
+
+A slicer sending a slice again writes a new 3MF around the same G-code, so the
+file's hash never matched and each send became an archive of its own, its
+print count stuck at one. A print sent from the slicer whose G-code matches an
+archive (same owner, no project, no File Manager file) now joins that archive:
+the archive takes the new file in place of its old one and opens this print's
+run on it.
+"""
+
+from __future__ import annotations
+
+import zipfile
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from sqlalchemy import select
+
+from backend.app.core.config import settings as app_settings
+from backend.app.models.archive import PrintArchive
+from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
+from backend.app.services import archive_work
+from backend.app.services.archive import ArchiveService
+from backend.app.services.archive_gcode_hash import gcode_fingerprint
+from backend.tests.integration.test_external_print_confirmation_1898 import (
+    _clear_print_state,  # noqa: F401 - autouse fixture
+    _drive_print_start,
+)
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
+
+GCODE = b"; HEADER_BLOCK_START\nG28\nG1 X10 Y10 F3000\n"
+
+
+def _sliced(path, gcode: bytes = GCODE, *, export: str = "first"):
+    """A sliced 3MF; ``export`` stands for what a new export of it changes."""
+    path.parent.mkdir(parents=True, exist_ok=True)
+    with zipfile.ZipFile(path, "w") as zf:
+        zf.writestr("3D/3dmodel.model", f"<model export='{export}'/>")
+        zf.writestr("Metadata/plate_1.gcode", gcode)
+    return path
+
+
+@pytest.fixture
+def files(tmp_path, monkeypatch):
+    monkeypatch.setattr(app_settings, "base_dir", tmp_path)
+    monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
+    return tmp_path
+
+
+async def _archived(db_session, printer_id: int, files, *, name: str = "Bracket.3mf", **fields) -> PrintArchive:
+    """The archive of the first send, printed and done."""
+    archive = await ArchiveService(db_session).archive_print(printer_id, _sliced(files / "first" / name))
+    for key, value in {"status": "completed", **fields}.items():
+        setattr(archive, key, value)
+    await db_session.commit()
+    return archive
+
+
+async def _send_again(test_engine, printer, files, gcode: bytes = GCODE, *, owner_id: int | None = None):
+    """The slicer sends a print; the printer's 3MF is a new export of ``gcode``."""
+    upload = _sliced(files / "upload" / "sent.3mf", gcode, export="again")
+
+    async def download(_ip, _code, _remote, local_path, **_kwargs):
+        local_path.write_bytes(upload.read_bytes())
+        return True
+
+    return await _drive_print_start(
+        test_engine,
+        printer,
+        download_ok=True,
+        extra_patches=(
+            patch("backend.app.main.download_file_async", new=AsyncMock(side_effect=download)),
+            patch("backend.app.main.ArchiveService", ArchiveService),
+            patch("backend.app.main._ask_outcome_for_external_print", new=AsyncMock(return_value=False)),
+            patch("backend.app.main._print_user_id_if_still_there", new=AsyncMock(return_value=owner_id)),
+        ),
+    )
+
+
+async def _archives(db_session) -> list[PrintArchive]:
+    db_session.expire_all()
+    return list((await db_session.scalars(select(PrintArchive).order_by(PrintArchive.id))).all())
+
+
+async def _open_runs(db_session, archive_id: int) -> list[PrintLogEntry]:
+    return list(
+        (
+            await db_session.scalars(
+                select(PrintLogEntry)
+                .where(PrintLogEntry.archive_id == archive_id, PrintLogEntry.status == RUN_OPEN)
+                .execution_options(**{INCLUDE_OPEN_RUNS: True})
+            )
+        ).all()
+    )
+
+
+class TestJoining:
+    async def test_the_same_slice_sent_again_adds_a_run_to_its_archive(
+        self, test_engine, db_session, printer_factory, files
+    ):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.id == archive.id
+        assert row.status == "printing"
+        assert len(await _open_runs(db_session, archive.id)) == 1
+        from backend.app.main import _active_prints
+
+        assert archive.id in _active_prints.values()
+
+    async def test_it_takes_the_new_file_into_its_own_folder(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+        folder = (files / archive.file_path).parent
+        old_file = files / archive.file_path
+        photo = folder / "photos" / "finish.jpg"
+        photo.parent.mkdir()
+        photo.write_bytes(b"jpg")
+        old_hash = archive.content_hash
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        new_file = files / row.file_path
+        assert new_file.parent == folder
+        assert new_file.is_file() and new_file != old_file
+        assert not old_file.exists()
+        assert photo.exists()
+        assert row.content_hash != old_hash
+        assert row.gcode_hash == gcode_fingerprint(new_file)
+
+    async def test_another_slice_is_archived_anew(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        await _send_again(test_engine, printer, files, GCODE + b"G1 Z0.2\n")
+
+        rows = await _archives(db_session)
+        assert len(rows) == 2
+        assert rows[0].id == archive.id and rows[0].status == "completed"
+
+    @pytest.mark.parametrize("which", ["project", "library file", "deleted"])
+    async def test_an_archive_that_is_not_the_slicers_is_not_joined(
+        self, test_engine, db_session, printer_factory, files, which
+    ):
+        from backend.app.models.library import LibraryFile
+        from backend.app.models.project import Project
+
+        printer = await printer_factory()
+        fields: dict = {}
+        if which == "project":
+            project = Project(name="Brackets")
+            db_session.add(project)
+            await db_session.commit()
+            fields["project_id"] = project.id
+        elif which == "library file":
+            lib = LibraryFile(filename="Bracket.3mf", file_path="library/Bracket.3mf", file_size=1, file_type="3mf")
+            db_session.add(lib)
+            await db_session.commit()
+            fields["library_file_id"] = lib.id
+        else:
+            fields["deleted_at"] = datetime.now(timezone.utc)
+        await _archived(db_session, printer.id, files, **fields)
+
+        await _send_again(test_engine, printer, files)
+
+        assert len(await _archives(db_session)) == 2
+
+    async def test_the_owner_has_to_match(self, test_engine, db_session, printer_factory, files):
+        from backend.app.models.user import User
+
+        user = User(username="maker", password_hash="x", role="user")
+        db_session.add(user)
+        await db_session.commit()
+        user_id = user.id
+        printer = await printer_factory()
+        owned = await _archived(db_session, printer.id, files, created_by_id=user_id)
+        owned_id = owned.id
+
+        # Nobody started this print: the owned archive is not its.
+        await _send_again(test_engine, printer, files)
+        assert len(await _archives(db_session)) == 2
+
+        # Its owner started the next one, once that print ended.
+        from sqlalchemy import update
+
+        await db_session.execute(update(PrintArchive).values(status="completed"))
+        await db_session.execute(
+            update(PrintLogEntry).values(status="completed").execution_options(**{INCLUDE_OPEN_RUNS: True})
+        )
+        await db_session.commit()
+        await db_session.refresh(printer)
+        await _send_again(test_engine, printer, files, owner_id=user_id)
+        rows = await _archives(db_session)
+        assert len(rows) == 2
+        assert len(await _open_runs(db_session, owned_id)) == 1
+
+    async def test_an_archive_being_merged_is_left_alone(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        with archive_work.merging([archive.id]):
+            await _send_again(test_engine, printer, files)
+
+        assert len(await _archives(db_session)) == 2
+        assert not archive_work.is_held(archive.id)
+
+    async def test_the_archive_is_released_once_its_run_is_open(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        await _send_again(test_engine, printer, files)
+
+        assert not archive_work.is_held(archive.id)
+
+
+class TestPrintingElsewhere:
+    async def test_the_file_another_print_reads_is_kept(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        other = await printer_factory(name="Other")
+        archive = await _archived(db_session, printer.id, files, status="printing")
+        old_file = files / archive.file_path
+        old_hash = archive.content_hash
+        db_session.add(
+            PrintLogEntry(
+                archive_id=archive.id,
+                printer_id=other.id,
+                status=RUN_OPEN,
+                print_name=archive.print_name,
+                started_at=datetime.now(timezone.utc),
+            )
+        )
+        await db_session.commit()
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert (row.content_hash, row.file_path) == (old_hash, archive.file_path)
+        assert old_file.exists()
+        assert len(await _open_runs(db_session, archive.id)) == 2
+
+
+class TestName:
+    async def test_a_name_the_file_gave_follows_the_file(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files, name="Old_name.3mf")
+        assert archive.print_name == "Old_name"
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.print_name == "Bracket_plate_1"  # the name of the file the printer had
+
+    async def test_a_name_set_by_hand_stays(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        await _archived(db_session, printer.id, files, name="Old_name.3mf", print_name="Wall bracket, left")
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.print_name == "Wall bracket, left"
+
+
+class TestWhatTheArchiveKeeps:
+    async def test_the_saved_ams_pick_stays(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        pick = {"mapping": [0, 2], "printer_id": printer.id}
+        await _archived(db_session, printer.id, files, extra_data={"slicer_ams_mapping": pick})
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.extra_data["slicer_ams_mapping"] == pick
+
+    async def test_a_copy_that_fails_its_check_leaves_the_old_file(
+        self, test_engine, db_session, printer_factory, files
+    ):
+        """Same file name: the copy goes to a temporary name first, so a
+        truncated one never lands on the archive's file."""
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files, name="Bracket_plate_1.gcode.3mf")
+        old_file = files / archive.file_path
+        old_bytes = old_file.read_bytes()
+
+        def truncated(_src, dst, *_args, **_kwargs):
+            dst.write_bytes(b"not a zip")
+
+        with patch("backend.app.services.archive._copy_and_fsync", side_effect=truncated):
+            await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert (row.file_path, row.content_hash) == (archive.file_path, archive.content_hash)
+        assert old_file.read_bytes() == old_bytes
+        assert len(await _open_runs(db_session, archive.id)) == 1
+
+    async def test_a_file_a_queue_dispatch_holds_is_kept(self, test_engine, db_session, printer_factory, files):
+        """A queue dispatch holding the archive uploads or prints its file: the
+        resend adds its run but does not take the file away under it."""
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+        old_file = files / archive.file_path
+
+        archive_work.hold(archive.id)
+        try:
+            await _send_again(test_engine, printer, files)
+            assert archive_work.is_held(archive.id), "the dispatch's hold is its own"
+        finally:
+            archive_work.release(archive.id)
+
+        (row,) = await _archives(db_session)
+        assert row.file_path == archive.file_path
+        assert old_file.exists()
+        assert len(await _open_runs(db_session, archive.id)) == 1
+
+
+class TestEvents:
+    async def test_a_joined_archive_is_updated_not_created(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        mocks = await _send_again(test_engine, printer, files)
+
+        mocks["ws_manager"].send_archive_created.assert_not_awaited()
+        mocks["mqtt_relay"].on_archive_created.assert_not_awaited()
+        (event,), _ = mocks["ws_manager"].send_archive_updated.await_args
+        assert event["id"] == archive.id
+
+    async def test_a_new_archive_is_created(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+
+        mocks = await _send_again(test_engine, printer, files)
+
+        mocks["ws_manager"].send_archive_created.assert_awaited_once()
+        mocks["mqtt_relay"].on_archive_created.assert_awaited_once()
+
+
+class TestPrinterDeleted:
+    async def test_a_joined_archive_is_not_removed_as_one_just_written(
+        self, test_engine, db_session, printer_factory, files
+    ):
+        """The check after writing removes an archive this start wrote for a
+        printer deleted meanwhile. A joined archive is not this start's: it
+        holds earlier runs, and its adoption checked the printer itself."""
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+        drop = AsyncMock(return_value=True)
+
+        with patch("backend.app.main._drop_archive_of_deleted_printer", drop):
+            await _send_again(test_engine, printer, files)
+
+        drop.assert_not_awaited()
+        (row,) = await _archives(db_session)
+        assert row.id == archive.id
+        assert len(await _open_runs(db_session, archive.id)) == 1

+ 75 - 0
backend/tests/integration/test_spoolman_filament_name_save_3561.py

@@ -0,0 +1,75 @@
+"""Saving a Spoolman spool leaves the filament's name alone (#3561).
+
+The update route rebuilt the filament's name as "<material> <subtype>" and
+PATCHed it whenever that differed from the stored one -- so saving any change
+to a spool whose filament is called "Matte Scarlet Red" renamed it in Spoolman.
+With the name now read as subtype "Matte" and colour "Scarlet Red", the same
+rule would have cut it down to "PLA Matte" and lost the colour from the name.
+The name is only rebuilt when material or subtype is actually changed.
+"""
+
+import pytest
+from httpx import AsyncClient
+
+from backend.tests.integration.test_spoolman_inventory_api import (  # noqa: F401  (fixtures)
+    SAMPLE_SPOOLMAN_SPOOL,
+    mock_spoolman_client,
+    spoolman_settings,
+)
+
+PRODUCT_NAMED = {
+    **SAMPLE_SPOOLMAN_SPOOL,
+    "filament": {**SAMPLE_SPOOLMAN_SPOOL["filament"], "name": "Matte Scarlet Red", "material": "PLA"},
+}
+
+
+@pytest.fixture
+def product_named(mock_spoolman_client):  # noqa: F811
+    mock_spoolman_client.get_spool.return_value = PRODUCT_NAMED
+    return mock_spoolman_client
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_saving_the_form_unchanged_does_not_rename_the_filament(
+    async_client: AsyncClient,
+    spoolman_settings,  # noqa: F811
+    product_named,
+):
+    """What the form sends back: the subtype and colour it was shown."""
+    response = await async_client.patch(
+        "/api/v1/spoolman/inventory/spools/42",
+        json={"material": "PLA", "subtype": "Matte", "color_name": "Scarlet Red", "note": "moved to shelf 2"},
+    )
+
+    assert response.status_code == 200
+    product_named.patch_filament.assert_not_called()
+    product_named.find_or_create_filament.assert_not_called()
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_a_colour_change_keeps_the_name_too(
+    async_client: AsyncClient,
+    spoolman_settings,  # noqa: F811
+    product_named,
+):
+    response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"rgba": "0000FFFF"})
+
+    assert response.status_code == 200
+    product_named.patch_filament.assert_called_once()
+    assert product_named.patch_filament.call_args.args[1]["name"] == "Matte Scarlet Red"
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_changing_the_subtype_still_renames_it(
+    async_client: AsyncClient,
+    spoolman_settings,  # noqa: F811
+    product_named,
+):
+    response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"subtype": "Silk"})
+
+    assert response.status_code == 200
+    product_named.patch_filament.assert_called_once()
+    assert product_named.patch_filament.call_args.args[1]["name"] == "PLA Silk"

+ 25 - 7
backend/tests/unit/services/test_bambu_ftp.py

@@ -452,13 +452,25 @@ class TestUpload:
         assert result is False
         client.disconnect()
 
-    @pytest.mark.parametrize(("server_size", "logged_error"), [(100, True), (1024, False), (None, False)])
+    @pytest.mark.parametrize(
+        ("sizes", "uploaded", "logged_error"),
+        [
+            ([1024], True, False),  # complete at the first read
+            ([None], True, False),  # unreadable: nothing to judge by, proceeds as before
+            # #3538: an A1 still writing the file out reads short at first,
+            # then reaches the full size.
+            ([0, 0, 512, 1024], True, False),
+            # Never complete: no print command for it.
+            ([100], False, True),
+        ],
+    )
     def test_upload_without_a_226_is_checked_on_a_new_connection(
-        self, ftp_client_factory, ftp_server, tmp_path, caplog, server_size, logged_error
+        self, ftp_client_factory, ftp_server, tmp_path, caplog, sizes, uploaded, logged_error
     ):
         """No 226 within the wait (an H2D can take 30+ s) still lets the upload
-        proceed, but its size is read back on a fresh connection, since the
-        old one may be out of step, and a mismatch is logged as an error."""
+        proceed once its size is read back on a fresh connection, since the
+        old one may be out of step. A short size is read again until it
+        matches; one that never does fails the upload so it is retried."""
         import logging
 
         import backend.app.services.bambu_ftp as ftp_mod
@@ -467,6 +479,8 @@ class TestUpload:
         local.write_bytes(b"data" * 256)
         client = ftp_client_factory()
         client.connect()
+        client.UNCONFIRMED_SIZE_POLL_INTERVAL = 0
+        client.UNCONFIRMED_SIZE_POLL_TIMEOUT = 0.2
 
         def never_answers():
             raise TimeoutError("timed out")
@@ -476,16 +490,20 @@ class TestUpload:
 
         def fake_size(c, remote_path):
             checked.append(remote_path)
-            return server_size
+            return sizes[min(len(checked), len(sizes)) - 1]
 
         with (
             patch.object(ftp_mod, "_size_on_new_connection", fake_size),
             caplog.at_level(logging.INFO, logger="backend.app.services.bambu_ftp"),
         ):
-            assert client.upload_file(local, "/cache/test.bin") is True
+            assert client.upload_file(local, "/cache/test.bin") is uploaded
         client.disconnect()
 
-        assert checked == ["/cache/test.bin"]
+        assert set(checked) == {"/cache/test.bin"}
+        if uploaded:
+            assert len(checked) == len(sizes)
+        else:
+            assert client.last_failure.kind is ftp_mod.FtpFailureKind.NETWORK
         errors = [r for r in caplog.records if r.levelno >= logging.ERROR]
         assert bool(errors) is logged_error
 

+ 53 - 0
backend/tests/unit/services/test_command_response_content_3531.py

@@ -0,0 +1,53 @@
+"""#3531: the debug log records the content of commands the printer reports back.
+
+The H3C touchscreen's Unload All is one command, ``multi_slot_ams_change_filament``,
+whose fields are not documented anywhere. The printer reports it back like every
+command, but the debug log kept only its name. push_status (the status itself)
+and project_file (which may carry a signed download URL) stay name-only.
+"""
+
+import logging
+
+import pytest
+
+from backend.app.services.bambu_mqtt import BambuMQTTClient
+
+
+@pytest.fixture
+def mqtt_client():
+    return BambuMQTTClient(ip_address="192.168.1.100", serial_number="TEST123", access_code="12345678")
+
+
+def _content_lines(caplog):
+    return [r.getMessage() for r in caplog.records if " content: " in r.getMessage()]
+
+
+def test_a_reported_command_is_logged_with_its_fields(mqtt_client, caplog):
+    caplog.set_level(logging.DEBUG, logger="backend.app.services.bambu_mqtt")
+
+    mqtt_client._process_message(
+        {"print": {"command": "multi_slot_ams_change_filament", "sequence_id": "7", "slots": [{"ams_id": 128}]}}
+    )
+
+    lines = _content_lines(caplog)
+    assert len(lines) == 1
+    assert "multi_slot_ams_change_filament content:" in lines[0]
+    assert '"slots": [{"ams_id": 128}]' in lines[0]
+
+
+@pytest.mark.parametrize("command", ["push_status", "project_file"])
+def test_status_and_print_start_stay_name_only(mqtt_client, caplog, command):
+    caplog.set_level(logging.DEBUG, logger="backend.app.services.bambu_mqtt")
+
+    mqtt_client._process_message({"print": {"command": command, "url": "https://example.invalid/signed?token=x"}})
+
+    assert _content_lines(caplog) == []
+
+
+def test_long_content_is_capped(mqtt_client, caplog):
+    caplog.set_level(logging.DEBUG, logger="backend.app.services.bambu_mqtt")
+
+    mqtt_client._process_message({"print": {"command": "gcode_line", "param": "G1 X1\n" * 2000}})
+
+    (line,) = _content_lines(caplog)
+    assert len(line.split(" content: ", 1)[1]) == 4000

+ 149 - 6
backend/tests/unit/services/test_label_renderer.py

@@ -9,6 +9,7 @@ from reportlab.lib.pagesizes import letter
 from reportlab.lib.units import mm
 
 from backend.app.services.label_renderer import (
+    FONT_BOLD,
     LabelData,
     SheetLayout,
     get_sheet_capacity,
@@ -300,7 +301,7 @@ def test_hex_color_code_skipped_when_rgba_invalid():
 
 
 def test_brand_rendered_in_bold_per_809_followup():
-    """#809 follow-up: brand should render in Helvetica-Bold (not regular).
+    """#809 follow-up: brand should render in the bold font (not regular).
     Uncompressed PDFs include font-name tokens like '/F2' tied to a font
     resource; we can grep for the bold font's basename in the resource block.
     """
@@ -315,10 +316,9 @@ def test_brand_rendered_in_bold_per_809_followup():
         )
     ]
     pdf = _render_uncompressed("box_62x29", data)
-    # ReportLab references the bold variant of Helvetica via /Helvetica-Bold
-    # in the font dictionary — both the spool ID (always bold) and the brand
-    # (now bold per #809 follow-up) cause the resource to be embedded.
-    assert b"Helvetica-Bold" in pdf, "label PDF must reference Helvetica-Bold for the brand line"
+    # Both the spool ID (always bold) and the brand (bold per #809 follow-up)
+    # embed the bold font, which the font dictionary names.
+    assert b"LiberationSans-Bold" in pdf, "label PDF must embed the bold font for the brand line"
 
 
 def test_box_template_does_not_truncate_normal_brand_or_name():
@@ -499,7 +499,7 @@ def test_the_smallest_label_has_room_for_a_full_size_spool_id(label_h_mm):
     swatch_w = min(inner_w * 0.18, inner_h, 16 * mm)
     qr = _roomy_qr_size(inner_w, inner_h)
     text_w = inner_w - swatch_w - qr - 2 * 1.5 * mm
-    assert text_w >= stringWidth("#9999", "Helvetica-Bold", 16)
+    assert text_w >= stringWidth("#9999", FONT_BOLD, 16)
     assert MIN_LABEL_H_MM >= 20.0  # the tight layout starts below 20 mm
 
 
@@ -581,3 +581,146 @@ def test_custom_layout_size_and_capacity():
     assert label_size_mm(layout) == (70.0, 36.0)
     assert get_sheet_capacity(layout) == 24
     assert render_labels(layout, [_sample()]).startswith(b"%PDF")
+
+
+# ── Non-Latin-1 text (#3553) ──
+
+
+def _page_texts(pdf: bytes) -> list[str]:
+    import pypdfium2 as pdfium  # noqa: PLC0415
+
+    doc = pdfium.PdfDocument(pdf)
+    try:
+        return [doc[i].get_textpage().get_text_range() for i in range(len(doc))]
+    finally:
+        doc.close()
+
+
+@pytest.mark.parametrize("template", ALL_TEMPLATES)
+def test_polish_and_cyrillic_text_prints_as_written(template):
+    """The PDF base fonts cover only Western European characters: Polish
+    ą ę ł ń ś ź ż and Cyrillic came out as empty boxes."""
+    data = [
+        _sample(
+            7,
+            brand="Żółć",
+            name="Brązowy",
+            material="PLA",
+            subtype="Мат",
+        )
+    ]
+    text = _page_texts(render_labels(template, data))[0]
+    for word in ("Żółć", "Brązowy", "Мат"):
+        assert word in text, f"{word!r} missing from {template}: {text!r}"
+
+
+@pytest.mark.parametrize("template", ALL_TEMPLATES)
+def test_labels_use_no_base_font(template):
+    import re  # noqa: PLC0415
+
+    pdf = render_labels(template, [_sample(3)])
+    fonts = set(re.findall(rb"/BaseFont /(?:[A-Z]{6}\+)?([^\s/>]+)", pdf))
+    assert fonts == {b"LiberationSans", b"LiberationSans-Bold"}, fonts
+
+
+# ── Chinese, Japanese and Korean (#3560) ──
+
+
+def _base_fonts(pdf: bytes) -> set[bytes]:
+    import re  # noqa: PLC0415
+
+    return set(re.findall(rb"/BaseFont /(?:[A-Z]{6}\+)?([^\s/>]+)", pdf))
+
+
+@pytest.mark.parametrize("template", ALL_TEMPLATES)
+def test_chinese_japanese_and_korean_print_as_written(template):
+    """Liberation Sans has no CJK, so a name in Chinese printed as empty boxes
+    (#3560). The characters it lacks are drawn in the fallback fonts, which
+    is what makes them visible -- the text layer alone would read correctly
+    even with boxes on the page, so the fonts are checked too."""
+    data = [_sample(8, brand="拓竹", name="玉白 흰색", material="PLA", subtype="ホワ")]
+    pdf = render_labels(template, data)
+
+    text = "".join(_page_texts(pdf))
+    for word in ("拓竹", "玉白", "PLA", "ホワ", "흰색"):
+        assert word in text, (template, word, text)
+    assert {b"DroidSansFallback", b"NotoSansKR-Regular"} <= _base_fonts(pdf)
+
+
+def test_only_the_characters_the_label_font_lacks_change_font():
+    from backend.app.services.label_renderer import (  # noqa: PLC0415
+        FONT_CJK,
+        FONT_HANGUL,
+        FONT_REGULAR,
+        _font_runs,
+    )
+
+    assert _font_runs("Żółć 玉白 흰색 Мат", FONT_REGULAR) == [
+        (FONT_REGULAR, "Żółć "),
+        (FONT_CJK, "玉白"),
+        (FONT_REGULAR, " "),
+        (FONT_HANGUL, "흰색"),
+        (FONT_REGULAR, " Мат"),
+    ]
+
+
+def test_a_label_in_one_script_embeds_only_the_fallback_it_needs():
+    pdf = render_labels("box_62x29", [_sample(9, name="玉白", material="PLA")])
+
+    fonts = _base_fonts(pdf)
+    assert b"DroidSansFallback" in fonts
+    assert b"NotoSansKR-Regular" not in fonts
+
+
+def test_a_long_chinese_name_is_truncated_by_its_real_width():
+    """Truncation measured the text in Liberation Sans, whose missing-glyph
+    box is narrower than a CJK character, so a long name ran off the label."""
+    import io  # noqa: PLC0415
+
+    from reportlab.pdfgen import canvas  # noqa: PLC0415
+
+    from backend.app.services.label_renderer import FONT_BOLD, _text_width, _truncate_to_width  # noqa: PLC0415
+
+    c = canvas.Canvas(io.BytesIO())
+    text = "很长很长很长很长很长很长很长很长的名字"
+    fitted = _truncate_to_width(c, text, FONT_BOLD, 9, 60)
+
+    assert fitted.endswith("…")
+    assert _text_width(fitted, FONT_BOLD, 9) <= 60
+    assert len(fitted) > 3  # and it still uses the room it has
+
+
+def test_a_short_chinese_name_that_only_looked_short_is_truncated():
+    """Four CJK characters measured as Liberation's missing-glyph boxes are
+    13 pt wide at 9 pt; drawn, they are 36. The early "it fits" check has to
+    measure what is drawn too."""
+    import io  # noqa: PLC0415
+
+    from reportlab.pdfgen import canvas  # noqa: PLC0415
+
+    from backend.app.services.label_renderer import FONT_BOLD, _text_width, _truncate_to_width  # noqa: PLC0415
+
+    fitted = _truncate_to_width(canvas.Canvas(io.BytesIO()), "玉白玉白", FONT_BOLD, 9, 30)
+
+    assert fitted.endswith("…")
+    assert _text_width(fitted, FONT_BOLD, 9) <= 30
+
+
+def test_the_tight_layout_draws_cjk_in_the_fallback_font():
+    """Labels under 20 mm tall use the four-line layout, which draws the brand
+    and material lines itself."""
+    import io  # noqa: PLC0415
+
+    from reportlab.pdfgen import canvas  # noqa: PLC0415
+
+    from backend.app.services.label_renderer import _draw_label  # noqa: PLC0415
+
+    buf = io.BytesIO()
+    c = canvas.Canvas(buf, pagesize=(60 * mm, 15 * mm))
+    _draw_label(c, 0, 0, 60 * mm, 15 * mm, _sample(4, brand="拓竹", material="PLA", subtype="흰색"))
+    c.save()
+    pdf = buf.getvalue()
+
+    text = "".join(_page_texts(pdf))
+    assert "拓竹" in text and "흰색" in text, text
+    assert {b"DroidSansFallback", b"NotoSansKR-Regular"} <= _base_fonts(pdf)

+ 105 - 8
backend/tests/unit/services/test_label_renderer_fields.py

@@ -20,6 +20,7 @@ from backend.app.services.label_renderer import (
     ALL_LABEL_FIELDS,
     DEFAULT_LABEL_FIELDS,
     LabelData,
+    _breaks_before,
     _draw_label,
     label_size_mm,
     pdf_to_pngs,
@@ -66,14 +67,13 @@ def _text(template: str, data: LabelData, fields=DEFAULT_LABEL_FIELDS) -> bytes:
     c.showPage()
     c.save()
     pdf = buf.getvalue()
-    streams = []
-    for m in re.finditer(rb"stream\r?\n(.*?)endstream", pdf, re.S):
-        # The object's own dictionary sits between its "N 0 obj" and "stream".
-        head = pdf[pdf.rfind(b" obj", 0, m.start()) : m.start()]
-        if b"/Subtype /Image" not in head:
-            streams.append(m.group(1))
-    assert len(streams) == 1, f"expected one page content stream, got {len(streams)}"
-    return streams[0]
+    # The page names its content stream; the embedded fonts and the QR image
+    # are streams of their own.
+    refs = re.findall(rb"/Contents (\d+) 0 R", pdf)
+    assert len(refs) == 1, f"expected one page content stream, got {len(refs)}"
+    m = re.search(rb"(?<!\d)" + refs[0] + rb" 0 obj.*?stream\r?\n(.*?)endstream", pdf, re.S)
+    assert m is not None
+    return m.group(1)
 
 
 def test_default_fields_are_what_labels_always_carried():
@@ -211,3 +211,100 @@ def test_qr_stays_black_and_white_in_the_png():
     qr_region = image.crop((w // 2, 0, w, h))
     greys = sum(1 for v in qr_region.getdata() if 40 < v < 215)
     assert greys / (qr_region.width * qr_region.height) < 0.02
+
+
+# ── Long rows continue on further lines (#3621) ──────────────────────────────
+
+ZH_NAME = "【快打】亚光PETG 哑光黑色 高速"
+
+
+def _lines(
+    data: LabelData, fields=DEFAULT_LABEL_FIELDS, monochrome: bool = True, size_mm: tuple[int, int] = (40, 30)
+) -> list[str]:
+    """The text drawn on a label, 40 x 30 unless given, one entry per line, top to bottom.
+    A line with Chinese is drawn in pieces, one per font, on one baseline."""
+    drawn: dict[float, str] = {}
+    real = rl_canvas.Canvas.drawString
+
+    def record(self, x, y, text, *args, **kwargs):
+        drawn[round(y, 2)] = drawn.get(round(y, 2), "") + text
+        return real(self, x, y, text, *args, **kwargs)
+
+    w, h = size_mm[0] * mm, size_mm[1] * mm
+    c = rl_canvas.Canvas(io.BytesIO(), pagesize=(w, h))
+    with patch.object(rl_canvas.Canvas, "drawString", record):
+        _draw_label(c, 0, 0, w, h, data, monochrome, fields)
+    return [drawn[y] for y in sorted(drawn, reverse=True)]
+
+
+def _name_lines(lines: list[str]) -> list[str]:
+    """The lines between the hex code and the next row or the spool ID."""
+    start = lines.index("#E8F0E0") + 1
+    return [line for line in lines[start:] if line not in ("Shelf 2", "#128")]
+
+
+def test_a_long_chinese_name_continues_on_the_next_lines():
+    lines = _name_lines(_lines(_data(name=ZH_NAME, storage_location=None)))
+
+    assert len(lines) > 1
+    # Nothing is lost but a space where a line breaks.
+    assert "".join(lines).replace(" ", "") == ZH_NAME.replace(" ", "")
+    assert not any(line.endswith("…") for line in lines)
+
+
+def test_a_latin_word_is_not_broken_next_to_chinese():
+    lines = _name_lines(_lines(_data(name=ZH_NAME, storage_location=None)))
+
+    assert any(line.startswith("PETG") or line.endswith("PETG") for line in lines)
+    assert not any(line.startswith("】") for line in lines)
+
+
+def test_a_long_latin_name_breaks_at_spaces():
+    name = "Matte Charcoal Black"
+    lines = _name_lines(_lines(_data(name=name, storage_location=None)))
+
+    assert len(lines) > 1
+    assert " ".join(lines) == name
+
+
+def test_the_row_below_keeps_its_line():
+    """The name takes no line the location needs: it is cut sooner instead."""
+    lines = _lines(_data(name=ZH_NAME, storage_location="Shelf 2"))
+
+    assert "Shelf 2" in lines
+    assert "#128" in lines
+    assert _name_lines(lines)[-1].endswith("…")
+
+
+def test_a_row_takes_at_most_three_lines():
+    """Also on a label with room for more."""
+    lines = _name_lines(_lines(_data(name="Charcoal " * 30, storage_location=None), size_mm=(75, 55)))
+
+    assert len(lines) == 3
+    assert lines[-1].endswith("…")
+
+
+def test_wrapped_lines_stay_above_the_spool_id():
+    drawn: list[tuple[float, str]] = []
+    real = rl_canvas.Canvas.drawString
+
+    def record(self, x, y, text, *args, **kwargs):
+        drawn.append((y, text))
+        return real(self, x, y, text, *args, **kwargs)
+
+    with patch.object(rl_canvas.Canvas, "drawString", record):
+        _text("box_40x30", _data(name="Charcoal " * 12, storage_location=None, note="Dry first " * 6), ALL)
+
+    id_y = next(y for y, text in drawn if text == "#128")
+    assert min(y for y, text in drawn if text != "#128") >= id_y + 16
+
+
+def test_chinese_punctuation_stays_with_its_word():
+    """A line never starts with a closing bracket or comma, nor ends with an
+    opening bracket."""
+    assert not _breaks_before("快打】", 2)
+    assert not _breaks_before("快,打", 1)
+    assert not _breaks_before("【快", 1)
+    assert _breaks_before("快打", 1)
+    assert _breaks_before("光PETG", 1)
+    assert not _breaks_before("PETG", 1)

+ 2 - 0
backend/tests/unit/services/test_mqtt_smart_plug_subscribe.py

@@ -27,6 +27,8 @@ def _plug(**overrides):
         "mqtt_energy_topic": None,
         "mqtt_energy_path": None,
         "mqtt_energy_multiplier": None,
+        "mqtt_energy_total_path": None,
+        "mqtt_energy_total_multiplier": None,
         "mqtt_state_topic": None,
         "mqtt_state_path": None,
         "mqtt_state_on_value": None,

+ 26 - 5
backend/tests/unit/services/test_p2s_accessory_fans.py

@@ -314,10 +314,31 @@ class TestExhaustFanLabelModels:
         for model in ("P2S", "X2D", "p2s", " P2S ", "N7", "N6"):
             assert uses_exhaust_fan_label(model) is True, model
 
+    def test_h2_series_and_h3c_use_exhaust_label(self):
+        """Bambu Studio doesn't rename their part 3, so it is "Exhaust" (#3521)."""
+        from backend.app.utils.printer_models import uses_exhaust_fan_label
+
+        for model in (
+            "H2D",
+            "H2D Pro",
+            "H2DPRO",
+            "H2C",
+            "H2S",
+            "H3C",
+            "O1D",
+            "O1E",
+            "O2D",
+            "O1C",
+            "O1C2",
+            "O1S",
+            "N10",
+        ):
+            assert uses_exhaust_fan_label(model) is True, model
+
     def test_other_enclosed_models_keep_chamber_label(self):
         from backend.app.utils.printer_models import uses_exhaust_fan_label
 
-        for model in ("X1C", "X1", "X1E", "P1S", "H2D", "H2C", "H2S", "A1"):
+        for model in ("X1C", "X1", "X1E", "P1S", "A1"):
             assert uses_exhaust_fan_label(model) is False, model
 
     def test_unknown_or_missing_model_defaults_to_chamber(self):
@@ -331,8 +352,8 @@ class TestExhaustFanLabelModels:
 class TestExhaustLabelModelListsAgree:
     """The exhaust-label model list is duplicated across the stack.
 
-    The backend keeps ``EXHAUST_FAN_LABEL_MODELS`` (display names plus the N7/N6
-    internal codes, since the API can be handed either) and the frontend keeps
+    The backend keeps ``EXHAUST_FAN_LABEL_MODELS`` (display names plus the internal
+    codes, since the API can be handed either) and the frontend keeps
     ``MODELS_WITH_EXHAUST_LABEL`` in PrintersPage.tsx (display names only —
     ``printer.model`` is always a display name by the time it reaches the card).
     Both are correct as written, but nothing stopped them drifting apart: adding
@@ -378,8 +399,8 @@ class TestExhaustLabelModelListsAgree:
     def test_every_backend_display_name_is_handled_by_the_frontend(self):
         from backend.app.utils.printer_models import EXHAUST_FAN_LABEL_MODELS
 
-        # N7/N6 are internal codes that never reach the card, so exclude them.
-        internal_codes = {"N7", "N6"}
+        # Internal codes never reach the card, so exclude them.
+        internal_codes = {"N7", "N6", "O1D", "O1E", "O2D", "O1C", "O1C2", "O1S", "N10"}
         backend_display = set(EXHAUST_FAN_LABEL_MODELS) - internal_codes
         missing = backend_display - self._frontend_models()
         assert not missing, (

+ 80 - 0
backend/tests/unit/test_archive_run_aggregation.py

@@ -605,3 +605,83 @@ async def test_a_run_without_an_estimate_shows_no_reconnect_gap(
     assert (row["actual_time_seconds"], row["time_accuracy"]) == (None, None)
     body = (await async_client.get("/api/v1/archives/stats")).json()
     assert body["average_time_accuracy"] is None
+
+
+def _plate_run(archive, day: int, *, grams: float, cost: float, energy_kwh=None, energy_cost=None) -> PrintLogEntry:
+    started = datetime(2026, 11, day, 10, 0, tzinfo=timezone.utc)
+    return PrintLogEntry(
+        archive_id=archive.id,
+        printer_id=archive.printer_id,
+        status="completed",
+        started_at=started,
+        completed_at=started,
+        duration_seconds=3600,
+        filament_used_grams=grams,
+        cost=cost,
+        energy_kwh=energy_kwh,
+        energy_cost=energy_cost,
+        created_at=started,
+    )
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_an_archive_printed_plate_by_plate_carries_what_all_its_prints_cost(
+    async_client: AsyncClient, archive_factory, printer_factory, db_session
+):
+    """Each plate of a multi-plate file is a run of one archive (#3609).
+
+    The archive keeps the file's filament and the first print's energy; the
+    totals are what the card shows, and what Statistics adds up.
+    """
+    printer = await printer_factory()
+    archive = await archive_factory(
+        printer.id,
+        status="completed",
+        filament_used_grams=837.0,  # the whole file, all plates
+        cost=45.17,
+        energy_kwh=0.2,
+        energy_cost=0.24,  # the first plate's
+        with_run=False,
+    )
+    db_session.add_all(
+        [
+            _plate_run(archive, 1, grams=120.0, cost=6.8, energy_kwh=0.2, energy_cost=0.24),
+            _plate_run(archive, 2, grams=150.0, cost=8.5, energy_kwh=0.5, energy_cost=0.61),
+            _plate_run(archive, 3, grams=90.0, cost=5.1, energy_kwh=0.3, energy_cost=0.38),
+        ]
+    )
+    await db_session.commit()
+
+    body = (await async_client.get(f"/api/v1/archives/{archive.id}")).json()
+
+    assert body["run_count"] == 3
+    assert body["total_filament_actual_grams"] == pytest.approx(360.0)
+    assert body["total_cost"] == pytest.approx(20.4)
+    assert body["total_energy_kwh"] == pytest.approx(1.0)
+    assert body["total_energy_cost"] == pytest.approx(1.23)
+    # The archive's own figures are unchanged (#1378).
+    assert body["cost"] == pytest.approx(45.17)
+    assert body["energy_cost"] == pytest.approx(0.24)
+
+    stats = (await async_client.get("/api/v1/archives/stats")).json()
+    assert stats["total_cost"] == pytest.approx(body["total_cost"])
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_no_energy_total_when_no_print_measured_any(
+    async_client: AsyncClient, archive_factory, printer_factory, db_session
+):
+    printer = await printer_factory()
+    archive = await archive_factory(printer.id, status="completed", with_run=False)
+    db_session.add_all([_plate_run(archive, 1, grams=10.0, cost=1.0), _plate_run(archive, 2, grams=10.0, cost=1.0)])
+    await db_session.commit()
+
+    body = (await async_client.get("/api/v1/archives/")).json()
+    row = next(a for a in body if a["id"] == archive.id)
+
+    assert row["total_cost"] == pytest.approx(2.0)
+    # Unknown, not zero: no smart plug measured either print.
+    assert row["total_energy_kwh"] is None
+    assert row["total_energy_cost"] is None

+ 97 - 0
backend/tests/unit/test_cloud_preset_listing_nulls_3593.py

@@ -0,0 +1,97 @@
+"""A Bambu Cloud preset listing with null types or lists still lists presets (#3593).
+
+The cloud sends ``null`` for a preset type, or for its private or public list,
+when the account has nothing there. The Slice dialog's preset list and the
+Profiles page's cloud list read the listing as nested dicts and failed on it,
+so one empty type cost every preset, local ones included.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.app.api.routes import cloud as cloud_routes, slicer_presets as sp
+from backend.app.services.bambu_cloud import BambuCloudService, _slicer_settings_listing
+
+# Shaped like an account with no filament presets, only stock printers and one
+# process preset of its own.
+LISTING = {
+    "filament": None,
+    "printer": {"private": None, "public": [{"setting_id": "GP1", "name": "Bambu Lab X1C 0.4 nozzle"}]},
+    "print": {"private": [{"setting_id": "PP1", "name": "My 0.2mm"}], "public": None},
+}
+
+
+def _cloud_answering(body) -> BambuCloudService:
+    service = BambuCloudService()
+    service.access_token = "test-token"
+    response = MagicMock()
+    response.status_code = 200
+    response.json.return_value = body
+    service._client = MagicMock()
+    service._client.get = AsyncMock(return_value=response)
+    service.close = AsyncMock()
+    return service
+
+
+def _user() -> MagicMock:
+    user = MagicMock(id=1)
+    user.has_permission = MagicMock(return_value=True)
+    return user
+
+
+async def test_the_slice_dialog_lists_the_presets_the_account_has():
+    sp._cloud_cache.clear()
+    with (
+        patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
+        patch.object(sp, "BambuCloudService", return_value=_cloud_answering(LISTING)),
+    ):
+        slots, status = await sp._fetch_cloud_presets(MagicMock(), _user())
+    sp._cloud_cache.clear()
+
+    assert status == "ok"
+    assert [p.name for p in slots["printer"]] == ["Bambu Lab X1C 0.4 nozzle"]
+    assert [p.name for p in slots["process"]] == ["My 0.2mm"]
+    assert slots["filament"] == []
+
+
+async def test_the_profiles_page_lists_the_presets_the_account_has():
+    service = _cloud_answering(LISTING)
+    with patch.object(cloud_routes, "build_authenticated_cloud", AsyncMock(return_value=service)):
+        result = await cloud_routes.get_slicer_settings(db=MagicMock(), current_user=None)
+
+    assert [s.name for s in result.printer] == ["Bambu Lab X1C 0.4 nozzle"]
+    assert [s.name for s in result.process] == ["My 0.2mm"]
+    assert result.filament == []
+
+
+@pytest.mark.parametrize(
+    ("body", "expected_printer_private"),
+    [
+        (None, []),
+        ([], []),
+        ({"printer": "unexpected"}, []),
+        ({"printer": {"private": "unexpected"}}, []),
+        ({"printer": {"private": [None, "x", {"setting_id": "P1"}]}}, [{"setting_id": "P1"}]),
+    ],
+)
+def test_every_type_reads_as_lists_of_presets(body, expected_printer_private):
+    listing = _slicer_settings_listing(body)
+
+    for key in ("filament", "printer", "print"):
+        assert isinstance(listing[key]["private"], list)
+        assert isinstance(listing[key]["public"], list)
+    assert listing["printer"]["private"] == expected_printer_private
+
+
+def test_a_full_listing_is_kept_as_it_is():
+    body = {
+        "filament": {"private": [{"setting_id": "F1"}], "public": [{"setting_id": "F2"}]},
+        "printer": {"private": [], "public": []},
+        "print": {"private": [], "public": []},
+        "message": "success",
+    }
+
+    assert _slicer_settings_listing(body) == body

+ 59 - 0
backend/tests/unit/test_dispatch_priority_migration_2915.py

@@ -0,0 +1,59 @@
+"""The startup migration gives a database from before #2915 the printers.dispatch_priority column."""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from backend.app.core.database import run_migrations
+
+
+@pytest.fixture(autouse=True)
+def force_sqlite_dialect(monkeypatch):
+    from backend.app.core import database as database_module, db_dialect
+
+    monkeypatch.setattr(db_dialect, "is_sqlite", lambda: True)
+    monkeypatch.setattr(db_dialect, "is_postgres", lambda: False)
+    monkeypatch.setattr(database_module, "is_sqlite", lambda: True)
+
+
+async def _columns(engine) -> list[str]:
+    async with engine.connect() as conn:
+        return [row[1] for row in (await conn.execute(text("PRAGMA table_info(printers)"))).all()]
+
+
+@pytest.mark.asyncio
+async def test_the_column_is_added_once_and_existing_printers_keep_no_priority():
+    import importlib
+    import pkgutil
+
+    from sqlalchemy.ext.asyncio import AsyncSession
+
+    import backend.app.models as models_pkg
+    from backend.app.core.database import Base
+
+    # Every table the migrations touch, not just those the package imports.
+    for module in pkgutil.iter_modules(models_pkg.__path__):
+        importlib.import_module(f"backend.app.models.{module.name}")
+    from backend.app.models.printer import Printer
+
+    engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
+    async with engine.begin() as conn:
+        await conn.run_sync(Base.metadata.create_all)
+    async with AsyncSession(engine) as db:
+        db.add(Printer(name="P", serial_number="S", ip_address="1.2.3.4", access_code="x"))
+        await db.commit()
+    async with engine.begin() as conn:
+        await conn.execute(text("ALTER TABLE printers DROP COLUMN dispatch_priority"))
+    assert "dispatch_priority" not in await _columns(engine)
+
+    for _ in range(2):  # idempotent
+        async with engine.begin() as conn:
+            await run_migrations(conn)
+
+    assert "dispatch_priority" in await _columns(engine)
+    async with engine.connect() as conn:
+        value = (await conn.execute(text("SELECT dispatch_priority FROM printers"))).scalar_one()
+    await engine.dispose()
+    assert value is None

+ 82 - 0
backend/tests/unit/test_export_spreadsheet_cells.py

@@ -0,0 +1,82 @@
+"""Archive and statistics exports show typed text as it was typed in a spreadsheet.
+
+Print names, notes, tags, project names and failure reasons are typed by
+people, and a spreadsheet reads a cell that starts like a formula as one. In
+CSV such a cell gets a leading quote; in Excel it is stored as text. Numbers
+and empty cells are written as they are.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+
+import pytest
+from openpyxl import load_workbook
+
+from backend.app.services.export import ExportService, _spreadsheet_text
+
+LINK = '=HYPERLINK("https://elsewhere.example","open")'
+
+
+@pytest.mark.parametrize(
+    ("value", "expected"),
+    [
+        ("Benchy", "Benchy"),
+        ("a = b", "a = b"),
+        (LINK, "'" + LINK),
+        ("+1 extra", "'+1 extra"),
+        ("-x", "'-x"),
+        ("@SUM(A1)", "'@SUM(A1)"),
+        ("  =1+1", "'  =1+1"),
+        ("\t=1+1", "'\t=1+1"),
+        ("\nnote", "'\nnote"),
+        ("=1+1", "'=1+1"),
+        ("", ""),
+        (None, None),
+        (-5, -5),
+        (2.5, 2.5),
+    ],
+)
+def test_cell_values(value, expected):
+    assert _spreadsheet_text(value) == expected
+
+
+def _service() -> ExportService:
+    return ExportService(db=None)  # type: ignore[arg-type]
+
+
+def test_archive_csv_keeps_typed_text_as_text():
+    data = _service()._generate_csv(["print_name", "notes", "cost"], [["Benchy", LINK, -1.5]])
+
+    rows = list(csv.reader(io.StringIO(data.decode("utf-8"))))
+
+    assert rows[1] == ["Benchy", "'" + LINK, "-1.5"]
+
+
+def test_stats_csv_keeps_typed_text_as_text():
+    data = _service()._generate_csv_simple([["Failures by Reason", ""], ["+spaghetti", 3]])
+
+    rows = list(csv.reader(io.StringIO(data.decode("utf-8"))))
+
+    assert rows == [["Failures by Reason", ""], ["'+spaghetti", "3"]]
+
+
+def test_archive_xlsx_stores_typed_text_as_text():
+    data = _service()._generate_xlsx(["print_name", "notes", "cost"], [["Benchy", LINK, -1.5]], ["a", "b", "c"])
+
+    sheet = load_workbook(io.BytesIO(data)).active
+    assert sheet is not None
+
+    assert (sheet["B2"].value, sheet["B2"].data_type) == (LINK, "s")
+    assert sheet["C2"].value == -1.5
+
+
+def test_stats_xlsx_stores_typed_text_as_text():
+    data = _service()._generate_xlsx_simple([["Failures by Reason", ""], [LINK, 3]])
+
+    sheet = load_workbook(io.BytesIO(data)).active
+    assert sheet is not None
+
+    assert (sheet["A2"].value, sheet["A2"].data_type) == (LINK, "s")
+    assert sheet["B2"].value == 3

+ 175 - 0
backend/tests/unit/test_github_empty_repo_backup_3565.py

@@ -0,0 +1,175 @@
+"""A first Git backup to a GitHub repository with no commits (#3565).
+
+GitHub answers every Git Data call -- the branch lookup, but also blobs and
+trees -- with 409 "Git Repository is empty" until the repository has a commit.
+Bambuddy read the 409 on the branch lookup as a failure, and its blob/tree
+initial-commit path could not have started the repository either. The first
+commit now goes through the Contents API, and the rest follows as usual.
+"""
+
+import base64
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+
+from backend.app.services.git_providers.github import GitHubBackend
+from backend.tests.unit.test_git_providers import _blob_sha, _make_mock_response
+
+pytestmark = pytest.mark.unit
+
+REPO_URL = "https://github.com/owner/repo"
+EMPTY = {"message": "Git Repository is empty.", "status": "409"}
+FILES = {"settings.json": {"a": 1}, "printers.json": [{"name": "X1C"}]}
+
+
+def _empty_409():
+    return _make_mock_response(409, EMPTY)
+
+
+def _client(*, get, put=(), post=(), patch=None):
+    client = AsyncMock()
+    client.get = AsyncMock(side_effect=list(get))
+    client.put = AsyncMock(side_effect=list(put))
+    client.post = AsyncMock(side_effect=list(post))
+    client.patch = AsyncMock(return_value=patch or _make_mock_response(200, {}))
+    return client
+
+
+def _branch_with(*paths):
+    """The three reads push_files makes on a branch holding these backup files."""
+    tree = [{"type": "blob", "path": p, "sha": _blob_sha(FILES[p])} for p in paths]
+    return [
+        _make_mock_response(200, {"object": {"sha": "c0"}}),
+        _make_mock_response(200, {"tree": {"sha": "t0"}}),
+        _make_mock_response(200, {"tree": tree}),
+    ]
+
+
+def _seeded(sha="c0"):
+    return _make_mock_response(201, {"commit": {"sha": sha}, "content": {}})
+
+
+async def _push(client, files=FILES, branch="main"):
+    return await GitHubBackend().push_files(REPO_URL, "ghp_token", branch, files, client)
+
+
+class TestTheFirstBackup:
+    @pytest.mark.asyncio
+    async def test_the_reported_case_creates_the_first_commit_and_pushes_the_rest(self):
+        client = _client(
+            get=[_empty_409(), *_branch_with("settings.json")],
+            put=[_seeded()],
+            post=[
+                _make_mock_response(201, {"sha": "blob-printers"}),
+                _make_mock_response(201, {"sha": "t1"}),
+                _make_mock_response(201, {"sha": "c1"}),
+            ],
+        )
+
+        result = await _push(client)
+
+        assert result["status"] == "success"
+        assert result["files_changed"] == 2
+        assert result["commit_sha"] == "c1"
+        # The first commit through the Contents API, on the configured branch,
+        # with the file exactly as push_files writes it, so it is not re-sent.
+        url = client.put.await_args.args[0]
+        body = client.put.await_args.kwargs["json"]
+        assert url == "https://api.github.com/repos/owner/repo/contents/settings.json"
+        assert body["branch"] == "main"
+        assert base64.b64decode(body["content"]) == json.dumps(FILES["settings.json"], indent=2).encode()
+        # The second file is the only blob: the seeded one was recognised.
+        blob_posts = [c for c in client.post.await_args_list if c.args[0].endswith("/git/blobs")]
+        assert len(blob_posts) == 1
+
+    @pytest.mark.asyncio
+    async def test_a_one_file_backup_is_done_by_the_first_commit(self):
+        client = _client(get=[_empty_409()], put=[_seeded()])
+
+        result = await _push(client, files={"settings.json": FILES["settings.json"]})
+
+        assert result == {
+            "status": "success",
+            "message": "Initial backup created - 1 files",
+            "commit_sha": "c0",
+            "files_changed": 1,
+        }
+        client.post.assert_not_awaited()
+
+    @pytest.mark.asyncio
+    async def test_a_backup_branch_github_will_not_create_branches_off_the_default_one(self):
+        files = {"settings.json": FILES["settings.json"]}
+        client = _client(
+            get=[
+                _empty_409(),
+                # After the commit on the default branch: backup branch missing,
+                # so it is branched off the default one and pushed to again.
+                _make_mock_response(404, {}),
+                _make_mock_response(200, {"default_branch": "main"}),
+                _make_mock_response(200, {"object": {"sha": "c0"}}),
+                *_branch_with("settings.json"),
+            ],
+            put=[_make_mock_response(404, {"message": "Branch bambuddy-backup not found"}), _seeded()],
+            post=[_make_mock_response(201, {"ref": "refs/heads/bambuddy-backup"})],
+        )
+
+        result = await _push(client, files=files, branch="bambuddy-backup")
+
+        assert result["status"] == "success"
+        first, second = client.put.await_args_list
+        assert first.kwargs["json"]["branch"] == "bambuddy-backup"
+        assert "branch" not in second.kwargs["json"]
+        assert client.post.await_args.kwargs["json"] == {"ref": "refs/heads/bambuddy-backup", "sha": "c0"}
+
+    @pytest.mark.asyncio
+    async def test_an_empty_default_branch_behind_a_missing_backup_branch_is_seeded_too(self):
+        client = _client(
+            get=[
+                _make_mock_response(404, {}),
+                _make_mock_response(200, {"default_branch": "main"}),
+                _empty_409(),
+            ],
+            put=[_seeded()],
+        )
+
+        result = await _push(client, files={"settings.json": FILES["settings.json"]}, branch="bambuddy-backup")
+
+        assert result["status"] == "success"
+        client.post.assert_not_awaited()
+
+
+class TestWhatStaysAFailure:
+    @pytest.mark.asyncio
+    async def test_another_409_is_reported_not_seeded(self):
+        client = _client(get=[_make_mock_response(409, {"message": "Conflict"}, text="Conflict")])
+
+        result = await _push(client)
+
+        assert result["status"] == "failed"
+        assert "Failed to get branch ref (HTTP 409)" in result["message"]
+        client.put.assert_not_awaited()
+
+    @pytest.mark.asyncio
+    async def test_a_refused_first_commit_says_why(self):
+        client = _client(
+            get=[_empty_409()],
+            put=[_make_mock_response(403, {}, text="Resource not accessible by personal access token")],
+        )
+
+        result = await _push(client)
+
+        assert result["status"] == "failed"
+        assert "HTTP 403" in result["message"]
+        assert "personal access token" in result["message"]
+
+    @pytest.mark.asyncio
+    async def test_a_repository_still_empty_after_the_first_commit_is_not_seeded_twice(self):
+        """GitHub lagging behind its own write: the next backup retries."""
+        client = _client(get=[_empty_409(), _empty_409()], put=[_seeded()])
+
+        result = await _push(client)
+
+        assert result["status"] == "failed"
+        assert "replication lag" in result["message"]
+        assert client.put.await_count == 1

+ 45 - 0
backend/tests/unit/test_maintenance_log_actor.py

@@ -0,0 +1,45 @@
+"""Who a maintenance reset is logged as (#3557).
+
+The user, an API key's owner, or, for a legacy key without an owner, the key
+by its name. Nobody when authentication is off.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from backend.app.api.routes.maintenance import _actor_identity
+from backend.app.core.auth import ApiKeyActor
+
+
+def _key_actor(name: str, owner: SimpleNamespace | None) -> ApiKeyActor:
+    actor = ApiKeyActor.__new__(ApiKeyActor)
+    actor.api_key = SimpleNamespace(name=name)
+    actor.owner = owner
+    actor.id = owner.id if owner else None
+    actor.username = owner.username if owner else None
+    return actor
+
+
+def test_auth_off_logs_nobody():
+    assert _actor_identity(None) == (None, None)
+
+
+def test_a_user_is_logged_by_id_and_name():
+    assert _actor_identity(SimpleNamespace(id=7, username="mechanic")) == (7, "mechanic")
+
+
+def test_a_key_is_logged_as_its_owner():
+    owner = SimpleNamespace(id=3, username="farm-admin")
+
+    assert _actor_identity(_key_actor("Home Assistant", owner)) == (3, "farm-admin")
+
+
+def test_a_legacy_key_without_an_owner_is_logged_by_its_name():
+    assert _actor_identity(_key_actor("Home Assistant", None)) == (None, "API key: Home Assistant")
+
+
+def test_a_long_key_name_fits_the_column():
+    _, name = _actor_identity(_key_actor("x" * 200, None))
+
+    assert name is not None and len(name) == 100

+ 125 - 0
backend/tests/unit/test_maintenance_log_backfill.py

@@ -0,0 +1,125 @@
+"""Resets from before the maintenance log are copied into it once, on upgrade.
+
+They are only in maintenance_history, which goes with its printer task. The
+copy takes the printer's and the task's names as they are now; who reset them
+was never recorded. A second start copies nothing again, not even entries
+deleted from the log since.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from backend.app.core.database import _backfill_maintenance_log
+from backend.app.models.maintenance import MaintenanceLogEntry
+
+pytestmark = pytest.mark.asyncio
+
+
+@pytest.fixture
+async def engine():
+    """In-memory SQLite with the tables the copy reads, as an upgrade finds them,
+    and the log as create_all builds it from the model."""
+    engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
+    async with engine.begin() as conn:
+        for ddl in (
+            'CREATE TABLE settings (id INTEGER PRIMARY KEY, "key" VARCHAR(100) NOT NULL UNIQUE, value TEXT)',
+            "CREATE TABLE printers (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL)",
+            "CREATE TABLE maintenance_types (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL)",
+            "CREATE TABLE printer_maintenance (id INTEGER PRIMARY KEY, printer_id INTEGER NOT NULL, "
+            "maintenance_type_id INTEGER NOT NULL)",
+            "CREATE TABLE maintenance_history (id INTEGER PRIMARY KEY, printer_maintenance_id INTEGER NOT NULL, "
+            "performed_at DATETIME, hours_at_maintenance FLOAT, notes TEXT)",
+        ):
+            await conn.execute(text(ddl))
+        await conn.run_sync(lambda sync: MaintenanceLogEntry.__table__.create(sync))
+        await conn.execute(text("INSERT INTO printers (id, name) VALUES (1, 'X1C')"))
+        await conn.execute(text("INSERT INTO maintenance_types (id, name) VALUES (7, 'Clean Nozzle')"))
+        await conn.execute(
+            text("INSERT INTO printer_maintenance (id, printer_id, maintenance_type_id) VALUES (3, 1, 7)")
+        )
+        for history_id, at, hours, notes in (
+            (10, datetime(2026, 1, 2, 3, 4), 12.5, "old note"),
+            (11, datetime(2026, 2, 1), 40.0, None),
+        ):
+            await conn.execute(
+                text(
+                    "INSERT INTO maintenance_history (id, printer_maintenance_id, performed_at, hours_at_maintenance, notes) "
+                    "VALUES (:id, 3, :at, :hours, :notes)"
+                ),
+                {"id": history_id, "at": at, "hours": hours, "notes": notes},
+            )
+    try:
+        yield engine
+    finally:
+        await engine.dispose()
+
+
+async def _entries(conn) -> list[tuple]:
+    result = await conn.execute(
+        text(
+            "SELECT history_id, printer_id, printer_name, maintenance_type_id, maintenance_type_name, "
+            "hours_at_maintenance, notes, performed_by_id, performed_by_username "
+            "FROM maintenance_log_entries ORDER BY history_id"
+        )
+    )
+    return [tuple(row) for row in result]
+
+
+async def test_old_resets_are_copied_with_their_printer_and_task(engine):
+    async with engine.begin() as conn:
+        await _backfill_maintenance_log(conn)
+        entries = await _entries(conn)
+
+    assert entries == [
+        (10, 1, "X1C", 7, "Clean Nozzle", 12.5, "old note", None, None),
+        (11, 1, "X1C", 7, "Clean Nozzle", 40.0, None, None, None),
+    ]
+
+
+async def test_the_copy_keeps_when_they_were_done(engine):
+    async with engine.begin() as conn:
+        await _backfill_maintenance_log(conn)
+        performed = (
+            await conn.execute(text("SELECT performed_at FROM maintenance_log_entries WHERE history_id = 10"))
+        ).scalar_one()
+
+    assert str(performed).startswith("2026-01-02 03:04")
+
+
+async def test_a_second_start_copies_nothing_again(engine):
+    async with engine.begin() as conn:
+        await _backfill_maintenance_log(conn)
+        await _backfill_maintenance_log(conn)
+        entries = await _entries(conn)
+
+    assert [e[0] for e in entries] == [10, 11]
+
+
+async def test_resets_already_logged_are_not_copied(engine):
+    async with engine.begin() as conn:
+        await conn.execute(
+            text(
+                "INSERT INTO maintenance_log_entries (printer_id, printer_name, maintenance_type_id, "
+                "maintenance_type_name, hours_at_maintenance, performed_by_username, history_id) "
+                "VALUES (1, 'X1C', 7, 'Clean Nozzle', 12.5, 'mechanic', 10)"
+            )
+        )
+        await _backfill_maintenance_log(conn)
+        entries = await _entries(conn)
+
+    assert [(e[0], e[-1]) for e in entries] == [(10, "mechanic"), (11, None)]
+
+
+async def test_entries_deleted_from_the_log_stay_deleted(engine):
+    async with engine.begin() as conn:
+        await _backfill_maintenance_log(conn)
+        await conn.execute(text("DELETE FROM maintenance_log_entries WHERE history_id = 10"))
+        await _backfill_maintenance_log(conn)
+        entries = await _entries(conn)
+
+    assert [e[0] for e in entries] == [11]

Some files were not shown because too many files changed in this diff