fix(setup): resolve folder aliases when identifying platforms in the setup wizard (#5473)

* fix(setup): resolve folder aliases when identifying platforms in the setup wizard

The setup library endpoint returned raw folder names, so folders such as
gamecube or a config-bound nintendo-snes showed as Unidentified and their
platform stayed in the supported list. Report the resolved platform slug
next to each folder and match on it in the wizard.

Fixes #5465

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(setup): match supported platforms on resolved slug, one detected row per folder

pr-ready step 2 (code-review xhigh --fix): compare supported platforms by
slug so a DB row with an alias fs_slug still matches, keep each folder's own
name and rom count, read config once per request, black-format the new test,
and add a SetupStepPlatforms unit test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(setup): fold detected-row branches, drop redundant selection guards

pr-ready step 3 (simplify): build identified and unidentified rows from one
object, drop the detected checks in togglePlatform and newSlugsInGroup (every
caller already lists only supportedAvailable), and merge the duplicated chip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(setup): assert the resolved slug in every setup/library entry

pr-ready step 4 (review-polish): compare whole existing_platforms entries in
the older setup/library tests so they cover slug too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(setup): tighten detected-row comment

pr-ready step 5 (humanizer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(settings): resolve built-in folder aliases in folder mappings

Folder Mappings matched folders to platforms on the client by exact slug,
so alias folders like gamecube or megadrive showed as unmapped even though
the scan resolves them. The heartbeat now returns FS_PLATFORM_SLUGS, each
folder's slug from its name or built-in alias, and the table reads it for
auto-detected rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: drop response schema field comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
This commit is contained in:
alexcastgonz
2026-11-08 23:25:29 -04:00
committed by GitHub
parent bbb7d98f53
commit 54fecf2500
12 changed files with 266 additions and 69 deletions

View File

@@ -72,6 +72,10 @@ from handler.redis_handler import sync_cache
from handler.scan.sources import MetadataSource
from logger.logger import log
from utils import get_git_branch, get_version
from utils.platform_aliases import (
resolve_builtin_platform_slug,
resolve_platform_slug,
)
from utils.platforms import get_supported_platforms
from utils.rate_limit import enforce_rate_limit, get_client_ip
from utils.router import APIRouter
@@ -103,6 +107,7 @@ async def heartbeat() -> HeartbeatResponse:
title_id_extraction_enabled = (
SigilService.is_enabled() and not cm.get_config().SKIP_TITLE_ID_EXTRACTION
)
fs_platforms = await fs_platform_handler.get_platforms()
igdb_enabled = meta_igdb_handler.is_enabled()
flashpoint_enabled = meta_flashpoint_handler.is_enabled()
@@ -165,7 +170,12 @@ async def heartbeat() -> HeartbeatResponse:
"LIBRETRO_API_ENABLED": libretro_enabled,
},
"FILESYSTEM": {
"FS_PLATFORMS": await fs_platform_handler.get_platforms(),
"FS_PLATFORMS": fs_platforms,
"FS_PLATFORM_SLUGS": {
fs_slug: slug
for fs_slug in fs_platforms
if (slug := resolve_builtin_platform_slug(fs_slug))
},
"TITLE_ID_EXTRACTION_ENABLED": title_id_extraction_enabled,
},
"EMULATION": {
@@ -307,6 +317,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse:
)
library_ready = fs_platform_handler.library_structure_exists()
config = cm.get_config()
# The per-platform rom counts below are a first-run hint, so a fresh
# instance can show what RomM already sees on disk. Once the database
@@ -315,7 +326,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse:
if db_stats_handler.get_roms_count() > 0:
return {
"library_ready": library_ready,
"library_structure": cm.get_config().default_structure_pattern,
"library_structure": config.default_structure_pattern,
"existing_platforms": [],
"supported_platforms": get_supported_platforms(
get_rom_visibility_filter(request)
@@ -361,6 +372,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse:
existing_platforms.append(
{
"fs_slug": fs_slug,
"slug": resolve_platform_slug(fs_slug, config),
"rom_count": rom_count,
}
)
@@ -370,7 +382,7 @@ async def get_setup_library_info(request: Request) -> SetupLibraryResponse:
return {
"library_ready": library_ready,
"library_structure": cm.get_config().default_structure_pattern,
"library_structure": config.default_structure_pattern,
"existing_platforms": existing_platforms,
"supported_platforms": supported_platforms,
}

View File

@@ -32,6 +32,7 @@ class MetadataSourcesDict(TypedDict):
class FilesystemDict(TypedDict):
FS_PLATFORMS: list[str]
FS_PLATFORM_SLUGS: dict[str, str]
TITLE_ID_EXTRACTION_ENABLED: bool
@@ -98,6 +99,7 @@ class HeartbeatResponse(TypedDict):
class SetupExistingPlatform(TypedDict):
fs_slug: str
slug: str
rom_count: int

View File

@@ -45,6 +45,7 @@ def test_heartbeat(client):
assert "FILESYSTEM" in heartbeat
filesystem = heartbeat["FILESYSTEM"]
assert isinstance(filesystem["FS_PLATFORMS"], list)
assert isinstance(filesystem["FS_PLATFORM_SLUGS"], dict)
assert "EMULATION" in heartbeat
emulation = heartbeat["EMULATION"]
@@ -67,6 +68,19 @@ def test_heartbeat(client):
assert isinstance(heartbeat["CONVERTO"]["ENABLED"], bool)
def test_heartbeat_maps_folders_to_builtin_slugs(client):
with patch(
"endpoints.heartbeat.fs_platform_handler.get_platforms",
AsyncMock(return_value=["gamecube", "N64", "mystery"]),
):
response = client.get("/api/heartbeat")
assert response.json()["FILESYSTEM"]["FS_PLATFORM_SLUGS"] == {
"gamecube": "ngc",
"N64": "n64",
}
@pytest.mark.parametrize(
"authorization_header",
["Bearer ", "Foo", "a b c", "Bearer bogus", "Basic not_base64"],
@@ -218,11 +232,10 @@ def test_get_setup_library_info_reports_a_ready_library(client, access_token):
data = response.json()
assert data["library_ready"] is True
assert len(data["existing_platforms"]) == 2
assert data["existing_platforms"][0]["fs_slug"] == "n64"
assert data["existing_platforms"][0]["rom_count"] == 2
assert data["existing_platforms"][1]["fs_slug"] == "psx"
assert data["existing_platforms"][1]["rom_count"] == 1
assert data["existing_platforms"] == [
{"fs_slug": "n64", "slug": "n64", "rom_count": 2},
{"fs_slug": "psx", "slug": "psx", "rom_count": 1},
]
assert "supported_platforms" in data
@@ -266,9 +279,9 @@ def test_get_setup_library_info_counts_one_platform(client, admin_user, access_t
data = response.json()
assert data["library_ready"] is True
assert len(data["existing_platforms"]) == 1
assert data["existing_platforms"][0]["fs_slug"] == "gba"
assert data["existing_platforms"][0]["rom_count"] == 3
assert data["existing_platforms"] == [
{"fs_slug": "gba", "slug": "gba", "rom_count": 3}
]
def test_get_setup_library_info_no_library_yet(client, admin_user, access_token):
@@ -384,7 +397,44 @@ def test_get_setup_library_info_walks_when_platforms_have_no_roms(
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["existing_platforms"] == [{"fs_slug": "n64", "rom_count": 1}]
assert data["existing_platforms"] == [
{"fs_slug": "n64", "slug": "n64", "rom_count": 1}
]
def test_get_setup_library_info_resolves_folder_aliases(
client, admin_user, access_token
):
"""A folder alias reports the platform slug it resolves to, next to its folder name."""
with (
patch(
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
) as mock_detect,
patch(
"endpoints.heartbeat.fs_platform_handler.get_platforms"
) as mock_get_platforms,
patch("endpoints.heartbeat.AnyioPath") as mock_anyio_path,
):
mock_detect.return_value = True
mock_get_platforms.return_value = ["gamecube", "megadrive", "gba"]
async def mock_iterdir():
return
yield
mock_path = AsyncMock()
mock_path.exists = AsyncMock(return_value=True)
mock_path.iterdir = mock_iterdir
mock_anyio_path.return_value = mock_path
response = client.get(
"/api/setup/library",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
folders = {p["fs_slug"]: p["slug"] for p in response.json()["existing_platforms"]}
assert folders == {"gamecube": "ngc", "megadrive": "genesis", "gba": "gba"}
def test_create_setup_platforms_success(client, admin_user, access_token):

View File

@@ -7,6 +7,7 @@ from config.config_manager import Config
from utils.platform_aliases import (
PLATFORM_FS_ALIASES,
PLATFORM_SLUG_FOLDERS,
resolve_builtin_platform_slug,
resolve_fs_folder,
resolve_fs_slug,
resolve_platform_slug,
@@ -159,3 +160,11 @@ def test_example_configs_list_only_needed_overrides(config_file: Path):
if resolve_platform_slug(fs_slug, empty) == slug
}
assert not redundant
@pytest.mark.parametrize(
("folder", "slug"),
[("gamecube", "ngc"), ("MegaDrive", "genesis"), ("N64", "n64"), ("mystery", None)],
)
def test_resolves_builtin_slug_without_config(folder: str, slug: str | None):
assert resolve_builtin_platform_slug(folder) == slug

View File

@@ -175,6 +175,16 @@ def _to_slug(name: str) -> str:
return alias.value if alias else name
def resolve_builtin_platform_slug(fs_slug: str) -> str | None:
"""Resolve a folder name to a platform slug by its name or built-in alias.
Returns:
The platform slug, or None when the folder needs a config mapping.
"""
slug = _to_slug(fs_slug)
return slug if slug in UPS else None
def resolve_platform_slug(fs_slug: str, config: Config) -> str:
"""Resolve a platform folder name to a RomM platform slug."""
key = fs_slug.lower()

View File

@@ -4,6 +4,7 @@
/* eslint-disable */
export type FilesystemDict = {
FS_PLATFORMS: Array<string>;
FS_PLATFORM_SLUGS: Record<string, string>;
TITLE_ID_EXTRACTION_ENABLED: boolean;
};

View File

@@ -4,6 +4,7 @@
/* eslint-disable */
export type SetupExistingPlatform = {
fs_slug: string;
slug: string;
rom_count: number;
};

View File

@@ -0,0 +1,101 @@
import { mount } from "@vue/test-utils";
import { describe, expect, it, vi } from "vitest";
import type { SetupExistingPlatform } from "@/__generated__";
import { RCheckbox } from "@/lib";
import { platformFixture } from "@/utils/platform.fixtures";
import SetupStepPlatforms from "./SetupStepPlatforms.vue";
vi.mock("vue-i18n");
const supported = [
platformFixture({ slug: "ngc", name: "Nintendo GameCube" }),
platformFixture({ slug: "genesis", name: "Sega Genesis" }),
platformFixture({ slug: "n64", name: "Nintendo 64" }),
];
function mountStep(
existing: SetupExistingPlatform[],
supportedPlatforms = supported,
) {
return mount(SetupStepPlatforms, {
props: {
libraryInfo: {
library_ready: true,
library_structure: "{platform}/roms",
existing_platforms: existing,
supported_platforms: supportedPlatforms,
},
selectedNewPlatforms: [],
},
global: {
stubs: {
PlatformIcon: true,
RChip: { template: "<span class='chip'><slot /></span>" },
RCollapsible: true,
REmptyState: true,
RIcon: true,
RSegmentedControl: true,
RTag: true,
RTextField: true,
},
},
});
}
function detectedRows(wrapper: ReturnType<typeof mountStep>) {
return wrapper.findAll("[data-state='detected']").map((row) => ({
name: row.get(".r-setup-platforms__item-name").text(),
folder: row.get(".r-setup-platforms__item-slug").text(),
roms: row.get(".r-setup-platforms__item-state .chip").text(),
}));
}
async function selectAll(wrapper: ReturnType<typeof mountStep>) {
await wrapper.getComponent(RCheckbox).vm.$emit("update:modelValue", true);
return wrapper.emitted("update:selectedNewPlatforms")?.[0]?.[0];
}
describe("SetupStepPlatforms detected folders", () => {
it("identifies alias folders by their resolved slug, one row per folder", () => {
const wrapper = mountStep([
{ fs_slug: "gamecube", slug: "ngc", rom_count: 2 },
{ fs_slug: "megadrive", slug: "genesis", rom_count: 3 },
{ fs_slug: "genesis", slug: "genesis", rom_count: 1 },
{ fs_slug: "mystery", slug: "mystery", rom_count: 4 },
]);
expect(detectedRows(wrapper)).toEqual([
{ name: "mystery", folder: "mystery", roms: "4" },
{ name: "Nintendo GameCube", folder: "gamecube", roms: "2" },
{ name: "Sega Genesis", folder: "megadrive", roms: "3" },
{ name: "Sega Genesis", folder: "genesis", roms: "1" },
]);
});
it("only offers platforms that no folder resolves to", async () => {
const wrapper = mountStep([
{ fs_slug: "gamecube", slug: "ngc", rom_count: 2 },
]);
expect(await selectAll(wrapper)).toEqual(["genesis", "n64"]);
});
it("matches a platform row whose fs_slug is the alias folder", async () => {
const wrapper = mountStep(
[{ fs_slug: "gamecube", slug: "ngc", rom_count: 0 }],
[
platformFixture({
slug: "ngc",
fs_slug: "gamecube",
name: "Nintendo GameCube",
}),
platformFixture({ slug: "n64", name: "Nintendo 64" }),
],
);
expect(detectedRows(wrapper)).toEqual([
{ name: "Nintendo GameCube", folder: "gamecube", roms: "0" },
]);
expect(await selectAll(wrapper)).toEqual(["n64"]);
});
});

View File

@@ -65,42 +65,33 @@ const SEARCH_LIMIT = 80;
// through the cracks.
const detectedSlugSet = computed(
() => new Set(props.libraryInfo.existing_platforms.map((p) => p.fs_slug)),
() => new Set(props.libraryInfo.existing_platforms.map((p) => p.slug)),
);
const romCountBySlug = computed(() => {
const map = new Map<string, number>();
for (const p of props.libraryInfo.existing_platforms)
map.set(p.fs_slug, p.rom_count);
return map;
});
const supportedSlugSet = computed(
() => new Set(props.libraryInfo.supported_platforms.map((p) => p.fs_slug)),
const supportedBySlug = computed(
() => new Map(props.libraryInfo.supported_platforms.map((p) => [p.slug, p])),
);
// One row per folder, so an alias folder shows its own name and rom count.
const detectedPlatforms = computed<Array<Platform & { unidentified: boolean }>>(
() => {
if (!props.libraryInfo.library_ready) return [];
const identified = props.libraryInfo.supported_platforms
.filter((p) => detectedSlugSet.value.has(p.fs_slug))
.map((p) => ({ ...p, unidentified: false }));
const unidentified = props.libraryInfo.existing_platforms
.filter((p) => !supportedSlugSet.value.has(p.fs_slug))
.map(
(p) =>
({
fs_slug: p.fs_slug,
slug: p.fs_slug,
return props.libraryInfo.existing_platforms
.map((p) => {
const supported = supportedBySlug.value.get(p.slug);
return {
...(supported ?? {
slug: p.slug,
name: p.fs_slug,
family_name: UNIDENTIFIED,
generation: 999,
unidentified: true,
}) as Platform & { unidentified: boolean },
);
return [...identified, ...unidentified].sort((a, b) =>
(a.name ?? a.fs_slug).localeCompare(b.name ?? b.fs_slug),
);
}),
fs_slug: p.fs_slug,
rom_count: p.rom_count,
unidentified: !supported,
} as Platform & { unidentified: boolean };
})
.sort((a, b) => (a.name ?? a.fs_slug).localeCompare(b.name ?? b.fs_slug));
},
);
@@ -163,11 +154,11 @@ const filteredDetectedPlatforms = computed(() => {
// ── Supported (selectable) platforms ───────────────────────────────
//
// Filter out anything already on disk, since those are shown in the detected
// section. We never present the same fs_slug twice.
// section. We never present the same platform twice.
const supportedAvailable = computed<Platform[]>(() =>
props.libraryInfo.supported_platforms.filter(
(p) => !detectedSlugSet.value.has(p.fs_slug),
(p) => !detectedSlugSet.value.has(p.slug),
),
);
@@ -230,7 +221,6 @@ function isSelected(slug: string): boolean {
}
function togglePlatform(slug: string, next: boolean) {
if (detectedSlugSet.value.has(slug)) return;
const set = new Set(props.selectedNewPlatforms);
if (next) set.add(slug);
else set.delete(slug);
@@ -238,9 +228,7 @@ function togglePlatform(slug: string, next: boolean) {
}
function newSlugsInGroup(items: Platform[]): string[] {
return items
.filter((p) => !detectedSlugSet.value.has(p.fs_slug))
.map((p) => p.fs_slug);
return items.map((p) => p.fs_slug);
}
function groupSelectedState(items: Platform[]): boolean | null {
@@ -404,29 +392,21 @@ const detectedPlatformCount = computed(
</span>
</div>
<div class="r-setup-platforms__item-state">
<template v-if="platform.unidentified">
<RTag size="x-small" tone="warning">
{{ t("setup.unidentified") }}
</RTag>
<RChip
size="x-small"
variant="translucent"
color="warning"
prepend-icon="mdi-disc"
:aria-label="t('setup.games')"
>
{{ romCountBySlug.get(platform.fs_slug) ?? 0 }}
</RChip>
</template>
<RTag
v-if="platform.unidentified"
size="x-small"
tone="warning"
>
{{ t("setup.unidentified") }}
</RTag>
<RChip
v-else
size="x-small"
variant="translucent"
color="primary"
:color="platform.unidentified ? 'warning' : 'primary'"
prepend-icon="mdi-disc"
:aria-label="t('setup.games')"
>
{{ romCountBySlug.get(platform.fs_slug) ?? 0 }}
{{ platform.rom_count }}
</RChip>
</div>
</li>

View File

@@ -46,6 +46,12 @@ vi.mock("@/composables/usePlatformIconCache", () => ({
const N64 = { id: 1, slug: "n64", name: "Nintendo 64", display_name: "N64" };
const PS2 = { id: 2, slug: "ps2", name: "PlayStation 2", display_name: "PS2" };
const NGC = {
id: 3,
slug: "ngc",
name: "Nintendo GameCube",
display_name: "GameCube",
};
// Exposes the built rows and renders the Platform cell the edit actions hang off.
const RTableStub = {
@@ -55,9 +61,13 @@ const RTableStub = {
'<div><slot v-for="row in items" name="cell.platform" :row="row" /></div>',
};
async function mountWith(folders: string[]) {
async function mountWith(
folders: string[],
folderSlugs: Record<string, string> = {},
) {
const heartbeat = storeHeartbeat();
heartbeat.value.FILESYSTEM.FS_PLATFORMS = folders;
heartbeat.value.FILESYSTEM.FS_PLATFORM_SLUGS = folderSlugs;
vi.spyOn(heartbeat, "fetchHeartbeat").mockResolvedValue(heartbeat.value);
const wrapper = mount(FolderMappingsSection, {
@@ -123,12 +133,35 @@ describe("FolderMappingsSection", () => {
expect(rows[0]).toMatchObject({ slug: "ps2", type: "variant" });
});
it("marks a folder matching a platform slug as auto-detected whatever its case", async () => {
const { rows } = await mountWith(["PS2"]);
it("marks a folder the backend resolves to a platform as auto-detected", async () => {
const { rows } = await mountWith(["PS2"], { PS2: "ps2" });
expect(rows[0]).toMatchObject({ slug: "ps2", type: "auto" });
});
it("marks a built-in alias folder as auto-detected", async () => {
getSupportedPlatforms.mockResolvedValue({ data: [N64, PS2, NGC] });
const { rows } = await mountWith(["gamecube", "unknown"], {
gamecube: "ngc",
});
expect(rows).toEqual([
{
fsSlug: "gamecube",
slug: "ngc",
displayName: "GameCube",
type: "auto",
},
{
fsSlug: "unknown",
slug: undefined,
displayName: undefined,
type: null,
},
]);
});
// A bare add on a folder that already has a binding is a no-op server-side.
it("replaces the binding when a mapped folder is pointed at another platform", async () => {
storeConfig().config.PLATFORMS_BINDING = { "nintendo 64": "n64" };

View File

@@ -63,9 +63,7 @@ const TYPE_ORDER: Record<NonNullable<RowType> | "none", number> = {
const mappings = computed<Row[]>(() => {
const rows: Row[] = [];
const folders = heartbeat.value?.FILESYSTEM?.FS_PLATFORMS || [];
const autoSlug: Record<string, string | undefined> = {};
for (const p of supportedPlatforms.value) autoSlug[p.slug] = p.slug;
const autoSlug = heartbeat.value?.FILESYSTEM?.FS_PLATFORM_SLUGS || {};
for (const folder of folders) {
const binding = configStore.getPlatformBinding(folder);
@@ -90,8 +88,7 @@ const mappings = computed<Row[]>(() => {
});
continue;
}
// Platform slugs are lowercase; the folder on disk may not be.
const auto = autoSlug[folder.toLowerCase()];
const auto = autoSlug[folder];
if (auto) {
const platform = supportedPlatforms.value.find((p) => p.slug === auto);
rows.push({

View File

@@ -40,6 +40,7 @@ const defaultHeartbeat: Heartbeat = {
},
FILESYSTEM: {
FS_PLATFORMS: [],
FS_PLATFORM_SLUGS: {},
TITLE_ID_EXTRACTION_ENABLED: false,
},
EMULATION: {