Code map¶
Use this as the current “where do I change X?” guide. App lifecycle, UI, and most live
orchestration live in Labstream/; reusable requests, models, and policies live in
PMSKit/. PMSKit is mostly pure, with narrow effectful infrastructure such as its
MediaBrowser request executor, loopback media-session proxy, diagnostic ring
buffer, and protected credential-artifact writer.
The directory names below are the stable first stop. Use symbol search and the ownership tables in the subsystem pages for current file-level detail; a duplicated per-file diagram would become stale as implementations move.
App shell and lifecycle¶
Labstream/Shared/App/AppRuntime.swiftis the shared composition root for app-lifetimeAppModel,AuthManager,MusicPlayerController,SessionBootstrap,LibraryCatalogRepository,MetadataRepository, andArtworkPipelineinstances. It also owns the realDownloadManageron download-capable products; tvOS has no download field or construction path.Labstream/Platforms/visionOS/App/Labstream.swiftis the visionOS entry point. It declares the main window, declares Custom Cinema, and owns the live app-lifetimeWatchTogetherCoordinatorshared by the window and Cinema.Labstream/Platforms/Mobile/App/LabstreamMobile.swiftis the universal iPhone/iPad entry point.Labstream/Platforms/macOS/App/LabstreamMac.swiftis the native macOS entry point and declares the one retained main-window group, removes the New Window command, owns the singleton Mac Settings scene, and supplies deterministic window reactivation and menu commands.Labstream/Platforms/tvOS/App/LabstreamTV.swiftis the streaming-only Apple TV entry point; it builds the sharedAppRuntimewithout Downloads.Labstream/Shared/App/RuntimeLifecycleCoordinator.swiftandAppSceneActivity.swift, built byAppRuntimeon download-capable products, own aggregate scene-phase lifecycle: the 500 ms scene-handoff grace, typed download-recovery reasons, and the best-effort diagnostic flush on genuine inactivity.Labstream/Shared/App/ContentView.swiftregisters system routing, runs the one-time restore, and applies PMSKit'sBrowseUIGateto select restoring, restricted offline, login, or authenticated browse state. The restricted offline path exists only on download-capable products; tvOS falls back to login.Labstream/Capabilities/Downloads/App/AppDelegate.swiftbridges iOS/visionOS background URLSession relaunch events.Labstream/Platforms/macOS/App/MacAppDelegate.swiftowns Mac launch, reopen, and window presentation; it is not a Downloads session adapter and does not handle UIKit background URLSession relaunch.Labstream/Shared/App/PlatformClientIdentity.swiftmaps the target to its Plex client/device identity.
Every app target owns Labstream/Shared/ plus exactly its matching Labstream/Platforms/
root. Vision Pro, mobile, and Mac also own Labstream/Capabilities/Downloads/; tvOS does not.
Use inline conditional compilation only where a genuinely shared file needs framework or
presentation variation. Do not create duplicate backend or policy implementations merely to
vary presentation.
Session state, authentication, and secrets¶
Labstream/Shared/App/AppModel.swiftowns live, separate Plex/Jellyfin/Emby server and credential lanes, the active backend, token-free UI session identities, exact opaque browse authorities, immutable authenticated browse contexts, and the sharedPlexClient.Labstream/Shared/Auth/AuthManager.swiftowns sign-in, restore, server selection, backend switching, and sign-out. It covers Plex PIN auth, Jellyfin credentials/Quick Connect, Emby credentials/Connect PIN, selected-lane-first restore, and demand-driven download hydration.Labstream/Shared/Auth/EmbyConnectAuthFlow.swiftprivately owns pending Emby Connect secrets, exact server-selection state, backend exchange, and session commit. It never owns a polling task or authorization generation;AuthManagerfences every follow-up through the global authority.Labstream/Shared/Auth/AuthAttemptAuthority.swiftowns the one global authorization generation used to reject cancellation and stale publication across all backend operations.Labstream/Shared/Auth/AuthorizationPollingCoordinator.swiftowns the single live Plex PIN, Jellyfin Quick Connect, or Emby Connect polling task plus its exact attempt/PIN metadata. Its narrow exact-owner finish/cancel API prevents stale poll cleanup from clearing a replacement.Labstream/Shared/Auth/KeychainStore.swiftstores secrets and the stable client identifier. Do not put tokens in UserDefaults, diagnostics, URLs that do not require them, or Codable profile indexes.Labstream/Shared/Auth/WebAuthSession.swiftis the cross-platform web-auth presentation adapter.PMSKit/Sources/PMSKit/SessionIdentity.swiftandPMSKit/Sources/PMSKit/MediaBackendSwitch.swiftcontain the corresponding pure identity and switch decisions.
Downloads call AppModel.backendSession(for:) so each row uses its own backend lane,
not necessarily the backend currently visible in the UI.
Browse, paging, search, and artwork¶
PMSKit/Sources/PMSKit/Models/PlexBrowseRequest.swiftcontains hubs, search, and metadata browse builders. Video-library section pages, filters, and sorts usePMSKit/Sources/PMSKit/PlexLibraryBrowseRequest.swift.Labstream/Shared/Backend/PlexBrowseAPI.swiftis the source-compatible app facade over both.Labstream/Shared/Backend/PlexBrowseService.swiftpins one immutable Plex session and owns execution. ItsPlexBrowseResponseExecutormoves JSON decoding and normalized-result mapping off the main actor while preserving the existing MainActor transport callback and typed errors.Labstream/Shared/Backend/Jellyfin/JellyfinBrowseService.swiftandLabstream/Shared/Backend/Emby/EmbyBrowseService.swiftare the live MediaBrowser browse facades. They snapshot MainActor session state into the Sendable browse-onlyLabstream/Shared/Backend/MediaBrowserBrowseCore.swift, which performs transport, decode, and DTO mapping off the main actor; playback and downloads stay outside it.Labstream/Shared/Backend/Paging/owns backend-neutral paging sources/models and the Plex/Jellyfin/Emby grid and rail adapters. Sparse library pages join one model-owned task flight per page rather than polling or issuing duplicate fetches. Movie-version grids retain stable first-seen groups and apply only each page's changed dense projection positions instead of re-collapsing all earlier pages.PlaylistPagingModelis deliberately positional: it pages long playlists while retaining duplicates, server order, retry, cancellation, clamped-page, and exact-authority semantics.RailPagingModel,RailPagingSource, andRailViewAllDestinationpower paged Home “View All” destinations.Labstream/Shared/Backend/BoundedAsyncMap.swiftprovides ordered fail-fast and partial-result fan-out. MediaBrowser library search and video/music alphabet probes cap their active requests at four while preserving the pre-existing order and failure contracts.Labstream/Shared/Backend/LibraryCatalogLoader.swiftnormalizes one native Plex section or Jellyfin/Emby view enumeration into ordered descriptors. The app-lifetimeLibraryCatalogRepositoryshares exact-authority values and in-flight work across Libraries, MediaBrowser Home, Search, Music, the Mac sidebar, visibility editing, system entries, and Watch Together; force refresh, failure eviction, and stale-work fencing remain repository concerns, while per-surface query, visibility, ordering, and destination policy stay out.Labstream/Shared/Backend/MetadataRepository.swiftowns exact backend/opaque-authority/item metadata flights, ten-second fresh display reuse, bounded stale-while-revalidate through sixty seconds, watched-state presentation patches, and provenance-based action admission.DetailMetadataLoader.swiftandDetailPlaybackLauncher.swiftconsume that boundary: an exact fresh native Detail result can authorize immediate Play without a second read, while reused, stale, patched, expired, or superseded values require a native read.PMSKit/Sources/PMSKit/Search/SearchResults.swiftowns the pure grouped, deduplicated, library-aware search presentation model;Labstream/Shared/UI/SearchView.swiftrenders its backend-neutral sections and routes standard versus music results.Labstream/Shared/UI/HomeView.swiftuses Plex native hubs orLabstream/Shared/UI/MediaBrowserHomeProvider.swiftfor shared Jellyfin/Emby Home rails.MediaBrowserHomeRailPlan.swiftassigns duplicate-safe canonical rail keys and reduces authority/attempt-fenced results. The provider publishes successful rails progressively under a single four-request ceiling and runs one failed-key-only retry while preserving successful and empty-success rails; only a complete, non-degraded result pins Home's loaded identity. Plex remains on native/hubs.PMSKit/Sources/PMSKit/UI/HomeRailArtworkPolicy.swiftclassifies MediaBrowser synthetic Primary artwork as portrait and Thumb/Backdrop as landscape so Home request dimensions match the selected source instead of reshaping it. The policy applies to Jellyfin and Emby Home, not Emby alone.Labstream/Shared/UI/LibraryGridView.swiftowns library roots and the shared sparse grid;LibraryAlphabetRail.swiftowns the A–Z interaction.Labstream/Shared/UI/ContainerBrowserView.swifthandles show/season child navigation and normalizes duplicate visible episode rows; on iPhone/iPad it hands shows and seasons toMobileShowBrowser.swift(show header, resume action, show | season split) and the shared detail pieces live inMobileDetailComponents.swift.Labstream/Shared/UI/SearchView.swiftowns the shared search surface and music-result queue actions.Labstream/Shared/UI/MediaArtwork.swiftresolves backend-authenticated, exact-authority artwork descriptors whose task/debug/reflection identity contains no request credentials. The app-lifetime actor-ownedArtworkPipelineexecutes remote and local requests with exact in-flight joining, independent waiter cancellation, canonical-origin priority admission, ephemeral nonpersistent remote transport, ImageIO downsampling/eager decode, and bounded compressed/decoded/negative caches.PosterImage, music/video system Now Playing,AVPlayerItemexternal and visionOS scoped metadata, offline row thumbnails, and offline player artwork consume it. Their success/failure callbacks publish only while the exact descriptor, pipeline instance, and owning view/playback generation remain current.Labstream/Shared/UI/OfflineArtworkSource.swiftturns persisted row ownership plusposterGenerationinto an opaque local authority, including same-path replacements.SettingsViewclears the one pipeline, memory pressure trims its decoded cache, andArtworkShimmerClock.swiftowns one app-lifetime, reference-counted ticker for visible placeholders in the root UI and visionOS Custom Cinema ImmersiveSpace, with a static Reduce Motion path and a Debug/PerformanceAuditperf.shimmer_sessionsummary line per ticker run. Shared image values use the immutable CGImage-backedLabstream/Shared/Platform/DecodedImage.swift; native images are created only at framework bridges.
RequestBackedChapterImage remains outside the pipeline because AVKit hosts the chapter tab in
an independent environment without an injected pixel contract. BIF and sprite-sheet providers,
Emby generated per-position frames, Emby online/offline chapter fallback, and the player nearest-
frame cache remain provider-scoped time-indexed exceptions rather than ArtworkPipeline
consumers.
Authenticated requests use the nonpersistent side-asset transport, and their leaf caches are
memory-only and bounded by byte cost plus entry count. Sprite sheets and final scrub previews cross
the eager off-main DecodedImage boundary before cache publication; BIF indexes retain/map one
backing payload and normal seek lookup copies only a selected frame (frames remains an explicit,
source-compatible materializing accessor). Largest-real-BIF and tile-sheet peak-RSS measurement
remains useful follow-up evidence rather than a completed acceptance claim. Using DecodedImage
there is not pipeline adoption. DownloadSideAssetService validates downloaded poster, chapter,
BIF, and subtitle payloads before promotion.
Request/DTO implementations live under PMSKit/Sources/PMSKit/Auth/,
PMSKit/Sources/PMSKit/Jellyfin/, PMSKit/Sources/PMSKit/Emby/,
PMSKit/Sources/PMSKit/MediaBrowser/, PMSKit/Sources/PMSKit/Models/, and
PMSKit/Sources/PMSKit/Optimize/ (Plex optimizer, Activities, and BackgroundQueue requests),
plus the root Plex request files such as PlexRequest.swift and PlexPhotoTranscode.swift.
PMSKit/Sources/PMSKit/Security/ owns credential-artifact storage and the credential
validation/migration policies. In the app, Labstream/Shared/Networking/PlexClient.swift is the
shared Plex transport and Labstream/Shared/Platform/PlatformFeaturePolicy.swift answers
per-product capability questions such as Downloads support.
Root navigation and shared UI¶
Labstream/Shared/UI/RootView.swiftis the common authenticated composition wrapper. It installs shared repositories/services and connects browse-session, music, system-entry, and Cinema-return events toRootNavigationCoordinator.swift.Labstream/Shared/UI/RootNavigationCoordinator.swiftowns destination selection, online/music paths, Search return/focus transitions, exact-session system-entry routing, music Now Playing presentation state, and the offline Cinema return focus key.BrowseNavigationStack.swiftis the repeated session-keyed stack/push boundary.Labstream/Platforms/visionOS/UI/VisionRootShell.swift,Labstream/Platforms/Mobile/UI/MobileRootShell.swift,Labstream/Platforms/macOS/UI/MacRootShell.swift, andLabstream/Platforms/tvOS/UI/TVRootShell.swiftindependently own the native vision tab/ornament, adaptive iPhone/iPad, Mac split-view/player, and focus-driven TV presentations respectively.Labstream/Shared/UI/LoginView.swift,BackendSignInComponents.swift,LoginChromeComponents.swift, andPairingCodeView.swiftown shared backend login UI.Labstream/Shared/UI/DetailView.swiftowns item-detail presentation state. Extracted backend effect seams are inDetailMetadataLoader.swift,DetailWatchedUpdater.swift, andDetailPlaybackLauncher.swift.Labstream/Capabilities/Downloads/UI/DownloadOptionsSheet.swiftowns download intent/version selection.Labstream/Shared/UI/SettingsView.swiftowns backend/server status, preferences, storage, library visibility, diagnostics export, and About information.Labstream/Shared/UI/DesignSystem.swiftcontains shared visual constants and modifiers.
Online navigation paths are scoped to AppModel.activeBrowseSessionKey and reset when
that session changes. Offline navigation is intentionally not reset because saved items
are backend-scoped and cross-backend.
Video playback¶
Labstream/Shared/Player/PlaybackController.swiftowns one activeAVPlayersession and the shared item-observation, transport, diagnostics, seek, chapter, and chrome-facing state for Plex streams, negotiated Jellyfin/Emby streams, and local files. Source negotiation, reopen/progress callbacks, track behavior, retry mechanics, and server cleanup remain lane-specific.PlaybackSessionSource.swiftis the typed construction lane;PlaybackRestartIntent.swiftowns reason-specific in-place restart plans;HLSStartupHardening.swiftownsHLSSessionPrewarmer.Labstream/Shared/Player/CustomPlayerView.swiftis the common windowed player presenter and hosts anAVPlayerLayerplusCustomPlayerChrome;Labstream/Platforms/visionOS/Player/CustomCinemaMode.swiftowns the separate immersive presenter for the same live controller.Labstream/Shared/Player/CustomPlayerChrome.swiftowns the shared transport/menu/scrubber UI and contains the largest concentration of platform conditional compilation.- Platform-exclusive chrome leaves extend
CustomPlayerChromeinLabstream/Platforms/<platform>/Player/*PlayerChrome.swift(VisionPlayerChrome,MobilePlayerChrome,MacPlayerChrome,TVPlayerChrome).TVPlayerChrome.swiftowns tvOS focus and Siri Remote input; on Mac,MacPlayerInputRouter.swiftresolves Escape priority (menu, then full screen, then the player). Labstream/Shared/UI/DetailPlaybackLauncher.swiftnegotiates Jellyfin/Emby playback and supplies remote reopen, progress, and encoding-cleanup callbacks to the controller.Labstream/Shared/Player/TimelineReporter.swiftserializes/coalesces Plex timeline and Jellyfin/Emby playback-progress traffic.Labstream/Shared/Player/PlaybackDiagnostics.swift,PlaybackController+Diagnostics.swift, andPlaybackHDRProbe.swiftown runtime diagnostics.PlaybackStatsSummary.swiftturns them into the Stats panel's signal chain, tiles, and expanded sections, andPlaybackStatsView.swiftrenders that panel.PMSKit/Sources/PMSKit/Models/PlaybackExplanation.swiftowns the compact Stats Why lane, at-most-two reasons, and provenance.DolbyVisionGuard.swiftandCaptionAppearance.swiftown the P5 safety gate and caption-profile preview.Labstream/Shared/Player/TrickPlayThumbnailProviders.swiftowns remote/local Plex BIF, online/offline Jellyfin tile-sheet, and online/offline Emby BIF/generated-frame/chapter providers;Labstream/Shared/Support/CostBoundedLRU.swiftowns the cost-and-entry cache bound shared by trick-play and artwork memory caches.Labstream/Shared/Player/AudioSessionCoordinator.swiftowns non-Mac audio-session policy.Labstream/Platforms/Mobile/Player/MobilePlayerSystemCoordinator.swiftandMobilePlayerOrientationCoordinator.swiftadd iOS/iPadOS PiP, AirPlay, system media, and orientation behavior.Labstream/Platforms/macOS/Player/MacPlayerPresentation.swiftadds native Mac player presentation behavior.Labstream/Shared/Player/VideoNowPlayingCore.swiftis the iOS/iPadOS and macOS video adapter for the shared process-wideSystemMediaSessionCoordinatorlease. The mobile coordinator wraps it alongside PiP/AirPlay, while the Mac player owns it directly.Labstream/Platforms/visionOS/Player/VideoNowPlayingCoordinator.swiftis the separate visionOS video system-media owner. It creates a scopedMPNowPlayingSession, publishes metadata on eachAVPlayerItem, and routes session commands back toPlaybackController.Labstream/Shared/Player/PlaybackLifecycleCallbackSink.swiftandVideoPlaybackLifecyclePolicy.swiftreject queued observer/task callbacks from a superseded item generation; removing an observer alone is not treated as cancellation.Labstream/Shared/Player/SystemMediaSessionCoordinator.swiftserializes process-wide Now Playing and remote-command ownership between music and video with identity-guarded leases; visionOS video does not use this lease path.Labstream/Shared/Player/NowPlayingArtwork.swiftprovides the shared MediaPlayer artwork wrapper used by both system-media approaches.Labstream/Shared/Player/PlaybackTransportPresentationPolicy.swiftowns transport/resume-button presentation decisions for Offline playback based on local preparation status, extracted out ofPlaybackController/PlayerChromeComponents.
Pure playback policies and request builders live primarily in
PMSKit/Sources/PMSKit/Playback/, PMSKit/Sources/PMSKit/Transcode/,
PMSKit/Sources/PMSKit/MediaBrowser/, and
PMSKit/Sources/PMSKit/MediaSession/. The MediaSession directory is the exception to
the usual pure-policy boundary: it owns the live, injectable loopback HLS proxy and
upstream connection rotation used by PlaybackController.
Cinema¶
Labstream/Platforms/visionOS/App/Labstream.swiftowns the app-lifetimeCustomCinemaSessionStorethat retains the live controller across window dismiss / Cinema present.Labstream/Platforms/visionOS/Player/CustomCinemaMode.swiftis the user-visible immersive presenter for that retained controller and is absent from non-vision products at compile time.Labstream/Platforms/visionOS/Player/CinemaTransitionCoordinator.swiftandCinemaTransitionPolicy.swiftown generation-fenced open/appear/detach/dismiss/disappear transitions. Do not re-home the controller on the ImmersiveSpace view.Labstream/Platforms/visionOS/Player/CinemaAppRouting.swiftis the small app-action adapter between PMSKit's pure Cinema exit decision and the visionOS system-entry router. Its deterministic suite is now visionOS-only; the assertions are preserved but honestly remain unexecuted until the planned visionOS-hosted test target exists.
Downloads and offline¶
Labstream/Capabilities/Downloads/Core/DownloadManager.swiftowns queue policy, observable records and snapshots, retry/resume, storage limits, server-prep polling, validation, and encoder cleanup. At startup it installs session callbacks and registers the dormant session before deferring only healthy-current initial transport submission by one bounded MainActor turn. The deferred task retains the manager; a retry cancels that edge and owns the sole immediate submission, while unsupported, unreadable, and malformed recovery retain their existing reset/fail-closed behavior. This is scheduling, not transport or durability deletion.DownloadKeepaliveCoordinator.swiftprivately owns exact-attempt Jellyfin/Emby keepalive tasks and credential-generation quarantine; the manager only forwards start/reconcile and exact-cancellation requests.DownloadManager+Plex.swiftandDownloadManager+PlexOptimize.swiftown Plex source and optimizer behavior.DownloadManager+Jellyfin.swiftowns Jellyfin original/transcode/remux behavior.DownloadManager+Emby.swiftandDownloadManager+EmbyConvert.swiftown Emby source, remux, and Convert behavior.DownloadManager+SideCache.swiftcaches posters, subtitles, chapters, Plex BIF, Emby BIF, Emby text subtitles, and Jellyfin trick-play assets throughDownloadSideAssetService.swift, which owns validated off-main repair inventory/preparation and exact resource admission.DownloadPlanningRequestExecutor.swiftis the injected nonpersistent request boundary forDownloadItemPlanner; same-origin 307/308 redirects preserve method/body/headers and every other redirect is rejected.DownloadOptionsModel.swiftowns typed per-item option resolution for the download sheet.DownloadManager+SeasonPlanner.swiftandSeasonDownloadPlannerSheet.swiftown immutable season drafts and the one atomic Store commit of new rows plus retry markers.DownloadTransferStartPlan.swiftis the common backend-to-transfer handoff contract.Labstream/Capabilities/Downloads/Core/BackgroundDownloadSession.swiftowns URLSession delegates, reattachment, progress, validation, background-wake release effects, and durable static byte-range recovery.BackgroundDownloadWakeCoordinator.swiftowns the locked background-completion gate, atomic deferred-revalidation drain, and range-rebuild grace generations.Labstream/Capabilities/Downloads/Core/BackgroundDownloadCompletionRegistry.swiftjoins system relaunch callbacks to the live/recreated background session.Labstream/Capabilities/Downloads/Core/DownloadStore.swiftowns the locked relative-path index and files under Application Support.DownloadArtifactLifecycleCoordinator.swiftregisters attempt-scoped filesystem work before execution and releases it only after the matching persistence outcome;DownloadArtifactFileCommitter.swift,DownloadPromotionFilesystem.swift, andDownloadStaticCheckpointFilesystem.swiftare the narrow file-effect seams.RevisionedPersistenceWriter.swiftandDownloadIndexFileCommitter.swiftserialize revisioned index writes.BackgroundCompletionPersistenceBarrier.swiftflushes the exact boundary before releasing background-session completion handlers.DownloadWorkRegistry.swifttracks attempt-scoped side-cache and encoder work.DownloadCleanupIntentJournal.swiftpersists credential-free Plex/Jellyfin/Emby cleanup independently so deleting a row cannot discard required server cleanup.EmbyConvertCleanupJournal.swiftowns the compatibility Emby Convert tombstone file and serializes that queue independently of theDownloadStoreindex lock.Labstream/Capabilities/Downloads/Core/OfflineLibraryView.swiftowns the cross-backend offline UI and local playback launch. On iPhone/iPad it is one list in every width with no detail page. Its snapshot is lightweight and actions re-resolve exact attempt identity.Labstream/Shared/UI/OfflineLaunchView.swiftowns the restricted cold-launch surface when a saved-session restore is temporarily unavailable and an existing local file belongs to a complete or unverified row. PMSKit'sOfflineLaunchAvailabilitydecides admission from the typedSessionRestoreOutcome(PMSKit/Sources/PMSKit/Auth/SessionRestoreOutcome.swift); this path permits local library/playback, reconnect/sign-in, and Settings rather than authenticated browsing, and is absent from tvOS. Invalid or missing credentials continue to Login.PMSKit/Sources/PMSKit/Downloads/DownloadStorageSnapshot.swiftowns provenance-aware known/unknown/not-applicable storage presentation.PMSKit/Sources/PMSKit/Downloads/contains pure route, status, retry, display, storage, identity, and range-transfer policies and offline models.
Download subsystem file guide¶
App files below are under Labstream/Capabilities/Downloads/; pure policy files are under
PMSKit/Sources/PMSKit/Downloads/. The file boundaries complement the behavioural contracts in
Downloads and offline and Persistence.
| File | Role |
|---|---|
Core/DownloadAdmissionCoordinator.swift |
Generation-supervised, event-driven start scheduling and deferral wakes. |
Core/DownloadManager+Admission.swift |
Connects taps, season rows, retries, recovery, lane occupancy and Pause All exemptions to admission. |
DownloadAdmissionPolicy.swift |
Pure lane caps, occupancy and request ordering. |
Core/DownloadCleanupIntentRunner.swift |
Bounded cleanup execution, claims, eligibility and per-intent retry deadlines. |
Core/DownloadManager+CleanupRunner.swift |
Cleanup producers, recovery barriers and backend-specific journal executors. |
CleanupIntentEligibilityPolicy.swift |
Exact resource/owner claims and deletion, terminal-release and abandonment eligibility. |
Core/DownloadCleanupOrdering.swift |
Journal-first ordering for destructive Delete: required server cleanup enters the journal first, else the row stays durably deletion-pending. |
Core/DurableJournalCommit.swift |
Full-sync atomic commit shared by cleanup authority files. |
DownloadLifecycle.swift |
Persisted lifecycle, pause/failure reasons and attempt history, including truncation and condemnation. |
DownloadLifecycleReducer.swift |
Pure authority for lifecycle/history transitions and their effects. |
Core/DownloadStoreAsyncContract.swift |
Typed submissions and bounded asynchronous resolution; acceptance is separate from durability. |
Core/DownloadPathLease.swift |
Process-local exclusion for all physical source/destination paths until I/O ends. |
Core/DownloadStoreFilesystem.swift |
Narrow injected stat/read/copy/rename/remove scheduling and fault seam. |
Core/DownloadUpgradeNotice.swift |
Durable, full-attempt-key removal/cleanup notice for the v4-to-v5 upgrade. |
Core/DownloadWakeBudgetContract.swift |
Monotonic receipt deadlines, identified operations and typed wake terminal outcomes. |
Core/StaticRangeTransferConfiguration.swift |
Static-range train sizing: 512 MiB closed segments and per-row depth. |
StaticRangeTaskHealthPolicy.swift |
Process-local #409 foreground range-reissue experiment: settle, active window, rate and discard bounds. |
DownloadAggregateRateEstimator.swift |
Header aggregate speed from common-interval delegate observations (#379/#406). DownloadLiveRangeProgressPolicy.swift keeps samples across Range segment boundaries (#416). |
Core/OrderedAsyncWorkCoordinator.swift |
Per-key serial async work with exactly-once, in-order completions. |
Core/CompletedSideAssetInventory.swift and Core/DownloadManager+ResumePresence.swift |
Observation-only side-asset and resume-presence evidence; neither grants publication authority. |
BackgroundReattachTaskGatePolicy.swift |
Rejects paused, halted or stale task adoption without reviving the row. |
Core/DownloadVolumeFreeSpace.swift |
Proactive free-space measurement for the downloads volume, including purgeable space. |
Core/DownloadFileStat.swift |
Metadata-only file observations for diagnostics and recovery, separate from body readers. |
DownloadStorageAdmissionPolicy.swift |
Shared physical free-space and self-excluding storage-cap accounting. |
DownloadNetworkAccessPolicy.swift |
One cellular/constrained/expensive network preference for new requests. |
DownloadExistingVersionDiscovery.swift |
Distinguishes interactive existing-version discovery from season planning. |
PlexOptimizePrepPolicy.swift |
Proven absence, create visibility grace and existing-render adoption decisions. |
Core/MediaBrowserDownloadNegotiator.swift |
Shared PlaybackInfo transport/decode/verdict boundary with captured-session currency checks. |
MediaBrowserDownloadContainer.swift |
First trimmed, lowercased container token shared by eligibility, requests and destinations. |
DownloadKeepaliveTransferGate.swift |
Ensures keepalive follows a tracked exact-attempt transfer rather than row status alone. |
Core/DownloadManager+OfflinePlayback.swift |
Manager-owned local launch factory implementation and exact event-sink binding. |
Core/OfflinePlaybackLaunchFactory.swift |
Immutable admitted local launch, presentation generation and typed rejection contract. |
Core/OfflinePlaybackEventSink.swift |
Exact-attempt/session observed-playing and bounded coalesced position persistence. |
Core/OfflinePlayableAvailability.swift |
Generation-tagged off-main local-file scan, independent of mutation admission. |
LaunchDownloadRecoveryGate.swift |
One serialized recovery replay when an offline launch reconnects. |
DownloadRowPresentation.swift |
Shared lifecycle, progress, caption (including the iPhone/iPad compactStatusText), color and accessibility presentation. |
UI/DownloadRowContent.swift |
Shared row cell: the compact one-status-line layout on iPhone/iPad, the full layout on visionOS and Mac. |
Debug/Debug*DownloadProbe.swift |
DEBUG-only Plex, Jellyfin and Emby download probes and their shared support. |
BackgroundDownloadWakeCoordinator.swift consumes the wake contract, while the completion
registry timestamps handlers before MainActor registration. DownloadKeepaliveCoordinator.swift
uses the common transfer gate and retains backend-specific request payloads. These owners remain
separate from the pure reducer and from the physical store workers.
Do not assume simulator and device transfers use identical URLSession configuration: hardware uses the relaunch-capable background session, while simulator runs normally use the documented foreground substitute.
Music¶
Labstream/Shared/Music/MusicProvider.swiftdefines the backend-neutral browse boundary.PlexMusicProvider.swiftsupplies Plex-native and richer artist data.MediaBrowserMusicProvider.swiftis shared by Jellyfin and Emby.MusicStreamResolver.swiftis the single backend-aware stream resolver.MusicPlayerController.swiftowns the app-lifetime AVPlayer queue, shuffle/repeat, audio-session behavior, remote commands, and Now Playing metadata.MusicPlaybackLifecycle.swiftgeneration-guards per-track observers and queued work; music acquires the sharedSystemMediaSessionCoordinatorlease rather than mutating global MediaPlayer state independently of video.MusicLibraryView.swift,MediaBrowserMusicView.swift,MusicPagedGrid.swift, and the album/artist/playlist detail views own presentation.MiniPlayerBar.swiftandNowPlayingView.swiftare the compact/full playback surfaces.RootNavigationCoordinator.nowPlayingPresentationowns shared presentation state;VisionRootShellowns the app-owned visionOS backdrop andVisionNowPlayingPanelso a surround tap and the explicit leading-edge close control use the same dismissal path without activating obscured content.RootViewonly forwards artist/album navigation requests.PMSKit/Sources/PMSKit/Music/contains Plex music request builders and pure queue mutation behavior.
Backend progress/scrobble support for music is described in Music architecture.
SharePlay / Watch Together (visionOS)¶
Labstream/Platforms/visionOS/SharePlay/WatchTogetherActivity.swiftdefines the GroupActivity wrapper and maps PMSKit's sanitized payload display fields intoGroupActivityMetadata.Labstream/Platforms/visionOS/SharePlay/WatchTogetherCoordinator.swiftowns activation, GroupSession and messenger state, participant readiness, local launch, the exact-item attachment consent gate, and theAVPlayerPlaybackCoordinatorsession binding.Labstream/Platforms/visionOS/SharePlay/WatchTogetherMediaLookup.swiftsearches and attempts to hydrate candidates only through the participant's currently authenticated online backend.Labstream/Platforms/visionOS/SharePlay/WatchTogetherJoinView.swiftpresents incoming local-resolution and participant-readiness state and forwards search, selection, start, and decline actions; the coordinator and lookup own the resolution work.Labstream/Shared/Player/CustomPlayerView.swiftandLabstream/Platforms/visionOS/Player/CustomCinemaMode.swiftmaintain attachment across player-item replacement and the window-to-Cinema handoff.PMSKit/Sources/PMSKit/SharePlay/SharePlayMediaIdentity.swiftowns backend-neutral payload privacy, matching, readiness, leave, and late-join re-broadcast decisions;PMSKit/Sources/PMSKit/SharePlay/SharePlayPlaybackAttachmentRevision.swiftowns the pure session/item revision key.
System integration¶
Labstream/Shared/SystemIntegration/SystemEntryRouter.swiftis the process-lifetime bridge from non-view entry points—including a participant-locally resolved SharePlay launch—into RootView navigation. It weakly references the app-owned state and can wait for or initiate session restoration without preempting an in-progress user authorization attempt.Labstream/Shared/SystemIntegration/LabstreamIntents.swiftdefines Play, Open, and Continue Watching App Intents for all three backends.Labstream/Shared/SystemIntegration/MediaItemEntity.swiftdefines backend/server-scoped AppEntity search and suggestions. Display values are snapshots; metadata is refetched before navigation.Labstream/Shared/SystemIntegration/SpotlightIndexer.swiftperforms token-free, index-as-you-browse video indexing and shared-domain deletion.PMSKit/Sources/PMSKit/SystemEntryRouting.swiftcontains pure identifier and routing helpers.
The current system surface excludes music and does not crawl an entire library in the background.
Diagnostics and privacy¶
Labstream/Shared/Diagnostics/AppDiagnostics.swiftis the opt-in app-side facade.DiagnosticFileLogSink.swiftowns the rotating local JSONL sink.DiagnosticReportArtifact.swiftowns export/share wrappers.Labstream/Platforms/tvOS/Diagnostics/owns Apple TV's Send log to iPhone: the listener that serves the report and event log on the local network while its screen is open. The request routing and download page arePMSKit/.../Diagnostics/DiagnosticLogShareHTTP.swift.BrowseDiagnostics.swiftcreates privacy-safe browse facts.MetricKitDiagnostics.swiftstores a bounded set of redacted crash/hang summaries for user-generated feedback; it does not upload them.PerformanceInstrumentation.swiftis real signpost instrumentation in Debug and the nonshipping PerformanceAudit configuration (PERFORMANCE_AUDIT), and an API-compatible no-op in Release. Its terminal gate emits at most one end/signpost record per span even when cancellation and completion race. Launch evidence includes app-wide runtime composition (downloads_capable=0|1) and selected-backend session restore (restored=0|1), without identities, URLs, or credentials;scripts/perf_evidence_schema.pyis the closed allowlist for every emitted terminal field and phase/backend pairing.PMSKit/Sources/PMSKit/Diagnostics/owns typed fields, redaction, the bounded event store, report rendering, and MetricKit summary models.- DEBUG-only probe and fixture harnesses live in
Labstream/Shared/Debug/(playback, browse, and HDR probes, frame capture, UI-test launch configuration and fixtures),Labstream/Capabilities/Downloads/Debug/(per-backend download probes), andLabstream/Platforms/tvOS/Debug/(TV input evidence and player fixture), andLabstream/Platforms/Mobile/Debug/(iPhone/iPad player fixture and chrome geometry probe). They back the probe, frame-capture, and platform-runner workflows and are not shipped.
Use typed DiagnosticFieldValues. Do not add raw tokens, URLs, hosts, usernames, local
paths, filenames, client identifiers, or media titles to diagnostics.
Tests, builds, and scripts¶
PMSKit/Tests/PMSKitTests/covers pure policies, request builders, decoders, state machines, and redaction. Run the hermetic suite withswift test --package-path PMSKit --no-parallel --skip 'Live.*ProbeTests'.LabstreamTests/holds app-hosted unit tests shared by theLabstreamTests,LabstreamMacTests, andLabstreamTVTeststargets (each with its own.xctestplan);LabstreamMobileUITests/andLabstreamTVUITests/hold the semantic XCUITest runners. See Testing strategy.Labstream.xcodeproj/project.pbxprojis the source of truth for the four native app target versions, platforms, and deployment settings.scripts/worktree-sim.shprovisions the visionOS worktree simulator or explicit iPhone/iPad and Apple TV simulators.scripts/deploy-mobile-to-device.shdeploys the signed mobile target to iPhone/iPad;scripts/deploy-to-device.shdeploys the signed visionOS target.scripts/deploy-macos-to-host.shbuilds/installs/cleans up the native Mac host app (no simulator);scripts/deploy-ad-hoc-to-device.shbuilds, exports, and installs an Ad Hoc distribution-signed visionOS build on a registered Apple Vision Pro.scripts/xcodebuild-versioned.shis the canonical build wrapper;scripts/native-test-matrix.py affectedselects the targets a change must verify;scripts/agent-*-run.shandagent-playback-run.pyare the platform runners; andscripts/testflight-release.pydrives archive, validate, upload, and build selection.scripts/also contains docs, hygiene, version stamping, and optional live-probe tools..woodpecker/contains portable CI definitions.