Yokan / rebuild
Course 1 8624561

LOCAL_LIBRARY_COMPATIBILITY.md

docs/features/LOCAL_LIBRARY_COMPATIBILITY.md

documentation / design asset353 lines
1# Local-library compatibility work23Parity stage 5 is in progress. This document distinguishes the scanner/import4foundation from remaining anime metadata, artwork and playback work.56## Verified scanner foundation78The shared scanner prepares its file backend before listing or checking paths.9Existing `metadata.json` and cover files use asynchronous bounded reads on every10platform: metadata is limited to 64 KiB and cover bytes to 4 MiB. Invalid/oversized11optional files fall back without removing existing library data. Cancellation12propagates. Existing fingerprint caches remain in use.1314After asynchronous reads, the scanner rereads the current title/chapter records15inside its write transaction. Reading progress, bookmarks, categories, notes and16covers changed during the scan survive. Deleted or rebound captured records are17not recreated or overwritten by a late scan result. Original files are not modified.1819Browser OPFS storage now provides readable-file/folder listings from its prepared20inventory. Native and browser listings share the readable extension definition.21An index of immediate child directories supports traversal without repeatedly22scanning the whole inventory; traversal is iterative. Empty directories are kept23distinct from missing/unreadable directories, including after file deletion and24reload, so reconciliation can identify readable empty roots accurately. Profile25path isolation remains enforced.2627Verification: 28 desktop checks and 10 Kotlin/Wasm browser tests passed, with no28failures, errors or skipped tests, and Android, iOS simulator ARM64, desktop and web29compiled. Browser checks exercise the real OPFS/Kotlin boundary, metadata/cover30reads, repeated scans, empty-directory reload and existing streamed archive/storage31regressions. Common tests suspend metadata reads while user edits/deletion occur.32These checks do not claim native video playback or finished browser import controls.3334## File and folder import3536Local media management includes **Import files** and **Import folder** on Android,37iOS, desktop and web. Choose manga/anime/novel before opening the picker. Imports38copy supported media and accompanying metadata/subtitles into the captured profile;39source files stay unchanged. Folder structure and the selected folder's name are40preserved. Native folder-reference scanning remains available in download settings.41Desktop/web support multiple file selection; the Android/iOS document picker selects42one file at a time. All platforms support folder import.4344Readers use at most 64 KiB per chunk and await the destination writer before reading45the next chunk. Browser media uses bounded Blob slices rather than the existing46whole-file backup picker. Android uses read-only SAF grants. iOS opens media in place through the document47picker, stores minimal bookmarks, explicitly balances security-scoped access, and48coordinates provider reads on a background dispatcher for their entire suspended49lifetime. Cancellation cancels coordination and joins the reader before releasing50access. See Apple’s [document-access guide](https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/DocumentPickerProgrammingGuide/AccessingDocuments/AccessingDocuments.html) and51[directory-access guidance](https://developer.apple.com/documentation/uikit/providing-access-to-directories). Native traversal skips hidden entries,52symlinks and special files. Selections are bounded to 10,000 supported files, 50,00053visited entries on native, and a 256 KiB total filename budget. Invalid paths,54case-insensitive collisions and file/directory name conflicts fail before copying.55Progress updates coalesce at 200 ms intervals, with explicit initial/final counts,56so large files and bursts of small files do not emit UI state for every chunk.5758Copies live under `<profile downloadRoot>/local-imports/<id>/<media type>`, outside59the built-in `local` scanner root. Scans of configured ancestors exclude this60managed area; only published roots expose it, preventing partial entries and duplicate61completed entries. A settings transaction adds that root only when62all copies and a READY journal have committed. Concurrent settings edits survive.63Profile retirement cancels and joins import work before closing file storage.64Cancellation/source-size changes/copy errors remove unpublished partial copies;65existing originals and completed imports are never rolled back by that cleanup.66Canonical ownership checks reject redirected import roots before writes,67publication, recovery discard and error cleanup. If a directory changes during a68copy, the importer stops and leaves quarantined data rather than cleaning through69the redirected path. Source grants and readers close when cancellation propagates.7071Interrupted COPY journals appear under **Interrupted imports** and can be explicitly72discarded. READY journals offer **Finish saved import**: recovery checks file presence73and sizes, publishes idempotently and retires the journal only after settings persist.74READY content cannot be discarded through incomplete-copy cleanup because publication75may already have succeeded. Malformed journals never authorize content deletion.76Unrecognizable journals remain on disk for investigation. Imports need disk space for77a complete copy; quota/read errors are surfaced. Codec support still depends on the78platform player; copying a format does not add a codec. Leaving the manager cancels79its active copy; interrupted incomplete copies must be selected again. Completed80copies remain protected. EPUB chapter/resource reading is described below.8182Standalone image files now produce a single reader page on every platform, including83images listed as chapters by local scans. JVM strict inventory validates decodability84without reusing cached content; direct file URLs preserve encoded spaces/percent signs.8586Browser media URLs and the media worker use the app page's base URL, so a script87served from an assets directory cannot accidentally register a worker outside the88page's scope. Serve `browser-files-sw.js`, `browser-archives.js` and its pinned vendor89bundle alongside the app page, as the web distribution does. Activation/claim waits90are bounded, failed preparation can retry, and there is no unbounded91`navigator.serviceWorker.ready` wait. Browser tests serve and fetch an actual image92through this worker rather than replacing it with a mock.9394Local media URLs also bypass remote image optimizers, including when the web app is95hosted on public HTTPS, so private filenames are not submitted to optimization services.9697Verification: 77 desktop checks and 43 Kotlin/Wasm browser tests passed with no98failures, errors or skips. Android, iOS simulator ARM64, desktop and web compiled.99Checks cover streaming/backpressure, cancellation, profile retirement, journal recovery,100size/path conflicts, redirected roots, concurrent settings and ancestor-scan visibility.101Browser checks use actual OPFS, large Blob slices and the media service worker. The102standalone Chrome storage/archive harness also passed. Two native iOS tests passed103when the final test binary was spawned in a fully booted simulator: scoped/coordinated104reads preserve source bytes, bound chunks and stop on cancellation. Gradle’s native105test runner still failed these two tests because its standalone execution lacked106working file coordination; its report is not counted as a passing suite.107108Native document-picker UI, iCloud/third-party provider UI and device playback have109not been exercised. To run the native integration checks, boot the simulator fully110and spawn the absolute path of `composeApp/build/bin/iosSimulatorArm64/debugTest/test.kexe`111with `xcrun simctl spawn <device> <absolute-test-binary>` and the quoted argument112`'--ktest_filter=eu.friedcutlet.yokan.services.files.IosLocalMediaInputTest.*'` after linking113the native test binary.114115## Asynchronous EPUB reading116117The scanner and profile-owned novel reader use asynchronous EPUB methods, with native118implementations retaining their existing readers. The browser now reads container,119package, spine chapters and referenced images directly from OPFS ZIP entries. It120uses the same manifest interpretation as native readers, including spine positions,121relative paths and percent-encoded spaces. A read operation opens one bounded index122and one immutable File snapshot, then closes it after use. Cancellation joins an123active bounded JavaScript read before closing its archive or retiring file storage;124a cancelled coroutine cannot stop an already-running Promise. It does not extract or125buffer the complete book. Chapter inventories use the existing bounded-cache design126(32 books / 2,000 chapters), keyed by file metadata; a full rescan invalidates them.127128Browser limits are 1 MiB per container/package file, 8 MiB per chapter, 16 MiB per129embedded resource and 64 MiB total reads while building one chapter inventory, in130addition to the existing ZIP index/entry limits. CRC and output-size validation apply131to decompression. Unsupported/malformed books retain a fallback scan entry rather132than preventing other titles from scanning; opening an unavailable chapter reports133an error. Optional missing/unreadable images retain existing fallback behavior.134The shared rich-content parser runs once, then awaits referenced images sequentially,135deduplicates repeated references and retains at most 32 MiB of embedded image bytes136per chapter. It preserves text, links and external-image behavior. This is the137existing rich novel renderer, not a full browser engine for arbitrary EPUB CSS.138139Verification for this addition passed 89 desktop checks and 45 Kotlin/Wasm browser140tests, with no failures, errors or skips, and compiled desktop, Android, iOS simulator141ARM64 and web. The browser integration imports a real EPUB into OPFS, scans spine142order and encoded paths, reads text and embedded images through the profile-owned143reader without a source runtime, verifies cache reuse/full-rescan invalidation and144retained progress, rejects oversized chapters, checks CRC failures, and holds a real145archive read across cancellation to verify joined finalization. Shared tests cover146suspending manifest reads, image deduplication, cancellation and existing reader147ownership/lifecycle behavior. The standalone Chrome archive/storage harness passed148after the JavaScript changes. Earlier import counts above are separate evidence.149150## Animetail title details151152Anime roots also read `details.json` beside the title’s files, using bounded 64 KiB153asynchronous reads and the same fingerprint cache/full-rescan invalidation as legacy154metadata. Nonblank title, description, author and artist fields and valid genre lists override155`metadata.json`; legacy artwork, language and omitted fields remain available. An156explicit empty genre list clears the file-provided genres. Malformed or oversized157optional details fall back to legacy metadata, and cancellation propagates.158159Numeric statuses follow the pinned SAnime constants: 0 unknown, 1 ongoing, 2 completed,1603 licensed, 4 publishing finished, 5 cancelled, 6 on hiatus and 7 upcoming. The initial161title-details implementation mapped licensed/upcoming to Unknown; the follow-up below162adds distinct values. Legacy `metadata.json` keeps its original six enum ordinals.163Cast metadata and episode sidecars are described below.164165Verification passed 51 desktop checks and 47 Kotlin/Wasm browser tests, with no166failures, errors or skips, and compiled all four targets. Tests cover all eight167source status numbers, separate legacy interpretation, empty genres, cached rereads,168malformed fallback, cancellation and preservation of edits/progress. A real OPFS169fixture verifies merging details with legacy artwork/language and stable identities170after a full rescan. These counts belong to this title-details regression run; the171earlier EPUB/import suites are separate evidence.172173The status follow-up appends Licensed and Upcoming to Yokan's database/domain enums,174preserving existing ordinal meanings and SQLite's stored names. Native backups and175native hub documents retain them; library status search and grouping distinguish176them from Unknown. Tachiyomi-family backup import maps licensed for manga/anime and177upcoming only for anime, matching the separate source constants. Mangayomi export178keeps its six wire ordinals and downgrades unsupported statuses to Unknown. Legacy179sync likewise sends UNKNOWN; an incoming UNKNOWN preserves an existing local180Licensed/Upcoming value, while a supported explicit incoming status can replace it.181The old protocol cannot transport that distinction to another installation or182express clearing it to Unknown on this installation. Verification passed 152 desktop183checks and 83 Kotlin/Wasm browser tests without failures/errors/skips and compiled184all four targets. Tests cover SQLite close/reopen, native backup replacement and hub185documents, fixed legacy export ordinals, legacy sync round trips, protobuf source186status mapping, search/grouping and real OPFS sidecar rescans.187188## Episode sidecars and stable numbering189190Anime title/season folders read `episodes.json` asynchronously with a 1 MiB file191limit and at most 10,000 entries. Valid rows require a finite nonnegative numeric192`episode_number`. A sorted index uses binary search instead of scanning every row193for every chapter. Exact duplicates keep their first declaration; a single nearby194match within 0.0001 supports floating-point source numbers. Ambiguous nearby matches195are ignored instead of applying metadata to an uncertain episode. Both the fingerprint196cache and the cache used during each scan are limited to 128 sidecars and an estimated1978 MiB of retained entries each; full rescans invalidate the fingerprint cache.198199Matched rows can supply display name, valid ISO local upload date, explicit filler200flag, scanlator, summary and preview URL. Missing/invalid optional fields preserve201existing values; explicit false filler and empty scanlator/summary values are applied.202Invalid/oversized files fall back to ordinary filename-based scanning. Cancellation203propagates. Previews accept HTTP(S) or existing paths below the title folder; relative204paths cannot traverse out of that folder. SAF sibling images use their actual provider205URI. Sibling preview images are excluded from a title's episode list.206207Optional stored `number`, `season` and `numberingName` fields separate display titles208from original numbering and release labels. Reader order, duplicate selection,209equivalent read actions, gap detection, download policy and player episode lookups210use them. Existing records default to null and retain name-based behavior. Room v14211adds nullable columns through a nondestructive v13 migration. A recognized season212folder name supplies the season when the episode filename has no season label.213File paths and captured database IDs remain unchanged when sidecars rename episodes;214reading position, bookmarks and read state survive rescans, including edits made215while the asynchronous metadata read is suspended.216217Native backup serialization and replacement retain the numbering fields. Backup218merge fills missing numbers/labels and keeps existing local choices and progress.219Legacy Mangayomi sync leaves these locally stored fields intact because its wire220schema cannot represent them. Android SAF sidecars resolve provider children from221both tree-root and explicit-document URIs without splitting opaque document IDs.222223Verification passed 199 desktop checks, 111 Kotlin/Wasm browser tests and 8 Android224unit checks, with no failures, errors or skips; desktop, Android, iOS simulator225ARM64 and web compiled. Tests include a real Room v13 upgrade/reopen, OPFS episode226sidecars, backup merge/replace and legacy sync, number/release/download/reader rules,227and cancellation/concurrent edits/deletion. Android checks cover URI path planning228and archive reads; actual document-provider UI remains unverified. Separate season229records were added later (`SEASON_RECORDS.md`).230231## Nested anime episode discovery232233Anime episode lists expand supported files at the title root and one immediate234subfolder level. Immediate listings are implemented on Android SAF, iOS scoped235storage, desktop and browser OPFS; they retain full file names and actual provider236URIs. Hidden names, preview images and deeper subfolders are excluded from these237episode lists. Recognized subfolder season labels supply the season when a file238does not declare one. A matching subfolder `episodes.json` row takes precedence239over a matching title-root row; its relative preview is resolved from that subfolder.240SAF previews can traverse existing child directories by display name, without241deriving paths from document IDs. Existing title discovery and virtual identities242are preserved. Old folder-as-chapter rows are retained for explicit reconciliation,243because their progress cannot be safely assigned to a particular video.244245Verification passed 202 desktop checks, 113 Kotlin/Wasm browser tests and 8 Android246unit checks, with no failures/errors/skips, and compiled all four targets. Native247filesystem and real OPFS fixtures verify one-level expansion, season-zero metadata,248preview resolution and repeated scans with retained IDs/progress. A shared fixture249uses opaque provider IDs that contain neither names nor extensions. The standalone250Chrome storage/archive harness passed. This discovery change does not decode video251or generate artwork, and does not yet connect separate season titles through252parent/child navigation. The follow-up run below also checks the bounded per-scan cache.253254## Selecting episodes by season255256Anime details include an **All episodes** / **Season …** selector when season numbers257are available. It uses explicit stored seasons or recognized original source labels;258season zero remains selectable. Episodes without a recognized season stay accessible259through All episodes. Sorting, release selection, status filters and offline rules260apply within the selected season. Continuation, bulk download targets and chapter261selection use that displayed scope. If the selected season is removed, the view262returns to All episodes. Selection lives in the detail ViewModel and does not alter263stored titles, episodes or progress. The same control is used in compact and wide264layouts on all four targets, with keyed virtualized items and resource-based labels.265266Verification passed 63 desktop checks and 50 Kotlin/Wasm browser tests, with no267failures/errors/skips, and compiled all four targets. The actual ViewModel test268checks explicit/inferred/zero/unknown seasons, invalid selections, scoped continuation269and bulk downloads, selection cleanup and season removal. The rendered compact270(360px, dark) and wide (1024px, light) desktop Compose layouts were inspected and271received a scoped `ship` finish review with no material fixes. This is shared layout272evidence, not Android/iOS device, native accessibility or frame-rate verification.273This is episode filtering within one indexed title; separate season records are274covered in `SEASON_RECORDS.md`.275276## Cast metadata277278Anime `details.json` and legacy `metadata.json` can declare `cast` rows with a name279and optional role, character and `image_url`. The existing 64 KiB metadata read limit280still applies; cast arrays are limited to 500 rows. Invalid rows are skipped, exact281name/role/character duplicates keep the first declaration, omitted or malformed cast282preserves existing credits, and an explicit empty array clears them. Portraits accept283HTTP(S) or existing relative images below the title folder, including actual SAF284provider children. Referenced portraits are excluded from automatic title-cover285selection. Original media and portrait bytes are not changed.286287The shared detail screen renders names, roles, characters and optional portraits in288a keyed, virtualized horizontal list using the existing image loader and fallback289initials. Metadata cache retention is bounded to 512 entries and an estimated 8 MiB.290Native Room v15 adds the owned `manga_credit` child table with ordered composite keys291and cascading title deletion. Credits are hydrated in one table read, and progress-only292title writes leave the child rows unchanged. Native backup merge fills missing cast293without replacing existing local cast; native replacement and hub documents retain it.294Legacy Mangayomi export omits unsupported cast and legacy pulls keep local cast.295Local metadata export includes the shared credit schema.296297Verification passed 182 desktop checks and 65 Kotlin/Wasm browser tests without298failures/errors/skips, and Android, iOS simulator ARM64, desktop and web compiled.299Tests cover real Room v14→15 migration, ordered 500-credit persistence/reopen,300replacement/reordering, cascading deletion and a SQL counter confirming progress301updates make no cast-row writes. Shared scanner/backup/sync/ViewModel checks and real302OPFS sidecar portrait/clear checks passed. Compact/wide desktop Compose captures303received a scoped `ship` finish review with no material fixes; native-device rendering,304accessibility, enlarged text and frame rate remain unverified. Source extension cast305and related-title groups are tracked separately below.306307## Source extension cast308309The common JavaScript/Mihon detail decoder accepts the same optional `cast` schema310and preserves ordering and the distinction between omission, invalid data and an311explicit empty list. Saved credits feed the shared detail screen and existing312backup/sync paths on every target. Source portraits accept only HTTP(S), with313relative references resolved against the source base URL. File/content/OPFS/data314URLs, credentials and malformed URLs are discarded without discarding the actor.315Offline detail fallback now selects the requested source first and returns no316chapters for an unknown title, avoiding collisions when sources share a relative URL.317318Verification passed 54 desktop checks and 49 Kotlin/Wasm browser tests without319failures/errors/skips, and all four targets compiled. This includes an actual QuickJS320extension-to-repository round trip, shared JS/Mihon service mapping, source-isolated321offline fallback, portrait validation, explicit clear and preservation of notes,322bookmarks and progress. This consumes credits when the extension or configured323Mihon bridge includes them in its detail response; it does not add cast support to324external bridge binaries that omit the field. The bundled Android bridge now exposes325optional `SAnime.cast`, compatible `Credit` objects and Upcoming, and forwards cast326through its detail JSON. Omitted credits from older APKs remain usable; explicit empty327credits remain an explicit clear. Fourteen Android bridge unit checks passed and the328Android app compiled. These include a Java class compiled against a deliberately older329interface and loaded against the current host, plus Jackson/Kotlin serialization.330External desktop/iOS/web bridge binaries that omit cast require an upstream update;331the common client is ready to consume the field. Source-related entries are covered332in `SOURCE_RELATIONS.md`.333334## Remaining stage 5 scope335336- Verify native picker/provider UI.337- Cast, related-entry and season fields in external bridge binaries that omit them338  (outside this repository).339- On-device Android/iOS video playback (shared resolution and desktop/web playback are verified).340341Season records, local-video playback verification and frame-derived artwork are342complete; see `SEASON_RECORDS.md` and `LOCAL_VIDEO_ARTWORK.md`. Folders without episode343files now become Seasons titles; the flattened per-title season selector described above344applies to titles whose folder has its own episode files.345346The pinned upstream metadata definitions inspected for the next implementation are347[AnimeDetails](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/core-metadata/src/main/java/tachiyomi/core/metadata/tachiyomi/AnimeDetails.kt),348[EpisodeDetails](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/core-metadata/src/main/java/tachiyomi/core/metadata/tachiyomi/EpisodeDetails.kt)349and [LocalAnimeSource](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/source-local/src/main/kotlin/tachiyomi/source/local/entries/anime/LocalAnimeSource.kt).350Their numeric source statuses use the351[SAnime constants](https://github.com/Animetailapp/Animetail/blob/d0eab5d6237dd09ebdb21a63fff5b66097c91087/source-api/src/main/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt),352which differ from Yokan's legacy metadata enum ordinals. They must be mapped by353format rather than silently reusing the legacy ordinal parser.354

Search chapters, reference and source filenames.