Skip to content

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.swift is the shared composition root for app-lifetime AppModel, AuthManager, MusicPlayerController, SessionBootstrap, LibraryCatalogRepository, MetadataRepository, and ArtworkPipeline instances. It also owns the real DownloadManager on download-capable products; tvOS has no download field or construction path.
  • Labstream/Platforms/visionOS/App/Labstream.swift is the visionOS entry point. It declares the main window, declares Custom Cinema, and owns the live app-lifetime WatchTogetherCoordinator shared by the window and Cinema.
  • Labstream/Platforms/Mobile/App/LabstreamMobile.swift is the universal iPhone/iPad entry point.
  • Labstream/Platforms/macOS/App/LabstreamMac.swift is 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.swift is the streaming-only Apple TV entry point; it builds the shared AppRuntime without Downloads.
  • Labstream/Shared/App/RuntimeLifecycleCoordinator.swift and AppSceneActivity.swift, built by AppRuntime on 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.swift registers system routing, runs the one-time restore, and applies PMSKit's BrowseUIGate to 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.swift bridges iOS/visionOS background URLSession relaunch events. Labstream/Platforms/macOS/App/MacAppDelegate.swift owns 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.swift maps 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.swift owns 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 shared PlexClient.
  • Labstream/Shared/Auth/AuthManager.swift owns 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.swift privately owns pending Emby Connect secrets, exact server-selection state, backend exchange, and session commit. It never owns a polling task or authorization generation; AuthManager fences every follow-up through the global authority.
  • Labstream/Shared/Auth/AuthAttemptAuthority.swift owns the one global authorization generation used to reject cancellation and stale publication across all backend operations.
  • Labstream/Shared/Auth/AuthorizationPollingCoordinator.swift owns 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.swift stores 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.swift is the cross-platform web-auth presentation adapter.
  • PMSKit/Sources/PMSKit/SessionIdentity.swift and PMSKit/Sources/PMSKit/MediaBackendSwitch.swift contain 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.swift contains hubs, search, and metadata browse builders. Video-library section pages, filters, and sorts use PMSKit/Sources/PMSKit/PlexLibraryBrowseRequest.swift. Labstream/Shared/Backend/PlexBrowseAPI.swift is the source-compatible app facade over both. Labstream/Shared/Backend/PlexBrowseService.swift pins one immutable Plex session and owns execution. Its PlexBrowseResponseExecutor moves 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.swift and Labstream/Shared/Backend/Emby/EmbyBrowseService.swift are the live MediaBrowser browse facades. They snapshot MainActor session state into the Sendable browse-only Labstream/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. PlaylistPagingModel is deliberately positional: it pages long playlists while retaining duplicates, server order, retry, cancellation, clamped-page, and exact-authority semantics. RailPagingModel, RailPagingSource, and RailViewAllDestination power paged Home “View All” destinations.
  • Labstream/Shared/Backend/BoundedAsyncMap.swift provides 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.swift normalizes one native Plex section or Jellyfin/Emby view enumeration into ordered descriptors. The app-lifetime LibraryCatalogRepository shares 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.swift owns 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.swift and DetailPlaybackLauncher.swift consume 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.swift owns the pure grouped, deduplicated, library-aware search presentation model; Labstream/Shared/UI/SearchView.swift renders its backend-neutral sections and routes standard versus music results.
  • Labstream/Shared/UI/HomeView.swift uses Plex native hubs or Labstream/Shared/UI/MediaBrowserHomeProvider.swift for shared Jellyfin/Emby Home rails. MediaBrowserHomeRailPlan.swift assigns 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.swift classifies 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.swift owns library roots and the shared sparse grid; LibraryAlphabetRail.swift owns the A–Z interaction.
  • Labstream/Shared/UI/ContainerBrowserView.swift handles show/season child navigation and normalizes duplicate visible episode rows; on iPhone/iPad it hands shows and seasons to MobileShowBrowser.swift (show header, resume action, show | season split) and the shared detail pieces live in MobileDetailComponents.swift.
  • Labstream/Shared/UI/SearchView.swift owns the shared search surface and music-result queue actions.
  • Labstream/Shared/UI/MediaArtwork.swift resolves backend-authenticated, exact-authority artwork descriptors whose task/debug/reflection identity contains no request credentials. The app-lifetime actor-owned ArtworkPipeline executes 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, AVPlayerItem external 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.swift turns persisted row ownership plus posterGeneration into an opaque local authority, including same-path replacements. SettingsView clears the one pipeline, memory pressure trims its decoded cache, and ArtworkShimmerClock.swift owns 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/PerformanceAudit perf.shimmer_session summary line per ticker run. Shared image values use the immutable CGImage-backed Labstream/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.swift is the common authenticated composition wrapper. It installs shared repositories/services and connects browse-session, music, system-entry, and Cinema-return events to RootNavigationCoordinator.swift.
  • Labstream/Shared/UI/RootNavigationCoordinator.swift owns 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.swift is 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, and Labstream/Platforms/tvOS/UI/TVRootShell.swift independently 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, and PairingCodeView.swift own shared backend login UI.
  • Labstream/Shared/UI/DetailView.swift owns item-detail presentation state. Extracted backend effect seams are in DetailMetadataLoader.swift, DetailWatchedUpdater.swift, and DetailPlaybackLauncher.swift.
  • Labstream/Capabilities/Downloads/UI/DownloadOptionsSheet.swift owns download intent/version selection.
  • Labstream/Shared/UI/SettingsView.swift owns backend/server status, preferences, storage, library visibility, diagnostics export, and About information.
  • Labstream/Shared/UI/DesignSystem.swift contains 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.swift owns one active AVPlayer session 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.swift is the typed construction lane; PlaybackRestartIntent.swift owns reason-specific in-place restart plans; HLSStartupHardening.swift owns HLSSessionPrewarmer.
  • Labstream/Shared/Player/CustomPlayerView.swift is the common windowed player presenter and hosts an AVPlayerLayer plus CustomPlayerChrome; Labstream/Platforms/visionOS/Player/CustomCinemaMode.swift owns the separate immersive presenter for the same live controller.
  • Labstream/Shared/Player/CustomPlayerChrome.swift owns the shared transport/menu/scrubber UI and contains the largest concentration of platform conditional compilation.
  • Platform-exclusive chrome leaves extend CustomPlayerChrome in Labstream/Platforms/<platform>/Player/*PlayerChrome.swift (VisionPlayerChrome, MobilePlayerChrome, MacPlayerChrome, TVPlayerChrome). TVPlayerChrome.swift owns tvOS focus and Siri Remote input; on Mac, MacPlayerInputRouter.swift resolves Escape priority (menu, then full screen, then the player).
  • Labstream/Shared/UI/DetailPlaybackLauncher.swift negotiates Jellyfin/Emby playback and supplies remote reopen, progress, and encoding-cleanup callbacks to the controller.
  • Labstream/Shared/Player/TimelineReporter.swift serializes/coalesces Plex timeline and Jellyfin/Emby playback-progress traffic.
  • Labstream/Shared/Player/PlaybackDiagnostics.swift, PlaybackController+Diagnostics.swift, and PlaybackHDRProbe.swift own runtime diagnostics. PlaybackStatsSummary.swift turns them into the Stats panel's signal chain, tiles, and expanded sections, and PlaybackStatsView.swift renders that panel. PMSKit/Sources/PMSKit/Models/PlaybackExplanation.swift owns the compact Stats Why lane, at-most-two reasons, and provenance. DolbyVisionGuard.swift and CaptionAppearance.swift own the P5 safety gate and caption-profile preview.
  • Labstream/Shared/Player/TrickPlayThumbnailProviders.swift owns remote/local Plex BIF, online/offline Jellyfin tile-sheet, and online/offline Emby BIF/generated-frame/chapter providers; Labstream/Shared/Support/CostBoundedLRU.swift owns the cost-and-entry cache bound shared by trick-play and artwork memory caches.
  • Labstream/Shared/Player/AudioSessionCoordinator.swift owns non-Mac audio-session policy.
  • Labstream/Platforms/Mobile/Player/MobilePlayerSystemCoordinator.swift and MobilePlayerOrientationCoordinator.swift add iOS/iPadOS PiP, AirPlay, system media, and orientation behavior.
  • Labstream/Platforms/macOS/Player/MacPlayerPresentation.swift adds native Mac player presentation behavior.
  • Labstream/Shared/Player/VideoNowPlayingCore.swift is the iOS/iPadOS and macOS video adapter for the shared process-wide SystemMediaSessionCoordinator lease. The mobile coordinator wraps it alongside PiP/AirPlay, while the Mac player owns it directly.
  • Labstream/Platforms/visionOS/Player/VideoNowPlayingCoordinator.swift is the separate visionOS video system-media owner. It creates a scoped MPNowPlayingSession, publishes metadata on each AVPlayerItem, and routes session commands back to PlaybackController.
  • Labstream/Shared/Player/PlaybackLifecycleCallbackSink.swift and VideoPlaybackLifecyclePolicy.swift reject queued observer/task callbacks from a superseded item generation; removing an observer alone is not treated as cancellation.
  • Labstream/Shared/Player/SystemMediaSessionCoordinator.swift serializes 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.swift provides the shared MediaPlayer artwork wrapper used by both system-media approaches.
  • Labstream/Shared/Player/PlaybackTransportPresentationPolicy.swift owns transport/resume-button presentation decisions for Offline playback based on local preparation status, extracted out of PlaybackController/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.swift owns the app-lifetime CustomCinemaSessionStore that retains the live controller across window dismiss / Cinema present. Labstream/Platforms/visionOS/Player/CustomCinemaMode.swift is the user-visible immersive presenter for that retained controller and is absent from non-vision products at compile time.
  • Labstream/Platforms/visionOS/Player/CinemaTransitionCoordinator.swift and CinemaTransitionPolicy.swift own generation-fenced open/appear/detach/dismiss/disappear transitions. Do not re-home the controller on the ImmersiveSpace view.
  • Labstream/Platforms/visionOS/Player/CinemaAppRouting.swift is 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.swift owns 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.swift privately owns exact-attempt Jellyfin/Emby keepalive tasks and credential-generation quarantine; the manager only forwards start/reconcile and exact-cancellation requests.
  • DownloadManager+Plex.swift and DownloadManager+PlexOptimize.swift own Plex source and optimizer behavior.
  • DownloadManager+Jellyfin.swift owns Jellyfin original/transcode/remux behavior.
  • DownloadManager+Emby.swift and DownloadManager+EmbyConvert.swift own Emby source, remux, and Convert behavior.
  • DownloadManager+SideCache.swift caches posters, subtitles, chapters, Plex BIF, Emby BIF, Emby text subtitles, and Jellyfin trick-play assets through DownloadSideAssetService.swift, which owns validated off-main repair inventory/preparation and exact resource admission.
  • DownloadPlanningRequestExecutor.swift is the injected nonpersistent request boundary for DownloadItemPlanner; same-origin 307/308 redirects preserve method/body/headers and every other redirect is rejected.
  • DownloadOptionsModel.swift owns typed per-item option resolution for the download sheet. DownloadManager+SeasonPlanner.swift and SeasonDownloadPlannerSheet.swift own immutable season drafts and the one atomic Store commit of new rows plus retry markers.
  • DownloadTransferStartPlan.swift is the common backend-to-transfer handoff contract.
  • Labstream/Capabilities/Downloads/Core/BackgroundDownloadSession.swift owns URLSession delegates, reattachment, progress, validation, background-wake release effects, and durable static byte-range recovery.
  • BackgroundDownloadWakeCoordinator.swift owns the locked background-completion gate, atomic deferred-revalidation drain, and range-rebuild grace generations.
  • Labstream/Capabilities/Downloads/Core/BackgroundDownloadCompletionRegistry.swift joins system relaunch callbacks to the live/recreated background session.
  • Labstream/Capabilities/Downloads/Core/DownloadStore.swift owns the locked relative-path index and files under Application Support.
  • DownloadArtifactLifecycleCoordinator.swift registers attempt-scoped filesystem work before execution and releases it only after the matching persistence outcome; DownloadArtifactFileCommitter.swift, DownloadPromotionFilesystem.swift, and DownloadStaticCheckpointFilesystem.swift are the narrow file-effect seams.
  • RevisionedPersistenceWriter.swift and DownloadIndexFileCommitter.swift serialize revisioned index writes. BackgroundCompletionPersistenceBarrier.swift flushes the exact boundary before releasing background-session completion handlers.
  • DownloadWorkRegistry.swift tracks attempt-scoped side-cache and encoder work. DownloadCleanupIntentJournal.swift persists credential-free Plex/Jellyfin/Emby cleanup independently so deleting a row cannot discard required server cleanup. EmbyConvertCleanupJournal.swift owns the compatibility Emby Convert tombstone file and serializes that queue independently of the DownloadStore index lock.
  • Labstream/Capabilities/Downloads/Core/OfflineLibraryView.swift owns 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.swift owns 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's OfflineLaunchAvailability decides admission from the typed SessionRestoreOutcome (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.swift owns 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.swift defines the backend-neutral browse boundary.
  • PlexMusicProvider.swift supplies Plex-native and richer artist data.
  • MediaBrowserMusicProvider.swift is shared by Jellyfin and Emby.
  • MusicStreamResolver.swift is the single backend-aware stream resolver.
  • MusicPlayerController.swift owns the app-lifetime AVPlayer queue, shuffle/repeat, audio-session behavior, remote commands, and Now Playing metadata.
  • MusicPlaybackLifecycle.swift generation-guards per-track observers and queued work; music acquires the shared SystemMediaSessionCoordinator lease 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.swift and NowPlayingView.swift are the compact/full playback surfaces. RootNavigationCoordinator.nowPlayingPresentation owns shared presentation state; VisionRootShell owns the app-owned visionOS backdrop and VisionNowPlayingPanel so a surround tap and the explicit leading-edge close control use the same dismissal path without activating obscured content. RootView only 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.swift defines the GroupActivity wrapper and maps PMSKit's sanitized payload display fields into GroupActivityMetadata.
  • Labstream/Platforms/visionOS/SharePlay/WatchTogetherCoordinator.swift owns activation, GroupSession and messenger state, participant readiness, local launch, the exact-item attachment consent gate, and the AVPlayerPlaybackCoordinator session binding.
  • Labstream/Platforms/visionOS/SharePlay/WatchTogetherMediaLookup.swift searches and attempts to hydrate candidates only through the participant's currently authenticated online backend.
  • Labstream/Platforms/visionOS/SharePlay/WatchTogetherJoinView.swift presents 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.swift and Labstream/Platforms/visionOS/Player/CustomCinemaMode.swift maintain attachment across player-item replacement and the window-to-Cinema handoff.
  • PMSKit/Sources/PMSKit/SharePlay/SharePlayMediaIdentity.swift owns backend-neutral payload privacy, matching, readiness, leave, and late-join re-broadcast decisions; PMSKit/Sources/PMSKit/SharePlay/SharePlayPlaybackAttachmentRevision.swift owns the pure session/item revision key.

System integration

  • Labstream/Shared/SystemIntegration/SystemEntryRouter.swift is 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.swift defines Play, Open, and Continue Watching App Intents for all three backends.
  • Labstream/Shared/SystemIntegration/MediaItemEntity.swift defines backend/server-scoped AppEntity search and suggestions. Display values are snapshots; metadata is refetched before navigation.
  • Labstream/Shared/SystemIntegration/SpotlightIndexer.swift performs token-free, index-as-you-browse video indexing and shared-domain deletion.
  • PMSKit/Sources/PMSKit/SystemEntryRouting.swift contains 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.swift is the opt-in app-side facade.
  • DiagnosticFileLogSink.swift owns the rotating local JSONL sink.
  • DiagnosticReportArtifact.swift owns 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 are PMSKit/.../Diagnostics/DiagnosticLogShareHTTP.swift.
  • BrowseDiagnostics.swift creates privacy-safe browse facts.
  • MetricKitDiagnostics.swift stores a bounded set of redacted crash/hang summaries for user-generated feedback; it does not upload them.
  • PerformanceInstrumentation.swift is 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.py is 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), and Labstream/Platforms/tvOS/Debug/ (TV input evidence and player fixture), and Labstream/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 with swift test --package-path PMSKit --no-parallel --skip 'Live.*ProbeTests'.
  • LabstreamTests/ holds app-hosted unit tests shared by the LabstreamTests, LabstreamMacTests, and LabstreamTVTests targets (each with its own .xctestplan); LabstreamMobileUITests/ and LabstreamTVUITests/ hold the semantic XCUITest runners. See Testing strategy.
  • Labstream.xcodeproj/project.pbxproj is the source of truth for the four native app target versions, platforms, and deployment settings.
  • scripts/worktree-sim.sh provisions the visionOS worktree simulator or explicit iPhone/iPad and Apple TV simulators.
  • scripts/deploy-mobile-to-device.sh deploys the signed mobile target to iPhone/iPad; scripts/deploy-to-device.sh deploys the signed visionOS target.
  • scripts/deploy-macos-to-host.sh builds/installs/cleans up the native Mac host app (no simulator); scripts/deploy-ad-hoc-to-device.sh builds, exports, and installs an Ad Hoc distribution-signed visionOS build on a registered Apple Vision Pro.
  • scripts/xcodebuild-versioned.sh is the canonical build wrapper; scripts/native-test-matrix.py affected selects the targets a change must verify; scripts/agent-*-run.sh and agent-playback-run.py are the platform runners; and scripts/testflight-release.py drives archive, validate, upload, and build selection.
  • scripts/ also contains docs, hygiene, version stamping, and optional live-probe tools.
  • .woodpecker/ contains portable CI definitions.