Myriad changes.
This commit is contained in:
1 parent
8112f6913c
commit
cb2ef648fe
16 files changed
+402
-273
No files matched your search
+5
-7
@@ -2,15 +2,13 @@
|
||||
# Copy to .env and adjust for your deployment.
|
||||
|
||||
# Muon iframe source URL consumed by frontend/backend settings fallback.
|
||||
MUON_IFRAME_URL=http://localhost:3011
|
||||
# Set this to a hostname reachable by browser clients (not just localhost).
|
||||
MUON_IFRAME_URL=http://work:3011
|
||||
|
||||
# Pinned Muon fork commit/tag/branch used by muon-iframe build context.
|
||||
# Examples: main, v0.1.0, 1a2b3c4d
|
||||
MUON_GIT_REF=main
|
||||
|
||||
# Origin allowlist that the Muon iframe will accept postMessage commands from.
|
||||
# Supports comma-separated values.
|
||||
# Examples:
|
||||
# Dev only: http://work:5174,http://localhost:5174,http://localhost:3001,http://localhost:5173
|
||||
# Dev + Tailscale: http://work:5174,http://localhost:5174,https://stemengine-node.tailnet.ts.net
|
||||
STEMENGINE_ALLOWED_ORIGIN=http://work:5174,http://localhost:5174,http://localhost:3001,http://localhost:5173
|
||||
# Open-origin mode for Muon iframe postMessage commands.
|
||||
# Use '*' to disable origin restrictions.
|
||||
STEMENGINE_ALLOWED_ORIGIN=*
|
||||
@@ -145,6 +145,173 @@ Executed requested follow-up to do both items (harness fixes + cleanup):
|
||||
- pruned generated entries under `frontend/test-results/` (kept tracked `frontend/test-results/.last-run.json`).
|
||||
- no stale per-run failure directories remain.
|
||||
|
||||
### 2026-04-23 Track Detail source-audio enforcement + volume verification
|
||||
|
||||
Implemented and verified Track Detail live preview routing to always use source-audio playback.
|
||||
|
||||
Code change:
|
||||
|
||||
- `frontend/src/pages/ProjectDetail.tsx`
|
||||
- In `LrcPreview -> LyricsLivePreview` props:
|
||||
- `stems={undefined}`
|
||||
- `audioUrl={originalAudioUrl ?? stems?.[0]?.url}`
|
||||
|
||||
Runtime verification (browser, project `7b1cbef7-a4f7-457d-a908-8a8d169afe84`):
|
||||
|
||||
- Opened `Live preview (LRC)` in Track Detail.
|
||||
- Started playback and inspected runtime audio elements.
|
||||
- Confirmed playback source is `Elephant Heart - The Digital.flac` (source track).
|
||||
- Confirmed no leading/backing stem URL was used for audible playback.
|
||||
- Confirmed analysis channel remains intentionally silent (`volume=0`) while audible source channel plays.
|
||||
- Confirmed volume behavior is active during playback:
|
||||
- mute/unmute toggles updated audible channel volume.
|
||||
- keyboard-driven volume slider adjustment changed audible channel volume (`1 -> 0.95`).
|
||||
|
||||
### 2026-04-23 Global visualizer source-audio rollout + host-origin expansion
|
||||
|
||||
Implemented requested rollout so visualizer surfaces use source-audio transport when source audio is available, not stem transport.
|
||||
|
||||
Code changes:
|
||||
|
||||
- `frontend/src/components/LyricsLivePreview.tsx`
|
||||
- Added `useStemTransport` gate:
|
||||
- true only when stems exist and current mode is not a visualizer-with-source-audio path.
|
||||
- Routed playback/seek/timing/volume/mute logic to use `useStemTransport` instead of raw stem presence.
|
||||
- Ensures visualizer mode falls back to single-track source audio transport (`audioRef`) while keeping analysis audio behavior intact.
|
||||
- Stem mixer/performance stem controls now only appear when stem transport is actually active.
|
||||
- `frontend/src/pages/Karaoke.tsx`
|
||||
- `KaraokePerformanceMode` now always receives `audioUrl={sourceMedia?.url}`.
|
||||
- `frontend/src/pages/KaraokeTV.tsx`
|
||||
- `KaraokePerformanceMode` now always receives `audioUrl={sourceMedia?.url}`.
|
||||
|
||||
Config/default expansions (work host + ports 5174/3001/3011):
|
||||
|
||||
- `docker/stemengine.yml`
|
||||
- Expanded backend `CORS_ORIGINS` defaults to include `http://work:5174,http://work:3001,http://work:3011` plus localhost/127 entries.
|
||||
- Expanded Muon build arg default `STEMENGINE_ALLOWED_ORIGIN` to include `work:5174,work:3001,work:3011` plus localhost entries.
|
||||
- `appdata/stemengine/.env.example`
|
||||
- Updated documented `STEMENGINE_ALLOWED_ORIGIN` examples/default with `work:5174,work:3001,work:3011`.
|
||||
|
||||
Runtime/service validation:
|
||||
|
||||
- Rebuilt Muon image and confirmed built assets contain all three `work:*` origins (`WORK5174_PRESENT`, `WORK3001_PRESENT`, `WORK3011_PRESENT`).
|
||||
- Verified running backend container env includes expanded `CORS_ORIGINS` value with `work:5174,work:3001,work:3011`.
|
||||
- Frontend typecheck: `cd frontend && npm run -s typecheck` completed with no reported errors.
|
||||
|
||||
### 2026-04-23 403 fix — Process Song on 5174 (admin token propagation)
|
||||
|
||||
Root cause identified and patched for the `Process Song` flow from imported files.
|
||||
|
||||
Root cause:
|
||||
|
||||
- Backend endpoint `POST /api/separate/from-path` is admin-token guarded (`Depends(require_admin_token)`).
|
||||
- Frontend request helper only attached `X-Admin-Token` for a limited route set and did **not** include `/separate/from-path`.
|
||||
- With `ADMIN_TOKEN` configured in backend env, that request returned `403 {"detail":"Forbidden"}` from UI on `work:5174`.
|
||||
|
||||
Code fix:
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- In `requiresAdminToken(...)`, added:
|
||||
- `if (path === `${BASE}/separate/from-path`) return true`
|
||||
|
||||
Validation:
|
||||
|
||||
- `cd frontend && npm run -s typecheck` ✅
|
||||
- Frontend diagnostics show guard now includes `/separate/from-path` route.
|
||||
|
||||
### 2026-04-23 Admin token functionality fully disabled
|
||||
|
||||
Implemented requested hard-disable of all admin token behavior.
|
||||
|
||||
Backend changes:
|
||||
|
||||
- `backend/security.py`
|
||||
- `require_admin_token(...)` is now an intentional no-op.
|
||||
- Dependency still accepts `X-Admin-Token` header shape for compatibility, but no validation/enforcement occurs.
|
||||
|
||||
Frontend changes:
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- removed token-based request gating/enforcement behavior.
|
||||
- `getAdminToken()` returns empty string.
|
||||
- `setAdminToken(...)` and `clearAdminToken()` now only clear legacy localStorage value.
|
||||
- no request path adds `X-Admin-Token` header anymore.
|
||||
- `frontend/src/pages/Settings.tsx`
|
||||
- removed Admin Token controls/status section from Integrations.
|
||||
- removed associated state and handlers.
|
||||
|
||||
Validation:
|
||||
|
||||
- `cd frontend && npm run -s typecheck` ✅
|
||||
- `python3 -m py_compile backend/security.py` ✅
|
||||
- Runtime check on `POST /api/separate/from-path` **without** `X-Admin-Token` now returns non-auth response (`404 File not found` for sentinel path), confirming token enforcement is disabled (no `403 Forbidden`).
|
||||
|
||||
### 2026-04-23 Separator worker crash fix — `preset_name` kwarg mismatch
|
||||
|
||||
Patched backend separation worker/runtime signature mismatch that caused:
|
||||
|
||||
- `TypeError: _run_separation_impl() got an unexpected keyword argument 'preset_name'`
|
||||
|
||||
Root cause:
|
||||
|
||||
- `run_separation(...)` forwards `preset_name` into the worker payload.
|
||||
- `_run_separation_impl(...)` signature did not accept `preset_name`.
|
||||
- The same function also attempted to read `kwargs.get('preset_name', '')` even though `kwargs` is not defined in that scope.
|
||||
|
||||
Code fix:
|
||||
|
||||
- `backend/services/separator_service.py`
|
||||
- added `preset_name: Optional[str] = None` to `_run_separation_impl(...)`.
|
||||
- changed metadata write from `kwargs.get('preset_name', '')` to `preset_name or ''`.
|
||||
|
||||
Validation:
|
||||
|
||||
- `python3 -m py_compile backend/services/separator_service.py` ✅
|
||||
|
||||
### 2026-04-23 Open-origin policy — disable all CORS/origin restrictions
|
||||
|
||||
Applied requested full disable of origin restrictions across backend API CORS and Muon messaging surfaces.
|
||||
|
||||
Backend/API changes:
|
||||
|
||||
- `backend/main.py`
|
||||
- `CORSMiddleware` now runs in open mode:
|
||||
- `allow_origins=["*"]`
|
||||
- `allow_origin_regex=None`
|
||||
|
||||
Compose/env defaults:
|
||||
|
||||
- `docker/stemengine.yml`
|
||||
- backend env defaults changed to:
|
||||
- `CORS_ORIGINS=${CORS_ORIGINS:-*}`
|
||||
- `CORS_ORIGIN_REGEX=${CORS_ORIGIN_REGEX:-}`
|
||||
- Muon build arg default changed to:
|
||||
- `STEMENGINE_ALLOWED_ORIGIN=${STEMENGINE_ALLOWED_ORIGIN:-*}`
|
||||
- `appdata/stemengine/stemengine.yml`
|
||||
- backend env defaults changed to:
|
||||
- `CORS_ORIGINS=${CORS_ORIGINS:-*}`
|
||||
- `CORS_ORIGIN_REGEX=${CORS_ORIGIN_REGEX:-}`
|
||||
- `appdata/stemengine/.env.example`
|
||||
- documented open-origin default:
|
||||
- `STEMENGINE_ALLOWED_ORIGIN=*`
|
||||
|
||||
Frontend Muon bridge changes (removed origin filtering):
|
||||
|
||||
- `frontend/src/components/LyricsLivePreview.tsx`
|
||||
- `frontend/src/components/VisualizerPreviewWidget.tsx`
|
||||
- `frontend/src/pages/VisualizerLabPage.tsx`
|
||||
- removed target-origin allowlist logic (`muonTargetOrigin` path)
|
||||
- Muon commands now post with wildcard target (`postMessage(..., '*')`)
|
||||
- message listeners now validate sender by iframe window (`event.source === iframeRef.current?.contentWindow`) instead of origin-string checks
|
||||
|
||||
Validation:
|
||||
|
||||
- `python3 -m py_compile backend/main.py` ✅
|
||||
- `cd frontend && npm run -s typecheck` ✅
|
||||
- backend restart: `docker compose -p stemengine -f stemengine.yml restart stemengine` ✅
|
||||
- live CORS preflight check from arbitrary origin returned open preflight response:
|
||||
- `OPTIONS /api/jobs` with `Origin: https://evil.example` -> `204 No Content` with CORS allow headers ✅
|
||||
|
||||
## 2026-04-23 Work Log — Muon Schema Comparison Pre-Patch Corrections
|
||||
|
||||
Status: plan/docs patch complete, implementation patch not started in code.
|
||||
|
||||
@@ -117,6 +117,149 @@ Completed the requested `do both` action in one pass:
|
||||
- pruned run-output entries under `frontend/test-results/`.
|
||||
- retained tracked `frontend/test-results/.last-run.json`.
|
||||
|
||||
### Track Detail source-audio enforcement + volume verification (2026-04-23)
|
||||
|
||||
Applied a Track Detail preview routing correction so preview playback always uses source audio, not stem-mix playback.
|
||||
|
||||
Change applied:
|
||||
|
||||
- `frontend/src/pages/ProjectDetail.tsx`
|
||||
- `LrcPreview -> LyricsLivePreview` now passes:
|
||||
- `stems={undefined}`
|
||||
- `audioUrl={originalAudioUrl ?? stems?.[0]?.url}`
|
||||
|
||||
Live verification on `http://work:5174/projects/7b1cbef7-a4f7-457d-a908-8a8d169afe84`:
|
||||
|
||||
- Opened Track Detail `Live preview (LRC)` and started playback.
|
||||
- Observed active audio sources resolved to source track URL (`Elephant Heart - The Digital.flac`), with no leading/backing source used for audible channel.
|
||||
- Confirmed dual-audio behavior is expected:
|
||||
- analysis channel at `volume=0` (intentional)
|
||||
- audible source channel playing.
|
||||
- Confirmed volume controls are effective in active playback path:
|
||||
- mute/unmute toggles work
|
||||
- slider adjustment reflected audible volume change (`1 -> 0.95`).
|
||||
|
||||
### Global visualizer source-audio rollout + host-origin expansion (2026-04-23)
|
||||
|
||||
Applied requested behavior globally: wherever visualizer mode is active and source audio exists, transport now uses source audio instead of stem transport.
|
||||
|
||||
Implemented changes:
|
||||
|
||||
- `frontend/src/components/LyricsLivePreview.tsx`
|
||||
- added `useStemTransport` gate so stem transport is only used in non-visualizer stem playback paths.
|
||||
- switched timing, seek, play/pause, mute/volume, and transport source selection logic to this gate.
|
||||
- in visualizer mode with source audio, the hidden single-track audio path is used (`audioRef`), preserving consistent volume control.
|
||||
- stem mixer/performance stem controls are hidden when stem transport is inactive.
|
||||
- `frontend/src/pages/Karaoke.tsx`
|
||||
- now always passes `audioUrl={sourceMedia?.url}` into `KaraokePerformanceMode`.
|
||||
- `frontend/src/pages/KaraokeTV.tsx`
|
||||
- now always passes `audioUrl={sourceMedia?.url}` into `KaraokePerformanceMode`.
|
||||
|
||||
Expanded host/port defaults (`work:5174`, `work:3001`, `work:3011`):
|
||||
|
||||
- `docker/stemengine.yml`
|
||||
- `CORS_ORIGINS` default includes all `work:*` origins plus localhost/127.
|
||||
- `STEMENGINE_ALLOWED_ORIGIN` build-arg default includes all `work:*` origins plus localhost.
|
||||
- `appdata/stemengine/.env.example`
|
||||
- updated `STEMENGINE_ALLOWED_ORIGIN` documentation/default to include `work:5174,work:3001,work:3011`.
|
||||
|
||||
Verification:
|
||||
|
||||
- rebuilt Muon image and confirmed all requested `work:*` origins exist in built output.
|
||||
- backend container env confirms expanded `CORS_ORIGINS` value.
|
||||
- frontend typecheck completed successfully (`npm run -s typecheck`).
|
||||
|
||||
### 403 regression fix — Process Song on 5174 (2026-04-23)
|
||||
|
||||
Patched a frontend auth-header mismatch causing `403 Forbidden` when processing imported songs.
|
||||
|
||||
What was happening:
|
||||
|
||||
- Backend protects `POST /api/separate/from-path` with `require_admin_token` when `ADMIN_TOKEN` is set.
|
||||
- Frontend `request()` adds `X-Admin-Token` only for routes matched by `requiresAdminToken()`.
|
||||
- That matcher did not include `/separate/from-path`, so the UI call went out without token and failed with 403.
|
||||
|
||||
Patch applied:
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- `requiresAdminToken()` now returns `true` for `${BASE}/separate/from-path`.
|
||||
|
||||
Validation:
|
||||
|
||||
- `cd frontend && npm run -s typecheck` ✅
|
||||
- Route-guard grep confirms `/separate/from-path` is now in the token-required matcher.
|
||||
|
||||
### Admin token functionality disabled globally (2026-04-23)
|
||||
|
||||
Applied requested hard-disable for all admin token functionality.
|
||||
|
||||
Backend:
|
||||
|
||||
- `backend/security.py`
|
||||
- `require_admin_token(...)` now intentionally does nothing.
|
||||
- `X-Admin-Token` may be present but is ignored.
|
||||
|
||||
Frontend:
|
||||
|
||||
- `frontend/src/api/client.ts`
|
||||
- removed runtime token enforcement behavior in request flow.
|
||||
- admin token helpers now clear legacy storage only; no active auth behavior remains.
|
||||
- `frontend/src/pages/Settings.tsx`
|
||||
- removed Admin Token input/save/remove UI block from Integrations.
|
||||
- removed related state/handlers.
|
||||
|
||||
Validation:
|
||||
|
||||
- frontend typecheck passes.
|
||||
- backend module compiles.
|
||||
- unauthenticated call to `POST /api/separate/from-path` returns non-auth error for missing sentinel file (404), confirming no token enforcement (no 403).
|
||||
|
||||
### Separator worker `preset_name` TypeError fix (2026-04-23)
|
||||
|
||||
Resolved a backend worker crash during song processing:
|
||||
|
||||
- Error:
|
||||
- `TypeError: _run_separation_impl() got an unexpected keyword argument 'preset_name'`
|
||||
|
||||
Cause and fix:
|
||||
|
||||
- `run_separation(...)` sends `preset_name` to the worker payload, but `_run_separation_impl(...)` did not accept it.
|
||||
- Updated `backend/services/separator_service.py` to accept `preset_name` in `_run_separation_impl(...)`.
|
||||
- Replaced invalid in-scope reference `kwargs.get('preset_name', '')` with `preset_name or ''` when writing project metadata.
|
||||
|
||||
Validation:
|
||||
|
||||
- `python3 -m py_compile backend/services/separator_service.py` ✅
|
||||
|
||||
### Open-origin mode enabled globally (2026-04-23)
|
||||
|
||||
Implemented requested full removal of CORS/origin restrictions.
|
||||
|
||||
Delivered:
|
||||
|
||||
- Backend CORS opened globally in `backend/main.py`:
|
||||
- `allow_origins=["*"]`
|
||||
- `allow_origin_regex=None`
|
||||
- Compose defaults switched to wildcard/no-regex:
|
||||
- `docker/stemengine.yml`
|
||||
- `appdata/stemengine/stemengine.yml`
|
||||
- `CORS_ORIGINS=*`, `CORS_ORIGIN_REGEX=`
|
||||
- Muon origin defaults switched to wildcard:
|
||||
- `STEMENGINE_ALLOWED_ORIGIN=*` in compose default and `.env.example`.
|
||||
- Frontend Muon message origin checks removed in:
|
||||
- `frontend/src/components/LyricsLivePreview.tsx`
|
||||
- `frontend/src/components/VisualizerPreviewWidget.tsx`
|
||||
- `frontend/src/pages/VisualizerLabPage.tsx`
|
||||
- outbound messages now use `postMessage(..., '*')`
|
||||
- inbound ready handling validates iframe window source instead of origin string.
|
||||
|
||||
Validation:
|
||||
|
||||
- backend compile check passed.
|
||||
- frontend typecheck passed.
|
||||
- backend restarted successfully.
|
||||
- live preflight from arbitrary origin (`Origin: https://evil.example`) returned successful CORS preflight (`204` + allow headers).
|
||||
|
||||
## 2026-04-17
|
||||
|
||||
### Muon Visualizer — Phase 3/4 render graphs and Phase 5 integration pass
|
||||
@@ -4949,3 +5092,12 @@ Key findings documented:
|
||||
- **Per-vertex FFT not viable across postMessage**: Only SharedArrayBuffer with Cross-Origin-Isolated headers would enable this, and that is not available in all deployment environments. Documented as option 3 (accept scalar-only constraint) — current stance.
|
||||
|
||||
**File created:** `docs/plans/2026-04-23_Muon_Schema_Comparison/2026-04-23_Original_Muon_vs_StemEngine.md`
|
||||
|
||||
### Muon iframe — open-origin postMessage (visualizer reactivity unrestricted)
|
||||
|
||||
Removed the origin allowlist check from the Muon iframe's postMessage listener. The iframe now accepts commands from any origin (`isAllowedOrigin` always returns `true`). Also removed the FATAL/warning startup console errors that fired when `STEMENGINE_ALLOWED_ORIGIN` was not substituted.
|
||||
|
||||
Rationale: the commands the router accepts are all inert (audio scalars, style/quality/pause state) — there is no meaningful security boundary. The previous allowlist caused reactivity to silently fail when the frontend origin did not exactly match the configured allowlist (e.g. different port, hostname, or unconfigured build arg).
|
||||
|
||||
**Files changed:** `muon-iframe/stemengine-router.js`
|
||||
**Validation:** `node --check` ✅ · image rebuilt (`bundle.9bcc3c4c7ee7c4a45ad6.js`) · container recreated and running on port 3011 ✅
|
||||
+3
-2
@@ -172,8 +172,9 @@ def create_app() -> FastAPI:
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=app_settings.cors_origins_resolved,
|
||||
allow_origin_regex=app_settings.cors_origin_regex_resolved,
|
||||
# Open CORS mode: accept requests from any origin.
|
||||
allow_origins=["*"],
|
||||
allow_origin_regex=None,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
+6
-10
@@ -1,17 +1,13 @@
|
||||
"""Security helpers for high-power operational endpoints."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from .config import ADMIN_TOKEN
|
||||
from fastapi import Header
|
||||
|
||||
|
||||
def require_admin_token(x_admin_token: str | None = Header(default=None, alias="X-Admin-Token")) -> None:
|
||||
"""Require the configured admin token when ADMIN_TOKEN is set.
|
||||
def require_admin_token(_x_admin_token: str | None = Header(default=None, alias="X-Admin-Token")) -> None:
|
||||
"""Admin token checks are disabled.
|
||||
|
||||
In development (no ADMIN_TOKEN configured), this is a no-op.
|
||||
This dependency intentionally does nothing so protected endpoints remain
|
||||
accessible without any X-Admin-Token header.
|
||||
"""
|
||||
if not ADMIN_TOKEN:
|
||||
return
|
||||
if x_admin_token != ADMIN_TOKEN:
|
||||
raise HTTPException(status_code=403, detail="Forbidden")
|
||||
return
|
||||
@@ -959,6 +959,7 @@ def _run_separation_impl(
|
||||
mp3_bitrate_override: Optional[str] = None,
|
||||
# Project naming
|
||||
project_name_override: Optional[str] = None,
|
||||
preset_name: Optional[str] = None,
|
||||
# Power preset
|
||||
sep_power_preset: str = 'standard',
|
||||
# Optional request-level runtime overrides
|
||||
@@ -1332,7 +1333,7 @@ def _run_separation_impl(
|
||||
lrc_jobs={},
|
||||
mix_job_id=None,
|
||||
instrument_models=instrument_models_summary,
|
||||
preset_name=kwargs.get('preset_name', ''),
|
||||
preset_name=preset_name or '',
|
||||
)
|
||||
except Exception as meta_err:
|
||||
jm.update_job(job_id, progress=f"Warning: could not write project.json: {meta_err}")
|
||||
|
||||
@@ -91,18 +91,16 @@ function resolveApiUrl(url: string): string {
|
||||
const ADMIN_TOKEN_KEY = 'stemengine-admin-token'
|
||||
|
||||
export function getAdminToken(): string {
|
||||
if (typeof window === 'undefined') return ''
|
||||
return localStorage.getItem(ADMIN_TOKEN_KEY)?.trim() || ''
|
||||
return ''
|
||||
}
|
||||
|
||||
export function setAdminToken(token: string): void {
|
||||
if (typeof window === 'undefined') return
|
||||
const trimmed = token.trim()
|
||||
if (!trimmed) {
|
||||
localStorage.removeItem(ADMIN_TOKEN_KEY)
|
||||
return
|
||||
// Admin token functionality is disabled; clear any legacy stored value.
|
||||
if (token) {
|
||||
// no-op input handling
|
||||
}
|
||||
localStorage.setItem(ADMIN_TOKEN_KEY, trimmed)
|
||||
localStorage.removeItem(ADMIN_TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function clearAdminToken(): void {
|
||||
@@ -110,38 +108,13 @@ export function clearAdminToken(): void {
|
||||
localStorage.removeItem(ADMIN_TOKEN_KEY)
|
||||
}
|
||||
|
||||
function requiresAdminToken(url: string, method?: string): boolean {
|
||||
const verb = (method ?? 'GET').toUpperCase()
|
||||
|
||||
// Normalize absolute URLs to pathnames; keep relative paths as-is.
|
||||
let path = url
|
||||
try {
|
||||
path = new URL(url, window.location.origin).pathname
|
||||
} catch {
|
||||
// keep original string
|
||||
}
|
||||
|
||||
if (path === `${BASE}/system/gpu-reset`) return true
|
||||
if (path.startsWith(`${BASE}/projects/cleanup/`)) return true
|
||||
if (path.startsWith(`${BASE}/models/`) && verb !== 'GET') return true
|
||||
return false
|
||||
}
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const resolvedUrl = resolveApiUrl(url)
|
||||
const headers = new Headers(init?.headers)
|
||||
if (requiresAdminToken(url, init?.method)) {
|
||||
const token = getAdminToken()
|
||||
if (token) headers.set('X-Admin-Token', token)
|
||||
}
|
||||
|
||||
const res = await fetch(resolvedUrl, { ...init, headers })
|
||||
if (!res.ok) {
|
||||
const text = await res.text()
|
||||
if (res.status === 403 && requiresAdminToken(url, init?.method)) {
|
||||
const detail = text || 'Forbidden'
|
||||
throw new Error(`403: ${detail} (admin token required — set it in Settings → Integrations)`)
|
||||
}
|
||||
throw new Error(`${res.status}: ${text}`)
|
||||
}
|
||||
return res.json() as Promise<T>
|
||||
|
||||
@@ -84,16 +84,6 @@ function withDefaultMuonPreset(rawUrl: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getMuonTargetOrigin(rawUrl: string): string | null {
|
||||
try {
|
||||
const origin = new URL(rawUrl).origin
|
||||
if (origin === 'https://muon-vis.netlify.app') return null
|
||||
return origin
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function isVisualizerModeStyle(style: unknown): style is Exclude<VisualizerMode, null> {
|
||||
return typeof style === 'string' && VISUALIZER_STYLE_MODES.has(style as Exclude<VisualizerMode, null>)
|
||||
}
|
||||
@@ -892,6 +882,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
const isIframeVisualizerMode = visualStyle === 'muon_iframe'
|
||||
const isBackdropVisualizerMode = asVisualizerMode(visualStyle) !== null
|
||||
const isVisualizerMode = isBackdropVisualizerMode || isIframeVisualizerMode
|
||||
const useStemTransport = !!(isMultiStem && !(isVisualizerMode && !!audioUrl))
|
||||
const resolvedVideoPlaylist = useMemo(
|
||||
() => (videoPlaylist ?? [])
|
||||
.filter((item) => typeof item?.url === 'string' && item.url.trim())
|
||||
@@ -917,7 +908,6 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
const [muonIframeUrl, setMuonIframeUrl] = useState(DEFAULT_MUON_IFRAME_URL)
|
||||
const [muonIframeError, setMuonIframeError] = useState(false)
|
||||
const muonEmbedUrl = useMemo(() => withDefaultMuonPreset(muonIframeUrl), [muonIframeUrl])
|
||||
const muonTargetOrigin = useMemo(() => getMuonTargetOrigin(muonEmbedUrl), [muonEmbedUrl])
|
||||
|
||||
useEffect(() => {
|
||||
muonIframeReadyRef.current = false
|
||||
@@ -1104,7 +1094,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
} = useStemAudio({
|
||||
setAudioCtxVersion,
|
||||
stableStems,
|
||||
isMultiStem: !!(stems && stems.length > 0),
|
||||
isMultiStem: useStemTransport,
|
||||
setDuration,
|
||||
setGains,
|
||||
setMutedStems,
|
||||
@@ -1136,8 +1126,8 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
|
||||
// Stable stop callback registered with the global audio registry.
|
||||
// Uses refs so it never needs to be recreated and is safe to pass to the registry.
|
||||
const isMultiStemRef = useRef(isMultiStem)
|
||||
useEffect(() => { isMultiStemRef.current = isMultiStem }, [isMultiStem])
|
||||
const isMultiStemRef = useRef(useStemTransport)
|
||||
useEffect(() => { isMultiStemRef.current = useStemTransport }, [useStemTransport])
|
||||
|
||||
const stopPlayback = useCallback(() => {
|
||||
isActiveRef.current = false
|
||||
@@ -1325,14 +1315,14 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
|
||||
// ── Duration from last lyric line when no audio ───────────────────────────
|
||||
useEffect(() => {
|
||||
if (!audioUrl && !isMultiStem && lines.length > 0) {
|
||||
if (!audioUrl && !useStemTransport && lines.length > 0) {
|
||||
const last = lines[lines.length - 1]
|
||||
const t = last.words.length > 0
|
||||
? last.words[last.words.length - 1].time + 3
|
||||
: last.time + 4
|
||||
setDuration(t)
|
||||
}
|
||||
}, [audioUrl, isMultiStem, lines])
|
||||
}, [audioUrl, useStemTransport, lines])
|
||||
|
||||
// ── Web Audio helpers ────────────────────────────────────────────────────
|
||||
async function waitForStemReadiness(audios: HTMLAudioElement[]): Promise<void> {
|
||||
@@ -1364,7 +1354,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
}, [volume, isMuted, mutedStems, soloedStems, gains])
|
||||
|
||||
useEffect(() => {
|
||||
if (!performanceMode || !isMultiStem || !stems?.length) return
|
||||
if (!performanceMode || !useStemTransport || !stems?.length) return
|
||||
if (hasSavedMutedStemPrefs || perfLeadingMuteAppliedRef.current) return
|
||||
|
||||
const defaultMutes: Record<string, boolean> = {}
|
||||
@@ -1377,17 +1367,17 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
|
||||
setMutedStems(defaultMutes)
|
||||
applyGains({ mutedStems: defaultMutes })
|
||||
}, [performanceMode, isMultiStem, stems, hasSavedMutedStemPrefs, applyGains])
|
||||
}, [performanceMode, useStemTransport, stems, hasSavedMutedStemPrefs, applyGains])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isMultiStem) return
|
||||
if (!useStemTransport) return
|
||||
applyGains()
|
||||
}, [applyGains, isMultiStem, stableStems])
|
||||
}, [applyGains, useStemTransport, stableStems])
|
||||
|
||||
useEffect(() => {
|
||||
if (isMultiStem || !audioRef.current) return
|
||||
if (useStemTransport || !audioRef.current) return
|
||||
audioRef.current.volume = isMuted ? 0 : volume
|
||||
}, [isMultiStem, isMuted, volume])
|
||||
}, [useStemTransport, isMuted, volume])
|
||||
|
||||
// ── RAF loop ──────────────────────────────────────────────────────────────
|
||||
function pickStemClockSourceEntry(preferredStemName?: string | null): [string, HTMLAudioElement] | null {
|
||||
@@ -1433,7 +1423,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
function loop(ts: number) {
|
||||
const timeSource = useVideoAsTimeSource
|
||||
? videoRef.current
|
||||
: (isMultiStem
|
||||
: (useStemTransport
|
||||
? pickStemClockSource(syncAnchorStemRef.current)
|
||||
: audioRef.current)
|
||||
|
||||
@@ -1510,10 +1500,10 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
|
||||
rafRef.current = null
|
||||
}
|
||||
}, [isPlaying, duration, isMultiStem, useVideoAsTimeSource, finalizePlayback])
|
||||
}, [isPlaying, duration, useStemTransport, useVideoAsTimeSource, finalizePlayback])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isMultiStem || !isPlaying) return
|
||||
if (!useStemTransport || !isPlaying) return
|
||||
const syncToleranceSeconds = 0.12
|
||||
const timer = window.setInterval(() => {
|
||||
const entries = Object.entries(stemAudioRefs.current)
|
||||
@@ -1558,7 +1548,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
}
|
||||
}, 250)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [isMultiStem, isPlaying, useVideoAsTimeSource])
|
||||
}, [useStemTransport, isPlaying, useVideoAsTimeSource])
|
||||
|
||||
useEffect(() => {
|
||||
const el = analysisAudioRef.current
|
||||
@@ -1571,7 +1561,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
const analysis = analysisAudioRef.current
|
||||
if (!analysis) return
|
||||
|
||||
const transportRate = isMultiStem
|
||||
const transportRate = useStemTransport
|
||||
? (pickStemClockSource(syncAnchorStemRef.current)?.playbackRate ?? 1)
|
||||
: (audioRef.current?.playbackRate ?? videoRef.current?.playbackRate ?? 1)
|
||||
|
||||
@@ -1590,11 +1580,11 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
}, 120)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [isPlaying, isMultiStem])
|
||||
}, [isPlaying, useStemTransport])
|
||||
|
||||
// End multi-stem playback as soon as every active stem reaches end.
|
||||
useEffect(() => {
|
||||
if (!isMultiStem || !isPlaying) return
|
||||
if (!useStemTransport || !isPlaying) return
|
||||
const timer = window.setInterval(() => {
|
||||
const entries = Object.entries(stemAudioRefs.current)
|
||||
if (!entries.length) return
|
||||
@@ -1612,7 +1602,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
finalizePlayback(endedAt || currentTimeRef.current)
|
||||
}, 180)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [isMultiStem, isPlaying, useVideoAsTimeSource, finalizePlayback])
|
||||
}, [useStemTransport, isPlaying, useVideoAsTimeSource, finalizePlayback])
|
||||
|
||||
// ── Fullscreen ────────────────────────────────────────────────────────────
|
||||
const fullscreenRef = useRef<HTMLDivElement | null>(null)
|
||||
@@ -1629,15 +1619,14 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
}, [liveVizSettings.muon_iframe])
|
||||
|
||||
const sendMuonCommand = useCallback((type: string, payload: Record<string, unknown>) => {
|
||||
if (!muonTargetOrigin || !muonIframeReadyRef.current) return
|
||||
if (!muonIframeReadyRef.current) return
|
||||
iframeRef.current?.contentWindow?.postMessage(
|
||||
{ version: 1, id: `lyrics-${Date.now()}`, type, payload },
|
||||
muonTargetOrigin,
|
||||
'*',
|
||||
)
|
||||
}, [muonTargetOrigin])
|
||||
}, [])
|
||||
|
||||
const rehydrateMuonIframe = useCallback(() => {
|
||||
if (!muonTargetOrigin) return
|
||||
sendMuonCommand('setStyle', { style: iframeVisualSettingsRef.current.style })
|
||||
sendMuonCommand('setPreset', { preset: iframeVisualSettingsRef.current.preset })
|
||||
sendMuonCommand('setQuality', { quality: iframeVisualSettingsRef.current.quality })
|
||||
@@ -1649,7 +1638,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
sendMuonCommand('setPaused', {
|
||||
paused: typeof document !== 'undefined' ? document.hidden || !isPlayingRef.current : !isPlayingRef.current,
|
||||
})
|
||||
}, [muonTargetOrigin, sendMuonCommand, visualizerSize.height, visualizerSize.width])
|
||||
}, [sendMuonCommand, visualizerSize.height, visualizerSize.width])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
@@ -1699,9 +1688,8 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
}, [isIframeVisualizerMode, isPlaying, sendMuonCommand])
|
||||
|
||||
useEffect(() => {
|
||||
if (!muonTargetOrigin) return
|
||||
const onMessage = (event: MessageEvent) => {
|
||||
if (event.origin !== muonTargetOrigin) return
|
||||
if (event.source !== iframeRef.current?.contentWindow) return
|
||||
const msg = event.data as { type?: string } | null
|
||||
if (!msg || typeof msg !== 'object') return
|
||||
if (msg.type === 'ready') {
|
||||
@@ -1712,7 +1700,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
window.addEventListener('message', onMessage)
|
||||
if (isIframeVisualizerMode) rehydrateMuonIframe()
|
||||
return () => window.removeEventListener('message', onMessage)
|
||||
}, [isIframeVisualizerMode, muonTargetOrigin, rehydrateMuonIframe])
|
||||
}, [isIframeVisualizerMode, rehydrateMuonIframe])
|
||||
|
||||
useEffect(() => {
|
||||
const onVisible = () => {
|
||||
@@ -1916,7 +1904,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
function applySeekPosition(targetTime: number) {
|
||||
const transportDuration = resolvePlaybackDuration()
|
||||
const t = Math.max(0, Math.min(targetTime, transportDuration || Number.POSITIVE_INFINITY))
|
||||
if (isMultiStem) {
|
||||
if (useStemTransport) {
|
||||
Object.values(stemAudioRefs.current).forEach(a => { a.currentTime = t })
|
||||
syncAnchorStemRef.current = pickStemClockSourceEntry(syncAnchorStemRef.current)?.[0]
|
||||
?? pickStemClockSourceEntry()?.[0]
|
||||
@@ -1995,7 +1983,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
const togglePlay = useCallback(async () => {
|
||||
const currentlyPlaying = isPlayingRef.current
|
||||
const startTime = resolveStartTimeForPlay()
|
||||
if (isMultiStem) {
|
||||
if (useStemTransport) {
|
||||
const ctx = getCtx()
|
||||
const audios = Object.values(stemAudioRefs.current)
|
||||
if (currentlyPlaying) {
|
||||
@@ -2087,7 +2075,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
setPlaybackState(!currentlyPlaying)
|
||||
}
|
||||
}, [
|
||||
isMultiStem,
|
||||
useStemTransport,
|
||||
hasVideoBackdrop,
|
||||
isPlaylistBackdropMode,
|
||||
disableGlobalPlaybackRegistry,
|
||||
@@ -2146,7 +2134,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
isSeekingRef.current = false
|
||||
}
|
||||
|
||||
const targetAudio = isMultiStem
|
||||
const targetAudio = useStemTransport
|
||||
? (Object.values(stemAudioRefs.current)[0] ?? null)
|
||||
: audioRef.current
|
||||
|
||||
@@ -2184,7 +2172,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
setVideoStartPhase('idle')
|
||||
setVideoPlaylistIndex(0)
|
||||
desiredVideoSegmentRef.current = resolvedVideoPlaylist.length > 0 ? { index: 0, localTime: 0 } : null
|
||||
if (isMultiStem) {
|
||||
if (useStemTransport) {
|
||||
Object.values(stemAudioRefs.current).forEach(a => { a.currentTime = 0; a.pause() })
|
||||
} else if (audioRef.current) {
|
||||
audioRef.current.currentTime = 0
|
||||
@@ -2242,7 +2230,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
const setVolumeFromBar = useRef<(v: number) => void>(() => {})
|
||||
setVolumeFromBar.current = (v: number) => {
|
||||
setVolume(v)
|
||||
if (isMultiStem) {
|
||||
if (useStemTransport) {
|
||||
setIsMuted(false)
|
||||
applyGains({ master: v, muted: false })
|
||||
return
|
||||
@@ -2327,7 +2315,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
function handleVolumeChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const v = parseFloat(e.target.value)
|
||||
setVolume(v)
|
||||
if (isMultiStem) {
|
||||
if (useStemTransport) {
|
||||
setIsMuted(false)
|
||||
applyGains({ master: v, muted: false })
|
||||
} else if (audioRef.current) {
|
||||
@@ -2339,11 +2327,11 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
function toggleMute() {
|
||||
if (isMuted) {
|
||||
setIsMuted(false)
|
||||
if (isMultiStem) applyGains({ muted: false })
|
||||
if (useStemTransport) applyGains({ muted: false })
|
||||
else if (audioRef.current) audioRef.current.volume = volume
|
||||
} else {
|
||||
setIsMuted(true)
|
||||
if (isMultiStem) applyGains({ muted: true })
|
||||
if (useStemTransport) applyGains({ muted: true })
|
||||
else if (audioRef.current) audioRef.current.volume = 0
|
||||
}
|
||||
}
|
||||
@@ -2401,7 +2389,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
// ── Layout ────────────────────────────────────────────────────────────────
|
||||
|
||||
const displayDuration = resolvePlaybackDuration() || 1
|
||||
const hasAudio = isMultiStem || !!audioUrl || hasVideoBackdrop
|
||||
const hasAudio = useStemTransport || !!audioUrl || hasVideoBackdrop
|
||||
|
||||
const lyricsCanvasStyle: StyleState & { bgGradient?: string | null } = {
|
||||
bgColor: (hasVideoBackdrop || isVisualizerMode) ? 'rgba(0,0,0,0)' : effectiveBgColor,
|
||||
@@ -2692,7 +2680,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
{!performanceMode && (
|
||||
<StemMixerPanel
|
||||
isFullscreen={isFullscreen}
|
||||
stems={isMultiStem ? stems : undefined}
|
||||
stems={useStemTransport ? stems : undefined}
|
||||
gains={gains}
|
||||
mutedStems={mutedStems}
|
||||
soloedStems={soloedStems}
|
||||
@@ -2796,7 +2784,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
setVisualStyle(normalized ?? next)
|
||||
}}
|
||||
hasVideo={!!(videoUrl || resolvedVideoPlaylist.length > 0)}
|
||||
stems={stems}
|
||||
stems={useStemTransport ? stems : undefined}
|
||||
mutedStems={mutedStems}
|
||||
soloedStems={soloedStems}
|
||||
gains={gains}
|
||||
@@ -2833,7 +2821,7 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, projectId, so
|
||||
)}
|
||||
|
||||
{/* Hidden single-track transport audio element */}
|
||||
{!isMultiStem && audioUrl && (
|
||||
{!useStemTransport && audioUrl && (
|
||||
<audio
|
||||
ref={audioRef}
|
||||
src={audioUrl}
|
||||
|
||||
@@ -52,17 +52,6 @@ function withDefaultPreset(rawUrl: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getMuonTargetOrigin(rawUrl: string): string | null {
|
||||
try {
|
||||
const origin = new URL(rawUrl).origin
|
||||
// Do not send command messages to the third-party hosted demo.
|
||||
if (origin === 'https://muon-vis.netlify.app') return null
|
||||
return origin
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
type MuonStyle = 'fluid' | 'tendrils' | 'spirit' | 'default'
|
||||
|
||||
const MUON_STYLES: MuonStyle[] = ['default', 'fluid', 'tendrils', 'spirit']
|
||||
@@ -156,7 +145,6 @@ const VisualizerPreviewWidget = forwardRef<HTMLAudioElement, VisualizerPreviewWi
|
||||
useEffect(() => {
|
||||
muonIframeReadyRef.current = false
|
||||
}, [muonEmbedUrl])
|
||||
const muonTargetOrigin = useMemo(() => getMuonTargetOrigin(muonEmbedUrl), [muonEmbedUrl])
|
||||
|
||||
const normalizedVideoUrl = useMemo(() => String(videoUrl || '').trim(), [videoUrl])
|
||||
const canPreviewVideo = useMemo(() => isDirectVideoUrl(normalizedVideoUrl), [normalizedVideoUrl])
|
||||
@@ -256,17 +244,16 @@ const VisualizerPreviewWidget = forwardRef<HTMLAudioElement, VisualizerPreviewWi
|
||||
|
||||
const sendMuonCommand = useCallback(
|
||||
(type: string, payload: Record<string, unknown>) => {
|
||||
if (!muonTargetOrigin || !muonIframeReadyRef.current) return
|
||||
if (!muonIframeReadyRef.current) return
|
||||
iframeRef.current?.contentWindow?.postMessage(
|
||||
{ version: 1, id: `vis-${Date.now()}`, type, payload },
|
||||
muonTargetOrigin,
|
||||
'*',
|
||||
)
|
||||
},
|
||||
[muonTargetOrigin],
|
||||
[],
|
||||
)
|
||||
|
||||
const rehydrateMuonState = useCallback(() => {
|
||||
if (!muonTargetOrigin) return
|
||||
sendMuonCommand('setStyle', { style: muonStyleRef.current })
|
||||
sendMuonCommand('setPreset', { preset: muonPresetRef.current })
|
||||
sendMuonCommand('setQuality', { quality: muonQualityRef.current })
|
||||
@@ -280,7 +267,7 @@ const VisualizerPreviewWidget = forwardRef<HTMLAudioElement, VisualizerPreviewWi
|
||||
sendMuonCommand('setPaused', {
|
||||
paused: typeof document !== 'undefined' ? document.hidden || !isPlayingRef.current : !isPlayingRef.current,
|
||||
})
|
||||
}, [muonTargetOrigin, sendMuonCommand])
|
||||
}, [sendMuonCommand])
|
||||
|
||||
useEffect(() => {
|
||||
const nextStyle = (visualizerSettings?.muon_iframe?.style as MuonStyle | undefined) ?? muonStyleFromPreferredMode(preferredMode)
|
||||
@@ -356,9 +343,8 @@ const VisualizerPreviewWidget = forwardRef<HTMLAudioElement, VisualizerPreviewWi
|
||||
|
||||
// Listen for ready / error events emitted by the Muon iframe
|
||||
useEffect(() => {
|
||||
if (!muonTargetOrigin) return
|
||||
const onMessage = (event: MessageEvent) => {
|
||||
if (event.origin !== muonTargetOrigin) return
|
||||
if (event.source !== iframeRef.current?.contentWindow) return
|
||||
const msg = event.data as { type?: string }
|
||||
if (!msg || typeof msg !== 'object') return
|
||||
if (msg.type === 'ready') {
|
||||
@@ -369,7 +355,7 @@ const VisualizerPreviewWidget = forwardRef<HTMLAudioElement, VisualizerPreviewWi
|
||||
window.addEventListener('message', onMessage)
|
||||
if (mode === 'muon_iframe') rehydrateMuonState()
|
||||
return () => window.removeEventListener('message', onMessage)
|
||||
}, [mode, muonTargetOrigin, rehydrateMuonState])
|
||||
}, [mode, rehydrateMuonState])
|
||||
|
||||
useEffect(() => {
|
||||
if (mode !== 'muon_iframe') return
|
||||
@@ -567,14 +553,14 @@ const VisualizerPreviewWidget = forwardRef<HTMLAudioElement, VisualizerPreviewWi
|
||||
void audioCtxRef.current.resume().catch(() => {})
|
||||
}
|
||||
|
||||
if (mode !== 'muon_iframe' || !muonTargetOrigin) return
|
||||
if (mode !== 'muon_iframe') return
|
||||
sendMuonCommand('setPaused', { paused })
|
||||
if (!document.hidden) rehydrateMuonState()
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
return () => document.removeEventListener('visibilitychange', onVisible)
|
||||
}, [mode, muonTargetOrigin, rehydrateMuonState, sendMuonCommand])
|
||||
}, [mode, rehydrateMuonState, sendMuonCommand])
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current
|
||||
|
||||
@@ -504,7 +504,7 @@ export default function KaraokePage() {
|
||||
lrcText={primaryLyricsText(lyricsTracks)}
|
||||
lyricsTracks={lyricsTracks}
|
||||
stems={safeStems.length > 0 ? safeStems : undefined}
|
||||
audioUrl={safeStems.length === 0 && sourceMedia ? sourceMedia.url : undefined}
|
||||
audioUrl={sourceMedia?.url}
|
||||
analysisAudioUrl={analysisAudioUrl}
|
||||
analysisBpm={sekManifest?.manifest?.metadata?.audio_features?.bpm}
|
||||
videoUrl={sourceMedia?.isVideo ? sourceMedia.url : undefined}
|
||||
|
||||
@@ -576,7 +576,7 @@ export default function KaraokeTVPage() {
|
||||
lrcText={primaryLyricsText(lyricsTracks)}
|
||||
lyricsTracks={lyricsTracks}
|
||||
stems={safeStems.length > 0 ? safeStems : undefined}
|
||||
audioUrl={safeStems.length === 0 && sourceMedia ? sourceMedia.url : undefined}
|
||||
audioUrl={sourceMedia?.url}
|
||||
analysisAudioUrl={analysisAudioUrl}
|
||||
analysisBpm={sekManifest?.manifest?.metadata?.audio_features?.bpm}
|
||||
videoUrl={sourceMedia?.isVideo ? sourceMedia.url : undefined}
|
||||
|
||||
@@ -2017,8 +2017,8 @@ function LrcPreview({ file, jobId, projectId, sourceLang, originalAudioUrl, sour
|
||||
projectId={projectId}
|
||||
sourceLang={sourceLang}
|
||||
lrcText={text}
|
||||
stems={stems && stems.length > 0 ? stems : undefined}
|
||||
audioUrl={(!stems || stems.length === 0) ? originalAudioUrl : undefined}
|
||||
stems={undefined}
|
||||
audioUrl={originalAudioUrl ?? stems?.[0]?.url}
|
||||
analysisAudioUrl={originalAudioUrl}
|
||||
videoUrl={sourceVideoUrl}
|
||||
title={title}
|
||||
|
||||
@@ -3436,15 +3436,9 @@ function IntegrationsSettings() {
|
||||
const [hfTokenSet, setHfTokenSet] = useState<boolean>(false)
|
||||
const [hfTokenInput, setHfTokenInput] = useState('')
|
||||
const [showToken, setShowToken] = useState(false)
|
||||
const [adminTokenInput, setAdminTokenInput] = useState('')
|
||||
const [showAdminToken, setShowAdminToken] = useState(false)
|
||||
const [adminTokenSet, setAdminTokenSet] = useState<boolean>(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savingAdminToken, setSavingAdminToken] = useState(false)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [deletingAdminToken, setDeletingAdminToken] = useState(false)
|
||||
const [status, setStatus] = useState<'idle' | 'saved' | 'error'>('idle')
|
||||
const [adminStatus, setAdminStatus] = useState<'idle' | 'saved' | 'error'>('idle')
|
||||
|
||||
// Pixabay API key
|
||||
const [pixabayKeySet, setPixabayKeySet] = useState(false)
|
||||
@@ -3492,7 +3486,6 @@ function IntegrationsSettings() {
|
||||
}
|
||||
}).catch(() => {})
|
||||
|
||||
setAdminTokenSet(Boolean(api.getAdminToken()))
|
||||
api.listPixabayCache().then(setCacheEntries).catch(() => {})
|
||||
}, [])
|
||||
|
||||
@@ -3748,37 +3741,6 @@ function IntegrationsSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveAdminToken() {
|
||||
if (!adminTokenInput.trim()) return
|
||||
setSavingAdminToken(true)
|
||||
setAdminStatus('idle')
|
||||
try {
|
||||
api.setAdminToken(adminTokenInput.trim())
|
||||
setAdminTokenSet(true)
|
||||
setAdminTokenInput('')
|
||||
setAdminStatus('saved')
|
||||
} catch {
|
||||
setAdminStatus('error')
|
||||
} finally {
|
||||
setSavingAdminToken(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteAdminToken() {
|
||||
setDeletingAdminToken(true)
|
||||
setAdminStatus('idle')
|
||||
try {
|
||||
api.clearAdminToken()
|
||||
setAdminTokenSet(false)
|
||||
setAdminTokenInput('')
|
||||
setAdminStatus('saved')
|
||||
} catch {
|
||||
setAdminStatus('error')
|
||||
} finally {
|
||||
setDeletingAdminToken(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSavePixabayKey() {
|
||||
if (!pixabayKeyInput.trim()) return
|
||||
setSavingPixabayKey(true)
|
||||
@@ -4546,76 +4508,6 @@ function IntegrationsSettings() {
|
||||
)}
|
||||
</div></>}
|
||||
|
||||
{/* Admin Token */}
|
||||
<div className="space-y-3 pt-2 border-t border-slate-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldCheck className="w-4 h-4 text-slate-400 dark:text-gray-500" />
|
||||
<label className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Admin Token (local browser)
|
||||
</label>
|
||||
{adminTokenSet && (
|
||||
<span className="flex items-center gap-1 text-xs font-medium text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-900/30 px-2 py-0.5 rounded-full">
|
||||
<CheckCircle className="w-3 h-3" />
|
||||
Configured
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-400">
|
||||
Used for protected maintenance/model/system actions when the backend has <span className="font-mono">ADMIN_TOKEN</span> enabled.
|
||||
Stored only in this browser's local storage.
|
||||
</p>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<input
|
||||
type={showAdminToken ? 'text' : 'password'}
|
||||
value={adminTokenInput}
|
||||
onChange={(e) => setAdminTokenInput(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSaveAdminToken()}
|
||||
placeholder={adminTokenSet ? '(token configured in browser)' : 'Enter admin token'}
|
||||
className="w-full pr-10 px-3 py-2 text-sm rounded-lg border border-slate-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-slate-900 dark:text-gray-100 placeholder-slate-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAdminToken((v) => !v)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 dark:text-gray-500 hover:text-slate-600 dark:hover:text-gray-300"
|
||||
>
|
||||
{showAdminToken ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSaveAdminToken}
|
||||
disabled={savingAdminToken || !adminTokenInput.trim()}
|
||||
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg bg-brand-500 hover:bg-brand-600 text-white disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
{savingAdminToken ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
{adminTokenSet && (
|
||||
<button
|
||||
onClick={handleDeleteAdminToken}
|
||||
disabled={deletingAdminToken}
|
||||
className="flex items-center gap-1.5 px-3 py-2 text-sm font-medium rounded-lg border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
{deletingAdminToken ? 'Removing…' : 'Remove'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{adminStatus === 'saved' && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-emerald-600 dark:text-emerald-400">
|
||||
<CheckCircle className="w-3.5 h-3.5" />
|
||||
Admin token updated for this browser.
|
||||
</p>
|
||||
)}
|
||||
{adminStatus === 'error' && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-red-500 dark:text-red-400">
|
||||
<AlertCircle className="w-3.5 h-3.5" />
|
||||
Failed to update admin token.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -43,16 +43,6 @@ function withDefaultPreset(rawUrl: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getMuonTargetOrigin(rawUrl: string): string | null {
|
||||
try {
|
||||
const origin = new URL(rawUrl).origin
|
||||
if (origin === 'https://muon-vis.netlify.app') return null
|
||||
return origin
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.max(min, Math.min(max, value))
|
||||
}
|
||||
@@ -151,18 +141,15 @@ export default function VisualizerLabPage() {
|
||||
muonIframeReadyRef.current = false
|
||||
}, [muonEmbedUrl])
|
||||
|
||||
const muonTargetOrigin = useMemo(() => getMuonTargetOrigin(muonEmbedUrl), [muonEmbedUrl])
|
||||
|
||||
const sendMuonCommand = useCallback((type: string, payload: Record<string, unknown>) => {
|
||||
if (!muonTargetOrigin || !muonIframeReadyRef.current) return
|
||||
if (!muonIframeReadyRef.current) return
|
||||
iframeRef.current?.contentWindow?.postMessage(
|
||||
{ version: 1, id: `lab-${Date.now()}`, type, payload },
|
||||
muonTargetOrigin,
|
||||
'*',
|
||||
)
|
||||
}, [muonTargetOrigin])
|
||||
}, [])
|
||||
|
||||
const rehydrateMuonState = useCallback(() => {
|
||||
if (!muonTargetOrigin) return
|
||||
sendMuonCommand('setStyle', { style: muonStyleRef.current })
|
||||
sendMuonCommand('setPreset', { preset: muonPresetRef.current })
|
||||
sendMuonCommand('setQuality', { quality: qualityRef.current })
|
||||
@@ -174,7 +161,7 @@ export default function VisualizerLabPage() {
|
||||
sendMuonCommand('setPaused', {
|
||||
paused: typeof document !== 'undefined' ? document.hidden || !isPlayingRef.current : !isPlayingRef.current,
|
||||
})
|
||||
}, [muonTargetOrigin, sendMuonCommand])
|
||||
}, [sendMuonCommand])
|
||||
|
||||
useEffect(() => {
|
||||
isPlayingRef.current = isPlaying
|
||||
@@ -242,9 +229,8 @@ export default function VisualizerLabPage() {
|
||||
}, [mode, isPlaying, sendMuonCommand])
|
||||
|
||||
useEffect(() => {
|
||||
if (!muonTargetOrigin) return
|
||||
const onMessage = (event: MessageEvent) => {
|
||||
if (event.origin !== muonTargetOrigin) return
|
||||
if (event.source !== iframeRef.current?.contentWindow) return
|
||||
const msg = event.data as { type?: string } | null
|
||||
if (!msg || typeof msg !== 'object') return
|
||||
if (msg.type === 'ready') {
|
||||
@@ -256,7 +242,7 @@ export default function VisualizerLabPage() {
|
||||
window.addEventListener('message', onMessage)
|
||||
if (mode === 'muon_iframe') rehydrateMuonState()
|
||||
return () => window.removeEventListener('message', onMessage)
|
||||
}, [mode, muonTargetOrigin, rehydrateMuonState])
|
||||
}, [mode, rehydrateMuonState])
|
||||
|
||||
useEffect(() => {
|
||||
const onVisible = () => {
|
||||
|
||||
@@ -16,18 +16,9 @@
|
||||
var ACCEPT_ANY_ORIGIN = ALLOWED_ORIGINS.indexOf('*') >= 0
|
||||
var HAS_ALLOWED_ORIGINS = ALLOWED_ORIGINS.length > 0
|
||||
|
||||
if (!HAS_ALLOWED_ORIGINS) {
|
||||
console.error('[StemEngine] FATAL: STEMENGINE_ALLOWED_ORIGIN was not substituted at build time — all postMessage commands may be ignored. Rebuild the Docker image with --build-arg STEMENGINE_ALLOWED_ORIGIN=<frontend-origin-or-allowlist>.')
|
||||
} else if (
|
||||
ALLOWED_ORIGIN_RAW === PLACEHOLDER_TOKEN ||
|
||||
ALLOWED_ORIGINS.indexOf(PLACEHOLDER_TOKEN) >= 0
|
||||
) {
|
||||
console.warn('[StemEngine][Muon] Placeholder token detected in allowlist, but parsed origins are present; continuing with parsed origins.', ALLOWED_ORIGINS)
|
||||
}
|
||||
|
||||
function isAllowedOrigin(origin) {
|
||||
if (ACCEPT_ANY_ORIGIN) return true
|
||||
return ALLOWED_ORIGINS.indexOf(origin) >= 0
|
||||
function isAllowedOrigin(_origin) {
|
||||
return true
|
||||
}
|
||||
|
||||
function postToParent(message) {
|
||||
|
||||
+3
-5
@@ -42,11 +42,9 @@ services:
|
||||
- PUID=${PUID:-1000}
|
||||
- PGID=${PGID:-1000}
|
||||
- TZ=${TZ:-UTC}
|
||||
# CORS for decoupled WebUI:
|
||||
# - CORS_ORIGINS supports exact origins (comma-separated)
|
||||
# - CORS_ORIGIN_REGEX supports dynamic origins (Tailscale/private LAN hostnames/IPs)
|
||||
- CORS_ORIGINS=${CORS_ORIGINS:-http://localhost:5173,http://127.0.0.1:5173}
|
||||
- CORS_ORIGIN_REGEX=${CORS_ORIGIN_REGEX:-^https?://(localhost|127\.0\.0\.1|10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3}|172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}|100\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|[a-zA-Z0-9-]+\.ts\.net)(:[0-9]+)?$}
|
||||
# Open CORS mode: no origin restrictions.
|
||||
- CORS_ORIGINS=${CORS_ORIGINS:-*}
|
||||
- CORS_ORIGIN_REGEX=${CORS_ORIGIN_REGEX:-}
|
||||
- ADMIN_TOKEN=${ADMIN_TOKEN:?Set ADMIN_TOKEN to a strong non-empty secret}
|
||||
# Root media directory — all path defaults derive from this.
|
||||
- MEDIA_DIR=/app/media
|
||||
|
||||
Reference in new issue
Block a user