fix(docker): copy gcode_viewer assets into the production image (issue #1218)

The embedded GCode viewer's static assets (gcode_viewer/) were never
  copied into the production Docker image, so /gcode-viewer/ returned a
  bare FastAPI 404 ({"detail":"Not Found"}) and 3D Preview broke for every
  Docker user since the viewer landed in 0.2.4b1. The Vite production
  build doesn't stage the directory either — the dev server serves it via
  a configureServer middleware that's dev-only.

  Dockerfile now copies gcode_viewer/ alongside the React build output.

  Defence in depth: main.py logs an ERROR at startup when
  _gcode_viewer_dir/index.html is missing so future packaging gaps surface
  in docker logs and the support bundle instead of as silent runtime 404s.

  The existing integration test accepted 404 unconditionally
  (assert response.status_code in (200, 404)) so CI never caught the
  missing files. Add test_gcode_viewer_index_served_when_assets_present
  which skips when the directory is intentionally absent (unit-test envs)
  but asserts 200 + non-empty HTML body when the assets do exist on disk —
  so a broken COPY fails CI loudly rather than shipping a broken image.
This commit is contained in:
maziggy
2026-05-06 14:23:39 +02:00
parent f87749d683
commit a3e09891d1
4 changed files with 50 additions and 0 deletions
+1
View File
@@ -8,6 +8,7 @@ All notable changes to Bambuddy will be documented in this file.
- **Slicer Bundle (.bbscfg) import — pick presets from a stored bundle instead of resolving cloud/local/standard PresetRefs every slice** — Closes the long tail of preset-resolution corner cases (cloud presets behind login, "from User" sentinel handling, the `# `-prefix clone trick, dangling `inherits` on renamed parents, etc.) by letting users upload a BambuStudio "Printer Preset Bundle" (`.bbscfg`) once per printer and pick from it for every subsequent slice. **Service layer (`backend/app/services/slicer_api.py`):** `BundleSummary` / `BundleNotFoundError` types, `import_bundle` / `list_bundles` / `get_bundle` / `delete_bundle` methods, `slice_with_bundle` which posts `/slice` with bundle id + per-category preset names instead of the JSON triplet. **Routes (`/api/v1/slicer/bundles`, all gated on `Permission.LIBRARY_UPLOAD`):** `POST` / `GET` / `GET :id` / `DELETE :id`. All routes proxy via `_resolve_slicer_api_url` so they follow the user's `preferred_slicer` setting (bambu_studio vs orcaslicer). Status-code mapping treats sidecar 4xx as 400, `BundleNotFoundError` as 404, sidecar unreachable as 503, and sidecar 5xx as 502. **Preview-slice (`backend/app/services/slice_preview.py::get_preview_filaments`)** picks up optional `bundle_id` + `printer_name` + `process_name` + `filament_names` params and routes through `slice_with_bundle` when set; the cache key picks up a bundle-context fingerprint so different bundle picks on the same file occupy distinct entries — gram numbers in the preview now match what the real print will produce instead of being derived from the file's embedded process settings (which can drift from the triplet the actual slice would use). The `library.py` and `archives.py` `/filament-requirements` routes forward the new params. **Dispatch (`SliceRequest.bundle: SliceBundleSpec`):** when set, `_run_slicer_with_fallback` skips `resolve_preset_ref` and calls `slice_with_bundle`; the validator skips the preset-required check so bundle-only requests validate. 3MF + bundle CLI 5xx still falls back to the embedded-settings slice path (`used_embedded_settings=True` surfaces in the response), and sidecar 404 (unknown bundle / preset name) maps to 400. **Frontend SliceModal Bundle tier:** new "Slicer bundle" picker at the top of the modal, rendered only when at least one bundle is imported (`GET /slicer/bundles` non-empty). Selecting a bundle replaces cloud / local / standard preset dropdowns with bundle-scoped pickers (process + per-slot filament names from the bundle) — printer is implicit (each `.bbscfg` has exactly one). "None" leaves the modal on the original preset-triplet path. Submit routes through `SliceRequest.bundle` so the backend skips PresetRef resolution and asks the sidecar to materialise the JSON triplet from the stored bundle by name. **Frontend types:** `SliceBundleSpec` + `bundle?: SliceBundleSpec` on `SliceRequest`; `getLibraryFileFilamentRequirements` / `getArchiveFilamentRequirements` accept an optional 4th-arg bundle context object. The orca-slicer-api fork's bundle endpoints (shipped on `bambuddy/bundle-import`) are the server side of this — see the slicer-api sidecar docker-compose for the matching versions.
### Fixed
- **3D Preview returned `{"detail":"Not Found"}` in Docker installs** ([#1218](https://github.com/maziggy/bambuddy/issues/1218)) — The embedded GCode viewer's static assets (`gcode_viewer/`) were not copied into the production Docker image, so clicking "3D Preview" on any archive loaded an iframe at `/gcode-viewer/?archive=<id>` that returned a bare FastAPI 404 — Firefox / Chrome rendered the JSON response inside the iframe area while the outer Bambuddy layout looked normal, masking the failure unless the user actually inspected the iframe. The Vite production build doesn't stage `gcode_viewer/` into `static/` either (the dev server serves it via a `configureServer` middleware that's dev-only), and the only integration test for the route accepted `404` as a valid outcome ("`assert response.status_code in (200, 404)`") so CI never caught the missing files. Affected every Docker build since the embedded viewer landed in 0.2.4b1 (commit `3adce435`, 2026-04-22). **Fix:** `Dockerfile` now copies the `gcode_viewer/` directory alongside the React build output. **Defence in depth:** `backend/app/main.py` logs an ERROR at startup when `_gcode_viewer_dir / "index.html"` is missing so future packaging gaps surface in `docker logs` and the support bundle instead of as silent runtime 404s. **Test guard:** `backend/tests/integration/test_gcode_viewer.py` adds `test_gcode_viewer_index_served_when_assets_present` which skips when the directory is intentionally absent (unit-test environments) but asserts `200 OK` + a non-empty HTML body when the assets do exist on disk — so a future broken `COPY` fails CI loudly rather than continuing to ship a broken image.
- **Slice button no longer enabled before the preview slice resolves** — Until the preview slice (or embedded-metadata read for already-sliced 3MFs) returned the per-plate filament list, the SliceModal rendered a synthetic single-slot fallback so the auto-pick had something to bind against. That made the Slice button enabled the moment the modal opened, even before the slicer had told us which AMS slots the plate actually consumes — clicking would dispatch against opaque defaults and the real-life print would either pick the wrong filament or fail with a slot-mismatch error after the fact. Adds `filamentReqsQuery.isSuccess` to the `isReady` chain so the button stays disabled while the preview slice is in flight (or before the backend's `/filament-requirements` call settles for sliced files) and flips to enabled the moment the real slot list lands and auto-pick fills it.
- **Docker data-volume ownership normalised at startup via gosu entrypoint** ([#1211](https://github.com/maziggy/bambuddy/issues/1211)) — Two long-standing failure modes have been biting Docker users repeatedly: (1) Docker named volumes are created by the daemon as `root:root`, and the previous `chmod 777 /app/data` Dockerfile workaround only covered the named-volume root — so subdirs Bambuddy creates at runtime (`virtual_printer/uploads`, `virtual_printer/certs`, etc.) inherited wrong ownership when the container ran as `1000:1000`. (2) The shipped `docker-compose.yml` ships `./virtual_printer:/app/data/virtual_printer` uncommented, and dockerd creates a missing bind-mount source on the host as root before the container starts — leaving the host directory unwritable by uid 1000 inside the container even though the named volume above it had the chmod-777 workaround. Symptom either way: `[Errno 13] Permission denied: '/app/data/virtual_printer/uploads'`, no virtual printer ever starts, "VP doesn't work" support reports follow. **Replaces the chmod-777 hack with a proper entrypoint:** `deploy/docker-entrypoint.sh` runs as root, chowns `/app/data` and `/app/logs` (and `/app/data/virtual_printer` when bind-mounted) to `PUID:PGID`, then drops to that uid via `gosu` before `exec`'ing the app. The chown is gated behind a top-level ownership check so subsequent restarts skip the recursive traversal — no multi-second startup penalty on multi-GB archive directories. A sentinel `.bambuddy` file in each data path prevents Docker from re-syncing image directory metadata on every mount (otherwise empty volumes have their ownership reverted from the image on each restart, defeating the idempotency). When the container is started with an explicit `user:` directive or `--user` flag the entrypoint detects it isn't root and falls through to direct `exec` — preserving compatibility for users who pin a specific uid. **Compose template changes:** removes `user: "${PUID:-1000}:${PGID:-1000}"` (the entrypoint owns privilege drop now), adds `PUID` / `PGID` env vars with the same defaults, and comments out the `./virtual_printer:/app/data/virtual_printer` bind mount by default with explicit "only needed if you also run a native install of Bambuddy on the same host and want both to share the VP CA cert" guidance. The entrypoint chowns the host-side dir through the bind mount the first time it sees wrong ownership, so existing uncommented installs continue to work and #1211 specifically gets fixed.
+9
View File
@@ -67,6 +67,15 @@ COPY .git/HEAD ./.git/HEAD
# Copy built frontend from builder stage
COPY --from=frontend-builder /app/static ./static
# Copy embedded GCode viewer static assets (PrettyGCode + Bambuddy adapter).
# Served by the explicit @app.get("/gcode-viewer/{...}") routes in main.py,
# which resolve files under (static_dir.parent / "gcode_viewer") = /app/gcode_viewer/.
# Without this COPY the routes return a bare 404 at request time and the 3D
# Preview iframe shows {"detail":"Not Found"} (see #1218). The directory is
# vendored third-party JS — the Vite build does NOT stage it into static/,
# the dev server serves it via a configureServer middleware that's dev-only.
COPY gcode_viewer/ ./gcode_viewer/
# Create data directories. Ownership is normalised at startup by the
# entrypoint (chowns to PUID:PGID and drops privileges via gosu before
# exec'ing the app), so we don't need a chmod 777 hack here — that was
+13
View File
@@ -5180,6 +5180,19 @@ async def serve_sw_register():
# to the /{full_path:path} catch-all in some Starlette versions).
_gcode_viewer_dir = (app_settings.static_dir.parent / "gcode_viewer").resolve()
# Surface packaging gaps at startup instead of as silent runtime 404s. If the
# directory is missing the explicit @app.get("/gcode-viewer/...") routes below
# return bare HTTPException(404) which renders as {"detail":"Not Found"} in
# the 3D Preview iframe (#1218) — easy to miss in normal operation, easy to
# spot if the operator scans the startup log or a support bundle.
if not (_gcode_viewer_dir / "index.html").is_file():
logging.getLogger(__name__).error(
"Embedded GCode viewer assets missing at %s — /gcode-viewer/ will return 404 "
"and 3D Preview will fail. This indicates a packaging bug; the gcode_viewer/ "
"directory must be present alongside static/.",
_gcode_viewer_dir,
)
def _gcode_viewer_response(rel: str) -> FileResponse:
from fastapi import HTTPException as _HTTPException
@@ -41,6 +41,33 @@ class TestGCodeViewerRouteOrdering:
# If a body came back it must NOT be the React SPA shell.
assert b'<div id="root">' not in response.content
@pytest.mark.asyncio
@pytest.mark.integration
async def test_gcode_viewer_index_served_when_assets_present(self, async_client: AsyncClient):
"""GET /gcode-viewer/ must return the PrettyGCode index when the
vendored assets are on disk.
Regression guard for #1218: the production Dockerfile has to copy
``gcode_viewer/`` into the image alongside ``static/``. The previous
``test_gcode_viewer_index_does_not_fall_through_to_spa`` accepted
404 unconditionally so a missing COPY never failed CI. This test
only runs when the directory is actually present (so it stays a
no-op in unit-test environments where the assets are intentionally
absent), but when it does run it asserts 200 + a non-empty HTML
body so a future packaging regression fails loudly.
"""
from backend.app.main import _gcode_viewer_dir
index = _gcode_viewer_dir / "index.html"
if not index.is_file():
pytest.skip(f"gcode_viewer/index.html not present at {index} — skipping packaging assertion")
response = await async_client.get("/gcode-viewer/")
assert response.status_code == 200, (
f"gcode_viewer/index.html exists at {index} but /gcode-viewer/ returned "
f"{response.status_code} — route or response wiring is broken."
)
assert b"PrettyGCode" in response.content or b"<!doctype html>" in response.content.lower()
@pytest.mark.asyncio
@pytest.mark.integration
async def test_gcode_viewer_no_trailing_slash_falls_through_to_spa(self, async_client: AsyncClient):