From 17104a3261bdcfc7ff8b2b4be35b849b982fcaca Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 15:21:30 +0000 Subject: [PATCH 1/7] feat(workspace): name tonight's first riff plan on the map Name the corroborated part, owned riffPlan copy, labeled section, and time so the next rehearsal action is obvious. Open moves to the matching rendered map section. Do not invent riff copy from groove, cue, simplification, overlap, range, chords, function labels, setup notes, transposition, fill, tuning, dynamics, articulation, voicing, hook, or capo plans. --- AGENTS.md | 1 + ARCHITECTURE.md | 3 +- CHANGELOG.md | 1 + CLAUDE.md | 2 +- .../FirstRiffPlanCallout.identity.test.tsx | 21 ++ .../FirstRiffPlanCallout.memoization.test.tsx | 25 ++ .../FirstRiffPlanCallout.particle.test.tsx | 52 ++++ ...rstRiffPlanCallout.reduced-motion.test.tsx | 43 +++ .../workspace/FirstRiffPlanCallout.test.tsx | 202 ++++++++++++ .../workspace/FirstRiffPlanCallout.tsx | 179 +++++++++++ ...tRiffPlanCallout.unavailable-copy.test.tsx | 34 +++ ...stRiffPlanCallout.workspace-scope.test.tsx | 54 ++++ .../src/features/workspace/Workspace.test.tsx | 30 ++ .../src/features/workspace/Workspace.tsx | 11 +- .../workspace/coverageContract.test.ts | 13 + .../firstRiffPlan.inherited-metadata.test.ts | 94 ++++++ .../firstRiffPlan.proxy-authority.test.ts | 31 ++ .../firstRiffPlan.section-label.test.ts | 14 + .../features/workspace/firstRiffPlan.test.ts | 286 +++++++++++++++++ .../src/features/workspace/firstRiffPlan.ts | 287 ++++++++++++++++++ apps/desktop/src/i18n/index.test.ts | 50 ++- apps/desktop/src/i18n/index.ts | 36 ++- apps/desktop/src/locales/en/common.json | 7 +- apps/desktop/src/locales/ko/common.json | 7 +- apps/desktop/vite.config.ts | 21 +- docs/design-system/component-contract.md | 1 + ...duced-motion-first-riff-plan-navigation.md | 3 + packages/shared-types/src/index.ts | 6 + packages/shared-types/test/index.test.ts | 7 + 29 files changed, 1505 insertions(+), 16 deletions(-) create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.identity.test.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.memoization.test.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.particle.test.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.reduced-motion.test.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.test.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.unavailable-copy.test.tsx create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.workspace-scope.test.tsx create mode 100644 apps/desktop/src/features/workspace/coverageContract.test.ts create mode 100644 apps/desktop/src/features/workspace/firstRiffPlan.inherited-metadata.test.ts create mode 100644 apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts create mode 100644 apps/desktop/src/features/workspace/firstRiffPlan.section-label.test.ts create mode 100644 apps/desktop/src/features/workspace/firstRiffPlan.test.ts create mode 100644 apps/desktop/src/features/workspace/firstRiffPlan.ts create mode 100644 docs/doctoring/reduced-motion-first-riff-plan-navigation.md diff --git a/AGENTS.md b/AGENTS.md index fca448ce9..0f687ff2d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,7 @@ This section applies to any agent (Claude, Codex, Cursor, opencode, ...) working - Keep UI and analysis engine decoupled through shared contracts. - Prefer minimal, test-first changes for production code. - Prefer practical, friendly, rehearsal-first wording over academic or authority-heavy language. +- Name tonight's first riff plan with the owning part when an active role is corroborated, the owned `riffPlan` copy, the labeled section, and the time so the next action is obvious. Do not invent that copy from groove, cue, simplification, overlap, range, chord labels, function labels, setup notes, transposition plans, fill plans, tuning plans, dynamics plans, articulation plans, voicing plans, hook plans, capo plans, confirmed overrides, harmonic explanations, or confidence notes. - Do not reduce the product to a chord analyzer when form, timing, player coordination, simplification, and setup cues are the real rehearsal blockers. - Do not frame usability as a reason to accept weak analysis quality; BandScope should aim for both easy use and high accuracy. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3302a6fc3..4ec13d187 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,10 +1,11 @@ # ARCHITECTURE.md -Last updated: 2026-03-11 +Last updated: 2026-08-24 ## Brand source - Product identity, UX tone, copy rules, and prioritization tie-breakers live in `docs/brand-story.md`. +- The mounted workspace copy for tonight's first riff plan must name the owning part when corroborated, the owned `riffPlan` text, the labeled section, and the time so the next action is obvious. Open moves to the matching rendered map section. Do not invent that copy from groove, cue, simplification, overlap, range, chord labels, function labels, setup notes, transposition plans, fill plans, tuning plans, dynamics plans, articulation plans, voicing plans, hook plans, capo plans, confirmed overrides, harmonic explanations, or confidence notes. Distinct from first-hook-plan, first-fill-plan, first-setup-note, first-transposition-plan, first-tuning-plan, first-dynamics-plan, first-articulation-plan, first-voicing-plan, and first-capo-plan. - Future PRDs, TRDs, onboarding copy, empty states, error messages, and marketing copy should use that document as the single brand source of truth. ## Security source diff --git a/CHANGELOG.md b/CHANGELOG.md index eea696893..ba427c44d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Added +- Name tonight's first riff plan in the mounted rehearsal workspace so a part can lock the owned riff before rehearsal; the Open action moves to the matching rendered map section, while inherited or accessor-backed runtime metadata remains guidance-only instead of becoming navigation authority. - 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 82c2c704a..bbdb8f818 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). `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 mounted workspace names tonight's first riff plan and opens the matching rendered map section. Do not invent that copy from groove, cue, simplification, overlap, range, chord labels, function labels, setup notes, transposition plans, fill plans, tuning plans, dynamics plans, articulation plans, voicing plans, hook plans, capo plans, confirmed overrides, harmonic explanations, or confidence notes. Distinct from first-hook-plan, first-fill-plan, first-setup-note, first-transposition-plan, first-tuning-plan, first-dynamics-plan, first-articulation-plan, first-voicing-plan, and first-capo-plan. `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/workspace/FirstRiffPlanCallout.identity.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.identity.test.tsx new file mode 100644 index 000000000..4a1e32276 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.identity.test.tsx @@ -0,0 +1,21 @@ +import { render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { expect, it } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +it("gives co-mounted riff-plan callouts distinct DOM identities", () => { + render( + <> + + + + ); + + const callouts = screen.getAllByRole("complementary", { + name: "Tonight's first riff plan" + }); + const ids = callouts.map((callout) => callout.id); + + expect(ids.every((id) => id.length > 0)).toBe(true); + expect(new Set(ids).size).toBe(callouts.length); +}); diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.memoization.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.memoization.test.tsx new file mode 100644 index 000000000..84ee61526 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.memoization.test.tsx @@ -0,0 +1,25 @@ +import { render } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +describe("FirstRiffPlanCallout resolver reuse", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("does not rescan role metadata when a parent rerenders the same song object", () => { + const song = createDemoRehearsalSong(); + const role = song.sections[0]!.roles.find((candidate) => candidate.id === "bass-guitar")!; + const descriptorSpy = vi.spyOn(Object, "getOwnPropertyDescriptor"); + + const { rerender } = render(); + const firstScanCount = descriptorSpy.mock.calls.filter(([target]) => target === role).length; + expect(firstScanCount).toBeGreaterThan(0); + + rerender(); + const secondScanCount = descriptorSpy.mock.calls.filter(([target]) => target === role).length; + + expect(secondScanCount).toBe(firstScanCount); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.particle.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.particle.test.tsx new file mode 100644 index 000000000..148f6b446 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.particle.test.tsx @@ -0,0 +1,52 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +describe("FirstRiffPlanCallout Korean role copy", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("keeps vowel-ending role names particle-safe before and after the riff action", () => { + vi.stubGlobal("navigator", { language: "ko-KR" }); + const song = createDemoRehearsalSong(); + const seed = song.sections[0]!; + seed.roles = [ + { + ...seed.roles[0]!, + id: "piano", + name: "피아노", + rehearsalPriority: "high", + riffPlan: "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift." + } + ]; + seed.partGraph = [{ role_id: "piano", is_active: true, handoff_to: [], handoff_from: [] }]; + + const grid = document.createElement("div"); + grid.dataset.testid = "song-structure-grid"; + grid.setAttribute("role", "region"); + grid.setAttribute("aria-label", "Scrollable song structure timeline"); + const target = document.createElement("div"); + target.dataset.sectionIndex = "0"; + Object.defineProperty(target, "scrollIntoView", { + configurable: true, + value: vi.fn() + }); + grid.appendChild(target); + document.body.appendChild(grid); + + render(); + + expect(screen.getByText("0:10 벌스에서 피아노 파트의 리프 계획이 있습니다.")).toBeTruthy(); + expect(screen.queryByText(/피아노이/)).toBeNull(); + expect(screen.queryByText(/피아노가/)).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: "0:10 피아노 리프 열기" })); + + expect(screen.getByText("0:10에서 피아노 파트의 리프를 맞춘 다음 합주를 시작하세요.")).toBeTruthy(); + expect(screen.queryByText(/피아노과/)).toBeNull(); + + grid.remove(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.reduced-motion.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.reduced-motion.test.tsx new file mode 100644 index 000000000..127b45423 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.reduced-motion.test.tsx @@ -0,0 +1,43 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +describe("FirstRiffPlanCallout reduced motion", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("scrolls immediately when the operating system requests reduced motion", () => { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: query === "(prefers-reduced-motion: reduce)", + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn() + })); + + const grid = document.createElement("div"); + grid.dataset.testid = "song-structure-grid"; + grid.setAttribute("role", "region"); + grid.setAttribute("aria-label", "Scrollable song structure timeline"); + const target = document.createElement("div"); + target.dataset.sectionIndex = "0"; + const scrollIntoView = vi.fn(); + Object.defineProperty(target, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + grid.appendChild(target); + document.body.appendChild(grid); + + render(); + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "auto" }); + + grid.remove(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.test.tsx new file mode 100644 index 000000000..bd1909fac --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.test.tsx @@ -0,0 +1,202 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong, type RehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +const DEMO_RIFF_PLAN = + "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift."; + +function songWithRiffPlan() { + return createDemoRehearsalSong(); +} + +function appendSongStructureTarget(ariaLabel = "Scrollable song structure timeline") { + const timeline = document.createElement("div"); + timeline.setAttribute("role", "region"); + timeline.setAttribute("aria-label", ariaLabel); + const grid = document.createElement("div"); + grid.dataset.testid = "song-structure-grid"; + const target = document.createElement("div"); + target.dataset.sectionIndex = "0"; + const scrollIntoView = vi.fn(); + Object.defineProperty(target, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + grid.appendChild(target); + timeline.appendChild(grid); + document.body.appendChild(timeline); + return { grid: timeline, scrollIntoView }; +} + +describe("FirstRiffPlanCallout", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("contains a malformed runtime song root instead of crashing the callout", () => { + render(); + + expect( + screen.getByText("No riff plan is available. Stay on tonight's map for the next rehearsal cue.") + ).toBeTruthy(); + }); + + it("contains a hostile song identity accessor instead of crashing the callout", () => { + const song = songWithRiffPlan(); + Object.defineProperty(song, "id", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile song id getter"); + } + }); + + expect(() => render()).not.toThrow(); + expect(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })).toBeTruthy(); + }); + + it("resets armed guidance when accessor-id songs change with the same riff signature", () => { + const firstSong = songWithRiffPlan(); + const nextSong = songWithRiffPlan(); + for (const song of [firstSong, nextSong]) { + Object.defineProperty(song, "id", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile song id getter"); + } + }); + } + const { grid } = appendSongStructureTarget(); + const { rerender } = render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + expect( + screen.getByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeTruthy(); + + rerender(); + + expect(screen.getByText("Bass Guitar still has a riff plan in the verse at 0:10.")).toBeTruthy(); + expect( + screen.queryByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeNull(); + + grid.remove(); + }); + + it("preserves armed guidance across immutable edits of the same owned song", () => { + const song = songWithRiffPlan(); + const { grid } = appendSongStructureTarget(); + const { rerender } = render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + expect( + screen.getByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeTruthy(); + + rerender(); + + expect( + screen.getByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeTruthy(); + expect(screen.queryByText("Bass Guitar still has a riff plan in the verse at 0:10.")).toBeNull(); + + grid.remove(); + }); + + it("does not show another part's riff plan under the named holding part", () => { + const song = songWithRiffPlan(); + song.sections[0]!.roles[0]!.riffPlan = ""; + song.sections[0]!.roles[0]!.rehearsalPriority = "low"; + song.sections[0]!.roles[2]!.riffPlan = "Leave the bass on roots while the hook lands."; + song.sections[0]!.roles[2]!.rehearsalPriority = "low"; + song.sections[0]!.roles[1]!.riffPlan = + "Keep the right-hand figure under the vocal so the riff still reads."; + + render(); + + expect( + screen.getByText("Keyboard 1 Right Hand still has a riff plan in the verse at 0:10.") + ).toBeTruthy(); + expect( + screen.getByText("Keep the right-hand figure under the vocal so the riff still reads.") + ).toBeTruthy(); + expect(screen.queryByText("Leave the bass on roots while the hook lands.")).toBeNull(); + expect(screen.queryByText(DEMO_RIFF_PLAN)).toBeNull(); + }); + + it("names the first riff plan as map navigation, scrolls to its rendered section, and arms that action", () => { + const { grid, scrollIntoView } = appendSongStructureTarget(); + + render(); + + expect(screen.getByText(DEMO_RIFF_PLAN)).toBeTruthy(); + const action = screen.getByRole("button", { + name: "Open Bass Guitar riff at 0:10" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect( + screen.getByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeTruthy(); + + grid.remove(); + }); + + it("keeps map navigation stable when the renderer accessible name is localized", () => { + const { grid, scrollIntoView } = appendSongStructureTarget("스크롤 가능한 곡 구조 타임라인"); + + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect( + screen.getByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeTruthy(); + + grid.remove(); + }); + + it("does not claim map navigation completed when the rendered section target is missing", () => { + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + + expect(screen.getByText("Bass Guitar still has a riff plan in the verse at 0:10.")).toBeTruthy(); + expect( + screen.queryByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeNull(); + }); + + it("navigates by renderer-owned section position instead of untrusted analysis ids", () => { + const song = songWithRiffPlan(); + song.sections[0]!.id = "analysis section / duplicate"; + const { grid, scrollIntoView } = appendSongStructureTarget(); + + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + + grid.remove(); + }); + + it("fails closed when more than one song-structure renderer is mounted globally", () => { + const first = appendSongStructureTarget(); + const second = appendSongStructureTarget(); + + render(); + fireEvent.click(screen.getByRole("button", { name: "Open Bass Guitar riff at 0:10" })); + + expect(first.scrollIntoView).not.toHaveBeenCalled(); + expect(second.scrollIntoView).not.toHaveBeenCalled(); + expect(screen.getByText("Bass Guitar still has a riff plan in the verse at 0:10.")).toBeTruthy(); + + first.grid.remove(); + second.grid.remove(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx new file mode 100644 index 000000000..8c9ad09e2 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx @@ -0,0 +1,179 @@ +import { useEffect, useId, useMemo, useState } from "react"; +import type { RehearsalSong } from "@bandscope/shared-types"; +import { Button } from "@/components/ui/button"; +import { + createTranslator, + detectPreferredLocale, + translateSectionFormLabel +} from "../../i18n"; +import { formatRiffPlanTime, resolveFirstRiffPlan } from "./firstRiffPlan"; + +/** Props for the first riff-plan rehearsal callout. */ +export interface FirstRiffPlanCalloutProps { + song: RehearsalSong; +} + +type RiffPlanCopyValues = Readonly>; + +type OpenedRiffPlan = Readonly<{ + songIdentity: unknown; + sectionId: string; + sectionIndex: number; + holdingRoleId: string; + riffPlan: string; + atSeconds: number; +}>; + +/** Read a stable owned song id, falling back to object identity for untrusted identity metadata. */ +function stableRiffPlanSongIdentity(song: RehearsalSong): unknown { + if (song === null || typeof song !== "object" || Array.isArray(song)) { + return song; + } + let descriptor: PropertyDescriptor | undefined; + try { + descriptor = Object.getOwnPropertyDescriptor(song, "id"); + } catch { + return song; + } + return descriptor !== undefined && + Object.prototype.hasOwnProperty.call(descriptor, "value") && + typeof descriptor.value === "string" && + descriptor.value.trim().length > 0 + ? descriptor.value + : song; +} + +/** Interpolate riff-plan placeholders once so rehearsal data is never rescanned as template syntax. */ +function formatRiffPlanCopy(template: string, values: RiffPlanCopyValues): string { + return template.replace(/\{(role|section|at)\}/g, (placeholder) => { + const key = placeholder.slice(1, -1) as keyof RiffPlanCopyValues; + return values[key] ?? placeholder; + }); +} + +/** Use immediate scrolling when the operating system requests reduced motion. */ +function preferredRiffPlanScrollBehavior(): ScrollBehavior { + return typeof window.matchMedia === "function" && + window.matchMedia("(prefers-reduced-motion: reduce)").matches + ? "auto" + : "smooth"; +} + +/** Resolve the song-structure renderer owned by this workspace, failing closed on ambiguous mounts. */ +function resolveRiffPlanRenderer(origin: HTMLElement): HTMLElement | null { + const selector = '[data-testid="song-structure-grid"]'; + const localScope = origin.closest("aside")?.parentElement ?? null; + const localRenderers = localScope?.querySelectorAll(selector) ?? []; + if (localRenderers.length === 1) { + return localRenderers[0] ?? null; + } + if (localRenderers.length > 1) { + return null; + } + + const globalRenderers = document.querySelectorAll(selector); + return globalRenderers.length === 1 ? (globalRenderers[0] ?? null) : null; +} + +/** Name tonight's first riff plan and open the matching rendered map section. */ +export function FirstRiffPlanCallout({ song }: FirstRiffPlanCalloutProps) { + const calloutId = `workspace-surface-riff-plan-${useId()}`; + const locale = detectPreferredLocale(); + const t = createTranslator(locale); + const songIdentity = stableRiffPlanSongIdentity(song); + const runtimeSong = song as unknown as Partial | null; + const named = useMemo(() => resolveFirstRiffPlan(song), [song]); + const namedSectionIndex = + named && Array.isArray(runtimeSong?.sections) + ? runtimeSong.sections.indexOf(named.section) + : -1; + const [openedRiffPlan, setOpenedRiffPlan] = useState(null); + + useEffect(() => { + setOpenedRiffPlan(null); + }, [ + songIdentity, + namedSectionIndex, + named?.section.id, + named?.holdingRole.id, + named?.riffPlan, + named?.atSeconds + ]); + + if (!named) { + return ( + + ); + } + + const opened = + openedRiffPlan !== null && + openedRiffPlan.songIdentity === songIdentity && + openedRiffPlan.sectionId === named.section.id && + openedRiffPlan.sectionIndex === namedSectionIndex && + openedRiffPlan.holdingRoleId === named.holdingRole.id && + openedRiffPlan.riffPlan === named.riffPlan && + openedRiffPlan.atSeconds === named.atSeconds; + const at = formatRiffPlanTime(named.atSeconds); + const copyValues: RiffPlanCopyValues = { + role: named.holdingRole.name, + section: translateSectionFormLabel(locale, named.section.label), + at + }; + const actionLabel = formatRiffPlanCopy(t("firstRiffPlanOpenAction"), copyValues); + const body = formatRiffPlanCopy(t("firstRiffPlanBody"), copyValues); + const armed = formatRiffPlanCopy(t("firstRiffPlanArmed"), copyValues); + + return ( + + ); +} diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.unavailable-copy.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.unavailable-copy.test.tsx new file mode 100644 index 000000000..daafa5112 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.unavailable-copy.test.tsx @@ -0,0 +1,34 @@ +import { render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +function songWithoutRiffPlan() { + const song = createDemoRehearsalSong(); + for (const section of song.sections) { + for (const role of section.roles) { + role.riffPlan = ""; + } + } + return song; +} + +describe("FirstRiffPlanCallout unavailable copy", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("does not assert why the English riff plan is unavailable", () => { + render(); + + expect(screen.getByText("No riff plan is available. Stay on tonight's map for the next rehearsal cue.")).toBeTruthy(); + }); + + it("does not assert why the Korean riff plan is unavailable", () => { + vi.stubGlobal("navigator", { language: "ko-KR" }); + + render(); + + expect(screen.getByText("사용 가능한 리프 계획이 없습니다. 다음 합주 큐를 위해 오늘 맵에 머무르세요.")).toBeTruthy(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.workspace-scope.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.workspace-scope.test.tsx new file mode 100644 index 000000000..c04d9fec0 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.workspace-scope.test.tsx @@ -0,0 +1,54 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it, vi } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +describe("FirstRiffPlanCallout workspace scope", () => { + it("opens the song-structure renderer owned by the current workspace", () => { + const firstSong = createDemoRehearsalSong(); + const secondSong = createDemoRehearsalSong(); + secondSong.id = "second-workspace-song"; + + const { container } = render( + <> +
+ +
+
+
+
+
+ +
+
+
+
+ + ); + + const targets = container.querySelectorAll('[data-section-index="0"]'); + expect(targets).toHaveLength(2); + const firstScrollIntoView = vi.fn(); + const secondScrollIntoView = vi.fn(); + Object.defineProperty(targets[0]!, "scrollIntoView", { + configurable: true, + value: firstScrollIntoView + }); + Object.defineProperty(targets[1]!, "scrollIntoView", { + configurable: true, + value: secondScrollIntoView + }); + + const actions = screen.getAllByRole("button", { + name: "Open Bass Guitar riff at 0:10" + }); + expect(actions).toHaveLength(2); + fireEvent.click(actions[1]!); + + expect(firstScrollIntoView).not.toHaveBeenCalled(); + expect(secondScrollIntoView).toHaveBeenCalledWith({ + block: "nearest", + behavior: "smooth" + }); + }); +}); diff --git a/apps/desktop/src/features/workspace/Workspace.test.tsx b/apps/desktop/src/features/workspace/Workspace.test.tsx index a3da5ffe6..480caa499 100644 --- a/apps/desktop/src/features/workspace/Workspace.test.tsx +++ b/apps/desktop/src/features/workspace/Workspace.test.tsx @@ -270,4 +270,34 @@ describe("Workspace", () => { expect(screen.getByText("합주 우선순위")).toBeTruthy(); expect(screen.getByText("역할과 화성")).toBeTruthy(); }); + + it("names tonight's first riff plan as workspace navigation", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + + render(); + + const target = screen.getByTestId("song-structure-grid").children.item(0); + expect(target).toBeTruthy(); + const scrollIntoView = vi.fn(); + Object.defineProperty(target!, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + + expect( + screen.getAllByText( + "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift." + ).length + ).toBeGreaterThan(0); + const action = screen.getByRole("button", { + name: "Open Bass Guitar riff at 0:10" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect( + screen.getByText(/Lock that riff on Bass Guitar at 0:10 before the room starts./) + ).toBeTruthy(); + }); }); diff --git a/apps/desktop/src/features/workspace/Workspace.tsx b/apps/desktop/src/features/workspace/Workspace.tsx index 71546b524..1bdfe2359 100644 --- a/apps/desktop/src/features/workspace/Workspace.tsx +++ b/apps/desktop/src/features/workspace/Workspace.tsx @@ -4,6 +4,7 @@ import { RoleSwitcher } from "./RoleSwitcher"; import { SectionRoadmap } from "./SectionRoadmap"; import { GrooveMap } from "./GrooveMap"; import { PracticeProgress } from "./PracticeProgress"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; import { createTranslator, detectPreferredLocale } from "../../i18n"; import { generateCueSheetCsv, generateChartSummaryJson, generateMetadataHandoffJson, sanitizeFilename } from "../../lib/export"; import { Button } from "@/components/ui/button"; @@ -90,8 +91,12 @@ const SongStructure = memo(function SongStructure({ sections, t }: { sections: R data-testid="song-structure-grid" style={{ gridTemplateColumns: `repeat(${Math.max(1, sections.length)}, minmax(8rem, 1fr))` }} > - {sections.map((section) => ( -
+ {sections.map((section, sectionIndex) => ( +

{section.label} · {formatTimelineTime(section.timeRange.start)}–{formatTimelineTime(section.timeRange.end)}

@@ -331,6 +336,8 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp
+ +
diff --git a/apps/desktop/src/features/workspace/coverageContract.test.ts b/apps/desktop/src/features/workspace/coverageContract.test.ts new file mode 100644 index 000000000..0b9e79e61 --- /dev/null +++ b/apps/desktop/src/features/workspace/coverageContract.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { DESKTOP_OWNED_PRODUCTION_COVERAGE } from "../../../vite.config"; + +describe("desktop owned production coverage", () => { + it("keeps the first riff-plan resolver and callout inside the coverage gate", () => { + expect(DESKTOP_OWNED_PRODUCTION_COVERAGE).toEqual( + expect.arrayContaining([ + "src/features/workspace/firstRiffPlan.ts", + "src/features/workspace/FirstRiffPlanCallout.tsx" + ]) + ); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.inherited-metadata.test.ts b/apps/desktop/src/features/workspace/firstRiffPlan.inherited-metadata.test.ts new file mode 100644 index 000000000..9c5b366fd --- /dev/null +++ b/apps/desktop/src/features/workspace/firstRiffPlan.inherited-metadata.test.ts @@ -0,0 +1,94 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstRiffPlan } from "./firstRiffPlan"; + +function songWithRiffPlan() { + const song = createDemoRehearsalSong(); + const section = structuredClone(song.sections[0]!); + section.id = "riff-own"; + section.roles = [ + { + ...section.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "high", + riffPlan: "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift." + } + ]; + section.partGraph = [{ role_id: "bass-guitar", is_active: true, handoff_to: [], handoff_from: [] }]; + song.sections = [section]; + return { song, section }; +} + +describe("resolveFirstRiffPlan inherited metadata", () => { + it("rejects a song or section whose required metadata is inherited", () => { + const { song, section } = songWithRiffPlan(); + const inheritedSong = Object.create({ sections: song.sections }) as typeof song; + expect(resolveFirstRiffPlan(inheritedSong)).toBeNull(); + + const inheritedSection = Object.create(section) as typeof section; + song.sections = [inheritedSection]; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("rejects inherited timing fields", () => { + const { song, section } = songWithRiffPlan(); + section.timeRange = Object.create({ start: 10, end: 30 }) as typeof section.timeRange; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("contains exceptions from own runtime accessors instead of trusting them", () => { + const { song, section } = songWithRiffPlan(); + Object.defineProperty(section.roles[0]!, "riffPlan", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile riffPlan getter"); + } + }); + + expect(() => resolveFirstRiffPlan(song)).not.toThrow(); + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("does not treat own accessors as stable riff-plan identity authority", () => { + const { song, section } = songWithRiffPlan(); + Object.defineProperty(section, "id", { + configurable: true, + enumerable: true, + get() { + return "riff-own"; + } + }); + + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("does not let inherited riff plans establish the named copy", () => { + const { song, section } = songWithRiffPlan(); + const inheritedRole = Object.create({ + riffPlan: "Inherited riff plan" + }) as (typeof section.roles)[0]; + Object.defineProperties(inheritedRole, { + id: { configurable: true, enumerable: true, value: "bass-guitar" }, + name: { configurable: true, enumerable: true, value: "Bass Guitar" }, + rehearsalPriority: { configurable: true, enumerable: true, value: "high" } + }); + section.roles = [inheritedRole]; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("does not let inherited role or graph metadata establish the holding part", () => { + const { song, section } = songWithRiffPlan(); + const node = section.partGraph[0]!; + section.partGraph = [Object.create(node) as typeof node]; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("rejects arrays masquerading as section records", () => { + const { song, section } = songWithRiffPlan(); + const arraySection = Object.assign([], section) as unknown as typeof section; + song.sections = [arraySection]; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts b/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts new file mode 100644 index 000000000..6b190b47c --- /dev/null +++ b/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts @@ -0,0 +1,31 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstRiffPlan } from "./firstRiffPlan"; + +const DEMO_RIFF_PLAN = + "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift."; + +describe("resolveFirstRiffPlan own-data authority", () => { + it("uses the snapshotted own-data riff plan instead of a Proxy get trap", () => { + const song = createDemoRehearsalSong(); + const section = song.sections.find((candidate) => candidate.id === "verse-1"); + const roleIndex = section?.roles.findIndex((role) => role.id === "bass-guitar") ?? -1; + const role = roleIndex >= 0 ? section?.roles[roleIndex] : undefined; + expect(section).toBeDefined(); + expect(role).toBeDefined(); + if (!section || !role || roleIndex < 0) { + throw new Error("Demo riff-plan fixture is missing the expected Bass Guitar role."); + } + + section.roles[roleIndex] = new Proxy(role, { + get(target, property, receiver) { + if (property === "riffPlan") { + return "Injected proxy riff."; + } + return Reflect.get(target, property, receiver); + } + }); + + expect(resolveFirstRiffPlan(song)?.riffPlan).toBe(DEMO_RIFF_PLAN); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.section-label.test.ts b/apps/desktop/src/features/workspace/firstRiffPlan.section-label.test.ts new file mode 100644 index 000000000..2cb251427 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstRiffPlan.section-label.test.ts @@ -0,0 +1,14 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstRiffPlan } from "./firstRiffPlan"; + +describe("resolveFirstRiffPlan section-label authority", () => { + it("fails closed when runtime metadata supplies a label outside the shared SectionFormLabel contract", () => { + const song = createDemoRehearsalSong(); + const section = song.sections[0]!; + + (section as unknown as { label: string }).label = "verse-legacy"; + + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.test.ts b/apps/desktop/src/features/workspace/firstRiffPlan.test.ts new file mode 100644 index 000000000..24a5458d4 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstRiffPlan.test.ts @@ -0,0 +1,286 @@ +import { describe, expect, it } from "vitest"; +import { MAX_SECTION_TIME_SECONDS, createDemoRehearsalSong } from "@bandscope/shared-types"; +import { formatRiffPlanTime, resolveFirstRiffPlan } from "./firstRiffPlan"; + +const DEMO_RIFF_PLAN = + "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift."; + +function withRiffSection( + overrides: { + id?: string; + start?: number; + end?: number; + riffPlan?: string; + label?: "intro" | "verse" | "pre-chorus" | "chorus" | "bridge" | "outro" | "tag" | "pickup" | "stop" | "handoff"; + roleId?: string; + roleName?: string; + priority?: "low" | "medium" | "high"; + isActive?: boolean; + functionLabel?: string; + } = {} +) { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const section = structuredClone(verse); + section.id = overrides.id ?? "verse-riff"; + section.label = overrides.label ?? "verse"; + section.groove = "Straight eighths with a late snare feel"; + section.timeRange = { start: overrides.start ?? 10, end: overrides.end ?? 30 }; + const roleId = overrides.roleId ?? "bass-guitar"; + section.roles = [ + { + ...verse.roles[0]!, + id: roleId, + name: overrides.roleName ?? "Bass Guitar", + rehearsalPriority: overrides.priority ?? "medium", + cue: { kind: "transition", value: "Hold through the pickup before the downbeat." }, + range: { lowestNote: "C#2", highestNote: "E3" }, + setupNote: "Keep the attack short so the verse breathes.", + simplification: "Stay on roots if the chorus entrance gets muddy.", + overlapWarnings: ["Density warning: competing with Keyboard Left Hand in low register."], + harmony: { + chord: "C#m7", + functionLabel: overrides.functionLabel ?? "vi pedal anchor", + source: "model" + }, + harmonicExplanation: + "The bass holds the vi center so the rest of the section can lean into the pickup without losing the tonal floor.", + confidence: { + level: "medium", + source: "model", + notes: "Watch the slide into the turnaround." + }, + riffPlan: overrides.riffPlan ?? DEMO_RIFF_PLAN, + manualOverrides: [] + } + ]; + section.partGraph = [ + { + role_id: roleId, + is_active: overrides.isActive ?? true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [section]; + return song; +} + +describe("resolveFirstRiffPlan", () => { + it("picks the demo song's earliest riff plan and the part that owns it", () => { + const resolved = resolveFirstRiffPlan(createDemoRehearsalSong()); + expect(resolved?.section.id).toBe("verse-1"); + expect(resolved?.holdingRole.id).toBe("bass-guitar"); + expect(resolved?.riffPlan).toBe(DEMO_RIFF_PLAN); + expect(resolved?.atSeconds).toBe(10); + expect(formatRiffPlanTime(resolved?.atSeconds ?? -1)).toBe("0:10"); + expect(formatRiffPlanTime(Number.NaN)).toBe("0:00"); + expect(formatRiffPlanTime(-4)).toBe("0:00"); + }); + + it("does not invent a riff plan from groove, cue, simplification, overlap, range, chords, function labels, setup notes, transposition plans, fill plans, tuning plans, dynamics plans, articulation plans, voicing plans, hook plans, capo plans, confirmed overrides, harmonic explanations, or confidence notes", () => { + const song = withRiffSection(); + delete song.sections[0]!.roles[0]!.riffPlan; + song.sections[0]!.groove = "Straight eighths with a late snare feel"; + song.sections[0]!.roles[0]!.simplification = "Stay on roots if the chorus entrance gets muddy."; + song.sections[0]!.roles[0]!.setupNote = DEMO_RIFF_PLAN; + song.sections[0]!.roles[0]!.transpositionPlan = + "If the singer drops to B minor, keep the shape a whole step lower."; + (song.sections[0]!.roles[0] as { fillPlan?: string }).fillPlan = + "Walk eight notes into the chorus downbeat; leave the vocal pickup empty."; + (song.sections[0]!.roles[0] as { tuningPlan?: string }).tuningPlan = + "Tune the E string down to D so the verse riff sits on the open fifth."; + (song.sections[0]!.roles[0] as { dynamicsPlan?: string }).dynamicsPlan = + "Keep the verse under the vocal so the chorus still has somewhere to lift."; + (song.sections[0]!.roles[0] as { articulationPlan?: string }).articulationPlan = + "Shorten the last chorus vowel so the band can hear the cutoff."; + (song.sections[0]!.roles[0] as { voicingPlan?: string }).voicingPlan = + "Keep the third out of the left hand so the bass owns the floor."; + (song.sections[0]!.roles[0] as { hookPlan?: string }).hookPlan = + "Lead vocal carries the chorus hook; lock the melody before anyone stacks harmony."; + (song.sections[0]!.roles[0] as { capoPlan?: string }).capoPlan = + "Capo 2 keeps the open-string riff under the singer."; + song.sections[0]!.roles[0]!.cue = { kind: "transition", value: "Hold through the pickup before the downbeat." }; + song.sections[0]!.roles[0]!.range = { lowestNote: "C#2", highestNote: "E3" }; + song.sections[0]!.roles[0]!.overlapWarnings = ["Density warning: competing with Keyboard Left Hand in low register."]; + song.sections[0]!.roles[0]!.harmony = { + chord: "C#m7", + functionLabel: "vi pedal anchor", + source: "user" + }; + song.sections[0]!.roles[0]!.harmonicExplanation = "The bass holds the vi center."; + song.sections[0]!.roles[0]!.manualOverrides = [ + { + field: "harmony", + value: { + chord: "C#m11", + functionLabel: "vi suspended lift", + source: "user" + }, + source: "user" + } + ]; + song.sections[0]!.roles[0]!.confidence = { + level: "high", + source: "user", + notes: DEMO_RIFF_PLAN + }; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("skips a blank riff plan", () => { + expect(resolveFirstRiffPlan(withRiffSection({ riffPlan: " " }))).toBeNull(); + }); + + it("skips a multi-line riff plan", () => { + expect( + resolveFirstRiffPlan(withRiffSection({ riffPlan: "Keep the riff centered.\nLeave the stack." })) + ).toBeNull(); + }); + + it("prefers the earlier of two riff plans", () => { + const song = withRiffSection({ + id: "verse-late", + start: 40, + end: 56, + roleId: "keys-right", + riffPlan: "Late riff." + }); + const earlier = structuredClone(song.sections[0]!); + earlier.id = "verse-early"; + earlier.roles = [ + { + ...earlier.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "low", + riffPlan: "Earlier riff." + } + ]; + earlier.timeRange = { start: 8, end: 24 }; + earlier.partGraph = [{ role_id: "bass-guitar", is_active: true, handoff_to: [], handoff_from: [] }]; + song.sections = [song.sections[0]!, earlier]; + + const resolved = resolveFirstRiffPlan(song); + expect(resolved?.section.id).toBe("verse-early"); + expect(resolved?.holdingRole.id).toBe("bass-guitar"); + expect(resolved?.riffPlan).toBe("Earlier riff."); + expect(resolved?.atSeconds).toBe(8); + }); + + it("breaks same-time riff-plan ties with locale-independent id ordering", () => { + const song = withRiffSection({ id: "ä-riff", start: 10, end: 26 }); + const ascii = structuredClone(song.sections[0]!); + ascii.id = "z-riff"; + song.sections = [song.sections[0]!, ascii]; + + expect(resolveFirstRiffPlan(song)?.section.id).toBe("z-riff"); + }); + + it("prefers a high-priority riff part over a low-priority part in the same section", () => { + const song = withRiffSection({ + roleId: "keys-right", + roleName: "Keys", + priority: "low", + riffPlan: "Low-priority riff." + }); + const section = song.sections[0]!; + const highRole = { + ...section.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "high" as const, + riffPlan: "High-priority riff." + }; + section.roles = [section.roles[0]!, highRole]; + section.partGraph = [ + { role_id: "keys-right", is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: "bass-guitar", is_active: true, handoff_to: [], handoff_from: [] } + ]; + + expect(resolveFirstRiffPlan(song)?.holdingRole.id).toBe("bass-guitar"); + expect(resolveFirstRiffPlan(song)?.riffPlan).toBe("High-priority riff."); + }); + + it("breaks equal-priority role ties with locale-independent id ordering", () => { + const song = withRiffSection({ roleId: "ä-role", roleName: "Umlaut role", priority: "high" }); + const section = song.sections[0]!; + const asciiRole = { + ...section.roles[0]!, + id: "z-role", + name: "ASCII role", + riffPlan: "ASCII riff." + }; + section.roles = [section.roles[0]!, asciiRole]; + section.partGraph = [ + { role_id: "ä-role", is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: "z-role", is_active: true, handoff_to: [], handoff_from: [] } + ]; + + expect(resolveFirstRiffPlan(song)?.holdingRole.id).toBe("z-role"); + expect(resolveFirstRiffPlan(song)?.riffPlan).toBe("ASCII riff."); + }); + + it("skips a riff plan whose graph node is inactive", () => { + expect(resolveFirstRiffPlan(withRiffSection({ isActive: false }))).toBeNull(); + }); + + it("skips a riff plan whose rehearsal window is unbounded", () => { + expect(resolveFirstRiffPlan(withRiffSection({ start: Number.NaN, end: 30 }))).toBeNull(); + }); + + it("skips a riff plan whose end precedes its start", () => { + expect(resolveFirstRiffPlan(withRiffSection({ start: 30, end: 10 }))).toBeNull(); + }); + + it("skips a zero-length riff-plan window", () => { + expect(resolveFirstRiffPlan(withRiffSection({ start: 10, end: 10 }))).toBeNull(); + }); + + it("skips a riff plan whose endpoint overflows the shared timing bound", () => { + expect( + resolveFirstRiffPlan( + withRiffSection({ + start: MAX_SECTION_TIME_SECONDS, + end: MAX_SECTION_TIME_SECONDS + 1 + }) + ) + ).toBeNull(); + }); + + it("returns null for a non-object song root", () => { + expect(resolveFirstRiffPlan(null as never)).toBeNull(); + }); + + it("returns null when the runtime section collection is sparse", () => { + const song = withRiffSection(); + const sparseSections: typeof song.sections = new Array(2); + sparseSections[1] = song.sections[0]!; + song.sections = sparseSections; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("keeps the riff plan unnamed when role identities are duplicated", () => { + const song = withRiffSection(); + const role = song.sections[0]!.roles[0]!; + song.sections[0]!.roles = [role, { ...role }]; + song.sections[0]!.partGraph = [ + { role_id: role.id, is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: role.id, is_active: true, handoff_to: [], handoff_from: [] } + ]; + expect(resolveFirstRiffPlan(song)).toBeNull(); + }); + + it("bounds the riff plan to 180 Unicode code points", () => { + const song = withRiffSection({ riffPlan: `${"G".repeat(200)}` }); + const resolved = resolveFirstRiffPlan(song); + expect(resolved?.riffPlan.length).toBe(180); + }); + + it("does not split a Unicode surrogate pair at the riff-plan boundary", () => { + const song = withRiffSection({ riffPlan: `${"a".repeat(179)}😀tail` }); + const resolved = resolveFirstRiffPlan(song); + expect(Array.from(resolved?.riffPlan ?? "")).toHaveLength(180); + expect(resolved?.riffPlan.endsWith("😀")).toBe(true); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.ts b/apps/desktop/src/features/workspace/firstRiffPlan.ts new file mode 100644 index 000000000..378cbc900 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstRiffPlan.ts @@ -0,0 +1,287 @@ +import { + MAX_SECTION_TIME_SECONDS, + SECTION_FORM_LABELS, + type RehearsalRole, + type RehearsalSection, + type RehearsalSong +} from "@bandscope/shared-types"; + +const PRIORITY_RANK = { high: 0, medium: 1, low: 2 } as const; +const MAX_RIFF_PLAN_CHARACTERS = 180; +const SECTION_FORM_LABEL_SET = new Set(SECTION_FORM_LABELS); + +/** Tonight's first riff plan: the earliest labeled section and the part that owns it. */ +export type FirstRiffPlan = { + section: RehearsalSection; + holdingRole: RehearsalRole; + riffPlan: string; + atSeconds: number; +}; + +/** Format a non-negative riff-plan time as m:ss for rehearsal copy. */ +export function formatRiffPlanTime(totalSeconds: number): string { + const safeSeconds = Number.isFinite(totalSeconds) && totalSeconds >= 0 ? totalSeconds : 0; + const minutes = Math.floor(safeSeconds / 60); + const seconds = Math.floor(safeSeconds % 60) + .toString() + .padStart(2, "0"); + return `${minutes}:${seconds}`; +} + +/** Compare opaque ids by Unicode code units so tie-breaking never depends on host locale. */ +function compareStableId(left: string, right: string): number { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} + +/** Return whether an untrusted runtime value can be inspected as a record. */ +function isRuntimeObject(value: unknown): value is object { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** Return whether a runtime record owns a stable data property rather than inherited/accessor state. */ +function hasOwnData(value: object, key: PropertyKey): boolean { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return descriptor !== undefined && Object.prototype.hasOwnProperty.call(descriptor, "value"); +} + +/** Return whether every numeric index is an own data element in a bounded runtime array. */ +function isDenseRuntimeArray(value: unknown): value is unknown[] { + if (!Array.isArray(value)) { + return false; + } + const length = Number(value.length); + if (!Number.isSafeInteger(length) || length < 0 || length > 0xffffffff) { + return false; + } + for (let index = 0; index < length; index += 1) { + if (!hasOwnData(value, index)) { + return false; + } + } + return true; +} + +/** Bound buyer-visible text by Unicode code points without splitting a surrogate pair. */ +function truncateCodePoints(value: string, maximum: number): string { + let codePoints = 0; + let endIndex = 0; + for (const character of value) { + if (codePoints >= maximum) { + break; + } + endIndex += character.length; + codePoints += 1; + } + return endIndex === value.length ? value : value.slice(0, endIndex); +} + +/** Return a bounded snapshotted own riff plan, or null when it cannot be shown. */ +function ownedRiffPlan(role: unknown): string | null { + if (!isRuntimeObject(role)) { + return null; + } + const descriptor = Object.getOwnPropertyDescriptor(role, "riffPlan"); + if (descriptor === undefined || !Object.prototype.hasOwnProperty.call(descriptor, "value")) { + return null; + } + const riffPlan = descriptor.value; + if (typeof riffPlan !== "string") { + return null; + } + const trimmed = riffPlan.trim(); + if (trimmed.length === 0 || trimmed.includes("\n") || trimmed.includes("\r")) { + return null; + } + return truncateCodePoints(trimmed, MAX_RIFF_PLAN_CHARACTERS); +} + +/** Return true when the role has safe owned identity/copy and ranked rehearsal priority. */ +function hasRankedPriority(role: RehearsalRole): boolean { + return ( + hasOwnData(role, "id") && + typeof role.id === "string" && + role.id.trim().length > 0 && + hasOwnData(role, "name") && + typeof role.name === "string" && + role.name.trim().length > 0 && + hasOwnData(role, "rehearsalPriority") && + Object.prototype.hasOwnProperty.call(PRIORITY_RANK, role.rehearsalPriority) + ); +} + +/** Return whether a section owns a canonical form label from the shared contract. */ +function hasSupportedSectionLabel(section: RehearsalSection): boolean { + return ( + hasOwnData(section, "label") && + typeof section.label === "string" && + SECTION_FORM_LABEL_SET.has(section.label) + ); +} + +/** Return whether a section owns a bounded, positive-length integer rehearsal window. */ +function hasBoundedTimeRange(section: RehearsalSection): boolean { + if (!hasOwnData(section, "timeRange")) { + return false; + } + const timeRange = section.timeRange as Partial | null; + if (!isRuntimeObject(timeRange) || !hasOwnData(timeRange, "start") || !hasOwnData(timeRange, "end")) { + return false; + } + + const start = timeRange.start ?? -1; + const end = timeRange.end ?? -1; + return ( + Number.isInteger(start) && + start >= 0 && + start <= MAX_SECTION_TIME_SECONDS && + Number.isInteger(end) && + end > start && + end <= MAX_SECTION_TIME_SECONDS + ); +} + +/** Return safe identities that appear more than once in one section-local collection. */ +function repeatedIds(ids: string[]): Set { + const seen = new Set(); + const repeated = new Set(); + for (const id of ids) { + if (seen.has(id)) { + repeated.add(id); + } else { + seen.add(id); + } + } + return repeated; +} + +/** Prefer the earlier ranked role, then rehearsal priority, then a locale-independent id. */ +function pickHoldingRole(roles: RehearsalRole[]): RehearsalRole | null { + if (roles.length === 0) { + return null; + } + return ( + [...roles].sort((left, right) => { + const priorityDelta = PRIORITY_RANK[left.rehearsalPriority] - PRIORITY_RANK[right.rehearsalPriority]; + if (priorityDelta !== 0) { + return priorityDelta; + } + return compareStableId(left.id, right.id); + })[0] ?? null + ); +} + +/** Return ranked roles whose unique graph node is explicitly active. */ +function rankedActiveRoles(section: RehearsalSection): RehearsalRole[] { + if ( + !hasOwnData(section, "roles") || + !hasOwnData(section, "partGraph") || + !isDenseRuntimeArray(section.roles) || + !isDenseRuntimeArray(section.partGraph) + ) { + return []; + } + + const safeRoleIds = section.roles + .filter( + (role) => + isRuntimeObject(role) && + hasOwnData(role, "id") && + typeof role.id === "string" && + role.id.trim().length > 0 + ) + .map((role) => role.id); + const safeGraphRoleIds = section.partGraph + .filter( + (node) => + isRuntimeObject(node) && + hasOwnData(node, "role_id") && + typeof node.role_id === "string" && + node.role_id.trim().length > 0 + ) + .map((node) => node.role_id); + const repeatedRoleIds = repeatedIds(safeRoleIds); + const repeatedGraphRoleIds = repeatedIds(safeGraphRoleIds); + const activeIds = new Set( + section.partGraph + .filter( + (node) => + isRuntimeObject(node) && + hasOwnData(node, "is_active") && + node.is_active === true && + hasOwnData(node, "role_id") && + typeof node.role_id === "string" && + node.role_id.trim().length > 0 && + !repeatedGraphRoleIds.has(node.role_id) + ) + .map((node) => node.role_id) + ); + + return section.roles.filter( + (role) => + isRuntimeObject(role) && + hasRankedPriority(role) && + !repeatedRoleIds.has(role.id) && + activeIds.has(role.id) + ); +} + +/** Resolve a riff plan after the runtime root has passed its structural boundary checks. */ +function resolveSafeFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { + if (!isRuntimeObject(song) || !hasOwnData(song, "sections") || !isDenseRuntimeArray(song.sections)) { + return null; + } + + const candidates = song.sections + .filter( + (section) => + isRuntimeObject(section) && + hasSupportedSectionLabel(section) && + hasOwnData(section, "id") && + typeof section.id === "string" && + section.id.trim().length > 0 && + hasBoundedTimeRange(section) + ) + .flatMap((section) => { + const holdingRole = pickHoldingRole( + rankedActiveRoles(section).filter((role) => ownedRiffPlan(role) !== null) + ); + if (!holdingRole) { + return []; + } + const riffPlan = ownedRiffPlan(holdingRole); + if (!riffPlan) { + return []; + } + return [ + { + section, + holdingRole, + riffPlan, + atSeconds: section.timeRange.start + } + ]; + }) + .sort((left, right) => { + if (left.atSeconds !== right.atSeconds) { + return left.atSeconds - right.atSeconds; + } + return compareStableId(left.section.id, right.section.id); + }); + + return candidates[0] ?? null; +} + +/** Return the first named riff plan, or null when untrusted runtime metadata cannot be read safely. */ +export function resolveFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { + try { + return resolveSafeFirstRiffPlan(song); + } catch { + return null; + } +} diff --git a/apps/desktop/src/i18n/index.test.ts b/apps/desktop/src/i18n/index.test.ts index dc49a0a25..dbc383305 100644 --- a/apps/desktop/src/i18n/index.test.ts +++ b/apps/desktop/src/i18n/index.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, afterEach } from "vitest"; -import { createTranslator, detectPreferredLocale } from "./index"; +import { createTranslator, detectPreferredLocale, translateSectionFormLabel } from "./index"; import koCommon from "../locales/ko/common.json"; describe("i18n", () => { @@ -75,4 +75,52 @@ describe("i18n", () => { } }); }); + + describe("translateSectionFormLabel", () => { + it("localizes every supported Korean section form label", () => { + expect( + [ + "intro", + "verse", + "pre-chorus", + "chorus", + "bridge", + "outro", + "tag", + "pickup", + "stop", + "handoff" + ].map((label) => translateSectionFormLabel("ko", label as never)) + ).toEqual([ + "인트로", + "벌스", + "프리코러스", + "코러스", + "브리지", + "아웃트로", + "태그", + "픽업", + "스톱", + "핸드오프" + ]); + }); + + it("preserves every supported English section form label", () => { + expect(translateSectionFormLabel("en", "verse")).toBe("verse"); + expect(translateSectionFormLabel("en", "pre-chorus")).toBe("pre-chorus"); + }); + + it("does not read inherited Object keys as section labels", () => { + const inheritedKey = "toString" as never; + expect(translateSectionFormLabel("en", inheritedKey)).toBe("toString"); + expect(translateSectionFormLabel("ko", inheritedKey)).toBe("toString"); + }); + + it("keeps Korean first-riff-plan next-action copy particle-safe", () => { + const t = createTranslator("ko"); + expect(t("firstRiffPlanOpenAction")).toBe("{at} {role} 리프 열기"); + expect(t("firstRiffPlanBody")).toBe("{at} {section}에서 {role} 파트의 리프 계획이 있습니다."); + expect(t("firstRiffPlanArmed")).toBe("{at}에서 {role} 파트의 리프를 맞춘 다음 합주를 시작하세요."); + }); + }); }); diff --git a/apps/desktop/src/i18n/index.ts b/apps/desktop/src/i18n/index.ts index 1a9f471f0..f5656ce01 100644 --- a/apps/desktop/src/i18n/index.ts +++ b/apps/desktop/src/i18n/index.ts @@ -1,3 +1,4 @@ +import type { SectionFormLabel } from "@bandscope/shared-types"; import enCommon from "../locales/en/common.json"; import koCommon from "../locales/ko/common.json"; @@ -11,13 +12,46 @@ const dictionaries = { ko: koCommon } as const; -/** Documented. */ +const sectionFormLabels: Readonly>>> = { + en: { + intro: "intro", + verse: "verse", + "pre-chorus": "pre-chorus", + chorus: "chorus", + bridge: "bridge", + outro: "outro", + tag: "tag", + pickup: "pickup", + stop: "stop", + handoff: "handoff" + }, + ko: { + intro: "인트로", + verse: "벌스", + "pre-chorus": "프리코러스", + chorus: "코러스", + bridge: "브리지", + outro: "아웃트로", + tag: "태그", + pickup: "픽업", + stop: "스톱", + handoff: "핸드오프" + } +}; + +/** Create a translator for the requested locale, falling back to the English dictionary for missing entries. */ export function createTranslator(locale: Locale = "en") { return function t(key: TranslationKey): string { return dictionaries[locale][key] ?? dictionaries.en[key]; }; } +/** Return the localized display label for a supported rehearsal section form. */ +export function translateSectionFormLabel(locale: Locale, label: SectionFormLabel): string { + const labels = sectionFormLabels[locale] as Readonly>; + return Object.prototype.hasOwnProperty.call(labels, label) ? labels[label] : String(label); +} + /** Documented. */ export function detectPreferredLocale(): Locale { if (typeof navigator !== "undefined" && navigator.language?.toLowerCase().startsWith("ko")) { diff --git a/apps/desktop/src/locales/en/common.json b/apps/desktop/src/locales/en/common.json index 39f716d50..2f290202c 100644 --- a/apps/desktop/src/locales/en/common.json +++ b/apps/desktop/src/locales/en/common.json @@ -148,5 +148,10 @@ "practiceProgressRegionLabel": "Practice Progress", "practiceProgressLabel": "Practice Progress", "decreasePracticeProgressLabel": "Decrease progress", - "increasePracticeProgressLabel": "Increase progress" + "increasePracticeProgressLabel": "Increase progress", + "firstRiffPlanLabel": "Tonight's first riff plan", + "firstRiffPlanOpenAction": "Open {role} riff at {at}", + "firstRiffPlanBody": "{role} still has a riff plan in the {section} at {at}.", + "firstRiffPlanArmed": "Lock that riff on {role} at {at} before the room starts.", + "firstRiffPlanUnavailable": "No riff plan is available. Stay on tonight's map for the next rehearsal cue." } diff --git a/apps/desktop/src/locales/ko/common.json b/apps/desktop/src/locales/ko/common.json index 371884abb..884189a54 100644 --- a/apps/desktop/src/locales/ko/common.json +++ b/apps/desktop/src/locales/ko/common.json @@ -148,5 +148,10 @@ "practiceProgressRegionLabel": "연습 진척도", "practiceProgressLabel": "연습 진척도", "decreasePracticeProgressLabel": "진척도 감소", - "increasePracticeProgressLabel": "진척도 증가" + "increasePracticeProgressLabel": "진척도 증가", + "firstRiffPlanLabel": "오늘 첫 리프 계획", + "firstRiffPlanOpenAction": "{at} {role} 리프 열기", + "firstRiffPlanBody": "{at} {section}에서 {role} 파트의 리프 계획이 있습니다.", + "firstRiffPlanArmed": "{at}에서 {role} 파트의 리프를 맞춘 다음 합주를 시작하세요.", + "firstRiffPlanUnavailable": "사용 가능한 리프 계획이 없습니다. 다음 합주 큐를 위해 오늘 맵에 머무르세요." } diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index f1db6f2b8..b7003090f 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -6,6 +6,18 @@ import { fileURLToPath } from "node:url"; const configDirectory = path.dirname(fileURLToPath(import.meta.url)); +/** Production files whose V8 coverage is owned by the desktop test gate. */ +export const DESKTOP_OWNED_PRODUCTION_COVERAGE = [ + "src/App.tsx", + "src/lib/export.ts", + "src/i18n/index.ts", + "src/features/score/ScoreViewer.tsx", + "src/features/score/ScoreView.tsx", + "src/features/score/scoreStorage.ts", + "src/features/workspace/firstRiffPlan.ts", + "src/features/workspace/FirstRiffPlanCallout.tsx" +]; + export default defineConfig({ plugins: [react(), tailwindcss()], resolve: { @@ -19,14 +31,7 @@ export default defineConfig({ setupFiles: ["./src/setupTests.ts"], coverage: { provider: "v8", - include: [ - "src/App.tsx", - "src/lib/export.ts", - "src/i18n/index.ts", - "src/features/score/ScoreViewer.tsx", - "src/features/score/ScoreView.tsx", - "src/features/score/scoreStorage.ts" - ], + include: DESKTOP_OWNED_PRODUCTION_COVERAGE, thresholds: { lines: 90, functions: 90, diff --git a/docs/design-system/component-contract.md b/docs/design-system/component-contract.md index 22602c313..5050b12f6 100644 --- a/docs/design-system/component-contract.md +++ b/docs/design-system/component-contract.md @@ -30,6 +30,7 @@ The authoritative Figma view is `31 Component Contract Catalog`. This file mirro | Status Pill | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-283 | `apps/desktop/src/features/workspace/Workspace.tsx` | Design pattern only. Current code uses `formatStatusLabel(status)` inside local badge-like markup. | | Role Switcher | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-337 | `apps/desktop/src/features/workspace/RoleSwitcher.tsx` | Use `roles`, `activeRole`, and `onRoleChange`; `null` means all roles. | | Section Roadmap Card | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-402 | `apps/desktop/src/features/workspace/SectionRoadmap.tsx` | Use `song`, `activeRole`, and optional `onSongUpdate`; avoid rebuilding its internal card layout. | +| First Riff Plan Callout | workspace next-action pattern | `apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx` | Name the owning part when an active graph node corroborates it, the owned `riffPlan` copy, the labeled section start, and the time. Do not invent that copy from `groove`, cue text, `simplification`, overlap warnings, range copy, `harmony.chord`, `harmony.functionLabel`, `setupNote`, `transpositionPlan`, `fillPlan`, `tuningPlan`, `dynamicsPlan`, `articulationPlan`, `voicingPlan`, `hookPlan`, `capoPlan`, confirmed overrides, `harmonicExplanation`, or confidence notes. Open scrolls the renderer-owned song-structure section. Keep the unavailable state guidance-only. Distinct from first-hook-plan, first-fill-plan, first-setup-note, first-transposition-plan, first-tuning-plan, first-dynamics-plan, first-articulation-plan, first-voicing-plan, and first-capo-plan. | | Song Structure Timeline | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-457 | `apps/desktop/src/features/workspace/Workspace.tsx` | Feature-local `SongStructure({ sections, t })` memo component; not exported. | | Groove Map | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-526 | `apps/desktop/src/features/workspace/GrooveMap.tsx` | Use `notes?: TranscriptionNote[]` and `isLoading?: boolean`; preserve scrollable region semantics and note labels. | | Source Control Stack | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-655 | `apps/desktop/src/App.tsx` | Feature-local source controls for local audio, YouTube URL import, project actions, and Start Analysis; keep before metrics at 375px. | diff --git a/docs/doctoring/reduced-motion-first-riff-plan-navigation.md b/docs/doctoring/reduced-motion-first-riff-plan-navigation.md new file mode 100644 index 000000000..ebf36a568 --- /dev/null +++ b/docs/doctoring/reduced-motion-first-riff-plan-navigation.md @@ -0,0 +1,3 @@ +# Reduced-motion first riff-plan navigation + +Open tonight's first riff plan with `behavior: "auto"` when `prefers-reduced-motion: reduce` matches. Do not keep a smooth scroll for that next action. diff --git a/packages/shared-types/src/index.ts b/packages/shared-types/src/index.ts index cba4606a2..e7f77d58e 100644 --- a/packages/shared-types/src/index.ts +++ b/packages/shared-types/src/index.ts @@ -139,6 +139,7 @@ export type RehearsalRole = { simplification: string; setupNote: string; transpositionPlan?: string; + riffPlan?: string; manualOverrides: ManualOverride[]; overlapWarnings: string[]; transcription?: TranscriptionNote[]; @@ -473,6 +474,7 @@ const demoRehearsalSongSeed: RehearsalSong = { rehearsalPriority: "high", simplification: "Stay on roots if the chorus entrance gets muddy.", setupNote: "Keep the attack short so the verse breathes.", + riffPlan: "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift.", transpositionPlan: "If the singer drops to B minor, keep the shape a whole step lower and let keys keep the color tones.", manualOverrides: [], overlapWarnings: [ @@ -1497,6 +1499,7 @@ function validateRehearsalRole(value: unknown, path: string): string | null { "simplification", "setupNote", "transpositionPlan", + "riffPlan", "manualOverrides", "overlapWarnings", "transcription", @@ -1552,6 +1555,9 @@ function validateRehearsalRole(value: unknown, path: string): string | null { if (value.transpositionPlan !== undefined && typeof value.transpositionPlan !== "string") { return invalidField(`${path}.transpositionPlan`); } + if (value.riffPlan !== undefined && typeof value.riffPlan !== "string") { + return invalidField(`${path}.riffPlan`); + } if (!isDenseArray(value.manualOverrides)) { return invalidField(`${path}.manualOverrides`); } diff --git a/packages/shared-types/test/index.test.ts b/packages/shared-types/test/index.test.ts index 564ee1827..b67c953ca 100644 --- a/packages/shared-types/test/index.test.ts +++ b/packages/shared-types/test/index.test.ts @@ -738,6 +738,7 @@ describe("shared type helpers", () => { expect(song.sections[0]?.roles[2]?.harmony?.source).toBe("model"); expect(song.sections[0]?.roles[0]?.harmonicExplanation).toContain("tonal floor"); expect(song.sections[0]?.roles[0]?.transpositionPlan).toContain("whole step lower"); + expect(song.sections[0]?.roles[0]?.riffPlan).toContain("verse riff"); expect(song.collaboration?.assignments).toHaveLength(2); expect(song.collaboration?.comments[0]?.status).toBe("open"); expect(song.sections[0]?.roles[2]?.manualOverrides?.[0]).toMatchObject({ @@ -1257,6 +1258,12 @@ describe("shared type helpers", () => { song.sections[0]!.roles[0]!.transpositionPlan = 2 as never; }) }, + { + message: "sections[0].roles[0].riffPlan", + payload: createInvalidSong((song) => { + song.sections[0]!.roles[0]!.riffPlan = 2 as never; + }) + }, { message: "sections[0].roles[0].practiceProgress", payload: createInvalidSong((song) => { From b886a5f966c1a05dd7c0f5f80295b0cedeaefbb8 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 09:11:59 -0700 Subject: [PATCH 2/7] test(workspace): reject riff-plan root proxy reread --- .../FirstRiffPlanCallout.proxy-root.test.tsx | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 apps/desktop/src/features/workspace/FirstRiffPlanCallout.proxy-root.test.tsx diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.proxy-root.test.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.proxy-root.test.tsx new file mode 100644 index 000000000..41f40ac08 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.proxy-root.test.tsx @@ -0,0 +1,27 @@ +import { render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { expect, it } from "vitest"; +import { FirstRiffPlanCallout } from "./FirstRiffPlanCallout"; + +it("does not re-read root sections through a Proxy get trap after resolving the riff plan", () => { + const source = createDemoRehearsalSong(); + let sectionReads = 0; + const song = new Proxy(source, { + get(target, property, receiver) { + if (property === "sections") { + sectionReads += 1; + if (sectionReads > 2) { + throw new Error("root sections were re-read after resolver validation"); + } + } + return Reflect.get(target, property, receiver); + } + }); + + expect(() => render()).not.toThrow(); + expect( + screen.getByText( + "Bass locks the verse riff on the open fifth; keep it dry before the chorus lift." + ) + ).toBeTruthy(); +}); From 624422ceb017f79a253a8eafc6d0d42f80b88918 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 09:14:30 -0700 Subject: [PATCH 3/7] fix(workspace): snapshot riff-plan section authority --- .../src/features/workspace/firstRiffPlan.ts | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.ts b/apps/desktop/src/features/workspace/firstRiffPlan.ts index 378cbc900..cfdf5cfc7 100644 --- a/apps/desktop/src/features/workspace/firstRiffPlan.ts +++ b/apps/desktop/src/features/workspace/firstRiffPlan.ts @@ -13,6 +13,7 @@ const SECTION_FORM_LABEL_SET = new Set(SECTION_FORM_LABELS); /** Tonight's first riff plan: the earliest labeled section and the part that owns it. */ export type FirstRiffPlan = { section: RehearsalSection; + sectionIndex: number; holdingRole: RehearsalRole; riffPlan: string; atSeconds: number; @@ -50,6 +51,14 @@ function hasOwnData(value: object, key: PropertyKey): boolean { return descriptor !== undefined && Object.prototype.hasOwnProperty.call(descriptor, "value"); } +/** Snapshot one owned data-property value without invoking a getter or Proxy get trap. */ +function ownDataValue(value: object, key: PropertyKey): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return descriptor !== undefined && Object.prototype.hasOwnProperty.call(descriptor, "value") + ? descriptor.value + : undefined; +} + /** Return whether every numeric index is an own data element in a bounded runtime array. */ function isDenseRuntimeArray(value: unknown): value is unknown[] { if (!Array.isArray(value)) { @@ -233,13 +242,19 @@ function rankedActiveRoles(section: RehearsalSection): RehearsalRole[] { /** Resolve a riff plan after the runtime root has passed its structural boundary checks. */ function resolveSafeFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { - if (!isRuntimeObject(song) || !hasOwnData(song, "sections") || !isDenseRuntimeArray(song.sections)) { + if (!isRuntimeObject(song)) { + return null; + } + const sectionsValue = ownDataValue(song, "sections"); + if (!isDenseRuntimeArray(sectionsValue)) { return null; } + const sections = sectionsValue as RehearsalSection[]; - const candidates = song.sections + const candidates = sections + .map((section, sectionIndex) => ({ section, sectionIndex })) .filter( - (section) => + ({ section }) => isRuntimeObject(section) && hasSupportedSectionLabel(section) && hasOwnData(section, "id") && @@ -247,7 +262,7 @@ function resolveSafeFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { section.id.trim().length > 0 && hasBoundedTimeRange(section) ) - .flatMap((section) => { + .flatMap(({ section, sectionIndex }) => { const holdingRole = pickHoldingRole( rankedActiveRoles(section).filter((role) => ownedRiffPlan(role) !== null) ); @@ -261,6 +276,7 @@ function resolveSafeFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { return [ { section, + sectionIndex, holdingRole, riffPlan, atSeconds: section.timeRange.start From 888c9489ddd3b0d4775c1dd1924a2ef03d6eacd0 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 09:15:20 -0700 Subject: [PATCH 4/7] fix(workspace): reuse validated riff-plan section index --- .../desktop/src/features/workspace/FirstRiffPlanCallout.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx index 8c9ad09e2..b1a7a49bf 100644 --- a/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx +++ b/apps/desktop/src/features/workspace/FirstRiffPlanCallout.tsx @@ -81,12 +81,8 @@ export function FirstRiffPlanCallout({ song }: FirstRiffPlanCalloutProps) { const locale = detectPreferredLocale(); const t = createTranslator(locale); const songIdentity = stableRiffPlanSongIdentity(song); - const runtimeSong = song as unknown as Partial | null; const named = useMemo(() => resolveFirstRiffPlan(song), [song]); - const namedSectionIndex = - named && Array.isArray(runtimeSong?.sections) - ? runtimeSong.sections.indexOf(named.section) - : -1; + const namedSectionIndex = named?.sectionIndex ?? -1; const [openedRiffPlan, setOpenedRiffPlan] = useState(null); useEffect(() => { From d912bceaafa632b2f1f0b48324e0f2f1ed6d6e3c Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 09:43:53 -0700 Subject: [PATCH 5/7] test(workspace): lock riff time-range descriptor authority --- .../firstRiffPlan.proxy-authority.test.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts b/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts index 6b190b47c..4780bc207 100644 --- a/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts +++ b/apps/desktop/src/features/workspace/firstRiffPlan.proxy-authority.test.ts @@ -28,4 +28,25 @@ describe("resolveFirstRiffPlan own-data authority", () => { expect(resolveFirstRiffPlan(song)?.riffPlan).toBe(DEMO_RIFF_PLAN); }); + + it("uses snapshotted time-range data instead of a Proxy get trap", () => { + const song = createDemoRehearsalSong(); + const section = song.sections.find((candidate) => candidate.id === "verse-1"); + expect(section).toBeDefined(); + if (!section) { + throw new Error("Demo riff-plan fixture is missing the expected verse section."); + } + + const trustedTimeRange = section.timeRange; + section.timeRange = new Proxy(trustedTimeRange, { + get(target, property, receiver) { + if (property === "start") { + return 20; + } + return Reflect.get(target, property, receiver); + } + }); + + expect(resolveFirstRiffPlan(song)?.atSeconds).toBe(10); + }); }); From ac85cef05f6d6844caaba2a024ad08f396775a86 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 09:45:03 -0700 Subject: [PATCH 6/7] fix(workspace): snapshot riff time-range authority --- .../src/features/workspace/firstRiffPlan.ts | 56 +++++++++++-------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.ts b/apps/desktop/src/features/workspace/firstRiffPlan.ts index cfdf5cfc7..d14dd2e46 100644 --- a/apps/desktop/src/features/workspace/firstRiffPlan.ts +++ b/apps/desktop/src/features/workspace/firstRiffPlan.ts @@ -133,26 +133,31 @@ function hasSupportedSectionLabel(section: RehearsalSection): boolean { ); } -/** Return whether a section owns a bounded, positive-length integer rehearsal window. */ -function hasBoundedTimeRange(section: RehearsalSection): boolean { - if (!hasOwnData(section, "timeRange")) { - return false; +/** Snapshot a section's bounded positive-length integer rehearsal window. */ +function ownedBoundedTimeRange( + section: RehearsalSection +): RehearsalSection["timeRange"] | null { + const timeRange = ownDataValue(section, "timeRange"); + if (!isRuntimeObject(timeRange)) { + return null; } - const timeRange = section.timeRange as Partial | null; - if (!isRuntimeObject(timeRange) || !hasOwnData(timeRange, "start") || !hasOwnData(timeRange, "end")) { - return false; + + const start = ownDataValue(timeRange, "start"); + const end = ownDataValue(timeRange, "end"); + if ( + !Number.isInteger(start) || + typeof start !== "number" || + start < 0 || + start > MAX_SECTION_TIME_SECONDS || + !Number.isInteger(end) || + typeof end !== "number" || + end <= start || + end > MAX_SECTION_TIME_SECONDS + ) { + return null; } - const start = timeRange.start ?? -1; - const end = timeRange.end ?? -1; - return ( - Number.isInteger(start) && - start >= 0 && - start <= MAX_SECTION_TIME_SECONDS && - Number.isInteger(end) && - end > start && - end <= MAX_SECTION_TIME_SECONDS - ); + return { start, end }; } /** Return safe identities that appear more than once in one section-local collection. */ @@ -252,17 +257,24 @@ function resolveSafeFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { const sections = sectionsValue as RehearsalSection[]; const candidates = sections - .map((section, sectionIndex) => ({ section, sectionIndex })) + .map((section, sectionIndex) => ({ + section, + sectionIndex, + timeRange: isRuntimeObject(section) ? ownedBoundedTimeRange(section) : null + })) .filter( - ({ section }) => + ({ section, timeRange }) => isRuntimeObject(section) && hasSupportedSectionLabel(section) && hasOwnData(section, "id") && typeof section.id === "string" && section.id.trim().length > 0 && - hasBoundedTimeRange(section) + timeRange !== null ) - .flatMap(({ section, sectionIndex }) => { + .flatMap(({ section, sectionIndex, timeRange }) => { + if (!timeRange) { + return []; + } const holdingRole = pickHoldingRole( rankedActiveRoles(section).filter((role) => ownedRiffPlan(role) !== null) ); @@ -279,7 +291,7 @@ function resolveSafeFirstRiffPlan(song: RehearsalSong): FirstRiffPlan | null { sectionIndex, holdingRole, riffPlan, - atSeconds: section.timeRange.start + atSeconds: timeRange.start } ]; }) From 45176f181a2ca78161a9c00a85469b752bffd58e Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Mon, 24 Aug 2026 09:46:53 -0700 Subject: [PATCH 7/7] fix(workspace): type-narrow riff time snapshots --- apps/desktop/src/features/workspace/firstRiffPlan.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/features/workspace/firstRiffPlan.ts b/apps/desktop/src/features/workspace/firstRiffPlan.ts index d14dd2e46..de84c9df7 100644 --- a/apps/desktop/src/features/workspace/firstRiffPlan.ts +++ b/apps/desktop/src/features/workspace/firstRiffPlan.ts @@ -145,12 +145,12 @@ function ownedBoundedTimeRange( const start = ownDataValue(timeRange, "start"); const end = ownDataValue(timeRange, "end"); if ( - !Number.isInteger(start) || typeof start !== "number" || + !Number.isInteger(start) || start < 0 || start > MAX_SECTION_TIME_SECONDS || - !Number.isInteger(end) || typeof end !== "number" || + !Number.isInteger(end) || end <= start || end > MAX_SECTION_TIME_SECONDS ) {