diff --git a/AGENTS.md b/AGENTS.md
index b9a67ce17..ee4558ed1 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, leftover last-dropout cues after leftover last-return, simplification guidance, transposition or setup cues, part-overlap cues, visible confidence, and rehearsal priorities.
- 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..7a792bccd 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -82,7 +82,7 @@ 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 naming tonight's first span and tonight's first leftover last-dropout after leftover last-return
- 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..d837ceb2f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Added
+- Name tonight's first leftover last-dropout on the ready rehearsal map and tell the leftover last-dropout to stay out, or the band to count that leftover last-dropout out, after leftover last-return.
- 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..2d8a0ab0f 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 tonight's first leftover last-dropout after leftover last-return. `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/Workspace.test.tsx b/apps/desktop/src/features/workspace/Workspace.test.tsx
index 7837bf80e..4eff6b6ba 100644
--- a/apps/desktop/src/features/workspace/Workspace.test.tsx
+++ b/apps/desktop/src/features/workspace/Workspace.test.tsx
@@ -140,6 +140,156 @@ describe("Workspace", () => {
expect(screen.getByText(/Verse harmony pass/i)).toBeTruthy();
});
+ it("names the next part to sit out after the band is back in", () => {
+ setNavigatorLanguage("en-US");
+ const song = createDemoRehearsalSong();
+ const verse = song.sections[0]!;
+ song.sections = [
+ {
+ ...verse,
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "bass-guitar" ||
+ node.role_id === "keys-right" ||
+ node.role_id === "lead-vocal"
+ ? { ...node, is_active: false }
+ : node
+ )
+ },
+ {
+ ...verse,
+ id: "chorus-1",
+ label: "chorus",
+ timeRange: { start: verse.timeRange.end, end: verse.timeRange.end + 20 },
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "keys-right" || node.role_id === "lead-vocal"
+ ? { ...node, is_active: false }
+ : node
+ )
+ },
+ {
+ ...verse,
+ id: "bridge-1",
+ label: "bridge",
+ timeRange: {
+ start: verse.timeRange.end + 20,
+ end: verse.timeRange.end + 40
+ },
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "lead-vocal" ? { ...node, is_active: false } : node
+ )
+ },
+ {
+ ...verse,
+ id: "outro-1",
+ label: "outro",
+ timeRange: {
+ start: verse.timeRange.end + 40,
+ end: verse.timeRange.end + 60
+ }
+ },
+ {
+ ...verse,
+ id: "tag-1",
+ label: "tag",
+ timeRange: {
+ start: verse.timeRange.end + 60,
+ end: verse.timeRange.end + 80
+ },
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "keys-right" ? { ...node, is_active: false } : node
+ )
+ }
+ ];
+
+ render();
+
+ const callout = screen.getByTestId("first-leftover-last-dropout");
+ expect(callout).toHaveTextContent("Next part to sit out");
+ expect(callout).toHaveTextContent(
+ "Keyboard 1 Right Hand sits out at tag after the band is back in at outro. Count Keyboard 1 Right Hand out from the top of tag."
+ );
+ });
+
+ it("tells the selected player where to stay out", () => {
+ setNavigatorLanguage("en-US");
+ const song = createDemoRehearsalSong();
+ const verse = song.sections[0]!;
+ song.sections = [
+ {
+ ...verse,
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "bass-guitar" ||
+ node.role_id === "keys-right" ||
+ node.role_id === "lead-vocal"
+ ? { ...node, is_active: false }
+ : node
+ )
+ },
+ {
+ ...verse,
+ id: "chorus-1",
+ label: "chorus",
+ timeRange: { start: verse.timeRange.end, end: verse.timeRange.end + 20 },
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "keys-right" || node.role_id === "lead-vocal"
+ ? { ...node, is_active: false }
+ : node
+ )
+ },
+ {
+ ...verse,
+ id: "bridge-1",
+ label: "bridge",
+ timeRange: {
+ start: verse.timeRange.end + 20,
+ end: verse.timeRange.end + 40
+ },
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "lead-vocal" ? { ...node, is_active: false } : node
+ )
+ },
+ {
+ ...verse,
+ id: "outro-1",
+ label: "outro",
+ timeRange: {
+ start: verse.timeRange.end + 40,
+ end: verse.timeRange.end + 60
+ }
+ },
+ {
+ ...verse,
+ id: "tag-1",
+ label: "tag",
+ timeRange: {
+ start: verse.timeRange.end + 60,
+ end: verse.timeRange.end + 80
+ },
+ partGraph: verse.partGraph.map((node) =>
+ node.role_id === "keys-right" ? { ...node, is_active: false } : node
+ )
+ }
+ ];
+
+ render();
+ fireEvent.click(screen.getByRole("tab", { name: "Keyboard 1 Right Hand" }));
+
+ expect(screen.getByTestId("first-leftover-last-dropout")).toHaveTextContent(
+ "Keyboard 1 Right Hand sits out at tag after the band is back in at outro. Stay out from the top of tag."
+ );
+ });
+
+ it("asks the player to confirm the next sit-out when no sit-out is mapped", () => {
+ setNavigatorLanguage("en-US");
+ const song = createDemoRehearsalSong();
+
+ render();
+
+ expect(screen.getByTestId("first-leftover-last-dropout")).toHaveTextContent(
+ "The next sit-out is not clear yet. Confirm who sits out after the band is back in before rehearsal."
+ );
+ });
+
it("names tonight's first playable range and the next instrument check", () => {
setNavigatorLanguage("en-US");
const song = createDemoRehearsalSong();
@@ -326,4 +476,4 @@ describe("Workspace", () => {
expect(screen.getByText("합주 우선순위")).toBeTruthy();
expect(screen.getByText("역할과 화성")).toBeTruthy();
});
-});
+});
\ No newline at end of file
diff --git a/apps/desktop/src/features/workspace/Workspace.tsx b/apps/desktop/src/features/workspace/Workspace.tsx
index d44e20777..8ea83868d 100644
--- a/apps/desktop/src/features/workspace/Workspace.tsx
+++ b/apps/desktop/src/features/workspace/Workspace.tsx
@@ -5,6 +5,7 @@ import { SectionRoadmap } from "./SectionRoadmap";
import { GrooveMap } from "./GrooveMap";
import { PracticeProgress } from "./PracticeProgress";
import { fillRangeCopy, firstRangeSqueeze } from "./firstRangeSqueeze";
+import { firstLeftoverLastDropout } from "./firstLeftoverLastDropout";
import { createTranslator, detectPreferredLocale } from "../../i18n";
import { generateCueSheetCsv, generateChartSummaryJson, generateMetadataHandoffJson, sanitizeFilename } from "../../lib/export";
import { Button } from "@/components/ui/button";
@@ -163,6 +164,24 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp
}
)
: t("workspaceFirstRangeMissing");
+ const namedLeftoverLastDropout = useMemo(
+ () => firstLeftoverLastDropout(song, activeRole),
+ [activeRole, song]
+ );
+ const firstLeftoverLastDropoutCopy = namedLeftoverLastDropout
+ ? fillRangeCopy(
+ t(
+ activeRole && activeRole === namedLeftoverLastDropout.dropoutRoleId
+ ? "workspaceFirstLeftoverLastDropoutStayOut"
+ : "workspaceFirstLeftoverLastDropoutNamed"
+ ),
+ {
+ dropoutRoleName: namedLeftoverLastDropout.dropoutRoleName,
+ sectionLabel: namedLeftoverLastDropout.sectionLabel,
+ lastReturnSectionLabel: namedLeftoverLastDropout.lastReturnSectionLabel
+ }
+ )
+ : t("workspaceFirstLeftoverLastDropoutMissing");
/** Handle the practice progress change internally by immutably updating the song state. */
const handlePracticeProgressChange = (newProgress: number) => {
@@ -309,6 +328,14 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp
{t("workspaceFirstRangeTitle")}
{firstRangeCopy}
+
+ {t("workspaceFirstLeftoverLastDropoutTitle")}
+ {firstLeftoverLastDropoutCopy}
+
diff --git a/apps/desktop/src/features/workspace/firstLeftoverLastDropout.redropout.test.ts b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.redropout.test.ts
new file mode 100644
index 000000000..de5f0dd8a
--- /dev/null
+++ b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.redropout.test.ts
@@ -0,0 +1,53 @@
+import { createDemoRehearsalSong, type RehearsalSong } from "@bandscope/shared-types";
+import { describe, expect, it } from "vitest";
+import { firstLeftoverLastDropout } from "./firstLeftoverLastDropout";
+
+function sectionWithInactiveRoles(
+ template: RehearsalSong["sections"][number],
+ id: string,
+ label: string,
+ start: number,
+ inactiveRoleIds: readonly string[]
+): RehearsalSong["sections"][number] {
+ const inactive = new Set(inactiveRoleIds);
+ return {
+ ...template,
+ id,
+ label: label as RehearsalSong["sections"][number]["label"],
+ timeRange: { start, end: start + 20 },
+ partGraph: template.partGraph.map((node) => ({
+ ...node,
+ is_active: !inactive.has(node.role_id)
+ }))
+ };
+}
+
+describe("firstLeftoverLastDropout remaining-leftover continuity", () => {
+ it("rejects a re-dropout that starts before the final leftover returns", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "breakdown-1", "breakdown", 60, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 80, ["keys-right"]),
+ sectionWithInactiveRoles(template, "tag-1", "tag", 100, ["keys-right"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/features/workspace/firstLeftoverLastDropout.selected-role.test.ts b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.selected-role.test.ts
new file mode 100644
index 000000000..6f90b6c5d
--- /dev/null
+++ b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.selected-role.test.ts
@@ -0,0 +1,124 @@
+import { createDemoRehearsalSong, type RehearsalSong } from "@bandscope/shared-types";
+import { describe, expect, it } from "vitest";
+import { firstLeftoverLastDropout } from "./firstLeftoverLastDropout";
+
+function sectionWithInactiveRoles(
+ template: RehearsalSong["sections"][number],
+ id: string,
+ label: RehearsalSong["sections"][number]["label"],
+ start: number,
+ inactiveRoleIds: readonly string[]
+): RehearsalSong["sections"][number] {
+ const inactive = new Set(inactiveRoleIds);
+ return {
+ ...template,
+ id,
+ label,
+ timeRange: { start, end: start + 20 },
+ partGraph: template.partGraph.map((node) => ({
+ ...node,
+ is_active: !inactive.has(node.role_id)
+ }))
+ };
+}
+
+describe("firstLeftoverLastDropout selected-role search", () => {
+ it("keeps searching after the selected part newly drops out during leftover last-return tutti", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, []),
+ sectionWithInactiveRoles(template, "tag-1", "tag", 80, []),
+ sectionWithInactiveRoles(template, "coda-1", "stop", 100, ["bass-guitar"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song, "bass-guitar")).toEqual({
+ sectionLabel: "stop",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "bass-guitar",
+ dropoutRoleName: "Bass Guitar"
+ });
+ });
+
+ it("does not tell a leftover last-return without a later sit-out to stay out", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, [])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song, "lead-vocal")).toBeNull();
+ });
+
+ it("does not show another part's leftover last-dropout to a selected part that stayed active", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const selectedRole = {
+ ...template.roles[0]!,
+ id: "always-active",
+ name: "Always Active"
+ };
+ const selectedTemplate: RehearsalSong["sections"][number] = {
+ ...template,
+ roles: [...template.roles, selectedRole],
+ partGraph: [
+ ...template.partGraph,
+ {
+ ...template.partGraph[0]!,
+ role_id: "always-active",
+ is_active: true,
+ handoff_to: [],
+ handoff_from: []
+ }
+ ]
+ };
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(selectedTemplate, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(selectedTemplate, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(selectedTemplate, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(selectedTemplate, "outro-1", "outro", 60, []),
+ sectionWithInactiveRoles(selectedTemplate, "tag-1", "tag", 80, ["keys-right"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song, "always-active")).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/features/workspace/firstLeftoverLastDropout.test.ts b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.test.ts
new file mode 100644
index 000000000..039a93a4a
--- /dev/null
+++ b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.test.ts
@@ -0,0 +1,466 @@
+import { createDemoRehearsalSong, type RehearsalSong } from "@bandscope/shared-types";
+import { describe, expect, it } from "vitest";
+import { fillRangeCopy } from "./firstRangeSqueeze";
+import { firstLeftoverLastDropout } from "./firstLeftoverLastDropout";
+
+function sectionWithInactiveRoles(
+ template: RehearsalSong["sections"][number],
+ id: string,
+ label: string,
+ start: number,
+ inactiveRoleIds: readonly string[],
+ activeOnlyRoles = false
+): RehearsalSong["sections"][number] {
+ const inactive = new Set(inactiveRoleIds);
+ const partGraph = template.partGraph.map((node) => ({
+ ...node,
+ is_active: !inactive.has(node.role_id)
+ }));
+ return {
+ ...template,
+ id,
+ label: label as RehearsalSong["sections"][number]["label"],
+ timeRange: { start, end: start + 20 },
+ partGraph,
+ roles: activeOnlyRoles
+ ? template.roles.filter((role) => !inactive.has(role.id))
+ : template.roles
+ };
+}
+
+function leftoverThenLastReturnThenDropout(
+ dropoutRoleId = "keys-right",
+ lastRoleId = "lead-vocal",
+ returningLeftoverId = "keys-right",
+ originalSitOutRoleId = "bass-guitar"
+): RehearsalSong {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ return {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ originalSitOutRoleId,
+ returningLeftoverId,
+ lastRoleId
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ returningLeftoverId,
+ lastRoleId
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, [lastRoleId]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, []),
+ sectionWithInactiveRoles(template, "tag-1", "tag", 80, [dropoutRoleId])
+ ]
+ };
+}
+
+describe("firstLeftoverLastDropout", () => {
+ it("returns null on the demo song where every graph node is active", () => {
+ expect(firstLeftoverLastDropout(createDemoRehearsalSong())).toBeNull();
+ });
+
+ it("names the leftover last-dropout after leftover last-return", () => {
+ expect(firstLeftoverLastDropout(leftoverThenLastReturnThenDropout())).toEqual({
+ sectionLabel: "tag",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "keys-right",
+ dropoutRoleName: "Keyboard 1 Right Hand"
+ });
+ });
+
+ it("uses song-wide role names when inactive analysis roles are omitted from section roles", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "opening-1", "opening", 0, []),
+ sectionWithInactiveRoles(
+ template,
+ "bridge-1",
+ "bridge",
+ 20,
+ ["bass-guitar", "keys-right", "lead-vocal"],
+ true
+ ),
+ sectionWithInactiveRoles(
+ template,
+ "chorus-1",
+ "chorus",
+ 40,
+ ["keys-right", "lead-vocal"],
+ true
+ ),
+ sectionWithInactiveRoles(template, "tag-1", "tag", 60, ["lead-vocal"], true),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 80, [], true),
+ sectionWithInactiveRoles(template, "coda-1", "stop", 100, ["lead-vocal"], true)
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toEqual({
+ sectionLabel: "stop",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "tag",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "bridge",
+ dropoutRoleId: "lead-vocal",
+ dropoutRoleName: "Lead Vocal"
+ });
+ });
+
+ it("treats repeated form labels as distinct timeline sections", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ song.sections[4] = {
+ ...song.sections[4]!,
+ label: song.sections[3]!.label
+ };
+
+ expect(firstLeftoverLastDropout(song)).toEqual({
+ sectionLabel: "outro",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "keys-right",
+ dropoutRoleName: "Keyboard 1 Right Hand"
+ });
+ });
+
+ it("skips a continued tutti after leftover last-return until the leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, []),
+ sectionWithInactiveRoles(template, "tag-1", "tag", 80, []),
+ sectionWithInactiveRoles(template, "coda-1", "stop", 100, ["bass-guitar"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toEqual({
+ sectionLabel: "stop",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "bass-guitar",
+ dropoutRoleName: "Bass Guitar"
+ });
+ });
+
+ it("fails closed when leftover last-return never last-drops", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, [])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("keeps the selected leftover last-dropout on tonight's first leftover last-dropout", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ expect(firstLeftoverLastDropout(song, "keys-right")).toEqual({
+ sectionLabel: "tag",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "keys-right",
+ dropoutRoleName: "Keyboard 1 Right Hand"
+ });
+ expect(firstLeftoverLastDropout(song, "lead-vocal")).toEqual({
+ sectionLabel: "tag",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "keys-right",
+ dropoutRoleName: "Keyboard 1 Right Hand"
+ });
+ expect(firstLeftoverLastDropout(song, "bass-guitar")).toEqual({
+ sectionLabel: "tag",
+ lastReturnSectionLabel: "outro",
+ remainingSectionLabel: "bridge",
+ leftoverSectionLabel: "chorus",
+ fromSectionLabel: "verse",
+ dropoutRoleId: "keys-right",
+ dropoutRoleName: "Keyboard 1 Right Hand"
+ });
+ expect(firstLeftoverLastDropout(song, "missing-role")).toBeNull();
+ });
+
+ it("does not treat a leftover sit-out without leftover return as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ expect(
+ firstLeftoverLastDropout({
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ])
+ ]
+ })
+ ).toBeNull();
+ });
+
+ it("does not treat leftover last-return as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, [])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("does not treat a leftover return with nobody still out as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, ["bass-guitar", "keys-right"]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, ["keys-right"]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, []),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, ["bass-guitar"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("does not treat a come-in without a leftover sit-out as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, ["keys-right"]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, []),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["bass-guitar"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("does not treat a tutti after a full original return as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, ["bass-guitar", "keys-right"]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, []),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, [])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("does not treat a new dropout after remaining leftover as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"]),
+ sectionWithInactiveRoles(template, "outro-1", "outro", 60, ["bass-guitar", "lead-vocal"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("does not treat remaining leftover without last-return as a leftover last-dropout", () => {
+ const seed = createDemoRehearsalSong();
+ const template = seed.sections[0]!;
+ const song: RehearsalSong = {
+ ...seed,
+ sections: [
+ sectionWithInactiveRoles(template, "verse-1", "verse", 0, [
+ "bass-guitar",
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "chorus-1", "chorus", 20, [
+ "keys-right",
+ "lead-vocal"
+ ]),
+ sectionWithInactiveRoles(template, "bridge-1", "bridge", 40, ["lead-vocal"])
+ ]
+ };
+
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("ignores inherited is_active evidence", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ const inherited = Object.create({
+ is_active: false,
+ role_id: "keys-right"
+ }) as RehearsalSong["sections"][number]["partGraph"][number];
+ song.sections[0] = {
+ ...song.sections[0]!,
+ partGraph: [inherited, ...song.sections[0]!.partGraph]
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("does not treat a missing is_active flag as leftover-last-dropout evidence", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ song.sections[1] = {
+ ...song.sections[1]!,
+ partGraph: song.sections[1]!.partGraph.map((node) => {
+ if (node.role_id !== "keys-right") {
+ return node;
+ }
+ const rest: Record = {
+ role_id: node.role_id,
+ handoff_to: node.handoff_to,
+ handoff_from: node.handoff_from
+ };
+ return rest as RehearsalSong["sections"][number]["partGraph"][number];
+ })
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("fails closed on contradictory duplicate graph identities", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ const section = song.sections[4]!;
+ const keysNode = section.partGraph.find((node) => node.role_id === "keys-right")!;
+ const withoutKeys = section.partGraph.filter((node) => node.role_id !== "keys-right");
+ song.sections[4] = {
+ ...section,
+ partGraph: [...withoutKeys, { ...keysNode, is_active: true }, { ...keysNode, is_active: false }]
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("skips blank leftover-last-dropout labels until a named leftover last-dropout exists", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ song.sections[4] = {
+ ...song.sections[4]!,
+ label: "none" as RehearsalSong["sections"][number]["label"]
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("fails closed when the leftover last-dropout has no named leftover role", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ song.sections[0] = {
+ ...song.sections[0]!,
+ roles: song.sections[0]!.roles.map((role) => ({ ...role, name: " " }))
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("fails closed when a later section has no named graph", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ song.sections[4] = {
+ ...song.sections[4]!,
+ partGraph: []
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+
+ it("fails closed on malformed runtime roots", () => {
+ for (const malformed of [null, {}, { sections: {} }, { sections: [null] }]) {
+ expect(firstLeftoverLastDropout(malformed as unknown as RehearsalSong)).toBeNull();
+ }
+ });
+
+ it("isolates blank role ids, non-boolean flags, and unnamed graph members", () => {
+ const song = leftoverThenLastReturnThenDropout();
+ song.sections[0] = {
+ ...song.sections[0]!,
+ partGraph: [
+ { role_id: " ", is_active: false, handoff_to: [], handoff_from: [] },
+ { role_id: "ghost", is_active: false, handoff_to: [], handoff_from: [] },
+ {
+ role_id: "keys-right",
+ is_active: "no" as unknown as boolean,
+ handoff_to: [],
+ handoff_from: []
+ },
+ ...song.sections[0]!.partGraph
+ ]
+ };
+ expect(firstLeftoverLastDropout(song)).toBeNull();
+ });
+});
+
+describe("leftover-last-dropout copy filling", () => {
+ it("keeps rehearsal values literal", () => {
+ expect(
+ fillRangeCopy(
+ "{dropoutRoleName} sits out at {sectionLabel} after leftover last-return at {lastReturnSectionLabel}.",
+ {
+ dropoutRoleName: "Keys Right {sectionLabel}",
+ sectionLabel: "tag",
+ lastReturnSectionLabel: "outro"
+ }
+ )
+ ).toBe("Keys Right {sectionLabel} sits out at tag after leftover last-return at outro.");
+ });
+});
diff --git a/apps/desktop/src/features/workspace/firstLeftoverLastDropout.ts b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.ts
new file mode 100644
index 000000000..babd310b0
--- /dev/null
+++ b/apps/desktop/src/features/workspace/firstLeftoverLastDropout.ts
@@ -0,0 +1,397 @@
+import type { RehearsalSong } from "@bandscope/shared-types";
+import { meaningfulRangeText } from "./firstRangeSqueeze";
+
+/** Tonight's first named leftover last-dropout after leftover last-return. */
+export type FirstLeftoverLastDropout = {
+ sectionLabel: string;
+ lastReturnSectionLabel: string;
+ remainingSectionLabel: string;
+ leftoverSectionLabel: string;
+ fromSectionLabel: string;
+ dropoutRoleId: string;
+ dropoutRoleName: string;
+};
+
+/** 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);
+}
+
+/** Admit an own-property boolean `is_active` flag. Inherited evidence is isolated. */
+function ownActiveFlag(value: Record): boolean | null {
+ if (!Object.prototype.hasOwnProperty.call(value, "is_active")) {
+ return null;
+ }
+ if (value.is_active === true) {
+ return true;
+ }
+ if (value.is_active === false) {
+ return false;
+ }
+ return null;
+}
+
+type NamedRoleCatalog = Map;
+
+/**
+ * Build trustworthy role identity evidence across the whole song.
+ *
+ * Production analysis emits active-only section `roles` while keeping inactive
+ * identities in `partGraph`. The song-wide catalog therefore lets a leftover
+ * part keep its trustworthy display name across leftover sit-out, remaining
+ * leftover, leftover last-return, and leftover last-dropout.
+ */
+function namedSongRoles(songValue: Record): NamedRoleCatalog | null {
+ if (!Array.isArray(songValue.sections)) {
+ return null;
+ }
+
+ const namedRoles: NamedRoleCatalog = new Map();
+ for (const sectionValue of songValue.sections) {
+ if (!isRuntimeObject(sectionValue) || !Array.isArray(sectionValue.roles)) {
+ return null;
+ }
+
+ const sectionRoleIds = new Set();
+ for (const roleValue of sectionValue.roles) {
+ if (
+ !isRuntimeObject(roleValue) ||
+ !Object.prototype.hasOwnProperty.call(roleValue, "id") ||
+ !Object.prototype.hasOwnProperty.call(roleValue, "name")
+ ) {
+ return null;
+ }
+
+ const roleId = meaningfulRangeText(roleValue.id);
+ const roleName = meaningfulRangeText(roleValue.name);
+ if (!roleId || !roleName || sectionRoleIds.has(roleId)) {
+ return null;
+ }
+ sectionRoleIds.add(roleId);
+
+ const knownName = namedRoles.get(roleId);
+ if (knownName && knownName !== roleName) {
+ return null;
+ }
+ namedRoles.set(roleId, roleName);
+ }
+ }
+
+ return namedRoles.size > 0 ? namedRoles : null;
+}
+
+type NamedGraphNode = {
+ roleId: string;
+ active: boolean;
+};
+
+/**
+ * Collect one complete, unique activity record for every song-wide named role.
+ *
+ * Missing, unknown, duplicate, inherited, or non-boolean graph evidence fails
+ * closed so a leftover part cannot be both last-returning and dropping in the
+ * same leftover last-dropout decision.
+ */
+function namedGraphNodes(
+ sectionValue: Record,
+ namedRoles: NamedRoleCatalog
+): NamedGraphNode[] | null {
+ if (!Array.isArray(sectionValue.partGraph)) {
+ return null;
+ }
+
+ const nodes: NamedGraphNode[] = [];
+ const seenRoleIds = new Set();
+ for (const nodeValue of sectionValue.partGraph) {
+ if (
+ !isRuntimeObject(nodeValue) ||
+ !Object.prototype.hasOwnProperty.call(nodeValue, "role_id")
+ ) {
+ return null;
+ }
+
+ const roleId = meaningfulRangeText(nodeValue.role_id);
+ if (!roleId || !namedRoles.has(roleId) || seenRoleIds.has(roleId)) {
+ return null;
+ }
+
+ const active = ownActiveFlag(nodeValue);
+ if (active === null) {
+ return null;
+ }
+
+ seenRoleIds.add(roleId);
+ nodes.push({ roleId, active });
+ }
+
+ return seenRoleIds.size === namedRoles.size ? nodes : null;
+}
+
+type PendingLeftoverSitOut = {
+ leftoverSectionLabel: string;
+ fromSectionLabel: string;
+ leftoverIds: string[];
+ originalSitOutIds: string[];
+};
+
+type PendingRemainingLeftover = {
+ leftoverSectionLabel: string;
+ remainingSectionLabel: string;
+ fromSectionLabel: string;
+ leftoverIds: string[];
+ remainingIds: string[];
+ originalSitOutIds: string[];
+};
+
+type PendingLastReturn = {
+ leftoverSectionLabel: string;
+ remainingSectionLabel: string;
+ lastReturnSectionLabel: string;
+ fromSectionLabel: string;
+ leftoverIds: string[];
+ remainingIds: string[];
+ originalSitOutIds: string[];
+ lastRoleId: string;
+};
+
+/**
+ * Return whether the selected part belongs to this leftover last-dropout.
+ *
+ * A leftover last-dropout is shown only after a leftover last-return whose
+ * original sit-out, leftover, remaining leftover, last leftover, or dropping
+ * named part includes that selected part, so a silent always-active part is
+ * never told to count someone out.
+ */
+function selectedPartBelongs(
+ pending: PendingLastReturn,
+ dropoutRoleId: string,
+ activeRole: string | null
+): boolean {
+ if (!activeRole) {
+ return true;
+ }
+ return (
+ pending.originalSitOutIds.includes(activeRole) ||
+ pending.leftoverIds.includes(activeRole) ||
+ pending.remainingIds.includes(activeRole) ||
+ pending.lastRoleId === activeRole ||
+ dropoutRoleId === activeRole
+ );
+}
+
+/**
+ * Pick the first leftover last-dropout a player should honor after leftover last-return.
+ *
+ * A leftover sit-out is the first later named section where at least one member
+ * of the current reduced cohort has returned and at least one remains out. A
+ * leftover return with remaining leftover is the first named section after that
+ * leftover sit-out where at least one leftover part is own-property active and
+ * at least one leftover remains own-property tacet. A leftover last-return is
+ * the first later named section where every remaining leftover is own-property
+ * active. A leftover last-dropout is the first later named section after that
+ * leftover last-return where at least one named part is own-property tacet.
+ * A leftover last-return, remaining leftover, leftover sit-out, leftover return,
+ * come-in, tacet, tutti, new dropout after remaining leftover, or leftover
+ * last-return without a later sit-out is not a leftover last-dropout.
+ *
+ * Inherited/missing activity, incomplete or contradictory graphs, unnamed
+ * roles, and malformed runtime data fail closed. When a role is selected, a
+ * leftover last-dropout is shown only after a leftover last-return that includes
+ * that named part or a later sit-out of that named part.
+ */
+export function firstLeftoverLastDropout(
+ song: RehearsalSong | unknown,
+ activeRole: string | null = null
+): FirstLeftoverLastDropout | null {
+ if (!isRuntimeObject(song) || !Array.isArray(song.sections)) {
+ return null;
+ }
+
+ const namedRoles = namedSongRoles(song);
+ if (!namedRoles || (activeRole && !namedRoles.has(activeRole))) {
+ return null;
+ }
+
+ let reducedFrom: string | null = null;
+ let sittingOutIds: Set | null = null;
+ let pendingSitOut: PendingLeftoverSitOut | null = null;
+ let pendingRemaining: PendingRemainingLeftover | null = null;
+ let pendingLastReturn: PendingLastReturn | null = null;
+
+ for (const sectionValue of song.sections) {
+ if (!isRuntimeObject(sectionValue)) {
+ return null;
+ }
+ const sectionLabel = meaningfulRangeText(sectionValue.label);
+ if (!sectionLabel) {
+ continue;
+ }
+
+ const nodes = namedGraphNodes(sectionValue, namedRoles);
+ if (!nodes) {
+ return null;
+ }
+
+ const sittingOut = nodes.filter((node) => node.active === false);
+
+ if (pendingLastReturn) {
+ if (sittingOut.length === 0) {
+ continue;
+ }
+
+ let dropout = sittingOut[0]!;
+ if (activeRole) {
+ const selectedDropout = sittingOut.find((node) => node.roleId === activeRole);
+ if (selectedDropout) {
+ dropout = selectedDropout;
+ } else if (!selectedPartBelongs(pendingLastReturn, dropout.roleId, activeRole)) {
+ continue;
+ }
+ }
+
+ return {
+ sectionLabel,
+ lastReturnSectionLabel: pendingLastReturn.lastReturnSectionLabel,
+ remainingSectionLabel: pendingLastReturn.remainingSectionLabel,
+ leftoverSectionLabel: pendingLastReturn.leftoverSectionLabel,
+ fromSectionLabel: pendingLastReturn.fromSectionLabel,
+ dropoutRoleId: dropout.roleId,
+ dropoutRoleName: namedRoles.get(dropout.roleId)!
+ };
+ }
+
+ if (pendingRemaining) {
+ const remainingNodes: NamedGraphNode[] = [];
+ for (const remainingId of pendingRemaining.remainingIds) {
+ const remainingNode = nodes.find((node) => node.roleId === remainingId);
+ if (!remainingNode) {
+ return null;
+ }
+ remainingNodes.push(remainingNode);
+ }
+
+ const trackedRemainingIds = new Set(pendingRemaining.remainingIds);
+ if (sittingOut.some((node) => !trackedRemainingIds.has(node.roleId))) {
+ pendingRemaining = null;
+ reducedFrom = sectionLabel;
+ sittingOutIds = new Set(sittingOut.map((node) => node.roleId));
+ continue;
+ }
+
+ const returningLast = remainingNodes.filter((node) => node.active);
+ const stillRemaining = remainingNodes.filter((node) => node.active === false);
+
+ if (returningLast.length > 0 && stillRemaining.length === 0) {
+ let last = returningLast[0]!;
+ if (activeRole) {
+ const activeRoleNode = nodes.find((node) => node.roleId === activeRole);
+ if (!activeRoleNode) {
+ return null;
+ }
+ const selectedLast = returningLast.find((node) => node.roleId === activeRole);
+ if (selectedLast) {
+ last = selectedLast;
+ }
+ }
+ pendingLastReturn = {
+ leftoverSectionLabel: pendingRemaining.leftoverSectionLabel,
+ remainingSectionLabel: pendingRemaining.remainingSectionLabel,
+ lastReturnSectionLabel: sectionLabel,
+ fromSectionLabel: pendingRemaining.fromSectionLabel,
+ leftoverIds: pendingRemaining.leftoverIds,
+ remainingIds: pendingRemaining.remainingIds,
+ originalSitOutIds: pendingRemaining.originalSitOutIds,
+ lastRoleId: last.roleId
+ };
+ pendingRemaining = null;
+ continue;
+ }
+
+ if (returningLast.length > 0 && stillRemaining.length > 0) {
+ pendingRemaining = {
+ leftoverSectionLabel: pendingRemaining.leftoverSectionLabel,
+ remainingSectionLabel: sectionLabel,
+ fromSectionLabel: pendingRemaining.fromSectionLabel,
+ leftoverIds: pendingRemaining.leftoverIds,
+ remainingIds: stillRemaining.map((node) => node.roleId),
+ originalSitOutIds: pendingRemaining.originalSitOutIds
+ };
+ }
+ continue;
+ }
+
+ if (pendingSitOut) {
+ const leftoverNodes = pendingSitOut.leftoverIds.map((leftoverId) =>
+ nodes.find((node) => node.roleId === leftoverId)
+ );
+ if (leftoverNodes.some((node) => !node)) {
+ return null;
+ }
+
+ const returningLeftovers = leftoverNodes.filter((node) => node!.active);
+ const remainingLeftovers = leftoverNodes.filter((node) => node!.active === false);
+
+ if (returningLeftovers.length > 0 && remainingLeftovers.length > 0) {
+ pendingRemaining = {
+ leftoverSectionLabel: pendingSitOut.leftoverSectionLabel,
+ remainingSectionLabel: sectionLabel,
+ fromSectionLabel: pendingSitOut.fromSectionLabel,
+ leftoverIds: pendingSitOut.leftoverIds,
+ remainingIds: remainingLeftovers.map((node) => node!.roleId),
+ originalSitOutIds: pendingSitOut.originalSitOutIds
+ };
+ pendingSitOut = null;
+ continue;
+ }
+
+ if (returningLeftovers.length > 0 && remainingLeftovers.length === 0) {
+ pendingSitOut = null;
+ if (sittingOut.length === 0) {
+ reducedFrom = null;
+ sittingOutIds = null;
+ } else {
+ reducedFrom = sectionLabel;
+ sittingOutIds = new Set(sittingOut.map((node) => node.roleId));
+ }
+ }
+ continue;
+ }
+
+ if (!sittingOutIds || !reducedFrom) {
+ if (sittingOut.length === 0) {
+ continue;
+ }
+ reducedFrom = sectionLabel;
+ sittingOutIds = new Set(sittingOut.map((node) => node.roleId));
+ continue;
+ }
+
+ const baselineIds = sittingOutIds;
+ const returning = nodes.filter(
+ (node) => node.active === true && baselineIds.has(node.roleId)
+ );
+ const leftovers = sittingOut.filter((node) => baselineIds.has(node.roleId));
+
+ if (returning.length > 0 && leftovers.length > 0) {
+ pendingSitOut = {
+ leftoverSectionLabel: sectionLabel,
+ fromSectionLabel: reducedFrom,
+ leftoverIds: leftovers.map((node) => node.roleId),
+ originalSitOutIds: [...baselineIds]
+ };
+ continue;
+ }
+
+ if (returning.length === baselineIds.size && leftovers.length === 0) {
+ if (sittingOut.length === 0) {
+ reducedFrom = null;
+ sittingOutIds = null;
+ } else {
+ reducedFrom = sectionLabel;
+ sittingOutIds = new Set(sittingOut.map((node) => node.roleId));
+ }
+ }
+ }
+
+ return null;
+}
diff --git a/apps/desktop/src/i18n/index.test.ts b/apps/desktop/src/i18n/index.test.ts
index dc49a0a25..3e00c1969 100644
--- a/apps/desktop/src/i18n/index.test.ts
+++ b/apps/desktop/src/i18n/index.test.ts
@@ -60,6 +60,7 @@ describe("i18n", () => {
const t = createTranslator("ko");
expect(t("appTitle")).toBe("BandScope");
expect(t("appSubtitle")).toBe("합주 준비를 위한 로컬-퍼스트 분석 도구");
+ expect(t("workspaceFirstLeftoverLastDropoutTitle")).toBe("오늘 먼저 마지막 복귀 후 쉬는 자리");
});
it("falls back to English when a Korean translation is missing", () => {
diff --git a/apps/desktop/src/i18n/workspaceDropoutCopy.test.ts b/apps/desktop/src/i18n/workspaceDropoutCopy.test.ts
new file mode 100644
index 000000000..162c0abda
--- /dev/null
+++ b/apps/desktop/src/i18n/workspaceDropoutCopy.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vitest";
+import enCommon from "../locales/en/common.json";
+import koCommon from "../locales/ko/common.json";
+
+describe("workspace sit-out copy", () => {
+ it("uses player-readable English instead of state-machine jargon", () => {
+ const english = [
+ enCommon.workspaceFirstLeftoverLastDropoutTitle,
+ enCommon.workspaceFirstLeftoverLastDropoutNamed,
+ enCommon.workspaceFirstLeftoverLastDropoutStayOut,
+ enCommon.workspaceFirstLeftoverLastDropoutMissing
+ ];
+
+ expect(english.join(" ").toLowerCase()).not.toContain("leftover");
+ expect(english.join(" ").toLowerCase()).not.toContain("last-dropout");
+ expect(enCommon.workspaceFirstLeftoverLastDropoutTitle).toBe("Next part to sit out");
+ expect(enCommon.workspaceFirstLeftoverLastDropoutNamed).toBe(
+ "{dropoutRoleName} sits out at {sectionLabel} after the band is back in at {lastReturnSectionLabel}. Count {dropoutRoleName} out from the top of {sectionLabel}."
+ );
+ expect(enCommon.workspaceFirstLeftoverLastDropoutStayOut).toBe(
+ "{dropoutRoleName} sits out at {sectionLabel} after the band is back in at {lastReturnSectionLabel}. Stay out from the top of {sectionLabel}."
+ );
+ expect(enCommon.workspaceFirstLeftoverLastDropoutMissing).toBe(
+ "The next sit-out is not clear yet. Confirm who sits out after the band is back in before rehearsal."
+ );
+ });
+
+ it("keeps the Korean cue equally concrete and action-oriented", () => {
+ expect(koCommon.workspaceFirstLeftoverLastDropoutTitle).toBe("다음에 쉬는 파트");
+ expect(koCommon.workspaceFirstLeftoverLastDropoutNamed).toBe(
+ "{dropoutRoleName}은 {lastReturnSectionLabel}에서 모두 다시 들어온 뒤 {sectionLabel}에서 쉽니다. {sectionLabel} 첫 박부터 {dropoutRoleName}을 빼 주세요."
+ );
+ expect(koCommon.workspaceFirstLeftoverLastDropoutStayOut).toBe(
+ "{dropoutRoleName}은 {lastReturnSectionLabel}에서 모두 다시 들어온 뒤 {sectionLabel}에서 쉽니다. {sectionLabel} 첫 박부터 쉬세요."
+ );
+ expect(koCommon.workspaceFirstLeftoverLastDropoutMissing).toBe(
+ "다음에 쉬는 파트가 아직 명확하지 않습니다. 모두 다시 들어온 뒤 누가 쉬는지 합주 전에 확인하세요."
+ );
+ });
+});
diff --git a/apps/desktop/src/locales/en/common.json b/apps/desktop/src/locales/en/common.json
index d803a765e..7ff235b71 100644
--- a/apps/desktop/src/locales/en/common.json
+++ b/apps/desktop/src/locales/en/common.json
@@ -153,6 +153,10 @@
"workspaceFirstRangeCheck": "{roleName} sits {lowestNote}–{highestNote} in {sectionLabel}. Check that span on your instrument before the {sectionLabel}.",
"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.",
+ "workspaceFirstLeftoverLastDropoutTitle": "Next part to sit out",
+ "workspaceFirstLeftoverLastDropoutNamed": "{dropoutRoleName} sits out at {sectionLabel} after the band is back in at {lastReturnSectionLabel}. Count {dropoutRoleName} out from the top of {sectionLabel}.",
+ "workspaceFirstLeftoverLastDropoutStayOut": "{dropoutRoleName} sits out at {sectionLabel} after the band is back in at {lastReturnSectionLabel}. Stay out from the top of {sectionLabel}.",
+ "workspaceFirstLeftoverLastDropoutMissing": "The next sit-out is not clear yet. Confirm who sits out after the band is back in before rehearsal.",
"sectionRangeLabel": "Range",
"sectionRangeNextAction": "Check this span on your instrument before {sectionLabel}."
}
diff --git a/apps/desktop/src/locales/ko/common.json b/apps/desktop/src/locales/ko/common.json
index 0f6c6c66d..eba441cd5 100644
--- a/apps/desktop/src/locales/ko/common.json
+++ b/apps/desktop/src/locales/ko/common.json
@@ -153,6 +153,10 @@
"workspaceFirstRangeCheck": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}입니다. {sectionLabel} 들어가기 전에 그 음역을 악기로 확인해 보세요.",
"workspaceFirstRangeClash": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}이고 다른 파트와 겹칩니다. {sectionLabel} 들어가기 전에 그 충돌을 악기로 들어 보세요.",
"workspaceFirstRangeMissing": "오늘 먼저 볼 음역은 아직 귀로 확인이 필요합니다. 선택한 파트의 최저·최고음을 첫 구간 전에 확인해 보세요.",
+ "workspaceFirstLeftoverLastDropoutTitle": "다음에 쉬는 파트",
+ "workspaceFirstLeftoverLastDropoutNamed": "{dropoutRoleName}은 {lastReturnSectionLabel}에서 모두 다시 들어온 뒤 {sectionLabel}에서 쉽니다. {sectionLabel} 첫 박부터 {dropoutRoleName}을 빼 주세요.",
+ "workspaceFirstLeftoverLastDropoutStayOut": "{dropoutRoleName}은 {lastReturnSectionLabel}에서 모두 다시 들어온 뒤 {sectionLabel}에서 쉽니다. {sectionLabel} 첫 박부터 쉬세요.",
+ "workspaceFirstLeftoverLastDropoutMissing": "다음에 쉬는 파트가 아직 명확하지 않습니다. 모두 다시 들어온 뒤 누가 쉬는지 합주 전에 확인하세요.",
"sectionRangeLabel": "음역",
"sectionRangeNextAction": "{sectionLabel} 들어가기 전에 이 음역을 악기로 확인해 보세요."
}
diff --git a/docs/design-system/component-contract.md b/docs/design-system/component-contract.md
index 22602c313..de50b7138 100644
--- a/docs/design-system/component-contract.md
+++ b/docs/design-system/component-contract.md
@@ -80,6 +80,7 @@ The authoritative Figma view is `31 Component Contract Catalog`. This file mirro
- `LoadingState` keeps `role="status"`, `aria-live="polite"`, `aria-atomic="true"`, and `aria-busy="true"`.
- `ErrorState` keeps `role="alert"`, `aria-live="assertive"`, and visible safe error detail copy.
- `EmptyState` must remain an actionable state card, not a blank placeholder panel.
+- Ready `Workspace` names tonight's first playable range and tonight's first leftover last-dropout so the map enables the next rehearsal action without opening files or export paths.
- If a new workspace state is added in code, update Figma page 34 and page 33 audit evidence before merging.
## Pattern Backlog
diff --git a/docs/doctoring/first-leftover-last-dropout.md b/docs/doctoring/first-leftover-last-dropout.md
new file mode 100644
index 000000000..d4ba43de9
--- /dev/null
+++ b/docs/doctoring/first-leftover-last-dropout.md
@@ -0,0 +1,18 @@
+# Tonight's first leftover last-dropout
+
+The ready rehearsal map names the first leftover last-dropout from existing `partGraph` evidence: a named leftover sit-out, then a later named leftover return where at least one leftover named part is own-property active and at least one leftover remains own-property tacet, then a later named leftover last-return where every remaining leftover is own-property active, then a later named section where at least one named part is own-property tacet. This is who sits out after leftover last-return. It is not a come-in, tacet, leftover sit-out, leftover return, remaining leftover, leftover last-return, tutti, handoff, Fine, last-line breath, a leftover last-return without a later sit-out, a new dropout after remaining leftover, or a new MIR product.
+
+## Next action
+
+- Named leftover last-dropout: stay out from the top of the named leftover last-dropout after leftover last-return.
+- Named returning or other included part: count the leftover last-dropout out from the top of that sit-out.
+- Missing: confirm who sits out after leftover last-return before the first section.
+
+## Security Notes
+
+- Untrusted inputs: `RehearsalSong` JSON, section labels, `partGraph` nodes, `is_active`, role ids, and role names from analysis or a reopened project.
+- Trust boundary: this helper never opens files, URLs, IPC, WebView, subprocesses, model artifacts, or export paths. It only admits an own-property leftover sit-out, leftover return with remaining leftover, leftover last-return, and a later named leftover last-dropout where at least one named part is own-property tacet.
+- Allowlist: section labels and role names must be meaningful text. A missing graph node is not a leftover last-dropout. Inherited `is_active` is isolated. A leftover last-return is leftover last-return, not leftover last-dropout. A new dropout after remaining leftover is a dropout, not a leftover last-dropout. All-active later sections after leftover last-return are tuttis, not leftover last-dropouts. When a role is selected, only a leftover last-dropout after a leftover last-return that includes that named part, or a later sit-out of that named part, is shown.
+- Safe failure: inherited flags, blank labels, missing names, leftover sit-outs without leftover return, leftover last-returns without a later sit-out, come-ins without a leftover, full-band returns, remaining leftovers without last-return, new dropouts after remaining leftover, unnamed roles, empty graphs, and malformed roots return `null` so the workspace shows the missing-copy next action instead of crashing or inventing a leftover last-dropout.
+- Logging/privacy: rejected or accepted leftover last-dropouts are not logged. Copy interpolation keeps rehearsal values literal.
+- Tests: `firstLeftoverLastDropout.test.ts` and the Workspace callout cover the demo all-active case, an explicit keys leftover last-dropout after leftover last-return, selected-role scoping, inherited flags, missing `is_active`, leftover last-returns without later sit-out, tuttis, come-ins, leftover returns with nobody still out, remaining leftovers without last-return, new dropouts after remaining leftover, unnamed roles, empty graphs, and literal copy filling.