diff --git a/AGENTS.md b/AGENTS.md index b9a67ce17..f5267aee6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## Project overview -- BandScope is a local-first desktop app for rehearsal prep: a practical song view with likely harmony by section and by instrument or vocal role, form and groove cues, stems, playable ranges, simplification guidance, transposition or setup cues, part-overlap cues, visible confidence, and rehearsal priorities. +- BandScope is a local-first desktop app for rehearsal prep: a practical song view with likely harmony by section and by instrument or vocal role, form and groove cues, stems, playable ranges, simplification guidance, transposition or setup cues, part-overlap cues, visible confidence, and rehearsal priorities. Ranges names only playable spans and the next instrument check. The Player window names tonight's first map section to loop and does not claim audio playback. - Authoritative delivery rules live in `ARCHITECTURE.md`, `docs/plans/`, and the root verification scripts. - Brand, tone, UX copy, and prioritization rules live in `docs/brand-story.md` and must be applied to PRDs, TRDs, UI copy, onboarding, empty states, and error messages. - App security rules live in `docs/security/app-security.md` and must be applied to file handling, URL intake, subprocesses, IPC, WebView usage, model loading, updates, logging, cache handling, and export behavior. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ca0df5ac4..df97e7005 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -82,7 +82,8 @@ Last updated: 2026-03-11 - likely harmony by section and by role - section roadmap with entries, dropouts, pickups, stops, tags, and handoffs - groove and timing cues relevant to locking the band together - - playable ranges and density or overlap warnings, with the ready workspace naming tonight's first span and the next instrument check + - playable ranges and density or overlap warnings, with the ready workspace and Ranges board naming tonight's first span and the next instrument check + - a Player window that names tonight's first map section to loop and does not claim local-audio playback before the rehearsal-player core exists - simplification, transposition, capo, tuning, or setup cues where applicable - role-specific rehearsal priorities and confidence flags - cue-sheet or chart-style exports that summarize the analysis in rehearsal-friendly form diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b6f7e784..31e29432d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Added +- Name playable spans on the Ranges board and send the player to check those notes on their instrument. The Player window names tonight's first map section to loop and does not claim audio playback. - Name tonight's first playable range on the ready rehearsal map and tell the player to check that span on their instrument before the section. - Display the analyzed song tempo (BPM) as a badge in the rehearsal workspace. - 각 합주 역할(Role)별 개인 연습 진행도를 0~100% 범위로 기록 및 시각화할 수 있는 연습 진척도(`practiceProgress`) 트래커 기능 추가. UI 컨트롤(슬라이더 및 +/- 버튼)과 한/영 다국어 지원 포함. diff --git a/CLAUDE.md b/CLAUDE.md index b5a34c1fa..a15843cb2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ BandScope is a local-first desktop app for rehearsal prep: it turns a song into Three layers, decoupled through shared contracts: -- `apps/desktop` — Tauri 2 + Vite + React 19 shell (Tailwind 4, Base UI, Storybook). Feature screens live in `src/features/` (home, workspace, chords, ranges, player, settings). The ready workspace names tonight's first playable range and the next instrument check. `src/lib/analysis.ts` and `src/lib/job_runner.ts` call typed Tauri IPC commands, with a browser fallback that serves demo data when not running inside Tauri. +- `apps/desktop` — Tauri 2 + Vite + React 19 shell (Tailwind 4, Base UI, Storybook). Feature screens live in `src/features/` (home, workspace, chords, ranges, player, settings). The ready workspace names tonight's first playable range and the next instrument check. Ranges uses that same playable-span authority. The Player window names tonight's first map section to loop and does not claim audio playback. `src/lib/analysis.ts` and `src/lib/job_runner.ts` call typed Tauri IPC commands, with a browser fallback that serves demo data when not running inside Tauri. - `apps/desktop/src-tauri/src/main.rs` — the Rust orchestration boundary. Tauri commands (`start_analysis_job`, `get_analysis_job_status`, `select_local_audio_source`, `import_youtube_url`) validate untrusted input (project IDs, file paths, URLs) and spawn the Python engine as a subprocess. There is no loopback HTTP listener and no network path for local analysis. - `services/analysis-engine` — Python package `bandscope_analysis` (librosa/numpy). Entry point `cli.py` reads a JSON job request on stdin and prints a structured job-status JSON envelope on stdout (`--progress-jsonl` streams progress lines). `api.py` orchestrates the pipeline across the `separation`, `sections`, `roles`, `chords`, `ranges`, `temporal`, `transcription`, and `youtube` modules. diff --git a/apps/desktop/src/features/player/index.test.tsx b/apps/desktop/src/features/player/index.test.tsx new file mode 100644 index 000000000..eaa52e4d9 --- /dev/null +++ b/apps/desktop/src/features/player/index.test.tsx @@ -0,0 +1,120 @@ +import { render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it } from "vitest"; +import { PlayerFeature, firstNamedSection } from "./index"; + +const originalLanguage = navigator.language; + +/** Set the browser language used by locale detection for one test case. */ +function setNavigatorLanguage(language: string) { + Object.defineProperty(navigator, "language", { + configurable: true, + value: language + }); +} + +describe("firstNamedSection", () => { + it("returns the first labeled window with a forward time range", () => { + expect(firstNamedSection(createDemoRehearsalSong())).toEqual({ id: "verse-1", label: "verse" }); + }); + + it("skips blank labels and inverted windows", () => { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + song.sections = [ + { + ...verse, + id: " ", + label: "none", + timeRange: { start: 30, end: 10 } + }, + { + ...verse, + id: "chorus-1", + label: "chorus", + timeRange: { start: 30, end: 50 } + } + ]; + expect(firstNamedSection(song)).toEqual({ id: "chorus-1", label: "chorus" }); + }); + + it("rejects Proxy section data instead of trusting descriptor reads", () => { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + song.sections = [ + new Proxy(verse, { + get(target, property, receiver) { + if (property === "id") return "spoofed-section"; + if (property === "label") return "chorus"; + if (property === "timeRange") return { start: 90, end: 100 }; + return Reflect.get(target, property, receiver); + } + }) + ]; + + expect(firstNamedSection(song)).toBeNull(); + }); + + it("rejects Proxy descriptor traps before they can forge a loop", () => { + const song = createDemoRehearsalSong(); + const forged = new Proxy(song, { + getOwnPropertyDescriptor(target, property) { + if (property === "sections") { + return { + configurable: true, + enumerable: true, + value: [{ id: "spoofed", label: "spoofed", timeRange: { start: 1, end: 2 } }], + writable: true + }; + } + return Reflect.getOwnPropertyDescriptor(target, property); + } + }); + + expect(firstNamedSection(forged as RehearsalSong)).toBeNull(); + }); + + it("rejects malformed roots instead of inventing a loop", () => { + expect(firstNamedSection(null)).toBeNull(); + expect(firstNamedSection({ sections: "bad" } as never)).toBeNull(); + }); +}); + +describe("PlayerFeature", () => { + afterEach(() => { + setNavigatorLanguage(originalLanguage); + }); + + it("names the rehearsal map when no song is loaded", () => { + setNavigatorLanguage("en-US"); + render(); + expect( + screen.getByText( + "Open the rehearsal map and choose a song first. This window does not play audio yet." + ) + ).toBeTruthy(); + }); + + it("names tonight's first map section without claiming playback", () => { + setNavigatorLanguage("en-US"); + render(); + + const callout = screen.getByTestId("player-next-map-loop"); + expect(callout).toHaveTextContent("Tonight's first loop"); + expect(callout).toHaveTextContent( + "Tonight's first section is verse. Open that section on the rehearsal map to set tonight's loop." + ); + expect(callout).toHaveTextContent("This window does not play audio yet."); + expect(screen.getByTestId("player-song-title")).toHaveTextContent("Late Night Set"); + }); + + it("asks for a named window when no section can be looped", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + song.sections = []; + render(); + expect( + screen.getByText("Tonight's first section still needs a named window on the rehearsal map.") + ).toBeTruthy(); + }); +}); diff --git a/apps/desktop/src/features/player/index.tsx b/apps/desktop/src/features/player/index.tsx index 37bc12f71..a017ce01b 100644 --- a/apps/desktop/src/features/player/index.tsx +++ b/apps/desktop/src/features/player/index.tsx @@ -1,56 +1,100 @@ +import { useMemo } from "react"; import type { RehearsalSong } from "@bandscope/shared-types"; +import { createTranslator, detectPreferredLocale } from "../../i18n"; +import { + fillRangeCopy, + isSafeRuntimeValue, + meaningfulRangeText, + ownDataProperty +} from "../workspace/firstRangeSqueeze"; -/** Documented. */ +/** Tonight's first named section a player should loop from the rehearsal map. */ +export type FirstNamedSection = { + id: string; + label: string; +}; + +/** Return whether an untrusted runtime value is a non-array object record. */ +function isRuntimeObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** Pick the first named section window without treating malformed evidence as a loop. */ +export function firstNamedSection(song: RehearsalSong | null | undefined): FirstNamedSection | null { + const runtimeSong: unknown = song; + if (!isRuntimeObject(runtimeSong) || !isSafeRuntimeValue(runtimeSong)) { + return null; + } + const sections = ownDataProperty(runtimeSong, "sections"); + if (!Array.isArray(sections)) { + return null; + } + for (const sectionValue of sections) { + if (!isRuntimeObject(sectionValue)) { + continue; + } + const id = meaningfulRangeText(ownDataProperty(sectionValue, "id")); + const label = meaningfulRangeText(ownDataProperty(sectionValue, "label")); + if (!id || !label) { + continue; + } + const timeRange = ownDataProperty(sectionValue, "timeRange"); + if (!isRuntimeObject(timeRange)) { + continue; + } + const start = ownDataProperty(timeRange, "start"); + const end = ownDataProperty(timeRange, "end"); + if (typeof start !== "number" || typeof end !== "number" || !Number.isFinite(start) || !Number.isFinite(end) || end <= start) { + continue; + } + return { id, label }; + } + return null; +} + +/** Name the next map loop when this window cannot play local audio yet. */ export function PlayerFeature(props: { title: string; song?: RehearsalSong | null }) { const { title, song } = props; + const t = useMemo(() => createTranslator(detectPreferredLocale()), []); + const safeSong = useMemo( + () => (song && isSafeRuntimeValue(song) ? song : null), + [song], + ); + const namedSection = useMemo(() => firstNamedSection(safeSong), [safeSong]); + const songTitle = meaningfulRangeText( + isRuntimeObject(safeSong) ? ownDataProperty(safeSong, "title") : undefined + ); if (!song) { return ( -
-

{title}

-

No song loaded. Start an analysis to use the player.

+
+

{title}

+

{t("playerEmptyState")}

); } + const nextAction = namedSection + ? fillRangeCopy(t("playerMapLoopNextAction"), { sectionLabel: namedSection.label }) + : t("playerMissingSection"); + return ( -
-

{title}

-
+

{title}

+
-
- {song.title} - - {song.sections.length} {song.sections.length === 1 ? "section" : "sections"} - -
-
- {song.sections.map((section) => ( - - {section.label} - - ))} -
-
- Audio playback requires the desktop app with a local audio source. -
-
+

{t("playerNextMapLoopTitle")}

+

{nextAction}

+

{t("playerNoAudioYet")}

+
+ {namedSection && songTitle ? ( +

+ {songTitle} +

+ ) : null}
); } diff --git a/apps/desktop/src/features/ranges/index.test.tsx b/apps/desktop/src/features/ranges/index.test.tsx index 585c1f4af..0a2486b2c 100644 --- a/apps/desktop/src/features/ranges/index.test.tsx +++ b/apps/desktop/src/features/ranges/index.test.tsx @@ -1,88 +1,136 @@ import { render, screen } from "@testing-library/react"; -import { describe, it, expect } from "vitest"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it } from "vitest"; import { RangesFeature } from "./index"; -import type { RehearsalSong } from "@bandscope/shared-types"; - -const mockSong: RehearsalSong = { - id: "song-1", - title: "Test Song", - exportSummary: { format: "cue-sheet", headline: "Test Headline", focusSections: [] }, - sections: [ - { - id: "sec-1", - label: "chorus", - groove: "test groove", - timeRange: { start: 0, end: 10 }, - confidence: { level: "high", reason: "test" }, - partGraph: [], - roles: [ - { - id: "role-1", - name: "Test Role 1", - roleType: "instrument", - harmony: { chord: "Cmaj7", functionLabel: "Tonic", source: "model" }, - cue: { value: "test cue", anchor: "count", confidence: { level: "high", reason: "test" } }, - range: { lowestNote: "C4", highestNote: "C5" }, - confidence: { level: "high", reason: "test" }, - rehearsalPriority: "high", - simplification: "none", - setupNote: "none", - manualOverrides: [], - overlapWarnings: ["Clashing notes with Role 2"], - transcription: [ - { pitch: "C4", onset: 0, offset: 1, velocity: 100 }, - { pitch: "E4", onset: 1, offset: 2, velocity: 100 }, - ], - }, - { - id: "role-2", - name: "Test Role 2", - roleType: "instrument", - harmony: { chord: "Cmaj7", functionLabel: "Tonic", source: "model" }, - cue: { value: "test cue", anchor: "count", confidence: { level: "high", reason: "test" } }, - range: { lowestNote: "G4", highestNote: "G5" }, - confidence: { level: "high", reason: "test" }, - rehearsalPriority: "high", - simplification: "none", - setupNote: "none", - manualOverrides: [], - overlapWarnings: [], - // No transcription - }, - ], - }, - ], -}; + +const originalLanguage = navigator.language; + +/** Set the browser language used by locale detection for one test case. */ +function setNavigatorLanguage(language: string) { + Object.defineProperty(navigator, "language", { + configurable: true, + value: language + }); +} describe("RangesFeature", () => { - it("renders empty state without a song", () => { + afterEach(() => { + setNavigatorLanguage(originalLanguage); + }); + + it("names choosing a song first when Ranges has no analysis", () => { + setNavigatorLanguage("en-US"); render(); - expect(screen.getByText("No song loaded. Start an analysis to see range data.")).toBeInTheDocument(); + expect( + screen.getByText("Choose a song on the rehearsal map first. Ranges will name tonight's playable spans after analysis.") + ).toBeTruthy(); + }); + + it("names tonight's first playable span and the next instrument check", () => { + setNavigatorLanguage("en-US"); + render(); + + const callout = screen.getByTestId("ranges-first-span"); + expect(callout).toHaveTextContent("Tonight's first range"); + expect(callout).toHaveTextContent( + "Bass Guitar sits C#2–E3 in verse. Hear that clash on your instrument before the verse." + ); + expect(screen.getByTestId("range-card-0-bass-guitar-0")).toHaveTextContent("C#2 — E3"); + expect(screen.getByTestId("range-card-0-bass-guitar-0")).toHaveTextContent( + "Check this span on your instrument before verse." + ); + expect(screen.getByText("Density warning: competing with Keyboard Left Hand in low register.")).toBeTruthy(); + }); + + it("rejects an id-less role instead of presenting it as a playable card", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + song.sections[0]!.roles[0] = { + ...song.sections[0]!.roles[0]!, + id: " " + }; + + render(); + + expect(screen.queryByTestId("range-card-0-role-0-0")).toBeNull(); + expect(screen.getByTestId("ranges-first-span")).not.toHaveTextContent("Bass Guitar sits C#2–E3"); }); - it("renders role names and ranges", () => { - render(); - expect(screen.getByText("Test Role 1")).toBeInTheDocument(); - expect(screen.getByText("🎵 C4 — C5")).toBeInTheDocument(); - expect(screen.getByText("Test Role 2")).toBeInTheDocument(); - expect(screen.getByText("🎵 G4 — G5")).toBeInTheDocument(); + it("rejects inverted spans instead of calling them playable", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + song.sections[0]!.roles[0] = { + ...song.sections[0]!.roles[0]!, + range: { lowestNote: "E3", highestNote: "C#2" }, + overlapWarnings: [] + }; + + render(); + + const card = screen.getByTestId("range-card-0-bass-guitar-0"); + expect(card).toHaveTextContent("Confirm the high and low notes by ear before treating this as a playable span."); + expect(card).not.toHaveTextContent("E3 — C#2"); }); - it("renders overlap warnings", () => { - render(); - expect(screen.getByText("⚠️ Clashing notes with Role 2")).toBeInTheDocument(); + it("names written notes as an instrument check", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + song.sections[0]!.roles[0] = { + ...song.sections[0]!.roles[0]!, + transcription: [ + { pitch: "C#2", onset: 0, offset: 1, velocity: 90 }, + { pitch: "E3", onset: 1, offset: 2, velocity: 90 } + ] + }; + + render(); + expect(screen.getByText("Check 2 written notes on your instrument.")).toBeTruthy(); }); - it("renders transcription count when transcription exists", () => { - render(); - expect(screen.getByText(/Transcription available:/)).toBeInTheDocument(); - expect(screen.getByText(/2 notes/)).toBeInTheDocument(); + it("uses singular copy for one written note", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + song.sections[0]!.roles[0] = { + ...song.sections[0]!.roles[0]!, + transcription: [{ pitch: "C#2", onset: 0, offset: 1, velocity: 90 }] + }; + + render(); + expect(screen.getByText("Check 1 written note on your instrument.")).toBeTruthy(); }); - it("does not render transcription block when transcription is undefined", () => { - render(); - // There is exactly one transcription block, from Role 1 - const elements = screen.getAllByText(/Transcription available:/); - expect(elements.length).toBe(1); + it("keeps repeated role cards addressable across sections", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + song.sections = [ + verse, + { ...verse, id: "chorus-1", label: "chorus", timeRange: { start: 30, end: 50 } } + ]; + + render(); + + expect(screen.getByTestId("range-card-0-bass-guitar-0")).toBeTruthy(); + expect(screen.getByTestId("range-card-1-bass-guitar-0")).toBeTruthy(); + }); + + it("rejects Proxy section evidence instead of trusting descriptor reads", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + song.sections = [ + new Proxy(verse, { + get(target, property, receiver) { + if (property === "label") return "spoofed-section"; + if (property === "roles") return []; + return Reflect.get(target, property, receiver); + } + }) + ]; + + render(); + + expect(screen.queryByText("spoofed-section")).toBeNull(); + expect(screen.queryByTestId("range-card-0-bass-guitar-0")).toBeNull(); }); }); diff --git a/apps/desktop/src/features/ranges/index.tsx b/apps/desktop/src/features/ranges/index.tsx index 1cbb020b4..dae56f7e0 100644 --- a/apps/desktop/src/features/ranges/index.tsx +++ b/apps/desktop/src/features/ranges/index.tsx @@ -1,71 +1,167 @@ +import { useMemo } from "react"; import type { RehearsalSong } from "@bandscope/shared-types"; +import { createTranslator, detectPreferredLocale } from "../../i18n"; +import { + fillRangeCopy, + firstRangeSqueeze, + isSafeRuntimeValue, + meaningfulRangeText, + ownDataProperty, + playableRange +} from "../workspace/firstRangeSqueeze"; -/** Documented. */ -export function RangesFeature(props: { title: string; song?: RehearsalSong | null }) { - const { title, song } = props; +/** Return whether an untrusted runtime value is a plain object record. */ +function isRuntimeObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** Return trimmed clash copy from untrusted overlap-warning evidence. */ +function namedOverlapWarnings(warnings: unknown): string[] { + if (!Array.isArray(warnings)) { + return []; + } + const named: string[] = []; + for (const warning of warnings) { + const namedWarning = meaningfulRangeText(warning); + if (namedWarning) { + named.push(namedWarning); + } + } + return named; +} + +/** Render per-role playable spans and the next instrument check for the loaded song. */ +export function RangesFeature(props: { + title: string; + song?: RehearsalSong | null; + activeRole?: string | null; +}) { + const { title, song, activeRole = null } = props; + const t = useMemo(() => createTranslator(detectPreferredLocale()), []); + const safeSong = useMemo( + () => (song && isSafeRuntimeValue(song) ? song : null), + [song], + ); + const firstRange = useMemo( + () => (safeSong ? firstRangeSqueeze(safeSong, activeRole) : null), + [activeRole, safeSong], + ); + const firstRangeCopy = firstRange + ? fillRangeCopy( + t(firstRange.overlapWarning ? "workspaceFirstRangeClash" : "workspaceFirstRangeCheck"), + { + roleName: firstRange.roleName, + lowestNote: firstRange.lowestNote, + highestNote: firstRange.highestNote, + sectionLabel: firstRange.sectionLabel + } + ) + : t("workspaceFirstRangeMissing"); if (!song) { return ( -
-

{title}

-

No song loaded. Start an analysis to see range data.

+
+

{title}

+

{t("rangesEmptyState")}

); } + const runtimeSong: unknown = safeSong; + const songSections = isRuntimeObject(runtimeSong) ? ownDataProperty(runtimeSong, "sections") : undefined; + const sections = Array.isArray(songSections) ? songSections : []; + return ( -
-

{title}

- {song.sections.map((section) => ( -
-

{section.label}

-
- {section.roles.map((role) => ( -
-
- {role.name} -
-
- 🎵 {role.range.lowestNote} — {role.range.highestNote} -
- {role.overlapWarnings.length > 0 && ( -
- {role.overlapWarnings.map((warning, wIndex) => ( -
- ⚠️ {warning} -
- ))} -
- )} - {role.transcription && role.transcription.length > 0 && ( -
- Transcription available: {role.transcription.length} notes -
- )} -
- ))} +
+

{title}

+
+

{t("workspaceFirstRangeTitle")}

+

{firstRangeCopy}

+
+ {sections.map((sectionValue, sectionIndex) => { + if (!isRuntimeObject(sectionValue)) { + return null; + } + const sectionRecord = sectionValue; + const sectionLabel = meaningfulRangeText(ownDataProperty(sectionRecord, "label")); + const sectionId = meaningfulRangeText(ownDataProperty(sectionRecord, "id")) ?? `section-${sectionIndex}`; + const roles = ownDataProperty(sectionRecord, "roles"); + if (!sectionLabel || !Array.isArray(roles)) { + return null; + } + return ( +
+

{sectionLabel}

+
+ {roles.map((roleValue, roleIndex) => { + if (!isRuntimeObject(roleValue)) { + return null; + } + const roleRecord = roleValue; + const roleName = meaningfulRangeText(ownDataProperty(roleRecord, "name")); + const roleId = meaningfulRangeText(ownDataProperty(roleRecord, "id")); + if (!roleId || !roleName) { + return null; + } + const rangeValue = ownDataProperty(roleRecord, "range"); + const rangeRecord = isRuntimeObject(rangeValue) ? rangeValue : {}; + const validatedRange = playableRange( + ownDataProperty(rangeRecord, "lowestNote"), + ownDataProperty(rangeRecord, "highestNote") + ); + const overlapWarnings = namedOverlapWarnings(ownDataProperty(roleRecord, "overlapWarnings")); + const transcription = ownDataProperty(roleRecord, "transcription"); + const transcriptionCount = Array.isArray(transcription) ? transcription.length : 0; + return ( +
+

{roleName}

+ {validatedRange ? ( + <> +

+ {validatedRange.lowestNote} — {validatedRange.highestNote} +

+

+ {fillRangeCopy(t("sectionRangeNextAction"), { sectionLabel })} +

+ + ) : ( +

{t("rangesUnnamedSpan")}

+ )} + {overlapWarnings.length > 0 ? ( +
    + {overlapWarnings.map((warning, warningIndex) => ( +
  • + {warning} +
  • + ))} +
+ ) : null} + {transcriptionCount > 0 ? ( +

+ {fillRangeCopy( + t(transcriptionCount === 1 ? "rangesOneNoteToCheck" : "rangesNotesToCheck"), + { count: String(transcriptionCount) } + )} +

+ ) : null} +
+ ); + })} +
-
- ))} + ); + })}
); } diff --git a/apps/desktop/src/features/workspace/Workspace.rehearsalSurfaces.test.tsx b/apps/desktop/src/features/workspace/Workspace.rehearsalSurfaces.test.tsx new file mode 100644 index 000000000..a368a81bf --- /dev/null +++ b/apps/desktop/src/features/workspace/Workspace.rehearsalSurfaces.test.tsx @@ -0,0 +1,31 @@ +import { render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it } from "vitest"; +import { Workspace } from "./Workspace"; + +const originalLanguage = navigator.language; + +function setNavigatorLanguage(language: string) { + Object.defineProperty(navigator, "language", { + configurable: true, + value: language + }); +} + +describe("Workspace rehearsal surfaces", () => { + afterEach(() => { + setNavigatorLanguage(originalLanguage); + }); + + it("makes the Ranges board and Player next-loop window reachable from the loaded workspace", () => { + setNavigatorLanguage("en-US"); + + render(); + + expect(screen.getByRole("heading", { name: "Ranges" })).toBeTruthy(); + expect(screen.getByTestId("ranges-first-span")).toHaveTextContent("Bass Guitar sits C#2–E3 in verse"); + expect(screen.getByRole("heading", { name: "Player" })).toBeTruthy(); + expect(screen.getByTestId("player-next-map-loop")).toHaveTextContent("Tonight's first section is verse"); + expect(screen.getByTestId("player-next-map-loop")).toHaveTextContent("does not play audio yet"); + }); +}); diff --git a/apps/desktop/src/features/workspace/Workspace.test.tsx b/apps/desktop/src/features/workspace/Workspace.test.tsx index 7837bf80e..961fbf3a8 100644 --- a/apps/desktop/src/features/workspace/Workspace.test.tsx +++ b/apps/desktop/src/features/workspace/Workspace.test.tsx @@ -146,7 +146,7 @@ describe("Workspace", () => { render(); - const callout = screen.getByTestId("first-range-squeeze"); + const callout = screen.getByTestId("ranges-first-span"); expect(callout).toHaveTextContent("Tonight's first range"); expect(callout).toHaveTextContent( "Bass Guitar sits C#2–E3 in verse. Hear that clash on your instrument before the verse." @@ -164,7 +164,7 @@ describe("Workspace", () => { render(); - expect(screen.getByTestId("first-range-squeeze")).toHaveTextContent( + expect(screen.getByTestId("ranges-first-span")).toHaveTextContent( "Tonight's first range still needs an ear check. Confirm the high and low notes on the selected part before the first section." ); }); @@ -176,7 +176,7 @@ describe("Workspace", () => { render(); fireEvent.click(screen.getByRole("tab", { name: "Lead Vocal" })); - expect(screen.getByTestId("first-range-squeeze")).toHaveTextContent( + expect(screen.getByTestId("ranges-first-span")).toHaveTextContent( "Lead Vocal sits G#3–C#5 in verse. Hear that clash on your instrument before the verse." ); }); @@ -191,7 +191,7 @@ describe("Workspace", () => { render(); - expect(screen.getByTestId("first-range-squeeze")).toHaveTextContent( + expect(screen.getByTestId("ranges-first-span")).toHaveTextContent( "Bass Guitar sits C#2–E3 in verse. Check that span on your instrument before the verse." ); }); diff --git a/apps/desktop/src/features/workspace/Workspace.tsx b/apps/desktop/src/features/workspace/Workspace.tsx index d44e20777..4ffd930e4 100644 --- a/apps/desktop/src/features/workspace/Workspace.tsx +++ b/apps/desktop/src/features/workspace/Workspace.tsx @@ -4,7 +4,8 @@ import { RoleSwitcher } from "./RoleSwitcher"; import { SectionRoadmap } from "./SectionRoadmap"; import { GrooveMap } from "./GrooveMap"; import { PracticeProgress } from "./PracticeProgress"; -import { fillRangeCopy, firstRangeSqueeze } from "./firstRangeSqueeze"; +import { RangesFeature } from "../ranges"; +import { PlayerFeature } from "../player"; import { createTranslator, detectPreferredLocale } from "../../i18n"; import { generateCueSheetCsv, generateChartSummaryJson, generateMetadataHandoffJson, sanitizeFilename } from "../../lib/export"; import { Button } from "@/components/ui/button"; @@ -151,18 +152,6 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp return roleMap.get(activeRole); }, [activeRole, roleMap]); const canTranscribeBass = activeRoleDetails?.name.toLowerCase().includes("bass") ?? false; - const firstRange = useMemo(() => firstRangeSqueeze(song, activeRole), [activeRole, song]); - const firstRangeCopy = firstRange - ? fillRangeCopy( - t(firstRange.overlapWarning ? "workspaceFirstRangeClash" : "workspaceFirstRangeCheck"), - { - roleName: firstRange.roleName, - lowestNote: firstRange.lowestNote, - highestNote: firstRange.highestNote, - sectionLabel: firstRange.sectionLabel - } - ) - : t("workspaceFirstRangeMissing"); /** Handle the practice progress change internally by immutably updating the song state. */ const handlePracticeProgressChange = (newProgress: number) => { @@ -301,14 +290,10 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp -
-

{t("workspaceFirstRangeTitle")}

-

{firstRangeCopy}

-
+
+ + +
diff --git a/apps/desktop/src/features/workspace/firstRangeSqueeze.test.ts b/apps/desktop/src/features/workspace/firstRangeSqueeze.test.ts index 643935954..857728712 100644 --- a/apps/desktop/src/features/workspace/firstRangeSqueeze.test.ts +++ b/apps/desktop/src/features/workspace/firstRangeSqueeze.test.ts @@ -47,7 +47,7 @@ describe("playableRange", () => { }); describe("firstRangeSqueeze", () => { - it("prefers the first named span that also carries a clash warning", () => { + it("returns the first playable span and preserves its clash warning", () => { const squeeze = firstRangeSqueeze(createDemoRehearsalSong()); expect(squeeze).toEqual({ @@ -59,6 +59,20 @@ describe("firstRangeSqueeze", () => { }); }); + it("returns the first playable span when a later span has a clash warning", () => { + const song = createDemoRehearsalSong(); + song.sections[0]!.roles[0] = { + ...song.sections[0]!.roles[0]!, + overlapWarnings: [] + }; + + expect(firstRangeSqueeze(song)).toMatchObject({ + sectionLabel: "verse", + roleName: "Bass Guitar", + overlapWarning: undefined + }); + }); + it("falls back to the first named span when clashes are only none sentinels", () => { const song = createDemoRehearsalSong(); song.sections[0]!.roles = song.sections[0]!.roles.map((role, index) => ({ @@ -122,6 +136,52 @@ describe("firstRangeSqueeze", () => { }); }); + it("rejects Proxy range evidence instead of trusting descriptor reads", () => { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + song.sections = [ + new Proxy(verse, { + get(target, property, receiver) { + if (property === "label") return "spoofed-section"; + if (property === "roles") return []; + return Reflect.get(target, property, receiver); + } + }) + ]; + + expect(firstRangeSqueeze(song)).toBeNull(); + }); + + it("rejects Proxy descriptor traps before they can forge range evidence", () => { + const song = createDemoRehearsalSong(); + const forged = new Proxy(song, { + getOwnPropertyDescriptor(target, property) { + if (property === "sections") { + return { configurable: true, enumerable: true, value: [], writable: true }; + } + return Reflect.getOwnPropertyDescriptor(target, property); + } + }); + + expect(firstRangeSqueeze(forged as RehearsalSong)).toBeNull(); + }); + + it("does not invoke accessor evidence while rejecting it", () => { + const song = createDemoRehearsalSong(); + let invoked = false; + Object.defineProperty(song, "sections", { + configurable: true, + enumerable: true, + get() { + invoked = true; + return []; + } + }); + + expect(firstRangeSqueeze(song)).toBeNull(); + expect(invoked).toBe(false); + }); + it("limits the squeeze to the selected role", () => { const squeeze = firstRangeSqueeze(createDemoRehearsalSong(), "lead-vocal"); diff --git a/apps/desktop/src/features/workspace/firstRangeSqueeze.ts b/apps/desktop/src/features/workspace/firstRangeSqueeze.ts index 47270d2a9..4e1047cc7 100644 --- a/apps/desktop/src/features/workspace/firstRangeSqueeze.ts +++ b/apps/desktop/src/features/workspace/firstRangeSqueeze.ts @@ -34,6 +34,59 @@ function isRuntimeObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } +/** Return whether an object graph contains only cloneable own data properties. */ +function hasDataPropertyGraph(value: unknown, seen = new WeakSet()): boolean { + if (typeof value !== "object" || value === null) { + return true; + } + if (seen.has(value)) { + return true; + } + seen.add(value); + + let keys: (string | symbol)[]; + try { + keys = Reflect.ownKeys(value); + } catch { + return false; + } + for (const key of keys) { + let descriptor: PropertyDescriptor | undefined; + try { + descriptor = Object.getOwnPropertyDescriptor(value, key); + } catch { + return false; + } + if (!descriptor || !("value" in descriptor) || !hasDataPropertyGraph(descriptor.value, seen)) { + return false; + } + } + return true; +} + +/** Reject accessors and Proxy containers before descriptor reads accept data. */ +export function isSafeRuntimeValue(value: unknown): boolean { + if (!hasDataPropertyGraph(value)) { + return false; + } + try { + structuredClone(value); + return true; + } catch { + return false; + } +} + +/** Read an owned data-property without invoking an accessor or Proxy get trap. */ +export function ownDataProperty(record: Record, property: string): unknown { + try { + const descriptor = Object.getOwnPropertyDescriptor(record, property); + return descriptor && "value" in descriptor ? descriptor.value : undefined; + } catch { + return undefined; + } +} + /** Return trimmed copy that is not a blank or `none` sentinel. */ export function meaningfulRangeText(value: unknown): string | undefined { if (typeof value !== "string") { @@ -87,9 +140,9 @@ export function playableRange( /** * Pick the first playable range a player should check before the next section. * - * Prefers a named span that also carries a clash warning so the board names - * the squeeze that will waste rehearsal time. Falls back to the first named - * span when no clash is present. Runtime roots and collection members are + * Returns the first named span that passes playable-range validation. Any + * warning attached to that span is preserved for copy selection. Runtime + * roots and collection members are * treated as untrusted; malformed evidence is isolated instead of crashing * the buyer-visible workspace or becoming playable-range authority. */ @@ -98,42 +151,50 @@ export function firstRangeSqueeze( activeRole: string | null = null ): FirstRangeSqueeze | null { const runtimeSong: unknown = song; - if (!isRuntimeObject(runtimeSong) || !Array.isArray(runtimeSong.sections)) { + if (!isRuntimeObject(runtimeSong) || !isSafeRuntimeValue(runtimeSong)) { + return null; + } + const sections = isRuntimeObject(runtimeSong) ? ownDataProperty(runtimeSong, "sections") : undefined; + if (!Array.isArray(sections)) { return null; } - let fallback: FirstRangeSqueeze | null = null; - - for (const sectionValue of runtimeSong.sections) { - if (!isRuntimeObject(sectionValue) || !Array.isArray(sectionValue.roles)) { + for (const sectionValue of sections) { + const roles = isRuntimeObject(sectionValue) ? ownDataProperty(sectionValue, "roles") : undefined; + if (!isRuntimeObject(sectionValue) || !Array.isArray(roles)) { continue; } - const sectionLabel = meaningfulRangeText(sectionValue.label); + const sectionLabel = meaningfulRangeText(ownDataProperty(sectionValue, "label")); if (!sectionLabel) { continue; } - for (const roleValue of sectionValue.roles) { + for (const roleValue of roles) { if (!isRuntimeObject(roleValue)) { continue; } - const roleId = meaningfulRangeText(roleValue.id); - const roleName = meaningfulRangeText(roleValue.name); + const roleId = meaningfulRangeText(ownDataProperty(roleValue, "id")); + const roleName = meaningfulRangeText(ownDataProperty(roleValue, "name")); if (!roleId || !roleName || (activeRole && roleId !== activeRole)) { continue; } - if (!isRuntimeObject(roleValue.range)) { + const rangeValue = ownDataProperty(roleValue, "range"); + if (!isRuntimeObject(rangeValue)) { continue; } - const range = playableRange(roleValue.range.lowestNote, roleValue.range.highestNote); + const range = playableRange( + ownDataProperty(rangeValue, "lowestNote"), + ownDataProperty(rangeValue, "highestNote") + ); if (!range) { continue; } let overlapWarning: string | undefined; - if (Array.isArray(roleValue.overlapWarnings)) { - for (const warning of roleValue.overlapWarnings) { + const overlapWarnings = ownDataProperty(roleValue, "overlapWarnings"); + if (Array.isArray(overlapWarnings)) { + for (const warning of overlapWarnings) { const meaningfulWarning = meaningfulRangeText(warning); if (meaningfulWarning) { overlapWarning = meaningfulWarning; @@ -149,17 +210,11 @@ export function firstRangeSqueeze( overlapWarning }; - if (overlapWarning) { - return candidate; - } - - if (!fallback) { - fallback = candidate; - } + return candidate; } } - return fallback; + return null; } /** Fill trusted `{token}` placeholders once while keeping rehearsal values literal. */ diff --git a/apps/desktop/src/locales/en/common.json b/apps/desktop/src/locales/en/common.json index d803a765e..3b2ccba62 100644 --- a/apps/desktop/src/locales/en/common.json +++ b/apps/desktop/src/locales/en/common.json @@ -154,5 +154,14 @@ "workspaceFirstRangeClash": "{roleName} sits {lowestNote}–{highestNote} in {sectionLabel}. Hear that clash on your instrument before the {sectionLabel}.", "workspaceFirstRangeMissing": "Tonight's first range still needs an ear check. Confirm the high and low notes on the selected part before the first section.", "sectionRangeLabel": "Range", - "sectionRangeNextAction": "Check this span on your instrument before {sectionLabel}." + "sectionRangeNextAction": "Check this span on your instrument before {sectionLabel}.", + "rangesEmptyState": "Choose a song on the rehearsal map first. Ranges will name tonight's playable spans after analysis.", + "rangesUnnamedSpan": "Confirm the high and low notes by ear before treating this as a playable span.", + "rangesOneNoteToCheck": "Check {count} written note on your instrument.", + "rangesNotesToCheck": "Check {count} written notes on your instrument.", + "playerEmptyState": "Open the rehearsal map and choose a song first. This window does not play audio yet.", + "playerNextMapLoopTitle": "Tonight's first loop", + "playerMapLoopNextAction": "Tonight's first section is {sectionLabel}. Open that section on the rehearsal map to set tonight's loop.", + "playerNoAudioYet": "This window does not play audio yet.", + "playerMissingSection": "Tonight's first section still needs a named window on the rehearsal map." } diff --git a/apps/desktop/src/locales/ko/common.json b/apps/desktop/src/locales/ko/common.json index 0f6c6c66d..a97f5bf93 100644 --- a/apps/desktop/src/locales/ko/common.json +++ b/apps/desktop/src/locales/ko/common.json @@ -154,5 +154,14 @@ "workspaceFirstRangeClash": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}이고 다른 파트와 겹칩니다. {sectionLabel} 들어가기 전에 그 충돌을 악기로 들어 보세요.", "workspaceFirstRangeMissing": "오늘 먼저 볼 음역은 아직 귀로 확인이 필요합니다. 선택한 파트의 최저·최고음을 첫 구간 전에 확인해 보세요.", "sectionRangeLabel": "음역", - "sectionRangeNextAction": "{sectionLabel} 들어가기 전에 이 음역을 악기로 확인해 보세요." + "sectionRangeNextAction": "{sectionLabel} 들어가기 전에 이 음역을 악기로 확인해 보세요.", + "rangesEmptyState": "먼저 합주 맵에서 곡을 선택하세요. 분석이 끝나면 음역 화면이 오늘 확인할 음역을 알려 줍니다.", + "rangesUnnamedSpan": "연주 가능한 음역으로 보기 전에 최저음과 최고음을 귀로 확인해 보세요.", + "rangesOneNoteToCheck": "악기로 기보된 음 {count}개를 확인해 보세요.", + "rangesNotesToCheck": "악기로 기보된 음 {count}개를 확인해 보세요.", + "playerEmptyState": "먼저 합주 맵에서 곡을 선택하세요. 이 화면은 아직 오디오를 재생하지 않습니다.", + "playerNextMapLoopTitle": "오늘 먼저 감을 루프", + "playerMapLoopNextAction": "오늘 첫 구간은 {sectionLabel}입니다. 합주 맵에서 그 구간을 열어 오늘 루프를 정하세요.", + "playerNoAudioYet": "이 화면은 아직 오디오를 재생하지 않습니다.", + "playerMissingSection": "오늘 첫 구간은 합주 맵에 이름 있는 구간이 생긴 뒤에 정할 수 있습니다." }