Просмотр исходного кода

Groups: limit which filaments a group may print with (#3522) (#3567)

Pau Lleonart Calvo 3 дней назад
Родитель
Сommit
33ecb151c6
77 измененных файлов с 4585 добавлено и 109 удалено
  1. 2 0
      CHANGELOG.md
  2. 6 0
      backend/app/api/routes/auth.py
  3. 45 0
      backend/app/api/routes/groups.py
  4. 29 0
      backend/app/api/routes/print_queue.py
  5. 15 0
      backend/app/api/routes/users.py
  6. 17 0
      backend/app/core/database.py
  7. 281 0
      backend/app/core/filament_scope.py
  8. 10 3
      backend/app/models/group.py
  9. 12 0
      backend/app/schemas/auth.py
  10. 23 1
      backend/app/schemas/group.py
  11. 19 11
      backend/app/services/bambu_mqtt.py
  12. 558 39
      backend/app/services/print_scheduler.py
  13. 43 0
      backend/app/utils/tray_ids.py
  14. 95 0
      backend/tests/integration/test_auth_me_filament_policies_3522.py
  15. 115 0
      backend/tests/integration/test_group_filament_rules_3522.py
  16. 267 0
      backend/tests/integration/test_queue_filament_scope_3522.py
  17. 1 0
      backend/tests/unit/test_ams_mapping_per_printer_2799.py
  18. 1 0
      backend/tests/unit/test_ams_mapping_unresolved_2589.py
  19. 2 2
      backend/tests/unit/test_expected_print_rollback.py
  20. 1 0
      backend/tests/unit/test_external_mapping_on_ams_printer_3239.py
  21. 1 1
      backend/tests/unit/test_failed_start_releases_printer.py
  22. 271 0
      backend/tests/unit/test_filament_scope.py
  23. 1 0
      backend/tests/unit/test_force_color_pinned_3280.py
  24. 1 1
      backend/tests/unit/test_library_dispatch_reuses_archive.py
  25. 2 0
      backend/tests/unit/test_model_path_unmatched_filament.py
  26. 1 0
      backend/tests/unit/test_printer_job_force_color_3445.py
  27. 1 1
      backend/tests/unit/test_scheduler_backup_gate.py
  28. 1 0
      backend/tests/unit/test_scheduler_external_spool_nozzle_2771.py
  29. 367 0
      backend/tests/unit/test_scheduler_filament_hold_3522.py
  30. 670 0
      backend/tests/unit/test_scheduler_filament_scope_3522.py
  31. 1 0
      backend/tests/unit/test_scheduler_force_color_ams_fallback.py
  32. 73 0
      frontend/src/__tests__/components/FilamentAccessCard.test.tsx
  33. 109 0
      frontend/src/__tests__/components/FilamentMapping.test.tsx
  34. 1 0
      frontend/src/__tests__/components/FilamentMappingArchivePick.test.tsx
  35. 1 0
      frontend/src/__tests__/components/FilamentMappingColorMismatch.test.tsx
  36. 1 0
      frontend/src/__tests__/components/FilamentMappingRackPicker.test.tsx
  37. 1 0
      frontend/src/__tests__/components/FilamentMappingSlotCost.test.tsx
  38. 53 1
      frontend/src/__tests__/components/FilamentOverride.test.tsx
  39. 152 0
      frontend/src/__tests__/components/PrintModal.test.tsx
  40. 54 0
      frontend/src/__tests__/components/PrintModalNarrowScreen.test.tsx
  41. 12 0
      frontend/src/__tests__/components/PrinterSelector.test.ts
  42. 40 0
      frontend/src/__tests__/components/SlotPicker.test.tsx
  43. 64 1
      frontend/src/__tests__/hooks/useFilamentMapping.test.ts
  44. 55 2
      frontend/src/__tests__/hooks/useMultiPrinterFilamentMapping.test.tsx
  45. 72 0
      frontend/src/__tests__/pages/GroupEditPage.test.tsx
  46. 139 0
      frontend/src/__tests__/utils/filamentScope.test.ts
  47. 17 0
      frontend/src/__tests__/utils/filamentScopeCases.json
  48. 31 0
      frontend/src/api/client.ts
  49. 193 0
      frontend/src/components/FilamentAccessCard.tsx
  50. 40 4
      frontend/src/components/PrintModal/FilamentMapping.tsx
  51. 25 14
      frontend/src/components/PrintModal/FilamentOverride.tsx
  52. 2 1
      frontend/src/components/PrintModal/PrinterSelector.tsx
  53. 13 2
      frontend/src/components/PrintModal/SlotPicker.tsx
  54. 83 4
      frontend/src/components/PrintModal/index.tsx
  55. 4 0
      frontend/src/components/PrintModal/types.ts
  56. 22 8
      frontend/src/hooks/useFilamentMapping.ts
  57. 9 0
      frontend/src/hooks/useFilamentPolicies.ts
  58. 18 10
      frontend/src/hooks/useMultiPrinterFilamentMapping.ts
  59. 19 0
      frontend/src/i18n/locales/de.ts
  60. 19 0
      frontend/src/i18n/locales/en.ts
  61. 19 0
      frontend/src/i18n/locales/es.ts
  62. 19 0
      frontend/src/i18n/locales/fr.ts
  63. 19 0
      frontend/src/i18n/locales/it.ts
  64. 19 0
      frontend/src/i18n/locales/ja.ts
  65. 19 0
      frontend/src/i18n/locales/ko.ts
  66. 19 0
      frontend/src/i18n/locales/nl.ts
  67. 19 0
      frontend/src/i18n/locales/pl.ts
  68. 19 0
      frontend/src/i18n/locales/pt-BR.ts
  69. 19 0
      frontend/src/i18n/locales/ru.ts
  70. 19 0
      frontend/src/i18n/locales/sv.ts
  71. 19 0
      frontend/src/i18n/locales/tr.ts
  72. 19 0
      frontend/src/i18n/locales/uk.ts
  73. 19 0
      frontend/src/i18n/locales/zh-CN.ts
  74. 19 0
      frontend/src/i18n/locales/zh-TW.ts
  75. 34 1
      frontend/src/pages/GroupEditPage.tsx
  76. 3 2
      frontend/src/utils/amsHelpers.ts
  77. 101 0
      frontend/src/utils/filamentScope.ts

+ 2 - 0
CHANGELOG.md

@@ -22,6 +22,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which notifications get the camera photo (#2877, requested by @HappyPuppy21)** — **Attach Photo** on a notification provider sent the snapshot with every event that has one, so a channel that should show the finished print also got a photo at the start and at 25, 50 and 75 percent. With Attach Photo on, the provider's settings now list the photo events it sends, and unticking one sends that event without the photo. Every event keeps its photo until it is unticked, and the provider card names the events that go without one.
 - **BIQU Panda Breath on the printer card (#1466, requested by @embed-3d)** — A Panda Breath chamber heater with firmware 1.0.4 or later can connect to an MQTT broker, and Bambuddy now follows it there. Under **Settings > Network > MQTT Publishing**, turn on **BIQU Panda Breath**; it uses the broker set there, and lists each Panda Breath that reports with the printer it is bound to. The printer card of that printer gets a **Panda Breath** tile with the chamber temperature it reads and its target; clicking it turns the heater on or off, picks Auto, Always on or Drying, and sets a target from 0 to 60 °C. The tile stays on the card while the printer is switched off, since the heater keeps running. The device is matched by the printer serial number it reports, so it needs to be bound to its printer in its own web interface. Changes need the printer control permission for that printer. Not tested on a real device yet. Wiki updated.
 - **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.
+- **Limit which filaments a group may print with (#3522, requested and contributed by @paulleonartcalvo in #3567)** — A group can now be limited to some filaments, as it can to some printers (#1727). In the group editor, **Limit filaments** under **Filament access** turns it on, with rules that either **Block these filaments** or **Allow only these filaments**. A rule names a material type (PETG, matched exactly, so PETG-CF is a different one) or a slicer filament ID (GFG03 for Bambu PETG Matte, the ID an AMS slot reports). A member may use a filament if any of their limited groups allows it; a user in no limited group, an admin, and every user with auth off are not limited. Queueing a file that needs a filament the user may not use is refused with the filament named. The print dialog says so before submitting, greys out the slots the group can't use and never picks one automatically. The queue never sends a job to a slot holding such a filament: it picks another slot, or holds the job with the reason on its row and starts it once the rules or the loaded spools allow it. That covers jobs from every source, including webhooks, pipelines and virtual printers, and "Print anyway" does not bypass it. Wiki updated.
 ### 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.
@@ -33,6 +34,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **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.
+- **The "job assigned" notification is sent once the job can start on its printer (#3522)** — An "Any model" job was announced as assigned the moment the queue picked a printer for it, before the queue had mapped its filaments to that printer's slots. The notification now follows that step. For every user, also one without filament rules, a job that fails right after the assignment because its filaments can't be mapped on that printer is no longer announced as assigned first; it sends the failure only. A job held by its creator's filament rules is given back to the pool without the notification, so it is not sent again on every pass of the queue.
 
 ### Fixed
 - **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.

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

@@ -42,6 +42,7 @@ from backend.app.core.auth import (
     token_outlived_its_session,
 )
 from backend.app.core.database import async_session, get_db
+from backend.app.core.filament_scope import filament_policies_for
 from backend.app.core.oidc_env import env_bool
 from backend.app.models.api_key import APIKey
 from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent, EventType, TokenType
@@ -93,6 +94,7 @@ def _user_to_response(user: User) -> UserResponse:
         auth_source=getattr(user, "auth_source", "local"),
         groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
         permissions=sorted(user.get_permissions()),
+        filament_policies=filament_policies_for(user),
         created_at=user.created_at.isoformat(),
     )
 
@@ -138,6 +140,10 @@ async def _api_key_to_user_response(db: AsyncSession, api_key) -> UserResponse:
         # imply capabilities the key does not inherit.
         groups=[],
         permissions=apikey_effective_permissions(api_key, owner),
+        # The owner's: the scheduler and the queue judge a key's jobs by the
+        # owner's filament rules (#3522). A legacy ownerless key's jobs have no
+        # creator, so they are unrestricted, as None says.
+        filament_policies=filament_policies_for(owner) if owner else None,
         created_at=api_key.created_at.isoformat(),
     )
 

+ 45 - 0
backend/app/api/routes/groups.py

@@ -7,6 +7,7 @@ from sqlalchemy.orm import selectinload
 
 from backend.app.core.auth import RequireAdminIfAuthEnabled, RequirePermissionIfAuthEnabled
 from backend.app.core.database import get_db
+from backend.app.core.filament_scope import clean_rules
 from backend.app.core.permissions import (
     ALL_PERMISSIONS,
     PERMISSION_CATEGORIES,
@@ -142,6 +143,40 @@ async def _apply_printer_scope(
     return changed
 
 
+def _apply_filament_scope(
+    group: Group,
+    restrict_filaments: bool | None,
+    filament_rule_mode: str | None,
+    filament_rules: list | None,
+) -> None:
+    """Store a group's filament scope (#3522).
+
+    The Administrators group can't be restricted: admins may use every
+    filament regardless, so the setting would only mislead.
+    """
+    if restrict_filaments is not None and restrict_filaments != bool(group.restrict_filaments):
+        if restrict_filaments and group.name == ADMIN_GROUP_NAME:
+            raise HTTPException(
+                status_code=status.HTTP_400_BAD_REQUEST,
+                detail="Administrators can always use every filament",
+            )
+        group.restrict_filaments = restrict_filaments
+    if filament_rule_mode is not None and filament_rule_mode != (group.filament_rule_mode or "block"):
+        group.filament_rule_mode = filament_rule_mode
+    if filament_rules is not None:
+        cleaned = clean_rules(filament_rules)
+        if cleaned != (group.filament_rules or []):
+            group.filament_rules = cleaned
+
+
+def _filament_fields(group: Group) -> dict:
+    return {
+        "restrict_filaments": bool(group.restrict_filaments),
+        "filament_rule_mode": group.filament_rule_mode or "block",
+        "filament_rules": clean_rules(group.filament_rules),
+    }
+
+
 def _group_response(group: Group, printer_ids: list[int], locations: list[str], user_count: int) -> GroupResponse:
     return GroupResponse(
         id=group.id,
@@ -152,6 +187,7 @@ def _group_response(group: Group, printer_ids: list[int], locations: list[str],
         restrict_printers=bool(group.restrict_printers),
         printer_ids=printer_ids,
         locations=locations,
+        **_filament_fields(group),
         user_count=user_count,
         created_at=group.created_at,
         updated_at=group.updated_at,
@@ -227,10 +263,15 @@ async def create_group(
         permissions=group_data.permissions,
         is_system=False,  # User-created groups are not system groups
         restrict_printers=False,
+        restrict_filaments=False,
+        filament_rule_mode="block",
     )
     db.add(group)
     await db.flush()
     await _apply_printer_scope(db, group, group_data.restrict_printers, group_data.printer_ids, group_data.locations)
+    _apply_filament_scope(
+        group, group_data.restrict_filaments, group_data.filament_rule_mode, group_data.filament_rules
+    )
     await db.commit()
     await db.refresh(group)
 
@@ -262,6 +303,7 @@ async def get_group(
         restrict_printers=bool(group.restrict_printers),
         printer_ids=await group_printer_ids(db, group.id),
         locations=await group_location_names(db, group.id),
+        **_filament_fields(group),
         user_count=len(group.users),
         created_at=group.created_at,
         updated_at=group.updated_at,
@@ -328,6 +370,9 @@ async def update_group(
     scope_changed = await _apply_printer_scope(
         db, group, group_data.restrict_printers, group_data.printer_ids, group_data.locations
     )
+    _apply_filament_scope(
+        group, group_data.restrict_filaments, group_data.filament_rule_mode, group_data.filament_rules
+    )
 
     await db.commit()
     await db.refresh(group)

+ 29 - 0
backend/app/api/routes/print_queue.py

@@ -1,5 +1,6 @@
 """API routes for print queue management."""
 
+import asyncio
 import json
 import logging
 import re
@@ -29,6 +30,11 @@ from backend.app.core.auth import (
 )
 from backend.app.core.config import settings
 from backend.app.core.database import get_db
+from backend.app.core.filament_scope import (
+    ensure_requirements_allowed,
+    judged_requirements,
+    resolve_user_id_filament_scope,
+)
 from backend.app.core.permissions import Permission
 from backend.app.core.printer_scope import PrinterScope, ensure_model_target_allowed
 from backend.app.core.websocket import ws_manager
@@ -1324,6 +1330,29 @@ async def add_to_queue(
     elif archive is not None:
         ensure_sliced(file_path, archive.filename)
     plate_id = data.plate_id or printed_plate_of_multi_plate_file(file_path)
+
+    # Filament permissions (#3522): refuse now, naming the filament, rather than
+    # queue a job the scheduler would only hold. Read before any lock or write,
+    # and for each file of a cross-model job, with the overrides that job keeps
+    # applied as the scheduler applies them (`judged_requirements`), so both
+    # answer alike. The scheduler checks again at dispatch, which also covers
+    # every other way a job is created; a file that is missing or unreadable
+    # here is left to it too.
+    filament_scope = await resolve_user_id_filament_scope(db, actor.id if actor else None)
+    if not filament_scope.is_unrestricted:
+        from backend.app.services.filament_requirements import extract_filament_requirements
+
+        kept_overrides = data.filament_overrides if target_model_norm or data.printer_id is not None else None
+        sources = [(file_path, plate_id, kept_overrides)] if file_path is not None else []
+        sources += [
+            (library_file_disk_path(variant_file), spec.plate_id, spec.filament_overrides)
+            for spec, variant_file, _ in variant_specs
+        ]
+        for source_path, source_plate, overrides in sources:
+            if source_path.exists():
+                requirements = await asyncio.to_thread(extract_filament_requirements, source_path, source_plate)
+                ensure_requirements_allowed(filament_scope, judged_requirements(requirements, overrides))
+
     if target_model_norm:
         if file_path and file_path.exists():
             filament_types = _extract_filament_types_from_3mf(file_path, plate_id)

+ 15 - 0
backend/app/api/routes/users.py

@@ -22,6 +22,7 @@ from backend.app.core.auth import (
     verify_password,
 )
 from backend.app.core.database import get_db
+from backend.app.core.filament_scope import filament_policies_for, resolve_user_filament_scope
 from backend.app.core.permissions import Permission
 from backend.app.core.websocket import ws_manager
 from backend.app.models.api_key import APIKey
@@ -74,6 +75,7 @@ def _user_to_response(user: User) -> UserResponse:
         auth_source=getattr(user, "auth_source", "local"),
         groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
         permissions=sorted(user.get_permissions()),
+        filament_policies=filament_policies_for(user),
         created_at=user.created_at.isoformat(),
     )
 
@@ -664,6 +666,19 @@ async def delete_user(
                 )
                 .values(manual_start=True)
             )
+        # Likewise for filaments (#3522), and for every pending job, pinned
+        # ones too: an ownerless job may print with any filament, so one held
+        # by this user's rules, or due to be, would otherwise go out on the
+        # next pass with the filament it was held from. Read off the user's
+        # groups, as the printer check above: a deactivated user's jobs are
+        # held because they are deactivated, not by a filament rule, and
+        # that hold is not this one's to keep.
+        if not resolve_user_filament_scope(user).is_unrestricted:
+            await db.execute(
+                update(PrintQueueItem)
+                .where(PrintQueueItem.created_by_id == user_id, PrintQueueItem.status == "pending")
+                .values(manual_start=True)
+            )
         await db.execute(update(PrintArchive).where(PrintArchive.created_by_id == user_id).values(created_by_id=None))
         await db.execute(
             update(PrintQueueItem).where(PrintQueueItem.created_by_id == user_id).values(created_by_id=None)

+ 17 - 0
backend/app/core/database.py

@@ -5992,6 +5992,21 @@ async def _run_migrations(conn):
             text("UPDATE groups SET restrict_printers = :off WHERE restrict_printers IS NULL"), {"off": False}
         )
 
+    # Migration: filament-scoped groups (#3522). Off by default, so no group
+    # narrows anyone's filaments on upgrade. The backfills cover a table
+    # create_all() already gave the columns, where the ALTER is swallowed.
+    await _safe_execute(conn, "ALTER TABLE groups ADD COLUMN restrict_filaments BOOLEAN DEFAULT FALSE")
+    async with conn.begin_nested():
+        await conn.execute(
+            text("UPDATE groups SET restrict_filaments = :off WHERE restrict_filaments IS NULL"), {"off": False}
+        )
+    await _safe_execute(conn, "ALTER TABLE groups ADD COLUMN filament_rule_mode VARCHAR(10) DEFAULT 'block'")
+    async with conn.begin_nested():
+        await conn.execute(
+            text("UPDATE groups SET filament_rule_mode = :mode WHERE filament_rule_mode IS NULL"), {"mode": "block"}
+        )
+    await _safe_execute(conn, "ALTER TABLE groups ADD COLUMN filament_rules JSON")
+
     # Migration: camera-stream and websocket tokens record who minted them, so
     # they carry that caller's printer scope (#1727). Camera tokens minted
     # before this have no principal at all (username NULL; every new one sets
@@ -6400,6 +6415,8 @@ _PG_COLUMNS_SET_FROM_MODEL = (
     ("api_keys", "can_update_energy_cost"),
     ("github_backup_config", "allow_insecure_http"),
     ("github_backup_config", "provider"),
+    ("groups", "filament_rule_mode"),
+    ("groups", "restrict_filaments"),
     ("groups", "restrict_printers"),
     ("library_files", "variant_position"),
     ("library_folders", "shared"),

+ 281 - 0
backend/app/core/filament_scope.py

@@ -0,0 +1,281 @@
+"""Which filaments a caller may print with (#3522).
+
+Permissions answer *what* a caller may do and a printer scope *on which
+printers* (#1727); a filament scope answers *with which filaments*. It is
+checked when a job is queued (the file's filaments) and again by the scheduler
+before dispatch (the file's filaments and the AMS trays it maps them to), so a
+job created any other way -- webhook, pipeline, batch, virtual printer -- is
+held to it too.
+
+How a scope is derived, as for printers:
+
+* Auth disabled, no user, or an admin: every filament.
+* A user: each of their groups with ``restrict_filaments`` set is a policy, and
+  a filament any of those policies allows is allowed. A user in no such group
+  may use every filament, so installs that never configure this are unchanged.
+* A deleted or deactivated user: no policies, so nothing identifiable.
+
+A policy is an allow list or a block list (``filament_rule_mode``). A rule
+matches a material type ("PETG", case-insensitive, by name: "PETG" is not
+"PETG-CF", but the materials the tray matcher treats as one, such as PA-CF,
+PA12-CF and PAHT-CF, count as one here too) or a slicer filament id ("GFG03":
+the ``tray_info_idx`` an AMS tray reports and a 3MF records). A
+filament with neither a type nor an id can't be judged and is allowed: the
+scheduler only blocks dispatch on a positive finding.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass
+from typing import Literal
+
+from fastapi import HTTPException, status
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from backend.app.schemas.auth import FilamentPolicyBrief
+from backend.app.schemas.group import FilamentRuleSchema
+from backend.app.utils.filament_types import canonical_filament_type
+
+RuleMatch = Literal["material", "filament_id"]
+RuleMode = Literal["allow", "block"]
+RULE_MATCHES: tuple[str, ...] = ("material", "filament_id")
+RULE_MODES: tuple[str, ...] = ("allow", "block")
+
+
+def _norm(value: object) -> str:
+    return str(value or "").strip().upper()
+
+
+@dataclass(frozen=True)
+class FilamentRule:
+    match: RuleMatch
+    value: str
+
+    def matches(self, filament_type: str | None, filament_id: str | None) -> bool:
+        wanted = _norm(self.value)
+        if not wanted:
+            return False
+        if self.match == "material":
+            # The tray matcher treats some materials as one (PA-CF, PA12-CF
+            # and PAHT-CF, ``canonical_filament_type``); a rule naming one of
+            # them names them all, or the matcher would map a job onto a
+            # spool the rule meant to keep it from, or hold it off one the
+            # rule allows.
+            return canonical_filament_type(_norm(filament_type)) == canonical_filament_type(wanted)
+        return _norm(filament_id) == wanted
+
+
+@dataclass(frozen=True)
+class GroupFilamentPolicy:
+    group_name: str
+    mode: RuleMode
+    rules: tuple[FilamentRule, ...]
+
+    def allows(self, filament_type: str | None, filament_id: str | None) -> bool:
+        hit = any(rule.matches(filament_type, filament_id) for rule in self.rules)
+        return hit if self.mode == "allow" else not hit
+
+
+@dataclass(frozen=True)
+class FilamentScope:
+    """The filaments a caller may use. ``policies=None`` means all of them."""
+
+    policies: tuple[GroupFilamentPolicy, ...] | None = None
+
+    @property
+    def is_unrestricted(self) -> bool:
+        return self.policies is None
+
+    def allows(self, filament_type: str | None, filament_id: str | None) -> bool:
+        if self.policies is None:
+            return True
+        if not _norm(filament_type) and not _norm(filament_id):
+            return True
+        return any(policy.allows(filament_type, filament_id) for policy in self.policies)
+
+    def blocked_requirements(self, requirements: Iterable[Mapping]) -> list[Mapping]:
+        """The file's filament slots (``extract_filament_requirements`` entries) not allowed."""
+        return [r for r in requirements if not self.allows(r.get("type"), r.get("tray_info_idx"))]
+
+    def blocked_tray_ids(self, loaded: Iterable[Mapping]) -> set[int]:
+        """Global tray ids (``_build_loaded_filaments`` entries) holding a filament not allowed."""
+        return {
+            int(tray["global_tray_id"])
+            for tray in loaded
+            if not self.allows(tray.get("type"), tray.get("tray_info_idx"))
+        }
+
+
+ALL_FILAMENTS = FilamentScope()
+NO_FILAMENTS = FilamentScope(())
+
+
+def clean_rules(raw: Iterable[Mapping | object] | None) -> list[dict]:
+    """Rules as stored: known kinds only, values stripped, materials upper-cased, no repeats."""
+    cleaned: list[dict] = []
+    seen: set[tuple[str, str]] = set()
+    for entry in raw or ():
+        if isinstance(entry, Mapping):
+            match, value = entry.get("match"), entry.get("value")
+        else:
+            match, value = getattr(entry, "match", None), getattr(entry, "value", None)
+        if match not in RULE_MATCHES or not isinstance(value, str) or not value.strip():
+            continue
+        value = value.strip().upper() if match == "material" else value.strip()
+        key = (match, _norm(value))
+        if key in seen:
+            continue
+        seen.add(key)
+        cleaned.append({"match": match, "value": value})
+    return cleaned
+
+
+def policy_for_group(group) -> GroupFilamentPolicy:
+    mode = group.filament_rule_mode if group.filament_rule_mode in RULE_MODES else "block"
+    rules = tuple(FilamentRule(r["match"], r["value"]) for r in clean_rules(group.filament_rules))
+    return GroupFilamentPolicy(group.name, mode, rules)
+
+
+def resolve_user_filament_scope(user) -> FilamentScope:
+    """Scope of a loaded ``User`` (``groups`` must already be loaded)."""
+    if user.is_admin:
+        return ALL_FILAMENTS
+    restricted = [g for g in user.groups if g.restrict_filaments]
+    if not restricted:
+        return ALL_FILAMENTS
+    return FilamentScope(tuple(policy_for_group(g) for g in restricted))
+
+
+def filament_policies_for(user) -> list[FilamentPolicyBrief] | None:
+    """The user's filament rules for the print dialog; None when unrestricted.
+
+    Every ``UserResponse`` builder fills ``filament_policies`` from this:
+    None there means "may print with every filament", so leaving it out for a
+    restricted user would say the wrong thing. ``user.groups`` must be loaded.
+    """
+    scope = resolve_user_filament_scope(user)
+    if scope.policies is None:
+        return None
+    return [
+        FilamentPolicyBrief(
+            group=policy.group_name,
+            mode=policy.mode,
+            rules=[FilamentRuleSchema(match=rule.match, value=rule.value) for rule in policy.rules],
+        )
+        for policy in scope.policies
+    ]
+
+
+async def resolve_user_id_filament_scope(db: AsyncSession, user_id: int | None) -> FilamentScope:
+    """Scope of the user with ``user_id``, as the scheduler and the queue routes read it."""
+    from sqlalchemy.orm import selectinload
+
+    from backend.app.core.auth import is_auth_enabled
+    from backend.app.models.user import User
+
+    if user_id is None or not await is_auth_enabled(db):
+        return ALL_FILAMENTS
+    result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
+    user = result.scalar_one_or_none()
+    if user is None or not user.is_active:
+        return NO_FILAMENTS
+    return resolve_user_filament_scope(user)
+
+
+def describe_filament(entry: Mapping) -> str:
+    """Name a filament for messages: "PETG (GFG03)", "PETG" or "GFG03"."""
+    kind = str(entry.get("type") or "").strip()
+    ident = str(entry.get("tray_info_idx") or "").strip()
+    if kind and ident:
+        return f"{kind} ({ident})"
+    return kind or ident
+
+
+def describe_filaments(entries: Iterable[Mapping]) -> str:
+    """Each filament in ``entries`` named once, sorted: "PETG (GFG03), PLA"."""
+    return ", ".join(sorted({describe_filament(e) for e in entries}))
+
+
+def blocked_message(entries: Iterable[Mapping]) -> str:
+    """What the queue route's 403 tells the caller about filaments their groups don't allow."""
+    return f"Your group can't print with: {describe_filaments(entries)}"
+
+
+# The scheduler's holds are read on the queue row, by an admin as well as by
+# the job's creator, so they name the creator's group in the third person. A
+# file finding and a spool finding are worded apart: the first waits for a
+# rule change or another file, the second also ends when the spool is swapped.
+_CREATOR_CANT = "the job creator's group can't print with"
+
+
+def file_hold_message(entries: Iterable[Mapping]) -> str:
+    """The scheduler's hold for a file that needs filaments its creator's groups don't allow."""
+    return f"This file needs a filament {_CREATOR_CANT}: {describe_filaments(entries)}"
+
+
+def spool_hold_message(entries: Iterable[Mapping]) -> str:
+    """The scheduler's hold for a job that would print from loaded spools its creator's groups don't allow."""
+    return f"It would print from a loaded spool {_CREATOR_CANT}: {describe_filaments(entries)}"
+
+
+def unlisted_file_hold_message(blocked: Iterable[Mapping]) -> str:
+    """The scheduler's hold for a file that lists no filaments, on a printer that could feed it a blocked spool."""
+    return (
+        f"This file doesn't list its filaments, and the printer has a loaded spool {_CREATOR_CANT}: "
+        f"{describe_filaments(blocked)}"
+    )
+
+
+def print_anyway_hold_message(unresolved: Iterable[Mapping], blocked: Iterable[Mapping]) -> str:
+    """The scheduler's hold for "Print anyway" leaving slots for the printer to fill, next to blocked spools.
+
+    The unmatched filament is named apart: it isn't the one the group blocks,
+    and may well be allowed.
+    """
+    return (
+        f"Print anyway leaves {describe_filaments(unresolved)} without a slot, and the printer could pick "
+        f"a loaded spool {_CREATOR_CANT}: {describe_filaments(blocked)}"
+    )
+
+
+def judged_requirements(requirements: Iterable[Mapping], overrides: Iterable[object] | None) -> list[Mapping]:
+    """The file's filament slots as a scope judges them once the job's overrides apply (#3522).
+
+    One rule wherever a file is judged: ``POST /queue/``, the scheduler and
+    the print dialog (``judgedFilaments`` in ``filamentScope.ts``). An
+    overridden slot is judged as its override names it: the override's type,
+    and its filament id only for a forced colour, since a swap clears the id
+    (``PrintScheduler._apply_filament_overrides``). A slot left naming no
+    filament id isn't judged here at all: the tray matcher never maps it onto
+    a spool the creator may not use, so the tray it prints from is what is
+    judged. Judged by its type alone, a group that allows only filament ids
+    would refuse a colour swap onto one of its own spools.
+    """
+    by_slot: dict[int, Mapping] = {}
+    for override in overrides or ():
+        if isinstance(override, Mapping):
+            slot_id = override.get("slot_id")
+            if isinstance(slot_id, int) and not isinstance(slot_id, bool):
+                by_slot[slot_id] = override
+    judged: list[Mapping] = []
+    for req in requirements:
+        slot_id = req.get("slot_id")
+        override = by_slot.get(slot_id) if isinstance(slot_id, int) else None
+        if override is None:
+            judged.append(req)
+            continue
+        filament_id = str(override.get("tray_info_idx") or "").strip() if override.get("force_color_match") else ""
+        if filament_id:
+            judged.append({**req, "type": override.get("type", ""), "tray_info_idx": filament_id})
+    return judged
+
+
+def ensure_requirements_allowed(scope: FilamentScope, requirements: Iterable[Mapping]) -> None:
+    """403 naming each filament of the file the caller's groups don't allow."""
+    if scope.is_unrestricted:
+        return
+    blocked = scope.blocked_requirements(requirements)
+    if blocked:
+        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=blocked_message(blocked))

+ 10 - 3
backend/app/models/group.py

@@ -54,9 +54,10 @@ class Group(Base):
     Users can belong to multiple groups, and their permissions are additive.
     System groups (Administrators, Operators, Viewers) cannot be deleted.
 
-    Permissions say *what* a member may do; ``restrict_printers`` says *where*.
-    A group without the flag doesn't narrow printer access at all, so it can be
-    combined with a team group that does. See ``core/printer_scope.py``.
+    Permissions say *what* a member may do; ``restrict_printers`` says *where*
+    and ``restrict_filaments`` *with which filaments*. A group without a flag
+    doesn't narrow that dimension at all, so it can be combined with a team
+    group that does. See ``core/printer_scope.py`` and ``core/filament_scope.py``.
     """
 
     __tablename__ = "groups"
@@ -67,6 +68,12 @@ class Group(Base):
     permissions: Mapped[list[str]] = mapped_column(JSON, default=list)
     is_system: Mapped[bool] = mapped_column(Boolean, default=False)
     restrict_printers: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0")
+    # Filament scope (#3522): when set, members may only print with the
+    # filaments this group's rules allow (see ``core/filament_scope.py``). The
+    # mode and rules are kept while the flag is off, like the printer picks.
+    restrict_filaments: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0")
+    filament_rule_mode: Mapped[str] = mapped_column(String(10), default="block", server_default="block")
+    filament_rules: Mapped[list[dict] | None] = mapped_column(JSON, nullable=True)
     created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
     updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
 

+ 12 - 0
backend/app/schemas/auth.py

@@ -3,6 +3,7 @@ from typing import Literal
 
 from pydantic import BaseModel, Field, field_validator, model_validator
 
+from backend.app.schemas.group import FilamentRuleSchema
 from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
 
 
@@ -80,6 +81,14 @@ class UserUpdate(IgnoresNullForRequiredColumns):
         return v
 
 
+class FilamentPolicyBrief(BaseModel):
+    """One restricted group's filament rules, as the print dialog applies them (#3522)."""
+
+    group: str
+    mode: Literal["allow", "block"]
+    rules: list[FilamentRuleSchema] = []
+
+
 class UserResponse(BaseModel):
     id: int
     username: str
@@ -90,6 +99,9 @@ class UserResponse(BaseModel):
     auth_source: str = "local"  # "local" or "ldap"
     groups: list[GroupBrief] = []
     permissions: list[str] = []  # All permissions from groups
+    # None: may print with every filament. Otherwise a filament is allowed when
+    # any of these policies allows it (#3522); the server enforces the same.
+    filament_policies: list[FilamentPolicyBrief] | None = None
     created_at: str
 
     class Config:

+ 23 - 1
backend/app/schemas/group.py

@@ -1,8 +1,9 @@
 """Pydantic schemas for Group CRUD operations."""
 
 from datetime import datetime
+from typing import Annotated, Literal
 
-from pydantic import BaseModel
+from pydantic import BaseModel, StringConstraints
 
 from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
 
@@ -17,6 +18,15 @@ class GroupBrief(BaseModel):
         from_attributes = True
 
 
+class FilamentRuleSchema(BaseModel):
+    """One filament rule of a group (#3522): a material type or a slicer filament id."""
+
+    match: Literal["material", "filament_id"]
+    # Stripped before the length check, so a blank value is a 422 rather than
+    # a rule `clean_rules` would silently drop.
+    value: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=64)]
+
+
 class GroupCreate(BaseModel):
     """Schema for creating a new group."""
 
@@ -28,6 +38,12 @@ class GroupCreate(BaseModel):
     restrict_printers: bool = False
     printer_ids: list[int] = []
     locations: list[str] = []
+    # Filament scope (#3522): when set, members may only print with the
+    # filaments these rules allow. In "block" mode that is every filament no
+    # rule names; in "allow" mode, only those a rule names.
+    restrict_filaments: bool = False
+    filament_rule_mode: Literal["allow", "block"] = "block"
+    filament_rules: list[FilamentRuleSchema] = []
 
 
 class GroupUpdate(IgnoresNullForRequiredColumns):
@@ -41,6 +57,9 @@ class GroupUpdate(IgnoresNullForRequiredColumns):
     restrict_printers: bool | None = None
     printer_ids: list[int] | None = None
     locations: list[str] | None = None
+    restrict_filaments: bool | None = None
+    filament_rule_mode: Literal["allow", "block"] | None = None
+    filament_rules: list[FilamentRuleSchema] | None = None
 
 
 class GroupResponse(BaseModel):
@@ -54,6 +73,9 @@ class GroupResponse(BaseModel):
     restrict_printers: bool = False
     printer_ids: list[int] = []
     locations: list[str] = []
+    restrict_filaments: bool = False
+    filament_rule_mode: Literal["allow", "block"] = "block"
+    filament_rules: list[FilamentRuleSchema] = []
     user_count: int = 0
     created_at: datetime
     updated_at: datetime

+ 19 - 11
backend/app/services/bambu_mqtt.py

@@ -40,6 +40,8 @@ from backend.app.utils.tray_ids import (
     is_rack_ams,
     legacy_tray_index,
     mapped_trays_with_slot,
+    reconcile_use_ams,
+    reports_no_ams,
     tray_flag_bit,
     unit_ams_type,
     unit_label,
@@ -6721,6 +6723,10 @@ class BambuMQTTClient:
             from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
 
             is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
+            # The scheduler's filament check (#3522) reads the feed with the
+            # same `reconcile_use_ams`, but its dual-nozzle test
+            # (`_might_be_dual_nozzle`) is more generous: it also counts a
+            # populated `ams_extruder_map` or more than one external feed.
 
             # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
             ams_mapping2 = []
@@ -6811,26 +6817,28 @@ class BambuMQTTClient:
             #     0-253. Keeping them distinct means an unresolved mapping fails loudly
             #     (or is recomputed upstream) instead of silently going external, and
             #     never gets force-enabled by (a) either.
+            #
+            # The rule lives in `reconcile_use_ams`, which the scheduler's
+            # filament-permission check (#3522) shares, so what it judges is
+            # what is sent here. (Not when the scheduler worked out from the
+            # plate's own filament list that it prints only from the spool
+            # holder: a real tray here is then one another plate of the file
+            # uses.)
             if ams_mapping and not is_dual_nozzle:
-                has_real_tray = any(
-                    t is not None and 0 <= int(t) <= 253 and not layout.is_external(int(t)) for t in ams_mapping
+                reconciled = reconcile_use_ams(
+                    ams_mapping, use_ams, layout, plate_uses_only_external=plate_uses_only_external
                 )
-                all_external = all(t is None or int(t) >= 254 or layout.is_external(int(t)) for t in ams_mapping)
-                # (Not when the scheduler worked out from the plate's own
-                # filament list that it prints only from the spool holder: a
-                # real tray here is then one another plate of the file uses.)
-                if has_real_tray and not use_ams and not plate_uses_only_external:
-                    use_ams = True
+                if reconciled and not use_ams:
                     logger.info(
                         "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
                         self.serial_number,
                     )
-                elif use_ams and all_external:
-                    use_ams = False
+                elif use_ams and not reconciled:
                     logger.info(
                         "[%s] All filament slots use external spool — setting use_ams=False",
                         self.serial_number,
                     )
+                use_ams = reconciled
 
             # (c) A single-nozzle printer that reported no AMS at all can only
             #     print from the spool holder, whatever the mapping says. With
@@ -6840,7 +6848,7 @@ class BambuMQTTClient:
             #     mapping table" (#3356). An empty raw_data["ams"] is the
             #     printer's own report of no AMS; a missing key means no AMS
             #     push has been handled yet (a reconnect), which changes nothing.
-            if use_ams and not is_dual_nozzle and self.state.raw_data.get("ams") == []:
+            if use_ams and not is_dual_nozzle and reports_no_ams(self.state.raw_data):
                 use_ams = False
                 logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
 

+ 558 - 39
backend/app/services/print_scheduler.py

@@ -21,6 +21,16 @@ from sqlalchemy.orm import selectinload
 
 from backend.app.core.config import settings
 from backend.app.core.database import async_session, run_with_retry
+from backend.app.core.filament_scope import (
+    ALL_FILAMENTS,
+    FilamentScope,
+    file_hold_message,
+    judged_requirements,
+    print_anyway_hold_message,
+    resolve_user_id_filament_scope,
+    spool_hold_message,
+    unlisted_file_hold_message,
+)
 from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope, resolve_user_id_printer_scope
 from backend.app.core.tasks import spawn_background_task
 from backend.app.core.websocket import ws_manager
@@ -88,6 +98,7 @@ from backend.app.utils.filename import InvalidFilenameError, derive_remote_filen
 from backend.app.utils.library_paths import move_library_photos
 from backend.app.utils.local_time import utcnow_naive
 from backend.app.utils.printer_models import (
+    has_ams3h,
     is_dual_nozzle_model,
     is_gcode_compatible,
     is_nozzle_rack_model,
@@ -104,6 +115,8 @@ from backend.app.utils.tray_ids import (
     TrayLayout,
     is_ams_ht_id,
     is_external_tray,
+    reconcile_use_ams,
+    reports_no_ams,
     unit_label,
 )
 
@@ -744,18 +757,22 @@ def _is_unmatched_hold_reason(reason: str | None) -> bool:
     return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
 
 
+def _filament_overrides_of(item: PrintQueueItem) -> list:
+    """The item's stored filament overrides, or an empty list when there are none or they don't parse."""
+    try:
+        overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
+    except (json.JSONDecodeError, TypeError):
+        return []
+    return overrides if isinstance(overrides, list) else []
+
+
 def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
     """The item's force_color_match overrides as filament requirements (#3280).
 
     What ``_build_override_direct_mapping`` matches when the 3MF cannot be
     read, so the checks after it judge the same list.
     """
-    try:
-        overrides = json.loads(item.filament_overrides) if item.filament_overrides else []
-    except (json.JSONDecodeError, TypeError):
-        return []
-    if not isinstance(overrides, list):
-        return []
+    overrides = _filament_overrides_of(item)
     return [
         {
             "slot_id": o.get("slot_id"),
@@ -769,6 +786,18 @@ def _forced_override_requirements(item: PrintQueueItem) -> list[dict]:
     ]
 
 
+@dataclass(frozen=True)
+class FilamentScopeHold:
+    """``_ensure_ams_mapping``'s answer when the job's creator may not print it as it stands (#3522).
+
+    Not a failure: like a printer its creator lost (#1727), the job is held
+    pending with ``reason`` on its queue row, and starts by itself on the first
+    pass after the group's rules, the loaded spools or the job allow it.
+    """
+
+    reason: str
+
+
 def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
     """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
 
@@ -824,6 +853,18 @@ def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None)
     return entries or None
 
 
+def _plate_uses_only_external(mapping: list | None, required: list[dict] | None, rack: bool = False) -> bool:
+    """Whether every slot this plate prints is mapped to an external spool (#3087).
+
+    Exact, because the plate's own filament list (``required``) tells padding
+    from a slot that never resolved (see ``_consumed_mapping_entries``). The
+    dispatch sends it to the command builder, and the filament-permission
+    check (#3522) judges the feed by it, so both read it the same way.
+    """
+    consumed = _consumed_mapping_entries(mapping, required)
+    return bool(consumed) and all(_is_external_tray(t, rack) for t in consumed or ())
+
+
 def _is_external_tray(tray_id, rack: bool = False) -> bool:
     """True for an explicit external-spool selection (254/255, and 247-253 on a
     ``rack`` printer), not for an unresolved slot and not for an AMS tray."""
@@ -887,6 +928,8 @@ _DISPATCH_INPUTS = (
     "plate_id",
     "filament_overrides",
     "skip_filament_check",
+    # Decides the feed, so it is part of the filament check too (#3522).
+    "use_ams",
     "target_model",
     "target_location",
 )
@@ -1584,6 +1627,12 @@ class PrintScheduler:
         # same job and printer (another variant, a previous-print retry, the
         # low-filament move). Cleared with the requirement memo.
         self._unmatched_memo: dict[tuple, list[str]] = {}
+        # Per-pass memo for `_creator_filament_scope` (#3522): choosing a
+        # printer for an "any model" job asks the matcher about every idle
+        # candidate, and each asks for the creator's filament scope. Cleared
+        # with the requirement memo, so a rule changed between passes applies
+        # on the next one.
+        self._filament_scope_memo: dict[int, FilamentScope] = {}
         # When each "any model" job held for low filament last looked for
         # another printer (#3137), by queue item id.
         self._short_hold_checked_at: dict[int, float] = {}
@@ -1800,6 +1849,7 @@ class PrintScheduler:
         # Scoped to one pass: a file re-sliced between ticks must be re-read.
         self._filament_req_memo.clear()
         self._unmatched_memo.clear()
+        self._filament_scope_memo.clear()
         async with async_session() as db:
             # Check if shortest-job-first scheduling is enabled
             sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
@@ -2429,6 +2479,21 @@ class PrintScheduler:
                         continue
 
                     unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
+                    if isinstance(unmappable, FilamentScopeHold):
+                        # Its creator may not print it as it stands (#3522).
+                        # Held, not failed, as for a printer they lost above:
+                        # it starts once the group's rules or the loaded
+                        # spools allow it.
+                        if item.waiting_reason != unmappable.reason:
+                            logger.info(
+                                "Queue item %s held on printer %s by its creator's filament rules — %s",
+                                item.id,
+                                item.printer_id,
+                                unmappable.reason,
+                            )
+                        await hold_item(item, unmappable.reason, notify=False)
+                        skip_reasons["filament_out_of_scope"] = skip_reasons.get("filament_out_of_scope", 0) + 1
+                        continue
                     if unmappable:
                         await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
                         continue
@@ -2567,6 +2632,21 @@ class PrintScheduler:
                             skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
                             continue
 
+                        # A file its creator may not print (#3522) waits here,
+                        # unassigned, with the filament named: no printer of
+                        # the model could take it, and assigning one only to
+                        # give it back would do so on every pass. It starts
+                        # once the group's rules allow it. The check reads the
+                        # candidate's file off the item; resolving is safe to
+                        # repeat (see is_short below), and skipped when the
+                        # creator is unrestricted, so their items are untouched.
+                        if not (await self._creator_filament_scope(db, item.created_by_id)).is_unrestricted:
+                            self._resolve_variant(item, candidate)
+                            if scope_reason := await self._filament_scope_violation(db, item):
+                                per_model_reasons.append((candidate.target_model, scope_reason))
+                                skip_reasons["filament_out_of_scope"] = skip_reasons.get("filament_out_of_scope", 0) + 1
+                                continue
+
                         wakeable_candidates.append(candidate)
 
                         async def is_short(
@@ -2663,6 +2743,25 @@ class PrintScheduler:
                     if chosen is not None:
                         self._resolve_variant(item, chosen)
 
+                    # Sent without the AMS, the job may print from the chosen
+                    # printer's external spool, so its creator must be allowed
+                    # that filament (#3522). Judged on the mapping dispatch
+                    # will compute once it is assigned: a real tray in it
+                    # turns the AMS back on (#2595), and the spool isn't fed.
+                    # Checked before assigning: a printer assigned only to be
+                    # given back would be on every pass. It waits with the
+                    # filament named instead.
+                    if (
+                        printer_id
+                        and item.use_ams is False
+                        and not (await self._creator_filament_scope(db, item.created_by_id)).is_unrestricted
+                    ):
+                        planned = await self._compute_ams_mapping_for_printer(db, printer_id, item)
+                        if spool_reason := await self._blocked_external_spools(db, printer_id, item, planned):
+                            printer_id = None
+                            waiting_reason = spool_reason
+                            skip_reasons["filament_out_of_scope"] = skip_reasons.get("filament_out_of_scope", 0) + 1
+
                     # Update waiting_reason if changed and send notification when first waiting
                     if item.waiting_reason != waiting_reason:
                         was_waiting = item.waiting_reason is not None
@@ -2710,16 +2809,7 @@ class PrintScheduler:
                         item.waiting_reason = None
                         logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
 
-                        # Send assignment notification
-                        job_name = await self._get_job_name(db, item)
                         printer = await self._get_printer(db, printer_id)
-                        await notification_service.on_queue_job_assigned(
-                            job_name=job_name,
-                            printer_id=printer_id,
-                            printer_name=printer.name if printer else "Unknown",
-                            target_model=item.target_model,
-                            db=db,
-                        )
 
                         # A mapping on this item was not made for the printer just
                         # picked: it came with a job moved here from a fixed
@@ -2754,10 +2844,41 @@ class PrintScheduler:
                         # always missing here, so this computes it, and it also
                         # self-heals a bogus stored [-1] (#2589).
                         unmappable = await self._ensure_ams_mapping(db, printer_id, item)
+                        if isinstance(unmappable, FilamentScopeHold):
+                            # Its creator may not print it on this printer as
+                            # it stands (#3522). The checks before choosing it
+                            # catch nearly all of this; what is left changed in
+                            # between. Held, not failed, and given back to the
+                            # pool with its mapping, as the unmatched hold
+                            # does: "any X1C" means any.
+                            logger.info(
+                                "Queue item %s held, released from printer %s by its creator's filament rules — %s",
+                                item.id,
+                                printer_id,
+                                unmappable.reason,
+                            )
+                            item.printer_id = None
+                            drop_printer_resolved(item)
+                            item.waiting_reason = unmappable.reason
+                            await db.commit()
+                            skip_reasons["filament_out_of_scope"] = skip_reasons.get("filament_out_of_scope", 0) + 1
+                            continue
                         if unmappable:
                             await self._fail_unmappable_item(db, item, printer_id, unmappable)
                             continue
 
+                        # Announced only once the mapping and the creator's
+                        # filament rules let it stay: a job given back above
+                        # would be assigned, and announced, again on every
+                        # pass, and the notification has no de-duplication.
+                        await notification_service.on_queue_job_assigned(
+                            job_name=await self._get_job_name(db, item),
+                            printer_id=printer_id,
+                            printer_name=printer.name if printer else "Unknown",
+                            target_model=item.target_model,
+                            db=db,
+                        )
+
                         # Filament-deficit pre-dispatch check (#1496).
                         if await self._block_on_filament_deficit(db, item):
                             continue
@@ -2992,6 +3113,21 @@ class PrintScheduler:
                     logger.info("Queue item %s vanished after claim — skipping", item_id)
                     return
                 item_printer_id = item.printer_id
+                # The pass judged the job as it loaded it, and the creator
+                # could edit the feed (use_ams, the mapping, "Print anyway")
+                # until the claim above, after which edits are refused (409).
+                # Judged again as claimed, so such an edit can't carry the
+                # job onto a filament its creator may not use (#3522). Cheap:
+                # the scope and requirement memos are warm, and an
+                # unrestricted creator stops at the first lookup. The claim is
+                # cleared below, and the next pass holds the job.
+                if scope_reason := await self._claimed_scope_violation(item_db, item):
+                    logger.info(
+                        "Queue item %s changed before dispatch and its creator's filament rules now hold it — %s",
+                        item_id,
+                        scope_reason,
+                    )
+                    return
                 await self._start_print(item_db, item)
             finally:
                 # Undo an expected-print registration whose print command never
@@ -4182,7 +4318,285 @@ class PrintScheduler:
             # actually going to run so history and the ETA agree with reality.
             item.print_time_seconds = variant.print_time_seconds
 
-    async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
+    async def _creator_filament_scope(self, db: AsyncSession, user_id: int | None) -> FilamentScope:
+        """The filament scope of a job's creator (#3522), resolved once per creator per pass.
+
+        Resolving costs a settings read and a user load, and model-based
+        printer choice asks once per idle candidate printer, so the answer is
+        memoised like the creator's printer scope (#1727). A job with no
+        creator needs no lookup at all.
+        """
+        if user_id is None:
+            return ALL_FILAMENTS
+        if user_id not in self._filament_scope_memo:
+            self._filament_scope_memo[user_id] = await resolve_user_id_filament_scope(db, user_id)
+        return self._filament_scope_memo[user_id]
+
+    async def _filament_scope_violation(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
+        """Why the job's creator may not print this file (#3522), or None.
+
+        The file prints a filament the creator's groups don't allow. Checked
+        first in ``_ensure_ams_mapping``, so "Print anyway"
+        (``skip_filament_check``) can't override it: it's a permission, not a
+        mismatch the user may accept.
+        """
+        scope = await self._creator_filament_scope(db, item.created_by_id)
+        if scope.is_unrestricted:
+            return None
+        # A 3MF without slice info is mapped from its force-colour overrides
+        # (#3280), so judge those instead.
+        required = await self._get_filament_requirements(db, item) or _forced_override_requirements(item)
+        if not required:
+            return None
+        # With the overrides applied as the queue route and the dialog apply
+        # them (`judged_requirements`). A slot they leave naming no filament
+        # id is the matcher's to fill, and it never picks a tray the creator
+        # may not use; one left unmapped waits for its filament, and "Print
+        # anyway" can't hand it to a blocked tray either
+        # (`_dispatch_scope_violation`).
+        blocked = scope.blocked_requirements(judged_requirements(required, _filament_overrides_of(item)))
+        if not blocked:
+            return None
+        return file_hold_message(blocked)
+
+    async def _mapping_uses_blocked_tray(
+        self, db: AsyncSession, printer_id: int, item: PrintQueueItem, stored_mapping: list
+    ) -> bool:
+        """Whether ``stored_mapping`` sends a slot to a tray the creator may not use (#3522).
+
+        The print dialog picks trays itself, without knowing the creator's
+        filament scope, so a stored mapping can name a blocked tray that an
+        allowed one could replace. The caller drops such a mapping and lets the
+        matcher, which skips blocked trays, choose again.
+        """
+        scope = await self._creator_filament_scope(db, item.created_by_id)
+        if scope.is_unrestricted:
+            return False
+        status = printer_manager.get_status(printer_id)
+        if not status:
+            return False
+        blocked = scope.blocked_tray_ids(self._build_loaded_filaments(status))
+        return any(_is_tray_id(tray) and tray in blocked for tray in stored_mapping)
+
+    async def _sent_feeds(
+        self, db: AsyncSession, printer_id: int, item: PrintQueueItem, status, mapping: list | None
+    ) -> tuple[bool, bool]:
+        """Whether the printer would feed (its external spools, the trays ``mapping`` names) (#3522).
+
+        Worked out as the job is sent, not from ``use_ams`` alone. On a
+        single-nozzle printer the dispatch turns the AMS off for a plate that
+        prints only from the spool holder (#3087), the command builder turns it
+        back on for a real tray in the mapping (``reconcile_use_ams``, #2595),
+        and a printer that reported no AMS feeds the spool holder (#3356). A
+        mapping that couldn't be sent at all is judged both ways.
+
+        On a dual-nozzle printer ``use_ams`` picks the extruder instead, and the
+        builder leaves it alone: with it off an external spool may feed, and
+        which one is not ours to guess, so the mapping counts as well.
+        """
+        # On by default: a row not yet flushed reads None.
+        use_ams = item.use_ams is not False
+        printer = await self._get_printer(db, printer_id)
+        # Not quite the builder's test. `start_print` calls a printer
+        # dual-nozzle by its model or a reported second extruder
+        # (`_is_dual_nozzle`); `_might_be_dual_nozzle` also says yes for a
+        # populated `ams_extruder_map` or more than one external feed. Where
+        # only this one says yes, the mapping is judged instead of the
+        # external spool alone, and a mapping onto a blocked external spool
+        # is still caught by its tray id.
+        if _might_be_dual_nozzle(printer.model if printer else None, status):
+            return not use_ams, True
+        if isinstance(mapping, list) and mapping:
+            # Each layout as its own step reads it: the dispatch from the live
+            # state, the builder also from the model (`tray_layout`).
+            rack = TrayLayout.from_state(status).rack
+            try:
+                only_external = any(_is_external_tray(t, rack) for t in mapping) and _plate_uses_only_external(
+                    mapping, await self._get_filament_requirements(db, item), rack
+                )
+                use_ams = reconcile_use_ams(
+                    mapping,
+                    use_ams and not only_external,
+                    TrayLayout.from_state(status, has_ams3h(printer.model if printer else None)),
+                    plate_uses_only_external=only_external,
+                )
+            except (TypeError, ValueError):
+                return True, True
+        if use_ams and reports_no_ams(status.raw_data):
+            use_ams = False
+        return not use_ams, use_ams
+
+    @staticmethod
+    def _blocked_external(scope: FilamentScope, loaded: list[dict], status, mapping: list | None) -> list[dict]:
+        """The external spools a job sent with ``mapping`` could feed that ``scope`` doesn't allow (#3522).
+
+        A spool with no filament set can't be judged and is allowed. Every
+        external spool counts: which one a dual-nozzle printer feeds is not
+        ours to guess. A rack printer (H3C) has one external input per hotend
+        and feeds the ones the mapping names, so there only those count; a
+        mapping that names none says nothing, and all of them count.
+        """
+        named: set[int] = set()
+        if TrayLayout.from_state(status).rack:
+            named = {t for t in mapping or () if _is_tray_id(t) and _is_external_tray(t, True)}
+        return [
+            spool
+            for spool in loaded
+            if spool.get("is_external")
+            and (not named or spool.get("global_tray_id") in named)
+            and not scope.allows(spool.get("type"), spool.get("tray_info_idx"))
+        ]
+
+    async def _blocked_external_spools(
+        self, db: AsyncSession, printer_id: int, item: PrintQueueItem, mapping: list | None
+    ) -> str | None:
+        """Why a job sent with ``mapping`` would print from an external spool its creator may not use (#3522), or None.
+
+        The spool is judged like any tray, but only where the printer would
+        actually feed it (``_sent_feeds``): a blocked spool on the holder must
+        not hold a job whose mapping turns the AMS on. Which external spools
+        count is ``_blocked_external``'s to say.
+        """
+        scope = await self._creator_filament_scope(db, item.created_by_id)
+        if scope.is_unrestricted:
+            return None
+        status = printer_manager.get_status(printer_id)
+        if not status:
+            return None
+        feeds_external, _ = await self._sent_feeds(db, printer_id, item, status, mapping)
+        if not feeds_external:
+            return None
+        blocked = self._blocked_external(scope, self._build_loaded_filaments(status), status, mapping)
+        return spool_hold_message(blocked) if blocked else None
+
+    async def _dispatch_scope_violation(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
+        """Why the mapping about to be sent would print a filament its creator may not use (#3522), or None.
+
+        The file check (``_filament_scope_violation``) judges what the file
+        asks for; this judges what the printer would feed, as it is sent
+        (``_sent_feeds``). That differs where the printer, not Bambuddy, picks
+        the spool:
+
+        * The external spool, where the printer would feed it.
+        * A mapping that names a blocked tray, where the printer would feed the
+          mapping. The matcher never picks one, so this is a backstop for a
+          mapping that reached dispatch some other way.
+        * A file that lists no filaments, which nothing can map: the printer
+          picks from its spools, so a blocked one it could pick holds the job.
+        * "Print anyway" with a printed slot left without a tray, while a
+          blocked tray is loaded. Without the flag
+          ``_block_on_unmatched_filament`` holds that job; with it, the printer
+          would choose a feed for the slot, possibly the blocked tray. For a
+          restricted creator the flag accepts a mismatch, not that. With
+          nothing blocked loaded, every feed it could choose is allowed. A
+          tray the printer doesn't report loaded counts as such a slot.
+        """
+        scope = await self._creator_filament_scope(db, item.created_by_id)
+        if scope.is_unrestricted:
+            return None
+        status = printer_manager.get_status(printer_id)
+        if not status:
+            return None
+        mapping: list | None = None
+        if item.ams_mapping:
+            try:
+                mapping = json.loads(item.ams_mapping)
+            except (json.JSONDecodeError, TypeError):
+                mapping = None
+            if not isinstance(mapping, list):
+                mapping = None
+        feeds_external, feeds_mapping = await self._sent_feeds(db, printer_id, item, status, mapping)
+        loaded = self._build_loaded_filaments(status)
+        if feeds_external and (external := self._blocked_external(scope, loaded, status, mapping)):
+            return spool_hold_message(external)
+        if not feeds_mapping:
+            return None
+        blocked_ids = scope.blocked_tray_ids(loaded)
+        used = {t for t in mapping or [] if _is_tray_id(t) and t in blocked_ids}
+        if used:
+            return spool_hold_message(tray for tray in loaded if tray["global_tray_id"] in used)
+        # What is left is a slot the printer fills by itself, so only a
+        # blocked spool it could pick matters: an AMS tray, and an external
+        # spool where it feeds those. With the AMS on, a single-nozzle
+        # printer never sends such a slot to the spool holder. On a printer
+        # that might be dual-nozzle `use_ams` picks the extruder rather than
+        # the AMS, so either external spool may feed whatever it says, as it
+        # is all an H2D without an AMS has.
+        printer = await self._get_printer(db, printer_id)
+        externals = feeds_external or _might_be_dual_nozzle(printer.model if printer else None, status)
+        pickable = [
+            tray
+            for tray in loaded
+            if tray["global_tray_id"] in blocked_ids and (externals or not tray.get("is_external"))
+        ]
+        if not pickable:
+            return None
+        if (
+            not (await self._get_filament_requirements(db, item) or _forced_override_requirements(item))
+            and (source := await self._source_file_path(db, item)) is not None
+            and source.exists()
+        ):
+            # A file that lists no filaments (no readable slice info) can't be
+            # judged from the file, and the matcher has nothing to map: the
+            # printer picks its feed. So the spools it could pick from are
+            # judged instead. A file that is gone is left to the dispatch,
+            # which fails it as missing.
+            return unlisted_file_hold_message(pickable)
+        if item.skip_filament_check:
+            # A tray the printer doesn't report loaded settles nothing: only a
+            # hand-written mapping names one, and "Print anyway" keeps it past
+            # the fit check (`_stored_mapping_conflict`). The printer would
+            # fill that slot itself, so it counts as unresolved.
+            known = {tray["global_tray_id"] for tray in loaded}
+            if mapping is not None:
+                mapping = [t if _is_tray_id(t) and t in known else -1 for t in mapping]
+            unresolved = await self._unmatched_requirements(db, item, printer_id, mapping)
+            if unresolved:
+                return print_anyway_hold_message(unresolved, pickable)
+        return None
+
+    async def _claimed_scope_violation(self, db: AsyncSession, item: PrintQueueItem) -> str | None:
+        """``_ensure_ams_mapping``'s filament-scope checks, on the row as claimed for dispatch (#3522).
+
+        The creator's rules are read afresh: the pass may have waited minutes
+        (a smart plug powering a printer on) since it memoised them, and a rule
+        tightened meanwhile must apply to what it dispatches now.
+        """
+        if item.printer_id is None:
+            return None
+        if item.created_by_id is not None:
+            self._filament_scope_memo.pop(item.created_by_id, None)
+        return await self._filament_scope_violation(db, item) or await self._dispatch_scope_violation(
+            db, item.printer_id, item
+        )
+
+    async def _ensure_ams_mapping(
+        self, db: AsyncSession, printer_id: int, item: PrintQueueItem
+    ) -> str | FilamentScopeHold | None:
+        """Settle the item's AMS mapping for ``printer_id``, then hold it to its creator's filament scope.
+
+        Returns ``_settle_ams_mapping``'s message when the item can't print on
+        this printer at all (the caller fails it), or a ``FilamentScopeHold``
+        when its creator may not print it as it stands (#3522; the caller
+        holds it), or None.
+
+        The file is judged first, so the "Print anyway" short-circuit inside
+        can't skip the check. What the printer would feed is judged after the
+        mapping is settled, whichever way it was: kept, filled, recomputed or
+        left unresolved.
+        """
+        if violation := await self._filament_scope_violation(db, item):
+            return FilamentScopeHold(violation)
+        unmappable = await self._settle_ams_mapping(db, printer_id, item)
+        if unmappable:
+            return unmappable
+        if violation := await self._dispatch_scope_violation(db, printer_id, item):
+            return FilamentScopeHold(violation)
+        return None
+
+    async def _settle_ams_mapping(
+        self, db: AsyncSession, printer_id: int, item: PrintQueueItem
+    ) -> str | FilamentScopeHold | None:
         """Ensure the queue item carries a usable AMS mapping before dispatch.
 
         Recomputes from live printer status when the stored mapping is missing OR
@@ -4211,7 +4625,11 @@ class PrintScheduler:
         on it instead of spending an upload on a print that cannot start.
         Returns None everywhere else, including every case where we simply lack
         the data to judge, so dispatch is only ever blocked on a positive
-        finding.
+        finding. A stored mapping that uses a tray the job's creator may not
+        use is recomputed (#3522), and a job only a spool its creator may not
+        use would match, on a printer with no AMS, is held instead of failed
+        (``_only_blocked_spools_match``); ``_ensure_ams_mapping`` judges the
+        rest of the creator's filament scope around this.
         """
         stored_mapping: list | None = None
         if item.ams_mapping:
@@ -4220,6 +4638,24 @@ class PrintScheduler:
             except (json.JSONDecodeError, TypeError):
                 stored_mapping = None
 
+        # A mapping that sends a slot to a tray the creator may not use is
+        # dropped and recomputed on allowed trays (#3522) -- before the "Print
+        # anyway" short-circuit below, which would otherwise keep it.
+        if (
+            isinstance(stored_mapping, list)
+            and not _mapping_is_all_unresolved(stored_mapping)
+            and await self._mapping_uses_blocked_tray(db, printer_id, item, stored_mapping)
+        ):
+            logger.info(
+                "Queue item %s: stored ams_mapping %s uses a tray its creator may not use on printer %s; recomputing",
+                item.id,
+                stored_mapping,
+                printer_id,
+            )
+            item.ams_mapping = None
+            stored_mapping = None
+            await db.commit()
+
         # Present and resolved. Global tray IDs only mean something relative to
         # the printer they were resolved against, so "resolved" is not the same
         # as "resolved *here*" — check the mapping still fits the printer that
@@ -4295,8 +4731,48 @@ class PrintScheduler:
             item.ams_mapping = None
             await db.commit()
 
+        if hold := await self._only_blocked_spools_match(db, printer_id, item):
+            return hold
         return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
 
+    async def _only_blocked_spools_match(
+        self, db: AsyncSession, printer_id: int, item: PrintQueueItem
+    ) -> FilamentScopeHold | None:
+        """A hold when, on a printer with no AMS, the job matches only spools its creator may not use (#3522).
+
+        The matcher leaves those spools out, so it resolves nothing, and the
+        job would be failed as if nothing matched
+        (``_unmappable_without_ams_message``), or held as unmatched. A
+        dual-nozzle printer (H2D/H2C) with only external spools reaches here,
+        since the single-feed fallback isn't its. Matched again with every
+        spool in, a printed slot that lands on a blocked one is a permission
+        finding: the job is held, and starts once the group's rules or the
+        spools allow it.
+        """
+        scope = await self._creator_filament_scope(db, item.created_by_id)
+        if scope.is_unrestricted:
+            return None
+        status = printer_manager.get_status(printer_id)
+        if status is None or not reports_no_ams(status.raw_data):
+            return None
+        loaded = self._build_loaded_filaments(status)
+        blocked_ids = scope.blocked_tray_ids(loaded)
+        if not blocked_ids:
+            return None
+        required = await self._get_filament_requirements(db, item)
+        if required:
+            self._apply_filament_overrides(item, required)
+        else:
+            required = _forced_override_requirements(item)
+        if not required:
+            return None
+        fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
+        mapping = self._match_filaments_to_slots(required, loaded, fts_installed=fts_installed) or []
+        used = {t for t in mapping if _is_tray_id(t) and t in blocked_ids}
+        if not used:
+            return None
+        return FilamentScopeHold(spool_hold_message(tray for tray in loaded if tray["global_tray_id"] in used))
+
     async def _external_spool_only_mapping(
         self, db: AsyncSession, printer_id: int, item: PrintQueueItem
     ) -> list[int] | None:
@@ -4421,6 +4897,7 @@ class PrintScheduler:
         # memoised so this reads the file as it is now. A pass running at the
         # same time only loses its cache.
         self._filament_req_memo.clear()
+        self._filament_scope_memo.clear()
 
         mapping: list | None = None
         if item.ams_mapping:
@@ -4645,6 +5122,12 @@ class PrintScheduler:
 
         required = await self._get_filament_requirements(db, item)
         loaded = self._build_loaded_filaments(status)
+        # A spool its creator may not use isn't one the job could print from,
+        # so the message doesn't offer it (#3522).
+        scope = await self._creator_filament_scope(db, item.created_by_id)
+        if not scope.is_unrestricted:
+            blocked_ids = scope.blocked_tray_ids(loaded)
+            loaded = [f for f in loaded if f["global_tray_id"] not in blocked_ids]
         if not required or not loaded:
             # Both were non-empty moments ago or the matcher could not have run.
             # If the picture changed under us, say nothing rather than fail an
@@ -4669,6 +5152,9 @@ class PrintScheduler:
         the printer already asks the matcher (``_unmatched_on``, #3280) and passes
         over one it cannot map, so an "Any <model>" job tries its siblings and
         otherwise waits; this remains for a match that failed at selection time.
+
+        Never for a filament the job's creator may not use: that is a
+        ``FilamentScopeHold``, and the job is held instead (#3522).
         """
         item.status = "failed"
         item.error_message = message
@@ -4760,7 +5246,14 @@ class PrintScheduler:
                             item.id,
                             len(force_overrides),
                         )
-                        return self._build_override_direct_mapping(force_overrides, status)
+                        # Same tray rule as the matcher below (#3522).
+                        override_scope = await self._creator_filament_scope(db, item.created_by_id)
+                        blocked_trays = (
+                            None
+                            if override_scope.is_unrestricted
+                            else override_scope.blocked_tray_ids(self._build_loaded_filaments(status))
+                        )
+                        return self._build_override_direct_mapping(force_overrides, status, blocked_trays=blocked_trays)
                 except (json.JSONDecodeError, KeyError, TypeError) as e:
                     logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
             logger.debug("No filament requirements found for queue item %s", item.id)
@@ -4776,6 +5269,13 @@ class PrintScheduler:
         loaded_filaments = self._build_loaded_filaments(status)
         if reserved_trays:
             loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
+        # Trays holding a filament the job's creator may not print with
+        # (#3522) are never matched: the job takes another tray or waits.
+        filament_scope = await self._creator_filament_scope(db, item.created_by_id)
+        if not filament_scope.is_unrestricted:
+            blocked_trays = filament_scope.blocked_tray_ids(loaded_filaments)
+            if blocked_trays:
+                loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in blocked_trays]
         if not loaded_filaments:
             logger.debug("No filaments loaded on printer %s", printer_id)
             return None
@@ -4851,7 +5351,9 @@ class PrintScheduler:
         except (json.JSONDecodeError, KeyError, TypeError) as e:
             logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
 
-    def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
+    def _build_override_direct_mapping(
+        self, force_overrides: list[dict], status, *, blocked_trays: set[int] | None = None
+    ) -> list[int] | None:
         """Build an AMS mapping directly from force-color overrides without a 3MF.
 
         Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
@@ -4860,10 +5362,15 @@ class PrintScheduler:
         treated as the filament requirement for that slot and matched against the
         current AMS state of the printer.
 
+        ``blocked_trays`` are global tray IDs holding a filament the job's
+        creator may not print with (#3522); they are left out of the match.
+
         Returns the same format as ``_match_filaments_to_slots``, or None when
-        the AMS has no loaded filaments.
+        the AMS has no loaded filaments (or only blocked ones).
         """
         loaded = self._build_loaded_filaments(status)
+        if blocked_trays:
+            loaded = [f for f in loaded if f["global_tray_id"] not in blocked_trays]
         if not loaded:
             return None
 
@@ -4901,26 +5408,29 @@ class PrintScheduler:
             cached = self._filament_req_memo[memo_key]
             return [dict(r) for r in cached] if cached else None
 
-        file_path: Path | None = None
+        file_path = await self._source_file_path(db, item)
+        if not file_path or not file_path.exists():
+            self._filament_req_memo[memo_key] = None
+            return None
+
+        filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
+        self._filament_req_memo[memo_key] = filaments or None
+        return [dict(r) for r in filaments] if filaments else None
+
+    async def _source_file_path(self, db: AsyncSession, item: PrintQueueItem) -> Path | None:
+        """Where the queue item's source file should be on disk, or None when its archive or library row is gone."""
         if item.archive_id:
             result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
             archive = result.scalar_one_or_none()
             if archive:
-                file_path = settings.base_dir / archive.file_path
+                return settings.base_dir / archive.file_path
         elif item.library_file_id:
             result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
             library_file = result.scalar_one_or_none()
             if library_file:
                 lib_path = Path(library_file.file_path)
-                file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
-
-        if not file_path or not file_path.exists():
-            self._filament_req_memo[memo_key] = None
-            return None
-
-        filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
-        self._filament_req_memo[memo_key] = filaments or None
-        return [dict(r) for r in filaments] if filaments else None
+                return lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
+        return None
 
     def _build_loaded_filaments(self, status) -> list[dict]:
         """Build list of loaded filaments from printer status.
@@ -9010,9 +9520,18 @@ class PrintScheduler:
 
         Empty when the hold would let the item through, including "Print
         Anyway" and a match that fails: the printer is then chosen as before.
+        Not "Print Anyway" for a creator whose filaments are restricted, on a
+        printer holding a filament they may not use (#3522): dispatch holds
+        that job where it can't map it (``_dispatch_scope_violation``), so the
+        printer must not be chosen.
         """
         if item.skip_filament_check:
-            return []
+            scope = await self._creator_filament_scope(db, item.created_by_id)
+            if scope.is_unrestricted:
+                return []
+            status = printer_manager.get_status(printer_id)
+            if status is None or not scope.blocked_tray_ids(self._build_loaded_filaments(status)):
+                return []
         key = (item.id, item.archive_id, item.library_file_id, item.plate_id, item.filament_overrides, printer_id)
         if key in self._unmatched_memo:
             return list(self._unmatched_memo[key])
@@ -10252,14 +10771,14 @@ class PrintScheduler:
         ):
             from backend.app.services.filament_requirements import extract_filament_requirements
 
-            consumed = _consumed_mapping_entries(
-                ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
+            # Exact for this plate: the command builder must not turn the AMS
+            # back on for a real tray another plate of the file uses, whether
+            # the job asked for the AMS or already had it off.
+            plate_uses_only_external = _plate_uses_only_external(
+                ams_mapping,
+                extract_filament_requirements(file_path, plate_id=effective_plate_id),
+                TrayLayout.from_state(pre_status).rack,
             )
-            if consumed and all(_is_external_tray(t, TrayLayout.from_state(pre_status).rack) for t in consumed):
-                # Exact for this plate: the command builder must not turn the
-                # AMS back on for a real tray another plate of the file uses,
-                # whether the job asked for the AMS or already had it off.
-                plate_uses_only_external = True
             if plate_uses_only_external and effective_use_ams:
                 effective_use_ams = False
                 logger.info(

+ 43 - 0
backend/app/utils/tray_ids.py

@@ -388,3 +388,46 @@ def mapped_trays_with_slot(mapping_raw: object, local_slot: int) -> dict[int, in
         if slot == local_slot and (ams_id in _REGULAR_WIRE_AMS_IDS or is_ams_ht_id(ams_id)):
             found[tray] = ams_id
     return found
+
+
+def reconcile_use_ams(
+    ams_mapping: Iterable[int | str | None],
+    use_ams: bool,
+    layout: TrayLayout = _NO_LAYOUT,
+    *,
+    plate_uses_only_external: bool = False,
+) -> bool:
+    """The ``use_ams`` a single-nozzle printer is sent for ``ams_mapping``: the mapping decides the feed.
+
+    The MQTT command builder applies this (see ``start_print``), and the
+    scheduler judges a job's filament permissions (#3522) on the same answer,
+    so the two can't drift apart. Two corrections:
+
+    * A real tray (0-253, not an external input) turns the AMS on, even if the
+      job arrived with it off (#2595), unless the caller worked out from the
+      plate's own filament list that it prints only from the spool holder and
+      the real tray belongs to another plate (#3087).
+    * Only explicit external selections turn it off. An unresolved slot (-1)
+      does neither (#2589).
+
+    Entries must read as integers; anything else raises, as it would when sent.
+    """
+    entries = list(ams_mapping)
+    if not entries:
+        return use_ams
+    has_real_tray = any(t is not None and 0 <= int(t) <= 253 and not layout.is_external(int(t)) for t in entries)
+    all_external = all(t is None or int(t) >= 254 or layout.is_external(int(t)) for t in entries)
+    if has_real_tray and not use_ams and not plate_uses_only_external:
+        return True
+    if use_ams and all_external:
+        return False
+    return use_ams
+
+
+def reports_no_ams(raw_data: object) -> bool:
+    """Whether a printer's raw state positively reports no AMS attached (#3356).
+
+    An empty ``ams`` list is that report; a missing key means no AMS push has
+    been handled yet (a reconnect), which says nothing.
+    """
+    return isinstance(raw_data, Mapping) and raw_data.get("ams") == []

+ 95 - 0
backend/tests/integration/test_auth_me_filament_policies_3522.py

@@ -0,0 +1,95 @@
+"""/auth/me tells the browser the caller's filament rules (#3522)."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
+
+
+def _auth(jwt: str) -> dict[str, str]:
+    return {"Authorization": f"Bearer {jwt}"}
+
+
+async def _admin_token(async_client: AsyncClient) -> str:
+    await async_client.post(
+        "/api/v1/auth/setup",
+        json={"auth_enabled": True, "admin_username": "meadmin", "admin_password": "AdminPass1!"},
+    )
+    login = await async_client.post("/api/v1/auth/login", json={"username": "meadmin", "password": "AdminPass1!"})
+    return login.json()["access_token"]
+
+
+async def _login(async_client: AsyncClient, admin: str, username: str, group_ids: list[int]) -> str:
+    created = await async_client.post(
+        "/api/v1/users/",
+        headers=_auth(admin),
+        json={"username": username, "password": "UserPass1!", "group_ids": group_ids},
+    )
+    assert created.status_code in (200, 201), created.text
+    login = await async_client.post("/api/v1/auth/login", json={"username": username, "password": "UserPass1!"})
+    return login.json()["access_token"]
+
+
+async def _friends_group(async_client: AsyncClient, admin: str) -> int:
+    friends = await async_client.post(
+        "/api/v1/groups/",
+        headers=_auth(admin),
+        json={
+            "name": "friends",
+            "permissions": ["api_keys:create", "users:read"],
+            "restrict_filaments": True,
+            "filament_rule_mode": "block",
+            "filament_rules": [{"match": "filament_id", "value": "GFG03"}],
+        },
+    )
+    assert friends.status_code == 201, friends.text
+    return friends.json()["id"]
+
+
+FRIENDS_POLICY = [{"group": "friends", "mode": "block", "rules": [{"match": "filament_id", "value": "GFG03"}]}]
+
+
+async def _my_policies(async_client: AsyncClient, headers: dict[str, str]) -> list[dict] | None:
+    me = await async_client.get("/api/v1/auth/me", headers=headers)
+    assert me.status_code == 200, me.text
+    return me.json()["filament_policies"]
+
+
+class TestMeFilamentPolicies:
+    async def test_admin_is_unrestricted(self, async_client):
+        admin = await _admin_token(async_client)
+        assert await _my_policies(async_client, _auth(admin)) is None
+
+    async def test_user_in_no_restricted_group_is_unrestricted(self, async_client):
+        admin = await _admin_token(async_client)
+        plain = await async_client.post("/api/v1/groups/", headers=_auth(admin), json={"name": "plain"})
+        jwt = await _login(async_client, admin, "plainuser", [plain.json()["id"]])
+        assert await _my_policies(async_client, _auth(jwt)) is None
+
+    async def test_restricted_member_gets_their_groups_rules(self, async_client):
+        admin = await _admin_token(async_client)
+        jwt = await _login(async_client, admin, "friend", [await _friends_group(async_client, admin)])
+        assert await _my_policies(async_client, _auth(jwt)) == FRIENDS_POLICY
+
+
+class TestOtherUserResponses:
+    """null means unrestricted, so every builder of the response must fill it (#3522)."""
+
+    async def test_an_api_key_reports_its_owners_rules(self, async_client):
+        admin = await _admin_token(async_client)
+        jwt = await _login(async_client, admin, "friend", [await _friends_group(async_client, admin)])
+        created = await async_client.post("/api/v1/api-keys/", headers=_auth(jwt), json={"name": "native"})
+        assert created.status_code in (200, 201), created.text
+
+        assert await _my_policies(async_client, {"X-API-Key": created.json()["key"]}) == FRIENDS_POLICY
+
+    async def test_the_user_list_reports_each_users_rules(self, async_client):
+        admin = await _admin_token(async_client)
+        await _login(async_client, admin, "friend", [await _friends_group(async_client, admin)])
+
+        users = (await async_client.get("/api/v1/users/", headers=_auth(admin))).json()
+        by_name = {u["username"]: u for u in users}
+        assert by_name["friend"]["filament_policies"] == FRIENDS_POLICY
+        assert by_name["meadmin"]["filament_policies"] is None

+ 115 - 0
backend/tests/integration/test_group_filament_rules_3522.py

@@ -0,0 +1,115 @@
+"""Group filament rules over the API (#3522)."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
+
+
+def _auth(jwt: str) -> dict[str, str]:
+    return {"Authorization": f"Bearer {jwt}"}
+
+
+async def _admin_token(async_client: AsyncClient) -> str:
+    await async_client.post(
+        "/api/v1/auth/setup",
+        json={"auth_enabled": True, "admin_username": "filadmin", "admin_password": "AdminPass1!"},
+    )
+    login = await async_client.post("/api/v1/auth/login", json={"username": "filadmin", "password": "AdminPass1!"})
+    assert login.status_code == 200, login.text
+    return login.json()["access_token"]
+
+
+class TestGroupFilamentRules:
+    async def test_defaults_on_a_new_group(self, async_client):
+        admin = await _admin_token(async_client)
+        created = await async_client.post("/api/v1/groups/", headers=_auth(admin), json={"name": "Plain"})
+        assert created.status_code == 201, created.text
+        body = created.json()
+        assert body["restrict_filaments"] is False
+        assert body["filament_rule_mode"] == "block"
+        assert body["filament_rules"] == []
+
+    async def test_round_trip(self, async_client):
+        admin = await _admin_token(async_client)
+        created = await async_client.post(
+            "/api/v1/groups/",
+            headers=_auth(admin),
+            json={
+                "name": "Friends",
+                "restrict_filaments": True,
+                "filament_rule_mode": "block",
+                "filament_rules": [
+                    {"match": "material", "value": " paht-cf "},
+                    {"match": "filament_id", "value": "GFG03"},
+                    {"match": "material", "value": "PAHT-CF"},
+                ],
+            },
+        )
+        assert created.status_code == 201, created.text
+        group_id = created.json()["id"]
+        assert created.json()["filament_rules"] == [
+            {"match": "material", "value": "PAHT-CF"},
+            {"match": "filament_id", "value": "GFG03"},
+        ]
+
+        updated = await async_client.patch(
+            f"/api/v1/groups/{group_id}",
+            headers=_auth(admin),
+            json={"filament_rule_mode": "allow", "filament_rules": [{"match": "material", "value": "PLA"}]},
+        )
+        assert updated.status_code == 200, updated.text
+        detail = (await async_client.get(f"/api/v1/groups/{group_id}", headers=_auth(admin))).json()
+        assert detail["restrict_filaments"] is True
+        assert detail["filament_rule_mode"] == "allow"
+        assert detail["filament_rules"] == [{"match": "material", "value": "PLA"}]
+
+    async def test_turning_off_keeps_the_rules(self, async_client):
+        admin = await _admin_token(async_client)
+        created = await async_client.post(
+            "/api/v1/groups/",
+            headers=_auth(admin),
+            json={
+                "name": "Keep",
+                "restrict_filaments": True,
+                "filament_rules": [{"match": "material", "value": "PETG"}],
+            },
+        )
+        group_id = created.json()["id"]
+        assert created.status_code == 201, created.text
+        off = await async_client.patch(
+            f"/api/v1/groups/{group_id}", headers=_auth(admin), json={"restrict_filaments": False}
+        )
+        assert off.status_code == 200, off.text
+        assert off.json()["restrict_filaments"] is False
+        assert off.json()["filament_rules"] == [{"match": "material", "value": "PETG"}]
+
+    async def test_bad_rule_kind_is_rejected(self, async_client):
+        admin = await _admin_token(async_client)
+        response = await async_client.post(
+            "/api/v1/groups/",
+            headers=_auth(admin),
+            json={"name": "Bad", "filament_rules": [{"match": "colour", "value": "red"}]},
+        )
+        assert response.status_code == 422
+
+    async def test_whitespace_only_rule_is_rejected(self, async_client):
+        """Not stored as nothing: a blank allow-list rule would block every filament."""
+        admin = await _admin_token(async_client)
+        response = await async_client.post(
+            "/api/v1/groups/",
+            headers=_auth(admin),
+            json={"name": "Blank", "filament_rules": [{"match": "material", "value": "   "}]},
+        )
+        assert response.status_code == 422, response.text
+
+    async def test_administrators_cannot_be_restricted(self, async_client):
+        admin = await _admin_token(async_client)
+        groups = (await async_client.get("/api/v1/groups/", headers=_auth(admin))).json()
+        admins = next(g for g in groups if g["name"] == "Administrators")
+        response = await async_client.patch(
+            f"/api/v1/groups/{admins['id']}", headers=_auth(admin), json={"restrict_filaments": True}
+        )
+        assert response.status_code == 400

+ 267 - 0
backend/tests/integration/test_queue_filament_scope_3522.py

@@ -0,0 +1,267 @@
+"""Queueing a job refuses filaments the user's groups don't allow (#3522)."""
+
+from __future__ import annotations
+
+import zipfile
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy import update
+
+from backend.app.core.config import settings
+from backend.app.models.library import LibraryFile
+from backend.app.models.print_queue import PrintQueueItem
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
+
+QUEUE_PERMISSIONS = [
+    "printers:read",
+    "queue:read_all",
+    "queue:create",
+    "archives:read_all",
+    "archives:reprint_all",
+    "library:read_all",
+]
+
+
+def _auth(jwt: str) -> dict[str, str]:
+    return {"Authorization": f"Bearer {jwt}"}
+
+
+@pytest.fixture(autouse=True)
+def _base_dir(tmp_path, monkeypatch):
+    # Archives resolve under settings.base_dir, which is the repo root in tests.
+    monkeypatch.setattr(settings, "base_dir", tmp_path)
+
+
+PETG_MATTE = '<filament id="1" used_g="5" type="PETG" tray_info_idx="GFG03" color="#FFFFFF"/>'
+PLA = '<filament id="1" used_g="5" type="PLA" tray_info_idx="GFA00" color="#FFFFFF"/>'
+
+
+def _write_3mf(rel: str, filaments: str) -> None:
+    path = Path(settings.base_dir) / rel
+    path.parent.mkdir(parents=True, exist_ok=True)
+    with zipfile.ZipFile(path, "w") as zf:
+        # A plate G-code member, or the queue refuses the file as unsliced (#3435).
+        zf.writestr("Metadata/plate_1.gcode", "; gcode\n")
+        zf.writestr(
+            "Metadata/slice_info.config",
+            f'<config><plate><metadata key="index" value="1"/>{filaments}</plate></config>',
+        )
+
+
+async def _admin_token(async_client: AsyncClient) -> str:
+    await async_client.post(
+        "/api/v1/auth/setup",
+        json={"auth_enabled": True, "admin_username": "qadmin", "admin_password": "AdminPass1!"},
+    )
+    login = await async_client.post("/api/v1/auth/login", json={"username": "qadmin", "password": "AdminPass1!"})
+    return login.json()["access_token"]
+
+
+async def _friend(async_client: AsyncClient, admin: str, rules: list[dict], mode: str = "block") -> str:
+    perms = await async_client.post(
+        "/api/v1/groups/", headers=_auth(admin), json={"name": "perms", "permissions": QUEUE_PERMISSIONS}
+    )
+    friends = await async_client.post(
+        "/api/v1/groups/",
+        headers=_auth(admin),
+        json={"name": "friends", "restrict_filaments": True, "filament_rule_mode": mode, "filament_rules": rules},
+    )
+    created = await async_client.post(
+        "/api/v1/users/",
+        headers=_auth(admin),
+        json={"username": "friend", "password": "UserPass1!", "group_ids": [perms.json()["id"], friends.json()["id"]]},
+    )
+    assert created.status_code in (200, 201), created.text
+    login = await async_client.post("/api/v1/auth/login", json={"username": "friend", "password": "UserPass1!"})
+    return login.json()["access_token"]
+
+
+BLOCK_PETG_MATTE = [{"match": "filament_id", "value": "GFG03"}]
+
+
+async def _printer_and_archive(printer_factory, archive_factory, name: str, filaments: str):
+    printer = await printer_factory(name="H3C")
+    rel = f"archives/fil/{name}.gcode.3mf"
+    _write_3mf(rel, filaments)
+    return printer, await archive_factory(printer.id, file_path=rel)
+
+
+def _library_file(db_session, name: str, filaments: str, metadata: dict | None = None) -> LibraryFile:
+    rel = f"library/{name}.gcode.3mf"
+    _write_3mf(rel, filaments)
+    row = LibraryFile(
+        filename=f"{name}.gcode.3mf", file_path=rel, file_size=100, file_type="gcode.3mf", file_metadata=metadata or {}
+    )
+    db_session.add(row)
+    return row
+
+
+async def _queue(async_client: AsyncClient, jwt: str, **job):
+    return await async_client.post("/api/v1/queue/", headers=_auth(jwt), json=job)
+
+
+class TestQueueFilamentScope:
+    async def test_blocked_filament_is_refused_with_its_name(self, async_client, printer_factory, archive_factory):
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "matte", PETG_MATTE)
+        friend = await _friend(async_client, await _admin_token(async_client), BLOCK_PETG_MATTE)
+
+        refused = await _queue(async_client, friend, archive_id=archive.id, printer_id=printer.id)
+        assert refused.status_code == 403, refused.text
+        assert "PETG (GFG03)" in refused.json()["detail"]
+
+    async def test_allowed_filament_is_queued(self, async_client, printer_factory, archive_factory):
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "pla", PLA)
+        friend = await _friend(async_client, await _admin_token(async_client), [{"match": "material", "value": "PETG"}])
+
+        ok = await _queue(async_client, friend, archive_id=archive.id, printer_id=printer.id)
+        assert ok.status_code == 200, ok.text
+
+    async def test_admin_is_never_refused(self, async_client, printer_factory, archive_factory):
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "admin", PETG_MATTE)
+        admin = await _admin_token(async_client)
+        await _friend(async_client, admin, BLOCK_PETG_MATTE)
+        # The admin is in the restricted group too: being an admin is what lets them through.
+        me = (await async_client.get("/api/v1/auth/me", headers=_auth(admin))).json()
+        groups = (await async_client.get("/api/v1/groups/", headers=_auth(admin))).json()
+        friends_id = next(g["id"] for g in groups if g["name"] == "friends")
+        joined = await async_client.patch(
+            f"/api/v1/users/{me['id']}",
+            headers=_auth(admin),
+            json={"group_ids": [g["id"] for g in me["groups"]] + [friends_id]},
+        )
+        assert joined.status_code == 200, joined.text
+        assert "friends" in [g["name"] for g in joined.json()["groups"]]
+
+        ok = await _queue(async_client, admin, archive_id=archive.id, printer_id=printer.id)
+        assert ok.status_code == 200, ok.text
+
+    async def test_refused_before_the_queue_is_locked(self, async_client, printer_factory, archive_factory):
+        """The 3MF is read before any lock or write (#3522)."""
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "early", PETG_MATTE)
+        friend = await _friend(async_client, await _admin_token(async_client), BLOCK_PETG_MATTE)
+
+        lock = AsyncMock()
+        with patch("backend.app.api.routes.print_queue.lock_queue_positions", lock):
+            refused = await _queue(async_client, friend, archive_id=archive.id, printer_id=printer.id, quantity=2)
+        assert refused.status_code == 403, refused.text
+        lock.assert_not_awaited()
+
+    async def test_a_library_file_is_judged_too(self, async_client, printer_factory, db_session):
+        printer = await printer_factory(name="H3C", model="X1C")
+        library_file = _library_file(db_session, "matte", PETG_MATTE)
+        await db_session.commit()
+        friend = await _friend(async_client, await _admin_token(async_client), BLOCK_PETG_MATTE)
+
+        refused = await _queue(async_client, friend, library_file_id=library_file.id, printer_id=printer.id)
+        assert refused.status_code == 403, refused.text
+        assert "PETG (GFG03)" in refused.json()["detail"]
+
+    async def test_each_cross_model_variant_is_judged(self, async_client, printer_factory, db_session):
+        """A job offered to several models is refused if any of its files is (#3522)."""
+        await printer_factory(name="S", model="H2S")
+        await printer_factory(name="C", model="H2C")
+        files = [
+            _library_file(db_session, model, filaments, {"sliced_for_model": model})
+            for model, filaments in (("H2S", PLA), ("H2C", PETG_MATTE))
+        ]
+        await db_session.commit()
+        friend = await _friend(async_client, await _admin_token(async_client), BLOCK_PETG_MATTE)
+
+        refused = await _queue(async_client, friend, variants=[{"library_file_id": f.id} for f in files])
+        assert refused.status_code == 403, refused.text
+        assert "PETG (GFG03)" in refused.json()["detail"]
+
+
+class TestOverridesAreJudgedAsTheSchedulerJudgesThem:
+    """The 403 applies the job's overrides the way the scheduler does, so both answer alike (#3522)."""
+
+    async def test_a_colour_swap_is_left_to_the_tray_matcher(self, async_client, printer_factory, archive_factory):
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "swap", PETG_MATTE)
+        friend = await _friend(async_client, await _admin_token(async_client), BLOCK_PETG_MATTE)
+
+        ok = await _queue(
+            async_client,
+            friend,
+            archive_id=archive.id,
+            printer_id=printer.id,
+            filament_overrides=[{"slot_id": 1, "type": "PETG", "color": "#000000", "force_color_match": False}],
+        )
+        assert ok.status_code == 200, ok.text
+
+    async def test_a_forced_colour_naming_a_blocked_id_is_refused(self, async_client, printer_factory, archive_factory):
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "forced", PLA)
+        friend = await _friend(async_client, await _admin_token(async_client), BLOCK_PETG_MATTE)
+
+        refused = await _queue(
+            async_client,
+            friend,
+            archive_id=archive.id,
+            printer_id=printer.id,
+            filament_overrides=[
+                {"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": "GFG03", "force_color_match": True}
+            ],
+        )
+        assert refused.status_code == 403, refused.text
+        assert "PETG (GFG03)" in refused.json()["detail"]
+
+
+class TestDeletingALimitedUser:
+    async def test_their_kept_jobs_wait_for_an_admin(self, async_client, printer_factory, archive_factory, db_session):
+        # Ownerless jobs are unrestricted, so a job held, or about to be, by
+        # the deleted user's filament rules is staged rather than released (#3522).
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "kept", PLA)
+        admin = await _admin_token(async_client)
+        friend = await _friend(async_client, admin, BLOCK_PETG_MATTE)
+        queued = await _queue(async_client, friend, archive_id=archive.id, printer_id=printer.id)
+        assert queued.status_code == 200, queued.text
+        # Released from review, as an admin would: the job is due to run.
+        await db_session.execute(
+            update(PrintQueueItem).where(PrintQueueItem.id == queued.json()["id"]).values(manual_start=False)
+        )
+        await db_session.commit()
+        friend_id = (await async_client.get("/api/v1/auth/me", headers=_auth(friend))).json()["id"]
+
+        deleted = await async_client.delete(f"/api/v1/users/{friend_id}", headers=_auth(admin))
+        assert deleted.status_code in (200, 204), deleted.text
+
+        item = (await async_client.get(f"/api/v1/queue/{queued.json()['id']}", headers=_auth(admin))).json()
+        assert (item["created_by_id"], item["manual_start"]) == (None, True)
+
+    async def test_a_deactivated_user_without_filament_rules_stages_nothing(
+        self, async_client, printer_factory, archive_factory, db_session
+    ):
+        # A deactivated user's jobs are held for that, not by a filament rule:
+        # with no rule on any of their groups, deleting them stages nothing.
+        printer, archive = await _printer_and_archive(printer_factory, archive_factory, "kept", PLA)
+        admin = await _admin_token(async_client)
+        perms = await async_client.post(
+            "/api/v1/groups/", headers=_auth(admin), json={"name": "perms", "permissions": QUEUE_PERMISSIONS}
+        )
+        created = await async_client.post(
+            "/api/v1/users/",
+            headers=_auth(admin),
+            json={"username": "leaver", "password": "UserPass1!", "group_ids": [perms.json()["id"]]},
+        )
+        assert created.status_code in (200, 201), created.text
+        leaver_id = created.json()["id"]
+        login = await async_client.post("/api/v1/auth/login", json={"username": "leaver", "password": "UserPass1!"})
+        queued = await _queue(async_client, login.json()["access_token"], archive_id=archive.id, printer_id=printer.id)
+        assert queued.status_code == 200, queued.text
+        await db_session.execute(
+            update(PrintQueueItem).where(PrintQueueItem.id == queued.json()["id"]).values(manual_start=False)
+        )
+        await db_session.commit()
+        deactivated = await async_client.patch(
+            f"/api/v1/users/{leaver_id}", headers=_auth(admin), json={"is_active": False}
+        )
+        assert deactivated.status_code == 200, deactivated.text
+
+        deleted = await async_client.delete(f"/api/v1/users/{leaver_id}", headers=_auth(admin))
+        assert deleted.status_code in (200, 204), deleted.text
+
+        item = (await async_client.get(f"/api/v1/queue/{queued.json()['id']}", headers=_auth(admin))).json()
+        assert (item["created_by_id"], item["manual_start"]) == (None, False)

+ 1 - 0
backend/tests/unit/test_ams_mapping_per_printer_2799.py

@@ -48,6 +48,7 @@ def _item(**overrides):
     item = MagicMock()
     item.id = 276
     item.printer_id = 8
+    item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
     item.ams_mapping = json.dumps(SHARED_MAPPING)
     item.skip_filament_check = False
     item.filament_overrides = None

+ 1 - 0
backend/tests/unit/test_ams_mapping_unresolved_2589.py

@@ -113,6 +113,7 @@ class TestEnsureAmsMapping:
         item = MagicMock()
         item.id = 92
         item.printer_id = 82
+        item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
         item.ams_mapping = ams_mapping
         return item
 

+ 2 - 2
backend/tests/unit/test_expected_print_rollback.py

@@ -195,7 +195,7 @@ async def test_dispatch_withdraws_the_expectation_when_start_print_raises(expect
         raise RuntimeError("remaining connection slots are reserved for roles with the SUPERUSER attribute")
 
     db = MagicMock()
-    db.get = AsyncMock(return_value=MagicMock(id=597))
+    db.get = AsyncMock(return_value=MagicMock(id=597, created_by_id=None))
     ctx = MagicMock()
     ctx.__aenter__ = AsyncMock(return_value=db)
     ctx.__aexit__ = AsyncMock(return_value=False)
@@ -234,7 +234,7 @@ async def test_dispatch_keeps_the_expectation_when_the_print_was_sent(expected_p
         sched._unconfirmed_expected_print.pop(597, None)  # start_print() returned True
 
     db = MagicMock()
-    db.get = AsyncMock(return_value=MagicMock(id=597))
+    db.get = AsyncMock(return_value=MagicMock(id=597, created_by_id=None))
     ctx = MagicMock()
     ctx.__aenter__ = AsyncMock(return_value=db)
     ctx.__aexit__ = AsyncMock(return_value=False)

+ 1 - 0
backend/tests/unit/test_external_mapping_on_ams_printer_3239.py

@@ -48,6 +48,7 @@ def _item():
     item = MagicMock()
     item.id = 2453
     item.printer_id = None
+    item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
     item.ams_mapping = json.dumps([254])
     item.skip_filament_check = False
     item.filament_overrides = None

+ 1 - 1
backend/tests/unit/test_failed_start_releases_printer.py

@@ -172,7 +172,7 @@ async def test_a_dispatch_that_never_sends_releases_the_print_user(clean_state):
         sched._unconfirmed_print_user[597] = PRINTER
 
     db = MagicMock()
-    db.get = AsyncMock(return_value=MagicMock(id=597, printer_id=PRINTER))
+    db.get = AsyncMock(return_value=MagicMock(id=597, printer_id=PRINTER, created_by_id=None))
     ctx = MagicMock()
     ctx.__aenter__ = AsyncMock(return_value=db)
     ctx.__aexit__ = AsyncMock(return_value=False)

+ 271 - 0
backend/tests/unit/test_filament_scope.py

@@ -0,0 +1,271 @@
+"""FilamentScope semantics (#3522)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from fastapi import HTTPException
+
+from backend.app.core.filament_scope import (
+    ALL_FILAMENTS,
+    NO_FILAMENTS,
+    FilamentRule,
+    FilamentScope,
+    GroupFilamentPolicy,
+    clean_rules,
+    describe_filament,
+    ensure_requirements_allowed,
+    judged_requirements,
+    policy_for_group,
+    resolve_user_filament_scope,
+    resolve_user_id_filament_scope,
+)
+
+PETG = FilamentRule("material", "PETG")
+PETG_MATTE = FilamentRule("filament_id", "GFG03")
+
+
+def _block(*rules):
+    return GroupFilamentPolicy("Friends", "block", tuple(rules))
+
+
+def _allow(*rules):
+    return GroupFilamentPolicy("Friends", "allow", tuple(rules))
+
+
+class TestRule:
+    def test_material_matches_case_insensitively_and_exactly(self):
+        assert PETG.matches("petg", None)
+        assert PETG.matches(" PETG ", "")
+        assert not PETG.matches("PETG-HF", None)
+
+    def test_filament_id_matches_the_tray_info_idx(self):
+        assert PETG_MATTE.matches("PETG", "gfg03")
+        assert not PETG_MATTE.matches("PETG", "GFG99")
+        assert not PETG_MATTE.matches("PETG", None)
+
+    def test_empty_value_matches_nothing(self):
+        assert not FilamentRule("material", " ").matches("", "")
+
+
+class TestPolicy:
+    def test_block_list_allows_what_it_does_not_name(self):
+        policy = _block(PETG_MATTE)
+        assert not policy.allows("PETG", "GFG03")
+        assert policy.allows("PETG", "GFG99")
+
+    def test_allow_list_allows_only_what_it_names(self):
+        policy = _allow(FilamentRule("material", "PLA"))
+        assert policy.allows("PLA", "GFA00")
+        assert not policy.allows("PETG", "GFG03")
+
+
+class TestScope:
+    def test_unrestricted_allows_everything(self):
+        assert ALL_FILAMENTS.is_unrestricted
+        assert ALL_FILAMENTS.allows("PAHT-CF", "GFN03")
+
+    def test_union_of_groups(self):
+        scope = FilamentScope((_allow(FilamentRule("material", "PLA")), _allow(FilamentRule("material", "PETG"))))
+        assert scope.allows("PLA", None)
+        assert scope.allows("PETG", None)
+        assert not scope.allows("ABS", None)
+
+    def test_block_group_does_not_narrow_an_allow_group(self):
+        # Allowed by any restricted group means allowed.
+        scope = FilamentScope((_block(PETG), _allow(PETG)))
+        assert scope.allows("PETG", None)
+
+    def test_unidentifiable_filament_is_allowed(self):
+        assert FilamentScope((_allow(FilamentRule("material", "PLA")),)).allows("", "")
+        assert NO_FILAMENTS.allows(None, None)
+
+    def test_no_policies_allows_nothing_identifiable(self):
+        assert not NO_FILAMENTS.allows("PLA", None)
+
+    def test_blocked_requirements_and_trays(self):
+        scope = FilamentScope((_block(PETG_MATTE),))
+        reqs = [
+            {"slot_id": 1, "type": "PETG", "tray_info_idx": "GFG03"},
+            {"slot_id": 2, "type": "PLA", "tray_info_idx": "GFA00"},
+        ]
+        assert [r["slot_id"] for r in scope.blocked_requirements(reqs)] == [1]
+        loaded = [
+            {"type": "PETG", "tray_info_idx": "GFG03", "global_tray_id": 0},
+            {"type": "PETG", "tray_info_idx": "GFG99", "global_tray_id": 1},
+        ]
+        assert scope.blocked_tray_ids(loaded) == {0}
+
+
+class TestCleanRules:
+    def test_strips_dedupes_and_drops_junk(self):
+        raw = [
+            {"match": "material", "value": " petg "},
+            {"match": "material", "value": "PETG"},
+            {"match": "filament_id", "value": "GFG03"},
+            {"match": "colour", "value": "red"},
+            {"match": "material", "value": ""},
+            "junk",
+        ]
+        assert clean_rules(raw) == [
+            {"match": "material", "value": "PETG"},
+            {"match": "filament_id", "value": "GFG03"},
+        ]
+
+    def test_accepts_objects_with_attributes(self):
+        assert clean_rules([SimpleNamespace(match="filament_id", value="GFG03")]) == [
+            {"match": "filament_id", "value": "GFG03"}
+        ]
+
+
+def _group(name, restrict, mode="block", rules=None):
+    return SimpleNamespace(name=name, restrict_filaments=restrict, filament_rule_mode=mode, filament_rules=rules)
+
+
+class TestResolveUser:
+    def test_admin_is_unrestricted(self):
+        user = SimpleNamespace(
+            is_admin=True, groups=[_group("Friends", True, rules=[{"match": "material", "value": "PETG"}])]
+        )
+        assert resolve_user_filament_scope(user).is_unrestricted
+
+    def test_user_in_no_restricted_group_is_unrestricted(self):
+        user = SimpleNamespace(is_admin=False, groups=[_group("Operators", False)])
+        assert resolve_user_filament_scope(user).is_unrestricted
+
+    def test_only_restricted_groups_count(self):
+        user = SimpleNamespace(
+            is_admin=False,
+            groups=[
+                _group("Operators", False),
+                _group("Friends", True, rules=[{"match": "material", "value": "PETG"}]),
+            ],
+        )
+        scope = resolve_user_filament_scope(user)
+        assert not scope.allows("PETG", None)
+        assert scope.allows("PLA", None)
+
+    def test_policy_for_group_tolerates_missing_values(self):
+        policy = policy_for_group(_group("Friends", True, mode=None, rules=None))
+        assert policy.mode == "block"
+        assert policy.rules == ()
+
+
+class TestMessages:
+    def test_describe(self):
+        assert describe_filament({"type": "PETG", "tray_info_idx": "GFG03"}) == "PETG (GFG03)"
+        assert describe_filament({"type": "PLA", "tray_info_idx": ""}) == "PLA"
+        assert describe_filament({"type": "", "tray_info_idx": "GFG03"}) == "GFG03"
+
+    def test_ensure_raises_403_naming_the_filament(self):
+        scope = FilamentScope((_block(PETG_MATTE),))
+        with pytest.raises(HTTPException) as exc:
+            ensure_requirements_allowed(scope, [{"type": "PETG", "tray_info_idx": "GFG03"}])
+        assert exc.value.status_code == 403
+        assert "PETG (GFG03)" in exc.value.detail
+
+    def test_ensure_passes_when_allowed(self):
+        ensure_requirements_allowed(ALL_FILAMENTS, [{"type": "PETG", "tray_info_idx": "GFG03"}])
+
+    def test_ensure_passes_a_restricted_user_whose_filaments_are_all_allowed(self):
+        scope = FilamentScope((_block(PETG_MATTE),))
+        ensure_requirements_allowed(
+            scope, [{"type": "PETG", "tray_info_idx": "GFG99"}, {"type": "PLA", "tray_info_idx": "GFA00"}]
+        )
+
+
+async def _resolve_id(user, *, auth_enabled: bool = True, user_id: int | None = 7):
+    result = MagicMock()
+    result.scalar_one_or_none.return_value = user
+    db = MagicMock()
+    db.execute = AsyncMock(return_value=result)
+    with patch("backend.app.core.auth.is_auth_enabled", AsyncMock(return_value=auth_enabled)):
+        return await resolve_user_id_filament_scope(db, user_id), db
+
+
+def _restricted_user(**fields):
+    group = SimpleNamespace(
+        name="Friends",
+        restrict_filaments=True,
+        filament_rule_mode="block",
+        filament_rules=[{"match": "filament_id", "value": "GFG03"}],
+    )
+    values = {"is_admin": False, "is_active": True, "groups": [group]}
+    values.update(fields)
+    return SimpleNamespace(**values)
+
+
+@pytest.mark.asyncio
+class TestResolveUserId:
+    """The scheduler and the queue route read a scope by user id (#3522)."""
+
+    async def test_auth_off_is_unrestricted_without_a_lookup(self):
+        scope, db = await _resolve_id(_restricted_user(), auth_enabled=False)
+        assert scope is ALL_FILAMENTS
+        db.execute.assert_not_awaited()
+
+    async def test_no_user_is_unrestricted(self):
+        scope, db = await _resolve_id(_restricted_user(), user_id=None)
+        assert scope is ALL_FILAMENTS
+        db.execute.assert_not_awaited()
+
+    async def test_a_deactivated_user_may_use_nothing_identifiable(self):
+        scope, _ = await _resolve_id(_restricted_user(is_active=False))
+        assert scope is NO_FILAMENTS
+
+    async def test_a_deleted_user_may_use_nothing_identifiable(self):
+        scope, _ = await _resolve_id(None)
+        assert scope is NO_FILAMENTS
+
+    async def test_an_active_user_gets_their_groups_rules(self):
+        scope, _ = await _resolve_id(_restricted_user())
+        assert not scope.allows("PETG", "GFG03")
+        assert scope.allows("PETG", "GFG99")
+
+
+# The print dialog's copy of these rules (``frontend/src/utils/filamentScope.ts``)
+# reads the same cases, so the two can't disagree on a filament.
+_SHARED_CASES = (
+    Path(__file__).resolve().parents[3] / "frontend" / "src" / "__tests__" / "utils" / "filamentScopeCases.json"
+)
+
+
+@pytest.mark.parametrize("case", json.loads(_SHARED_CASES.read_text())["cases"], ids=lambda c: c["name"])
+def test_shared_cases_with_the_print_dialog(case):
+    rules = tuple(FilamentRule(r["match"], r["value"]) for r in case["rules"])
+    scope = FilamentScope((GroupFilamentPolicy("Friends", case["mode"], rules),))
+    assert scope.allows(case["type"], case["filament_id"]) is case["allowed"]
+
+
+class TestJudgedRequirements:
+    """One rule for overrides wherever a file is judged: the queue route, the scheduler, the dialog (#3522)."""
+
+    REQS = [
+        {"slot_id": 1, "type": "PETG", "tray_info_idx": "GFG03"},
+        {"slot_id": 2, "type": "PLA", "tray_info_idx": "GFA00"},
+    ]
+
+    def test_without_overrides_the_file_is_judged_as_sliced(self):
+        assert judged_requirements(self.REQS, None) == self.REQS
+
+    def test_a_swap_is_left_to_the_tray_matcher(self):
+        swap = [{"slot_id": 1, "type": "PETG", "color": "#000000", "force_color_match": False}]
+        assert judged_requirements(self.REQS, swap) == [self.REQS[1]]
+
+    def test_a_forced_colour_naming_an_id_is_judged_as_it_names_it(self):
+        forced = [{"slot_id": 2, "type": "PETG", "tray_info_idx": "GFG03", "force_color_match": True}]
+        assert judged_requirements(self.REQS, forced) == [
+            self.REQS[0],
+            {"slot_id": 2, "type": "PETG", "tray_info_idx": "GFG03"},
+        ]
+
+    def test_a_forced_colour_naming_no_id_is_left_to_the_tray_matcher(self):
+        forced = [{"slot_id": 1, "type": "PETG", "force_color_match": True}]
+        assert judged_requirements(self.REQS, forced) == [self.REQS[1]]
+
+    def test_junk_entries_are_ignored(self):
+        assert judged_requirements(self.REQS, ["x", {"slot_id": True}, {"type": "PLA"}]) == self.REQS

+ 1 - 0
backend/tests/unit/test_force_color_pinned_3280.py

@@ -38,6 +38,7 @@ def _item(**overrides):
     item = MagicMock()
     item.id = 495
     item.printer_id = 4
+    item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
     item.archive_id = 460
     item.library_file_id = None
     item.plate_id = None

+ 1 - 1
backend/tests/unit/test_library_dispatch_reuses_archive.py

@@ -374,7 +374,7 @@ async def test_the_dispatch_releases_its_archive_when_it_ends(fails):
 
     scheduler._hold_archive(600, 300)
     db = MagicMock()
-    db.get = AsyncMock(return_value=MagicMock(id=597))
+    db.get = AsyncMock(return_value=MagicMock(id=597, created_by_id=None))
     session = MagicMock()
     session.__aenter__ = AsyncMock(return_value=db)
     session.__aexit__ = AsyncMock(return_value=False)

+ 2 - 0
backend/tests/unit/test_model_path_unmatched_filament.py

@@ -146,6 +146,7 @@ class TestUnmatchedOn:
             "archive_id": None,
             "library_file_id": 3,
             "plate_id": 1,
+            "created_by_id": None,  # no creator: unrestricted filament scope (#3522)
         }
         values.update(fields)
         return SimpleNamespace(**values)
@@ -230,6 +231,7 @@ class TestDualNozzleEndToEnd:
         item = MagicMock()
         item.id = 9
         item.printer_id = 4
+        item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
         item.archive_id = None
         item.library_file_id = 3
         item.plate_id = 1

+ 1 - 0
backend/tests/unit/test_printer_job_force_color_3445.py

@@ -34,6 +34,7 @@ def _item(overrides):
     item = MagicMock()
     item.id = 74
     item.printer_id = 2
+    item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
     item.ams_mapping = json.dumps([1])
     item.skip_filament_check = False
     item.filament_overrides = json.dumps(overrides) if overrides is not None else None

+ 1 - 1
backend/tests/unit/test_scheduler_backup_gate.py

@@ -34,7 +34,7 @@ async def _run_with_backup(scheduler, backup_state, prefer_lowest_setting):
     """Drive ``_compute_ams_mapping_for_printer`` past the gate point and
     return whatever ``prefer_lowest`` value gets handed to the matcher."""
     db = MagicMock()
-    item = SimpleNamespace(filament_overrides=None)
+    item = SimpleNamespace(filament_overrides=None, created_by_id=None)
     filament_reqs = [{"slot_id": 1, "type": "PLA", "color": "#000000", "tray_info_idx": ""}]
     loaded = [
         {

+ 1 - 0
backend/tests/unit/test_scheduler_external_spool_nozzle_2771.py

@@ -158,6 +158,7 @@ class TestUnmappableWithoutAmsGuard:
         item = MagicMock()
         item.id = 22
         item.printer_id = 4
+        item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
         item.ams_mapping = ams_mapping
         item.filament_overrides = None
         return item

+ 367 - 0
backend/tests/unit/test_scheduler_filament_hold_3522.py

@@ -0,0 +1,367 @@
+"""check_queue holds a job its creator may not print, and starts it once allowed (#3522).
+
+Run on a real database with the dispatch drained, as the printer-scope hold
+(#1727) is in ``test_scheduler_check_queue_holds.py``: the job stays pending
+with a reason naming the filament, is never failed, and goes out on its own
+on the first pass after the group's rules stop blocking it.
+"""
+
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from sqlalchemy import update
+
+import backend.app.services.print_scheduler as scheduler_module
+from backend.app.models.group import Group
+from backend.app.models.print_queue import PrintQueueItem
+from backend.app.models.printer import Printer
+from backend.app.models.settings import Settings
+from backend.app.models.user import User
+from backend.app.services.print_scheduler import PrintScheduler
+from backend.tests.unit.test_scheduler_busy_reasons_3018 import _scheduler, one_printer  # noqa: F401
+from backend.tests.unit.test_scheduler_filament_scope_3522 import (
+    FILE_NEEDS_PETG_MATTE,
+    REQ_PETG_MATTE,
+    REQ_WHITE_PETG,
+    SPOOL_IS_PETG_MATTE,
+    _external,
+    _tray,
+)
+
+
+async def _job_by_a_creator_blocked_from_petg_matte(ctx, **fields) -> tuple[int, int]:
+    """Queue a job created by a user whose group blocks PETG Matte; returns (item id, group id)."""
+    async with ctx.session_maker() as db:
+        db.add(Settings(key="auth_enabled", value="true"))
+        group = Group(
+            name="friends",
+            permissions=["queue:create"],
+            restrict_filaments=True,
+            filament_rule_mode="block",
+            filament_rules=[{"match": "filament_id", "value": "GFG03"}],
+        )
+        user = User(username="friend", password_hash="x", is_active=True, groups=[group])
+        db.add_all([group, user])
+        await db.commit()
+    item_id = await ctx.add_item()
+    async with ctx.session_maker() as db:
+        await db.execute(
+            update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(created_by_id=user.id, **fields)
+        )
+        await db.commit()
+    return item_id, group.id
+
+
+async def _load(ctx, item_id: int) -> PrintQueueItem:
+    async with ctx.session_maker() as db:
+        return await db.get(PrintQueueItem, item_id)
+
+
+async def _lift_the_rule(session_maker, group_id: int) -> None:
+    async with session_maker() as db:
+        await db.execute(update(Group).where(Group.id == group_id).values(filament_rules=[]))
+        await db.commit()
+
+
+def _file_prints_petg_matte():
+    return patch.object(PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(REQ_PETG_MATTE)]))
+
+
+class TestAJobOnAFixedPrinter:
+    @pytest.mark.asyncio
+    async def test_is_held_then_starts_once_the_rule_is_lifted(self, one_printer):  # noqa: F811
+        item_id, group_id = await _job_by_a_creator_blocked_from_petg_matte(one_printer)
+
+        # One scheduler for both passes, as in production: each pass must read
+        # the group's rules afresh, not keep the last pass's answer.
+        with _file_prints_petg_matte():
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                await scheduler.check_queue()
+                assert not scheduler._inflight
+
+                item = await _load(one_printer, item_id)
+                assert item.status == "pending"
+                assert item.waiting_reason == FILE_NEEDS_PETG_MATTE
+                assert not item.manual_start
+                assert item.error_message is None
+
+                await _lift_the_rule(one_printer.session_maker, group_id)
+                await scheduler.check_queue()
+
+        item = await _load(one_printer, item_id)
+        assert item.status != "pending"
+        assert item.status != "failed"
+
+
+class TestAJobForAnyPrinterOfAModel:
+    @pytest.mark.asyncio
+    async def test_is_held_unassigned_then_starts_once_the_rule_is_lifted(self, one_printer):  # noqa: F811
+        item_id, group_id = await _job_by_a_creator_blocked_from_petg_matte(
+            one_printer, printer_id=None, target_model="X1C"
+        )
+
+        with (
+            _file_prints_petg_matte(),
+            patch(
+                "backend.app.services.notification_service.notification_service.on_queue_job_assigned",
+                AsyncMock(),
+            ) as assigned,
+            patch(
+                "backend.app.services.notification_service.notification_service.on_queue_job_waiting",
+                AsyncMock(),
+            ),
+        ):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                await scheduler.check_queue()
+                assert not scheduler._inflight
+
+                item = await _load(one_printer, item_id)
+                assert (item.status, item.printer_id) == ("pending", None)
+                assert item.waiting_reason == FILE_NEEDS_PETG_MATTE
+                # Never assigned to a printer only to be given back on every pass.
+                assigned.assert_not_awaited()
+
+                await _lift_the_rule(one_printer.session_maker, group_id)
+                await scheduler.check_queue()
+
+        item = await _load(one_printer, item_id)
+        assert item.status not in ("pending", "failed")
+
+
+class TestAnEditBetweenTheCheckAndTheClaim:
+    """The pass judges the job as loaded; dispatch sends the row as claimed (#3522).
+
+    An edit landing in between must not carry the job onto a blocked spool:
+    it is re-judged once claimed, when edits are refused, and left to the
+    next pass, which holds it.
+    """
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        "edit",
+        [
+            # Without the AMS the blocked external spool would feed.
+            {"use_ams": False, "ams_mapping": "[254]"},
+            # A real tray turns the AMS back on (#2595): the blocked tray would feed.
+            {"use_ams": False, "ams_mapping": "[0]"},
+            {"ams_mapping": "[0]"},
+        ],
+        ids=["use_ams_off_onto_the_external_spool", "use_ams_off_onto_a_blocked_tray", "blocked_tray"],
+    )
+    async def test_is_not_dispatched_as_edited(self, one_printer, edit):  # noqa: F811
+        item_id, _ = await _job_by_a_creator_blocked_from_petg_matte(one_printer)
+
+        # Tray 1 is allowed and is what the pass maps the slot to; tray 0 and
+        # the external spool hold PETG Matte, which the group blocks.
+        loaded = [_tray(0, "GFG03"), _tray(1, "GFG99"), _external(254, "GFG03")]
+
+        with (
+            patch.object(PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(REQ_WHITE_PETG)])),
+            patch.object(PrintScheduler, "_build_loaded_filaments", lambda self, status: [dict(f) for f in loaded]),
+        ):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                real_claim = scheduler._claim_for_dispatch
+
+                async def claim_after_an_edit(db, claimed_id, printer_id=None):
+                    async with one_printer.session_maker() as edit_db:
+                        await edit_db.execute(
+                            update(PrintQueueItem).where(PrintQueueItem.id == claimed_id).values(**edit)
+                        )
+                        await edit_db.commit()
+                    return await real_claim(db, claimed_id, printer_id)
+
+                clear_claim = AsyncMock(wraps=scheduler._clear_dispatch_claim)
+                with (
+                    patch.object(scheduler, "_claim_for_dispatch", claim_after_an_edit),
+                    patch.object(scheduler, "_clear_dispatch_claim", clear_claim),
+                ):
+                    await scheduler.check_queue()
+                    if scheduler._inflight:
+                        await asyncio.gather(*(t for t, _ in scheduler._inflight.values()), return_exceptions=True)
+                start_print = scheduler_module.printer_manager.start_print
+                start_print.assert_not_called()
+                # The claim is backed out, as on every exit from a dispatch.
+                assert [c.args[1] for c in clear_claim.await_args_list] == [item_id]
+
+            async with one_printer.session_maker() as db:
+                assert (await db.get(PrintQueueItem, item_id)).status == "pending"
+                # The harness's in-memory SQLite shares one connection between
+                # sessions (StaticPool), so the pass closing its session can
+                # roll back the clear the dispatch task just wrote. Done again
+                # here so the next pass can claim the row, as it could in
+                # production.
+                await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
+                await db.commit()
+
+            # A stored blocked tray is re-picked onto the allowed one (#3522),
+            # which feeds from the AMS whatever use_ams says.
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                await scheduler.check_queue()
+                await asyncio.gather(*(t for t, _ in scheduler._inflight.values()), return_exceptions=True)
+                start_print = scheduler_module.printer_manager.start_print
+                assert start_print.call_args.kwargs["ams_mapping"] == [1]
+
+
+def _spools(loaded):
+    """The printer's spools as ``_build_loaded_filaments`` reports them."""
+    return patch.object(PrintScheduler, "_build_loaded_filaments", lambda self, status: [dict(f) for f in loaded])
+
+
+def _assignment_notifications():
+    return (
+        patch(
+            "backend.app.services.notification_service.notification_service.on_queue_job_assigned",
+            AsyncMock(),
+        ),
+        patch(
+            "backend.app.services.notification_service.notification_service.on_queue_job_waiting",
+            AsyncMock(),
+        ),
+    )
+
+
+class TestAModelJobWithoutTheAms:
+    """The model branch judges the external spool before assigning a printer (#3522)."""
+
+    @pytest.mark.asyncio
+    async def test_on_a_dual_nozzle_printer_a_blocked_external_spool_holds_it_unassigned(self, one_printer):  # noqa: F811
+        # use_ams picks the extruder there, so every external spool counts.
+        async with one_printer.session_maker() as db:
+            await db.execute(update(Printer).where(Printer.id == one_printer.printer_id).values(model="H2D"))
+            await db.commit()
+        item_id, _ = await _job_by_a_creator_blocked_from_petg_matte(
+            one_printer, printer_id=None, target_model="H2D", use_ams=False
+        )
+
+        assigned_patch, waiting_patch = _assignment_notifications()
+        with (
+            patch.object(PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(REQ_WHITE_PETG)])),
+            _spools([_tray(1, "GFG99"), _external(254, "GFG03")]),
+            assigned_patch as assigned,
+            waiting_patch as waiting,
+        ):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                for _ in range(2):
+                    await scheduler.check_queue()
+                    assert not scheduler._inflight
+
+        item = await _load(one_printer, item_id)
+        assert (item.status, item.printer_id) == ("pending", None)
+        assert item.waiting_reason == SPOOL_IS_PETG_MATTE
+        # Not assigned only to be given back on every pass.
+        assigned.assert_not_awaited()
+        # Held before a printer is assigned, the job says so once, as any
+        # waiting model job does. Held only after the assignment, it would
+        # be given back without a word.
+        waiting.assert_awaited_once()
+        assert waiting.await_args.kwargs["waiting_reason"] == SPOOL_IS_PETG_MATTE
+
+    @pytest.mark.asyncio
+    async def test_on_a_single_nozzle_printer_the_ams_tray_it_is_sent_decides(self, one_printer):  # noqa: F811
+        # A real tray in the mapping turns the AMS back on (#2595), so the
+        # blocked spool on the holder isn't fed and holds nothing.
+        item_id, _ = await _job_by_a_creator_blocked_from_petg_matte(
+            one_printer, printer_id=None, target_model="X1C", use_ams=False
+        )
+
+        assigned_patch, waiting_patch = _assignment_notifications()
+        with (
+            patch.object(PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(REQ_WHITE_PETG)])),
+            _spools([_tray(1, "GFG99"), _external(254, "GFG03")]),
+            assigned_patch,
+            waiting_patch,
+        ):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                await scheduler.check_queue()
+                await asyncio.gather(*(t for t, _ in scheduler._inflight.values()), return_exceptions=True)
+                start_print = scheduler_module.printer_manager.start_print
+                assert start_print.call_args.kwargs["ams_mapping"] == [1]
+
+
+class TestAnEditToUseAms:
+    @pytest.mark.asyncio
+    async def test_counts_as_an_edit_since_the_pass_loaded_the_job(self, one_printer):  # noqa: F811
+        # use_ams decides the feed the filament check judges (#3522), so a
+        # pass must not act on a job whose use_ams changed under it.
+        item_id = await one_printer.add_item()
+        async with one_printer.session_maker() as db:
+            item = await db.get(PrintQueueItem, item_id)
+            assert not await scheduler_module._edited_since_loaded(db, item)
+            async with one_printer.session_maker() as edit_db:
+                await edit_db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(use_ams=False))
+                await edit_db.commit()
+            assert await scheduler_module._edited_since_loaded(db, item)
+
+
+class TestAJobHeldByALoadedSpool:
+    @pytest.mark.asyncio
+    async def test_starts_once_the_spool_is_swapped(self, one_printer):  # noqa: F811
+        # Sent without the AMS, the job prints from the holder; no AMS tray
+        # matches, so nothing turns the AMS back on.
+        item_id, _ = await _job_by_a_creator_blocked_from_petg_matte(one_printer, use_ams=False)
+        loaded = [_tray(1, "GFA00", "PLA"), _external(254, "GFG03")]
+
+        with (
+            patch.object(PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(REQ_WHITE_PETG)])),
+            patch.object(PrintScheduler, "_build_loaded_filaments", lambda self, status: [dict(f) for f in loaded]),
+        ):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                await scheduler.check_queue()
+                assert not scheduler._inflight
+                item = await _load(one_printer, item_id)
+                assert (item.status, item.waiting_reason) == ("pending", SPOOL_IS_PETG_MATTE)
+
+                loaded[1] = _external(254, "GFG99")
+                await scheduler.check_queue()
+                await asyncio.gather(*(t for t, _ in scheduler._inflight.values()), return_exceptions=True)
+                start_print = scheduler_module.printer_manager.start_print
+                assert start_print.call_args.kwargs["ams_mapping"] == [254]
+
+
+class TestAModelJobHeldOnceAssigned:
+    @pytest.mark.asyncio
+    async def test_is_released_back_to_the_pool_not_failed_and_never_announced(self, one_printer):  # noqa: F811
+        # A file with no readable filament list passes every check made while
+        # choosing a printer; once assigned, the printer's blocked tray holds
+        # it, and "any X1C" means any, so the printer is given back. That
+        # repeats on every pass, so "assigned" is only announced once the job
+        # has passed the checks that follow the assignment.
+        item_id, _ = await _job_by_a_creator_blocked_from_petg_matte(one_printer, printer_id=None, target_model="X1C")
+
+        assigned_patch, waiting_patch = _assignment_notifications()
+        with (
+            patch.object(PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=None)),
+            _spools([_tray(0, "GFG03"), _tray(1, "GFG99")]),
+            assigned_patch as assigned,
+            waiting_patch,
+        ):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                for _ in range(2):
+                    await scheduler.check_queue()
+                    assert not scheduler._inflight
+        assigned.assert_not_awaited()
+
+        item = await _load(one_printer, item_id)
+        assert (item.status, item.printer_id, item.error_message) == ("pending", None, None)
+        assert item.waiting_reason == (
+            "This file doesn't list its filaments, and the printer has a loaded spool "
+            "the job creator's group can't print with: PETG (GFG03)"
+        )
+
+
+class TestAJobWhoseFileIsGone:
+    @pytest.mark.asyncio
+    async def test_fails_as_missing_instead_of_waiting_as_unlisted(self, one_printer):  # noqa: F811
+        # A missing file lists no filaments either, but there is nothing to
+        # judge or print: it takes the dispatch's missing-file failure.
+        item_id, _ = await _job_by_a_creator_blocked_from_petg_matte(one_printer)
+        (one_printer.base_dir / "archives" / "job-0.3mf").unlink()
+
+        with _spools([_tray(0, "GFG03")]):
+            async with _scheduler(one_printer, idle=True) as scheduler:
+                await scheduler.check_queue()
+
+        item = await _load(one_printer, item_id)
+        assert item.status == "failed"
+        assert "can't print with" not in (item.waiting_reason or "")

+ 670 - 0
backend/tests/unit/test_scheduler_filament_scope_3522.py

@@ -0,0 +1,670 @@
+"""The scheduler holds a job to its creator's filament scope (#3522)."""
+
+from __future__ import annotations
+
+import json
+from contextlib import ExitStack
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+import backend.app.services.print_scheduler as scheduler_module
+from backend.app.core.filament_scope import ALL_FILAMENTS, FilamentRule, FilamentScope, GroupFilamentPolicy
+from backend.app.models.print_queue import PrintQueueItem
+from backend.app.services.print_scheduler import FilamentScopeHold, PrintScheduler
+
+BLOCK_PETG_MATTE = FilamentScope((GroupFilamentPolicy("Friends", "block", (FilamentRule("filament_id", "GFG03"),)),))
+# A hold names who may not print it in the third person: an admin reads it too.
+FILE_NEEDS_PETG_MATTE = "This file needs a filament the job creator's group can't print with: PETG (GFG03)"
+SPOOL_IS_PETG_MATTE = "It would print from a loaded spool the job creator's group can't print with: PETG (GFG03)"
+
+
+def _tray(global_id: int, tray_info_idx: str, filament_type: str = "PETG") -> dict:
+    return {
+        "type": filament_type,
+        "color": "#FFFFFF",
+        "color_known": True,
+        "tray_info_idx": tray_info_idx,
+        "ams_id": 0,
+        "tray_id": global_id,
+        "is_ht": False,
+        "is_external": False,
+        "global_tray_id": global_id,
+        "extruder_id": None,
+        "remain": 80,
+    }
+
+
+def _external(global_id: int, tray_info_idx: str, filament_type: str = "PETG") -> dict:
+    return {**_tray(global_id, tray_info_idx, filament_type), "ams_id": -1, "tray_id": 0, "is_external": True}
+
+
+REQ_WHITE_PETG = {"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": "", "used_grams": 10.0}
+REQ_PETG_MATTE = {"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": "GFG03", "used_grams": 10.0}
+REQ_WHITE_PLA = {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "tray_info_idx": "", "used_grams": 10.0}
+
+
+def _item(**kwargs) -> PrintQueueItem:
+    defaults = {"id": 1, "printer_id": 1, "archive_id": 1, "created_by_id": 7, "plate_id": None}
+    defaults.update(kwargs)
+    return PrintQueueItem(**defaults)
+
+
+async def _run(
+    call,
+    scope=BLOCK_PETG_MATTE,
+    *,
+    requirements=(REQ_WHITE_PETG,),
+    loaded,
+    printer_model="X1C",
+    raw_data=None,
+    source: Path | None = None,
+):
+    """Await ``call(scheduler)`` with the creator's scope, the file and the printer's spools stubbed."""
+    status = SimpleNamespace(raw_data=raw_data or {}, fila_switch=None, ams_filament_backup=None)
+    patches = [
+        patch.object(PrintScheduler, "_get_printer", AsyncMock(return_value=SimpleNamespace(model=printer_model))),
+        patch.object(scheduler_module, "resolve_user_id_filament_scope", AsyncMock(return_value=scope)),
+        patch.object(scheduler_module.printer_manager, "get_status", MagicMock(return_value=status)),
+        patch.object(
+            PrintScheduler, "_get_filament_requirements", AsyncMock(return_value=[dict(r) for r in requirements])
+        ),
+        patch.object(PrintScheduler, "_build_loaded_filaments", MagicMock(return_value=loaded)),
+        patch.object(PrintScheduler, "_get_bool_setting", AsyncMock(return_value=False)),
+        # The job's file is on disk: this module stands in for it.
+        patch.object(PrintScheduler, "_source_file_path", AsyncMock(return_value=source or Path(__file__))),
+    ]
+    with ExitStack() as stack:
+        for p in patches:
+            stack.enter_context(p)
+        return await call(PrintScheduler())
+
+
+def _compute(item=None):
+    return lambda sched: sched._compute_ams_mapping_for_printer(AsyncMock(), 1, item or _item())
+
+
+def _violation(item=None):
+    return lambda sched: sched._filament_scope_violation(AsyncMock(), item or _item())
+
+
+def _ensure(item):
+    return lambda sched: sched._ensure_ams_mapping(AsyncMock(), 1, item)
+
+
+@pytest.mark.asyncio
+class TestMappingSkipsBlockedTrays:
+    @pytest.mark.parametrize(
+        ("scope", "loaded", "mapping"),
+        [
+            pytest.param(BLOCK_PETG_MATTE, [_tray(0, "GFG03"), _tray(1, "GFG99")], [1], id="blocked_tray_never_chosen"),
+            pytest.param(BLOCK_PETG_MATTE, [_tray(0, "GFG03")], None, id="only_blocked_trays_means_no_mapping"),
+            pytest.param(ALL_FILAMENTS, [_tray(0, "GFG03")], [0], id="unrestricted_creator_may_use_any_tray"),
+        ],
+    )
+    async def test_mapping(self, scope, loaded, mapping):
+        assert await _run(_compute(), scope, loaded=loaded) == mapping
+
+
+@pytest.mark.asyncio
+class TestViolation:
+    @pytest.mark.parametrize(
+        ("scope", "requirements", "message"),
+        [
+            pytest.param(BLOCK_PETG_MATTE, [REQ_PETG_MATTE], FILE_NEEDS_PETG_MATTE, id="file_needs_a_blocked_filament"),
+            pytest.param(BLOCK_PETG_MATTE, [REQ_WHITE_PETG], None, id="allowed_file"),
+            pytest.param(ALL_FILAMENTS, [REQ_PETG_MATTE], None, id="unrestricted_skips_the_check"),
+        ],
+    )
+    async def test_violation(self, scope, requirements, message):
+        loaded = [_tray(0, "GFG03"), _tray(1, "GFG99")]
+        assert await _run(_violation(), scope, requirements=requirements, loaded=loaded) == message
+
+
+@pytest.mark.asyncio
+class TestStoredMappingOnBlockedTray:
+    @pytest.mark.parametrize("print_anyway", [False, True], ids=["checked", "print_anyway"])
+    async def test_is_recomputed_onto_an_allowed_tray(self, print_anyway):
+        # "Print anyway" skips the filament check, but never keeps a blocked tray.
+        item = _item(ams_mapping=json.dumps([0]), skip_filament_check=print_anyway)
+        result = await _run(_ensure(item), loaded=[_tray(0, "GFG03"), _tray(1, "GFG99")])
+        assert result is None
+        assert json.loads(item.ams_mapping)[0] == 1
+
+    @pytest.mark.parametrize(("stored", "uses_blocked"), [([1], False), ([0], True)], ids=["allowed", "blocked"])
+    async def test_mapping_uses_blocked_tray(self, stored, uses_blocked):
+        uses = await _run(
+            lambda sched: sched._mapping_uses_blocked_tray(AsyncMock(), 1, _item(), stored),
+            loaded=[_tray(0, "GFG03"), _tray(1, "GFG99")],
+        )
+        assert uses is uses_blocked
+
+
+def _force_override(tray_info_idx: str) -> str:
+    """A ``force_color_match`` override for slot 1, white PETG, as the print dialog stores it."""
+    return json.dumps(
+        [{"slot_id": 1, "type": "PETG", "color": "#FFFFFF", "tray_info_idx": tray_info_idx, "force_color_match": True}]
+    )
+
+
+@pytest.mark.asyncio
+class TestForcedOverridesWithoutFileRequirements:
+    """A 3MF without slice info falls back to its force-colour overrides (#3280); so does the scope."""
+
+    async def test_a_forced_blocked_filament_is_a_violation(self):
+        item = _item(filament_overrides=_force_override("GFG03"))
+        message = await _run(_violation(item), requirements=[], loaded=[_tray(1, "GFG99")])
+        assert message == FILE_NEEDS_PETG_MATTE
+
+    async def test_the_direct_override_mapping_skips_blocked_trays(self):
+        item = _item(filament_overrides=_force_override(""))
+        mapping = await _run(_compute(item), requirements=[], loaded=[_tray(0, "GFG03"), _tray(1, "GFG99")])
+        assert mapping is not None
+        assert 0 not in mapping
+        assert mapping[0] == 1
+
+
+PRINT_ANYWAY = {"skip_filament_check": True}
+PRINT_ANYWAY_LEAVES_PETG = (
+    "Print anyway leaves PETG without a slot, and the printer could pick a loaded spool "
+    "the job creator's group can't print with: PETG (GFG03)"
+)
+
+
+@pytest.mark.asyncio
+class TestHoldNotFail:
+    """A permission finding holds the job, it doesn't fail it (#3522)."""
+
+    @pytest.mark.parametrize(
+        ("item_fields", "requirements", "loaded", "reason"),
+        [
+            pytest.param(
+                {"ams_mapping": "[1]"},
+                [REQ_PETG_MATTE],
+                [_tray(1, "GFG99")],
+                FILE_NEEDS_PETG_MATTE,
+                id="file_needs_a_blocked_filament",
+            ),
+            pytest.param(
+                {"ams_mapping": "[1]", **PRINT_ANYWAY},
+                [REQ_PETG_MATTE],
+                [_tray(1, "GFG99")],
+                FILE_NEEDS_PETG_MATTE,
+                id="file_needs_a_blocked_filament_even_with_print_anyway",
+            ),
+            pytest.param(
+                {"ams_mapping": "[0]", **PRINT_ANYWAY},
+                [REQ_WHITE_PETG],
+                [_tray(0, "GFG03")],
+                PRINT_ANYWAY_LEAVES_PETG,
+                id="print_anyway_with_only_blocked_trays",
+            ),
+            pytest.param(
+                {"ams_mapping": None, **PRINT_ANYWAY},
+                [REQ_WHITE_PETG],
+                [_tray(0, "GFG03")],
+                PRINT_ANYWAY_LEAVES_PETG,
+                id="print_anyway_with_no_mapping_and_only_blocked_trays",
+            ),
+            pytest.param(
+                # No AMS tray matches, so nothing turns the AMS back on (#2595).
+                {"use_ams": False},
+                [REQ_WHITE_PETG],
+                [_tray(1, "GFA00", "PLA"), _external(254, "GFG03")],
+                SPOOL_IS_PETG_MATTE,
+                id="external_spool_with_a_blocked_filament_without_the_ams",
+            ),
+        ],
+    )
+    async def test_is_held_with_the_reason(self, item_fields, requirements, loaded, reason):
+        result = await _run(_ensure(_item(**item_fields)), requirements=requirements, loaded=loaded)
+        assert isinstance(result, FilamentScopeHold)
+        assert result.reason == reason
+
+    @pytest.mark.parametrize(
+        ("item_fields", "loaded"),
+        [
+            pytest.param(
+                {"ams_mapping": "[1]", **PRINT_ANYWAY},
+                [_tray(0, "GFG03"), _tray(1, "GFG99")],
+                id="print_anyway_with_an_allowed_tray",
+            ),
+            pytest.param(
+                {"use_ams": False},
+                [_tray(1, "GFG03"), _external(254, "GFG99")],
+                id="external_spool_with_an_allowed_filament_without_the_ams",
+            ),
+        ],
+    )
+    async def test_dispatches(self, item_fields, loaded):
+        assert await _run(_ensure(_item(**item_fields)), loaded=loaded) is None
+
+    async def test_unrestricted_print_anyway_still_short_circuits(self):
+        item = _item(ams_mapping=json.dumps([0]), use_ams=False, **PRINT_ANYWAY)
+        result = await _run(
+            _ensure(item),
+            ALL_FILAMENTS,
+            requirements=[REQ_PETG_MATTE],
+            loaded=[_tray(0, "GFG03"), _external(254, "GFG03")],
+        )
+        assert result is None
+        assert json.loads(item.ams_mapping) == [0]
+
+
+@pytest.mark.asyncio
+class TestScopeIsResolvedOncePerPass:
+    async def test_two_candidate_printers_resolve_the_scope_once(self):
+        async def two_printers(sched):
+            await sched._compute_ams_mapping_for_printer(AsyncMock(), 1, _item())
+            await sched._compute_ams_mapping_for_printer(AsyncMock(), 2, _item())
+            return scheduler_module.resolve_user_id_filament_scope.await_count
+
+        assert await _run(two_printers, loaded=[_tray(1, "GFG99")]) == 1
+
+    async def test_memo_answers_repeat_calls_and_is_cleared_each_pass(self):
+        sched = PrintScheduler()
+        resolve = AsyncMock(return_value=BLOCK_PETG_MATTE)
+        with patch.object(scheduler_module, "resolve_user_id_filament_scope", resolve):
+            for _ in range(3):
+                assert await sched._creator_filament_scope(AsyncMock(), 7) is BLOCK_PETG_MATTE
+            assert resolve.await_count == 1
+            assert (await sched._creator_filament_scope(AsyncMock(), None)).is_unrestricted
+            assert resolve.await_count == 1
+            sched._filament_scope_memo.clear()
+            await sched._creator_filament_scope(AsyncMock(), 7)
+            assert resolve.await_count == 2
+
+
+@pytest.mark.asyncio
+class TestModelSelectionUnderPrintAnyway:
+    async def _unmatched(self, scope):
+        item = _item(printer_id=None, target_model="X1C", **PRINT_ANYWAY)
+        return await _run(lambda sched: sched._unmatched_on(AsyncMock(), item, 1), scope, loaded=[_tray(0, "GFG03")])
+
+    async def test_a_restricted_creator_does_not_skip_the_printer_match(self):
+        assert await self._unmatched(BLOCK_PETG_MATTE)
+
+    async def test_an_unrestricted_creator_still_skips_it(self):
+        assert await self._unmatched(ALL_FILAMENTS) == []
+
+
+@pytest.mark.asyncio
+class TestWithoutTheAmsTheMappingDoesNotDecide:
+    """With use_ams off and no tray mapped, a single-nozzle printer feeds its external spool (#3522)."""
+
+    async def _judge(self, model: str):
+        return await _run(
+            _ensure(_item(use_ams=False, **PRINT_ANYWAY)),
+            # "Print anyway" for PLA from an allowed PETG spool: no slot maps,
+            # and a blocked tray is loaded the printer could pick.
+            requirements=[REQ_WHITE_PLA],
+            loaded=[_tray(0, "GFG03"), _external(254, "GFG99")],
+            printer_model=model,
+        )
+
+    async def test_an_allowed_external_spool_is_enough_on_a_single_nozzle_printer(self):
+        assert await self._judge("X1C") is None
+
+    async def test_a_dual_nozzle_printer_still_has_its_mapping_judged(self):
+        assert isinstance(await self._judge("H2D"), FilamentScopeHold)
+
+
+def _claimed(item):
+    return lambda sched: sched._claimed_scope_violation(AsyncMock(), item)
+
+
+BLOCK_TPU = FilamentScope((GroupFilamentPolicy("Friends", "block", (FilamentRule("material", "TPU"),)),))
+ALLOW_ONLY_PETG_MATTE = FilamentScope(
+    (GroupFilamentPolicy("Friends", "allow", (FilamentRule("filament_id", "GFG03"),)),)
+)
+# Slot 1 white PETG, slot 2 white PLA: two filaments the plate prints.
+TWO_SLOTS = (REQ_WHITE_PETG, {**REQ_WHITE_PLA, "slot_id": 2})
+
+
+@pytest.mark.asyncio
+class TestTheFeedThePrinterIsSent:
+    """The feed is judged as the printer receives it (#3522).
+
+    On a single-nozzle printer the command builder turns ``use_ams=False``
+    back on when the mapping names a real tray (#2595), unless the plate
+    prints only from the spool holder; and a printer that reported no AMS
+    feeds the spool holder whatever ``use_ams`` says (#3356).
+    """
+
+    @pytest.mark.parametrize(
+        ("item_fields", "requirements", "loaded", "raw_data", "reason"),
+        [
+            pytest.param(
+                {"use_ams": False, "ams_mapping": "[0]"},
+                (REQ_WHITE_PETG,),
+                [_tray(0, "GFG03"), _external(254, "GFG99")],
+                None,
+                SPOOL_IS_PETG_MATTE,
+                id="use_ams_off_but_the_mapping_names_a_blocked_tray",
+            ),
+            pytest.param(
+                {"use_ams": False, "ams_mapping": "[1, -1]", **PRINT_ANYWAY},
+                TWO_SLOTS,
+                [_tray(0, "GFG03"), _tray(1, "GFG99"), _external(254, "GFG99")],
+                None,
+                "Print anyway leaves PLA without a slot, and the printer could pick a loaded spool "
+                "the job creator's group can't print with: PETG (GFG03)",
+                id="use_ams_off_print_anyway_with_an_unresolved_slot",
+            ),
+            pytest.param(
+                {"ams_mapping": None},
+                (REQ_WHITE_PETG,),
+                [_external(254, "GFG03")],
+                {"ams": []},
+                SPOOL_IS_PETG_MATTE,
+                id="no_ams_feeds_the_spool_holder_even_with_use_ams_on",
+            ),
+        ],
+    )
+    async def test_is_held(self, item_fields, requirements, loaded, raw_data, reason):
+        result = await _run(_claimed(_item(**item_fields)), requirements=requirements, loaded=loaded, raw_data=raw_data)
+        assert result == reason
+
+    @pytest.mark.parametrize(
+        ("item_fields", "requirements", "loaded"),
+        [
+            pytest.param(
+                {"use_ams": False, "ams_mapping": "[1]"},
+                (REQ_WHITE_PETG,),
+                [_tray(1, "GFG99"), _external(254, "GFG03")],
+                id="use_ams_off_but_the_mapping_names_an_allowed_tray",
+            ),
+            pytest.param(
+                # Slot 2 is another plate's: this plate prints only from the
+                # spool holder, so the AMS stays off (#3087) and tray 0 unused.
+                {"use_ams": False, "ams_mapping": "[254, 0]"},
+                (REQ_WHITE_PETG,),
+                [_tray(0, "GFG03"), _external(254, "GFG99")],
+                id="plate_prints_only_the_allowed_external_spool",
+            ),
+        ],
+    )
+    async def test_dispatches(self, item_fields, requirements, loaded):
+        assert await _run(_claimed(_item(**item_fields)), requirements=requirements, loaded=loaded) is None
+
+    async def test_a_blocked_external_spool_does_not_hold_a_job_the_ams_feeds(self):
+        # use_ams=False as a Virtual Printer stamps it; the matcher picks the
+        # allowed AMS tray, which turns the AMS back on (#2595).
+        item = _item(use_ams=False)
+        result = await _run(_ensure(item), loaded=[_tray(1, "GFG99"), _external(254, "GFG03")])
+        assert result is None
+        assert json.loads(item.ams_mapping) == [1]
+
+
+@pytest.mark.asyncio
+class TestOverriddenSlotsAndFilamentIdRules:
+    """An overridden slot is left to the tray filter, not judged without its filament id (#3522)."""
+
+    @staticmethod
+    def _override(*, force: bool, tray_info_idx: str = "GFG03") -> str:
+        return json.dumps(
+            [
+                {
+                    "slot_id": 1,
+                    "type": "PETG",
+                    "color": "#000000",
+                    "tray_info_idx": tray_info_idx,
+                    "force_color_match": force,
+                }
+            ]
+        )
+
+    @pytest.mark.parametrize(
+        ("override", "message"),
+        [
+            # A colour swap to another allowed GFG03 spool clears the id.
+            pytest.param({"force": False}, None, id="colour_swap"),
+            pytest.param({"force": True, "tray_info_idx": ""}, None, id="forced_colour_naming_no_id"),
+            pytest.param({"force": True}, None, id="forced_colour_of_the_allowed_id"),
+        ],
+    )
+    async def test_allowed_override_is_not_held(self, override, message):
+        item = _item(filament_overrides=self._override(**override))
+        result = await _run(
+            _violation(item), ALLOW_ONLY_PETG_MATTE, requirements=[REQ_PETG_MATTE], loaded=[_tray(0, "GFG03")]
+        )
+        assert result == message
+
+    async def test_a_forced_override_naming_a_blocked_id_is_still_held(self):
+        item = _item(filament_overrides=self._override(force=True))
+        result = await _run(_violation(item), requirements=[REQ_WHITE_PETG], loaded=[_tray(1, "GFG99")])
+        assert result == FILE_NEEDS_PETG_MATTE
+
+    async def test_an_override_onto_a_blocked_tray_with_print_anyway_is_held_at_dispatch(self):
+        # Skipped by the file check; the tray filter leaves the slot unmapped,
+        # and "Print anyway" doesn't let the printer pick the blocked tray.
+        item = _item(filament_overrides=self._override(force=False), **PRINT_ANYWAY)
+        result = await _run(_ensure(item), requirements=[REQ_WHITE_PLA], loaded=[_tray(0, "GFG03")])
+        assert isinstance(result, FilamentScopeHold)
+        assert "PETG (GFG03)" in result.reason
+
+
+@pytest.mark.asyncio
+class TestPrintAnywayOnlyWhereABlockedTrayIsLoaded:
+    """The unresolved-slot check needs a blocked tray on the printer (#3522)."""
+
+    async def test_nothing_blocked_loaded_lets_print_anyway_through(self):
+        item = _item(ams_mapping=None, **PRINT_ANYWAY)
+        result = await _run(_claimed(item), BLOCK_TPU, requirements=[REQ_WHITE_PLA], loaded=[_tray(0, "GFG99")])
+        assert result is None
+
+    async def test_a_blocked_tray_holds_it_naming_only_the_blocked_filament(self):
+        item = _item(ams_mapping=None, **PRINT_ANYWAY)
+        result = await _run(
+            _claimed(item),
+            BLOCK_TPU,
+            requirements=[REQ_WHITE_PLA],
+            loaded=[_tray(0, "", "TPU"), _tray(1, "GFG99")],
+        )
+        assert result == (
+            "Print anyway leaves PLA without a slot, and the printer could pick a loaded spool "
+            "the job creator's group can't print with: TPU"
+        )
+
+    async def test_a_blocked_external_spool_the_ams_job_is_not_fed_from_holds_nothing(self):
+        # Single nozzle, AMS on: a slot left without a tray never goes to the
+        # spool holder, so the blocked spool there is not one it could pick.
+        item = _item(ams_mapping=None, **PRINT_ANYWAY)
+        loaded = [_tray(1, "GFG99"), _external(254, "GFG03")]
+        assert await _run(_claimed(item), requirements=[REQ_WHITE_PLA], loaded=loaded) is None
+
+    async def test_a_blocked_external_spool_the_job_is_fed_from_still_holds_it(self):
+        item = _item(ams_mapping=None, use_ams=False, **PRINT_ANYWAY)
+        loaded = [_tray(1, "GFG99"), _external(254, "GFG03")]
+        assert await _run(_claimed(item), requirements=[REQ_WHITE_PLA], loaded=loaded) == SPOOL_IS_PETG_MATTE
+
+
+H2D_WITHOUT_AMS = {"ams": [], "vt_tray": [{"id": "254"}, {"id": "255"}]}
+
+
+@pytest.mark.asyncio
+class TestDualNozzleWithOnlyExternalSpools:
+    """A blocked spool that would have matched holds the job, it doesn't fail it (#3522)."""
+
+    @pytest.mark.parametrize(
+        "loaded",
+        [
+            pytest.param([_external(254, "GFG03"), _external(255, "GFA00", "PLA")], id="next_to_an_allowed_spool"),
+            pytest.param([_external(254, "GFG03")], id="alone"),
+        ],
+    )
+    async def test_is_held_with_the_permission_reason(self, loaded):
+        result = await _run(_ensure(_item()), loaded=loaded, raw_data=H2D_WITHOUT_AMS, printer_model="H2D")
+        assert result == FilamentScopeHold(SPOOL_IS_PETG_MATTE)
+
+    async def test_the_failure_does_not_list_a_blocked_spool_as_loaded(self):
+        # Nothing loaded matches TPU, blocked or not: the job fails (#2771),
+        # naming only the spools its creator may use.
+        tpu = {**REQ_WHITE_PLA, "type": "TPU"}
+        result = await _run(
+            _ensure(_item()),
+            requirements=[tpu],
+            loaded=[_external(254, "GFG03"), _external(255, "GFA00", "PLA")],
+            raw_data=H2D_WITHOUT_AMS,
+            printer_model="H2D",
+        )
+        assert isinstance(result, str)
+        assert "PLA" in result
+        assert "PETG" not in result
+
+
+@pytest.mark.asyncio
+class TestModelSelectionUnderPrintAnywayWithNothingBlockedLoaded:
+    async def test_print_anyway_is_honoured_where_no_blocked_tray_is_loaded(self):
+        # Dispatch lets it through with nothing blocked loaded, so choosing a
+        # printer does too.
+        item = _item(printer_id=None, target_model="X1C", **PRINT_ANYWAY)
+        unmatched = await _run(
+            lambda sched: sched._unmatched_on(AsyncMock(), item, 1),
+            BLOCK_TPU,
+            requirements=[REQ_WHITE_PLA],
+            loaded=[_tray(0, "GFG03")],
+        )
+        assert unmatched == []
+
+
+@pytest.mark.asyncio
+class TestAMappedTrayThePrinterDoesNotHave:
+    """A tray id the printer doesn't report loaded settles nothing for a restricted creator (#3522).
+
+    Only a hand-written payload carries one, and "Print anyway" keeps it past
+    the fit check, so it is read as a slot left for the printer to fill.
+    """
+
+    async def test_on_a_printer_without_an_ams_the_blocked_external_spool_holds_it(self):
+        # use_ams stays on, but the command builder turns it off for a printer
+        # that reports no AMS, so the spool holder is what feeds.
+        item = _item(ams_mapping="[0]", **PRINT_ANYWAY)
+        result = await _run(
+            _ensure(item), requirements=[REQ_WHITE_PLA], loaded=[_external(254, "GFG03")], raw_data={"ams": []}
+        )
+        assert result == FilamentScopeHold(SPOOL_IS_PETG_MATTE)
+
+    async def test_on_a_printer_with_an_ams_it_is_left_for_the_printer_to_fill(self):
+        item = _item(ams_mapping="[5]", **PRINT_ANYWAY)
+        result = await _run(
+            _ensure(item), requirements=[REQ_WHITE_PLA], loaded=[_tray(0, "GFG03"), _tray(1, "GFA00", "PLA")]
+        )
+        assert result == FilamentScopeHold(
+            "Print anyway leaves PLA without a slot, and the printer could pick a loaded spool "
+            "the job creator's group can't print with: PETG (GFG03)"
+        )
+
+
+# An H3C has an external input per hotend, 247-255, and reports the ones in use.
+H3C_INPUTS = {"vt_tray": [{"id": "250"}, {"id": "251"}]}
+
+
+@pytest.mark.asyncio
+class TestARackPrintersExternalInputs:
+    """On an H3C the mapping names the external input that feeds, so only that one is judged (#3522)."""
+
+    @pytest.mark.parametrize(
+        ("mapping", "raw_data", "reason"),
+        [
+            pytest.param("[250]", H3C_INPUTS, None, id="mapped_to_the_allowed_input"),
+            pytest.param("[251]", H3C_INPUTS, SPOOL_IS_PETG_MATTE, id="mapped_to_the_blocked_input"),
+            pytest.param("[250, 251]", H3C_INPUTS, SPOOL_IS_PETG_MATTE, id="mapped_to_both"),
+            # No AMS and no input named: any of them may feed.
+            pytest.param(None, {**H3C_INPUTS, "ams": []}, SPOOL_IS_PETG_MATTE, id="no_input_named"),
+        ],
+    )
+    async def test_only_a_named_input_holds_the_job(self, mapping, raw_data, reason):
+        result = await _run(
+            _claimed(_item(ams_mapping=mapping)),
+            loaded=[_external(250, "GFG99"), _external(251, "GFG03")],
+            raw_data=raw_data,
+            printer_model="H3C",
+        )
+        assert result == reason
+
+
+UNLISTED_NEXT_TO_PETG_MATTE = (
+    "This file doesn't list its filaments, and the printer has a loaded spool "
+    "the job creator's group can't print with: PETG (GFG03)"
+)
+
+
+@pytest.mark.asyncio
+class TestAFileThatListsNoFilaments:
+    """A file without readable slice info can't be judged from the file, so the printer is (#3522)."""
+
+    @pytest.mark.parametrize(
+        ("scope", "loaded", "raw_data", "result"),
+        [
+            pytest.param(
+                BLOCK_PETG_MATTE,
+                [_external(254, "GFG03")],
+                {"ams": []},
+                FilamentScopeHold(SPOOL_IS_PETG_MATTE),
+                id="no_ams_and_a_blocked_external_spool",
+            ),
+            pytest.param(BLOCK_PETG_MATTE, [_external(254, "GFG99")], {"ams": []}, None, id="allowed_external_spool"),
+            pytest.param(
+                BLOCK_PETG_MATTE,
+                [_tray(0, "GFG03"), _tray(1, "GFG99")],
+                None,
+                FilamentScopeHold(UNLISTED_NEXT_TO_PETG_MATTE),
+                id="a_blocked_ams_tray_the_printer_could_pick",
+            ),
+            pytest.param(
+                # The AMS feeds, so the spool holder isn't one it could pick.
+                BLOCK_PETG_MATTE,
+                [_tray(1, "GFG99"), _external(254, "GFG03")],
+                None,
+                None,
+                id="only_the_unfed_external_spool_is_blocked",
+            ),
+            pytest.param(ALL_FILAMENTS, [_tray(0, "GFG03")], None, None, id="unrestricted_creator_is_unaffected"),
+        ],
+    )
+    async def test_the_spools_it_could_be_fed_from_decide(self, scope, loaded, raw_data, result):
+        assert await _run(_ensure(_item()), scope, requirements=[], loaded=loaded, raw_data=raw_data) == result
+
+    async def test_a_file_that_is_gone_is_left_to_the_missing_file_failure(self, tmp_path):
+        result = await _run(_ensure(_item()), requirements=[], loaded=[_tray(0, "GFG03")], source=tmp_path / "gone.3mf")
+        assert result is None
+
+    @pytest.mark.parametrize("item_fields", [{}, {"ams_mapping": "[254]"}], ids=["no_mapping", "mapped_to_it"])
+    async def test_a_dual_nozzle_printer_without_an_ams_may_feed_its_blocked_external_spool(self, item_fields):
+        # use_ams picks the extruder there, not the AMS, so it stays on and
+        # the external spools are all the printer has to feed from.
+        result = await _run(
+            _ensure(_item(**item_fields)),
+            requirements=[],
+            loaded=[_external(254, "GFG03"), _external(255, "GFA00", "PLA")],
+            raw_data=H2D_WITHOUT_AMS,
+            printer_model="H2D",
+        )
+        assert result == FilamentScopeHold(UNLISTED_NEXT_TO_PETG_MATTE)
+
+
+@pytest.mark.asyncio
+class TestTheCheckOnceClaimed:
+    async def test_reads_the_creators_rules_afresh(self):
+        # A pass can wait minutes on a smart plug; a rule tightened meanwhile
+        # applies to the job it dispatches next.
+        async def stale_then_claimed(sched):
+            sched._filament_scope_memo[7] = ALL_FILAMENTS
+            return await sched._claimed_scope_violation(AsyncMock(), _item())
+
+        assert await _run(stale_then_claimed, requirements=[REQ_PETG_MATTE], loaded=[]) == FILE_NEEDS_PETG_MATTE
+
+
+@pytest.mark.asyncio
+class TestStartingAStagedJob:
+    async def test_reads_the_creators_rules_afresh(self):
+        # Start is a request, not a pass: a rule lifted since the last pass
+        # lets the job map onto the tray it was held from.
+        async def stale_then_start(sched):
+            sched._filament_scope_memo[7] = BLOCK_PETG_MATTE
+            return await sched.missing_filament_for_start(AsyncMock(), _item())
+
+        assert await _run(stale_then_start, ALL_FILAMENTS, loaded=[_tray(0, "GFG03")]) is None

+ 1 - 0
backend/tests/unit/test_scheduler_force_color_ams_fallback.py

@@ -159,6 +159,7 @@ class TestComputeAmsMappingFallback:
         item.plate_id = None
         item.filament_overrides = filament_overrides_json
         item.printer_id = 5
+        item.created_by_id = None  # no creator: unrestricted filament scope (#3522)
         return item
 
     def _make_status(self) -> MagicMock:

+ 73 - 0
frontend/src/__tests__/components/FilamentAccessCard.test.tsx

@@ -0,0 +1,73 @@
+import { describe, it, expect, vi } from 'vitest';
+import { screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ComponentProps } from 'react';
+import { render } from '../utils';
+import { FilamentAccessCard } from '../../components/FilamentAccessCard';
+
+type CardProps = ComponentProps<typeof FilamentAccessCard>;
+
+const card = (props: Partial<CardProps> = {}) => (
+  <FilamentAccessCard enabled mode="block" rules={[]} onChange={vi.fn()} {...props} />
+);
+
+describe('FilamentAccessCard', () => {
+  it('turns the restriction on', async () => {
+    const onChange = vi.fn();
+    render(card({ enabled: false, onChange }));
+    await userEvent.click(screen.getByRole('checkbox', { name: /limit filaments/i }));
+    expect(onChange).toHaveBeenCalledWith({ enabled: true, mode: 'block', rules: [] });
+  });
+
+  it('adds a material rule from the input', async () => {
+    const onChange = vi.fn();
+    render(card({ onChange }));
+    await userEvent.type(screen.getByLabelText(/rule value/i), 'petg');
+    await userEvent.click(screen.getByRole('button', { name: /add rule/i }));
+    expect(onChange).toHaveBeenCalledWith({
+      enabled: true,
+      mode: 'block',
+      rules: [{ match: 'material', value: 'PETG' }],
+    });
+  });
+
+  it('removes a rule', async () => {
+    const onChange = vi.fn();
+    render(card({ mode: 'allow', rules: [{ match: 'filament_id', value: 'GFG03' }], onChange }));
+    await userEvent.click(screen.getByRole('button', { name: /remove GFG03/i }));
+    expect(onChange).toHaveBeenCalledWith({ enabled: true, mode: 'allow', rules: [] });
+  });
+
+  it('shows the admin note instead of controls when disabled', () => {
+    render(card({ enabled: false, disabled: true }));
+    expect(screen.queryByRole('checkbox', { name: /limit filaments/i })).toBeNull();
+    expect(screen.getByText(/administrators can always use every filament/i)).toBeInTheDocument();
+  });
+
+  it('warns that an empty allow list blocks every filament', () => {
+    const { rerender } = render(card({ mode: 'allow' }));
+    expect(screen.getByRole('status')).toHaveTextContent(/an allow list blocks every filament/i);
+    rerender(card({ mode: 'allow', rules: [{ match: 'material', value: 'PLA' }] }));
+    expect(screen.queryByText(/an allow list blocks every filament/i)).toBeNull();
+  });
+
+  it('does not report typed text the admin can no longer see', async () => {
+    const pending = vi.fn();
+    const allowCard = (enabled: boolean) => card({ enabled, mode: 'allow', onPendingRulesChange: pending });
+    const { rerender } = render(allowCard(true));
+    await userEvent.type(screen.getByLabelText(/rule value/i), 'pla');
+    expect(pending).toHaveBeenLastCalledWith([{ match: 'material', value: 'PLA' }]);
+
+    // Another match kind: the text typed for the old one goes.
+    await userEvent.selectOptions(screen.getByDisplayValue('Material type'), 'filament_id');
+    expect(screen.getByLabelText(/rule value/i)).toHaveValue('');
+    expect(pending).toHaveBeenLastCalledWith([]);
+
+    // Unticked, the input is hidden: nothing typed there is saved.
+    await userEvent.type(screen.getByLabelText(/rule value/i), 'GFG03');
+    rerender(allowCard(false));
+    expect(pending).toHaveBeenLastCalledWith([]);
+    rerender(allowCard(true));
+    expect(pending).toHaveBeenLastCalledWith([]);
+  });
+});

+ 109 - 0
frontend/src/__tests__/components/FilamentMapping.test.tsx

@@ -15,6 +15,7 @@ import { http, HttpResponse } from 'msw';
 import { render } from '../utils';
 import { server } from '../mocks/server';
 import { FilamentMapping } from '../../components/PrintModal/FilamentMapping';
+import { setAuthToken } from '../../api/client';
 import type { PrinterStatus } from '../../api/client';
 
 /**
@@ -99,6 +100,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={mockFilamentReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -141,6 +143,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={mockFilamentReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -175,6 +178,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={mockFilamentReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -217,6 +221,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={mockFilamentReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -261,6 +266,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={mockFilamentReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -318,6 +324,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={charcoalReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -356,6 +363,7 @@ describe('FilamentMapping — FTS routing', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={{
           filaments: [
             { slot_id: 1, type: 'PLA', color: '#000000', used_grams: 25, used_meters: 8.5, nozzle_id: 1, tray_info_idx: 'GFA01' },
@@ -417,6 +425,7 @@ describe('FilamentMapping — FTS same-inlet advisory', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={twoFilamentReqs}
         manualMappings={{}}
         onManualMappingChange={() => {}}
@@ -451,3 +460,103 @@ describe('FilamentMapping — FTS same-inlet advisory', () => {
     expect(screen.queryByText(/same inlet is slower/i)).not.toBeInTheDocument();
   });
 });
+
+describe('FilamentMapping — filament rules of the user\'s group (#3522)', () => {
+  // Slot 0 and slot 1 hold the same white PETG; only the slicer preset id
+  // tells them apart, and the group blocks GFG03.
+  const status = createStatus({
+    ams: [
+      {
+        id: 0,
+        tray: [
+          { id: 0, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG03', tray_sub_brands: 'PETG Matte' },
+          { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG99', tray_sub_brands: 'PETG Other' },
+        ],
+      },
+    ],
+  } as Partial<PrinterStatus>);
+  const blockedSlotText = "Your group can't use PETG (GFG03)";
+
+  beforeEach(() => {
+    setAuthToken('test-token', 'session');
+    server.use(
+      http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
+      http.get('*/api/v1/auth/me', () =>
+        HttpResponse.json({
+          id: 2,
+          username: 'student',
+          is_admin: false,
+          permissions: [],
+          filament_policies: [
+            { group: 'Students', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] },
+          ],
+        }),
+      ),
+      http.get('/api/v1/printers/:id/spool-assignments', () => HttpResponse.json([])),
+      http.get('/api/v1/printers/:id/status', () => HttpResponse.json(status)),
+    );
+  });
+
+  afterEach(() => {
+    setAuthToken(null);
+  });
+
+  const renderMapping = (
+    filaments: Array<{ slot_id: number; type: string; color: string; used_grams: number; used_meters: number; tray_info_idx?: string }>,
+    props: Partial<React.ComponentProps<typeof FilamentMapping>> = {},
+  ) =>
+    render(
+      <FilamentMapping
+        printerId={1}
+        blockedFilaments={[]}
+        filamentReqs={{ filaments }}
+        manualMappings={{}}
+        onManualMappingChange={() => {}}
+        currencySymbol="$"
+        defaultCostPerKg={0}
+        defaultExpanded
+        {...props}
+      />,
+    );
+
+  it('auto-maps to the allowed slot and greys out the blocked one', async () => {
+    renderMapping([{ slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 10, used_meters: 3 }]);
+
+    // The policies arrive with /auth/me, after the first render; once they
+    // have, the auto-match moves off the blocked slot.
+    const trigger = await screen.findByRole('combobox');
+    await waitFor(() => expect(trigger).toHaveTextContent(/PETG Other/));
+
+    fireEvent.click(trigger);
+    const listbox = await screen.findByRole('listbox');
+    const blocked = within(listbox).getByRole('option', { name: /PETG Matte/ });
+    expect(blocked).toHaveAttribute('aria-disabled', 'true');
+    expect(blocked).toHaveAttribute('title', blockedSlotText);
+    expect(within(listbox).getByRole('option', { name: /PETG Other/ })).not.toHaveAttribute('aria-disabled');
+  });
+
+  it('warns, even collapsed, when the file itself needs a blocked filament', async () => {
+    renderMapping(
+      [{ slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 10, used_meters: 3, tray_info_idx: 'GFG03' }],
+      // The dialog judges the file and hands the panel the list.
+      { defaultExpanded: false, blockedFilaments: ['PETG (GFG03)'] },
+    );
+
+    const alert = await screen.findByRole('alert');
+    expect(alert).toHaveTextContent("This file uses a filament your group can't print with: PETG (GFG03)");
+    // The header must not read "Ready" while Print is disabled for this.
+    expect(screen.getByText('(Blocked)')).toBeInTheDocument();
+    expect(screen.queryByText('(Ready)')).not.toBeInTheDocument();
+  });
+
+  it('flags a blocked tray that is still the chosen one', async () => {
+    // A manual pick (an older queue job, the archive's saved mapping) can name
+    // a blocked tray. The server re-picks it, but the row must say so.
+    renderMapping([{ slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 10, used_meters: 3 }], {
+      manualMappings: { 1: 0 },
+    });
+
+    const warning = await screen.findByRole('img', { name: blockedSlotText });
+    expect(warning).toHaveAttribute('title', blockedSlotText);
+  });
+});

+ 1 - 0
frontend/src/__tests__/components/FilamentMappingArchivePick.test.tsx

@@ -65,6 +65,7 @@ function Harness({
   return (
     <FilamentMapping
       printerId={1}
+      blockedFilaments={[]}
       filamentReqs={TWO_SLOT_REQS}
       manualMappings={manualMappings}
       onManualMappingChange={(m) => {

+ 1 - 0
frontend/src/__tests__/components/FilamentMappingColorMismatch.test.tsx

@@ -48,6 +48,7 @@ function renderMapping() {
   render(
     <FilamentMapping
       printerId={1}
+      blockedFilaments={[]}
       filamentReqs={blueReqs}
       manualMappings={{}}
       onManualMappingChange={() => {}}

+ 1 - 0
frontend/src/__tests__/components/FilamentMappingRackPicker.test.tsx

@@ -88,6 +88,7 @@ function mount(props: Record<string, unknown> = {}, rack = fullRack) {
   return render(
     <FilamentMapping
       printerId={1}
+      blockedFilaments={[]}
       filamentReqs={benchyReqs}
       manualMappings={{}}
       onManualMappingChange={() => {}}

+ 1 - 0
frontend/src/__tests__/components/FilamentMappingSlotCost.test.tsx

@@ -53,6 +53,7 @@ function renderWith(cost: number | null) {
   render(
     <FilamentMapping
       printerId={1}
+      blockedFilaments={[]}
       filamentReqs={{ filaments: [{ slot_id: 1, type: 'PLA', color: '#FF0000', used_grams: 100, used_meters: 30 }] }}
       manualMappings={{}}
       onManualMappingChange={() => {}}

+ 53 - 1
frontend/src/__tests__/components/FilamentOverride.test.tsx

@@ -5,11 +5,12 @@
  * choices with filaments available across printers of the selected model.
  */
 
-import { describe, it, expect, vi, afterEach } from 'vitest';
+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
 import { screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
 import { http, HttpResponse } from 'msw';
 import { render } from '../utils';
 import { server } from '../mocks/server';
+import { setAuthToken } from '../../api/client';
 import { FilamentOverride } from '../../components/PrintModal/FilamentOverride';
 import type { FilamentReqsData } from '../../components/PrintModal/types';
 
@@ -611,3 +612,54 @@ describe('FilamentOverride', () => {
     });
   });
 });
+
+describe('FilamentOverride — filament rules of the user\'s group (#3522)', () => {
+  beforeEach(() => {
+    setAuthToken('test-token', 'session');
+    server.use(
+      http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
+      http.get('*/api/v1/auth/me', () =>
+        HttpResponse.json({
+          id: 2,
+          username: 'student',
+          is_admin: false,
+          permissions: [],
+          filament_policies: [
+            { group: 'Students', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] },
+          ],
+        }),
+      ),
+    );
+  });
+
+  afterEach(() => {
+    setAuthToken(null);
+  });
+
+  it('lists a filament the group may not use, greyed out with the reason', async () => {
+    render(
+      <FilamentOverride
+        filamentReqs={{ filaments: [{ slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 10, used_meters: 3 }] }}
+        availableFilaments={[
+          { type: 'PETG', color: '#000000', tray_info_idx: 'GFG03', tray_sub_brands: 'PETG Matte', extruder_id: null },
+          { type: 'PETG', color: '#0000FF', tray_info_idx: 'GFG99', tray_sub_brands: 'PETG Other', extruder_id: null },
+        ]}
+        overrides={{}}
+        onChange={mockOnChange}
+      />,
+    );
+
+    fireEvent.click(screen.getByRole('combobox'));
+    const listbox = await screen.findByRole('listbox');
+    // The policies arrive with /auth/me, after the first render.
+    await waitFor(() =>
+      expect(within(listbox).getByRole('option', { name: /PETG Matte/ })).toHaveAttribute('aria-disabled', 'true'),
+    );
+    const blocked = within(listbox).getByRole('option', { name: /PETG Matte/ });
+    expect(blocked).toHaveAttribute('title', "Your group can't use PETG (GFG03)");
+    expect(within(listbox).getByRole('option', { name: /PETG Other/ })).not.toHaveAttribute('aria-disabled');
+
+    fireEvent.click(blocked);
+    expect(mockOnChange).not.toHaveBeenCalled();
+  });
+});

+ 152 - 0
frontend/src/__tests__/components/PrintModal.test.tsx

@@ -3477,3 +3477,155 @@ describe('PrintModal — "Force color match" on a specific printer is saved (#34
     expect(posted[0].filament_overrides).toEqual([expect.objectContaining(BLACK_FORCED)]);
   });
 });
+
+describe('PrintModal — filament rules of the user\'s group (#3522)', () => {
+  const mockOnClose = vi.fn();
+  const PRINTERS = [{ id: 1, name: 'Printer 01', model: 'P1S', ip_address: '192.168.1.101', enabled: true, is_active: true }];
+  // Same white PETG twice; only the slicer preset id differs, and GFG03 is blocked.
+  const STATUS = {
+    connected: true,
+    state: 'IDLE',
+    ams: [
+      {
+        id: 0,
+        tray: [
+          { id: 0, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG03', tray_sub_brands: 'PETG Matte' },
+          { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG99', tray_sub_brands: 'PETG Other' },
+        ],
+      },
+    ],
+    vt_tray: [],
+  };
+  const PETG_ANY = { slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 10, used_meters: 3 };
+  const PETG_BLOCKED = { ...PETG_ANY, tray_info_idx: 'GFG03' };
+  const BANNER = "This file uses a filament your group can't print with: PETG (GFG03)";
+  let posted: Array<{ ams_mapping?: number[] | null }>;
+
+  const useRequirements = (filaments: unknown[]) =>
+    server.use(http.get('/api/v1/archives/:id/filament-requirements', () => HttpResponse.json({ filaments })));
+  const submitButton = () => document.querySelector('button[type="submit"]') as HTMLButtonElement;
+
+  beforeEach(() => {
+    vi.clearAllMocks();
+    posted = [];
+    setAuthToken('test-token', 'session');
+    server.use(
+      http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
+      http.get('*/api/v1/auth/me', () =>
+        HttpResponse.json({
+          id: 7,
+          username: 'student',
+          is_admin: false,
+          permissions: ['printers:read', 'queue:create'],
+          filament_policies: [
+            { group: 'Students', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] },
+          ],
+        }),
+      ),
+      http.get('/api/v1/printers/', () => HttpResponse.json(PRINTERS)),
+      http.get('/api/v1/archives/:id/plates', () => HttpResponse.json({ is_multi_plate: false, plates: [] })),
+      http.get('/api/v1/printers/:id/status', () => HttpResponse.json(STATUS)),
+      http.get('/api/v1/printers/:id/assignments', () => HttpResponse.json([])),
+      http.get('/api/v1/printers/available-filaments', () => HttpResponse.json([])),
+      http.post('/api/v1/queue/', async ({ request }) => {
+        posted.push((await request.json()) as { ams_mapping?: number[] | null });
+        return HttpResponse.json({ id: 1, status: 'pending' });
+      }),
+    );
+  });
+
+  afterEach(() => {
+    setAuthToken(null);
+  });
+
+  it('greys out the blocked slot and sends the allowed one', async () => {
+    useRequirements([PETG_ANY]);
+    const user = userEvent.setup();
+    render(<PrintModal mode="create" archiveId={1} archiveName="Job" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />);
+
+    const trigger = await screen.findByRole('combobox', { name: /printer slot for/i });
+    await waitFor(() => expect(trigger).toHaveTextContent(/PETG Other/));
+    await user.click(trigger);
+    const listbox = await screen.findByRole('listbox');
+    expect(within(listbox).getByRole('option', { name: /PETG Matte/ })).toHaveAttribute('aria-disabled', 'true');
+    await user.keyboard('{Escape}');
+
+    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+    await waitFor(() => expect(submitButton()).toBeEnabled());
+    await user.click(submitButton());
+    await waitFor(() => expect(posted).toHaveLength(1));
+    expect(posted[0].ams_mapping).toEqual([1]);
+  });
+
+  it('names the blocked filament and keeps submit disabled', async () => {
+    useRequirements([PETG_BLOCKED]);
+    render(<PrintModal mode="create" archiveId={1} archiveName="Job" initialSelectedPrinterIds={[1]} onClose={mockOnClose} />);
+
+    expect(await screen.findByRole('alert')).toHaveTextContent(BANNER);
+    expect(submitButton()).toBeDisabled();
+  });
+
+  it('names the blocked filament after a model-mode job is moved to a printer (#3133)', async () => {
+    // The mapping panel takes over the banner, so a disabled Print still says why.
+    useRequirements([PETG_BLOCKED]);
+    const user = userEvent.setup();
+    render(
+      <PrintModal
+        mode="edit-queue-item"
+        archiveId={1}
+        archiveName="Job"
+        queueItem={createMockQueueItem({ printer_id: null, target_model: 'P1S' } as Partial<PrintQueueItem>)}
+        onClose={mockOnClose}
+      />,
+    );
+
+    await user.click(await screen.findByRole('button', { name: /specific printer/i }));
+    await user.click(await screen.findByText('Printer 01'));
+    await screen.findByText(/filament mapping/i);
+
+    await waitFor(() => expect(submitButton()).toBeDisabled());
+    expect(await screen.findByRole('alert')).toHaveTextContent(BANNER);
+    // The panel's banner, not the dialog's as well.
+    expect(screen.getAllByRole('alert')).toHaveLength(1);
+  });
+
+  it('lets a slot swapped to another filament through, as the server does', async () => {
+    // The file was sliced with blocked GFG03; the job asks for PLA in that
+    // slot. The swap clears the preset id, so the tray it lands on is what
+    // the rules judge, here as on the server.
+    useRequirements([PETG_BLOCKED]);
+    render(
+      <PrintModal
+        mode="edit-queue-item"
+        archiveId={1}
+        archiveName="Job"
+        queueItem={createMockQueueItem({
+          printer_id: null,
+          target_model: 'P1S',
+          filament_overrides: [{ slot_id: 1, type: 'PLA', color: '#000000', force_color_match: false }],
+        } as Partial<PrintQueueItem>)}
+        onClose={mockOnClose}
+      />,
+    );
+
+    await waitFor(() => expect(submitButton()).toBeEnabled());
+    expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+  });
+
+  it('still names it in model mode, which has no mapping panel', async () => {
+    useRequirements([PETG_BLOCKED]);
+    render(
+      <PrintModal
+        mode="edit-queue-item"
+        archiveId={1}
+        archiveName="Job"
+        queueItem={createMockQueueItem({ printer_id: null, target_model: 'P1S' } as Partial<PrintQueueItem>)}
+        onClose={mockOnClose}
+      />,
+    );
+
+    expect(await screen.findByRole('alert')).toHaveTextContent(BANNER);
+    expect(screen.getAllByRole('alert')).toHaveLength(1);
+    expect(submitButton()).toBeDisabled();
+  });
+});

+ 54 - 0
frontend/src/__tests__/components/PrintModalNarrowScreen.test.tsx

@@ -156,6 +156,7 @@ describe('mapping row on a narrow screen', () => {
     render(
       <FilamentMapping
         printerId={1}
+        blockedFilaments={[]}
         filamentReqs={{
           filaments: [{ slot_id: 1, type: 'PLA', color: '#DE4343', used_grams: 297.6, used_meters: 90, ...filament }],
         }}
@@ -244,3 +245,56 @@ describe('custom slot mapping of one of several printers, on a narrow screen', (
     }
   });
 });
+
+describe('custom slot mapping of one of several printers, with filament rules (#3522)', () => {
+  afterEach(() => cleanup());
+
+  it('lists a tray the group may not use as disabled', async () => {
+    const printer = (id: number) => ({ id, name: `H2C-${id}`, model: 'H2C', ip_address: `192.0.2.${id}`, is_active: true }) as unknown as Printer;
+    const tray = (globalTrayId: number, trayInfoIdx: string, blocked?: boolean) => ({
+      globalTrayId,
+      type: 'PETG',
+      color: '#FFFFFF',
+      colorName: 'White',
+      amsId: 0,
+      trayId: globalTrayId,
+      isHt: false,
+      isExternal: false,
+      label: `AMS1-T${globalTrayId + 1}`,
+      trayInfoIdx,
+      remain: -1,
+      ...(blocked ? { blocked } : {}),
+    });
+    const result = (id: number): PrinterMappingResult => ({
+      printerId: id,
+      printerName: `H2C-${id}`,
+      status: undefined,
+      isLoading: false,
+      loadedFilaments: [tray(0, 'GFG03', true), tray(1, 'GFG99')],
+      autoMapping: undefined,
+      finalMapping: undefined,
+      matchStatus: 'missing',
+      exactMatches: 0,
+      typeOnlyMatches: 0,
+      missingTypes: 1,
+      totalSlots: 1,
+      config: { useDefault: false, manualMappings: {}, autoConfigured: false },
+    });
+    render(
+      <PrinterSelector
+        printers={[printer(1), printer(2)]}
+        selectedPrinterIds={[1, 2]}
+        onMultiSelect={() => {}}
+        allowMultiple
+        printerMappingResults={[result(1), result(2)]}
+        filamentReqs={{ filaments: [{ slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 25, used_meters: 8.5 }] }}
+        onAutoConfigurePrinter={() => {}}
+        onUpdatePrinterConfig={() => {}}
+      />,
+    );
+    const [select] = await screen.findAllByRole('combobox');
+    const options = Array.from(select.querySelectorAll('option'));
+    expect(options.find((o) => o.value === '0')).toBeDisabled();
+    expect(options.find((o) => o.value === '1')).not.toBeDisabled();
+  });
+});

+ 12 - 0
frontend/src/__tests__/components/PrinterSelector.test.ts

@@ -179,6 +179,18 @@ describe('autoMatchFilament', () => {
     expect(result!.globalTrayId).toBe(5);
   });
 
+  // #3522: InlineMappingEditor's loaded list comes from the multi-printer
+  // hook, which flags the trays the user's groups block.
+  it('never picks a blocked filament, even the only exact colour match', () => {
+    const filaments: LoadedFilament[] = [
+      makeFilament({ globalTrayId: 0, type: 'PETG', color: '#FFFFFF', blocked: true }),
+      makeFilament({ globalTrayId: 1, type: 'PETG', color: '#000000', colorName: 'Black' }),
+    ];
+    const req = makeReq({ type: 'PETG', color: '#FFFFFF' });
+    expect(autoMatchFilament(req, filaments, new Set())?.globalTrayId).toBe(1);
+    expect(autoMatchFilament(req, filaments.slice(0, 1), new Set())).toBeUndefined();
+  });
+
   it('matches PA-CF requirement to PA12-CF filament — #688', () => {
     const filaments: LoadedFilament[] = [
       makeFilament({ globalTrayId: 0, type: 'PA12-CF', color: '#000000', colorName: 'Black' }),

+ 40 - 0
frontend/src/__tests__/components/SlotPicker.test.tsx

@@ -180,4 +180,44 @@ describe('SlotPicker', () => {
     await user.click(within(listbox).getByRole('option', { name: /Select slot/ }));
     expect(onChange).toHaveBeenCalledWith('');
   });
+
+  it('shows a disabled row with its reason and does not pick it (#3522)', async () => {
+    const user = userEvent.setup();
+    const { onChange } = renderPicker({
+      options: [
+        { value: '0', label: 'A1: PETG', disabled: true, disabledReason: "Your group can't use PETG (GFG03)" },
+        { value: '1', label: 'A2: PLA' },
+      ],
+    });
+
+    const listbox = await open(user);
+    const blocked = within(listbox).getByRole('option', { name: /A1: PETG/ });
+    expect(blocked).toHaveAttribute('aria-disabled', 'true');
+    expect(blocked).toHaveAttribute('title', "Your group can't use PETG (GFG03)");
+
+    await user.click(blocked);
+    expect(onChange).not.toHaveBeenCalled();
+    // The list stays open: nothing was chosen, so there is nothing to close on.
+    expect(screen.getByRole('listbox')).toBeInTheDocument();
+
+    await user.click(within(listbox).getByRole('option', { name: /A2: PLA/ }));
+    expect(onChange).toHaveBeenCalledWith('1');
+  });
+
+  it('ignores Enter on a disabled row (#3522)', async () => {
+    const user = userEvent.setup();
+    const { onChange } = renderPicker({
+      options: [
+        { value: '0', label: 'A1: PETG', disabled: true, disabledReason: "Your group can't use PETG" },
+        { value: '1', label: 'A2: PLA' },
+      ],
+    });
+
+    screen.getByRole('combobox', { name: /printer slot for pla/i }).focus();
+    await user.keyboard('{ArrowDown}');
+    await screen.findByRole('listbox');
+    // Row 0 is the placeholder, so one press lands on the blocked slot.
+    await user.keyboard('{ArrowDown}{Enter}');
+    expect(onChange).not.toHaveBeenCalled();
+  });
 });

+ 64 - 1
frontend/src/__tests__/hooks/useFilamentMapping.test.ts

@@ -16,7 +16,7 @@ import {
 } from '../../hooks/useFilamentMapping';
 import { effectivePreferLowest } from '../../utils/amsHelpers';
 import { getColorName, setColorCatalog, __resetColorCatalogForTests } from '../../utils/colors';
-import type { PrinterStatus } from '../../api/client';
+import type { FilamentPolicy, PrinterStatus } from '../../api/client';
 
 // Helper to create a minimal printer status with AMS data
 function createPrinterStatus(ams: PrinterStatus['ams'], vt_tray: PrinterStatus['vt_tray'] = []): PrinterStatus {
@@ -1694,3 +1694,66 @@ describe('buildLoadedFilaments - H3C rack printer', () => {
     expect(computeAmsMapping(reqs, h3cStatus())).toEqual([34]);
   });
 });
+
+// #3522: a user whose groups block a filament must never have it auto-picked.
+describe('filament rules (#3522)', () => {
+  const blockMatte: FilamentPolicy[] = [
+    { group: 'friends', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] },
+  ];
+  // Two white PETG spools: the blocked one sits in the first slot, where every
+  // tie-break would otherwise land.
+  const twoWhitePetg = () =>
+    createPrinterStatus([
+      {
+        id: 0,
+        tray: [
+          { id: 0, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG03' },
+          { id: 1, tray_type: 'PETG', tray_color: 'FFFFFFFF', tray_info_idx: 'GFG99' },
+        ],
+      },
+    ] as PrinterStatus['ams']);
+  const whitePetg = { filaments: [{ slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 5 }] };
+
+  it('flags the trays the policies block', () => {
+    const loaded = buildLoadedFilaments(twoWhitePetg(), undefined, blockMatte);
+    expect(loaded.map((f) => f.blocked)).toEqual([true, undefined]);
+  });
+
+  it('flags nothing when the user is unrestricted', () => {
+    const loaded = buildLoadedFilaments(twoWhitePetg(), undefined, null);
+    expect(loaded.some((f) => 'blocked' in f)).toBe(false);
+  });
+
+  it('maps around a blocked tray', () => {
+    expect(computeAmsMapping(whitePetg, twoWhitePetg())).toEqual([0]);
+    expect(computeAmsMapping(whitePetg, twoWhitePetg(), false, undefined, blockMatte)).toEqual([1]);
+  });
+
+  it('skips a blocked tray even when it is the unique tray_info_idx match', () => {
+    const reqs = { filaments: [{ ...whitePetg.filaments[0], tray_info_idx: 'GFG03' }] };
+    const loaded = buildLoadedFilaments(twoWhitePetg(), undefined, blockMatte);
+    const [comparison] = buildFilamentComparison(reqs, loaded, {});
+    expect(comparison.loaded?.globalTrayId).toBe(1);
+  });
+
+  it('leaves no tray mapped when every candidate is blocked', () => {
+    const blockPetg: FilamentPolicy[] = [
+      { group: 'friends', mode: 'block', rules: [{ match: 'material', value: 'PETG' }] },
+    ];
+    expect(computeAmsMapping(whitePetg, twoWhitePetg(), false, undefined, blockPetg)).toEqual([-1]);
+  });
+
+  it('keeps a manual pick of a blocked tray as the user made it', () => {
+    const loaded = buildLoadedFilaments(twoWhitePetg(), undefined, blockMatte);
+    const [comparison] = buildFilamentComparison(whitePetg, loaded, { 1: 0 });
+    expect(comparison).toMatchObject({ isManual: true, loaded: { globalTrayId: 0, blocked: true } });
+  });
+
+  it('passes the policies through the hook', () => {
+    const { result } = renderHook(() =>
+      useFilamentMapping(whitePetg, twoWhitePetg(), {}, false, undefined, undefined, blockMatte),
+    );
+    expect(result.current.loadedFilaments.map((f) => !!f.blocked)).toEqual([true, false]);
+    expect(result.current.amsMapping).toEqual([1]);
+  });
+});

+ 55 - 2
frontend/src/__tests__/hooks/useMultiPrinterFilamentMapping.test.tsx

@@ -15,8 +15,8 @@
  */
 
 import { afterEach, describe, expect, it, vi } from 'vitest';
-import { renderHook } from '@testing-library/react';
-import type { PrinterStatus } from '../../api/client';
+import { act, renderHook } from '@testing-library/react';
+import type { FilamentPolicy, PrinterStatus } from '../../api/client';
 
 const statusByPrinter: Record<number, PrinterStatus> = {};
 
@@ -156,3 +156,56 @@ describe('useMultiPrinterFilamentMapping — per-printer mapping (#2799)', () =>
     expect(result.current.getFinalMapping(10)?.[2]).toBe(-1);
   });
 });
+
+// #3522: every selected printer is mapped for the signed-in user, so none of
+// them may be handed a tray holding a filament the user's groups block.
+describe('useMultiPrinterFilamentMapping — filament rules (#3522)', () => {
+  const blockMatte: FilamentPolicy[] = [
+    { group: 'friends', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] },
+  ];
+  // Light blue twice: the blocked spool first, where the match would land.
+  const withBlockedFirst = {
+    ams: [{
+      id: 0,
+      tray: [
+        { id: 0, tray_type: 'PETG', tray_color: '76D9F4FF', tray_info_idx: 'GFG03' },
+        { id: 1, tray_type: 'PETG', tray_color: '76D9F4FF', tray_info_idx: 'GFG99' },
+        { id: 2, tray_type: 'PETG', tray_color: '2850E0FF', tray_info_idx: 'GFG99' },
+      ],
+    }],
+  } as unknown as PrinterStatus;
+
+  const renderFor = (policies: FilamentPolicy[] | null, setConfigs = vi.fn()) => {
+    statusByPrinter[11] = withBlockedFirst;
+    return renderHook(() =>
+      useMultiPrinterFilamentMapping(
+        [11], [{ id: 11, name: 'P2S-6' }] as never, FILAMENT_REQS, {}, {}, setConfigs, false, undefined, null, policies,
+      ),
+    );
+  };
+
+  afterEach(() => {
+    delete statusByPrinter[11];
+  });
+
+  it('flags the blocked tray and maps around it', () => {
+    const p2s6 = renderFor(blockMatte).result.current.printerResults[0];
+    expect(p2s6.loadedFilaments.map((f) => !!f.blocked)).toEqual([true, false, false]);
+    expect(p2s6.autoMapping).toEqual([1, -1, 2]);
+    expect(p2s6.finalMapping).toEqual([1, -1, 2]);
+    expect(p2s6.matchStatus).toBe('full');
+  });
+
+  it('auto-configures around the blocked tray', () => {
+    const setConfigs = vi.fn();
+    const { result } = renderFor(blockMatte, setConfigs);
+
+    act(() => result.current.autoConfigurePrinter(11));
+    const update = setConfigs.mock.calls[0][0] as (prev: object) => Record<number, { manualMappings: object }>;
+    expect(update({})[11].manualMappings).toEqual({ 1: 1, 3: 2 });
+  });
+
+  it('maps onto the first spool when the user is unrestricted', () => {
+    expect(renderFor(null).result.current.printerResults[0].finalMapping).toEqual([0, -1, 2]);
+  });
+});

+ 72 - 0
frontend/src/__tests__/pages/GroupEditPage.test.tsx

@@ -280,6 +280,78 @@ describe('GroupEditPage', () => {
       expect(cached!.permissions).toContain('archives:read');
     });
   });
+
+  describe('filament rules (#3522)', () => {
+    let patched: Record<string, unknown> | null;
+
+    const renderEdit = async (filamentFields: Record<string, unknown>) => {
+      patched = null;
+      server.use(
+        // Registered first: the :id handler below would otherwise match /permissions too
+        http.get('/api/v1/groups/permissions', () => HttpResponse.json(mockPermissions)),
+        http.get('/api/v1/groups/:id', () =>
+          HttpResponse.json({ ...mockGroup, id: 5, name: 'Friends', is_system: false, ...filamentFields }),
+        ),
+        http.patch('/api/v1/groups/:id', async ({ request }) => {
+          patched = (await request.json()) as Record<string, unknown>;
+          return HttpResponse.json({ ...mockGroup, ...patched });
+        }),
+      );
+      const { QueryClient, QueryClientProvider } = await import('@tanstack/react-query');
+      const { MemoryRouter, Routes, Route } = await import('react-router-dom');
+      const { AuthProvider } = await import('../../contexts/AuthContext');
+      const { ToastProvider } = await import('../../contexts/ToastContext');
+      const { ThemeProvider } = await import('../../contexts/ThemeContext');
+      const { render: rtlRender } = await import('@testing-library/react');
+      const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+      rtlRender(
+        <QueryClientProvider client={queryClient}>
+          <AuthProvider>
+            <ThemeProvider>
+              <ToastProvider>
+                <MemoryRouter initialEntries={['/groups/5/edit']}>
+                  <Routes>
+                    <Route path="/groups/:id/edit" element={<GroupEditPage />} />
+                    <Route path="/settings" element={<div>Settings</div>} />
+                  </Routes>
+                </MemoryRouter>
+              </ToastProvider>
+            </ThemeProvider>
+          </AuthProvider>
+        </QueryClientProvider>
+      );
+    };
+
+    it('sends filament rules on save', async () => {
+      await renderEdit({ restrict_filaments: false, filament_rule_mode: 'block', filament_rules: [] });
+
+      await userEvent.click(await screen.findByRole('checkbox', { name: /limit filaments/i }));
+      await userEvent.type(screen.getByLabelText(/rule value/i), 'PAHT-CF');
+      await userEvent.click(screen.getByRole('button', { name: /add rule/i }));
+      await userEvent.click(screen.getByRole('button', { name: /save/i }));
+      await waitFor(() => expect(patched).not.toBeNull());
+      expect(patched).toMatchObject({
+        restrict_filaments: true,
+        filament_rule_mode: 'block',
+        filament_rules: [{ match: 'material', value: 'PAHT-CF' }],
+      });
+    });
+
+    it('saves a rule that was typed but not added', async () => {
+      // In "allow" mode an empty list blocks everyone, so losing the typed
+      // value on Save would lock the group out (#3522).
+      await renderEdit({ restrict_filaments: true, filament_rule_mode: 'allow', filament_rules: [] });
+
+      await userEvent.type(await screen.findByLabelText(/rule value/i), 'pla');
+      await userEvent.click(screen.getByRole('button', { name: /save/i }));
+      await waitFor(() => expect(patched).not.toBeNull());
+      expect(patched).toMatchObject({
+        restrict_filaments: true,
+        filament_rule_mode: 'allow',
+        filament_rules: [{ match: 'material', value: 'PLA' }],
+      });
+    });
+  });
 });
 
 describe('GroupEditPage printer access (#1727)', () => {

+ 139 - 0
frontend/src/__tests__/utils/filamentScope.test.ts

@@ -0,0 +1,139 @@
+import { describe, it, expect } from 'vitest';
+import {
+  blockedFilamentNames,
+  filamentAllowed,
+  filamentName,
+  judgedFilaments,
+  markBlocked,
+  withFilamentRule,
+} from '../../utils/filamentScope';
+import type { FilamentPolicy } from '../../api/client';
+import shared from './filamentScopeCases.json';
+
+const blockMatte: FilamentPolicy[] = [{ group: 'friends', mode: 'block', rules: [{ match: 'filament_id', value: 'GFG03' }] }];
+const allowPla: FilamentPolicy[] = [{ group: 'friends', mode: 'allow', rules: [{ match: 'material', value: 'PLA' }] }];
+
+describe('filamentAllowed', () => {
+  it('treats null or undefined policies as unrestricted', () => {
+    expect(filamentAllowed(null, 'PETG', 'GFG03')).toBe(true);
+    expect(filamentAllowed(undefined, 'PETG', 'GFG03')).toBe(true);
+  });
+  it('applies a block list by filament id, case-insensitively', () => {
+    expect(filamentAllowed(blockMatte, 'PETG', 'gfg03')).toBe(false);
+    expect(filamentAllowed(blockMatte, 'PETG', 'GFG99')).toBe(true);
+  });
+  it('matches material types exactly', () => {
+    expect(filamentAllowed(allowPla, 'pla', '')).toBe(true);
+    expect(filamentAllowed(allowPla, 'PLA-CF', '')).toBe(false);
+  });
+  it('allows when any policy allows', () => {
+    const both: FilamentPolicy[] = [...blockMatte, { group: 'b', mode: 'allow', rules: [{ match: 'filament_id', value: 'GFG03' }] }];
+    expect(filamentAllowed(both, 'PETG', 'GFG03')).toBe(true);
+  });
+  it('allows a filament with neither type nor id', () => {
+    expect(filamentAllowed(allowPla, '', '')).toBe(true);
+  });
+  it('allows nothing identifiable with an empty policy list', () => {
+    expect(filamentAllowed([], 'PLA', '')).toBe(false);
+  });
+  it('ignores a rule with an empty value, as the server does', () => {
+    const blankBlock: FilamentPolicy[] = [{ group: 'b', mode: 'block', rules: [{ match: 'material', value: '  ' }] }];
+    const blankAllow: FilamentPolicy[] = [{ group: 'a', mode: 'allow', rules: [{ match: 'material', value: '' }] }];
+    expect(filamentAllowed(blankBlock, 'PLA', '')).toBe(true);
+    expect(filamentAllowed(blankAllow, 'PLA', '')).toBe(false);
+  });
+  it('judges a filament with an id but no type by its id', () => {
+    expect(filamentAllowed(blockMatte, '', 'GFG03')).toBe(false);
+    expect(filamentAllowed(blockMatte, '', 'GFG99')).toBe(true);
+  });
+});
+
+describe('markBlocked', () => {
+  it('flags blocked trays and leaves the rest untouched', () => {
+    const loaded = [
+      { globalTrayId: 0, type: 'PETG', trayInfoIdx: 'GFG03' },
+      { globalTrayId: 1, type: 'PETG', trayInfoIdx: 'GFG99' },
+    ];
+    const marked = markBlocked(loaded, blockMatte);
+    expect(marked.map((f) => !!f.blocked)).toEqual([true, false]);
+    expect(marked[1]).toBe(loaded[1]);
+    expect(markBlocked(loaded, null)).toBe(loaded);
+  });
+});
+
+describe('filamentName', () => {
+  it('reads TYPE (ID), or TYPE alone without an id', () => {
+    expect(filamentName('PETG', 'GFG03')).toBe('PETG (GFG03)');
+    expect(filamentName('PETG', '')).toBe('PETG');
+    expect(filamentName('PETG', undefined)).toBe('PETG');
+  });
+  it('mirrors the server: trimmed, and the id alone without a type', () => {
+    expect(filamentName(' PETG ', ' GFG03 ')).toBe('PETG (GFG03)');
+    expect(filamentName('', 'GFG03')).toBe('GFG03');
+    expect(filamentName('  ', '  ')).toBe('');
+  });
+});
+
+describe('blockedFilamentNames', () => {
+  it('names each blocked requirement once, in order', () => {
+    const reqs = [
+      { type: 'PETG', tray_info_idx: 'GFG03' },
+      { type: 'PETG', tray_info_idx: 'GFG99' },
+      { type: 'PETG', tray_info_idx: 'GFG03' },
+    ];
+    expect(blockedFilamentNames(reqs, blockMatte)).toEqual(['PETG (GFG03)']);
+  });
+  it('names a requirement with no id by its type', () => {
+    expect(blockedFilamentNames([{ type: 'PETG' }, { type: 'PLA' }], allowPla)).toEqual(['PETG']);
+  });
+  it('is empty when unrestricted or there are no requirements', () => {
+    expect(blockedFilamentNames([{ type: 'PETG', tray_info_idx: 'GFG03' }], null)).toEqual([]);
+    expect(blockedFilamentNames(undefined, blockMatte)).toEqual([]);
+  });
+});
+
+describe('withFilamentRule', () => {
+  it('adds a trimmed rule, upper-casing a material, once', () => {
+    const rules = withFilamentRule([], 'material', ' petg ');
+    expect(rules).toEqual([{ match: 'material', value: 'PETG' }]);
+    expect(withFilamentRule(rules, 'material', 'Petg')).toBe(rules);
+    expect(withFilamentRule(rules, 'filament_id', ' GFG03 ')).toEqual([...rules, { match: 'filament_id', value: 'GFG03' }]);
+  });
+  it('returns the same list for a blank value', () => {
+    const rules = [{ match: 'material' as const, value: 'PLA' }];
+    expect(withFilamentRule(rules, 'material', '   ')).toBe(rules);
+  });
+});
+
+// The same cases backend/tests/unit/test_filament_scope.py feeds the server's
+// rules, so the dialog never greys out what the server allows or the reverse.
+describe('filamentAllowed agrees with the server', () => {
+  it.each(shared.cases)('$name', (c) => {
+    const policies: FilamentPolicy[] = [
+      { group: 'friends', mode: c.mode as FilamentPolicy['mode'], rules: c.rules as FilamentPolicy['rules'] },
+    ];
+    expect(filamentAllowed(policies, c.type, c.filament_id)).toBe(c.allowed);
+  });
+});
+
+// Mirrors TestJudgedRequirements in backend/tests/unit/test_filament_scope.py.
+describe('judgedFilaments', () => {
+  const reqs = [
+    { slot_id: 1, type: 'PETG', tray_info_idx: 'GFG03' },
+    { slot_id: 2, type: 'PLA', tray_info_idx: 'GFA00' },
+  ];
+  it('judges the file as sliced without overrides', () => {
+    expect(judgedFilaments(reqs, undefined)).toEqual(reqs);
+  });
+  it('leaves a swap to the tray matcher', () => {
+    expect(judgedFilaments(reqs, [{ slot_id: 1, type: 'PETG', force_color_match: false }])).toEqual([reqs[1]]);
+  });
+  it('judges a forced colour naming an id as it names it', () => {
+    expect(
+      judgedFilaments(reqs, [{ slot_id: 2, type: 'PETG', tray_info_idx: 'GFG03', force_color_match: true }]),
+    ).toEqual([reqs[0], { slot_id: 2, type: 'PETG', tray_info_idx: 'GFG03' }]);
+  });
+  it('leaves a forced colour naming no id to the tray matcher', () => {
+    expect(judgedFilaments(reqs, [{ slot_id: 1, type: 'PETG', force_color_match: true }])).toEqual([reqs[1]]);
+  });
+});

+ 17 - 0
frontend/src/__tests__/utils/filamentScopeCases.json

@@ -0,0 +1,17 @@
+{
+  "_comment": "Shared by filamentScope.test.ts and backend/tests/unit/test_filament_scope.py, so the print dialog and the server judge a filament the same way (#3522). Material rules compare the matcher's canonical type: PA-CF, PA12-CF and PAHT-CF are one material.",
+  "cases": [
+    { "name": "block PAHT-CF blocks PA-CF", "mode": "block", "rules": [{ "match": "material", "value": "PAHT-CF" }], "type": "PA-CF", "filament_id": "", "allowed": false },
+    { "name": "block PAHT-CF blocks PA12-CF", "mode": "block", "rules": [{ "match": "material", "value": "PAHT-CF" }], "type": "PA12-CF", "filament_id": "", "allowed": false },
+    { "name": "block PAHT-CF blocks padded lower-case paht-cf", "mode": "block", "rules": [{ "match": "material", "value": "PAHT-CF" }], "type": " paht-cf ", "filament_id": "", "allowed": false },
+    { "name": "block PAHT-CF leaves PA6-CF alone", "mode": "block", "rules": [{ "match": "material", "value": "PAHT-CF" }], "type": "PA6-CF", "filament_id": "", "allowed": true },
+    { "name": "allow PA-CF allows PAHT-CF", "mode": "allow", "rules": [{ "match": "material", "value": "PA-CF" }], "type": "PAHT-CF", "filament_id": "", "allowed": true },
+    { "name": "allow PA-CF holds PLA", "mode": "allow", "rules": [{ "match": "material", "value": "PA-CF" }], "type": "PLA", "filament_id": "", "allowed": false },
+    { "name": "block PETG leaves PETG-HF alone", "mode": "block", "rules": [{ "match": "material", "value": "PETG" }], "type": "PETG-HF", "filament_id": "", "allowed": true },
+    { "name": "block PETG leaves PETG-CF alone", "mode": "block", "rules": [{ "match": "material", "value": "PETG" }], "type": "PETG-CF", "filament_id": "", "allowed": true },
+    { "name": "block PETG blocks petg", "mode": "block", "rules": [{ "match": "material", "value": "PETG" }], "type": "petg", "filament_id": "GFG99", "allowed": false },
+    { "name": "block GFG03 blocks gfg03 whatever the type", "mode": "block", "rules": [{ "match": "filament_id", "value": "GFG03" }], "type": "PLA", "filament_id": "gfg03", "allowed": false },
+    { "name": "a filament id rule is not a material rule", "mode": "block", "rules": [{ "match": "filament_id", "value": "PA-CF" }], "type": "PAHT-CF", "filament_id": "", "allowed": true },
+    { "name": "no type and no id can't be judged", "mode": "allow", "rules": [{ "match": "material", "value": "PLA" }], "type": "", "filament_id": "", "allowed": true }
+  ]
+}

+ 31 - 0
frontend/src/api/client.ts

@@ -4793,6 +4793,21 @@ export interface GroupBrief {
   name: string;
 }
 
+/** One filament rule of a group (#3522): a material type or a slicer filament id */
+export interface FilamentRule {
+  match: 'material' | 'filament_id';
+  value: string;
+}
+
+export type FilamentRuleMode = 'allow' | 'block';
+
+/** One restricted group's filament rules, from /auth/me (#3522) */
+export interface FilamentPolicy {
+  group: string;
+  mode: FilamentRuleMode;
+  rules: FilamentRule[];
+}
+
 export interface Group {
   id: number;
   name: string;
@@ -4804,6 +4819,10 @@ export interface Group {
   printer_ids: number[];
   /** Matched against Printer.location, so printers added there later are included */
   locations: string[];
+  /** Members may only print with filaments these rules allow (#3522) */
+  restrict_filaments: boolean;
+  filament_rule_mode: FilamentRuleMode;
+  filament_rules: FilamentRule[];
   user_count: number;
   created_at: string;
   updated_at: string;
@@ -4820,6 +4839,9 @@ export interface GroupCreate {
   restrict_printers?: boolean;
   printer_ids?: number[];
   locations?: string[];
+  restrict_filaments?: boolean;
+  filament_rule_mode?: FilamentRuleMode;
+  filament_rules?: FilamentRule[];
 }
 
 export interface GroupUpdate {
@@ -4829,6 +4851,9 @@ export interface GroupUpdate {
   restrict_printers?: boolean;
   printer_ids?: number[];
   locations?: string[];
+  restrict_filaments?: boolean;
+  filament_rule_mode?: FilamentRuleMode;
+  filament_rules?: FilamentRule[];
 }
 
 export interface PermissionInfo {
@@ -4880,6 +4905,8 @@ export interface UserResponse {
   auth_source: string;  // "local" or "ldap"
   groups: GroupBrief[];
   permissions: Permission[];  // All permissions from groups
+  /** null: may print with every filament (#3522) */
+  filament_policies?: FilamentPolicy[] | null;
   created_at: string;
 }
 
@@ -6528,6 +6555,8 @@ export const api = {
         used_grams: number;
         used_meters: number;
         used_in_plate?: boolean;
+        /** Slicer filament preset id, e.g. GFG03; '' when the 3MF names none. */
+        tray_info_idx?: string;
       }>;
     }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
   },
@@ -8535,6 +8564,8 @@ export const api = {
         used_grams: number;
         used_meters: number;
         used_in_plate?: boolean;
+        /** Slicer filament preset id, e.g. GFG03; '' when the 3MF names none. */
+        tray_info_idx?: string;
       }>;
     }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
   },

+ 193 - 0
frontend/src/components/FilamentAccessCard.tsx

@@ -0,0 +1,193 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { AlertTriangle, Plus, Spool, X } from 'lucide-react';
+import type { FilamentRule, FilamentRuleMode } from '../api/client';
+import { Button } from './Button';
+import { Card } from './Card';
+import { withFilamentRule } from '../utils/filamentScope';
+
+// Suggestions only: any type the printer reports can be typed in.
+const MATERIAL_SUGGESTIONS = ['PLA', 'PETG', 'PCTG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'PA-CF', 'PAHT-CF', 'PET-CF', 'PVA', 'HIPS', 'PP'];
+
+export interface FilamentAccessValue {
+  enabled: boolean;
+  mode: FilamentRuleMode;
+  rules: FilamentRule[];
+}
+
+interface FilamentAccessCardProps extends FilamentAccessValue {
+  /** Administrators can't be limited: show a note instead of controls */
+  disabled?: boolean;
+  onChange: (value: FilamentAccessValue) => void;
+  /**
+   * The rules with whatever is typed in the input but not yet added. The page
+   * saves these, so a value typed and never added isn't lost on Save: in
+   * "allow" mode that would leave an empty list, which blocks every filament.
+   */
+  onPendingRulesChange?: (rules: FilamentRule[]) => void;
+}
+
+/** Which filaments a group's members may print with (#3522). */
+export function FilamentAccessCard({
+  enabled,
+  mode,
+  rules,
+  disabled = false,
+  onChange,
+  onPendingRulesChange,
+}: FilamentAccessCardProps) {
+  const { t } = useTranslation();
+  const [match, setMatch] = useState<FilamentRule['match']>('material');
+  const [value, setValue] = useState('');
+
+  // Typed text goes when the limit is switched off, which hides the input:
+  // Save must not store a rule nobody can see (#3522).
+  const [wasEnabled, setWasEnabled] = useState(enabled);
+  if (enabled !== wasEnabled) {
+    setWasEnabled(enabled);
+    if (!enabled) setValue('');
+  }
+
+  const emit = (next: Partial<FilamentAccessValue>) => onChange({ enabled, mode, rules, ...next });
+
+  useEffect(() => {
+    onPendingRulesChange?.(enabled ? withFilamentRule(rules, match, value) : rules);
+  }, [enabled, rules, match, value, onPendingRulesChange]);
+
+  const addRule = () => {
+    const next = withFilamentRule(rules, match, value);
+    if (next !== rules) emit({ rules: next });
+    setValue('');
+  };
+
+  return (
+    <Card>
+      <div className="p-4 space-y-3">
+        <div className="flex items-center gap-2">
+          <Spool className="w-4 h-4 text-bambu-gray shrink-0" />
+          <span className="text-white font-medium text-sm">{t('groups.editor.filamentAccess')}</span>
+        </div>
+
+        {disabled ? (
+          <p className="text-sm text-bambu-gray">{t('groups.editor.adminsUseAllFilaments')}</p>
+        ) : (
+          <>
+            <label className="flex items-center gap-2 text-sm text-white cursor-pointer">
+              <input
+                type="checkbox"
+                checked={enabled}
+                onChange={(e) => emit({ enabled: e.target.checked })}
+                className="w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"
+              />
+              {t('groups.editor.limitFilaments')}
+            </label>
+
+            {!enabled ? (
+              <p className="text-sm text-bambu-gray">{t('groups.editor.filamentAccessOpen')}</p>
+            ) : (
+              <div className="space-y-3">
+                <div className="flex flex-wrap gap-4 text-sm text-white">
+                  {(['block', 'allow'] as const).map((m) => (
+                    <label key={m} className="flex items-center gap-2 cursor-pointer">
+                      <input
+                        type="radio"
+                        name="filament-rule-mode"
+                        checked={mode === m}
+                        onChange={() => emit({ mode: m })}
+                        className="text-bambu-green focus:ring-bambu-green bg-bambu-dark-secondary"
+                      />
+                      {m === 'block' ? t('groups.editor.filamentModeBlock') : t('groups.editor.filamentModeAllow')}
+                    </label>
+                  ))}
+                </div>
+
+                <div className="flex flex-wrap gap-2">
+                  {rules.length === 0 ? (
+                    <span className="text-sm text-bambu-gray">{t('groups.editor.noFilamentRules')}</span>
+                  ) : (
+                    rules.map((rule) => (
+                      <span
+                        key={`${rule.match}:${rule.value}`}
+                        className="inline-flex items-center gap-1 px-2 py-1 rounded bg-bambu-dark-tertiary text-sm text-white"
+                      >
+                        <span className="text-bambu-gray">
+                          {rule.match === 'material'
+                            ? t('groups.editor.filamentMatchMaterial')
+                            : t('groups.editor.filamentMatchId')}
+                          :
+                        </span>
+                        {rule.value}
+                        <button
+                          type="button"
+                          aria-label={t('groups.editor.removeFilamentRule', { value: rule.value })}
+                          onClick={() => emit({ rules: rules.filter((r) => r !== rule) })}
+                          className="text-bambu-gray hover:text-white"
+                        >
+                          <X className="w-3 h-3" />
+                        </button>
+                      </span>
+                    ))
+                  )}
+                </div>
+
+                {/* The backend treats an empty allow list as "allow nothing" (#3522) */}
+                {mode === 'allow' && rules.length === 0 && (
+                  <p role="status" className="flex items-center gap-2 text-sm text-yellow-700 dark:text-yellow-400">
+                    <AlertTriangle className="w-4 h-4 shrink-0" />
+                    {t('groups.editor.filamentAllowEmptyWarning')}
+                  </p>
+                )}
+
+                <div className="flex flex-wrap items-center gap-2">
+                  <select
+                    value={match}
+                    onChange={(e) => {
+                      // A value typed for one kind of rule is not one of the other.
+                      setMatch(e.target.value as FilamentRule['match']);
+                      setValue('');
+                    }}
+                    className="px-3 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white"
+                  >
+                    <option value="material">{t('groups.editor.filamentMatchMaterial')}</option>
+                    <option value="filament_id">{t('groups.editor.filamentMatchId')}</option>
+                  </select>
+                  <input
+                    type="text"
+                    aria-label={t('groups.editor.filamentRuleValue')}
+                    value={value}
+                    list={match === 'material' ? 'filament-material-suggestions' : undefined}
+                    onChange={(e) => setValue(e.target.value)}
+                    onKeyDown={(e) => {
+                      if (e.key === 'Enter') {
+                        e.preventDefault();
+                        addRule();
+                      }
+                    }}
+                    placeholder={
+                      match === 'material'
+                        ? t('groups.editor.filamentRuleMaterialPlaceholder')
+                        : t('groups.editor.filamentRuleIdPlaceholder')
+                    }
+                    maxLength={64}
+                    className="px-3 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray w-48"
+                  />
+                  <datalist id="filament-material-suggestions">
+                    {MATERIAL_SUGGESTIONS.map((m) => (
+                      <option key={m} value={m} />
+                    ))}
+                  </datalist>
+                  <Button size="sm" variant="secondary" onClick={addRule} disabled={!value.trim()}>
+                    <Plus className="w-4 h-4" />
+                    {t('groups.editor.addFilamentRule')}
+                  </Button>
+                </div>
+
+                <p className="text-xs text-bambu-gray/80">{t('groups.editor.filamentRulesHint')}</p>
+              </div>
+            )}
+          </>
+        )}
+      </div>
+    </Card>
+  );
+}

+ 40 - 4
frontend/src/components/PrintModal/FilamentMapping.tsx

@@ -13,6 +13,8 @@ import { useFilamentLabels } from './useFilamentLabels';
 import { autoAssignRackPositions, rackOptionsForGroup } from '../../utils/nozzleRack';
 import type { FilamentMappingProps, RackGroupInfo } from './types';
 import { useUiSettings } from '../../hooks/useUiSettings';
+import { useFilamentPolicies } from '../../hooks/useFilamentPolicies';
+import { filamentName } from '../../utils/filamentScope';
 
 /**
  * Filament mapping UI for comparing required filaments with loaded AMS slots.
@@ -21,6 +23,7 @@ import { useUiSettings } from '../../hooks/useUiSettings';
 export function FilamentMapping({
   printerId,
   filamentReqs,
+  blockedFilaments,
   manualMappings,
   onManualMappingChange,
   onEstimatedCostChange,
@@ -102,6 +105,7 @@ export function FilamentMapping({
   // the dispatcher uses (#1766). Without this, the per-slot dropdown's
   // auto-suggestion could disagree with what actually gets dispatched.
   const { data: settings } = useUiSettings();
+  const filamentPolicies = useFilamentPolicies();
   const { data: inventoryRemain } = useQuery({
     queryKey: ['printer-inventory-remain', printerId],
     queryFn: () => api.getInventoryRemain(printerId),
@@ -152,8 +156,16 @@ export function FilamentMapping({
       gatedPreferLowest,
       inventoryByTrayId,
       slotSpools,
+      filamentPolicies,
     );
 
+  // Filaments this file needs that the user's group may not print with
+  // (#3522). The server refuses such a job; this says so before submitting.
+  // The dialog passes the list its submit check uses, so the two never disagree.
+  const blockedReqNames = blockedFilaments;
+  const blockedSlotReason = (f: { type: string; trayInfoIdx?: string }) =>
+    t('printModal.filamentBlockedSlot', { filament: filamentName(f.type, f.trayInfoIdx) });
+
   // Per-slot sub-brand + material-disambiguated colour labels (#1718). Same
   // shared hook the model-mode FilamentOverride uses so both panels render
   // the same sliced-3MF identity. Falls back to the raw type / generic
@@ -298,7 +310,10 @@ export function FilamentMapping({
   }
 
   // Determine status indicator color
-  const statusColor = hasTypeMismatch
+  // A blocked filament outranks every mismatch: Print is disabled for it (#3522).
+  const statusColor = blockedReqNames.length > 0
+    ? '#ef4444' // red
+    : hasTypeMismatch
     ? '#f97316' // orange
     : hasColorMismatch
     ? '#facc15' // yellow
@@ -342,7 +357,9 @@ export function FilamentMapping({
       >
         <Circle className="w-4 h-4" fill={statusColor} stroke="none" />
         <span>{plateLabel ? `${t('printModal.filamentMapping')} — ${plateLabel}` : t('printModal.filamentMapping')}</span>
-        {hasTypeMismatch ? (
+        {blockedReqNames.length > 0 ? (
+          <span className="text-xs text-red-700 dark:text-red-400">({t('printModal.statusBlocked')})</span>
+        ) : hasTypeMismatch ? (
           <span className="text-xs text-orange-700 dark:text-orange-400">({t('printModal.statusTypeNotFound')})</span>
         ) : hasColorMismatch ? (
           <span className="text-xs text-yellow-700 dark:text-yellow-400">({t('printModal.statusColorMismatch')})</span>
@@ -356,6 +373,15 @@ export function FilamentMapping({
         )}
       </button>
 
+      {/* Outside the collapsible part: the panel starts collapsed, and this is
+          the reason the submit button is disabled (#3522). */}
+      {blockedReqNames.length > 0 && (
+        <div role="alert" className="mt-2 flex items-start gap-2 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/20 text-red-700 dark:text-red-400 text-xs">
+          <AlertTriangle className="w-3 h-3 mt-0.5 shrink-0" />
+          {t('printModal.filamentBlockedFile', { filaments: blockedReqNames.join(', ') })}
+        </div>
+      )}
+
       {isExpanded && (
         <div className="mt-2 bg-bambu-dark rounded-lg p-3 space-y-2">
           <div className="flex items-center justify-between mb-2">
@@ -549,11 +575,21 @@ export function FilamentMapping({
                         exactMatch:
                           normalizeColorForCompare(item.color) !== '' &&
                           normalizeColorForCompare(f.color) === normalizeColorForCompare(item.color),
+                        // Listed but not selectable: the group may not use it (#3522).
+                        disabled: f.blocked,
+                        disabledReason: f.blocked ? blockedSlotReason(f) : undefined,
                       };
                   })}
                 />
-                {/* Status icon */}
-                {item.status === 'match' ? (
+                {/* Status icon. A blocked tray outranks the match status: it
+                    can still be the chosen one through a manual pick (an older
+                    queue job, the archive's saved mapping), and the server
+                    will pick another tray for it (#3522). */}
+                {item.loaded?.blocked ? (
+                  <span role="img" title={blockedSlotReason(item.loaded)} aria-label={blockedSlotReason(item.loaded)}>
+                    <AlertTriangle className="w-3 h-3 text-red-600 dark:text-red-400" />
+                  </span>
+                ) : item.status === 'match' ? (
                   <Check className="w-3 h-3 text-bambu-green" />
                 ) : item.status === 'type_only' ? (
                   <span

+ 25 - 14
frontend/src/components/PrintModal/FilamentOverride.tsx

@@ -6,6 +6,8 @@ import { canonicalFilamentType, normalizeColorForCompare } from '../../utils/ams
 import { SlotPicker } from './SlotPicker';
 import { displayHex } from './displayHex';
 import { useFilamentLabels } from './useFilamentLabels';
+import { useFilamentPolicies } from '../../hooks/useFilamentPolicies';
+import { filamentAllowed, filamentName } from '../../utils/filamentScope';
 import type { FilamentReqsData } from './types';
 
 interface FilamentOverrideProps {
@@ -47,6 +49,7 @@ export function FilamentOverride({
   // shared hook fronts the three queries that power the resolution so this
   // component and ``FilamentMapping`` cannot drift apart on label content.
   const labels = useFilamentLabels(filamentReqs?.filaments);
+  const filamentPolicies = useFilamentPolicies();
 
   // Index available filaments by canonical type for per-slot filtering.
   // Types in the same equivalence group (e.g. PA-CF / PA12-CF / PAHT-CF) share one bucket.
@@ -145,20 +148,28 @@ export function FilamentOverride({
                       ? 'border-blue-500/50 dark:border-blue-400/50 text-blue-700 dark:text-blue-400'
                       : 'border-bambu-gray/30 text-bambu-gray'
                   }
-                  options={compatible.map((f, idx) => ({
-                    // The value has to stay `TYPE|COLOR` -- `handleChange`
-                    // parses it -- but two spools of the same type and colour
-                    // on different printers collapse to one value, so the key
-                    // keeps the sub-brand and the index as it did before.
-                    value: `${f.type}|${f.color}`,
-                    key: `${f.type}-${f.color}-${f.tray_sub_brands}-${idx}`,
-                    label: `${f.tray_sub_brands || f.type} (${getColorName(f.color, f.tray_sub_brands, f.tray_info_idx)})`,
-                    rgba: f.color,
-                    hex: displayHex(f.color),
-                    exactMatch:
-                      normalizeColorForCompare(req.color) !== '' &&
-                      normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color),
-                  }))}
+                  options={compatible.map((f, idx) => {
+                    // Listed but not selectable: the group may not use it (#3522).
+                    const blocked = !filamentAllowed(filamentPolicies, f.type, f.tray_info_idx);
+                    return {
+                      // The value has to stay `TYPE|COLOR` -- `handleChange`
+                      // parses it -- but two spools of the same type and colour
+                      // on different printers collapse to one value, so the key
+                      // keeps the sub-brand and the index as it did before.
+                      value: `${f.type}|${f.color}`,
+                      key: `${f.type}-${f.color}-${f.tray_sub_brands}-${idx}`,
+                      label: `${f.tray_sub_brands || f.type} (${getColorName(f.color, f.tray_sub_brands, f.tray_info_idx)})`,
+                      rgba: f.color,
+                      hex: displayHex(f.color),
+                      exactMatch:
+                        normalizeColorForCompare(req.color) !== '' &&
+                        normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color),
+                      disabled: blocked,
+                      disabledReason: blocked
+                        ? t('printModal.filamentBlockedSlot', { filament: filamentName(f.type, f.tray_info_idx) })
+                        : undefined,
+                    };
+                  })}
                 />
                 {/* Reset button */}
                 {isOverridden ? (

+ 2 - 1
frontend/src/components/PrintModal/PrinterSelector.tsx

@@ -188,7 +188,8 @@ function InlineMappingEditor({
             </option>
             {filterFilamentsByNozzle(printerResult.loadedFilaments, req.nozzle_id)
               .map((f) => (
-              <option key={f.globalTrayId} value={f.globalTrayId} className="bg-bambu-dark text-white">
+              // Listed but not selectable: the group may not use it (#3522).
+              <option key={f.globalTrayId} value={f.globalTrayId} disabled={f.blocked} className="bg-bambu-dark text-white">
                 {f.label}: {f.traySubBrands || f.type} ({f.colorName})
               </option>
             ))}

+ 13 - 2
frontend/src/components/PrintModal/SlotPicker.tsx

@@ -51,6 +51,10 @@ export interface SlotPickerOption {
    *  every printer of a model, so two spools of the same type and colour
    *  collapse to one `TYPE|COLOR` value while still being two rows. */
   key?: string;
+  /** Shown but not selectable, e.g. a filament the user's group may not use (#3522). */
+  disabled?: boolean;
+  /** Tooltip saying why the row is disabled. */
+  disabledReason?: string;
 }
 
 interface SlotPickerProps {
@@ -178,6 +182,9 @@ export function SlotPicker({
   }, [open, place]);
 
   const choose = (index: number) => {
+    // A disabled row is listed so the user can see why the slot is not used,
+    // not to be picked; the list stays open for another choice (#3522).
+    if (rows[index].disabled) return;
     onChange(rows[index].value);
     setOpen(false);
     triggerRef.current?.focus();
@@ -288,6 +295,8 @@ export function SlotPicker({
                 // identity of the choice, separate from how it reads.
                 data-value={row.value}
                 aria-selected={index === selectedIndex}
+                aria-disabled={row.disabled || undefined}
+                title={row.disabled ? row.disabledReason : undefined}
                 onMouseEnter={() => setActiveIndex(index)}
                 onClick={() => choose(index)}
                 className={`w-full flex items-center gap-1.5 text-left px-2 py-1.5 rounded-md text-xs ${
@@ -296,10 +305,12 @@ export function SlotPicker({
                     : index === activeIndex
                       ? 'bg-bambu-dark text-white'
                       : 'text-white'
-                }`}
+                }${row.disabled ? ' opacity-40 cursor-not-allowed' : ''}`}
               >
                 {renderSwatch(row)}
-                <span className="flex-1 min-w-0 truncate" title={row.label}>
+                {/* No title of its own on a disabled row: the label fills most
+                    of the row, and its title would hide the row's reason. */}
+                <span className="flex-1 min-w-0 truncate" title={row.disabled ? undefined : row.label}>
                   {row.label}
                   {row.meta ? <span className="text-bambu-gray">{row.meta}</span> : null}
                 </span>

+ 83 - 4
frontend/src/components/PrintModal/index.tsx

@@ -1,6 +1,6 @@
 import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
 import { AlertCircle, AlertTriangle, Layers, Loader2, Pencil, Printer, ThumbsUp, X } from 'lucide-react';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 import { useTranslation } from 'react-i18next';
 import type { CostCenterSummary, PrintQueueItemCreate, PrintQueueItemUpdate, SlotMaterial } from '../../api/client';
 import { api } from '../../api/client';
@@ -16,6 +16,8 @@ import {
   useFilamentMapping,
 } from '../../hooks/useFilamentMapping';
 import { useMultiPrinterFilamentMapping, type PerPrinterConfig } from '../../hooks/useMultiPrinterFilamentMapping';
+import { useFilamentPolicies } from '../../hooks/useFilamentPolicies';
+import { blockedFilamentNames, judgedFilaments } from '../../utils/filamentScope';
 import { getColorName } from '../../utils/colors';
 import { productLineOf, useFilamentNameByIdx } from './useFilamentLabels';
 import { isGcodeCompatible, isPrinterCurrentlyDispatchable } from '../../utils/printer';
@@ -116,6 +118,7 @@ export function PrintModal({
   const queryClient = useQueryClient();
   const { showToast } = useToast();
   const { hasPermission, hasAnyPermission, user } = useAuth();
+  const filamentPolicies = useFilamentPolicies();
   // Their jobs wait for someone to start them (#1620); the server enforces it,
   // this keeps the request and the dialog honest about it.
   const needsReview = !hasAnyPermission('queue:start_unreviewed', 'queue:update_all');
@@ -723,6 +726,8 @@ export function PrintModal({
     manualMappings,
     singlePrinterPreferLowest,
     effectivePrinterId ? inventoryByTrayIdPerPrinter.get(effectivePrinterId) : undefined,
+    undefined,
+    filamentPolicies,
   );
 
   // --- Per-plate filament mapping (multi-plate submissions) ---------------
@@ -812,7 +817,7 @@ export function PrintModal({
     const byPlate = new Map<number, number[] | undefined>();
     if (!isMultiPlateSelection || !effectivePrinterId || selectedPrinters.length !== 1) return byPlate;
 
-    const loaded = buildLoadedFilaments(printerStatus);
+    const loaded = buildLoadedFilaments(printerStatus, undefined, filamentPolicies);
     const ftsActive = printerStatus?.fila_switch?.installed === true;
     const inventoryByTrayId = inventoryByTrayIdPerPrinter.get(effectivePrinterId);
 
@@ -840,6 +845,7 @@ export function PrintModal({
     manualMappingsByPlate,
     singlePrinterPreferLowest,
     selectedPrinters.length,
+    filamentPolicies,
   ]);
 
   // Multi-printer filament mapping (for per-printer configuration)
@@ -853,6 +859,7 @@ export function PrintModal({
     settings?.prefer_lowest_filament,
     inventoryByTrayIdPerPrinter,
     sharedMappingPrinterId,
+    filamentPolicies,
   );
 
   // Auto-select first plate when plates load (single or multi-plate). A plate
@@ -1944,6 +1951,56 @@ export function PrintModal({
   const waitingForAmsStatus =
     !isSeparateJobs && assignmentMode === 'printer' && selectedPrinters.length === 1 && printerStatusLoading;
 
+  // Filaments the file needs that the user's group may not print with (#3522).
+  // The server refuses the job (403) on the file's filaments with the job's
+  // overrides applied (`judgedFilaments`, as the scheduler applies them), so
+  // this reads the plate's requirements, or each selected plate's, with the
+  // overrides the job will be sent with: a changed slot, and a ticked "Force
+  // color match" wherever the box is saved, carrying the preset id a stored
+  // entry kept (see `buildFilamentOverridesArray`). The mapping panels are
+  // handed these same lists for their banner, so a disabled Print always has
+  // its reason on screen. Separate jobs skip it, as the spool check does: these
+  // are the first file's filaments only, and the server judges each job by its
+  // own file.
+  const sentOverrides = useCallback(
+    (reqs: FilamentReqsData | undefined) => {
+      const stored = new Map(
+        (mode === 'edit-queue-item' ? queueItem?.filament_overrides ?? [] : []).map((o) => [o.slot_id, o]),
+      );
+      const ticksSaved = assignmentMode === 'model' || selectedPrinters.length === 1;
+      return (reqs?.filaments ?? []).flatMap((req) => {
+        const swap = filamentOverrides[req.slot_id];
+        const forced = forceColorMatch[req.slot_id] ?? false;
+        if (!swap && !(forced && ticksSaved)) return [];
+        const filament = { type: swap?.type ?? req.type, color: swap?.color ?? req.color };
+        const kept = stored.get(req.slot_id);
+        const variant = kept?.tray_info_idx && isSameFilament(kept, filament) ? kept.tray_info_idx : undefined;
+        return [{ slot_id: req.slot_id, type: filament.type, tray_info_idx: variant, force_color_match: forced }];
+      });
+    },
+    [mode, queueItem, assignmentMode, selectedPrinters.length, filamentOverrides, forceColorMatch],
+  );
+  const blockedFilamentsSinglePlate = useMemo(
+    () =>
+      blockedFilamentNames(
+        judgedFilaments(effectiveFilamentReqs?.filaments, sentOverrides(effectiveFilamentReqs)),
+        filamentPolicies,
+      ),
+    [effectiveFilamentReqs, sentOverrides, filamentPolicies],
+  );
+  const blockedFilamentsByPlate = useMemo(() => {
+    const byPlate = new Map<number, string[]>();
+    for (const [plateId, reqs] of perPlateReqs) {
+      byPlate.set(plateId, blockedFilamentNames(judgedFilaments(reqs.filaments, sentOverrides(reqs)), filamentPolicies));
+    }
+    return byPlate;
+  }, [perPlateReqs, sentOverrides, filamentPolicies]);
+  const blockedFileFilaments = useMemo(() => {
+    if (isSeparateJobs) return [];
+    if (!isMultiPlateSelection) return blockedFilamentsSinglePlate;
+    return [...new Set([...blockedFilamentsByPlate.values()].flat())];
+  }, [isSeparateJobs, isMultiPlateSelection, blockedFilamentsSinglePlate, blockedFilamentsByPlate]);
+
   const canSubmit = useMemo(() => {
     if (isPending) return false;
 
@@ -1976,8 +2033,12 @@ export function PrintModal({
     // The printer's live status first (#2589, see waitingForAmsStatus).
     if (waitingForAmsStatus) return false;
 
+    // Saves the round-trip to a 403 (#3522); the banner says which filament.
+    if (blockedFileFilaments.length > 0) return false;
+
     return true;
   }, [
+    blockedFileFilaments,
     selectedPrinters.length,
     assignmentMode,
     targetModel,
@@ -2086,6 +2147,12 @@ export function PrintModal({
   // computes one per plate when it picks the printer.
   const showPerPlateFilamentMapping =
     !isSeparateJobs && !!effectivePrinterId && isMultiPlateSelection && selectedPrinters.length === 1;
+  // The two FilamentMapping render sites below, decided once: whether a panel
+  // is on screen is also whether a blocked filament already has its banner
+  // there (#3522).
+  const singleMappingPanelShown = !!showFilamentMapping && !archiveDataMissing && selectedPrinters.length === 1;
+  const perPlateMappingPanelsShown = showPerPlateFilamentMapping && !archiveDataMissing;
+  const mappingPanelShown = singleMappingPanelShown || perPlateMappingPanelsShown;
 
   // Model mode has no printer and so no trays to map onto; what it offers instead
   // is the filament each slot must be printed in, which the scheduler matches
@@ -2415,10 +2482,11 @@ export function PrintModal({
             )}
 
             {/* Filament mapping - only show when single printer selected */}
-            {showFilamentMapping && !archiveDataMissing && selectedPrinters.length === 1 && (
+            {singleMappingPanelShown && (
               <FilamentMapping
                 printerId={effectivePrinterId!}
                 filamentReqs={mappingFilamentReqs}
+                blockedFilaments={blockedFilamentsSinglePlate}
                 manualMappings={manualMappings}
                 onManualMappingChange={(next) => {
                   // This panel only renders for a single selected printer, so
@@ -2444,7 +2512,7 @@ export function PrintModal({
 
             {/* Filament mapping, one panel per selected plate — each plate is its
                 own print with its own slots, so it gets its own AMS mapping. */}
-            {showPerPlateFilamentMapping && !archiveDataMissing && selectedPlateIds.map((plateId) => {
+            {perPlateMappingPanelsShown && selectedPlateIds.map((plateId) => {
               const plate = plates.find((p) => p.index === plateId);
               const plateReqs = mappingPerPlateReqs.get(plateId);
               if (!plateReqs) return null;
@@ -2454,6 +2522,7 @@ export function PrintModal({
                   printerId={effectivePrinterId!}
                   plateLabel={plate?.name || t('printModal.plateN', 'Plate {{n}}', { n: plateId })}
                   filamentReqs={plateReqs}
+                  blockedFilaments={blockedFilamentsByPlate.get(plateId) ?? []}
                   manualMappings={manualMappingsByPlate[plateId] ?? {}}
                   onManualMappingChange={(mappings) =>
                     setManualMappingsByPlate((prev) => ({ ...prev, [plateId]: mappings }))
@@ -2584,6 +2653,16 @@ export function PrintModal({
               </div>
             )}
 
+            {/* The mapping panel names a blocked filament when it is shown. Model
+                mode and several printers have no panel, and the disabled
+                button still needs a reason (#3522). */}
+            {blockedFileFilaments.length > 0 && !mappingPanelShown && (
+              <div role="alert" className="mb-4 p-3 bg-red-100 dark:bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-700 dark:text-red-400 flex items-start gap-2">
+                <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
+                {t('printModal.filamentBlockedFile', { filaments: blockedFileFilaments.join(', ') })}
+              </div>
+            )}
+
             {selectedPlatesSummary && (
               <p
                 className="flex items-center gap-1.5 text-sm text-bambu-gray min-w-0"

+ 4 - 0
frontend/src/components/PrintModal/types.ts

@@ -296,6 +296,10 @@ export interface FilamentMappingProps {
   printerId: number;
   /** Pre-fetched filament requirements data */
   filamentReqs: FilamentReqsData | undefined;
+  /** Filaments the file needs that the user's group may not use, as the
+   *  dialog's submit check sees them (#3522). `filamentReqs` can carry a
+   *  colour override in their place, so the banner must not judge those. */
+  blockedFilaments: string[];
   manualMappings: Record<number, number>;
   onManualMappingChange: (mappings: Record<number, number>) => void;
   onEstimatedCostChange?: (estimatedCost: number | null) => void;

+ 22 - 8
frontend/src/hooks/useFilamentMapping.ts

@@ -15,7 +15,8 @@ import {
   rackExternalLabel,
 } from '../utils/amsHelpers';
 import { externalSlotIndex, trayLayoutOf } from '../utils/trayIds';
-import type { PrinterStatus, SlotSpoolIdentity } from '../api/client';
+import { markBlocked } from '../utils/filamentScope';
+import type { FilamentPolicy, PrinterStatus, SlotSpoolIdentity } from '../api/client';
 
 /** Global-tray-id → the identity of the spool Bambuddy has bound to that slot. */
 export type SlotSpoolIdentities = Map<number, SlotSpoolIdentity>;
@@ -46,10 +47,14 @@ function spoolDisplayName(identity: SlotSpoolIdentity | undefined): string | nul
  * `slotSpools` is optional and display-only: it renames slots after their
  * bound spool without touching `type`, `color` or `trayInfoIdx`, so matching
  * and the dispatcher keep drawing on the printer's own telemetry.
+ *
+ * `policies` are the signed-in user's filament rules (#3522): trays they don't
+ * allow come back with `blocked` set.
  */
 export function buildLoadedFilaments(
   printerStatus: PrinterStatus | undefined,
   slotSpools?: SlotSpoolIdentities,
+  policies?: FilamentPolicy[] | null,
 ): LoadedFilament[] {
   const filaments: LoadedFilament[] = [];
   const amsExtruderMap = printerStatus?.ams_extruder_map;
@@ -131,7 +136,7 @@ export function buildLoadedFilaments(
     }
   }
 
-  return filaments;
+  return markBlocked(filaments, policies);
 }
 
 /**
@@ -148,6 +153,7 @@ export function buildLoadedFilaments(
  *
  * @param filamentReqs - Required filaments from the 3MF file
  * @param printerStatus - Current printer status with AMS information
+ * @param policies - The signed-in user's filament rules (#3522); blocked trays are never picked
  * @returns AMS mapping array or undefined if no mapping needed
  */
 export function computeAmsMapping(
@@ -155,8 +161,9 @@ export function computeAmsMapping(
   printerStatus: PrinterStatus | undefined,
   preferLowest?: boolean,
   inventoryByTrayId?: Map<number, number>,
+  policies?: FilamentPolicy[] | null,
 ): number[] | undefined {
-  const loadedFilaments = buildLoadedFilaments(printerStatus);
+  const loadedFilaments = buildLoadedFilaments(printerStatus, undefined, policies);
   if (loadedFilaments.length === 0) return undefined;
 
   // FTS routes any AMS slot to any extruder, so per-nozzle slot restriction
@@ -205,6 +212,8 @@ export interface LoadedFilament {
   /** The bound spool's subtype ("PLA Silk", "Multicolor"), which decides
    *  whether the swatch renders its stops as a conic sweep. */
   spoolSubtype?: string;
+  /** The signed-in user's groups may not use this filament (#3522): never auto-picked, greyed out in the picker */
+  blocked?: boolean;
 }
 
 /**
@@ -269,10 +278,11 @@ interface UseFilamentMappingResult {
 export function useLoadedFilaments(
   printerStatus: PrinterStatus | undefined,
   slotSpools?: SlotSpoolIdentities,
+  policies?: FilamentPolicy[] | null,
 ): LoadedFilament[] {
   return useMemo(() => {
-    return buildLoadedFilaments(printerStatus, slotSpools);
-  }, [printerStatus, slotSpools]);
+    return buildLoadedFilaments(printerStatus, slotSpools, policies);
+  }, [printerStatus, slotSpools, policies]);
 }
 
 /**
@@ -357,8 +367,10 @@ export function buildFilamentComparison(
     // IMPORTANT: Exclude trays that are already assigned (manually or auto)
     const reqTrayInfoIdx = req.tray_info_idx || '';
 
-    // Get available trays (not already used)
-    let available = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
+    // Get available trays (not already used). A tray the user's groups block is
+    // never auto-picked (#3522); a manual pick of one is kept above as theirs,
+    // and the scheduler re-picks it at dispatch.
+    let available = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId) && !f.blocked);
 
     // Nozzle-aware filtering: restrict to trays on the correct nozzle.
     // This is a hard filter — cross-nozzle assignment causes print failures.
@@ -519,8 +531,10 @@ export function useFilamentMapping(
   preferLowest?: boolean,
   inventoryByTrayId?: Map<number, number>,
   slotSpools?: SlotSpoolIdentities,
+  /** The signed-in user's filament rules (#3522), from `useFilamentPolicies` */
+  policies?: FilamentPolicy[] | null,
 ): UseFilamentMappingResult {
-  const loadedFilaments = useLoadedFilaments(printerStatus, slotSpools);
+  const loadedFilaments = useLoadedFilaments(printerStatus, slotSpools, policies);
 
   // FTS routes any AMS slot to any extruder, so per-nozzle slot restriction
   // doesn't apply when it's installed (#1162).

+ 9 - 0
frontend/src/hooks/useFilamentPolicies.ts

@@ -0,0 +1,9 @@
+import { useAuth } from '../contexts/AuthContext';
+import type { FilamentPolicy } from '../api/client';
+
+/** The signed-in user's filament rules (#3522); null when unrestricted or auth is off. */
+export function useFilamentPolicies(): FilamentPolicy[] | null {
+  const { authEnabled, user } = useAuth();
+  if (!authEnabled) return null;
+  return user?.filament_policies ?? null;
+}

+ 18 - 10
frontend/src/hooks/useMultiPrinterFilamentMapping.ts

@@ -1,7 +1,7 @@
 import { useMemo } from 'react';
 import { useQueries } from '@tanstack/react-query';
 import { api } from '../api/client';
-import type { PrinterStatus, Printer } from '../api/client';
+import type { FilamentPolicy, PrinterStatus, Printer } from '../api/client';
 import {
   buildLoadedFilaments,
   computeAmsMapping,
@@ -133,8 +133,9 @@ function computeMatchDetails(
       }
     }
 
-    // Auto-match with nozzle-aware filtering
-    let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
+    // Auto-match with nozzle-aware filtering. A tray the user's groups block
+    // is never auto-picked (#3522).
+    let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId) && !f.blocked);
     if (req.nozzle_id != null) {
       const nozzleFiltered = candidates.filter((f) => f.extruderId === req.nozzle_id);
       if (nozzleFiltered.length > 0) {
@@ -204,10 +205,11 @@ function computeMappingWithOverrides(
   manualMappings: Record<number, number>,
   preferLowest?: boolean,
   inventoryByTrayId?: Map<number, number>,
+  policies?: FilamentPolicy[] | null,
 ): number[] | undefined {
   if (!filamentReqs?.filaments || filamentReqs.filaments.length === 0) return undefined;
 
-  const loadedFilaments = buildLoadedFilaments(printerStatus);
+  const loadedFilaments = buildLoadedFilaments(printerStatus, undefined, policies);
   if (loadedFilaments.length === 0) return undefined;
 
   const usedTrayIds = new Set<number>(Object.values(manualMappings));
@@ -222,8 +224,9 @@ function computeMappingWithOverrides(
       continue;
     }
 
-    // Auto-match with nozzle-aware filtering
-    let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
+    // Auto-match with nozzle-aware filtering. A tray the user's groups block
+    // is never auto-picked (#3522).
+    let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId) && !f.blocked);
     if (req.nozzle_id != null) {
       const nozzleFiltered = candidates.filter((f) => f.extruderId === req.nozzle_id);
       if (nozzleFiltered.length > 0) {
@@ -310,6 +313,8 @@ export function useMultiPrinterFilamentMapping(
    * then empty anyway.
    */
   defaultMappingsPrinterId?: number | null,
+  /** The signed-in user's filament rules (#3522), from `useFilamentPolicies` */
+  policies?: FilamentPolicy[] | null,
 ): UseMultiPrinterFilamentMappingResult {
   // Fetch printer status for all selected printers in parallel
   const statusQueries = useQueries({
@@ -329,7 +334,7 @@ export function useMultiPrinterFilamentMapping(
       const printer = printers?.find((p) => p.id === printerId);
       const printerName = printer?.name || `Printer ${printerId}`;
 
-      const loadedFilaments = buildLoadedFilaments(printerStatus);
+      const loadedFilaments = buildLoadedFilaments(printerStatus, undefined, policies);
       const config = perPrinterConfigs[printerId] || DEFAULT_PRINTER_CONFIG;
       const inventoryByTrayId = inventoryByTrayIdPerPrinter?.get(printerId);
       // Per-printer gate (#1766): two printers in the same dispatch can have
@@ -338,7 +343,7 @@ export function useMultiPrinterFilamentMapping(
       const printerPreferLowest = effectivePreferLowest(preferLowest, printerStatus?.ams_filament_backup);
 
       // Compute auto mapping for this printer
-      const autoMapping = computeAmsMapping(filamentReqs, printerStatus, printerPreferLowest, inventoryByTrayId);
+      const autoMapping = computeAmsMapping(filamentReqs, printerStatus, printerPreferLowest, inventoryByTrayId, policies);
 
       // Which manual overrides apply to THIS printer.
       //
@@ -368,7 +373,9 @@ export function useMultiPrinterFilamentMapping(
           : {};
 
       // Compute final mapping with overrides
-      const finalMapping = computeMappingWithOverrides(filamentReqs, printerStatus, effectiveMappings, printerPreferLowest, inventoryByTrayId);
+      const finalMapping = computeMappingWithOverrides(
+        filamentReqs, printerStatus, effectiveMappings, printerPreferLowest, inventoryByTrayId, policies,
+      );
 
       // Compute match details
       const matchDetails = computeMatchDetails(
@@ -396,7 +403,7 @@ export function useMultiPrinterFilamentMapping(
         inventoryByTrayId,
       };
     });
-  }, [selectedPrinterIds, statusQueries, printers, filamentReqs, perPrinterConfigs, defaultMappings, preferLowest, inventoryByTrayIdPerPrinter, defaultMappingsPrinterId]);
+  }, [selectedPrinterIds, statusQueries, printers, filamentReqs, perPrinterConfigs, defaultMappings, preferLowest, inventoryByTrayIdPerPrinter, defaultMappingsPrinterId, policies]);
 
   const isLoading = statusQueries.some((q) => q.isLoading);
 
@@ -422,6 +429,7 @@ export function useMultiPrinterFilamentMapping(
       result.status,
       effectivePreferLowest(preferLowest, result.status?.ams_filament_backup),
       inventoryByTrayIdPerPrinter?.get(printerId),
+      policies,
     );
     if (!autoMapping) return;
 

+ 19 - 0
frontend/src/i18n/locales/de.ts

@@ -3791,6 +3791,22 @@ export default {
       printerAccessLimited: 'Eingeschränkt: {{printers}} Drucker ausgewählt, {{locations}} Standorte',
       printerAccessOpen: 'Nicht eingeschränkt: Mitglieder sehen alle Drucker.',
       managePrinterAccess: 'Druckerzugriff verwalten',
+      filamentAccess: 'Filamentzugriff',
+      adminsUseAllFilaments: 'Administratoren können immer alle Filamente verwenden.',
+      limitFilaments: 'Filamente einschränken',
+      filamentAccessOpen: 'Nicht eingeschränkt: Mitglieder können mit jedem Filament drucken.',
+      filamentModeBlock: 'Diese Filamente sperren',
+      filamentModeAllow: 'Nur diese Filamente erlauben',
+      filamentMatchMaterial: 'Materialtyp',
+      filamentMatchId: 'Filament-ID',
+      filamentRuleValue: 'Regelwert',
+      filamentRuleMaterialPlaceholder: 'z. B. PETG',
+      filamentRuleIdPlaceholder: 'z. B. GFG03',
+      addFilamentRule: 'Regel hinzufügen',
+      removeFilamentRule: '{{value}} entfernen',
+      noFilamentRules: 'Noch keine Regeln.',
+      filamentAllowEmptyWarning: 'Ohne Regeln sperrt eine Erlaubnisliste jedes Filament.',
+      filamentRulesHint: 'Ein Materialtyp passt über seinen Namen (PETG passt nicht zu PETG-CF); PA-CF, PA12-CF und PAHT-CF zählen als ein Material, so wie der Drucker sie behandelt. Eine Filament-ID ist die ID des Slicer-Presets, z. B. GFG03 für Bambu PETG Matte. Ein Mitglied darf ein Filament verwenden, wenn eine seiner eingeschränkten Gruppen es erlaubt.',
     },
   },
 
@@ -5790,6 +5806,7 @@ export default {
     sameTypeDifferentColor: 'Gleicher Typ, andere Farbe',
     filamentTypeNotLoaded: 'Filamenttyp nicht geladen',
     statusReady: 'Bereit',
+    statusBlocked: 'Gesperrt',
     statusColorMismatch: 'Farbe weicht ab',
     statusTypeNotFound: 'Typ nicht gefunden',
     requiredTooltip: 'Benötigt: {{name}} - {{color}}',
@@ -5801,6 +5818,8 @@ export default {
     overrideForFilament: 'Filament-Überschreibung für {{name}}',
     sameTypeDifferentColorDetail: 'Gleicher Typ, andere Farbe: benötigt {{required}}, im Slot ist {{loaded}}',
     requiredTypeNotInPrinter: 'Benötigter Filamenttyp im Drucker nicht gefunden.',
+    filamentBlockedSlot: 'Deine Gruppe darf {{filament}} nicht verwenden',
+    filamentBlockedFile: 'Diese Datei verwendet ein Filament, mit dem deine Gruppe nicht drucken darf: {{filaments}}',
     whenToPrint: 'Wann drucken',
     asap: 'Sofort',
     queue: 'Warteschlange',

+ 19 - 0
frontend/src/i18n/locales/en.ts

@@ -3823,6 +3823,22 @@ export default {
       printerAccessLimited: 'Limited: {{printers}} printers picked, {{locations}} locations',
       printerAccessOpen: 'Not limited: members see every printer.',
       managePrinterAccess: 'Manage printer access',
+      filamentAccess: 'Filament access',
+      adminsUseAllFilaments: 'Administrators can always use every filament.',
+      limitFilaments: 'Limit filaments',
+      filamentAccessOpen: 'Not limited: members may print with any filament.',
+      filamentModeBlock: 'Block these filaments',
+      filamentModeAllow: 'Allow only these filaments',
+      filamentMatchMaterial: 'Material type',
+      filamentMatchId: 'Filament ID',
+      filamentRuleValue: 'Rule value',
+      filamentRuleMaterialPlaceholder: 'e.g. PETG',
+      filamentRuleIdPlaceholder: 'e.g. GFG03',
+      addFilamentRule: 'Add rule',
+      removeFilamentRule: 'Remove {{value}}',
+      noFilamentRules: 'No rules yet.',
+      filamentAllowEmptyWarning: 'With no rules, an allow list blocks every filament.',
+      filamentRulesHint: 'A material type matches by its name (PETG does not match PETG-CF); PA-CF, PA12-CF and PAHT-CF count as one material, as the printer treats them. A filament ID is the slicer preset ID, e.g. GFG03 for Bambu PETG Matte. A member may use a filament if any of their limited groups allows it.',
     },
   },
 
@@ -5837,6 +5853,7 @@ export default {
     sameTypeDifferentColor: 'Same type, different color',
     filamentTypeNotLoaded: 'Filament type not loaded',
     statusReady: 'Ready',
+    statusBlocked: 'Blocked',
     statusColorMismatch: 'Color mismatch',
     statusTypeNotFound: 'Type not found',
     requiredTooltip: 'Required: {{name}} - {{color}}',
@@ -5848,6 +5865,8 @@ export default {
     overrideForFilament: 'Filament override for {{name}}',
     sameTypeDifferentColorDetail: 'Same type, different color: needs {{required}}, slot has {{loaded}}',
     requiredTypeNotInPrinter: 'Required filament type not found in printer.',
+    filamentBlockedSlot: 'Your group can\'t use {{filament}}',
+    filamentBlockedFile: 'This file uses a filament your group can\'t print with: {{filaments}}',
     whenToPrint: 'When to print',
     asap: 'ASAP',
     queue: 'Queue',

+ 19 - 0
frontend/src/i18n/locales/es.ts

@@ -3793,6 +3793,22 @@ export default {
       printerAccessLimited: 'Limitado: {{printers}} impresoras elegidas, {{locations}} ubicaciones',
       printerAccessOpen: 'Sin límite: los miembros ven todas las impresoras.',
       managePrinterAccess: 'Gestionar acceso a impresoras',
+      filamentAccess: 'Acceso a filamentos',
+      adminsUseAllFilaments: 'Los administradores siempre pueden usar todos los filamentos.',
+      limitFilaments: 'Limitar filamentos',
+      filamentAccessOpen: 'Sin límite: los miembros pueden imprimir con cualquier filamento.',
+      filamentModeBlock: 'Bloquear estos filamentos',
+      filamentModeAllow: 'Permitir solo estos filamentos',
+      filamentMatchMaterial: 'Tipo de material',
+      filamentMatchId: 'ID de filamento',
+      filamentRuleValue: 'Valor de la regla',
+      filamentRuleMaterialPlaceholder: 'p. ej. PETG',
+      filamentRuleIdPlaceholder: 'p. ej. GFG03',
+      addFilamentRule: 'Añadir regla',
+      removeFilamentRule: 'Quitar {{value}}',
+      noFilamentRules: 'Aún no hay reglas.',
+      filamentAllowEmptyWarning: 'Sin reglas, una lista de permitidos bloquea todos los filamentos.',
+      filamentRulesHint: 'Un tipo de material coincide por su nombre (PETG no coincide con PETG-CF); PA-CF, PA12-CF y PAHT-CF cuentan como un solo material, como los trata la impresora. Un ID de filamento es el ID del preajuste del laminador, p. ej. GFG03 para Bambu PETG Matte. Un miembro puede usar un filamento si alguno de sus grupos limitados lo permite.',
     },
   },
 
@@ -5797,6 +5813,7 @@ export default {
     sameTypeDifferentColor: 'Mismo tipo, color distinto',
     filamentTypeNotLoaded: 'Tipo de filamento no cargado',
     statusReady: 'Listo',
+    statusBlocked: 'Bloqueado',
     statusColorMismatch: 'Color distinto',
     statusTypeNotFound: 'Tipo no encontrado',
     requiredTooltip: 'Requerido: {{name}} - {{color}}',
@@ -5808,6 +5825,8 @@ export default {
     overrideForFilament: 'Anulación de filamento para {{name}}',
     sameTypeDifferentColorDetail: 'Mismo tipo, color distinto: necesita {{required}}, la ranura tiene {{loaded}}',
     requiredTypeNotInPrinter: 'El tipo de filamento requerido no se encuentra en la impresora.',
+    filamentBlockedSlot: 'Tu grupo no puede usar {{filament}}',
+    filamentBlockedFile: 'Este archivo usa un filamento con el que tu grupo no puede imprimir: {{filaments}}',
     whenToPrint: 'Cuándo imprimir',
     asap: 'Lo antes posible',
     queue: 'Cola',

+ 19 - 0
frontend/src/i18n/locales/fr.ts

@@ -3779,6 +3779,22 @@ export default {
       printerAccessLimited: 'Limité : {{printers}} imprimantes choisies, {{locations}} emplacements',
       printerAccessOpen: 'Non limité : les membres voient toutes les imprimantes.',
       managePrinterAccess: 'Gérer l\'accès aux imprimantes',
+      filamentAccess: 'Accès aux filaments',
+      adminsUseAllFilaments: 'Les administrateurs peuvent toujours utiliser tous les filaments.',
+      limitFilaments: 'Limiter les filaments',
+      filamentAccessOpen: 'Non limité : les membres peuvent imprimer avec n\'importe quel filament.',
+      filamentModeBlock: 'Bloquer ces filaments',
+      filamentModeAllow: 'Autoriser uniquement ces filaments',
+      filamentMatchMaterial: 'Type de matériau',
+      filamentMatchId: 'ID du filament',
+      filamentRuleValue: 'Valeur de la règle',
+      filamentRuleMaterialPlaceholder: 'ex. PETG',
+      filamentRuleIdPlaceholder: 'ex. GFG03',
+      addFilamentRule: 'Ajouter une règle',
+      removeFilamentRule: 'Retirer {{value}}',
+      noFilamentRules: 'Aucune règle pour l\'instant.',
+      filamentAllowEmptyWarning: 'Sans règle, une liste d\'autorisation bloque tous les filaments.',
+      filamentRulesHint: 'Un type de matériau correspond par son nom (PETG ne correspond pas à PETG-CF) ; PA-CF, PA12-CF et PAHT-CF comptent comme un seul matériau, comme l\'imprimante les traite. Un ID de filament est l\'ID du préréglage du slicer, ex. GFG03 pour Bambu PETG Matte. Un membre peut utiliser un filament si l\'un de ses groupes limités l\'autorise.',
     },
   },
 
@@ -5777,6 +5793,7 @@ export default {
     sameTypeDifferentColor: 'Même type, couleur différente',
     filamentTypeNotLoaded: 'Type de filament non chargé',
     statusReady: 'Prêt',
+    statusBlocked: 'Bloqué',
     statusColorMismatch: 'Couleur différente',
     statusTypeNotFound: 'Type introuvable',
     requiredTooltip: 'Requis : {{name}} - {{color}}',
@@ -5788,6 +5805,8 @@ export default {
     overrideForFilament: 'Remplacement de filament pour {{name}}',
     sameTypeDifferentColorDetail: 'Même type, couleur différente : requiert {{required}}, l’emplacement contient {{loaded}}',
     requiredTypeNotInPrinter: 'Type de filament requis introuvable dans l’imprimante.',
+    filamentBlockedSlot: 'Votre groupe ne peut pas utiliser {{filament}}',
+    filamentBlockedFile: 'Ce fichier utilise un filament avec lequel votre groupe ne peut pas imprimer : {{filaments}}',
     whenToPrint: 'Quand imprimer',
     asap: 'Dès que possible',
     queue: 'File',

+ 19 - 0
frontend/src/i18n/locales/it.ts

@@ -3778,6 +3778,22 @@ export default {
       printerAccessLimited: 'Limitato: {{printers}} stampanti scelte, {{locations}} posizioni',
       printerAccessOpen: 'Non limitato: i membri vedono tutte le stampanti.',
       managePrinterAccess: 'Gestisci accesso alle stampanti',
+      filamentAccess: 'Accesso ai filamenti',
+      adminsUseAllFilaments: 'Gli amministratori possono sempre usare tutti i filamenti.',
+      limitFilaments: 'Limita i filamenti',
+      filamentAccessOpen: 'Non limitato: i membri possono stampare con qualsiasi filamento.',
+      filamentModeBlock: 'Blocca questi filamenti',
+      filamentModeAllow: 'Consenti solo questi filamenti',
+      filamentMatchMaterial: 'Tipo di materiale',
+      filamentMatchId: 'ID filamento',
+      filamentRuleValue: 'Valore della regola',
+      filamentRuleMaterialPlaceholder: 'es. PETG',
+      filamentRuleIdPlaceholder: 'es. GFG03',
+      addFilamentRule: 'Aggiungi regola',
+      removeFilamentRule: 'Rimuovi {{value}}',
+      noFilamentRules: 'Ancora nessuna regola.',
+      filamentAllowEmptyWarning: 'Senza regole, un elenco di consentiti blocca ogni filamento.',
+      filamentRulesHint: 'Un tipo di materiale corrisponde per nome (PETG non corrisponde a PETG-CF); PA-CF, PA12-CF e PAHT-CF contano come un unico materiale, come li tratta la stampante. Un ID filamento è l\'ID del preset dello slicer, es. GFG03 per Bambu PETG Matte. Un membro può usare un filamento se uno qualsiasi dei suoi gruppi limitati lo consente.',
     },
   },
 
@@ -5776,6 +5792,7 @@ export default {
     sameTypeDifferentColor: 'Stesso tipo, colore diverso',
     filamentTypeNotLoaded: 'Tipo di filamento non caricato',
     statusReady: 'Pronto',
+    statusBlocked: 'Bloccato',
     statusColorMismatch: 'Colore diverso',
     statusTypeNotFound: 'Tipo non trovato',
     requiredTooltip: 'Richiesto: {{name}} - {{color}}',
@@ -5787,6 +5804,8 @@ export default {
     overrideForFilament: 'Sostituzione filamento per {{name}}',
     sameTypeDifferentColorDetail: 'Stesso tipo, colore diverso: richiede {{required}}, lo slot ha {{loaded}}',
     requiredTypeNotInPrinter: 'Tipo di filamento richiesto non trovato nella stampante.',
+    filamentBlockedSlot: 'Il tuo gruppo non può usare {{filament}}',
+    filamentBlockedFile: 'Questo file usa un filamento con cui il tuo gruppo non può stampare: {{filaments}}',
     whenToPrint: 'Quando stampare',
     asap: 'Subito',
     queue: 'Coda',

+ 19 - 0
frontend/src/i18n/locales/ja.ts

@@ -3791,6 +3791,22 @@ export default {
       printerAccessLimited: '制限あり: {{printers}} 台のプリンターを選択、{{locations}} 件のロケーション',
       printerAccessOpen: '制限なし: メンバーはすべてのプリンターを表示できます。',
       managePrinterAccess: 'プリンターへのアクセスを管理',
+      filamentAccess: 'フィラメントへのアクセス',
+      adminsUseAllFilaments: '管理者は常にすべてのフィラメントを使用できます。',
+      limitFilaments: 'フィラメントを制限',
+      filamentAccessOpen: '制限なし: メンバーはどのフィラメントでも印刷できます。',
+      filamentModeBlock: 'これらのフィラメントをブロック',
+      filamentModeAllow: 'これらのフィラメントのみ許可',
+      filamentMatchMaterial: '材料の種類',
+      filamentMatchId: 'フィラメント ID',
+      filamentRuleValue: 'ルールの値',
+      filamentRuleMaterialPlaceholder: '例: PETG',
+      filamentRuleIdPlaceholder: '例: GFG03',
+      addFilamentRule: 'ルールを追加',
+      removeFilamentRule: '{{value}} を削除',
+      noFilamentRules: 'ルールはまだありません。',
+      filamentAllowEmptyWarning: 'ルールがない場合、許可リストはすべてのフィラメントをブロックします。',
+      filamentRulesHint: '材料の種類は名前で判定されます (PETG は PETG-CF に一致しません)。ただし PA-CF、PA12-CF、PAHT-CF はプリンターと同様に同じ材料として扱われます。フィラメント ID はスライサープリセットの ID です (例: Bambu PETG Matte は GFG03)。メンバーは、所属する制限付きグループのいずれかが許可していれば、そのフィラメントを使用できます。',
     },
   },
 
@@ -5790,6 +5806,7 @@ export default {
     sameTypeDifferentColor: '同じ種類、異なる色',
     filamentTypeNotLoaded: 'フィラメントタイプが未読み込み',
     statusReady: '準備完了',
+    statusBlocked: '使用不可',
     statusColorMismatch: '色が不一致',
     statusTypeNotFound: 'タイプが見つかりません',
     requiredTooltip: '必要: {{name}} - {{color}}',
@@ -5801,6 +5818,8 @@ export default {
     overrideForFilament: '{{name}} のフィラメントオーバーライド',
     sameTypeDifferentColorDetail: '同じ種類、異なる色: 必要な色は {{required}}、スロットは {{loaded}}',
     requiredTypeNotInPrinter: '必要なフィラメントタイプがプリンターに見つかりません。',
+    filamentBlockedSlot: 'あなたのグループは {{filament}} を使用できません',
+    filamentBlockedFile: 'このファイルには、あなたのグループが印刷に使用できないフィラメントが含まれています: {{filaments}}',
     whenToPrint: '印刷タイミング',
     asap: '即時',
     queue: 'キュー',

+ 19 - 0
frontend/src/i18n/locales/ko.ts

@@ -3620,6 +3620,22 @@ export default {
       printerAccessLimited: '제한됨: 프린터 {{printers}}대 선택, 위치 {{locations}}개',
       printerAccessOpen: '제한 없음: 구성원은 모든 프린터를 볼 수 있습니다.',
       managePrinterAccess: '프린터 접근 관리',
+      filamentAccess: '필라멘트 접근',
+      adminsUseAllFilaments: '관리자는 항상 모든 필라멘트를 사용할 수 있습니다.',
+      limitFilaments: '필라멘트 제한',
+      filamentAccessOpen: '제한 없음: 구성원은 어떤 필라멘트로든 출력할 수 있습니다.',
+      filamentModeBlock: '이 필라멘트 차단',
+      filamentModeAllow: '이 필라멘트만 허용',
+      filamentMatchMaterial: '재료 유형',
+      filamentMatchId: '필라멘트 ID',
+      filamentRuleValue: '규칙 값',
+      filamentRuleMaterialPlaceholder: '예: PETG',
+      filamentRuleIdPlaceholder: '예: GFG03',
+      addFilamentRule: '규칙 추가',
+      removeFilamentRule: '{{value}} 제거',
+      noFilamentRules: '아직 규칙이 없습니다.',
+      filamentAllowEmptyWarning: '규칙이 없으면 허용 목록이 모든 필라멘트를 차단합니다.',
+      filamentRulesHint: '재료 유형은 이름으로 일치 여부를 판단합니다(PETG는 PETG-CF와 일치하지 않음). 단, PA-CF, PA12-CF, PAHT-CF는 프린터와 마찬가지로 하나의 재료로 취급됩니다. 필라멘트 ID는 슬라이서 프리셋 ID입니다(예: Bambu PETG Matte는 GFG03). 구성원이 속한 제한 그룹 중 하나라도 허용하면 해당 필라멘트를 사용할 수 있습니다.',
     }
   },
 
@@ -5560,6 +5576,7 @@ export default {
     sameTypeDifferentColor: '같은 유형, 다른 색상',
     filamentTypeNotLoaded: '필라멘트 유형이 장착되지 않음',
     statusReady: '준비됨',
+    statusBlocked: '사용 불가',
     statusColorMismatch: '색상 불일치',
     statusTypeNotFound: '유형을 찾을 수 없음',
     requiredTooltip: '필요: {{name}} - {{color}}',
@@ -5571,6 +5588,8 @@ export default {
     overrideForFilament: '{{name}}의 필라멘트 재정의',
     sameTypeDifferentColorDetail: '같은 유형, 다른 색상: {{required}} 필요, 슬롯에는 {{loaded}}',
     requiredTypeNotInPrinter: '필요한 필라멘트 유형을 프린터에서 찾을 수 없습니다.',
+    filamentBlockedSlot: '내 그룹은 {{filament}}을(를) 사용할 수 없습니다',
+    filamentBlockedFile: '이 파일은 내 그룹이 인쇄에 사용할 수 없는 필라멘트를 사용합니다: {{filaments}}',
     whenToPrint: '인쇄 시점',
     asap: '최대한 빨리',
     queue: '대기열',

+ 19 - 0
frontend/src/i18n/locales/nl.ts

@@ -3821,6 +3821,22 @@ export default {
       printerAccessLimited: 'Beperkt: {{printers}} printers gekozen, {{locations}} locaties',
       printerAccessOpen: 'Niet beperkt: leden zien alle printers.',
       managePrinterAccess: 'Printertoegang beheren',
+      filamentAccess: 'Filamenttoegang',
+      adminsUseAllFilaments: 'Beheerders kunnen altijd elk filament gebruiken.',
+      limitFilaments: 'Filamenten beperken',
+      filamentAccessOpen: 'Niet beperkt: leden mogen met elk filament printen.',
+      filamentModeBlock: 'Deze filamenten blokkeren',
+      filamentModeAllow: 'Alleen deze filamenten toestaan',
+      filamentMatchMaterial: 'Materiaaltype',
+      filamentMatchId: 'Filament-ID',
+      filamentRuleValue: 'Regelwaarde',
+      filamentRuleMaterialPlaceholder: 'bijv. PETG',
+      filamentRuleIdPlaceholder: 'bijv. GFG03',
+      addFilamentRule: 'Regel toevoegen',
+      removeFilamentRule: '{{value}} verwijderen',
+      noFilamentRules: 'Nog geen regels.',
+      filamentAllowEmptyWarning: 'Zonder regels blokkeert een toelatingslijst elk filament.',
+      filamentRulesHint: 'Een materiaaltype komt overeen op naam (PETG komt niet overeen met PETG-CF); PA-CF, PA12-CF en PAHT-CF tellen als één materiaal, zoals de printer ze behandelt. Een filament-ID is de ID van de slicer-preset, bijv. GFG03 voor Bambu PETG Matte. Een lid mag een filament gebruiken als een van zijn beperkte groepen het toestaat.',
     },
   },
 
@@ -5835,6 +5851,7 @@ export default {
     sameTypeDifferentColor: 'Zelfde type, andere kleur',
     filamentTypeNotLoaded: 'Filamenttype niet geladen',
     statusReady: 'Gereed',
+    statusBlocked: 'Geblokkeerd',
     statusColorMismatch: 'Kleur komt niet overeen',
     statusTypeNotFound: 'Type niet gevonden',
     requiredTooltip: 'Vereist: {{name}} - {{color}}',
@@ -5846,6 +5863,8 @@ export default {
     overrideForFilament: 'Filament overschrijven voor {{name}}',
     sameTypeDifferentColorDetail: 'Zelfde type, andere kleur: vereist {{required}}, sleuf bevat {{loaded}}',
     requiredTypeNotInPrinter: 'Vereist filamenttype niet gevonden in printer.',
+    filamentBlockedSlot: 'Je groep mag {{filament}} niet gebruiken',
+    filamentBlockedFile: 'Dit bestand gebruikt een filament waarmee je groep niet mag printen: {{filaments}}',
     whenToPrint: 'Wanneer afdrukken',
     asap: 'Zo snel mogelijk',
     queue: 'Wachtrij',

+ 19 - 0
frontend/src/i18n/locales/pl.ts

@@ -3823,6 +3823,22 @@ export default {
       printerAccessLimited: 'Ograniczony: wybrane drukarki: {{printers}}, lokalizacje: {{locations}}',
       printerAccessOpen: 'Bez ograniczeń: członkowie widzą wszystkie drukarki.',
       managePrinterAccess: 'Zarządzaj dostępem do drukarek',
+      filamentAccess: 'Dostęp do filamentów',
+      adminsUseAllFilaments: 'Administratorzy zawsze mogą używać wszystkich filamentów.',
+      limitFilaments: 'Ogranicz filamenty',
+      filamentAccessOpen: 'Bez ograniczeń: członkowie mogą drukować dowolnym filamentem.',
+      filamentModeBlock: 'Blokuj te filamenty',
+      filamentModeAllow: 'Zezwalaj tylko na te filamenty',
+      filamentMatchMaterial: 'Typ materiału',
+      filamentMatchId: 'ID filamentu',
+      filamentRuleValue: 'Wartość reguły',
+      filamentRuleMaterialPlaceholder: 'np. PETG',
+      filamentRuleIdPlaceholder: 'np. GFG03',
+      addFilamentRule: 'Dodaj regułę',
+      removeFilamentRule: 'Usuń {{value}}',
+      noFilamentRules: 'Brak reguł.',
+      filamentAllowEmptyWarning: 'Bez reguł lista dozwolonych blokuje wszystkie filamenty.',
+      filamentRulesHint: 'Typ materiału jest dopasowywany po nazwie (PETG nie pasuje do PETG-CF); PA-CF, PA12-CF i PAHT-CF liczą się jako jeden materiał, tak jak traktuje je drukarka. ID filamentu to ID profilu slicera, np. GFG03 dla Bambu PETG Matte. Członek może używać filamentu, jeśli zezwala na to którakolwiek z jego ograniczonych grup.',
     },
   },
 
@@ -5837,6 +5853,7 @@ export default {
     sameTypeDifferentColor: 'Ten sam typ, inny kolor',
     filamentTypeNotLoaded: 'Typ filamentu nie jest załadowany',
     statusReady: 'Gotowe',
+    statusBlocked: 'Zablokowane',
     statusColorMismatch: 'Niezgodny kolor',
     statusTypeNotFound: 'Nie znaleziono typu',
     requiredTooltip: 'Wymagane: {{name}} - {{color}}',
@@ -5848,6 +5865,8 @@ export default {
     overrideForFilament: 'Zastąpienie filamentu dla {{name}}',
     sameTypeDifferentColorDetail: 'Ten sam typ, inny kolor: wymagany {{required}}, w slocie jest {{loaded}}',
     requiredTypeNotInPrinter: 'Nie znaleziono w drukarce wymaganego typu filamentu.',
+    filamentBlockedSlot: 'Twoja grupa nie może używać {{filament}}',
+    filamentBlockedFile: 'Ten plik używa filamentu, którym Twoja grupa nie może drukować: {{filaments}}',
     whenToPrint: 'Kiedy drukować',
     asap: 'Jak najszybciej',
     queue: 'Kolejka',

+ 19 - 0
frontend/src/i18n/locales/pt-BR.ts

@@ -3778,6 +3778,22 @@ export default {
       printerAccessLimited: 'Limitado: {{printers}} impressoras escolhidas, {{locations}} locais',
       printerAccessOpen: 'Sem limite: os membros veem todas as impressoras.',
       managePrinterAccess: 'Gerenciar acesso às impressoras',
+      filamentAccess: 'Acesso aos filamentos',
+      adminsUseAllFilaments: 'Administradores sempre podem usar todos os filamentos.',
+      limitFilaments: 'Limitar filamentos',
+      filamentAccessOpen: 'Sem limite: os membros podem imprimir com qualquer filamento.',
+      filamentModeBlock: 'Bloquear estes filamentos',
+      filamentModeAllow: 'Permitir apenas estes filamentos',
+      filamentMatchMaterial: 'Tipo de material',
+      filamentMatchId: 'ID do filamento',
+      filamentRuleValue: 'Valor da regra',
+      filamentRuleMaterialPlaceholder: 'ex.: PETG',
+      filamentRuleIdPlaceholder: 'ex.: GFG03',
+      addFilamentRule: 'Adicionar regra',
+      removeFilamentRule: 'Remover {{value}}',
+      noFilamentRules: 'Nenhuma regra ainda.',
+      filamentAllowEmptyWarning: 'Sem regras, uma lista de permitidos bloqueia todos os filamentos.',
+      filamentRulesHint: 'Um tipo de material corresponde pelo nome (PETG não corresponde a PETG-CF); PA-CF, PA12-CF e PAHT-CF contam como um só material, como a impressora os trata. Um ID de filamento é o ID da predefinição do fatiador, ex.: GFG03 para Bambu PETG Matte. Um membro pode usar um filamento se qualquer um dos seus grupos limitados permitir.',
     },
   },
 
@@ -5776,6 +5792,7 @@ export default {
     sameTypeDifferentColor: 'Mesmo tipo, cor diferente',
     filamentTypeNotLoaded: 'Tipo de filamento não carregado',
     statusReady: 'Pronto',
+    statusBlocked: 'Bloqueado',
     statusColorMismatch: 'Cor diferente',
     statusTypeNotFound: 'Tipo não encontrado',
     requiredTooltip: 'Necessário: {{name}} - {{color}}',
@@ -5787,6 +5804,8 @@ export default {
     overrideForFilament: 'Substituição de filamento para {{name}}',
     sameTypeDifferentColorDetail: 'Mesmo tipo, cor diferente: precisa de {{required}}, o slot tem {{loaded}}',
     requiredTypeNotInPrinter: 'Tipo de filamento necessário não encontrado na impressora.',
+    filamentBlockedSlot: 'Seu grupo não pode usar {{filament}}',
+    filamentBlockedFile: 'Este arquivo usa um filamento com o qual seu grupo não pode imprimir: {{filaments}}',
     whenToPrint: 'Quando imprimir',
     asap: 'O quanto antes',
     queue: 'Fila',

+ 19 - 0
frontend/src/i18n/locales/ru.ts

@@ -3612,6 +3612,22 @@ export default {
       printerAccessLimited: 'Ограничена: выбрано принтеров — {{printers}}, расположений — {{locations}}',
       printerAccessOpen: 'Без ограничений: участники видят все принтеры.',
       managePrinterAccess: 'Управление доступом к принтерам',
+      filamentAccess: 'Доступ к филаментам',
+      adminsUseAllFilaments: 'Администраторы всегда могут использовать любой филамент.',
+      limitFilaments: 'Ограничить филаменты',
+      filamentAccessOpen: 'Без ограничений: участники могут печатать любым филаментом.',
+      filamentModeBlock: 'Запретить эти филаменты',
+      filamentModeAllow: 'Разрешить только эти филаменты',
+      filamentMatchMaterial: 'Тип материала',
+      filamentMatchId: 'ID филамента',
+      filamentRuleValue: 'Значение правила',
+      filamentRuleMaterialPlaceholder: 'напр. PETG',
+      filamentRuleIdPlaceholder: 'напр. GFG03',
+      addFilamentRule: 'Добавить правило',
+      removeFilamentRule: 'Удалить {{value}}',
+      noFilamentRules: 'Правил пока нет.',
+      filamentAllowEmptyWarning: 'Без правил список разрешённых запрещает любой филамент.',
+      filamentRulesHint: 'Тип материала сравнивается по названию (PETG не совпадает с PETG-CF); PA-CF, PA12-CF и PAHT-CF считаются одним материалом, как и для принтера. ID филамента — это ID пресета слайсера, напр. GFG03 для Bambu PETG Matte. Участник может использовать филамент, если его разрешает хотя бы одна из его ограниченных групп.',
     },
   },
 
@@ -5549,6 +5565,7 @@ export default {
     sameTypeDifferentColor: "Тот же тип, другой цвет",
     filamentTypeNotLoaded: "Филамент этого типа не загружен",
     statusReady: "Готово",
+    statusBlocked: "Заблокировано",
     statusColorMismatch: "Цвет не совпадает",
     statusTypeNotFound: "Тип не найден",
     requiredTooltip: "Требуется: {{name}} - {{color}}",
@@ -5560,6 +5577,8 @@ export default {
     overrideForFilament: "Переопределение филамента для {{name}}",
     sameTypeDifferentColorDetail: "Тот же тип, другой цвет: нужен {{required}}, в слоте {{loaded}}",
     requiredTypeNotInPrinter: "Требуемый тип филамента не найден в принтере.",
+    filamentBlockedSlot: 'Вашей группе нельзя использовать {{filament}}',
+    filamentBlockedFile: 'В этом файле используется филамент, которым вашей группе нельзя печатать: {{filaments}}',
     whenToPrint: "Когда печатать",
     asap: "Как можно скорее",
     queue: "В очередь",

+ 19 - 0
frontend/src/i18n/locales/sv.ts

@@ -3853,6 +3853,22 @@ errors: {
       printerAccessLimited: 'Begränsad: {{printers}} skrivare valda, {{locations}} platser',
       printerAccessOpen: 'Inte begränsad: medlemmar ser alla skrivare.',
       managePrinterAccess: 'Hantera skrivaråtkomst',
+      filamentAccess: 'Filamentåtkomst',
+      adminsUseAllFilaments: 'Administratörer kan alltid använda alla filament.',
+      limitFilaments: 'Begränsa filament',
+      filamentAccessOpen: 'Inte begränsad: medlemmar får skriva ut med vilket filament som helst.',
+      filamentModeBlock: 'Blockera dessa filament',
+      filamentModeAllow: 'Tillåt endast dessa filament',
+      filamentMatchMaterial: 'Materialtyp',
+      filamentMatchId: 'Filament-ID',
+      filamentRuleValue: 'Regelvärde',
+      filamentRuleMaterialPlaceholder: 't.ex. PETG',
+      filamentRuleIdPlaceholder: 't.ex. GFG03',
+      addFilamentRule: 'Lägg till regel',
+      removeFilamentRule: 'Ta bort {{value}}',
+      noFilamentRules: 'Inga regler än.',
+      filamentAllowEmptyWarning: 'Utan regler blockerar en tillåtelselista alla filament.',
+      filamentRulesHint: 'En materialtyp matchas på namnet (PETG matchar inte PETG-CF); PA-CF, PA12-CF och PAHT-CF räknas som ett material, så som skrivaren behandlar dem. Ett filament-ID är ID:t för slicer-förinställningen, t.ex. GFG03 för Bambu PETG Matte. En medlem får använda ett filament om någon av medlemmens begränsade grupper tillåter det.',
     },
   },
 
@@ -5866,6 +5882,7 @@ errors: {
     sameTypeDifferentColor: 'Samma typ, olika färg',
     filamentTypeNotLoaded: 'Filamenttyp inte laddad',
     statusReady: 'Redo',
+    statusBlocked: 'Blockerad',
     statusColorMismatch: 'Färg matchar ej',
     statusTypeNotFound: 'Typ hittades ej',
     requiredTooltip: 'Kräver: {{name}} - {{color}}',
@@ -5877,6 +5894,8 @@ errors: {
     overrideForFilament: 'Åsidosätt filament för {{name}}',
     sameTypeDifferentColorDetail: 'Samma typ, annan färg: behöver {{required}}, facket har {{loaded}}',
     requiredTypeNotInPrinter: 'Krävd filamenttyp hittades inte i skrivaren.',
+    filamentBlockedSlot: 'Din grupp får inte använda {{filament}}',
+    filamentBlockedFile: 'Den här filen använder ett filament som din grupp inte får skriva ut med: {{filaments}}',
     whenToPrint: 'När utskriften ska starta',
     asap: 'Så snart som möjligt',
     queue: 'Kö',

+ 19 - 0
frontend/src/i18n/locales/tr.ts

@@ -3794,6 +3794,22 @@ export default {
       printerAccessLimited: 'Sınırlı: {{printers}} yazıcı seçildi, {{locations}} konum',
       printerAccessOpen: 'Sınırsız: üyeler tüm yazıcıları görür.',
       managePrinterAccess: 'Yazıcı erişimini yönet',
+      filamentAccess: 'Filament erişimi',
+      adminsUseAllFilaments: 'Yöneticiler her zaman tüm filamentleri kullanabilir.',
+      limitFilaments: 'Filamentleri sınırla',
+      filamentAccessOpen: 'Sınırsız: üyeler herhangi bir filamentle baskı yapabilir.',
+      filamentModeBlock: 'Bu filamentleri engelle',
+      filamentModeAllow: 'Yalnızca bu filamentlere izin ver',
+      filamentMatchMaterial: 'Malzeme türü',
+      filamentMatchId: 'Filament kimliği',
+      filamentRuleValue: 'Kural değeri',
+      filamentRuleMaterialPlaceholder: 'örn. PETG',
+      filamentRuleIdPlaceholder: 'örn. GFG03',
+      addFilamentRule: 'Kural ekle',
+      removeFilamentRule: '{{value}} öğesini kaldır',
+      noFilamentRules: 'Henüz kural yok.',
+      filamentAllowEmptyWarning: 'Kural yoksa izin listesi tüm filamentleri engeller.',
+      filamentRulesHint: 'Malzeme türü adıyla eşleşir (PETG, PETG-CF ile eşleşmez); PA-CF, PA12-CF ve PAHT-CF, yazıcının yaptığı gibi tek bir malzeme sayılır. Filament kimliği, dilimleyici ön ayarının kimliğidir; örn. Bambu PETG Matte için GFG03. Bir üye, sınırlı gruplarından herhangi biri izin veriyorsa o filamenti kullanabilir.',
     },
   },
 
@@ -5766,6 +5782,7 @@ export default {
     sameTypeDifferentColor: 'Aynı tür, farklı renk',
     filamentTypeNotLoaded: 'Filament türü yüklenmedi',
     statusReady: 'Hazır',
+    statusBlocked: 'Engellendi',
     statusColorMismatch: 'Renk uyuşmuyor',
     statusTypeNotFound: 'Tür bulunamadı',
     requiredTooltip: 'Gereken: {{name}} - {{color}}',
@@ -5777,6 +5794,8 @@ export default {
     overrideForFilament: '{{name}} için filament geçersiz kılma',
     sameTypeDifferentColorDetail: 'Aynı tür, farklı renk: {{required}} gerekiyor, yuvada {{loaded}} var',
     requiredTypeNotInPrinter: 'Gereken filament türü yazıcıda bulunamadı.',
+    filamentBlockedSlot: 'Grubunuz {{filament}} kullanamaz',
+    filamentBlockedFile: 'Bu dosya, grubunuzun baskı için kullanamayacağı bir filament kullanıyor: {{filaments}}',
     whenToPrint: 'Ne zaman yazdırılsın',
     asap: 'En kısa sürede',
     queue: 'Kuyruk',

+ 19 - 0
frontend/src/i18n/locales/uk.ts

@@ -3818,6 +3818,22 @@ export default {
       printerAccessLimited: 'Обмежена: вибрано принтерів — {{printers}}, розташувань — {{locations}}',
       printerAccessOpen: 'Без обмежень: учасники бачать усі принтери.',
       managePrinterAccess: 'Керувати доступом до принтерів',
+      filamentAccess: 'Доступ до філаментів',
+      adminsUseAllFilaments: 'Адміністратори завжди можуть використовувати будь-який філамент.',
+      limitFilaments: 'Обмежити філаменти',
+      filamentAccessOpen: 'Без обмежень: учасники можуть друкувати будь-яким філаментом.',
+      filamentModeBlock: 'Заборонити ці філаменти',
+      filamentModeAllow: 'Дозволити лише ці філаменти',
+      filamentMatchMaterial: 'Тип матеріалу',
+      filamentMatchId: 'ID філаменту',
+      filamentRuleValue: 'Значення правила',
+      filamentRuleMaterialPlaceholder: 'напр. PETG',
+      filamentRuleIdPlaceholder: 'напр. GFG03',
+      addFilamentRule: 'Додати правило',
+      removeFilamentRule: 'Видалити {{value}}',
+      noFilamentRules: 'Правил поки немає.',
+      filamentAllowEmptyWarning: 'Без правил список дозволених забороняє будь-який філамент.',
+      filamentRulesHint: 'Тип матеріалу порівнюється за назвою (PETG не збігається з PETG-CF); PA-CF, PA12-CF і PAHT-CF вважаються одним матеріалом, як і для принтера. ID філаменту — це ID пресету слайсера, напр. GFG03 для Bambu PETG Matte. Учасник може використовувати філамент, якщо його дозволяє хоча б одна з його обмежених груп.',
     },
   },
 
@@ -5830,6 +5846,7 @@ export default {
     sameTypeDifferentColor: "Одного типу, іншого кольору",
     filamentTypeNotLoaded: "Тип філаменту не завантажено",
     statusReady: "Готово",
+    statusBlocked: "Заблоковано",
     statusColorMismatch: "Колір не збігається",
     statusTypeNotFound: "Тип не знайдено",
     requiredTooltip: "Потрібно: {{name}} - {{color}}",
@@ -5841,6 +5858,8 @@ export default {
     overrideForFilament: "Перевизначення філаменту для {{name}}",
     sameTypeDifferentColorDetail: "Того самого типу, іншого кольору: потрібен {{required}}, у слоті {{loaded}}",
     requiredTypeNotInPrinter: "Потрібний тип філаменту не знайдено у принтері.",
+    filamentBlockedSlot: 'Вашій групі не можна використовувати {{filament}}',
+    filamentBlockedFile: 'У цьому файлі використовується філамент, яким вашій групі не можна друкувати: {{filaments}}',
     whenToPrint: "Коли друкувати",
     asap: "Якнайшвидше",
     queue: "Черга",

+ 19 - 0
frontend/src/i18n/locales/zh-CN.ts

@@ -3778,6 +3778,22 @@ export default {
       printerAccessLimited: '受限:已选 {{printers}} 台打印机,{{locations}} 个位置',
       printerAccessOpen: '不受限:成员可以看到所有打印机。',
       managePrinterAccess: '管理打印机访问',
+      filamentAccess: '耗材访问',
+      adminsUseAllFilaments: '管理员始终可以使用所有耗材。',
+      limitFilaments: '限制耗材',
+      filamentAccessOpen: '不受限:成员可以使用任何耗材打印。',
+      filamentModeBlock: '禁用这些耗材',
+      filamentModeAllow: '仅允许这些耗材',
+      filamentMatchMaterial: '材料类型',
+      filamentMatchId: '耗材 ID',
+      filamentRuleValue: '规则值',
+      filamentRuleMaterialPlaceholder: '例如 PETG',
+      filamentRuleIdPlaceholder: '例如 GFG03',
+      addFilamentRule: '添加规则',
+      removeFilamentRule: '移除 {{value}}',
+      noFilamentRules: '暂无规则。',
+      filamentAllowEmptyWarning: '没有规则时,允许列表会禁用所有耗材。',
+      filamentRulesHint: '材料类型按名称匹配(PETG 不匹配 PETG-CF);PA-CF、PA12-CF 和 PAHT-CF 与打印机一样视为同一种材料。耗材 ID 是切片预设的 ID,例如 Bambu PETG Matte 为 GFG03。只要成员所在的任一受限组允许,该成员即可使用该耗材。',
     },
   },
 
@@ -5776,6 +5792,7 @@ export default {
     sameTypeDifferentColor: '相同类型,不同颜色',
     filamentTypeNotLoaded: '耗材类型未装载',
     statusReady: '就绪',
+    statusBlocked: '不可用',
     statusColorMismatch: '颜色不匹配',
     statusTypeNotFound: '未找到类型',
     requiredTooltip: '需要:{{name}} - {{color}}',
@@ -5787,6 +5804,8 @@ export default {
     overrideForFilament: '{{name}} 的耗材覆盖',
     sameTypeDifferentColorDetail: '相同类型,不同颜色:需要 {{required}},槽位为 {{loaded}}',
     requiredTypeNotInPrinter: '打印机中未找到所需的耗材类型。',
+    filamentBlockedSlot: '您的组无法使用 {{filament}}',
+    filamentBlockedFile: '此文件使用了您的组无法用于打印的耗材:{{filaments}}',
     whenToPrint: '何时打印',
     asap: '尽快',
     queue: '队列',

+ 19 - 0
frontend/src/i18n/locales/zh-TW.ts

@@ -3778,6 +3778,22 @@ export default {
       printerAccessLimited: '受限:已選 {{printers}} 台印表機,{{locations}} 個位置',
       printerAccessOpen: '不受限:成員可以看到所有印表機。',
       managePrinterAccess: '管理印表機存取',
+      filamentAccess: '耗材存取',
+      adminsUseAllFilaments: '管理員一律可以使用所有耗材。',
+      limitFilaments: '限制耗材',
+      filamentAccessOpen: '不受限:成員可以使用任何耗材列印。',
+      filamentModeBlock: '封鎖這些耗材',
+      filamentModeAllow: '僅允許這些耗材',
+      filamentMatchMaterial: '材料類型',
+      filamentMatchId: '耗材 ID',
+      filamentRuleValue: '規則值',
+      filamentRuleMaterialPlaceholder: '例如 PETG',
+      filamentRuleIdPlaceholder: '例如 GFG03',
+      addFilamentRule: '新增規則',
+      removeFilamentRule: '移除 {{value}}',
+      noFilamentRules: '尚無規則。',
+      filamentAllowEmptyWarning: '沒有規則時,允許清單會封鎖所有耗材。',
+      filamentRulesHint: '材料類型依名稱比對(PETG 不符合 PETG-CF);PA-CF、PA12-CF 與 PAHT-CF 與印表機一樣視為同一種材料。耗材 ID 是切片預設的 ID,例如 Bambu PETG Matte 為 GFG03。只要成員所屬的任一受限群組允許,該成員即可使用該耗材。',
     },
   },
 
@@ -5776,6 +5792,7 @@ export default {
     sameTypeDifferentColor: '相同類型,不同顏色',
     filamentTypeNotLoaded: '耗材類型未裝載',
     statusReady: '就緒',
+    statusBlocked: '不可用',
     statusColorMismatch: '顏色不符',
     statusTypeNotFound: '找不到類型',
     requiredTooltip: '需要:{{name}} - {{color}}',
@@ -5787,6 +5804,8 @@ export default {
     overrideForFilament: '{{name}} 的耗材覆蓋',
     sameTypeDifferentColorDetail: '相同類型,不同顏色:需要 {{required}},插槽為 {{loaded}}',
     requiredTypeNotInPrinter: '印表機中找不到所需的耗材類型。',
+    filamentBlockedSlot: '您的群組無法使用 {{filament}}',
+    filamentBlockedFile: '此檔案使用了您的群組無法用於列印的耗材:{{filaments}}',
     whenToPrint: '何時列印',
     asap: '盡快',
     queue: '佇列',

+ 34 - 1
frontend/src/pages/GroupEditPage.tsx

@@ -4,9 +4,10 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
 import { useTranslation } from 'react-i18next';
 import { ArrowLeft, Save, Loader2, Search, Check, Minus, Shield, AlertTriangle, Printer as PrinterIcon } from 'lucide-react';
 import { api } from '../api/client';
-import type { GroupCreate, GroupUpdate, Permission, PermissionCategory } from '../api/client';
+import type { FilamentRule, FilamentRuleMode, GroupCreate, GroupUpdate, Permission, PermissionCategory } from '../api/client';
 import { Button } from '../components/Button';
 import { Card } from '../components/Card';
+import { FilamentAccessCard } from '../components/FilamentAccessCard';
 import { useToast } from '../contexts/ToastContext';
 
 export function GroupEditPage() {
@@ -22,6 +23,11 @@ export function GroupEditPage() {
   const [permissions, setPermissions] = useState<Permission[]>([]);
   const [search, setSearch] = useState('');
   const [initialized, setInitialized] = useState(false);
+  const [restrictFilaments, setRestrictFilaments] = useState(false);
+  const [filamentMode, setFilamentMode] = useState<FilamentRuleMode>('block');
+  const [filamentRules, setFilamentRules] = useState<FilamentRule[]>([]);
+  // The rules plus one typed in the card but not added yet, which Save keeps (#3522).
+  const [filamentRulesToSave, setFilamentRulesToSave] = useState<FilamentRule[] | null>(null);
 
   const { data: groupData, isLoading: groupLoading } = useQuery({
     queryKey: ['group', id],
@@ -39,6 +45,9 @@ export function GroupEditPage() {
     setName(groupData.name);
     setDescription(groupData.description || '');
     setPermissions(groupData.permissions);
+    setRestrictFilaments(groupData.restrict_filaments ?? false);
+    setFilamentMode(groupData.filament_rule_mode ?? 'block');
+    setFilamentRules(groupData.filament_rules ?? []);
     setInitialized(true);
   }
 
@@ -98,12 +107,22 @@ export function GroupEditPage() {
         name: name !== groupData?.name ? name : undefined,
         description,
         permissions: groupData?.is_system && !permissionsChanged ? undefined : permissions,
+        ...(isAdministrators
+          ? {}
+          : {
+              restrict_filaments: restrictFilaments,
+              filament_rule_mode: filamentMode,
+              filament_rules: filamentRulesToSave ?? filamentRules,
+            }),
       });
     } else {
       createMutation.mutate({
         name,
         description: description || undefined,
         permissions,
+        restrict_filaments: restrictFilaments,
+        filament_rule_mode: filamentMode,
+        filament_rules: filamentRulesToSave ?? filamentRules,
       });
     }
   };
@@ -243,6 +262,20 @@ export function GroupEditPage() {
         </div>
       </Card>
 
+      {/* Filament access (#3522) */}
+      <FilamentAccessCard
+        enabled={restrictFilaments}
+        mode={filamentMode}
+        rules={filamentRules}
+        disabled={isAdministrators}
+        onChange={({ enabled, mode, rules }) => {
+          setRestrictFilaments(enabled);
+          setFilamentMode(mode);
+          setFilamentRules(rules);
+        }}
+        onPendingRulesChange={setFilamentRulesToSave}
+      />
+
       {/* Toolbar */}
       <div className="flex items-center justify-between flex-wrap gap-3">
         <div className="flex items-center gap-3">

+ 3 - 2
frontend/src/utils/amsHelpers.ts

@@ -638,12 +638,13 @@ export function effectivePreferLowest(
  */
 export function autoMatchFilament(
   req: { type?: string; color?: string; nozzle_id?: number | null },
-  loadedFilaments: { globalTrayId: number; amsId?: number; trayId?: number; type?: string; color?: string; extruderId?: number; remain?: number }[],
+  loadedFilaments: { globalTrayId: number; amsId?: number; trayId?: number; type?: string; color?: string; extruderId?: number; remain?: number; blocked?: boolean }[],
   usedTrayIds: Set<number>,
   preferLowest?: boolean,
   inventoryByTrayId?: Map<number, number>,
 ): typeof loadedFilaments[number] | undefined {
-  let nozzleFilaments = filterFilamentsByNozzle(loadedFilaments, req.nozzle_id);
+  // A tray the user's groups block is never auto-picked (#3522).
+  let nozzleFilaments = filterFilamentsByNozzle(loadedFilaments.filter((f) => !f.blocked), req.nozzle_id);
 
   if (preferLowest) {
     nozzleFilaments = [...nozzleFilaments].sort((a, b) =>

+ 101 - 0
frontend/src/utils/filamentScope.ts

@@ -0,0 +1,101 @@
+import type { FilamentPolicy, FilamentRule } from '../api/client';
+import { canonicalFilamentType } from './amsHelpers';
+
+// Mirrors backend/app/core/filament_scope.py (#3522): the server enforces the
+// same rules, so the print dialog only shows ahead of time what it would do.
+
+const norm = (value?: string | null) => (value ?? '').trim().toUpperCase();
+
+/** Whether a filament with this type and slicer filament id may be used. */
+export function filamentAllowed(
+  policies: FilamentPolicy[] | null | undefined,
+  type?: string | null,
+  filamentId?: string | null,
+): boolean {
+  if (policies == null) return true;
+  const t = norm(type);
+  const id = norm(filamentId);
+  if (!t && !id) return true;
+  return policies.some((policy) => {
+    const hit = policy.rules.some((rule) => {
+      const wanted = norm(rule.value);
+      if (!wanted) return false;
+      // A material rule names every type the tray matcher treats as that
+      // material (PA-CF, PA12-CF and PAHT-CF are one), as the server does.
+      return rule.match === 'material' ? canonicalFilamentType(t) === canonicalFilamentType(wanted) : id === wanted;
+    });
+    return policy.mode === 'allow' ? hit : !hit;
+  });
+}
+
+/** `loaded` with `blocked` set on each tray the policies don't allow; the same array when unrestricted. */
+export function markBlocked<T extends { type?: string; trayInfoIdx?: string }>(
+  loaded: T[],
+  policies: FilamentPolicy[] | null | undefined,
+): (T & { blocked?: boolean })[] {
+  if (policies == null) return loaded;
+  return loaded.map((f) => (filamentAllowed(policies, f.type, f.trayInfoIdx) ? f : { ...f, blocked: true }));
+}
+
+/**
+ * How the print dialog names a filament (#3522): `TYPE (ID)`, `TYPE` or `ID`.
+ * Mirrors `describe_filament` on the server, so the dialog and the 403 agree.
+ */
+export function filamentName(type?: string | null, filamentId?: string | null): string {
+  const kind = (type ?? '').trim();
+  const id = (filamentId ?? '').trim();
+  if (kind && id) return `${kind} (${id})`;
+  return kind || id;
+}
+
+/**
+ * `rules` with `{ match, value }` added as the group editor stores it: trimmed,
+ * a material upper-cased, and not twice. The same array when there is nothing
+ * to add (#3522).
+ */
+export function withFilamentRule(rules: FilamentRule[], match: FilamentRule['match'], value: string): FilamentRule[] {
+  const trimmed = value.trim();
+  if (!trimmed) return rules;
+  const stored = match === 'material' ? trimmed.toUpperCase() : trimmed;
+  if (rules.some((r) => r.match === match && r.value.toUpperCase() === stored.toUpperCase())) return rules;
+  return [...rules, { match, value: stored }];
+}
+
+/** A filament override as a queue job carries it (`filament_overrides`). */
+interface JudgedOverride {
+  slot_id: number;
+  type: string;
+  tray_info_idx?: string | null;
+  force_color_match?: boolean;
+}
+
+/**
+ * The file's filaments as the rules judge them once the job's overrides apply
+ * (#3522). Mirrors `judged_requirements` on the server: an overridden slot is
+ * judged as its override names it, with its filament id only for a forced
+ * colour (a swap clears the id), and one left naming no id isn't judged here:
+ * the tray matcher never maps it onto a spool the user may not use.
+ */
+export function judgedFilaments<T extends { slot_id: number; type: string; tray_info_idx?: string | null }>(
+  reqs: T[] | undefined,
+  overrides: JudgedOverride[] | undefined,
+): T[] {
+  const bySlot = new Map((overrides ?? []).map((o) => [o.slot_id, o]));
+  return (reqs ?? []).flatMap((req) => {
+    const override = bySlot.get(req.slot_id);
+    if (!override) return [req];
+    const id = override.force_color_match ? (override.tray_info_idx ?? '').trim() : '';
+    return id ? [{ ...req, type: override.type, tray_info_idx: id }] : [];
+  });
+}
+
+/** Names of the requirements the policies don't allow, each once, in order. */
+export function blockedFilamentNames(
+  reqs: { type: string; tray_info_idx?: string | null }[] | undefined,
+  policies: FilamentPolicy[] | null | undefined,
+): string[] {
+  const names = (reqs ?? [])
+    .filter((req) => !filamentAllowed(policies, req.type, req.tray_info_idx))
+    .map((req) => filamentName(req.type, req.tray_info_idx));
+  return [...new Set(names)];
+}