瀏覽代碼

fix(virtual-printer): forward H2C rack-swap nozzle pick from slicer to dispatch (#1780)

  BambuStudio's project_file MQTT command for O1C2 (the H2C dual-
  nozzle-rack variant) carries nozzle_mapping (per-filament physical
  nozzle position IDs) and nozzles_info (per-extruder rack metadata).
  The VP intake was dropping both, so the H2C firmware fell back to
  "last matching nozzle type" auto-pick and ignored the user's
  slicer choice — every HF print landed on R2, every standard print
  landed on R4.

  Carry both fields through the VP intake → queue item → MQTT
  dispatch path. New nullable TEXT columns on print_queue, non-
  branched ALTER (matches ams_mapping / filament_overrides
  precedent). Dual-nozzle gate at start_print() keeps the fields
  off single-nozzle dispatches. Fail-open on malformed JSON —
  firmware auto-picks, never worse than pre-fix.

  Stamps both fields on every plate in the multi-plate Send All
  loop (#1697 / #1188 precedent).

  ams_mapping2 still handles H2D/X2D dual-extruder routing
  unchanged; this fix is scoped to the O1C2 rack-swap mechanism.
maziggy 2 月之前
父節點
當前提交
d196cfc5

文件差異過大導致無法顯示
+ 0 - 0
CHANGELOG.md


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

@@ -184,6 +184,23 @@ def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
         except json.JSONDecodeError:
             filament_overrides_parsed = None
 
+    # Parse nozzle_mapping + nozzles_info from JSON string (#1780 — H2C rack
+    # slicer-pick preservation). Both are nullable opaque JSON blobs stored
+    # verbatim from BambuStudio's project_file; surface them parsed for the
+    # response model and any future "edit print → nozzle" UI.
+    nozzle_mapping_parsed = None
+    if item.nozzle_mapping:
+        try:
+            nozzle_mapping_parsed = json.loads(item.nozzle_mapping)
+        except json.JSONDecodeError:
+            nozzle_mapping_parsed = None
+    nozzles_info_parsed = None
+    if item.nozzles_info:
+        try:
+            nozzles_info_parsed = json.loads(item.nozzles_info)
+        except json.JSONDecodeError:
+            nozzles_info_parsed = None
+
     # Create response with parsed ams_mapping
     item_dict = {
         "id": item.id,
@@ -226,6 +243,9 @@ def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
         "been_jumped": item.been_jumped,
         # Auto-print G-code injection
         "gcode_injection": item.gcode_injection,
+        # H2C rack-swap nozzle pick (#1780)
+        "nozzle_mapping": nozzle_mapping_parsed,
+        "nozzles_info": nozzles_info_parsed,
     }
     response = PrintQueueItemResponse(**item_dict)
     if item.archive:
@@ -1051,6 +1071,15 @@ async def update_queue_item(
             json.dumps(update_data["filament_overrides"]) if update_data["filament_overrides"] else None
         )
 
+    # Serialize H2C rack-swap nozzle pick (#1780) to JSON for TEXT column
+    # storage; same Text-as-opaque-blob convention as ams_mapping above.
+    if "nozzle_mapping" in update_data:
+        update_data["nozzle_mapping"] = (
+            json.dumps(update_data["nozzle_mapping"]) if update_data["nozzle_mapping"] else None
+        )
+    if "nozzles_info" in update_data:
+        update_data["nozzles_info"] = json.dumps(update_data["nozzles_info"]) if update_data["nozzles_info"] else None
+
     for field, value in update_data.items():
         setattr(item, field, value)
 

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

@@ -967,6 +967,15 @@ async def run_migrations(conn):
     else:
         await _safe_execute(conn, "ALTER TABLE virtual_printers ADD COLUMN gcode_injection BOOLEAN DEFAULT FALSE")
 
+    # Migration: nozzle_mapping + nozzles_info on print_queue for H2C rack-swap
+    # slicer-pick preservation (#1780). Opaque JSON-string columns carrying
+    # BambuStudio's per-filament physical nozzle position IDs and the
+    # per-extruder rack metadata, forwarded straight from the VP intake to
+    # the dispatcher's project_file MQTT command. NULL on every other model.
+    # Nullable TEXT — no Postgres / SQLite divergence here.
+    await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzle_mapping TEXT")
+    await _safe_execute(conn, "ALTER TABLE print_queue ADD COLUMN nozzles_info TEXT")
+
     # Migration: Add target_parts_count column to projects for tracking total parts needed
     await _safe_execute(conn, "ALTER TABLE projects ADD COLUMN target_parts_count INTEGER")
 

+ 11 - 0
backend/app/models/print_queue.py

@@ -65,6 +65,17 @@ class PrintQueueItem(Base):
     # Auto-print G-code injection (#422)
     gcode_injection: Mapped[bool] = mapped_column(Boolean, default=False)
 
+    # H2C dual-nozzle-rack slicer pick preservation (#1780). BambuStudio's
+    # project_file MQTT command for rack-swap-capable models (O1C2 today)
+    # carries per-filament physical nozzle position IDs in `nozzle_mapping`
+    # and per-extruder rack metadata in `nozzles_info`. Both are forwarded
+    # verbatim through the queue and replayed by the dispatcher so the
+    # firmware honours the user's pick instead of falling back to
+    # "last matching nozzle type" auto-pick. Stored as opaque JSON strings
+    # (list[int] and list[dict] respectively); NULL on every other model.
+    nozzle_mapping: Mapped[str | None] = mapped_column(Text, nullable=True)
+    nozzles_info: Mapped[str | None] = mapped_column(Text, nullable=True)
+
     # Print options
     bed_levelling: Mapped[bool] = mapped_column(Boolean, default=True)
     flow_cali: Mapped[bool] = mapped_column(Boolean, default=False)

+ 13 - 0
backend/app/schemas/print_queue.py

@@ -82,6 +82,13 @@ class PrintQueueItemUpdate(BaseModel):
     nozzle_offset_cali: bool | None = None
     # Auto-print G-code injection
     gcode_injection: bool | None = None
+    # H2C dual-nozzle-rack slicer pick (#1780). Both fields are opaque
+    # JSON-encoded structures BambuStudio sends in its project_file MQTT
+    # body; sent back to the printer verbatim on dispatch. list[int] for
+    # nozzle_mapping (per-filament physical nozzle position IDs), list[dict]
+    # for nozzles_info (per-extruder rack metadata).
+    nozzle_mapping: list[int] | None = None
+    nozzles_info: list[dict] | None = None
 
 
 class PrintQueueItemResponse(BaseModel):
@@ -163,6 +170,12 @@ class PrintQueueItemResponse(BaseModel):
     # Auto-print G-code injection
     gcode_injection: bool = False
 
+    # H2C dual-nozzle-rack slicer pick (#1780). Surface for any future
+    # "edit print → choose nozzle" UI; null on every model except O1C2
+    # uploads from BambuStudio.
+    nozzle_mapping: list[int] | None = None
+    nozzles_info: list[dict] | None = None
+
     class Config:
         from_attributes = True
 

+ 41 - 0
backend/app/services/bambu_mqtt.py

@@ -3439,6 +3439,8 @@ class BambuMQTTClient:
         timelapse: bool = False,
         use_ams: bool = True,
         nozzle_offset_cali: bool = False,
+        nozzle_mapping: str | None = None,
+        nozzles_info: str | None = None,
     ):
         """Start a print job on the printer.
 
@@ -3457,6 +3459,16 @@ class BambuMQTTClient:
             use_ams: Use AMS for automatic filament changes
             nozzle_offset_cali: Run nozzle offset calibration before print
                 (dual-nozzle printers only — silently ignored on single-nozzle).
+            nozzle_mapping: Opaque JSON string captured from BambuStudio's
+                project_file for H2C rack-swap (O1C2) (#1780). When non-null
+                AND the printer is dual-nozzle, parsed and injected as the
+                `nozzle_mapping` array on the dispatched project_file so the
+                firmware honours the user's slicer pick instead of falling
+                back to "last matching nozzle" auto-pick. Silently ignored
+                on single-nozzle printers.
+            nozzles_info: Opaque JSON string for the per-extruder rack
+                metadata BambuStudio's project_file carries alongside
+                `nozzle_mapping` (#1780). Same dual-nozzle gating.
         """
         if self._client and self.state.connected:
             # Bambu print command format — matches Bambu Studio's format.
@@ -3614,6 +3626,35 @@ class BambuMQTTClient:
                 command["print"]["ams_mapping"] = flat_ams_mapping
                 command["print"]["ams_mapping2"] = ams_mapping2
 
+            # H2C dual-nozzle-rack slicer-pick preservation (#1780).
+            # `nozzle_mapping` carries per-filament physical nozzle position
+            # IDs (`list[int]`), `nozzles_info` carries per-extruder rack
+            # metadata (`list[dict]`). Both are JSON-string-encoded when
+            # they leave the queue item; parse here so the wire ships
+            # arrays/objects, matching BambuStudio's project_file shape.
+            # Gate by `is_dual_nozzle` defensively — single-nozzle firmwares
+            # would ignore them but we err on the side of not emitting
+            # unrecognised fields. A parse failure is logged but never
+            # blocks the dispatch — the firmware will fall back to its
+            # auto-pick path, which is the pre-fix behaviour.
+            if is_dual_nozzle:
+                for src_str, json_key in (
+                    (nozzle_mapping, "nozzle_mapping"),
+                    (nozzles_info, "nozzles_info"),
+                ):
+                    if not src_str:
+                        continue
+                    try:
+                        command["print"][json_key] = json.loads(src_str)
+                    except json.JSONDecodeError:
+                        logger.warning(
+                            "[%s] Invalid %s JSON on dispatch, omitting from "
+                            "project_file (firmware will auto-pick): %r",
+                            self.serial_number,
+                            json_key,
+                            src_str,
+                        )
+
             logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
             self._client.publish(self.topic_publish, json.dumps(command), qos=1)
             # Record what we dispatched so /cover can pick the right plate

+ 7 - 1
backend/app/services/print_scheduler.py

@@ -2253,7 +2253,11 @@ class PrintScheduler:
         # FINISH-state fallback — no need to force a video.
         effective_timelapse = bool(item.timelapse)
 
-        # Start the print with AMS mapping, plate_id and print options
+        # Start the print with AMS mapping, plate_id and print options.
+        # nozzle_mapping / nozzles_info ride through verbatim — JSON strings
+        # captured from Bambu Studio's project_file on VP intake (#1780); the
+        # MQTT layer parses + injects them only for dual-nozzle models so a
+        # null on every other model is a transparent pass-through.
         started = printer_manager.start_print(
             item.printer_id,
             remote_filename,
@@ -2266,6 +2270,8 @@ class PrintScheduler:
             timelapse=effective_timelapse,
             use_ams=item.use_ams,
             nozzle_offset_cali=item.nozzle_offset_cali,
+            nozzle_mapping=item.nozzle_mapping,
+            nozzles_info=item.nozzles_info,
         )
 
         if started:

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

@@ -565,8 +565,17 @@ class PrinterManager:
         timelapse: bool = False,
         use_ams: bool = True,
         nozzle_offset_cali: bool = False,
+        nozzle_mapping: str | None = None,
+        nozzles_info: str | None = None,
     ) -> bool:
-        """Start a print on a connected printer."""
+        """Start a print on a connected printer.
+
+        ``nozzle_mapping`` and ``nozzles_info`` are opaque JSON strings
+        captured from BambuStudio's project_file MQTT command (H2C rack-swap
+        slicer pick preservation, #1780). They ride through to the MQTT
+        client untouched; the dispatch builder there parses + injects them
+        only on dual-nozzle models.
+        """
         caller = traceback.extract_stack(limit=3)[0]
         logger.info(
             "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
@@ -588,6 +597,8 @@ class PrinterManager:
                 layer_inspect=layer_inspect,
                 use_ams=use_ams,
                 nozzle_offset_cali=nozzle_offset_cali,
+                nozzle_mapping=nozzle_mapping,
+                nozzles_info=nozzles_info,
             )
         return False
 

+ 49 - 0
backend/app/services/virtual_printer/manager.py

@@ -573,6 +573,49 @@ class VirtualPrinterInstance:
                 )
                 timelapse = _slicer_or("timelapse", _bool_setting(await get_setting(db, "default_timelapse"), False))
 
+                # H2C dual-nozzle-rack slicer-pick preservation (#1780).
+                # BambuStudio's project_file MQTT command for rack-swap models
+                # (O1C2 today) carries:
+                #   `nozzle_mapping` — per-filament array of physical nozzle
+                #     position IDs (`list[int]`).
+                #   `nozzles_info`   — per-extruder rack metadata
+                #     (`list[dict]`, fields: id / type / flowSize / diameter).
+                # Forward both verbatim onto the queue item so the dispatcher
+                # can replay them in its own project_file command. Without
+                # this the H2C firmware falls back to "last matching nozzle"
+                # auto-pick and ignores the user's Bambu Studio choice. Every
+                # other model has these absent from slicer_opts, so the
+                # capture is a transparent no-op there.
+                nozzle_mapping_json: str | None = None
+                nozzles_info_json: str | None = None
+                if slicer_opts is not None:
+                    for src_key in ("nozzle_mapping", "nozzles_info"):
+                        raw = slicer_opts.get(src_key)
+                        if raw is None:
+                            continue
+                        # BambuStudio's NetworkAgent should embed these as
+                        # parsed JSON in the project_file body (matching the
+                        # ams_mapping / ams_mapping2 shape Bambuddy already
+                        # consumes as list[int] / list[dict]). Accept a
+                        # JSON-encoded string defensively in case any path
+                        # arrives stringified.
+                        if isinstance(raw, str):
+                            try:
+                                raw = json.loads(raw)
+                            except json.JSONDecodeError:
+                                logger.warning(
+                                    "[VP %s] Slicer %s is unparseable JSON, dropping: %r",
+                                    self.name,
+                                    src_key,
+                                    raw,
+                                )
+                                continue
+                        encoded = json.dumps(raw)
+                        if src_key == "nozzle_mapping":
+                            nozzle_mapping_json = encoded
+                        else:
+                            nozzles_info_json = encoded
+
                 service = ArchiveService(db)
                 archive = await service.archive_print(
                     printer_id=None,
@@ -675,6 +718,12 @@ class VirtualPrinterInstance:
                             # gcode_snippets are configured for the target model, so it's
                             # effectively "inject when enabled AND snippets exist".
                             gcode_injection=self.gcode_injection,
+                            # H2C rack-swap slicer pick (#1780). Captured above;
+                            # stamped on every plate so a multi-plate Send All keeps
+                            # the same nozzle pick across plates rather than only the
+                            # first one (mirrors the #1697 / #1188 per-plate loop fix).
+                            nozzle_mapping=nozzle_mapping_json,
+                            nozzles_info=nozzles_info_json,
                         )
                         db.add(queue_item)
                         await db.flush()  # populate queue_item.id before logging

+ 129 - 0
backend/tests/unit/services/test_bambu_mqtt.py

@@ -5081,6 +5081,135 @@ class TestStartPrintRecordsDispatchedPlate:
         assert mqtt_client.state.dispatched_subtask is None
 
 
+class TestStartPrintNozzleMappingDispatch:
+    """H2C dual-nozzle-rack (#1780) — nozzle_mapping + nozzles_info on dispatch.
+
+    BambuStudio's project_file MQTT command for O1C2 carries a per-filament
+    physical nozzle position ID array (`nozzle_mapping`) and a per-extruder
+    rack metadata array (`nozzles_info`). Without forwarding both, the H2C
+    firmware falls back to "last matching nozzle type" auto-pick and ignores
+    the user's slicer choice. Tests pin the gate, the parse, the no-op cases,
+    and the malformed-JSON safety net.
+    """
+
+    @pytest.fixture
+    def mqtt_client(self):
+        from unittest.mock import MagicMock
+
+        from backend.app.services.bambu_mqtt import BambuMQTTClient
+
+        client = BambuMQTTClient(
+            ip_address="192.168.1.100",
+            serial_number="TEST_O1C2",
+            access_code="12345678",
+        )
+        client._client = MagicMock()
+        client.state.connected = True
+        return client
+
+    def _published_print_cmd(self, mqtt_client):
+        call_args = mqtt_client._client.publish.call_args
+        return json.loads(call_args[0][1])["print"]
+
+    def test_dual_nozzle_includes_nozzle_mapping_and_nozzles_info(self, mqtt_client):
+        """Dual-nozzle + both fields present → parsed JSON arrays injected
+        verbatim onto the dispatched project_file command."""
+        mqtt_client._is_dual_nozzle = True
+        nozzles_info = [
+            {"id": 1, "type": None, "flowSize": "High Flow", "diameter": 0.4},
+            {"id": 2, "type": None, "flowSize": "Standard", "diameter": 0.4},
+        ]
+
+        mqtt_client.start_print(
+            "test.3mf",
+            nozzle_mapping=json.dumps([16, 0, 19]),
+            nozzles_info=json.dumps(nozzles_info),
+        )
+
+        cmd = self._published_print_cmd(mqtt_client)
+        # Lists, not strings — the wire shape must match BambuStudio's.
+        assert cmd["nozzle_mapping"] == [16, 0, 19]
+        assert cmd["nozzles_info"] == nozzles_info
+
+    def test_single_nozzle_omits_nozzle_mapping_even_if_set(self, mqtt_client):
+        """A single-nozzle printer must NOT emit the rack fields even if the
+        caller passes them (defense-in-depth — the queue item could legitimately
+        carry a stale capture from before a model change)."""
+        mqtt_client._is_dual_nozzle = False
+        mqtt_client.model = "P1S"  # single-nozzle
+
+        mqtt_client.start_print(
+            "test.3mf",
+            nozzle_mapping=json.dumps([16, 0, 19]),
+            nozzles_info=json.dumps([{"id": 1}]),
+        )
+
+        cmd = self._published_print_cmd(mqtt_client)
+        assert "nozzle_mapping" not in cmd
+        assert "nozzles_info" not in cmd
+
+    def test_dual_nozzle_no_fields_no_injection(self, mqtt_client):
+        """Dual-nozzle printer + no slicer pick (NULL on queue item) → command
+        carries no nozzle_mapping / nozzles_info. The firmware then runs its
+        normal auto-pick, which is the pre-fix behaviour for any non-O1C2 dual-
+        nozzle model that has no rack to disambiguate against anyway."""
+        mqtt_client._is_dual_nozzle = True
+
+        mqtt_client.start_print("test.3mf", nozzle_mapping=None, nozzles_info=None)
+
+        cmd = self._published_print_cmd(mqtt_client)
+        assert "nozzle_mapping" not in cmd
+        assert "nozzles_info" not in cmd
+
+    def test_dual_nozzle_partial_only_mapping(self, mqtt_client):
+        """Half-populated case: nozzle_mapping carried but nozzles_info NULL.
+        Forward what we have; firmware tolerates a missing rack metadata
+        field and resolves against its own state."""
+        mqtt_client._is_dual_nozzle = True
+
+        mqtt_client.start_print(
+            "test.3mf",
+            nozzle_mapping=json.dumps([16]),
+            nozzles_info=None,
+        )
+
+        cmd = self._published_print_cmd(mqtt_client)
+        assert cmd["nozzle_mapping"] == [16]
+        assert "nozzles_info" not in cmd
+
+    def test_malformed_nozzle_mapping_is_logged_and_omitted(self, mqtt_client, caplog):
+        """Invalid JSON on the queue item must NOT block the dispatch. Log a
+        warning and let the firmware auto-pick — the failure mode is just
+        the pre-fix behaviour, not a worse one. Fail-open is correct here
+        because the alternative would silently brick every dispatch on a
+        single bad row."""
+        mqtt_client._is_dual_nozzle = True
+
+        with caplog.at_level("WARNING"):
+            result = mqtt_client.start_print(
+                "test.3mf",
+                nozzle_mapping="not valid json {",
+                nozzles_info=None,
+            )
+
+        assert result is True  # dispatch still proceeded
+        cmd = self._published_print_cmd(mqtt_client)
+        assert "nozzle_mapping" not in cmd
+        assert any("Invalid nozzle_mapping" in rec.message for rec in caplog.records)
+
+    def test_empty_string_fields_are_treated_as_absent(self, mqtt_client):
+        """An empty-string column value (legacy data, or a NOT NULL DB
+        recovery shim) must behave the same as NULL — no injection, no
+        parse error log."""
+        mqtt_client._is_dual_nozzle = True
+
+        mqtt_client.start_print("test.3mf", nozzle_mapping="", nozzles_info="")
+
+        cmd = self._published_print_cmd(mqtt_client)
+        assert "nozzle_mapping" not in cmd
+        assert "nozzles_info" not in cmd
+
+
 class TestFilamentTrackSwitchDetection:
     """Tests for Filament Track Switch (FTS) accessory detection (#1162).
 

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

@@ -378,6 +378,8 @@ class TestPrinterManager:
             layer_inspect=False,
             use_ams=True,
             nozzle_offset_cali=False,
+            nozzle_mapping=None,
+            nozzles_info=None,
         )
         assert result is True
 

+ 215 - 0
backend/tests/unit/services/test_virtual_printer.py

@@ -1579,6 +1579,221 @@ class TestVirtualPrinterInstance:
         # auto_dispatch=False on the VP → every item is manual_start.
         assert all(q.manual_start for q in added_items)
 
+    @pytest.mark.asyncio
+    async def test_add_to_print_queue_captures_nozzle_mapping_and_nozzles_info(self, tmp_path):
+        """#1780: BambuStudio's project_file for H2C rack-swap (O1C2) sends
+        per-filament physical nozzle position IDs in `nozzle_mapping` and
+        per-extruder rack metadata in `nozzles_info`. VP intake must store
+        both as JSON strings on the queue item so the dispatcher can replay
+        them. Without this the H2C firmware falls back to "last matching
+        nozzle" auto-pick and ignores the user's slicer choice.
+        """
+        import json as _json
+
+        from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
+
+        added_items = []
+        mock_db = AsyncMock()
+        mock_db.add = MagicMock(side_effect=added_items.append)
+        mock_db.commit = AsyncMock()
+        mock_session_factory = MagicMock()
+        mock_session_ctx = AsyncMock()
+        mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
+        mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
+        mock_session_factory.return_value = mock_session_ctx
+
+        inst = VirtualPrinterInstance(
+            vp_id=42,
+            name="H2CRack",
+            mode="queue",
+            model="O1C2",
+            access_code="12345678",
+            serial_suffix="391800042",
+            base_dir=tmp_path,
+            session_factory=mock_session_factory,
+        )
+
+        file_path = tmp_path / "test.3mf"
+        file_path.write_bytes(b"fake3mf")
+
+        # Pre-populate as if BS's project_file arrived. Wire shape matches
+        # BambuStudio's PrintJob params: nozzle_mapping = array of per-
+        # filament physical nozzle position IDs, nozzles_info = array of
+        # per-extruder rack-side metadata.
+        await inst.on_print_command(
+            file_path.name,
+            {
+                "command": "project_file",
+                "nozzle_mapping": [16, 0, 19],
+                "nozzles_info": [
+                    {"id": 1, "type": None, "flowSize": "High Flow", "diameter": 0.4},
+                    {"id": 2, "type": None, "flowSize": "Standard", "diameter": 0.4},
+                ],
+            },
+        )
+
+        mock_archive = MagicMock()
+        mock_archive.id = 1
+        mock_archive.print_name = "test"
+
+        with (
+            patch(
+                "backend.app.api.routes.settings.get_setting",
+                new_callable=AsyncMock,
+                return_value=None,
+            ),
+            patch(
+                "backend.app.services.archive.ArchiveService.archive_print",
+                new_callable=AsyncMock,
+                return_value=mock_archive,
+            ),
+        ):
+            await inst._add_to_print_queue(file_path, "192.168.1.100")
+
+        assert len(added_items) == 1
+        item = added_items[0]
+        assert item.nozzle_mapping is not None
+        assert _json.loads(item.nozzle_mapping) == [16, 0, 19]
+        assert item.nozzles_info is not None
+        parsed_info = _json.loads(item.nozzles_info)
+        assert parsed_info[0]["flowSize"] == "High Flow"
+        assert parsed_info[1]["flowSize"] == "Standard"
+
+    @pytest.mark.asyncio
+    async def test_add_to_print_queue_no_nozzle_fields_when_slicer_omits(self, tmp_path):
+        """#1780: every model other than O1C2 sends no nozzle_mapping /
+        nozzles_info — the queue item must carry NULL on both, not an empty
+        list. NULL is what the dispatch layer keys off of to skip the
+        injection entirely on non-rack-swap printers.
+        """
+        from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
+
+        added_items = []
+        mock_db = AsyncMock()
+        mock_db.add = MagicMock(side_effect=added_items.append)
+        mock_db.commit = AsyncMock()
+        mock_session_factory = MagicMock()
+        mock_session_ctx = AsyncMock()
+        mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
+        mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
+        mock_session_factory.return_value = mock_session_ctx
+
+        inst = VirtualPrinterInstance(
+            vp_id=43,
+            name="NotH2C",
+            mode="queue",
+            model="C11",
+            access_code="12345678",
+            serial_suffix="391800043",
+            base_dir=tmp_path,
+            session_factory=mock_session_factory,
+        )
+
+        file_path = tmp_path / "test.3mf"
+        file_path.write_bytes(b"fake3mf")
+
+        # X1C-style slicer command — no nozzle fields.
+        await inst.on_print_command(
+            file_path.name,
+            {"command": "project_file", "timelapse": False, "bed_leveling": True},
+        )
+
+        mock_archive = MagicMock()
+        mock_archive.id = 1
+        mock_archive.print_name = "test"
+
+        with (
+            patch(
+                "backend.app.api.routes.settings.get_setting",
+                new_callable=AsyncMock,
+                return_value=None,
+            ),
+            patch(
+                "backend.app.services.archive.ArchiveService.archive_print",
+                new_callable=AsyncMock,
+                return_value=mock_archive,
+            ),
+        ):
+            await inst._add_to_print_queue(file_path, "192.168.1.100")
+
+        assert len(added_items) == 1
+        item = added_items[0]
+        assert item.nozzle_mapping is None
+        assert item.nozzles_info is None
+
+    @pytest.mark.asyncio
+    async def test_add_to_print_queue_nozzle_pick_replicated_across_plates(self, tmp_path, monkeypatch):
+        """#1780 × #1697/#1188: a multi-plate Send All from BS must stamp the
+        same nozzle_mapping / nozzles_info on every plate's queue item, not
+        only the first. Mirrors the per-plate stamping for gcode_injection,
+        filament_overrides, etc.
+        """
+        import json as _json
+
+        from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
+
+        added_items = []
+        mock_db = AsyncMock()
+        mock_db.add = MagicMock(side_effect=added_items.append)
+        mock_db.flush = AsyncMock()
+        mock_db.commit = AsyncMock()
+        mock_db.execute = AsyncMock()
+        mock_db.execute.return_value.scalar.return_value = None
+        mock_session_factory = MagicMock()
+        mock_session_ctx = AsyncMock()
+        mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
+        mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
+        mock_session_factory.return_value = mock_session_ctx
+
+        inst = VirtualPrinterInstance(
+            vp_id=44,
+            name="H2CMultiPlate",
+            mode="queue",
+            model="O1C2",
+            access_code="12345678",
+            serial_suffix="391800044",
+            base_dir=tmp_path,
+            session_factory=mock_session_factory,
+        )
+
+        file_path = tmp_path / "test.3mf"
+        file_path.write_bytes(b"fake3mf")
+
+        # Force 3 plates so the queue loop runs three times.
+        monkeypatch.setattr(inst, "_extract_plate_ids", lambda _p: [1, 2, 3])
+
+        await inst.on_print_command(
+            file_path.name,
+            {
+                "command": "project_file",
+                "nozzle_mapping": [16, 0],
+                "nozzles_info": [{"id": 1, "flowSize": "High Flow", "diameter": 0.4}],
+            },
+        )
+
+        mock_archive = MagicMock()
+        mock_archive.id = 1
+        mock_archive.print_name = "test"
+
+        with (
+            patch(
+                "backend.app.api.routes.settings.get_setting",
+                new_callable=AsyncMock,
+                return_value=None,
+            ),
+            patch(
+                "backend.app.services.archive.ArchiveService.archive_print",
+                new_callable=AsyncMock,
+                return_value=mock_archive,
+            ),
+        ):
+            await inst._add_to_print_queue(file_path, "192.168.1.100")
+
+        assert len(added_items) == 3
+        for item in added_items:
+            assert _json.loads(item.nozzle_mapping) == [16, 0]
+            assert _json.loads(item.nozzles_info)[0]["flowSize"] == "High Flow"
+
 
 class TestVirtualPrinterManager:
     """Tests for VirtualPrinterManager orchestrator."""

部分文件因文件數量過多而無法顯示