π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune Apple comments
Manav Rathi4adae1241ea6
diff --git a/apple/apps/cast/Cast/Models/CastModels.swift b/apple/apps/cast/Cast/Models/CastModels.swiftindex 2da95e5f99..1164c2dd12 100644--- a/apple/apps/cast/Cast/Models/CastModels.swift+++ b/apple/apps/cast/Cast/Models/CastModels.swift@@ -1,13 +1,11 @@import Foundationimport AVKit-// MARK: - Notification Extensionsextension Notification.Name {static let authenticationExpired = Notification.Name("authenticationExpired")static let slideshowRestarted = Notification.Name("slideshowRestarted")}-// MARK: - Slide Configurationstruct SlideConfiguration {let imageDuration: TimeIntervallet videoDuration: TimeInterval@@ -17,7 +15,6 @@ struct SlideConfiguration {let maxVideoSize: Int64let includeVideos: Bool- // Enhanced prefetch settingslet prefetchCount: Intlet maxCacheSize: Intlet prefetchDelay: TimeInterval@@ -28,8 +25,8 @@ struct SlideConfiguration {videoDuration: TimeInterval = 30.0,useThumbnails: Bool = false,shuffle: Bool = true,- maxImageSize: Int64 = 100 * 1024 * 1024, // 100MB- maxVideoSize: Int64 = 500 * 1024 * 1024, // 500MB+ maxImageSize: Int64 = 100 * 1024 * 1024,+ maxVideoSize: Int64 = 500 * 1024 * 1024,includeVideos: Bool = true,prefetchCount: Int = 3,maxCacheSize: Int = 5,@@ -55,23 +52,21 @@ struct SlideConfiguration {static let `default` = SlideConfiguration()- // TV-optimized configuration (use thumbnails for better performance)static let tvOptimized = SlideConfiguration(- imageDuration: 8.0, // Faster progression for TV viewing+ imageDuration: 8.0,videoDuration: 25.0,- useThumbnails: true, // Better performance on Apple TV+ useThumbnails: true,shuffle: true,- maxImageSize: 50 * 1024 * 1024, // 50MB for TV- maxVideoSize: 200 * 1024 * 1024, // 200MB for TV+ maxImageSize: 50 * 1024 * 1024,+ maxVideoSize: 200 * 1024 * 1024,includeVideos: true,- prefetchCount: 3, // Prefetch next 3 slides- maxCacheSize: 5, // Keep 5 slides in cache- prefetchDelay: 0.5, // 500ms delay between prefetch operations- enablePrefetching: true // Enable prefetching for smooth transitions+ prefetchCount: 3,+ maxCacheSize: 5,+ prefetchDelay: 0.5,+ enablePrefetching: true)}-// MARK: - Data Modelsstruct CastFile: Codable, Equatable {let id: Intlet title: String@@ -110,7 +105,6 @@ struct CastDevice {let receiver: CastReceiver}-// MARK: - Server Response Modelsstruct DeviceRegistrationResponse: Codable {let deviceCode: String}@@ -119,7 +113,6 @@ struct CastDataResponse: Codable {let encCastData: String?}-// MARK: - Errorsenum CastError: Error, LocalizedError {case networkError(String)case serverError(Int, String?)@@ -137,7 +130,6 @@ enum CastError: Error, LocalizedError {}}-// MARK: - Live Photo Modelsstruct LivePhotoComponents {let imageData: Data?let videoData: Data?@@ -145,7 +137,6 @@ struct LivePhotoComponents {let videoPath: URL?}-// MARK: - Cache Metadatastruct CacheMetadata: Codable {let fileIDs: [Int]let totalBytes: Intdiff --git a/apple/apps/cast/Cast/Services/CastPairingService.swift b/apple/apps/cast/Cast/Services/CastPairingService.swiftindex 502d48a6f0..030d185a69 100644--- a/apple/apps/cast/Cast/Services/CastPairingService.swift+++ b/apple/apps/cast/Cast/Services/CastPairingService.swift@@ -1,8 +1,6 @@import SwiftUIimport Foundation-// MARK: - Cast Session Management-@MainActorclass CastSession: ObservableObject {@Published var state: CastSessionState = .idle@@ -35,8 +33,6 @@ class CastSession: ObservableObject {}}-// MARK: - Real Cast Pairing Service-class RealCastPairingService {private let baseURL = "https://api.ente.com"private var pollingTimer: Timer?@@ -44,9 +40,9 @@ class RealCastPairingService {private var isFetchingPayload: Bool = falseprivate var hasDeliveredPayload: Bool = falseprivate var pollingStartTime: Date?- private let initialPollingInterval: TimeInterval = 2.0 // 2 seconds initially- private let extendedPollingInterval: TimeInterval = 5.0 // 5 seconds after 60 seconds- private let pollingIntervalSwitchTime: TimeInterval = 60.0 // Switch after 60 seconds+ private let initialPollingInterval: TimeInterval = 2.0+ private let extendedPollingInterval: TimeInterval = 5.0+ private let pollingIntervalSwitchTime: TimeInterval = 60.0private var hasLoggedIntervalSwitch: Bool = falseprivate func getCurrentPollingInterval() -> TimeInterval {@@ -54,7 +50,6 @@ class RealCastPairingService {let elapsed = Date().timeIntervalSince(startTime)let newInterval = elapsed >= pollingIntervalSwitchTime ? extendedPollingInterval : initialPollingInterval- // Log when switching to extended interval for the first timeif elapsed >= pollingIntervalSwitchTime && newInterval == extendedPollingInterval && !hasLoggedIntervalSwitch {print("Switched to extended polling interval (\(extendedPollingInterval)s) after \(Int(elapsed))s")hasLoggedIntervalSwitch = true@@ -114,7 +109,7 @@ class RealCastPairingService {pollingTimer = Timer.scheduledTimer(withTimeInterval: currentInterval, repeats: false) { [weak self] _ inTask {await self?.checkForPayload(device: device, onPayloadReceived: onPayloadReceived, onError: onError)- // Schedule next poll after this one completes+ // Poll again only after this request finishes.await MainActor.run {self?.scheduleNextPoll(device: device, onPayloadReceived: onPayloadReceived, onError: onError)}@@ -138,7 +133,7 @@ class RealCastPairingService {}if httpResponse.statusCode == 404 {- // No payload available yet - this is expected+ // 404 means no cast payload is available yet.return}diff --git a/apple/apps/cast/Cast/Services/FileCache.swift b/apple/apps/cast/Cast/Services/FileCache.swiftindex a108fb2046..ae89faba53 100644--- a/apple/apps/cast/Cast/Services/FileCache.swift+++ b/apple/apps/cast/Cast/Services/FileCache.swift@@ -1,7 +1,5 @@import Foundation-// MARK: - Persistent Thread-Safe File Cache-actor ThreadSafeFileCache {private var cache: [Int: Data] = [:]private var cacheOrder: [Int] = []@@ -19,7 +17,6 @@ actor ThreadSafeFileCache {self.cacheDirectory = documentsPath.appendingPathComponent("EnteFileCache")self.metadataURL = cacheDirectory.appendingPathComponent("cache_metadata.json")- // Create cache directory if it doesn't existtry? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)loadCacheFromDisk()@@ -32,7 +29,6 @@ actor ThreadSafeFileCache {let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")if let data = try? Data(contentsOf: fileURL) {- // Load into memory cache for faster future accesscache[fileID] = dataif !cacheOrder.contains(fileID) {cacheOrder.append(fileID)@@ -117,7 +113,6 @@ actor ThreadSafeFileCache {}totalBytes -= removedBytes- // Save updated metadata after evictionsaveCacheMetadata()print("Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")@@ -150,7 +145,6 @@ actor ThreadSafeFileCache {print("Loaded \(validFileIDs.count) cached files (\(loadedBytes) bytes) from disk")- // Clean up any invalid entriesif validFileIDs.count != metadata.fileIDs.count {saveCacheMetadata()}@@ -162,4 +156,4 @@ actor ThreadSafeFileCache {try? data.write(to: metadataURL)}}-}\ No newline at end of file+}diff --git a/apple/apps/cast/Cast/Utils/FontUtils.swift b/apple/apps/cast/Cast/Utils/FontUtils.swiftindex 552d0ef652..6a9eec04d1 100644--- a/apple/apps/cast/Cast/Utils/FontUtils.swift+++ b/apple/apps/cast/Cast/Utils/FontUtils.swift@@ -2,9 +2,7 @@ import SwiftUIimport UIKitstruct FontUtils {-- // MARK: - Safe Font Creation-+private static func safeFont(name: String, size: CGFloat, fallback: Font) -> Font {if UIFont(name: name, size: size) != nil {return .custom(name, size: size)@@ -12,9 +10,7 @@ struct FontUtils {return fallback}}-- // MARK: - Font Presets-+static func montserratBold(size: CGFloat) -> Font {return safeFont(name: "Montserrat-Bold", size: size, fallback: .system(size: size, weight: .bold))}diff --git a/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift b/apple/apps/cast/Cast/Utils/ScreenSaverManager.swiftindex 730300028f..669d6822a3 100644--- a/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift+++ b/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift@@ -23,8 +23,7 @@ class ScreenSaverManager: ObservableObject {UIApplication.shared.isIdleTimerDisabled = trueisDisabled = true- // Fallback for problematic tvOS versions where isIdleTimerDisabled doesn't work reliably- // This timer periodically refreshes the setting to ensure it stays disabled+ // Refresh because this setting is unreliable on some tvOS versions.refreshTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { _ inUIApplication.shared.isIdleTimerDisabled = falseUIApplication.shared.isIdleTimerDisabled = truediff --git a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/apple/apps/cast/Cast/ViewModels/CastViewModel.swiftindex bd36684904..50e6559899 100644--- a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift+++ b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift@@ -4,7 +4,6 @@ import UIKit@MainActorclass CastViewModel: ObservableObject {- // MARK: - Published Properties@Published var currentView: CurrentView = .connecting@Published var deviceCode: String = ""@Published var currentImageData: Data?@@ -13,12 +12,10 @@ class CastViewModel: ObservableObject {@Published var statusMessage: String = ""@Published var errorMessage: String?- // MARK: - Private Propertiesprivate var cancellables = Set<AnyCancellable>()private let pairingService: RealCastPairingServiceprivate let castSession: CastSession- // MARK: - Public Propertiespublic let slideshowService: RealSlideshowServiceenum CurrentView {@@ -50,7 +47,6 @@ class CastViewModel: ObservableObject {.receive(on: DispatchQueue.main).assign(to: \.currentImageData, on: self).store(in: &cancellables)- // Auto-transition once first image arrives (covers single-image albums and empty-to-populated)slideshowService.$currentImageData.receive(on: DispatchQueue.main).sink { [weak self] data in@@ -123,8 +119,6 @@ class CastViewModel: ObservableObject {.store(in: &cancellables)}- // MARK: - Public Methods-func startCastSession() {castSession.setState(.registering)deviceCode = ""@@ -178,7 +172,6 @@ class CastViewModel: ObservableObject {}private func handlePayloadReceived(_ payload: CastPayload) {- // Idempotency: if we're already connected with same payload, skipif case .connected(let existing) = castSession.state, existing == payload {return}@@ -188,12 +181,10 @@ class CastViewModel: ObservableObject {statusMessage = ""Task {- // Add a small delay to prevent flickering from rapid state changestry? await Task.sleep(nanoseconds: 500_000_000)await slideshowService.start(castPayload: payload)- // Additional delay to ensure slideshow is properly loadedtry? await Task.sleep(nanoseconds: 1_000_000_000)await MainActor.run {@@ -220,8 +211,6 @@ class CastViewModel: ObservableObject {}}- // MARK: - Slideshow Navigation-func nextSlide() {guard currentView == .slideshow else { return }@@ -238,8 +227,6 @@ class CastViewModel: ObservableObject {}}- // MARK: - Private Methods-private func handleStateChange(_ state: CastSessionState) {switch state {case .idle:@@ -263,10 +250,8 @@ class CastViewModel: ObservableObject {}private func handleSlideshowError(_ error: String) {- // Prevent stale slideshow errors from a previous (expired) session- // from overriding the fresh pairing code UI. Only react to slideshow- // errors once we are actually in a connected/slideshow flow.- // Exception: Allow empty state errors even during connecting+ // Ignore stale slideshow errors while a new connection is starting.+ // Empty-state errors may belong to the new connection.let isEmptyStateError = error.contains("No media files") ||error.contains("available in this album") ||error.contains("available in this collection") ||@@ -310,7 +295,6 @@ class CastViewModel: ObservableObject {pairingService.resetForNewSession()await MainActor.run {- // Directly set to pairing once device registration begins to avoid brief empty/error flickercurrentView = .connectingerrorMessage = nilstatusMessage = "Starting fresh session..."diff --git a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/apple/apps/cast/Cast/ViewModels/SlideshowService.swiftindex f95428198c..36a5d6d2d8 100644--- a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift+++ b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift@@ -6,11 +6,10 @@ import UIKit@MainActorclass RealSlideshowService: ObservableObject {- // MARK: - Published Properties@Published var currentImageData: Data?- @Published var currentVideoData: Data? // Deprecated path (kept for compatibility)- @Published var currentVideoURL: URL? // Temp file URL for AVPlayer playback- @Published var livePhotoVideoData: Data? // Video component for live photos+ @Published var currentVideoData: Data?+ @Published var currentVideoURL: URL?+ @Published var livePhotoVideoData: Data?@Published var videoPlayer: AVPlayer?@Published var isVideoPlaying: Bool = false@Published var videoCurrentTime: Double = 0@@ -18,16 +17,12 @@ class RealSlideshowService: ObservableObject {@Published var currentFile: CastFile?@Published var error: String?- // Enhanced state management@Published var isPlaying: Bool = false@Published var isPaused: Bool = false@Published var slideLoadingProgress: Double = 0.0@Published var currentSlideIndex: Int = 0@Published var totalSlides: Int = 0- // MARK: - Private Properties-- // Global file list managementprivate var allFiles: [CastFile] = []private var currentFileIndex: Int = 0private var lastUpdateTime: Int64 = 0@@ -35,14 +30,12 @@ class RealSlideshowService: ObservableObject {private var hasCompletedInitialFetch: Bool = falseprivate var storedCastPayload: CastPayload?- // Periodic diff pollingprivate var diffPollingTimer: Timer?- private let diffPollingInterval: TimeInterval = 5.0 // 5 seconds+ private let diffPollingInterval: TimeInterval = 5.0private var isPeriodicPollingEnabled: Bool = trueprivate var currentFileWasDeleted: Bool = false- private var isStopping: Bool = false // Flag to indicate service is being stopped+ private var isStopping: Bool = false- // Enhanced slideshow featuresprivate var slideTimer: Timer?private var prefetchCache: [Int: Data] = [:]private var videoTempFiles: [Int: URL] = [:]@@ -51,34 +44,27 @@ class RealSlideshowService: ObservableObject {private var slidePauseTime: Date?private var slideStartTime: Date?- // File content caching - prevent redundant downloadsprivate let fileCache = ThreadSafeFileCache(- maxBytes: 4096 * 1024 * 1024, // 4GB- shrinkTargetBytes: 2048 * 1024 * 1024 // 2GB+ maxBytes: 4096 * 1024 * 1024,+ shrinkTargetBytes: 2048 * 1024 * 1024)- // Simplified mode: only load first file (no slideshow navigation)private var didDisplayFirstFile: Bool = falseprivate let baseURL = "https://api.ente.com"private let castDownloadURL = "https://cast-albums.ente.com/download"- // Configuration Flags- private let verboseFileLogging = false // Reduces per-file spam unless true- private let verboseDecryptionLogging = false // Detailed size/key logs+ private let verboseFileLogging = false+ private let verboseDecryptionLogging = false- // 401 Error Handlingprivate var isHandlingAuthExpiry: Bool = false- // MARK: - Slideshow Controls-func pause() {slideTimer?.invalidate()slideTimer = nilisPlaying = falseisPaused = true- // Calculate remaining time when pausingif let startTime = slideStartTime {let elapsed = Date().timeIntervalSince(startTime)let totalDuration = currentFile.map { slideshowConfiguration.duration(for: $0) } ?? 0@@ -93,7 +79,6 @@ class RealSlideshowService: ObservableObject {isPlaying = trueslidePauseTime = nil- // Resume with remaining time if we have it, otherwise start freshif slideTimeRemaining > 0 {startSlideTimer(withDuration: slideTimeRemaining)} else {@@ -110,33 +95,29 @@ class RealSlideshowService: ObservableObject {}func nextSlide() async {- // If we no longer have an active payload (e.g. after auth expiry reset) just ignore any stray timer fires+ // Ignore timer callbacks after the session has been reset.guard storedCastPayload != nil else { return }guard !allFiles.isEmpty else {- // Only surface empty-state error if we're in an active slideshow session (payload present)await MainActor.run {self.error = "No media files available in this album"}return}- // For single photo, just restart the timer without changing indexif allFiles.count == 1 {if isPlaying && !isPaused {startSlideTimer()}return}-- // Check if current file was deleted and handle accordingly+if currentFileWasDeleted {currentFileWasDeleted = false- // Current index already adjusted in processDiffBatch+ // Removing this file already exposed the next item at this index.if currentFileIndex >= allFiles.count {currentFileIndex = 0}} else {- // Normal progression to next slidecurrentFileIndex = (currentFileIndex + 1) % allFiles.count}@@ -155,25 +136,18 @@ class RealSlideshowService: ObservableObject {}}- // MARK: - Main Entry Points-func start(castPayload: CastPayload) async {- // Enable screen saver prevention for slideshowScreenSaverManager.preventScreenSaver()- // Clear any expired state first, then store new payloadawait clearExpiredTokenState()storedCastPayload = castPayloadawait MainActor.run {- // Don't blindly nuke existing UI state until we actually know file list status- // Just mark as loading; CastViewModel controls high-level view transitions.if self.error != nil { self.error = nil }}do {- // Initialize file list and fetch all files with paginationawait initializeFileList(castPayload: castPayload)let fileCount = await MainActor.run { allFiles.count }@@ -186,7 +160,6 @@ class RealSlideshowService: ObservableObject {print("Found \(fileCount) files total")- // Clean up cache for files no longer in the collectionlet validFileIDs = Set(await MainActor.run { allFiles.map { $0.id } })await cleanupExpiredCache(validFileIDs: validFileIDs)@@ -198,10 +171,8 @@ class RealSlideshowService: ObservableObject {self.isPaused = false}- // Display first file and start slideshowawait displaySlideAtCurrentIndex()- // For single photo, ensure timer is started even if it's an imageif fileCount == 1 {startSlideTimer()} else {@@ -219,20 +190,17 @@ class RealSlideshowService: ObservableObject {func stop() async {- // Disable screen saver prevention when stopping slideshowScreenSaverManager.allowScreenSaver()- // Set stopping flag to cancel ongoing operationsawait MainActor.run {isStopping = truestopPeriodicDiffPolling()}- // Invalidate slide timer to avoid post-reset nextSlide() firing that could trigger false empty-state UI- slideTimer?.invalidate()- slideTimer = nil+ // A late timer callback would surface a false empty state.+ slideTimer?.invalidate()+ slideTimer = nil- // Clear navigation stateawait MainActor.run {currentFile = nilcurrentImageData = nil@@ -246,7 +214,6 @@ class RealSlideshowService: ObservableObject {let stats = await getCacheStats()print("Final cache stats: \(stats.count) files, \(stats.totalSize) bytes")- // Reset stopping flag for next sessionawait MainActor.run {isStopping = false}@@ -254,11 +221,10 @@ class RealSlideshowService: ObservableObject {func clearExpiredTokenState() async {- // Ensure screen saver prevention is disabled when clearing expired stateScreenSaverManager.allowScreenSaver()await MainActor.run {- // Ensure any existing slide timer from previous session is cancelled to prevent spurious empty-state errors+ // A late timer callback would surface a false empty state.slideTimer?.invalidate()slideTimer = nilstoredCastPayload = nil@@ -266,7 +232,6 @@ class RealSlideshowService: ObservableObject {hasCompletedInitialFetch = falseallFiles.removeAll()prefetchCache.removeAll()- // Clear any error state that might trigger empty viewerror = nilcurrentFile = nilcurrentImageData = nil@@ -274,38 +239,31 @@ class RealSlideshowService: ObservableObject {currentVideoURL = nillivePhotoVideoData = nil}- // Don't clear cache automatically - preserve across sessions+ // Preserve the cache across sessions.}- // MARK: - File List Management-@MainActorprivate func initializeFileList(castPayload: CastPayload) async {- // Check if we've already completed the initial fetchif hasCompletedInitialFetch && !allFiles.isEmpty {print("Using cached file list with \(allFiles.count) files")return}- // Reset state for fresh fetchallFiles.removeAll()lastUpdateTime = 0currentFileIndex = 0hasCompletedInitialFetch = false- // Fetch all pages until hasMore is falsedo {try await fetchAllFiles(castPayload: castPayload)- // Mark as completed only after successfully fetching all pageshasCompletedInitialFetch = true- // Shuffle order to randomize slideshow similar to web experienceif !allFiles.isEmpty {allFiles.shuffle()}print("Initial diff fetch completed - \(allFiles.count) files cached (shuffled)")} catch {print("Failed to fetch files: \(error)")- hasCompletedInitialFetch = false // Ensure we retry on next attempt+ hasCompletedInitialFetch = falseself.error = "Failed to load files: \(error.localizedDescription)"}}@@ -318,10 +276,8 @@ class RealSlideshowService: ObservableObject {if verboseFileLogging { print("Fetching files since time: \(sinceTime)") }let result = try await fetchFilesBatch(castPayload: castPayload, sinceTime: sinceTime)- // Process the batch on MainActorawait processDiffBatch(result.files, collectionKey: castPayload.collectionKey)- // Update pagination state on MainActorawait MainActor.run {if result.latestUpdateTime > self.lastUpdateTime {print("Initial fetch updating lastUpdateTime: \(self.lastUpdateTime) β \(result.latestUpdateTime)")@@ -336,7 +292,6 @@ class RealSlideshowService: ObservableObject {print("Initial diff fetch complete - total files cached: \(await MainActor.run { allFiles.count })")- // Start periodic polling after initial fetch completesawait MainActor.run {startPeriodicDiffPolling()}@@ -361,7 +316,6 @@ class RealSlideshowService: ObservableObject {}guard httpResponse.statusCode == 200 else {- // Handle 401 specially - this means token expired, need to reset to pairingif httpResponse.statusCode == 401 {await handleUnauthorizedError()throw CastError.serverError(401, "Authentication expired - resetting to pairing mode")@@ -369,7 +323,6 @@ class RealSlideshowService: ObservableObject {throw CastError.serverError(httpResponse.statusCode, String(data: data, encoding: .utf8))}- // Parse the diff responseguard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],let diff = json["diff"] as? [[String: Any]] else {throw CastError.networkError("Invalid JSON response")@@ -377,7 +330,6 @@ class RealSlideshowService: ObservableObject {let hasMore = json["hasMore"] as? Bool ?? false- // Find the latest update time from this batchvar latestUpdateTime = sinceTimevar foundAnyUpdates = falsefor item in diff {@@ -387,7 +339,6 @@ class RealSlideshowService: ObservableObject {}}- // If no items had updationTime, keep the original sinceTimeif !foundAnyUpdates {latestUpdateTime = sinceTime}@@ -411,26 +362,22 @@ class RealSlideshowService: ObservableObject {let isDeleted = item["isDeleted"] as? Bool ?? falseif isDeleted {- // Remove file from list if it existsif let index = allFiles.firstIndex(where: { $0.id == id }) {let removedFile = allFiles.remove(at: index)print("Removed deleted file: \(removedFile.title) (ID: \(id))")- // Check if deleted file was the currently playing oneif originalCurrentFile?.id == id {currentFileWasDeleted = true- // Immediately move to next slide if current was deletedTask {await self.nextSlide()}}- // Adjust current index if necessaryif index < currentFileIndex && currentFileIndex > 0 {currentFileIndex -= 1} else if index == currentFileIndex && currentFileIndex >= allFiles.count && !allFiles.isEmpty {- currentFileIndex = 0 // Wrap around to beginning+ currentFileIndex = 0}prefetchCache.removeValue(forKey: id)@@ -440,29 +387,24 @@ class RealSlideshowService: ObservableObject {print("Skipping deleted file \(id) (not in list)")}} else {- // Add or update filedo {- // Only decrypt metadata here, not file contentif let file = try await decryptFileMetadata(item: item, collectionKey: collectionKey) {- // Skip pure videos (we only want images + live photos)+ // Cast images and Live Photos, not standalone videos.if file.isVideo && !file.isLivePhoto {if verboseFileLogging { print("Skipping video file: \(file.title) (ID: \(id))") }continue}- // Check if file already existsif let existingIndex = allFiles.firstIndex(where: { $0.id == id }) {let oldFile = allFiles[existingIndex]allFiles[existingIndex] = fileprint("Updated file: \(file.title) (ID: \(id))")- // Check if hash changed - clear cache if soif oldFile.hash != file.hash && file.hash != nil {print("Hash changed for file \(id) - clearing cache")prefetchCache.removeValue(forKey: id)await removeCachedFileContent(fileID: id)}- // Track if current file was modifiedif existingIndex == currentFileIndex {currentFileChanged = true}@@ -479,9 +421,7 @@ class RealSlideshowService: ObservableObject {print("File list now contains \(allFiles.count) files")- // Handle state transitionsif allFiles.isEmpty {- // Transition to empty stateslideTimer?.invalidate()slideTimer = nilisPlaying = false@@ -495,17 +435,15 @@ class RealSlideshowService: ObservableObject {currentFileIndex = 0error = "No media files available in this album"} else if wasEmpty {- // Transition from empty to having filescurrentFileIndex = 0currentSlideIndex = 0totalSlides = allFiles.count- // Restart slideshow if we have a stored payloadif let payload = storedCastPayload {print("Restarting slideshow with \(allFiles.count) files")- error = nil // Clear error first to avoid UI flicker+ // Clear before loading to avoid an empty-state flash.+ error = nil- // Display first slide and start slideshowTask {await displaySlideAtCurrentIndex()await MainActor.run {@@ -517,15 +455,12 @@ class RealSlideshowService: ObservableObject {}}} else {- // Normal update - just update counttotalSlides = allFiles.count- // Ensure current index is validif currentFileIndex >= allFiles.count {currentFileIndex = 0}- // If current file was modified, reload itif currentFileChanged && !allFiles.isEmpty {Task {await displaySlideAtCurrentIndex()@@ -533,15 +468,12 @@ class RealSlideshowService: ObservableObject {}}- // Clean up expired cache entries after processing batchlet currentValidFileIDs = Set(allFiles.map { $0.id })Task {await cleanupExpiredCache(validFileIDs: currentValidFileIDs)}}- // MARK: - Slide Display & Navigation-private func displaySlideAtCurrentIndex() async {guard currentFileIndex >= 0, currentFileIndex < allFiles.count,let payload = storedCastPayload else { return }@@ -551,7 +483,6 @@ class RealSlideshowService: ObservableObject {slideLoadingProgress = 0.0}- // Check cache firstif let cachedData = prefetchCache[currentFileIndex] {await updateCurrentSlide(with: cachedData, file: allFiles[currentFileIndex])await MainActor.run { slideLoadingProgress = 1.0 }@@ -575,19 +506,16 @@ class RealSlideshowService: ObservableObject {await updateCurrentSlide(with: decryptedData, file: file)await MainActor.run { slideLoadingProgress = 1.0 }- // Start prefetching next few slidesstartPrefetching()} catch {let file = allFiles[currentFileIndex]print("Failed to load file \(file.id): \(file.title) at index \(currentFileIndex) - \(error)")- // Auto-skip problematic files and continue slideshowawait MainActor.run {slideLoadingProgress = 0.0}- // Try next slide automatically after a brief delayDispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {Task {await self.skipToNextSlide()@@ -598,17 +526,15 @@ class RealSlideshowService: ObservableObject {@MainActorprivate func updateCurrentSlide(with data: Data, file: CastFile) {- // Seamless transition: don't nuke existing image until replacement assigned- let wasEmpty = error == "No media files available in this album"- error = nil- currentFile = file+ // Keep the old image until its replacement is ready.+ let wasEmpty = error == "No media files available in this album"+ error = nil+ currentFile = fileif file.isLivePhoto {- // Handle live photo: extract image component only, store video separatelydo {let components = try extractLivePhotoComponents(from: data)- // For live photos, only set the image component for displayif let imageData = components.imageData {currentImageData = imageDataprint("Live photo image component loaded: \(imageData.count) bytes")@@ -616,7 +542,6 @@ class RealSlideshowService: ObservableObject {currentImageData = data}- // Store video component separately for long-press playbackif let videoData = components.videoData {livePhotoVideoData = videoDataprint("Live photo video component stored: \(videoData.count) bytes")@@ -624,34 +549,29 @@ class RealSlideshowService: ObservableObject {livePhotoVideoData = nil}- // Clear video properties to ensure image displaycurrentVideoData = nilcurrentVideoURL = nil- // Start timer for live photo (show as image)startSlideTimer()} catch {print("Failed to extract live photo components: \(error)")- // Fallback to treating as regular imagecurrentImageData = datacurrentVideoData = nilcurrentVideoURL = nillivePhotoVideoData = nilstartSlideTimer()}-+} else if file.isVideo {- // Switching to video: clear image state nowcurrentImageData = nillivePhotoVideoData = nil- // Write decrypted data to a temp file to preserve original color space & avoid brightness shifts+ // A temp file preserves the color space and avoids brightness shifts.do {let url: URLif let existing = videoTempFiles[file.id] {url = existing} else {- // Extract proper file extension from filenamelet fileExtension = file.title.components(separatedBy: ".").last?.lowercased() ?? "mp4"let tmpURL = FileManager.default.temporaryDirectory.appendingPathComponent("cast_video_\(file.id)_\(UUID().uuidString).\(fileExtension)")try data.write(to: tmpURL, options: .atomic)@@ -659,24 +579,22 @@ class RealSlideshowService: ObservableObject {url = tmpURL}currentVideoURL = url- currentVideoData = nil // release raw data memory+ currentVideoData = nilprepareVideoPlayer(url: url)} catch {print("Failed to persist video temp file: \(error)")currentVideoURL = nil}} else {- // Regular imagecurrentVideoData = nilcurrentVideoURL = nillivePhotoVideoData = nil- currentImageData = data // assign image last for minimal black gap- // Start timer for image slide immediately+ // Assign the image last to avoid a black frame.+ currentImageData = datastartSlideTimer()}error = nil- // If we just transitioned from empty to having content, notify the UIif wasEmpty {NotificationCenter.default.post(name: .slideshowRestarted, object: nil)}@@ -684,7 +602,7 @@ class RealSlideshowService: ObservableObject {private func startSlideTimer(withDuration customDuration: TimeInterval? = nil) {guard let currentFile = currentFile else { return }- // For video slides we rely on actual playback end rather than a fixed timer+ // Video playback advances the slideshow when it ends.if currentFile.isVideo {slideTimeRemaining = 0slideStartTime = nil@@ -696,14 +614,12 @@ class RealSlideshowService: ObservableObject {slideStartTime = Date()slideTimeRemaining = duration- // For single photo albums, we still want the timer to fire to maintain the slideshow loopslideTimer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { [weak self] _ inTask { @MainActor inguard let self = self, self.isPlaying, !self.isPaused else { return }self.slideTimeRemaining = 0self.slideStartTime = nil- // For single photos, nextSlide will just restart the timerawait self.nextSlide()}}@@ -714,7 +630,6 @@ class RealSlideshowService: ObservableObject {currentFileIndex = (currentFileIndex + 1) % allFiles.count- // If we've gone through all files and still have errors, stop the slideshowlet maxRetries = allFiles.countvar retryCount = 0@@ -730,7 +645,6 @@ class RealSlideshowService: ObservableObject {file: file)- // Success! Update the slideprefetchCache[currentFileIndex] = decryptedDataawait updateCurrentSlide(with: decryptedData, file: file)@@ -741,12 +655,10 @@ class RealSlideshowService: ObservableObject {print("Successfully loaded file \(file.id): \(file.title)")- // Restart timer if playingif isPlaying && !isPaused {startSlideTimer()}- // Start prefetching againstartPrefetching()return@@ -758,7 +670,6 @@ class RealSlideshowService: ObservableObject {}}- // If we reach here, all files have issuesawait MainActor.run {self.error = "Unable to load any slides. All files may be corrupted or have decryption issues."}@@ -770,7 +681,6 @@ class RealSlideshowService: ObservableObject {for i in 1...prefetchCount {let prefetchIndex = (currentFileIndex + i) % allFiles.count- // Skip if already cachedif prefetchCache[prefetchIndex] != nil { continue }guard let payload = storedCastPayload else { continue }@@ -783,7 +693,6 @@ class RealSlideshowService: ObservableObject {)prefetchCache[prefetchIndex] = data- // Clean up old cache entriesif prefetchCache.count > 5 {let oldKeys = Array(prefetchCache.keys.sorted().prefix(prefetchCache.count - 5))for key in oldKeys {@@ -797,17 +706,13 @@ class RealSlideshowService: ObservableObject {continue}- // Add delay between prefetch operations- try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds+ try? await Task.sleep(nanoseconds: 500_000_000)}}}- // MARK: - Video Playback Management-private func prepareVideoPlayer(url: URL) {let playerItem = AVPlayerItem(url: url)- // Observe duration once readyNotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: playerItem, queue: .main) { [weak self] _ inTask { @MainActor inself?.videoDidFinish()@@ -818,13 +723,11 @@ class RealSlideshowService: ObservableObject {videoPlayer = playerisVideoPlaying = falsevideoCurrentTime = 0- // Get duration asynchronously for iOS 16+Task { @MainActor inif let duration = try? await playerItem.asset.load(.duration) {self.videoDuration = CMTimeGetSeconds(duration)}}- // Auto-playplayVideo()startVideoProgressUpdates()}@@ -845,7 +748,6 @@ class RealSlideshowService: ObservableObject {guard let player = videoPlayer else { return }player.play()isVideoPlaying = true- // Ensure slideshow timer paused during video playbackslideTimer?.invalidate()}@@ -858,13 +760,11 @@ class RealSlideshowService: ObservableObject {}}- // MARK: - Periodic Diff Polling-@MainActorprivate func startPeriodicDiffPolling() {guard isPeriodicPollingEnabled && storedCastPayload != nil else { return }- stopPeriodicDiffPolling() // Stop any existing timer+ stopPeriodicDiffPolling()print("Starting periodic diff polling (every \(diffPollingInterval)s)")@@ -896,7 +796,6 @@ class RealSlideshowService: ObservableObject {await processDiffBatch(result.files, collectionKey: payload.collectionKey)- // Only update lastUpdateTime if we actually found items with valid updationTimeawait MainActor.run {if result.latestUpdateTime > self.lastUpdateTime {print("Updating lastUpdateTime: \(self.lastUpdateTime) β \(result.latestUpdateTime)")@@ -910,48 +809,38 @@ class RealSlideshowService: ObservableObject {} catch {if let castError = error as? CastError,case .serverError(401, _) = castError {- // handleUnauthorizedError already called in fetchFilesBatch+ // fetchFilesBatch already handled this error.} else {print("Periodic diff check failed: \(error)")- // Continue polling on other errors}}}- // MARK: - 401 Error Handling-@MainActorprivate func handleUnauthorizedError() {- // Prevent multiple concurrent auth expiry handlingguard !isHandlingAuthExpiry else {return}isHandlingAuthExpiry = true- // Stop screen saver prevention immediately before any UI transitionsScreenSaverManager.allowScreenSaver()- // Stop all ongoing operationsisPeriodicPollingEnabled = falsestopPeriodicDiffPolling()- // Notify the view model to reset sessionNotificationCenter.default.post(name: .authenticationExpired, object: nil)- // Reset flag after a delay to allow reset to complete+ // Keep the guard set while the session resets.Task {- try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds+ try? await Task.sleep(nanoseconds: 2_000_000_000)await MainActor.run {self.isHandlingAuthExpiry = false}}}- // MARK: - Network & Download-private func downloadEncryptedFile(castPayload: CastPayload, fileID: Int) async throws -> Data {- // Use the file download endpoint with cast-specific headerslet url = URL(string: "\(castDownloadURL)/?fileID=\(fileID)")!var request = URLRequest(url: url)@@ -965,7 +854,6 @@ class RealSlideshowService: ObservableObject {}guard httpResponse.statusCode == 200 else {- // Condensed error loglet snippet = (String(data: data, encoding: .utf8) ?? "").prefix(160)print("Download error [\(httpResponse.statusCode)] fileID=\(fileID): \(snippet)")if httpResponse.statusCode == 401 {@@ -980,13 +868,11 @@ class RealSlideshowService: ObservableObject {}private func downloadAndDecryptFileContent(castPayload: CastPayload, file: CastFile) async throws -> Data {- // Check if service is stoppinglet stopping = await MainActor.run { isStopping }if stopping {throw CastError.networkError("Service is stopping")}- // Check cache firstif let cachedData = await getCachedFileContent(fileID: file.id) {if verboseFileLogging { print("Using cached content for file \(file.id): \(file.title) (\(cachedData.count) bytes)") }return cachedData@@ -994,11 +880,9 @@ class RealSlideshowService: ObservableObject {if verboseFileLogging { print("Downloading and decrypting file \(file.id): \(file.title)") }- // Step 1: Download encrypted filelet encryptedData = try await downloadEncryptedFile(castPayload: castPayload, fileID: file.id)if verboseFileLogging { print("Downloaded \(encryptedData.count) bytes") }- // Step 2: Decrypt file key using collection keylet fileKey = try decryptFileKey(encryptedKey: file.encryptedKey,nonce: file.keyDecryptionNonce,@@ -1006,7 +890,6 @@ class RealSlideshowService: ObservableObject {)- // Step 3: Decrypt file content using file key and decryption headerlet decryptedData = try decryptFileContent(encryptedData: encryptedData,fileKey: fileKey,@@ -1014,14 +897,11 @@ class RealSlideshowService: ObservableObject {)- // Step 4: Cache the decrypted contentawait cacheFileContent(fileID: file.id, data: decryptedData)return decryptedData}- // MARK: - File Decryption Functions-private func decryptFileMetadata(item: [String: Any], collectionKey: String) async throws -> CastFile? {guard let id = item["id"] as? Int,let encryptedKey = item["encryptedKey"] as? String,@@ -1036,7 +916,6 @@ class RealSlideshowService: ObservableObject {}do {- // Step 1: Decrypt file key using collection key (SecretBox)let fileKey = try decryptFileKey(encryptedKey: encryptedKey,nonce: keyDecryptionNonce,@@ -1044,7 +923,6 @@ class RealSlideshowService: ObservableObject {)if verboseDecryptionLogging { print("File key decrypted successfully") }- // Step 2: Decrypt metadata using file key (XChaCha20-Poly1305)let metadata = try decryptMetadata(encryptedData: encryptedMetadata,decryptionHeader: metadataHeader,@@ -1052,11 +930,9 @@ class RealSlideshowService: ObservableObject {)- // Step 3: Parse decrypted metadata JSONlet fileMetadata = try parseFileMetadata(data: metadata)- // Create CastFile with decrypted metadata and decryption infolet isVideo = fileMetadata.fileType == 1let isLivePhoto = fileMetadata.fileType == 2return CastFile(@@ -1077,7 +953,6 @@ class RealSlideshowService: ObservableObject {}private func decryptFileKey(encryptedKey: String, nonce: String, collectionKey: String) throws -> Data {- // Convert base64 inputs to dataguard let encryptedKeyData = Data(base64Encoded: encryptedKey),let nonceData = Data(base64Encoded: nonce),let collectionKeyData = Data(base64Encoded: collectionKey) else {@@ -1093,7 +968,6 @@ class RealSlideshowService: ObservableObject {}private func decryptMetadata(encryptedData: String, decryptionHeader: String, fileKey: Data) throws -> Data {- // Convert base64 inputs to dataguard let encryptedBytes = Data(base64Encoded: encryptedData),let headerBytes = Data(base64Encoded: decryptionHeader) else {throw CastError.decryptionError("Invalid base64 in metadata decryption")@@ -1111,7 +985,6 @@ class RealSlideshowService: ObservableObject {}private func decryptFileContent(encryptedData: Data, fileKey: Data, decryptionHeader: String) throws -> Data {- // Convert base64 header to dataguard let headerBytes = Data(base64Encoded: decryptionHeader) else {throw CastError.decryptionError("Invalid base64 in file decryption header")}@@ -1126,7 +999,6 @@ class RealSlideshowService: ObservableObject {}private func parseFileMetadata(data: Data) throws -> FileMetadata {- // Parse the decrypted JSON metadataguard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {throw CastError.decryptionError("Invalid JSON in decrypted metadata")}@@ -1146,8 +1018,6 @@ class RealSlideshowService: ObservableObject {)}- // MARK: - Cache Management Helpers-private func getCachedFileContent(fileID: Int) async -> Data? {return await fileCache.get(fileID)}@@ -1160,10 +1030,8 @@ class RealSlideshowService: ObservableObject {let stats = await getCacheStats()print("Starting cache cleanup - current cache has \(stats.count) files")- // Get all currently cached file IDslet cachedFileIDs = await fileCache.getCachedFileIDs()- // Remove files that are no longer validvar removedCount = 0for cachedFileID in cachedFileIDs {if !validFileIDs.contains(cachedFileID) {@@ -1191,8 +1059,6 @@ class RealSlideshowService: ObservableObject {}}-// MARK: - Live Photo Utilities-func extractZipUsingFoundation(zipURL: URL, to destinationURL: URL) throws {do {try FileManager.default.unzipItem(at: zipURL, to: destinationURL)@@ -1220,10 +1086,9 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponentvar videoPath: URL?do {- // For tvOS, we'll implement a simple zip reader using Foundationtry extractZipUsingFoundation(zipURL: zipURL, to: extractDirectory)- // Enumerate all extracted files (including nested) because zips may contain a folder structure.+ // Live Photo zips may nest their assets.let resourceKeys: [URLResourceKey] = [.isDirectoryKey]let enumerator = FileManager.default.enumerator(at: extractDirectory, includingPropertiesForKeys: resourceKeys)@@ -1238,7 +1103,6 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent}while let fileURL = enumerator?.nextObject() as? URL {- // Skip directoriesif (try? fileURL.resourceValues(forKeys: Set(resourceKeys)).isDirectory) == true { continue }let filename = fileURL.lastPathComponent@@ -1251,18 +1115,17 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponentvideoPath = fileURLprint("Extracted live photo video: \(filename) (\(videoData?.count ?? 0) bytes)")} else {- // Only log unexpected files once both components missing to avoid noiseif imageData == nil || videoData == nil {print("Ignoring non-component file in live photo zip: \(filename)")}}}- // Fallback heuristics: Some live photo packages may store assets without extensions or with generic names.+ // Some packages use extensionless or generic asset names.if imageData == nil || videoData == nil {let contents = try FileManager.default.contentsOfDirectory(at: extractDirectory, includingPropertiesForKeys: nil)if imageData == nil {- if let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) { // pick first extension-less file as possible image+ if let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) {imageData = try? Data(contentsOf: guessImage)imagePath = guessImageif imageData != nil { print("Heuristic image pick: \(guessImage.lastPathComponent)") }diff --git a/apple/apps/cast/Cast/Views/PairingView.swift b/apple/apps/cast/Cast/Views/PairingView.swiftindex 2d31e48f9c..a8c2d45773 100644--- a/apple/apps/cast/Cast/Views/PairingView.swift+++ b/apple/apps/cast/Cast/Views/PairingView.swift@@ -8,26 +8,19 @@ struct PairingView: View {var body: some View {GeometryReader { geometry inZStack {- // White backgroundColor.white.ignoresSafeArea()- // Main content - card positioned with custom paddingHStack(spacing: 0) {- // Left padding (1x)Spacer().frame(width: geometry.size.width * 0.05)- // Green card with contentZStack {- // Green card backgroundRoundedRectangle(cornerRadius: 36).fill(Color(red: 0/255, green: 179/255, blue: 61/255)).shadow(color: Color.black.opacity(0.25), radius: 4, y: 4)- // Card contentVStack(spacing: 0) {- // Title sectionVStack(spacing: -5) {Text("Ready to").font(FontUtils.montserratExtraBold(size: geometry.size.width * 0.035))@@ -42,9 +35,8 @@ struct PairingView: View {Spacer().frame(height: geometry.size.height * 0.05)- // Pairing code boxZStack {- // Reserve the 6-char code footprint so the box doesn't resize when the code arrives+ // Reserve six characters so the box does not resize.Text(deviceCode.isEmpty ? "000000" : deviceCode).font(.system(size: geometry.size.width * 0.09, weight: .heavy, design: .monospaced)).tracking(geometry.size.width * 0.015)@@ -73,7 +65,6 @@ struct PairingView: View {Spacer().frame(height: geometry.size.height * 0.08)- // Instruction stepsHStack(spacing: geometry.size.width * 0.05) {InstructionStep(number: "1",@@ -100,7 +91,6 @@ struct PairingView: View {Spacer().frame(height: geometry.size.height * 0.06)- // Help textText("Visit ente.com/cast for help").font(FontUtils.interMedium(size: geometry.size.width * 0.012)).foregroundColor(.white)@@ -109,7 +99,6 @@ struct PairingView: View {.frame(height: geometry.size.height * 0.04)}- // Ducky positioned at bottom right of the cardVStack {Spacer()HStack {@@ -127,14 +116,12 @@ struct PairingView: View {.frame(width: geometry.size.width * 0.8,height: geometry.size.height * 0.85)- // Right padding (3x)Spacer().frame(width: geometry.size.width * 0.15)}- .padding(.top, geometry.size.height * 0.05) // Top padding (1x)- .padding(.bottom, geometry.size.height * 0.05) // Bottom padding (1x)+ .padding(.top, geometry.size.height * 0.05)+ .padding(.bottom, geometry.size.height * 0.05)- // Ente logo in top right cornerVStack {HStack {Spacer()@@ -167,7 +154,6 @@ struct InstructionStep: View {var body: some View {VStack(spacing: geometry.size.height * 0.015) {- // Circular icon backgroundZStack {Circle().fill(Color(red: 0/255, green: 150/255, blue: 51/255))@@ -179,7 +165,6 @@ struct InstructionStep: View {.foregroundColor(.white)}- // Step textText(text).font(FontUtils.interMedium(size: geometry.size.width * 0.012)).foregroundColor(.white)diff --git a/apple/apps/cast/Cast/Views/SlideshowView.swift b/apple/apps/cast/Cast/Views/SlideshowView.swiftindex d7a34e16c6..5a0c3108ad 100644--- a/apple/apps/cast/Cast/Views/SlideshowView.swift+++ b/apple/apps/cast/Cast/Views/SlideshowView.swift@@ -40,13 +40,11 @@ struct SlideshowView: View {}var body: some View {- // Use pre-decoded images to avoid decoding during renderlet mainUIImage = preDecodedImagelet previousUIImage = previousDecodedImagereturn GeometryReader { geometry inZStack {- // Background layerif let uiImage = mainUIImage {Image(uiImage: uiImage).resizable()@@ -61,7 +59,6 @@ struct SlideshowView: View {Color.black.ignoresSafeArea()}- // Foreground contentif isVideo, let videoData = videoData {VideoPlayerView(videoData: videoData,@@ -82,9 +79,7 @@ struct SlideshowView: View {removal: .scale(scale: 0.9).combined(with: .opacity)))} else if let uiImage = mainUIImage {- // Crossfade image transitionZStack {- // Previous image (fading out)if let prevImage = previousUIImage {Image(uiImage: prevImage).resizable()@@ -94,7 +89,6 @@ struct SlideshowView: View {.opacity(previousImageOpacity)}- // Current image (fading in)Image(uiImage: uiImage).resizable().aspectRatio(contentMode: .fit)@@ -103,7 +97,6 @@ struct SlideshowView: View {.opacity(imageOpacity)}.onAppear {- // Pass image data count for logging purposesanimateImageIn(bytes: displayImageData?.count ?? 0, isLive: isLivePhoto)}.onDisappear {@@ -115,20 +108,16 @@ struct SlideshowView: View {} else {- // Check if we have an empty state vs loading stateif let error = slideshowService.error,(error.contains("No media files available") || error.contains("Empty file list")) {EmptyState()} else if slideshowService.totalSlides == 0 && !slideshowService.isPlaying {- // Still loading initial file listLoadingState()} else {- // Files exist but current slide is loadingLoadingState()}}- // OverlaysactionFeedbackOverlaycontrolsOverlaytoastOverlay@@ -137,28 +126,22 @@ struct SlideshowView: View {.onChange(of: imageData) { newValue inif let newData = newValue {Task {- // Pre-decode image off main threadlet decodedImage = decodedUIImage(from: newData)await MainActor.run {- // Store current decoded image as previous for crossfadepreviousDecodedImage = preDecodedImagepreviousImageData = displayImageData- // Set decoded image firstpreDecodedImage = decodedImage- // Set up opacity statesif previousDecodedImage != nil {previousImageOpacity = 1.0imageOpacity = 0.0} else {- // First image - no crossfade neededimageOpacity = 1.0previousImageOpacity = 0.0}- // Then update display data to trigger view updatedisplayImageData = newDataanimateImageIn(bytes: newData.count, isLive: isLivePhoto)}@@ -181,13 +164,9 @@ struct SlideshowView: View {.onAppear {startControlsTimer()isFocused = true- // Backup screen saver prevention at view levelScreenSaverManager.preventScreenSaver()- // Process initial image data if present and not already processed- // This handles the case where SlideshowView is created with imageData already populated- // (e.g., when transitioning from .connecting to .slideshow state)- // Without this, onChange won't fire and the image won't display+ // onChange does not fire when the view starts with imageData set.if let initialImageData = imageData, displayImageData == nil && !isVideo {Task {let decodedImage = decodedUIImage(from: initialImageData)@@ -203,13 +182,10 @@ struct SlideshowView: View {}}.onDisappear {- // Ensure screen saver prevention is disabled when view disappearsScreenSaverManager.allowScreenSaver()}}- // MARK: - Overlay Views-@ViewBuilderprivate var actionFeedbackOverlay: some View {if let feedback = actionFeedback {@@ -267,7 +243,6 @@ struct SlideshowView: View {showToast(icon: "livephoto", message: "Live Photo Paused")}- // Auto-return to image after video playsif isPlayingLivePhotoVideo {DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {withAnimation(.easeInOut(duration: 0.3)) {@@ -282,7 +257,6 @@ struct SlideshowView: View {slideshowService.togglePlayPause()await MainActor.run {- // Show toast notification onlyif slideshowService.isPaused {showToast(icon: "pause.fill", message: "Paused")} else {@@ -295,10 +269,8 @@ struct SlideshowView: View {switch direction {case .left:await slideshowService.previousSlide()- // No center feedback for navigationcase .right:await slideshowService.nextSlide()- // No center feedback for navigationcase .up, .down:toggleControls()@unknown default:@@ -329,18 +301,15 @@ struct SlideshowView: View {toastMessage = messageshowToast = true- // Auto-dismiss after 2 secondsDispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {showToast = false}}- // MARK: - Image Decoding & Animation-private func decodedUIImage(from data: Data) -> UIImage? {imageDecodeFailed = falseif let uiImage = UIImage(data: data) {- // Force decompression by accessing cgImage+ // Accessing cgImage forces decompression.if let cg = uiImage.cgImage {return UIImage(cgImage: cg, scale: uiImage.scale, orientation: uiImage.imageOrientation)}@@ -356,7 +325,6 @@ struct SlideshowView: View {lastImageBytes = bytesimageScale = 1.0- // Opacity states are already set up in onChange, just animate the crossfadewithAnimation(.easeInOut(duration: 0.25)) {imageOpacity = 1.0previousImageOpacity = 0.0@@ -364,9 +332,8 @@ struct SlideshowView: View {print("Displaying \(isLive ? "live" : "static") image (\(bytes) bytes)")- // Clean up previous image data after animationTask {- try? await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds+ try? await Task.sleep(nanoseconds: 300_000_000)await MainActor.run {previousImageData = nilpreviousImageOpacity = 0.0@@ -376,8 +343,6 @@ struct SlideshowView: View {}-// MARK: - Supporting Views and Types-struct LoadingState: View {@State private var animationPhase: CGFloat = 0@State private var pulseScale: CGFloat = 1.0@@ -633,8 +598,6 @@ struct AppleStyleToast: View {}}-// MARK: - Preview-class MockSlideshowService: ObservableObject {@Published var currentFile: (title: String, isLivePhoto: Bool)? = (title: "Sample Image", isLivePhoto: false)@Published var isPlaying: Bool = truediff --git a/apple/apps/cast/Cast/Views/StatusView.swift b/apple/apps/cast/Cast/Views/StatusView.swiftindex d37bfb8eb1..31f5ba38f5 100644--- a/apple/apps/cast/Cast/Views/StatusView.swift+++ b/apple/apps/cast/Cast/Views/StatusView.swift@@ -17,25 +17,20 @@ struct StatusView: View {var body: some View {GeometryReader { geometry inZStack {- // White backgroundColor.white.ignoresSafeArea()- // Main contentVStack(spacing: 24) {Spacer()- // Status icon - clean display without backgroundsStatusIcon(status: status).padding(.bottom, 16)- // TitleText(title).font(FontUtils.interSemiBold(size: 42)).foregroundColor(.black).multilineTextAlignment(.center)- // Message (if not empty)if !message.isEmpty {Text(message).font(FontUtils.interRegular(size: 20))@@ -49,7 +44,6 @@ struct StatusView: View {.frame(maxWidth: 900).frame(maxWidth: .infinity)- // Ente branding in top right cornerVStack {HStack {Spacer()@@ -94,7 +88,6 @@ struct StatusIcon: View {let status: StatusView.StatusTypevar body: some View {- // Simple icon display without any backgrounds or effectsiconView.frame(width: 400, height: 240)}diff --git a/apple/apps/cast/Cast/Views/VideoPlayerView.swift b/apple/apps/cast/Cast/Views/VideoPlayerView.swiftindex b8c07cb2d3..1c6a2c972f 100644--- a/apple/apps/cast/Cast/Views/VideoPlayerView.swift+++ b/apple/apps/cast/Cast/Views/VideoPlayerView.swift@@ -33,7 +33,6 @@ struct VideoPlayerView: View {cleanup()}} else {- // Clean loading stateVStack(spacing: 24) {ProgressView().progressViewStyle(CircularProgressViewStyle(tint: Color(red: 29/255, green: 185/255, blue: 84/255)))@@ -72,7 +71,6 @@ struct VideoPlayerView: View {let playerItem = AVPlayerItem(url: tempURL)let player = AVPlayer(playerItem: playerItem)- // Monitor player item status using modern async/await approachself.monitorPlayerItemStatus(playerItem)self.playerItem = playerItem@@ -95,7 +93,6 @@ struct VideoPlayerView: View {}private func tryVideoFallback(originalURL: URL) {- // Try creating a new temp file with .mov extension as fallbackTask {do {let fallbackURL = originalURL.deletingPathExtension().appendingPathExtension("mov")@@ -118,11 +115,9 @@ struct VideoPlayerView: View {}private func showErrorState() {- // Could show an error message or placeholder}private func monitorPlayerItemStatus(_ playerItem: AVPlayerItem) {- // Monitor status using a timer-based approach since we can't use KVO in SwiftUI structsTimer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer inswitch playerItem.status {case .readyToPlay:@@ -137,7 +132,6 @@ struct VideoPlayerView: View {self.showErrorState()}case .unknown:- // Keep checkingbreak@unknown default:timer.invalidate()@@ -148,11 +142,9 @@ struct VideoPlayerView: View {private func setupPlayer() {guard let player = player else { return }- // Configure player for TV playbackplayer.actionAtItemEnd = .noneplayer.automaticallyWaitsToMinimizeStalling = true- // Set audio session for proper audio handlingdo {try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)try AVAudioSession.sharedInstance().setActive(true)@@ -169,13 +161,11 @@ struct VideoPlayerView: View {private func setupPlayerObservers() {guard let player = player, let currentItem = player.currentItem else { return }- // Add observer for when video endsNotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime,object: currentItem,queue: .main) { _ in- // Loop the videoplayer.seek(to: .zero)player.play()}@@ -190,7 +180,6 @@ struct VideoPlayerView: View {}}- // Add observer for app lifecycleNotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification,object: nil,@@ -217,9 +206,8 @@ struct VideoPlayerView: View {try data.write(to: tempURL)- // Schedule cleanup of temp file after some timeTask {- try? await Task.sleep(nanoseconds: 60_000_000_000) // 60 seconds+ try? await Task.sleep(nanoseconds: 60_000_000_000)try? FileManager.default.removeItem(at: tempURL)}@@ -227,7 +215,7 @@ struct VideoPlayerView: View {}private func detectVideoExtension(from data: Data) -> String? {- let headerBytes = data.prefix(32) // Read more bytes for better detection+ let headerBytes = data.prefix(32)if headerBytes.count >= 4 {let signature = headerBytes.prefix(4)@@ -278,8 +266,6 @@ struct VideoPlayerView: View {private func cleanup() {player?.pause()- // KVO observer removal no longer needed as we use modern async/await approach-NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)NotificationCenter.default.removeObserver(self, name: .AVPlayerItemFailedToPlayToEndTime, object: nil)NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)diff --git a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex 35f7dd027f..78fb826bc0 100644--- a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -129,7 +129,6 @@ final class ChatViewModel: ObservableObject {let knowledgeProvider = KnowledgeProvider(assetStore: assetStore)let knowledgeStore = KnowledgeStore(datasets: config.knowledgeDatasets, provider: knowledgeProvider)- // Chat DB + attachments.let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)try? FileManager.default.createDirectory(at: dbDir, withIntermediateDirectories: true, attributes: nil)let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)@@ -152,7 +151,6 @@ final class ChatViewModel: ObservableObject {fatalError("Failed to open chat DB: \(error)")}- // Load sessions/messages.let loadedResult = try? chatDb.listSessions()if let loadedResult {Self.pruneOrphanedAttachments(@@ -164,7 +162,6 @@ final class ChatViewModel: ObservableObject {let loaded = loadedResult ?? []let sessions = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)- // Stored properties.self.provider = providerself.knowledgeEmbedding = config.knowledgeEmbeddingself.knowledgeProvider = knowledgeProviderdiff --git a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift b/apple/apps/ensu/Ensu/Chat/MessageInputView.swiftindex 5d329738c8..ec51c758c9 100644--- a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift@@ -53,7 +53,6 @@ struct MessageInputView: View {let inputVerticalPadding: CGFloat = 10let textFieldPadding: CGFloat = 6- // Lift the bar slightly off the bottom edge.let bottomPadding: CGFloat = EnsuSpacing.mdlet inputStackSpacing: CGFloat = EnsuSpacing.smdiff --git a/apple/apps/ensu/Ensu/Services/KeychainStore.swift b/apple/apps/ensu/Ensu/Services/KeychainStore.swiftindex 969f758013..6839f3aab3 100644--- a/apple/apps/ensu/Ensu/Services/KeychainStore.swift+++ b/apple/apps/ensu/Ensu/Services/KeychainStore.swift@@ -18,7 +18,6 @@ final class KeychainStore {kSecValueData as String: data,]- // Try update first.let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)if updateStatus == errSecSuccess {return@@ -27,7 +26,6 @@ final class KeychainStore {throw KeychainStoreError.unexpectedStatus(updateStatus)}- // Insert.var insertQuery = queryinsertQuery[kSecValueData as String] = datainsertQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly