ChatGPT commited on
Commit
ce84147
·
1 Parent(s): 7f1f066

fix: surface api errors and coerce params

Browse files
README.md CHANGED
@@ -42,6 +42,7 @@ Implemented:
42
  - Clean, fixed, non-scrolling workstation UI: explicit top-bar upload button, whole-app drag/drop overlay, collapsed left/right/bottom tool panels by default, large center waveform/sample workspace, bottom dock for review/edit tools, and an explicit Start here flow.
43
  - Immediate browser-side waveform rendering on file selection, before backend extraction starts.
44
  - Waveform-based real progress visualization during extraction using backend `progress` events; no ETA or time-progress guessing.
 
45
  - Supervision UI:
46
  - selected-hit actions,
47
  - move hit to cluster,
@@ -78,6 +79,7 @@ See:
78
  - `docs/REPRODUCED_AUDIO_AND_PARAMETERS.md`
79
  - `docs/CLEAN_DEFAULT_UI.md`
80
  - `docs/IMMEDIATE_WAVEFORM_AND_REAL_PROGRESS.md`
 
81
 
82
  ## Run locally
83
 
@@ -106,6 +108,7 @@ python3 scripts/test_sse_and_review_hits.py
106
  python3 scripts/test_interactive_supervision.py
107
  python3 scripts/test_supervised_export_and_force_onset.py
108
  python3 scripts/test_progress_contract.py
 
109
  ```
110
 
111
  ## Run benchmarks
@@ -165,6 +168,7 @@ curl http://127.0.0.1:7860/api/jobs
165
  | `scripts/benchmark_subprocesses.py` | Synthetic benchmark runner for stage timings |
166
  | `scripts/test_interactive_supervision.py` | Smoke test for supervised state endpoints |
167
  | `scripts/test_supervised_export_and_force_onset.py` | Smoke test for force-onset, restore, suggestion diffs, and edited exports |
 
168
  | `docs/interactive-ux/` | Supplied interactive UX docs aligned to current implementation |
169
  | `docs/` | Review, timing, API, UI, feature, task, progress, and remaining-work documentation |
170
  | `legacy/` | Previous Gradio apps retained for reference |
 
42
  - Clean, fixed, non-scrolling workstation UI: explicit top-bar upload button, whole-app drag/drop overlay, collapsed left/right/bottom tool panels by default, large center waveform/sample workspace, bottom dock for review/edit tools, and an explicit Start here flow.
43
  - Immediate browser-side waveform rendering on file selection, before backend extraction starts.
44
  - Waveform-based real progress visualization during extraction using backend `progress` events; no ETA or time-progress guessing.
45
+ - Visible API/runtime error banner in the UI, plus backend coercion for browser-form parameter values such as `subdivision="16"`.
46
  - Supervision UI:
47
  - selected-hit actions,
48
  - move hit to cluster,
 
79
  - `docs/REPRODUCED_AUDIO_AND_PARAMETERS.md`
80
  - `docs/CLEAN_DEFAULT_UI.md`
81
  - `docs/IMMEDIATE_WAVEFORM_AND_REAL_PROGRESS.md`
82
+ - `docs/API_ERRORS_AND_PARAMETER_VALIDATION.md`
83
 
84
  ## Run locally
85
 
 
108
  python3 scripts/test_interactive_supervision.py
109
  python3 scripts/test_supervised_export_and_force_onset.py
110
  python3 scripts/test_progress_contract.py
111
+ python3 scripts/test_param_validation_and_api_errors.py
112
  ```
113
 
114
  ## Run benchmarks
 
168
  | `scripts/benchmark_subprocesses.py` | Synthetic benchmark runner for stage timings |
169
  | `scripts/test_interactive_supervision.py` | Smoke test for supervised state endpoints |
170
  | `scripts/test_supervised_export_and_force_onset.py` | Smoke test for force-onset, restore, suggestion diffs, and edited exports |
171
+ | `scripts/test_param_validation_and_api_errors.py` | Regression test for browser-style parameter coercion and visible API error details |
172
  | `docs/interactive-ux/` | Supplied interactive UX docs aligned to current implementation |
173
  | `docs/` | Review, timing, API, UI, feature, task, progress, and remaining-work documentation |
174
  | `legacy/` | Previous Gradio apps retained for reference |
app.py CHANGED
@@ -48,7 +48,7 @@ WEB_DIR = ROOT / "web"
48
  RUNS_DIR = ROOT / ".runs"
49
  RUNS_DIR.mkdir(exist_ok=True)
50
 
51
- app = FastAPI(title="Drum Sample Extractor", version="14.0.0")
52
  app.add_middleware(
53
  CORSMiddleware,
54
  allow_origins=["*"],
@@ -271,8 +271,12 @@ async def create_job(file: UploadFile = File(...), params: str = Form("{}")) ->
271
  try:
272
  parsed_params = json.loads(params)
273
  validated = PipelineParams.from_mapping(parsed_params)
 
 
 
 
274
  except Exception as exc:
275
- raise HTTPException(status_code=400, detail=str(exc)) from exc
276
 
277
  job_id = uuid.uuid4().hex[:12]
278
  job_dir = RUNS_DIR / job_id
 
48
  RUNS_DIR = ROOT / ".runs"
49
  RUNS_DIR.mkdir(exist_ok=True)
50
 
51
+ app = FastAPI(title="Drum Sample Extractor", version="14.1.0")
52
  app.add_middleware(
53
  CORSMiddleware,
54
  allow_origins=["*"],
 
271
  try:
272
  parsed_params = json.loads(params)
273
  validated = PipelineParams.from_mapping(parsed_params)
274
+ except json.JSONDecodeError as exc:
275
+ raise HTTPException(status_code=400, detail=f"Invalid params JSON: {exc.msg}") from exc
276
+ except ValueError as exc:
277
+ raise HTTPException(status_code=400, detail=f"Invalid extraction parameter: {exc}") from exc
278
  except Exception as exc:
279
+ raise HTTPException(status_code=400, detail=f"Invalid extraction request: {exc}") from exc
280
 
281
  job_id = uuid.uuid4().hex[:12]
282
  job_dir = RUNS_DIR / job_id
docs/API.md CHANGED
@@ -75,6 +75,8 @@ Response:
75
 
76
  Creates an extraction job.
77
 
 
 
78
  Content type: `multipart/form-data`
79
 
80
  Fields:
@@ -94,6 +96,12 @@ curl -F 'file=@song.wav' \
94
 
95
  Response status: `202 Accepted`
96
 
 
 
 
 
 
 
97
  ```json
98
  {
99
  "id": "58ca0db4ac74",
 
75
 
76
  Creates an extraction job.
77
 
78
+ The endpoint accepts browser-form-style JSON values for numeric and boolean params. For example, `{ "subdivision": "16" }` is coerced to integer `16` before validation. Invalid values return `400` with an actionable `detail` message suitable for direct UI display.
79
+
80
  Content type: `multipart/form-data`
81
 
82
  Fields:
 
96
 
97
  Response status: `202 Accepted`
98
 
99
+ Invalid params response example:
100
+
101
+ ```json
102
+ {"detail":"Invalid extraction parameter: subdivision must be one of 4, 8, 16, 32, 64"}
103
+ ```
104
+
105
  ```json
106
  {
107
  "id": "58ca0db4ac74",
docs/API_ERRORS_AND_PARAMETER_VALIDATION.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # API errors and parameter validation
2
+
3
+ Last updated: 2026-05-12
4
+
5
+ ## Purpose
6
+
7
+ Failed extraction requests must be visible in the application UI. Users should not need to open the browser network monitor to understand why a job did not start.
8
+
9
+ ## Implemented behavior
10
+
11
+ - `POST /api/jobs` now accepts browser-form-style parameter values for numeric and boolean fields.
12
+ - Example: the MIDI grid selector sends `"16"`; the backend coerces it to integer `16` before validation.
13
+ - Integer fields: `demucs_shifts`, `target_min`, `target_max`, `subdivision`.
14
+ - Float fields: Demucs overlap, onset, duration, clustering, and threshold controls.
15
+ - Boolean fields: `synthesize`, `quantize_midi`, `use_disk_cache`.
16
+ - Invalid request bodies return actionable `400` errors prefixed with `Invalid extraction parameter:` or `Invalid params JSON:`.
17
+ - The frontend has a global visible error banner for failed API/network requests.
18
+ - Pipeline runtime errors also surface in the banner and remain available in the Pipeline panel logs.
19
+ - The extraction start path writes failed-request details into `resultSummary` and `logs` so the error is visible even if the banner is dismissed.
20
+
21
+ ## Regression fixed
22
+
23
+ The UI sent the `subdivision` selector value as a string. The backend previously validated it directly against `{4, 8, 16, 32, 64}`, so `"16"` failed with:
24
+
25
+ ```json
26
+ {"detail":"subdivision must be one of 4, 8, 16, 32, 64"}
27
+ ```
28
+
29
+ That is now fixed in both places:
30
+
31
+ 1. `web/app.js` converts controls based on the `/api/config` default parameter types.
32
+ 2. `pipeline_runner.PipelineParams.from_mapping()` coerces JSON/form values defensively before validation.
33
+
34
+ ## Validation
35
+
36
+ Run:
37
+
38
+ ```bash
39
+ python3 scripts/test_param_validation_and_api_errors.py
40
+ ```
41
+
42
+ This verifies:
43
+
44
+ - browser-style string values are accepted and coerced;
45
+ - invalid subdivisions still fail;
46
+ - `/api/jobs` accepts a string `subdivision` from the UI;
47
+ - bad parameter responses include visible actionable details.
docs/FEATURES.md CHANGED
@@ -17,12 +17,13 @@ Turn an input audio file into a practical drum sample pack: detected hits, group
17
  | UI | Minimal custom transport | Implemented | One play/time/progress row can audition Source, Stem, or Reproduced previews; completed runs default to Reproduced. |
18
  | UI | Common vs advanced parameters | Implemented | Default view shows stem, sensitivity, group count, and two presets; helper copy and advanced model/DSP/export controls stay hidden until the user opens the relevant panel. |
19
  | UI | Streaming progress | Implemented | Uses `EventSource` over `GET /api/jobs/{id}/events`, with polling fallback. |
 
20
  | UI | Waveform/onset overview | Implemented | Canvas envelope plus clickable onset markers from `manifest.json`. |
21
  | UI | Result downloads | Implemented | ZIP, MIDI, stem WAV, reconstruction WAV, individual sample WAVs, and per-hit review WAVs. |
22
  | UI | Run history browser | Implemented | Lists completed `.runs/*/output/manifest.json` entries and reloads results. |
23
  | UI | Hit and sample audition | Implemented | Click-to-audition via hidden audio elements keeps the default screen clean. |
24
  | API | Health/config | Implemented | `GET /api/health`, `GET /api/config`. |
25
- | API | Job creation/status | Implemented | `POST /api/jobs`, `GET /api/jobs/{id}`. |
26
  | API | SSE job events | Implemented | `GET /api/jobs/{id}/events` streams job snapshots until complete/error. |
27
  | API | Run listing | Implemented | `GET /api/jobs` returns active and completed runs. |
28
  | API | Safe artifact serving | Implemented | Path traversal is blocked by resolved output-root checks. |
 
17
  | UI | Minimal custom transport | Implemented | One play/time/progress row can audition Source, Stem, or Reproduced previews; completed runs default to Reproduced. |
18
  | UI | Common vs advanced parameters | Implemented | Default view shows stem, sensitivity, group count, and two presets; helper copy and advanced model/DSP/export controls stay hidden until the user opens the relevant panel. |
19
  | UI | Streaming progress | Implemented | Uses `EventSource` over `GET /api/jobs/{id}/events`, with polling fallback. |
20
+ | UI | Visible request/runtime errors | Implemented | Failed API requests and pipeline errors appear in a global error banner and are also written to summary/log panels. |
21
  | UI | Waveform/onset overview | Implemented | Canvas envelope plus clickable onset markers from `manifest.json`. |
22
  | UI | Result downloads | Implemented | ZIP, MIDI, stem WAV, reconstruction WAV, individual sample WAVs, and per-hit review WAVs. |
23
  | UI | Run history browser | Implemented | Lists completed `.runs/*/output/manifest.json` entries and reloads results. |
24
  | UI | Hit and sample audition | Implemented | Click-to-audition via hidden audio elements keeps the default screen clean. |
25
  | API | Health/config | Implemented | `GET /api/health`, `GET /api/config`. |
26
+ | API | Job creation/status | Implemented | `POST /api/jobs`, `GET /api/jobs/{id}`. Browser-style string params are coerced before validation. |
27
  | API | SSE job events | Implemented | `GET /api/jobs/{id}/events` streams job snapshots until complete/error. |
28
  | API | Run listing | Implemented | `GET /api/jobs` returns active and completed runs. |
29
  | API | Safe artifact serving | Implemented | Path traversal is blocked by resolved output-root checks. |
docs/PROGRESS.md CHANGED
@@ -318,3 +318,22 @@ Completed in this pass:
318
  Outcome:
319
 
320
  The app now starts with a clear sequence instead of a blank workstation. Uploading or dropping a file immediately produces a waveform, and extraction progress is visualized directly on that waveform using backend-reported progress only. The UI does not fake ETA or time-based progress; non-instrumented stages step only at real boundaries.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  Outcome:
319
 
320
  The app now starts with a clear sequence instead of a blank workstation. Uploading or dropping a file immediately produces a waveform, and extraction progress is visualized directly on that waveform using backend-reported progress only. The UI does not fake ETA or time-based progress; non-instrumented stages step only at real boundaries.
321
+
322
+ ## 2026-05-12 — API validation and visible error pass
323
+
324
+ Completed:
325
+
326
+ - Fixed a real `/api/jobs` regression where the UI submitted `subdivision` as a string and the backend rejected it with `400`.
327
+ - Added backend parameter coercion before validation for integer, float, and boolean pipeline params.
328
+ - Updated frontend `collectParams()` to use `/api/config.defaults` as the type source for controls, including `<select>` elements.
329
+ - Added a global error banner so failed API requests and pipeline errors are visible without browser devtools.
330
+ - Removed a duplicate `historyList` id in the HTML.
331
+ - Added `docs/API_ERRORS_AND_PARAMETER_VALIDATION.md` and `scripts/test_param_validation_and_api_errors.py`.
332
+
333
+ Validation:
334
+
335
+ ```bash
336
+ python3 scripts/test_param_validation_and_api_errors.py
337
+ node --check web/app.js
338
+ python3 -m py_compile app.py pipeline_runner.py sample_extractor.py supervised_state.py supervised_export.py scripts/*.py
339
+ ```
docs/REMAINING_WORK.md CHANGED
@@ -6,6 +6,8 @@ Last updated: 2026-05-12
6
 
7
  The project is now a usable extraction workstation, not a complete interactive sample editor. The largest remaining gaps are UX/editor capabilities rather than core batch extraction.
8
 
 
 
9
  ## Highest-priority remaining gaps
10
 
11
  Completed since the previous snapshot: reproduced audio now incorporates non-target context stems, and common/advanced parameters are separated in the right sidebar.
 
6
 
7
  The project is now a usable extraction workstation, not a complete interactive sample editor. The largest remaining gaps are UX/editor capabilities rather than core batch extraction.
8
 
9
+ Failed API requests are now visible in the UI, and browser-style parameter values are coerced before backend validation.
10
+
11
  ## Highest-priority remaining gaps
12
 
13
  Completed since the previous snapshot: reproduced audio now incorporates non-target context stems, and common/advanced parameters are separated in the right sidebar.
docs/TASKS.md CHANGED
@@ -2,6 +2,16 @@
2
 
3
  Last updated: 2026-05-12
4
 
 
 
 
 
 
 
 
 
 
 
5
  ## User-requested tasks
6
 
7
  | Task | Status | Evidence |
 
2
 
3
  Last updated: 2026-05-12
4
 
5
+ ## Completed in current pass: API validation and visible errors
6
+
7
+ - [x] Fix `/api/jobs` rejecting UI-submitted `subdivision` values such as `"16"`.
8
+ - [x] Add defensive backend coercion for integer, float, and boolean pipeline parameters.
9
+ - [x] Convert frontend control values according to `/api/config.defaults` before submitting jobs.
10
+ - [x] Add a global visible error banner for failed API/network requests.
11
+ - [x] Surface extraction-start failures in the summary and Pipeline log panels.
12
+ - [x] Add regression coverage in `scripts/test_param_validation_and_api_errors.py`.
13
+
14
+
15
  ## User-requested tasks
16
 
17
  | Task | Status | Evidence |
pipeline_runner.py CHANGED
@@ -71,7 +71,58 @@ class PipelineParams:
71
  unknown = sorted(set(data) - allowed)
72
  if unknown:
73
  raise ValueError(f"Unknown pipeline parameter(s): {', '.join(unknown)}")
74
- params = cls(**data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  params.validate()
76
  return params
77
 
 
71
  unknown = sorted(set(data) - allowed)
72
  if unknown:
73
  raise ValueError(f"Unknown pipeline parameter(s): {', '.join(unknown)}")
74
+
75
+ int_fields = {"demucs_shifts", "target_min", "target_max", "subdivision"}
76
+ float_fields = {
77
+ "demucs_overlap",
78
+ "onset_delta",
79
+ "energy_threshold_db",
80
+ "pre_pad",
81
+ "min_dur",
82
+ "max_dur",
83
+ "min_gap",
84
+ "ncc_threshold",
85
+ "attack_ms",
86
+ "mel_threshold",
87
+ }
88
+ bool_fields = {"synthesize", "quantize_midi", "use_disk_cache"}
89
+
90
+ def coerce_bool(name: str, value: Any) -> bool:
91
+ if isinstance(value, bool):
92
+ return value
93
+ if isinstance(value, (int, float)) and value in {0, 1}:
94
+ return bool(value)
95
+ if isinstance(value, str):
96
+ normalized = value.strip().lower()
97
+ if normalized in {"true", "1", "yes", "on"}:
98
+ return True
99
+ if normalized in {"false", "0", "no", "off"}:
100
+ return False
101
+ raise ValueError(f"{name} must be a boolean")
102
+
103
+ coerced: dict[str, Any] = {}
104
+ for name, value in data.items():
105
+ if value is None:
106
+ coerced[name] = value
107
+ elif name in int_fields:
108
+ try:
109
+ number = float(value) if isinstance(value, str) else value
110
+ if int(number) != number:
111
+ raise ValueError
112
+ coerced[name] = int(number)
113
+ except (TypeError, ValueError):
114
+ raise ValueError(f"{name} must be an integer") from None
115
+ elif name in float_fields:
116
+ try:
117
+ coerced[name] = float(value)
118
+ except (TypeError, ValueError):
119
+ raise ValueError(f"{name} must be a number") from None
120
+ elif name in bool_fields:
121
+ coerced[name] = coerce_bool(name, value)
122
+ else:
123
+ coerced[name] = value
124
+
125
+ params = cls(**coerced)
126
  params.validate()
127
  return params
128
 
scripts/test_param_validation_and_api_errors.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
7
+
8
+ import numpy as np
9
+ import soundfile as sf
10
+ from fastapi.testclient import TestClient
11
+
12
+ from app import app
13
+ from pipeline_runner import PipelineParams
14
+
15
+
16
+ def wav_bytes() -> io.BytesIO:
17
+ sr = 22050
18
+ t = np.arange(int(sr * 0.25)) / sr
19
+ y = 0.15 * np.sin(2 * np.pi * 220 * t) * np.exp(-t * 10)
20
+ buf = io.BytesIO()
21
+ sf.write(buf, y, sr, format="WAV")
22
+ buf.seek(0)
23
+ return buf
24
+
25
+
26
+ def test_mapping_coerces_browser_form_values() -> None:
27
+ params = PipelineParams.from_mapping({
28
+ "stem": "all",
29
+ "subdivision": "16",
30
+ "demucs_shifts": "0",
31
+ "demucs_overlap": "0.25",
32
+ "target_min": "2",
33
+ "target_max": "6",
34
+ "synthesize": "false",
35
+ "quantize_midi": "true",
36
+ "use_disk_cache": "1",
37
+ })
38
+ assert params.subdivision == 16
39
+ assert params.demucs_shifts == 0
40
+ assert params.demucs_overlap == 0.25
41
+ assert params.target_min == 2
42
+ assert params.target_max == 6
43
+ assert params.synthesize is False
44
+ assert params.quantize_midi is True
45
+ assert params.use_disk_cache is True
46
+
47
+
48
+ def test_invalid_subdivision_is_actionable() -> None:
49
+ try:
50
+ PipelineParams.from_mapping({"subdivision": "12"})
51
+ except ValueError as exc:
52
+ assert "subdivision must be one of 4, 8, 16, 32, 64" in str(exc)
53
+ else:
54
+ raise AssertionError("invalid subdivision was accepted")
55
+
56
+
57
+ def test_jobs_endpoint_accepts_string_subdivision_from_browser_select() -> None:
58
+ client = TestClient(app)
59
+ params = {
60
+ "stem": "all",
61
+ "subdivision": "16",
62
+ "demucs_shifts": "0",
63
+ "synthesize": "false",
64
+ "use_disk_cache": "false",
65
+ }
66
+ response = client.post(
67
+ "/api/jobs",
68
+ files={"file": ("tiny.wav", wav_bytes(), "audio/wav")},
69
+ data={"params": json.dumps(params)},
70
+ )
71
+ assert response.status_code == 202, response.text
72
+ payload = response.json()
73
+ assert payload["params"]["subdivision"] == 16
74
+ assert payload["params"]["demucs_shifts"] == 0
75
+ assert payload["params"]["synthesize"] is False
76
+ assert payload["params"]["use_disk_cache"] is False
77
+
78
+
79
+ def test_jobs_endpoint_reports_bad_parameter_as_visible_detail() -> None:
80
+ client = TestClient(app)
81
+ response = client.post(
82
+ "/api/jobs",
83
+ files={"file": ("tiny.wav", wav_bytes(), "audio/wav")},
84
+ data={"params": json.dumps({"subdivision": "12"})},
85
+ )
86
+ assert response.status_code == 400
87
+ payload = response.json()
88
+ assert "Invalid extraction parameter" in payload["detail"]
89
+ assert "subdivision must be one of 4, 8, 16, 32, 64" in payload["detail"]
90
+
91
+
92
+ if __name__ == "__main__":
93
+ test_mapping_coerces_browser_form_values()
94
+ test_invalid_subdivision_is_actionable()
95
+ test_jobs_endpoint_accepts_string_subdivision_from_browser_select()
96
+ test_jobs_endpoint_reports_bad_parameter_as_visible_detail()
97
+ print("parameter validation and API error visibility contract passed")
web/app.js CHANGED
@@ -40,6 +40,42 @@ function esc(value) {
40
  return String(value ?? "").replace(/[&<>'"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;" }[c]));
41
  }
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  function fmtSec(value) {
44
  if (value === null || value === undefined || Number.isNaN(Number(value))) return "—";
45
  const n = Number(value);
@@ -212,11 +248,32 @@ function setHealth(ok, text, subtext) {
212
  }
213
 
214
  async function api(path, options = {}) {
215
- const response = await fetch(path, options);
 
 
 
 
 
 
 
216
  if (!response.ok) {
217
- let detail = response.statusText;
218
- try { detail = (await response.json()).detail ?? detail; } catch {}
219
- throw new Error(detail);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  }
221
  return response.json();
222
  }
@@ -313,12 +370,21 @@ function updateStemOptions() {
313
 
314
  function collectParams() {
315
  const params = {};
 
316
  for (const field of fields) {
317
  const el = $(field);
318
  if (!el) continue;
319
- if (el.type === "checkbox") params[field] = el.checked;
320
- else if (["number", "range"].includes(el.type)) params[field] = Number(el.value);
321
- else params[field] = el.value;
 
 
 
 
 
 
 
 
322
  }
323
  return params;
324
  }
@@ -903,6 +969,7 @@ function renderJob(job) {
903
  if (job.status === "error") {
904
  $("resultSummary").textContent = `Extraction failed: ${job.error}`;
905
  $("logs").textContent = `${(job.logs ?? []).join("\n")}\n\n${job.traceback ?? ""}`;
 
906
  }
907
  }
908
 
@@ -1006,13 +1073,17 @@ async function runExtraction() {
1006
  form.append("file", selectedFile, selectedFile.name);
1007
  form.append("params", JSON.stringify(collectParams()));
1008
  try {
 
1009
  const job = await api("/api/jobs", { method: "POST", body: form });
1010
  renderJob(job);
1011
  await watchJob(job.id);
1012
  await refreshHistory();
1013
  } catch (error) {
1014
  $("runButton").disabled = false;
1015
- $("resultSummary").textContent = error.message;
 
 
 
1016
  }
1017
  }
1018
 
@@ -1032,6 +1103,7 @@ function clearRunViews() {
1032
  }
1033
 
1034
  function setFile(file) {
 
1035
  selectedFile = file;
1036
  clearRunViews();
1037
  $("dropTitle").textContent = file ? file.name : "Choose an audio file";
@@ -1094,9 +1166,11 @@ async function boot() {
1094
  setHealth(true, "Ready", "Backend online");
1095
  } catch (error) {
1096
  setHealth(false, "Offline", error.message);
 
1097
  }
1098
  }
1099
 
 
1100
  $("demucs_model").addEventListener("change", updateStemOptions);
1101
  $("fileInput").addEventListener("change", (event) => setFile(event.target.files?.[0] ?? null));
1102
  $("runButton").addEventListener("click", runExtraction);
 
40
  return String(value ?? "").replace(/[&<>'"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;" }[c]));
41
  }
42
 
43
+ class ApiRequestError extends Error {
44
+ constructor(message, meta = {}) {
45
+ super(message);
46
+ this.name = "ApiRequestError";
47
+ this.status = meta.status ?? null;
48
+ this.statusText = meta.statusText ?? "";
49
+ this.path = meta.path ?? "";
50
+ this.detail = meta.detail ?? null;
51
+ this.payload = meta.payload ?? null;
52
+ }
53
+ }
54
+
55
+ function stringifyErrorDetail(value) {
56
+ if (value === null || value === undefined || value === "") return "";
57
+ if (typeof value === "string") return value;
58
+ try { return JSON.stringify(value, null, 2); } catch { return String(value); }
59
+ }
60
+
61
+ function showError(title, error, detail = "") {
62
+ const banner = $("errorBanner");
63
+ if (!banner) return;
64
+ const message = error instanceof Error ? error.message : String(error ?? "Unknown error");
65
+ const status = error?.status ? `HTTP ${error.status}${error.statusText ? ` ${error.statusText}` : ""}` : "";
66
+ const path = error?.path ? ` · ${error.path}` : "";
67
+ const extra = stringifyErrorDetail(detail || error?.detail || error?.payload?.detail || "");
68
+ $("errorTitle").textContent = title || "Request failed";
69
+ $("errorMessage").textContent = message;
70
+ $("errorDetail").textContent = [status + path, extra].filter(Boolean).join(" — ");
71
+ banner.hidden = false;
72
+ }
73
+
74
+ function clearError() {
75
+ const banner = $("errorBanner");
76
+ if (banner) banner.hidden = true;
77
+ }
78
+
79
  function fmtSec(value) {
80
  if (value === null || value === undefined || Number.isNaN(Number(value))) return "—";
81
  const n = Number(value);
 
248
  }
249
 
250
  async function api(path, options = {}) {
251
+ let response;
252
+ try {
253
+ response = await fetch(path, options);
254
+ } catch (cause) {
255
+ const error = new ApiRequestError(cause?.message || "Network request failed", { path });
256
+ showError("Network request failed", error);
257
+ throw error;
258
+ }
259
  if (!response.ok) {
260
+ let payload = null;
261
+ let detail = response.statusText || `HTTP ${response.status}`;
262
+ try {
263
+ payload = await response.json();
264
+ detail = stringifyErrorDetail(payload.detail ?? payload.error ?? payload.message ?? detail);
265
+ } catch {
266
+ try { detail = await response.text(); } catch {}
267
+ }
268
+ const error = new ApiRequestError(detail, {
269
+ status: response.status,
270
+ statusText: response.statusText,
271
+ path,
272
+ detail,
273
+ payload,
274
+ });
275
+ showError("API request failed", error);
276
+ throw error;
277
  }
278
  return response.json();
279
  }
 
370
 
371
  function collectParams() {
372
  const params = {};
373
+ const defaults = config?.defaults ?? {};
374
  for (const field of fields) {
375
  const el = $(field);
376
  if (!el) continue;
377
+ const defaultValue = defaults[field];
378
+ if (el.type === "checkbox") {
379
+ params[field] = el.checked;
380
+ } else if (["number", "range"].includes(el.type) || typeof defaultValue === "number") {
381
+ const raw = String(el.value ?? "").trim();
382
+ params[field] = raw === "" && defaultValue !== undefined ? defaultValue : Number(raw);
383
+ } else if (typeof defaultValue === "boolean") {
384
+ params[field] = el.value === "true" || el.value === "1" || el.value === "on";
385
+ } else {
386
+ params[field] = el.value;
387
+ }
388
  }
389
  return params;
390
  }
 
969
  if (job.status === "error") {
970
  $("resultSummary").textContent = `Extraction failed: ${job.error}`;
971
  $("logs").textContent = `${(job.logs ?? []).join("\n")}\n\n${job.traceback ?? ""}`;
972
+ showError("Extraction failed", new Error(job.error || "Pipeline error"), job.traceback || "See the Pipeline panel for logs.");
973
  }
974
  }
975
 
 
1073
  form.append("file", selectedFile, selectedFile.name);
1074
  form.append("params", JSON.stringify(collectParams()));
1075
  try {
1076
+ clearError();
1077
  const job = await api("/api/jobs", { method: "POST", body: form });
1078
  renderJob(job);
1079
  await watchJob(job.id);
1080
  await refreshHistory();
1081
  } catch (error) {
1082
  $("runButton").disabled = false;
1083
+ $("jobPill").textContent = "error";
1084
+ $("resultSummary").textContent = `Extraction could not start: ${error.message}`;
1085
+ $("logs").textContent = `Request failed before the pipeline started.\n${error.message}`;
1086
+ showError("Extraction could not start", error, "Check the visible controls first; advanced parameters may also be invalid.");
1087
  }
1088
  }
1089
 
 
1103
  }
1104
 
1105
  function setFile(file) {
1106
+ clearError();
1107
  selectedFile = file;
1108
  clearRunViews();
1109
  $("dropTitle").textContent = file ? file.name : "Choose an audio file";
 
1166
  setHealth(true, "Ready", "Backend online");
1167
  } catch (error) {
1168
  setHealth(false, "Offline", error.message);
1169
+ showError("Backend unavailable", error, "Start the FastAPI server, then reload this page.");
1170
  }
1171
  }
1172
 
1173
+ $("dismissErrorButton").addEventListener("click", clearError);
1174
  $("demucs_model").addEventListener("change", updateStemOptions);
1175
  $("fileInput").addEventListener("change", (event) => setFile(event.target.files?.[0] ?? null));
1176
  $("runButton").addEventListener("click", runExtraction);
web/index.html CHANGED
@@ -14,6 +14,16 @@
14
  </div>
15
  </div>
16
 
 
 
 
 
 
 
 
 
 
 
17
  <div class="shell">
18
  <header class="topbar">
19
  <div class="app-title">
 
14
  </div>
15
  </div>
16
 
17
+
18
+ <div id="errorBanner" class="error-banner" role="alert" hidden>
19
+ <div class="error-copy">
20
+ <strong id="errorTitle">Request failed</strong>
21
+ <span id="errorMessage">Something went wrong.</span>
22
+ <small id="errorDetail"></small>
23
+ </div>
24
+ <button id="dismissErrorButton" class="error-dismiss" type="button" aria-label="Dismiss error">×</button>
25
+ </div>
26
+
27
  <div class="shell">
28
  <header class="topbar">
29
  <div class="app-title">
web/styles.css CHANGED
@@ -62,6 +62,41 @@ code { color: var(--accent-strong); }
62
  .global-drop-overlay strong { font-size: 26px; letter-spacing: -.035em; }
63
  .global-drop-overlay span { color: var(--muted); }
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  .shell {
66
  width: 100%;
67
  height: 100vh;
 
62
  .global-drop-overlay strong { font-size: 26px; letter-spacing: -.035em; }
63
  .global-drop-overlay span { color: var(--muted); }
64
 
65
+ .error-banner {
66
+ position: fixed;
67
+ top: 14px;
68
+ left: 50%;
69
+ z-index: 140;
70
+ width: min(760px, calc(100vw - 32px));
71
+ display: grid;
72
+ grid-template-columns: minmax(0, 1fr) auto;
73
+ align-items: start;
74
+ gap: 14px;
75
+ padding: 14px 14px 14px 16px;
76
+ border: 1px solid rgba(216, 88, 103, .34);
77
+ border-radius: 16px;
78
+ background: rgba(255, 248, 249, .97);
79
+ color: #7c202c;
80
+ box-shadow: 0 18px 44px rgba(126, 24, 42, .14);
81
+ transform: translateX(-50%);
82
+ }
83
+ .error-banner[hidden] { display: none; }
84
+ .error-copy { min-width: 0; display: grid; gap: 3px; }
85
+ .error-copy strong { font-size: 13px; letter-spacing: -.01em; }
86
+ .error-copy span { overflow-wrap: anywhere; font-size: 13px; line-height: 1.35; }
87
+ .error-copy small { overflow-wrap: anywhere; color: rgba(124, 32, 44, .72); line-height: 1.35; }
88
+ .error-dismiss {
89
+ width: 28px;
90
+ height: 28px;
91
+ border: 1px solid rgba(216, 88, 103, .26);
92
+ border-radius: 999px;
93
+ background: #fff;
94
+ color: #7c202c;
95
+ font-size: 18px;
96
+ line-height: 1;
97
+ }
98
+ .error-dismiss:hover { border-color: rgba(216, 88, 103, .52); }
99
+
100
  .shell {
101
  width: 100%;
102
  height: 100vh;