# Local-library compatibility work

Parity stage 5 is in progress. This document distinguishes the scanner/import
foundation from remaining anime metadata, artwork and playback work.

## Verified scanner foundation

The shared scanner prepares its file backend before listing or checking paths.
Existing `metadata.json` and cover files use asynchronous bounded reads on every
platform: metadata is limited to 64 KiB and cover bytes to 4 MiB. Invalid/oversized
optional files fall back without removing existing library data. Cancellation
propagates. Existing fingerprint caches remain in use.

After asynchronous reads, the scanner rereads the current title/chapter records
inside its write transaction. Reading progress, bookmarks, categories, notes and
covers changed during the scan survive. Deleted or rebound captured records are
not recreated or overwritten by a late scan result. Original files are not modified.

Browser OPFS storage now provides readable-file/folder listings from its prepared
inventory. Native and browser listings share the readable extension definition.
An index of immediate child directories supports traversal without repeatedly
scanning the whole inventory; traversal is iterative. Empty directories are kept
distinct from missing/unreadable directories, including after file deletion and
reload, so reconciliation can identify readable empty roots accurately. Profile
path isolation remains enforced.

Verification: 28 desktop checks and 10 Kotlin/Wasm browser tests passed, with no
failures, errors or skipped tests, and Android, iOS simulator ARM64, desktop and web
compiled. Browser checks exercise the real OPFS/Kotlin boundary, metadata/cover
reads, repeated scans, empty-directory reload and existing streamed archive/storage
regressions. Common tests suspend metadata reads while user edits/deletion occur.
These checks do not claim native video playback or finished browser import controls.

## File and folder import

Local media management includes **Import files** and **Import folder** on Android,
iOS, desktop and web. Choose manga/anime/novel before opening the picker. Imports
copy supported media and accompanying metadata/subtitles into the captured profile;
source files stay unchanged. Folder structure and the selected folder's name are
preserved. Native folder-reference scanning remains available in download settings.
Desktop/web support multiple file selection; the Android/iOS document picker selects
one file at a time. All platforms support folder import.

Readers use at most 64 KiB per chunk and await the destination writer before reading
the next chunk. Browser media uses bounded Blob slices rather than the existing
whole-file backup picker. Android uses read-only SAF grants. iOS opens media in place through the document
picker, stores minimal bookmarks, explicitly balances security-scoped access, and
coordinates provider reads on a background dispatcher for their entire suspended
lifetime. Cancellation cancels coordination and joins the reader before releasing
access. See Apple’s [document-access guide](https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/DocumentPickerProgrammingGuide/AccessingDocuments/AccessingDocuments.html) and
[directory-access guidance](https://developer.apple.com/documentation/uikit/providing-access-to-directories). Native traversal skips hidden entries,
symlinks and special files. Selections are bounded to 10,000 supported files, 50,000
visited entries on native, and a 256 KiB total filename budget. Invalid paths,
case-insensitive collisions and file/directory name conflicts fail before copying.
Progress updates coalesce at 200 ms intervals, with explicit initial/final counts,
so large files and bursts of small files do not emit UI state for every chunk.

Copies live under `<profile downloadRoot>/local-imports/<id>/<media type>`, outside
the built-in `local` scanner root. Scans of configured ancestors exclude this
managed area; only published roots expose it, preventing partial entries and duplicate
completed entries. A settings transaction adds that root only when
all copies and a READY journal have committed. Concurrent settings edits survive.
Profile retirement cancels and joins import work before closing file storage.
Cancellation/source-size changes/copy errors remove unpublished partial copies;
existing originals and completed imports are never rolled back by that cleanup.
Canonical ownership checks reject redirected import roots before writes,
publication, recovery discard and error cleanup. If a directory changes during a
copy, the importer stops and leaves quarantined data rather than cleaning through
the redirected path. Source grants and readers close when cancellation propagates.

Interrupted COPY journals appear under **Interrupted imports** and can be explicitly
discarded. READY journals offer **Finish saved import**: recovery checks file presence
and sizes, publishes idempotently and retires the journal only after settings persist.
READY content cannot be discarded through incomplete-copy cleanup because publication
may already have succeeded. Malformed journals never authorize content deletion.
Unrecognizable journals remain on disk for investigation. Imports need disk space for
a complete copy; quota/read errors are surfaced. Codec support still depends on the
platform player; copying a format does not add a codec. Leaving the manager cancels
its active copy; interrupted incomplete copies must be selected again. Completed
copies remain protected. EPUB chapter/resource reading is described below.

Standalone image files now produce a single reader page on every platform, including
images listed as chapters by local scans. JVM strict inventory validates decodability
without reusing cached content; direct file URLs preserve encoded spaces/percent signs.

Browser media URLs and the media worker use the app page's base URL, so a script
served from an assets directory cannot accidentally register a worker outside the
page's scope. Serve `browser-files-sw.js`, `browser-archives.js` and its pinned vendor
bundle alongside the app page, as the web distribution does. Activation/claim waits
are bounded, failed preparation can retry, and there is no unbounded
`navigator.serviceWorker.ready` wait. Browser tests serve and fetch an actual image
through this worker rather than replacing it with a mock.

Local media URLs also bypass remote image optimizers, including when the web app is
hosted on public HTTPS, so private filenames are not submitted to optimization services.

Verification: 77 desktop checks and 43 Kotlin/Wasm browser tests passed with no
failures, errors or skips. Android, iOS simulator ARM64, desktop and web compiled.
Checks cover streaming/backpressure, cancellation, profile retirement, journal recovery,
size/path conflicts, redirected roots, concurrent settings and ancestor-scan visibility.
Browser checks use actual OPFS, large Blob slices and the media service worker. The
standalone Chrome storage/archive harness also passed. Two native iOS tests passed
when the final test binary was spawned in a fully booted simulator: scoped/coordinated
reads preserve source bytes, bound chunks and stop on cancellation. Gradle’s native
test runner still failed these two tests because its standalone execution lacked
working file coordination; its report is not counted as a passing suite.

Native document-picker UI, iCloud/third-party provider UI and device playback have
not been exercised. To run the native integration checks, boot the simulator fully
and spawn the absolute path of `composeApp/build/bin/iosSimulatorArm64/debugTest/test.kexe`
with `xcrun simctl spawn <device> <absolute-test-binary>` and the quoted argument
`'--ktest_filter=eu.friedcutlet.yokan.services.files.IosLocalMediaInputTest.*'` after linking
the native test binary.

## Asynchronous EPUB reading

The scanner and profile-owned novel reader use asynchronous EPUB methods, with native
implementations retaining their existing readers. The browser now reads container,
package, spine chapters and referenced images directly from OPFS ZIP entries. It
uses the same manifest interpretation as native readers, including spine positions,
relative paths and percent-encoded spaces. A read operation opens one bounded index
and one immutable File snapshot, then closes it after use. Cancellation joins an
active bounded JavaScript read before closing its archive or retiring file storage;
a cancelled coroutine cannot stop an already-running Promise. It does not extract or
buffer the complete book. Chapter inventories use the existing bounded-cache design
(32 books / 2,000 chapters), keyed by file metadata; a full rescan invalidates them.

Browser limits are 1 MiB per container/package file, 8 MiB per chapter, 16 MiB per
embedded resource and 64 MiB total reads while building one chapter inventory, in
addition to the existing ZIP index/entry limits. CRC and output-size validation apply
to decompression. Unsupported/malformed books retain a fallback scan entry rather
than preventing other titles from scanning; opening an unavailable chapter reports
an error. Optional missing/unreadable images retain existing fallback behavior.
The shared rich-content parser runs once, then awaits referenced images sequentially,
deduplicates repeated references and retains at most 32 MiB of embedded image bytes
per chapter. It preserves text, links and external-image behavior. This is the
existing rich novel renderer, not a full browser engine for arbitrary EPUB CSS.

Verification for this addition passed 89 desktop checks and 45 Kotlin/Wasm browser
tests, with no failures, errors or skips, and compiled desktop, Android, iOS simulator
ARM64 and web. The browser integration imports a real EPUB into OPFS, scans spine
order and encoded paths, reads text and embedded images through the profile-owned
reader without a source runtime, verifies cache reuse/full-rescan invalidation and
retained progress, rejects oversized chapters, checks CRC failures, and holds a real
archive read across cancellation to verify joined finalization. Shared tests cover
suspending manifest reads, image deduplication, cancellation and existing reader
ownership/lifecycle behavior. The standalone Chrome archive/storage harness passed
after the JavaScript changes. Earlier import counts above are separate evidence.

## Animetail title details

Anime roots also read `details.json` beside the title’s files, using bounded 64 KiB
asynchronous reads and the same fingerprint cache/full-rescan invalidation as legacy
metadata. Nonblank title, description, author and artist fields and valid genre lists override
`metadata.json`; legacy artwork, language and omitted fields remain available. An
explicit empty genre list clears the file-provided genres. Malformed or oversized
optional details fall back to legacy metadata, and cancellation propagates.

Numeric statuses follow the pinned SAnime constants: 0 unknown, 1 ongoing, 2 completed,
3 licensed, 4 publishing finished, 5 cancelled, 6 on hiatus and 7 upcoming. The initial
title-details implementation mapped licensed/upcoming to Unknown; the follow-up below
adds distinct values. Legacy `metadata.json` keeps its original six enum ordinals.
Cast metadata and episode sidecars are described below.

Verification passed 51 desktop checks and 47 Kotlin/Wasm browser tests, with no
failures, errors or skips, and compiled all four targets. Tests cover all eight
source status numbers, separate legacy interpretation, empty genres, cached rereads,
malformed fallback, cancellation and preservation of edits/progress. A real OPFS
fixture verifies merging details with legacy artwork/language and stable identities
after a full rescan. These counts belong to this title-details regression run; the
earlier EPUB/import suites are separate evidence.

The status follow-up appends Licensed and Upcoming to Yokan's database/domain enums,
preserving existing ordinal meanings and SQLite's stored names. Native backups and
native hub documents retain them; library status search and grouping distinguish
them from Unknown. Tachiyomi-family backup import maps licensed for manga/anime and
upcoming only for anime, matching the separate source constants. Mangayomi export
keeps its six wire ordinals and downgrades unsupported statuses to Unknown. Legacy
sync likewise sends UNKNOWN; an incoming UNKNOWN preserves an existing local
Licensed/Upcoming value, while a supported explicit incoming status can replace it.
The old protocol cannot transport that distinction to another installation or
express clearing it to Unknown on this installation. Verification passed 152 desktop
checks and 83 Kotlin/Wasm browser tests without failures/errors/skips and compiled
all four targets. Tests cover SQLite close/reopen, native backup replacement and hub
documents, fixed legacy export ordinals, legacy sync round trips, protobuf source
status mapping, search/grouping and real OPFS sidecar rescans.

## Episode sidecars and stable numbering

Anime title/season folders read `episodes.json` asynchronously with a 1 MiB file
limit and at most 10,000 entries. Valid rows require a finite nonnegative numeric
`episode_number`. A sorted index uses binary search instead of scanning every row
for every chapter. Exact duplicates keep their first declaration; a single nearby
match within 0.0001 supports floating-point source numbers. Ambiguous nearby matches
are ignored instead of applying metadata to an uncertain episode. Both the fingerprint
cache and the cache used during each scan are limited to 128 sidecars and an estimated
8 MiB of retained entries each; full rescans invalidate the fingerprint cache.

Matched rows can supply display name, valid ISO local upload date, explicit filler
flag, scanlator, summary and preview URL. Missing/invalid optional fields preserve
existing values; explicit false filler and empty scanlator/summary values are applied.
Invalid/oversized files fall back to ordinary filename-based scanning. Cancellation
propagates. Previews accept HTTP(S) or existing paths below the title folder; relative
paths cannot traverse out of that folder. SAF sibling images use their actual provider
URI. Sibling preview images are excluded from a title's episode list.

Optional stored `number`, `season` and `numberingName` fields separate display titles
from original numbering and release labels. Reader order, duplicate selection,
equivalent read actions, gap detection, download policy and player episode lookups
use them. Existing records default to null and retain name-based behavior. Room v14
adds nullable columns through a nondestructive v13 migration. A recognized season
folder name supplies the season when the episode filename has no season label.
File paths and captured database IDs remain unchanged when sidecars rename episodes;
reading position, bookmarks and read state survive rescans, including edits made
while the asynchronous metadata read is suspended.

Native backup serialization and replacement retain the numbering fields. Backup
merge fills missing numbers/labels and keeps existing local choices and progress.
Legacy Mangayomi sync leaves these locally stored fields intact because its wire
schema cannot represent them. Android SAF sidecars resolve provider children from
both tree-root and explicit-document URIs without splitting opaque document IDs.

Verification passed 199 desktop checks, 111 Kotlin/Wasm browser tests and 8 Android
unit checks, with no failures, errors or skips; desktop, Android, iOS simulator
ARM64 and web compiled. Tests include a real Room v13 upgrade/reopen, OPFS episode
sidecars, backup merge/replace and legacy sync, number/release/download/reader rules,
and cancellation/concurrent edits/deletion. Android checks cover URI path planning
and archive reads; actual document-provider UI remains unverified. Separate season
records were added later (`SEASON_RECORDS.md`).

## Nested anime episode discovery

Anime episode lists expand supported files at the title root and one immediate
subfolder level. Immediate listings are implemented on Android SAF, iOS scoped
storage, desktop and browser OPFS; they retain full file names and actual provider
URIs. Hidden names, preview images and deeper subfolders are excluded from these
episode lists. Recognized subfolder season labels supply the season when a file
does not declare one. A matching subfolder `episodes.json` row takes precedence
over a matching title-root row; its relative preview is resolved from that subfolder.
SAF previews can traverse existing child directories by display name, without
deriving paths from document IDs. Existing title discovery and virtual identities
are preserved. Old folder-as-chapter rows are retained for explicit reconciliation,
because their progress cannot be safely assigned to a particular video.

Verification passed 202 desktop checks, 113 Kotlin/Wasm browser tests and 8 Android
unit checks, with no failures/errors/skips, and compiled all four targets. Native
filesystem and real OPFS fixtures verify one-level expansion, season-zero metadata,
preview resolution and repeated scans with retained IDs/progress. A shared fixture
uses opaque provider IDs that contain neither names nor extensions. The standalone
Chrome storage/archive harness passed. This discovery change does not decode video
or generate artwork, and does not yet connect separate season titles through
parent/child navigation. The follow-up run below also checks the bounded per-scan cache.

## Selecting episodes by season

Anime details include an **All episodes** / **Season …** selector when season numbers
are available. It uses explicit stored seasons or recognized original source labels;
season zero remains selectable. Episodes without a recognized season stay accessible
through All episodes. Sorting, release selection, status filters and offline rules
apply within the selected season. Continuation, bulk download targets and chapter
selection use that displayed scope. If the selected season is removed, the view
returns to All episodes. Selection lives in the detail ViewModel and does not alter
stored titles, episodes or progress. The same control is used in compact and wide
layouts on all four targets, with keyed virtualized items and resource-based labels.

Verification passed 63 desktop checks and 50 Kotlin/Wasm browser tests, with no
failures/errors/skips, and compiled all four targets. The actual ViewModel test
checks explicit/inferred/zero/unknown seasons, invalid selections, scoped continuation
and bulk downloads, selection cleanup and season removal. The rendered compact
(360px, dark) and wide (1024px, light) desktop Compose layouts were inspected and
received a scoped `ship` finish review with no material fixes. This is shared layout
evidence, not Android/iOS device, native accessibility or frame-rate verification.
This is episode filtering within one indexed title; separate season records are
covered in `SEASON_RECORDS.md`.

## Cast metadata

Anime `details.json` and legacy `metadata.json` can declare `cast` rows with a name
and optional role, character and `image_url`. The existing 64 KiB metadata read limit
still applies; cast arrays are limited to 500 rows. Invalid rows are skipped, exact
name/role/character duplicates keep the first declaration, omitted or malformed cast
preserves existing credits, and an explicit empty array clears them. Portraits accept
HTTP(S) or existing relative images below the title folder, including actual SAF
provider children. Referenced portraits are excluded from automatic title-cover
selection. Original media and portrait bytes are not changed.

The shared detail screen renders names, roles, characters and optional portraits in
a keyed, virtualized horizontal list using the existing image loader and fallback
initials. Metadata cache retention is bounded to 512 entries and an estimated 8 MiB.
Native Room v15 adds the owned `manga_credit` child table with ordered composite keys
and cascading title deletion. Credits are hydrated in one table read, and progress-only
title writes leave the child rows unchanged. Native backup merge fills missing cast
without replacing existing local cast; native replacement and hub documents retain it.
Legacy Mangayomi export omits unsupported cast and legacy pulls keep local cast.
Local metadata export includes the shared credit schema.

Verification passed 182 desktop checks and 65 Kotlin/Wasm browser tests without
failures/errors/skips, and Android, iOS simulator ARM64, desktop and web compiled.
Tests cover real Room v14→15 migration, ordered 500-credit persistence/reopen,
replacement/reordering, cascading deletion and a SQL counter confirming progress
updates make no cast-row writes. Shared scanner/backup/sync/ViewModel checks and real
OPFS sidecar portrait/clear checks passed. Compact/wide desktop Compose captures
received a scoped `ship` finish review with no material fixes; native-device rendering,
accessibility, enlarged text and frame rate remain unverified. Source extension cast
and related-title groups are tracked separately below.

## Source extension cast

The common JavaScript/Mihon detail decoder accepts the same optional `cast` schema
and preserves ordering and the distinction between omission, invalid data and an
explicit empty list. Saved credits feed the shared detail screen and existing
backup/sync paths on every target. Source portraits accept only HTTP(S), with
relative references resolved against the source base URL. File/content/OPFS/data
URLs, credentials and malformed URLs are discarded without discarding the actor.
Offline detail fallback now selects the requested source first and returns no
chapters for an unknown title, avoiding collisions when sources share a relative URL.

Verification passed 54 desktop checks and 49 Kotlin/Wasm browser tests without
failures/errors/skips, and all four targets compiled. This includes an actual QuickJS
extension-to-repository round trip, shared JS/Mihon service mapping, source-isolated
offline fallback, portrait validation, explicit clear and preservation of notes,
bookmarks and progress. This consumes credits when the extension or configured
Mihon bridge includes them in its detail response; it does not add cast support to
external bridge binaries that omit the field. The bundled Android bridge now exposes
optional `SAnime.cast`, compatible `Credit` objects and Upcoming, and forwards cast
through its detail JSON. Omitted credits from older APKs remain usable; explicit empty
credits remain an explicit clear. Fourteen Android bridge unit checks passed and the
Android app compiled. These include a Java class compiled against a deliberately older
interface and loaded against the current host, plus Jackson/Kotlin serialization.
External desktop/iOS/web bridge binaries that omit cast require an upstream update;
the common client is ready to consume the field. Source-related entries are covered
in `SOURCE_RELATIONS.md`.

## Remaining stage 5 scope

- Verify native picker/provider UI.
- Cast, related-entry and season fields in external bridge binaries that omit them
  (outside this repository).
- On-device Android/iOS video playback (shared resolution and desktop/web playback are verified).

Season records, local-video playback verification and frame-derived artwork are
complete; see `SEASON_RECORDS.md` and `LOCAL_VIDEO_ARTWORK.md`. Folders without episode
files now become Seasons titles; the flattened per-title season selector described above
applies to titles whose folder has its own episode files.

The pinned upstream metadata definitions inspected for the next implementation are
[AnimeDetails](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/core-metadata/src/main/java/tachiyomi/core/metadata/tachiyomi/AnimeDetails.kt),
[EpisodeDetails](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/core-metadata/src/main/java/tachiyomi/core/metadata/tachiyomi/EpisodeDetails.kt)
and [LocalAnimeSource](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/source-local/src/main/kotlin/tachiyomi/source/local/entries/anime/LocalAnimeSource.kt).
Their numeric source statuses use the
[SAnime constants](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/source-api/src/main/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt),
which differ from Yokan's legacy metadata enum ordinals. They must be mapped by
format rather than silently reusing the legacy ordinal parser.
