Skip to content

Open source CapCut alternative.

TypeScript

feat(ios): the phone syncs itself to the cloud shelf

David Le34cd767693c8
diff --git a/apps/ios/Donkey/Controllers/AuthController.swift b/apps/ios/Donkey/Controllers/AuthController.swift
index f5fc4fd2..a6b73244 100644
--- a/apps/ios/Donkey/Controllers/AuthController.swift
+++ b/apps/ios/Donkey/Controllers/AuthController.swift
@@ -38,7 +38,8 @@ enum AuthError: LocalizedError {
/// Cut session (better-auth with the bearer plugin). The session token and
/// profile live in the keychain.
final class AuthController: NSObject, AuthServicing {
- private static let tokenKey = "session-token"
+ /// Shared with CutCloudClient, which reads the same session token.
+ static let tokenKey = "session-token"
private static let profileKey = "session-profile"
private var appleContinuation: CheckedContinuation<(token: String, nonce: String), any Error>?
diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swift
new file mode 100644
index 00000000..86cd8e63
--- /dev/null
+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift
@@ -0,0 +1,470 @@
+import AVFoundation
+import DonkeyKitModels
+import Foundation
+import UIKit
+
+/// The phone's HTTP client for the hosted Cut API (/api/cut-cloud/*). The
+/// bearer session comes from the keychain, and every request carries the iOS
+/// client header — the marker that links this account for the desktop's phone
+/// features. Media requests are stamped with the caller's cellular decision so
+/// an upload started on Wi-Fi never silently continues over cell.
+final class CutCloudClient: NSObject {
+ private let base = AuthBackend.baseURL
+
+ // MARK: Requests
+
+ private var token: String? {
+ KeychainStore.read(AuthController.tokenKey).flatMap { String(data: $0, encoding: .utf8) }
+ }
+
+ private func request(
+ _ method: String,
+ _ path: String,
+ body: [String: Any]? = nil,
+ allowCellular: Bool = true
+ ) throws -> URLRequest {
+ guard let token else { throw CloudSyncError.unauthorized }
+ var request = URLRequest(url: base.appending(path: path))
+ request.httpMethod = method
+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ request.setValue("ios", forHTTPHeaderField: "x-donkey-cut-client")
+ request.allowsCellularAccess = allowCellular
+ request.allowsExpensiveNetworkAccess = allowCellular
+ if let body {
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try? JSONSerialization.data(withJSONObject: body)
+ }
+ return request
+ }
+
+ private func send(_ request: URLRequest) async throws -> Data {
+ let data: Data
+ let response: URLResponse
+ do {
+ (data, response) = try await URLSession.shared.data(for: request)
+ } catch {
+ throw CloudSyncError.transport
+ }
+ guard let http = response as? HTTPURLResponse else { throw CloudSyncError.transport }
+ switch http.statusCode {
+ case 200..<300: return data
+ case 401, 403: throw CloudSyncError.unauthorized
+ case 413: throw CloudSyncError.storageFull
+ default: throw CloudSyncError.transport
+ }
+ }
+
+ private func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
+ guard let value = try? JSONDecoder().decode(type, from: data) else {
+ throw CloudSyncError.transport
+ }
+ return value
+ }
+
+ /// Follows the API's 302 by hand and hands back the CDN URL it points at,
+ /// so AVPlayer streams the CDN directly.
+ private func resolveRedirect(_ path: String) async throws -> URL {
+ let request = try request("GET", path)
+ let response: URLResponse
+ do {
+ (_, response) = try await URLSession.shared.data(for: request, delegate: RedirectCatcher())
+ } catch {
+ throw CloudSyncError.transport
+ }
+ guard let http = response as? HTTPURLResponse,
+ (300..<400).contains(http.statusCode),
+ let location = http.value(forHTTPHeaderField: "Location"),
+ let url = URL(string: location, relativeTo: base) else {
+ throw CloudSyncError.transport
+ }
+ return url.absoluteURL
+ }
+}
+
+// MARK: - Media up-sync
+
+extension CutCloudClient: CloudSyncServicing {
+ private struct PresignResponse: Decodable {
+ var fileName: String
+ var key: String
+ var url: String?
+ var done: Bool?
+ }
+
+ private struct AssetResponse: Decodable {
+ var id: String
+ var fileName: String
+ }
+
+ func uploadLibraryMedia(
+ _ upload: LibraryUpload,
+ allowCellular: Bool,
+ progress: @escaping @Sendable (Double) -> Void
+ ) async throws -> RemoteAsset {
+ let presign = try await presignLibrary(
+ fileName: upload.fileName,
+ mime: upload.mime,
+ bytes: upload.bytes,
+ resume: upload.resume,
+ allowCellular: allowCellular
+ )
+ if presign.done != true {
+ guard let url = presign.url.flatMap(URL.init(string:)) else { throw CloudSyncError.transport }
+ try await putFile(upload.fileURL, to: url, mime: upload.mime, allowCellular: allowCellular, progress: progress)
+ }
+ let posterKey: String? = if let poster = upload.poster {
+ try? await uploadPoster(poster, besides: presign.fileName, allowCellular: allowCellular)
+ } else {
+ nil
+ }
+ var meta: [String: Any] = [
+ "name": upload.name,
+ "type": upload.type,
+ "duration": upload.duration,
+ "origin": upload.origin,
+ ]
+ if let width = upload.width, let height = upload.height {
+ meta["width"] = width
+ meta["height"] = height
+ }
+ var body: [String: Any] = ["key": presign.key, "meta": meta]
+ if let posterKey { body["posterKey"] = posterKey }
+ let data = try await send(
+ try request("POST", "/api/cut-cloud/library/complete", body: body, allowCellular: allowCellular)
+ )
+ let asset = try decode(AssetResponse.self, from: data)
+ progress(1)
+ return RemoteAsset(id: asset.id, fileName: asset.fileName)
+ }
+
+ private func presignLibrary(
+ fileName: String,
+ mime: String,
+ bytes: Int64,
+ resume: Bool,
+ allowCellular: Bool
+ ) async throws -> PresignResponse {
+ let data = try await send(
+ try request(
+ "POST",
+ "/api/cut-cloud/library/presign",
+ body: ["fileName": fileName, "mime": mime, "bytes": bytes, "resume": resume],
+ allowCellular: allowCellular
+ )
+ )
+ return try decode(PresignResponse.self, from: data)
+ }
+
+ /// The recording's thumbnail goes up beside the movie so the desktop card
+ /// paints without decoding video. Best-effort: the upload stands without it.
+ private func uploadPoster(_ poster: Data, besides fileName: String, allowCellular: Bool) async throws -> String {
+ let posterName = (fileName as NSString).deletingPathExtension + "-poster.jpg"
+ let presign = try await presignLibrary(
+ fileName: posterName,
+ mime: "image/jpeg",
+ bytes: Int64(poster.count),
+ resume: true,
+ allowCellular: allowCellular
+ )
+ if presign.done != true {
+ guard let url = presign.url.flatMap(URL.init(string:)) else { throw CloudSyncError.transport }
+ try await putData(poster, to: url, mime: "image/jpeg", allowCellular: allowCellular)
+ }
+ return presign.key
+ }
+
+ private func putFile(
+ _ file: URL,
+ to url: URL,
+ mime: String,
+ allowCellular: Bool,
+ progress: @escaping @Sendable (Double) -> Void
+ ) async throws {
+ let response: URLResponse
+ do {
+ (_, response) = try await URLSession.shared.upload(
+ for: putRequest(url, mime: mime, allowCellular: allowCellular),
+ fromFile: file,
+ delegate: UploadProgressDelegate(progress)
+ )
+ } catch {
+ throw CloudSyncError.transport
+ }
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
+ throw CloudSyncError.transport
+ }
+ }
+
+ private func putData(_ data: Data, to url: URL, mime: String, allowCellular: Bool) async throws {
+ let response: URLResponse
+ do {
+ (_, response) = try await URLSession.shared.upload(
+ for: putRequest(url, mime: mime, allowCellular: allowCellular),
+ from: data
+ )
+ } catch {
+ throw CloudSyncError.transport
+ }
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
+ throw CloudSyncError.transport
+ }
+ }
+
+ private func putRequest(_ url: URL, mime: String, allowCellular: Bool) -> URLRequest {
+ var request = URLRequest(url: url)
+ request.httpMethod = "PUT"
+ // The presigned URL is signed over this content type.
+ request.setValue(mime, forHTTPHeaderField: "Content-Type")
+ request.allowsCellularAccess = allowCellular
+ request.allowsExpensiveNetworkAccess = allowCellular
+ return request
+ }
+
+ func deleteLibraryAsset(id: String) async throws {
+ _ = try await send(try request("DELETE", "/api/cut-cloud/library/\(id)"))
+ }
+
+ func importInspirationLink(_ url: URL) async throws {
+ _ = try await send(
+ try request(
+ "POST",
+ "/api/cut-cloud/library/import-url",
+ body: ["url": url.absoluteString, "origin": "inspiration"]
+ )
+ )
+ }
+
+ func fetchUsage() async throws -> StorageUsage {
+ struct UsageResponse: Decodable {
+ var bytes: Int64
+ var quotaBytes: Int64?
+ }
+ let data = try await send(try request("GET", "/api/cut-cloud/usage"))
+ let usage = try decode(UsageResponse.self, from: data)
+ return StorageUsage(bytes: usage.bytes, quotaBytes: usage.quotaBytes)
+ }
+
+ // MARK: Notes
+
+ private struct NoteDTO: Decodable {
+ var id: String
+ var title: String
+ var body: String
+ var colorIndex: Int
+ var updatedAt: Double
+ var deletedAt: Double?
+ var createdAt: Double
+ }
+
+ func fetchNotes() async throws -> [RemoteNote] {
+ struct NotesResponse: Decodable { var notes: [NoteDTO] }
+ let data = try await send(try request("GET", "/api/cut-cloud/notes"))
+ return try decode(NotesResponse.self, from: data).notes.compactMap { dto in
+ guard let id = UUID(uuidString: dto.id) else { return nil }
+ return RemoteNote(
+ id: id,
+ title: dto.title,
+ body: dto.body,
+ colorIndex: dto.colorIndex,
+ updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),
+ deletedAt: dto.deletedAt.map { Date(timeIntervalSince1970: $0 / 1000) },
+ createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)
+ )
+ }
+ }
+
+ func putNote(_ note: RemoteNote) async throws -> RemoteNote {
+ let data = try await send(
+ try request(
+ "PUT",
+ "/api/cut-cloud/notes/\(note.id.uuidString.lowercased())",
+ body: [
+ "title": note.title,
+ "body": note.body,
+ "colorIndex": note.colorIndex,
+ "updatedAt": Int(note.updatedAt.timeIntervalSince1970 * 1000),
+ ]
+ )
+ )
+ let dto = try decode(NoteDTO.self, from: data)
+ return RemoteNote(
+ id: note.id,
+ title: dto.title,
+ body: dto.body,
+ colorIndex: dto.colorIndex,
+ updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),
+ deletedAt: dto.deletedAt.map { Date(timeIntervalSince1970: $0 / 1000) },
+ createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)
+ )
+ }
+
+ func deleteNote(id: UUID) async throws {
+ _ = try await send(try request("DELETE", "/api/cut-cloud/notes/\(id.uuidString.lowercased())"))
+ }
+}
+
+// MARK: - Projects down-sync
+
+extension CutCloudClient: CloudProjectsServicing {
+ private struct ProjectDTO: Decodable {
+ var id: String
+ var name: String
+ var duration: Double
+ var updatedAt: Double
+ var hasPreview: Bool?
+ var previewFile: String?
+ var previewIsImage: Bool?
+ var previewStart: Double?
+ }
+
+ func fetchProjects() async throws -> [RemoteProject] {
+ let data = try await send(try request("GET", "/api/cut-cloud/projects"))
+ return try decode([ProjectDTO].self, from: data).map { dto in
+ RemoteProject(
+ id: dto.id,
+ name: dto.name,
+ duration: dto.duration,
+ updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),
+ hasPreview: dto.hasPreview ?? false,
+ previewFile: dto.previewFile,
+ previewIsImage: dto.previewIsImage ?? false,
+ previewStart: dto.previewStart ?? 0
+ )
+ }
+ }
+
+ func fetchExports(projectId: String) async throws -> [RemoteExport] {
+ struct ExportDTO: Decodable {
+ var file: String
+ var mtime: Double
+ }
+ let data = try await send(try request("GET", "/api/cut-cloud/projects/\(projectId)/exports"))
+ return try decode([ExportDTO].self, from: data).map {
+ RemoteExport(file: $0.file, modifiedAt: Date(timeIntervalSince1970: $0.mtime / 1000))
+ }
+ }
+
+ func streamURL(project: RemoteProject, export: RemoteExport?) async throws -> URL {
+ if let export {
+ return try await resolveRedirect("/api/cut-cloud/projects/\(project.id)/exports/\(export.file)")
+ }
+ guard project.hasPreview else { throw CloudSyncError.transport }
+ return try await resolveRedirect("/api/cut-cloud/projects/\(project.id)/preview")
+ }
+
+ func thumbnailFile(for project: RemoteProject) async -> URL? {
+ let directory = FileManager.default
+ .urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ .appending(path: "ProjectThumbs")
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let stamp = Int(project.updatedAt.timeIntervalSince1970 * 1000)
+ let file = directory.appending(path: "\(project.id)-\(stamp).jpg")
+ if FileManager.default.fileExists(atPath: file.path()) { return file }
+ guard let image = await thumbnailImage(for: project),
+ let data = image.jpegData(compressionQuality: 0.8) else { return nil }
+ // Versions of this project from before the edit leave with the refresh.
+ let stale = (try? FileManager.default.contentsOfDirectory(atPath: directory.path()))?
+ .filter { $0.hasPrefix("\(project.id)-") } ?? []
+ for name in stale {
+ try? FileManager.default.removeItem(at: directory.appending(path: name))
+ }
+ try? data.write(to: file, options: .atomic)
+ return file
+ }
+
+ /// Only a poster rides the network: a still poster file as its own bytes,
+ /// or one decoded frame of the composited preview / poster video.
+ private func thumbnailImage(for project: RemoteProject) async -> UIImage? {
+ if project.previewIsImage, let file = project.previewFile {
+ guard let url = try? await resolveRedirect("/api/cut-cloud/projects/\(project.id)/media/\(file)"),
+ let (data, _) = try? await URLSession.shared.data(from: url) else { return nil }
+ return UIImage(data: data)
+ }
+ let source: (path: String, at: TimeInterval)? = if project.hasPreview {
+ ("/api/cut-cloud/projects/\(project.id)/preview", 0)
+ } else if let file = project.previewFile {
+ ("/api/cut-cloud/projects/\(project.id)/media/\(file)", project.previewStart)
+ } else {
+ nil
+ }
+ guard let source, let url = try? await resolveRedirect(source.path) else { return nil }
+ let generator = AVAssetImageGenerator(asset: AVURLAsset(url: url))
+ generator.appliesPreferredTrackTransform = true
+ generator.maximumSize = CGSize(width: 720, height: 720)
+ generator.requestedTimeToleranceAfter = CMTime(seconds: 1, preferredTimescale: 600)
+ let time = CMTime(seconds: source.at, preferredTimescale: 600)
+ guard let frame = try? await generator.image(at: time).image else { return nil }
+ return UIImage(cgImage: frame)
+ }
+}
+
+// MARK: - Recording payloads
+
+extension CutCloudClient {
+ /// Everything an upload needs, read off the finished recording: bytes on
+ /// disk, probed dimensions, and the stored thumbnail as the poster.
+ static func uploadPayload(for recording: Recording, media: MediaModel) async -> LibraryUpload? {
+ let fileURL = media.movieURL(for: recording)
+ let size = ((try? FileManager.default.attributesOfItem(atPath: fileURL.path()))?[.size] as? NSNumber)?
+ .int64Value ?? 0
+ guard size > 0 else { return nil }
+ var width: Int?
+ var height: Int?
+ let asset = AVURLAsset(url: fileURL)
+ if let track = try? await asset.loadTracks(withMediaType: .video).first,
+ let (naturalSize, transform) = try? await track.load(.naturalSize, .preferredTransform) {
+ let rect = CGRect(origin: .zero, size: naturalSize).applying(transform)
+ width = Int(abs(rect.width).rounded())
+ height = Int(abs(rect.height).rounded())
+ }
+ let poster = media.thumbnailURL(for: recording).flatMap { try? Data(contentsOf: $0) }
+ return LibraryUpload(
+ fileURL: fileURL,
+ fileName: recording.fileName,
+ mime: "video/quicktime",
+ bytes: size,
+ name: "Recording \(recording.createdAt.formatted(date: .abbreviated, time: .shortened))",
+ type: "video",
+ duration: recording.duration,
+ width: width,
+ height: height,
+ origin: "camera",
+ poster: poster
+ )
+ }
+}
+
+// MARK: - Session delegates
+
+/// Reports PUT progress off the session's queue back to the caller.
+private nonisolated final class UploadProgressDelegate: NSObject, URLSessionTaskDelegate {
+ private let onProgress: @Sendable (Double) -> Void
+
+ init(_ onProgress: @escaping @Sendable (Double) -> Void) {
+ self.onProgress = onProgress
+ }
+
+ func urlSession(
+ _ session: URLSession,
+ task: URLSessionTask,
+ didSendBodyData bytesSent: Int64,
+ totalBytesSent: Int64,
+ totalBytesExpectedToSend: Int64
+ ) {
+ guard totalBytesExpectedToSend > 0 else { return }
+ onProgress(Double(totalBytesSent) / Double(totalBytesExpectedToSend))
+ }
+}
+
+/// Stops the API's 302 so the Location header can be read.
+private nonisolated final class RedirectCatcher: NSObject, URLSessionTaskDelegate {
+ func urlSession(
+ _ session: URLSession,
+ task: URLSessionTask,
+ willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest,
+ completionHandler: @escaping (URLRequest?) -> Void
+ ) {
+ completionHandler(nil)
+ }
+}
diff --git a/apps/ios/Donkey/DonkeyApp.swift b/apps/ios/Donkey/DonkeyApp.swift
index 9ba96922..887d2ed4 100644
--- a/apps/ios/Donkey/DonkeyApp.swift
+++ b/apps/ios/Donkey/DonkeyApp.swift
@@ -37,17 +37,41 @@ final class AppWiring {
let projects: ProjectsModel
let auth: AuthModel
let cameraController: CameraController
+ let sync: SyncEngine
+ private let networkMonitor: NetworkMonitor
init() {
// A store that cannot open is a programmer error worth crashing on.
let store = try! DonkeyStore()
- app = AppModel()
- ideas = IdeasModel(store: store)
+ let cloud = CutCloudClient()
+ let app = AppModel()
+ let ideas = IdeasModel(store: store)
+ let media = MediaModel(store: store)
+ let auth = AuthModel(service: AuthController())
+ let sync = SyncEngine(
+ journal: store,
+ service: cloud,
+ cellularAllowed: { app.syncOverCellular },
+ signedIn: { auth.isSignedIn },
+ uploadFor: { recording in
+ await CutCloudClient.uploadPayload(for: recording, media: media)
+ }
+ )
+ sync.media = media
+ sync.ideas = ideas
+ media.sync = sync
+ ideas.onLocalChange = { sync.kick() }
+ app.onSyncPolicyChange = { sync.kick() }
+
+ self.app = app
+ self.ideas = ideas
+ self.media = media
+ self.auth = auth
+ self.sync = sync
camera = CameraModel()
- media = MediaModel(store: store)
- projects = ProjectsModel()
- auth = AuthModel(service: AuthController())
+ projects = ProjectsModel(service: cloud)
cameraController = CameraController()
+ networkMonitor = NetworkMonitor { sync.network = $0 }
cameraController.model = camera
camera.controller = cameraController
diff --git a/apps/ios/Donkey/Support/NetworkMonitor.swift b/apps/ios/Donkey/Support/NetworkMonitor.swift
new file mode 100644
index 00000000..35bf4a76
--- /dev/null
+++ b/apps/ios/Donkey/Support/NetworkMonitor.swift
@@ -0,0 +1,28 @@
+import DonkeyKitModels
+import Foundation
+import Network
+
+/// Feeds the sync engine the current network path so policy can decide what
+/// moves. Cellular and other expensive paths (personal hotspots) both count
+/// as cellular: they spend metered data.
+final class NetworkMonitor {
+ private let monitor = NWPathMonitor()
+
+ init(onChange: @escaping @Sendable @MainActor (NetworkPath) -> Void) {
+ monitor.pathUpdateHandler = { path in
+ let mapped: NetworkPath = if path.status != .satisfied {
+ .offline
+ } else if path.usesInterfaceType(.cellular) || path.isExpensive {
+ .cellular
+ } else {
+ .wifi
+ }
+ Task { @MainActor in onChange(mapped) }
+ }
+ monitor.start(queue: DispatchQueue(label: "network-monitor"))
+ }
+
+ deinit {
+ monitor.cancel()
+ }
+}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift
index fd8a93a7..4a124d7a 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift
@@ -16,16 +16,32 @@ public final class AppModel {
didSet { defaults.set(appearance.rawValue, forKey: Self.appearanceKey) }
}
+ /// Media syncs over cellular data too. Off by default: large files wait
+ /// for Wi-Fi until the user opts in. Small traffic (notes, links) always
+ /// moves.
+ public var syncOverCellular: Bool {
+ didSet {
+ defaults.set(syncOverCellular, forKey: Self.cellularKey)
+ if syncOverCellular != oldValue { onSyncPolicyChange?() }
+ }
+ }
+
+ /// Fires when the cellular choice flips so queued uploads re-evaluate.
+ /// Wired by the app entry.
+ public var onSyncPolicyChange: (() -> Void)?
+
/// A transient confirmation message ("Note saved"), cleared by the UI.
public var toast: String?
private let defaults: UserDefaults
private static let appearanceKey = "appearancePreference"
+ private static let cellularKey = "syncOverCellular"
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
appearance = defaults.string(forKey: Self.appearanceKey)
.flatMap(AppearancePreference.init(rawValue:)) ?? .system
+ syncOverCellular = defaults.bool(forKey: Self.cellularKey)
}
public func show(toast message: String) {
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swift
index 47ddf11c..ac92d995 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swift
@@ -33,13 +33,33 @@ public final class CameraModel {
public private(set) var isTorchOn = false
public internal(set) var hasTorch = false
public internal(set) var recordingStartedAt: Date?
- public var teleprompter = TeleprompterState()
+ /// Teleprompter settings persist across sessions: set the pace once and
+ /// every later recording starts with it.
+ public var teleprompter = TeleprompterState() {
+ didSet {
+ if teleprompter.settings != oldValue.settings { persistTeleprompterSettings() }
+ }
+ }
public var isRecording: Bool { recordingStartedAt != nil }
public var controller: (any CameraControlling)?
- public init() {}
+ private let defaults: UserDefaults
+ private static let teleprompterKey = "teleprompterSettings"
+
+ public init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ if let data = defaults.data(forKey: Self.teleprompterKey),
+ let settings = try? JSONDecoder().decode(TeleprompterSettings.self, from: data) {
+ teleprompter.settings = settings
+ }
+ }
+
+ private func persistTeleprompterSettings() {
+ guard let data = try? JSONEncoder().encode(teleprompter.settings) else { return }
+ defaults.set(data, forKey: Self.teleprompterKey)
+ }
// MARK: Intents
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
new file mode 100644
index 00000000..5152b914
--- /dev/null
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
@@ -0,0 +1,225 @@
+import Foundation
+
+// The cloud as the phone sees it: plain records for the Donkey Cut hosted API
+// (/api/cut-cloud/*), the transport protocols the app target implements with
+// URLSession, and the pure policy that decides what may move on which network.
+
+nonisolated public struct StorageUsage: Equatable, Sendable {
+ public var bytes: Int64
+ /// nil = unlimited.
+ public var quotaBytes: Int64?
+
+ public init(bytes: Int64, quotaBytes: Int64?) {
+ self.bytes = bytes
+ self.quotaBytes = quotaBytes
+ }
+
+ public var isFull: Bool {
+ guard let quotaBytes else { return false }
+ return bytes >= quotaBytes
+ }
+}
+
+/// One library upload: a recording off the camera or an inspiration item.
+nonisolated public struct LibraryUpload: Sendable {
+ public var fileURL: URL
+ public var fileName: String
+ public var mime: String
+ public var bytes: Int64
+ public var name: String
+ public var type: String // "video" | "image"
+ public var duration: TimeInterval
+ public var width: Int?
+ public var height: Int?
+ public var origin: String // "camera" | "inspiration"
+ /// JPEG poster stored beside the media so the desktop card paints at once.
+ public var poster: Data?
+ /// True when this upload was claimed before (the journal holds the name):
+ /// the server re-mints the same claim instead of minting a twin.
+ public var resume: Bool
+
+ public init(
+ fileURL: URL,
+ fileName: String,
+ mime: String,
+ bytes: Int64,
+ name: String,
+ type: String,
+ duration: TimeInterval,
+ width: Int? = nil,
+ height: Int? = nil,
+ origin: String,
+ poster: Data? = nil,
+ resume: Bool = false
+ ) {
+ self.fileURL = fileURL
+ self.fileName = fileName
+ self.mime = mime
+ self.bytes = bytes
+ self.name = name
+ self.type = type
+ self.duration = duration
+ self.width = width
+ self.height = height
+ self.origin = origin
+ self.poster = poster
+ self.resume = resume
+ }
+}
+
+nonisolated public struct RemoteAsset: Equatable, Sendable {
+ public var id: String
+ public var fileName: String
+
+ public init(id: String, fileName: String) {
+ self.id = id
+ self.fileName = fileName
+ }
+}
+
+/// A note as the cloud stores it. `updatedAt` is the last-writer-wins clock;
+/// a tombstone carries `deletedAt`.
+nonisolated public struct RemoteNote: Equatable, Sendable {
+ public var id: UUID
+ public var title: String
+ public var body: String
+ public var colorIndex: Int
+ public var updatedAt: Date
+ public var deletedAt: Date?
+ public var createdAt: Date
+
+ public init(
+ id: UUID,
+ title: String,
+ body: String,
+ colorIndex: Int,
+ updatedAt: Date,
+ deletedAt: Date? = nil,
+ createdAt: Date = .now
+ ) {
+ self.id = id
+ self.title = title
+ self.body = body
+ self.colorIndex = colorIndex
+ self.updatedAt = updatedAt
+ self.deletedAt = deletedAt
+ self.createdAt = createdAt
+ }
+}
+
+nonisolated public enum CloudSyncError: Error, Equatable {
+ /// The account is out of cloud storage: uploads pause, the Library shows
+ /// its banner, and nothing retries until space frees up.
+ case storageFull
+ /// The session is gone; syncing waits for the next sign-in.
+ case unauthorized
+ /// Anything transient: network, 5xx. The item stays queued.
+ case transport
+}
+
+/// What the app target's CutCloudClient does for the sync engine.
+public protocol CloudSyncServicing: AnyObject {
+ /// Presign → PUT the bytes to R2 → complete. Reports rough progress in
+ /// 0...1. `allowCellular` is stamped on the requests so a Wi-Fi upload
+ /// never silently continues over cell when the path changes mid-transfer.
+ func uploadLibraryMedia(
+ _ upload: LibraryUpload,
+ allowCellular: Bool,
+ progress: @escaping @Sendable (Double) -> Void
+ ) async throws -> RemoteAsset
+ func deleteLibraryAsset(id: String) async throws
+ /// Queue a cloud-side import of an inspiration link (the render worker
+ /// fetches the media into the Inspiration folder).
+ func importInspirationLink(_ url: URL) async throws
+ func fetchUsage() async throws -> StorageUsage
+ func fetchNotes() async throws -> [RemoteNote]
+ /// Returns the winning version — this write, or a newer one already there.
+ func putNote(_ note: RemoteNote) async throws -> RemoteNote
+ func deleteNote(id: UUID) async throws
+}
+
+// MARK: - Projects (down-sync)
+
+/// A cloud project summary reduced to what the phone shows.
+nonisolated public struct RemoteProject: Equatable, Sendable, Identifiable {
+ public var id: String
+ public var name: String
+ public var duration: TimeInterval
+ public var updatedAt: Date
+ /// The composited hover-proxy render exists; it is the stream of record
+ /// when no export does.
+ public var hasPreview: Bool
+ public var previewFile: String?
+ public var previewIsImage: Bool
+ public var previewStart: TimeInterval
+
+ public init(
+ id: String,
+ name: String,
+ duration: TimeInterval,
+ updatedAt: Date,
+ hasPreview: Bool,
+ previewFile: String? = nil,
+ previewIsImage: Bool = false,
+ previewStart: TimeInterval = 0
+ ) {
+ self.id = id
+ self.name = name
+ self.duration = duration
+ self.updatedAt = updatedAt
+ self.hasPreview = hasPreview
+ self.previewFile = previewFile
+ self.previewIsImage = previewIsImage
+ self.previewStart = previewStart
+ }
+}
+
+nonisolated public struct RemoteExport: Equatable, Sendable {
+ public var file: String
+ public var modifiedAt: Date
+
+ public init(file: String, modifiedAt: Date) {
+ self.file = file
+ self.modifiedAt = modifiedAt
+ }
+}
+
+public protocol CloudProjectsServicing: AnyObject, Sendable {
+ func fetchProjects() async throws -> [RemoteProject]
+ func fetchExports(projectId: String) async throws -> [RemoteExport]
+ /// CDN URL behind the API's redirect for the latest render of a project:
+ /// its newest export, or the composited preview proxy.
+ func streamURL(project: RemoteProject, export: RemoteExport?) async throws -> URL
+ /// A local poster image for the project card, cached on disk keyed by the
+ /// project's updatedAt so only thumbnails ride the network.
+ func thumbnailFile(for project: RemoteProject) async -> URL?
+}
+
+// MARK: - Network policy
+
+nonisolated public enum NetworkPath: Equatable, Sendable {
+ case wifi
+ case cellular
+ case offline
+}
+
+/// How big a transfer is, as policy sees it. Small-class traffic (notes, link
+/// imports, JSON) moves on any connection; media waits for Wi-Fi unless the
+/// user allows cellular.
+nonisolated public enum TransferClass: Equatable, Sendable {
+ case small
+ case media
+}
+
+/// The one rule that spends the user's data.
+nonisolated public func transferAllowed(
+ _ kind: TransferClass,
+ on path: NetworkPath,
+ cellularAllowed: Bool
+) -> Bool {
+ switch path {
+ case .offline: false
+ case .wifi: true
+ case .cellular: kind == .small || cellularAllowed
+ }
+}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
index 57f978f9..30b71c86 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
@@ -3,7 +3,9 @@ import SwiftData
// Persistence stays at the edge: these SwiftData records never leave this
// file, and the rest of the app talks to the plain structs the repository
-// methods return.
+// methods return. The sync journal lives here too — which rows are synced,
+// which notes are dirty, and the tombstones deletes leave — so an upload
+// interrupted by an app kill resumes from disk on the next launch.
@Model
final class NoteRecord {
@@ -12,17 +14,32 @@ final class NoteRecord {
var body: String
var colorIndex: Int
var createdAt: Date
+ /// Last edit, the sync's last-writer-wins clock. Older rows carry nil and
+ /// read as their creation time.
+ var updatedAt: Date?
+ /// Locally edited and not yet pushed. Older rows carry nil (dirty), so a
+ /// note from before sync existed gets pushed once.
+ var dirty: Bool?
- init(_ note: Note) {
+ init(_ note: Note, dirty: Bool) {
id = note.id
title = note.title
body = note.body
colorIndex = note.color.rawValue
createdAt = note.createdAt
+ updatedAt = note.updatedAt
+ self.dirty = dirty
}
var note: Note {
- Note(id: id, title: title, body: body, color: NoteColor(rawValue: colorIndex) ?? .butter, createdAt: createdAt)
+ Note(
+ id: id,
+ title: title,
+ body: body,
+ color: NoteColor(rawValue: colorIndex) ?? .butter,
+ createdAt: createdAt,
+ updatedAt: updatedAt ?? createdAt
+ )
}
}
@@ -33,6 +50,10 @@ final class InspirationRecord {
var mediaFileName: String?
var isVideo: Bool
var createdAt: Date
+ /// Cloud library asset id once a media item has synced.
+ var remoteAssetId: String?
+ /// When a link's cloud-side import was queued.
+ var linkSyncedAt: Date?
init(id: UUID, linkURL: String?, mediaFileName: String?, isVideo: Bool, createdAt: Date) {
self.id = id
@@ -60,6 +81,11 @@ final class RecordingRecord {
var thumbnailFileName: String?
var duration: TimeInterval
var createdAt: Date
+ /// Cloud library asset id once the clip has synced.
+ var remoteAssetId: String?
+ /// The upload name the cloud claimed at presign time. An interrupted
+ /// upload resumes under it instead of claiming a twin.
+ var claimedFileName: String?
init(_ recording: Recording) {
id = recording.id
@@ -74,9 +100,30 @@ final class RecordingRecord {
}
}
-/// One store behind both repository seams: SwiftData for metadata, plain
+/// A delete waiting to replay against the cloud.
+@Model
+final class TombstoneRecord {
+ @Attribute(.unique) var id: UUID
+ var kind: String
+ var remoteId: String
+ var stamp: Date
+
+ init(kind: String, remoteId: String, stamp: Date) {
+ id = UUID()
+ self.kind = kind
+ self.remoteId = remoteId
+ self.stamp = stamp
+ }
+
+ var tombstone: SyncTombstone? {
+ guard let kind = SyncTombstone.Kind(rawValue: kind) else { return nil }
+ return SyncTombstone(id: id, kind: kind, remoteId: remoteId, stamp: stamp)
+ }
+}
+
+/// One store behind the repository seams: SwiftData for metadata, plain
/// files under Application Support for movie/media bytes.
-public final class DonkeyStore: IdeasStoring, RecordingStoring {
+public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoring {
private let container: ModelContainer
private let context: ModelContext
private let mediaDirectory: URL
@@ -94,7 +141,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring {
for directory in [mediaDirectory, recordingsDirectory] {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
- let schema = Schema([NoteRecord.self, InspirationRecord.self, RecordingRecord.self])
+ let schema = Schema([NoteRecord.self, InspirationRecord.self, RecordingRecord.self, TombstoneRecord.self])
let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: inMemory)
container = try ModelContainer(for: schema, configurations: [configuration])
context = ModelContext(container)
@@ -114,14 +161,17 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring {
existing.title = note.title
existing.body = note.body
existing.colorIndex = note.color.rawValue
+ existing.updatedAt = note.updatedAt
+ existing.dirty = true
} else {
- context.insert(NoteRecord(note))
+ context.insert(NoteRecord(note, dirty: true))
}
try context.save()
}
public func deleteNote(id: UUID) throws {
try context.delete(model: NoteRecord.self, where: #Predicate { $0.id == id })
+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.note.rawValue, remoteId: id.uuidString, stamp: .now))
try context.save()
}
@@ -153,6 +203,9 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring {
if let fileName = record.mediaFileName {
try? FileManager.default.removeItem(at: mediaDirectory.appending(path: fileName))
}
+ if let remote = record.remoteAssetId {
+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.libraryAsset.rawValue, remoteId: remote, stamp: .now))
+ }
context.delete(record)
try context.save()
}
@@ -191,7 +244,13 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring {
try? FileManager.default.removeItem(at: thumbnailURL)
}
let id = recording.id
- try context.delete(model: RecordingRecord.self, where: #Predicate { $0.id == id })
+ let descriptor = FetchDescriptor<RecordingRecord>(predicate: #Predicate { $0.id == id })
+ if let record = try context.fetch(descriptor).first {
+ if let remote = record.remoteAssetId {
+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.libraryAsset.rawValue, remoteId: remote, stamp: .now))
+ }
+ context.delete(record)
+ }
try context.save()
}
@@ -202,4 +261,99 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring {
public func thumbnailURL(for recording: Recording) -> URL? {
recording.thumbnailFileName.map { recordingsDirectory.appending(path: $0) }
}
+
+ // MARK: SyncJournalStoring
+
+ public func dirtyNotes() throws -> [Note] {
+ let descriptor = FetchDescriptor<NoteRecord>(sortBy: [SortDescriptor(\.createdAt)])
+ return try context.fetch(descriptor).filter { $0.dirty ?? true }.map(\.note)
+ }
+
+ public func applyRemoteNote(_ note: Note) throws {
+ let id = note.id
+ let descriptor = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.id == id })
+ if let existing = try context.fetch(descriptor).first {
+ guard existing.dirty != true else { return }
+ existing.title = note.title
+ existing.body = note.body
+ existing.colorIndex = note.color.rawValue
+ existing.updatedAt = note.updatedAt
+ existing.dirty = false
+ } else {
+ context.insert(NoteRecord(note, dirty: false))
+ }
+ try context.save()
+ }
+
+ public func clearNoteDirty(id: UUID, ifUpdatedAt stamp: Date) throws {
+ let descriptor = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else { return }
+ guard (record.updatedAt ?? record.createdAt) == stamp else { return }
+ record.dirty = false
+ try context.save()
+ }
+
+ public func removeNoteFromCloudDelete(id: UUID) throws {
+ try context.delete(model: NoteRecord.self, where: #Predicate { $0.id == id })
+ try context.save()
+ }
+
+ public func recordingRemote(_ id: UUID) throws -> (assetId: String?, claimedFileName: String?) {
+ let descriptor = FetchDescriptor<RecordingRecord>(predicate: #Predicate { $0.id == id })
+ let record = try context.fetch(descriptor).first
+ return (record?.remoteAssetId, record?.claimedFileName)
+ }
+
+ @discardableResult
+ public func setRecordingRemote(_ id: UUID, assetId: String?, claimedFileName: String?) throws -> Bool {
+ let descriptor = FetchDescriptor<RecordingRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else {
+ // The recording was deleted while its upload was in flight, so
+ // the delete had no asset id to tombstone. The finished upload
+ // reports one here; tombstone it so the cloud copy goes too.
+ if let assetId {
+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.libraryAsset.rawValue, remoteId: assetId, stamp: .now))
+ try context.save()
+ }
+ return false
+ }
+ record.remoteAssetId = assetId
+ record.claimedFileName = claimedFileName
+ try context.save()
+ return true
+ }
+
+ public func inspirationRemoteAssetId(_ id: UUID) throws -> String? {
+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
+ return try context.fetch(descriptor).first?.remoteAssetId
+ }
+
+ public func isInspirationLinkSynced(_ id: UUID) throws -> Bool {
+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
+ return try context.fetch(descriptor).first?.linkSyncedAt != nil
+ }
+
+ public func markInspirationMediaSynced(_ id: UUID, remoteAssetId: String) throws {
+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else { return }
+ record.remoteAssetId = remoteAssetId
+ try context.save()
+ }
+
+ public func markInspirationLinkSynced(_ id: UUID) throws {
+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else { return }
+ record.linkSyncedAt = .now
+ try context.save()
+ }
+
+ public func tombstones() throws -> [SyncTombstone] {
+ let descriptor = FetchDescriptor<TombstoneRecord>(sortBy: [SortDescriptor(\.stamp)])
+ return try context.fetch(descriptor).compactMap(\.tombstone)
+ }
+
+ public func removeTombstone(id: UUID) throws {
+ try context.delete(model: TombstoneRecord.self, where: #Predicate { $0.id == id })
+ try context.save()
+ }
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift
index 825119e1..edf6bc40 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift
@@ -36,13 +36,24 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {
public var body: String
public var color: NoteColor
public var createdAt: Date
-
- public init(id: UUID = UUID(), title: String, body: String, color: NoteColor, createdAt: Date = .now) {
+ /// Last edit, wherever it happened. The sync's last-writer-wins clock:
+ /// the newer stamp survives when the phone and the desktop both wrote.
+ public var updatedAt: Date
+
+ public init(
+ id: UUID = UUID(),
+ title: String,
+ body: String,
+ color: NoteColor,
+ createdAt: Date = .now,
+ updatedAt: Date = .now
+ ) {
self.id = id
self.title = title
self.body = body
self.color = color
self.createdAt = createdAt
+ self.updatedAt = updatedAt
}
/// The text a teleprompter reads for this note.
@@ -103,6 +114,10 @@ public final class IdeasModel {
/// The note open in the editor; nil when the editor is closed.
public var draft: NoteDraft?
+ /// Fires after any local edit so the sync engine pushes it. Wired by the
+ /// app entry; nil in tests.
+ public var onLocalChange: (() -> Void)?
+
private let store: any IdeasStoring
public init(store: any IdeasStoring) {
@@ -111,6 +126,12 @@ public final class IdeasModel {
inspiration = (try? store.loadInspiration()) ?? []
}
+ /// Re-read what the store holds — how a cloud merge lands on screen.
+ public func reloadFromStore() {
+ notes = (try? store.loadNotes()) ?? []
+ inspiration = (try? store.loadInspiration()) ?? []
+ }
+
nonisolated public struct NoteDraft: Identifiable, Equatable {
public var id: UUID
public var title: String
@@ -150,7 +171,8 @@ public final class IdeasModel {
title: title.isEmpty ? "Untitled" : title,
body: body,
color: draft.color,
- createdAt: existing?.createdAt ?? .now
+ createdAt: existing?.createdAt ?? .now,
+ updatedAt: .now
)
try? store.upsert(note)
if let index = notes.firstIndex(where: { $0.id == note.id }) {
@@ -159,6 +181,7 @@ public final class IdeasModel {
notes.insert(note, at: 0)
}
self.draft = nil
+ onLocalChange?()
return note
}
@@ -167,6 +190,7 @@ public final class IdeasModel {
public func deleteNote(id: UUID) {
try? store.deleteNote(id: id)
notes.removeAll { $0.id == id }
+ onLocalChange?()
}
@discardableResult
@@ -174,17 +198,20 @@ public final class IdeasModel {
guard let url = normalizedInspirationURL(urlText),
let item = try? store.addLink(url) else { return false }
inspiration.insert(item, at: 0)
+ onLocalChange?()
return true
}
public func addInspiration(mediaData: Data, isVideo: Bool) {
guard let item = try? store.addMedia(data: mediaData, isVideo: isVideo) else { return }
inspiration.insert(item, at: 0)
+ onLocalChange?()
}
public func deleteInspiration(id: UUID) {
try? store.deleteInspiration(id: id)
inspiration.removeAll { $0.id == id }
+ onLocalChange?()
}
public func mediaURL(fileName: String) -> URL { store.mediaURL(fileName: fileName) }
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift
index e8a62782..098469bd 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift
@@ -16,9 +16,7 @@ nonisolated public struct Recording: Identifiable, Equatable, Sendable {
}
}
-/// Where a clip's bytes live relative to the cloud. Upload is simulated
-/// until the cloud clip endpoint exists; the states and badge UI are the
-/// supported shape.
+/// Where a clip's bytes live relative to the cloud.
nonisolated public enum RecordingSyncState: Equatable, Sendable {
case onDevice
case uploading(percent: Int)
@@ -37,7 +35,10 @@ public protocol RecordingStoring: AnyObject {
@Observable
public final class MediaModel {
public private(set) var recordings: [Recording] = []
- private var syncStates: [UUID: RecordingSyncState] = [:]
+
+ /// The engine that carries recordings to the cloud. Wired by the app
+ /// entry; nil in tests, where everything reads as on-device.
+ public var sync: SyncEngine?
private let store: any RecordingStoring
@@ -47,33 +48,24 @@ public final class MediaModel {
}
public func syncState(for recording: Recording) -> RecordingSyncState {
- syncStates[recording.id] ?? .onDevice
+ sync?.state(for: recording) ?? .onDevice
}
+ /// The cloud is out of room; the Library banner reads this.
+ public var storageFull: Bool { sync?.storageFull ?? false }
+
public func ingest(movieAt url: URL, duration: TimeInterval, thumbnail: Data?) {
guard let recording = try? store.ingest(movieAt: url, duration: duration, thumbnail: thumbnail) else { return }
recordings.insert(recording, at: 0)
- beginUpload(of: recording)
+ sync?.recordingAdded(recording)
}
+ /// Deletes the clip everywhere: the local file now, and the cloud copy
+ /// through the tombstone the store records.
public func delete(_ recording: Recording) {
try? store.deleteRecording(recording)
recordings.removeAll { $0.id == recording.id }
- syncStates[recording.id] = nil
- }
-
- private func beginUpload(of recording: Recording) {
- syncStates[recording.id] = .uploading(percent: 0)
- Task {
- var percent = 0.0
- while percent < 100 {
- try? await Task.sleep(for: .seconds(0.6))
- guard recordings.contains(where: { $0.id == recording.id }) else { return }
- percent = min(percent + .random(in: 6 ... 22), 100)
- syncStates[recording.id] = .uploading(percent: Int(percent))
- }
- syncStates[recording.id] = .synced
- }
+ sync?.kick()
}
public func movieURL(for recording: Recording) -> URL { store.movieURL(for: recording) }
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift
index ecceb4e9..a79ad9b0 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift
@@ -2,34 +2,94 @@ import Foundation
nonisolated public enum ProjectExport: Equatable, Sendable {
case none
- case exporting(percent: Int)
case ready(renderedOn: String)
-
- public var isExporting: Bool {
- if case .exporting = self { true } else { false }
- }
}
+/// A cloud project as the phone shows it: name, duration, a cached thumbnail
+/// file, and which render a tap streams. Only thumbnails sync down — the
+/// video stays in the cloud and streams on demand.
nonisolated public struct Project: Identifiable, Equatable, Sendable {
- public var id: UUID
+ public var id: String
public var name: String
public var duration: TimeInterval
public var export: ProjectExport
+ public var thumbnail: URL?
- public init(id: UUID = UUID(), name: String, duration: TimeInterval, export: ProjectExport) {
+ public init(id: String, name: String, duration: TimeInterval, export: ProjectExport, thumbnail: URL? = nil) {
self.id = id
self.name = name
self.duration = duration
self.export = export
+ self.thumbnail = thumbnail
}
}
@Observable
public final class ProjectsModel {
- public private(set) var projects: [Project]
+ public private(set) var projects: [Project] = []
+ public private(set) var isLoading = false
+
+ private var summaries: [String: RemoteProject] = [:]
+ private var latestExports: [String: RemoteExport] = [:]
+ private let service: (any CloudProjectsServicing)?
+
+ public init(service: (any CloudProjectsServicing)? = nil) {
+ self.service = service
+ }
+
+ /// Pull the listing and per-project latest exports, then fill thumbnails
+ /// as they cache — cards paint with names first, posters as they land.
+ public func refresh() async {
+ guard let service, !isLoading else { return }
+ isLoading = true
+ defer { isLoading = false }
+ guard let remote = try? await service.fetchProjects() else { return }
+ summaries = Dictionary(uniqueKeysWithValues: remote.map { ($0.id, $0) })
+ projects = remote.map { project(for: $0, latest: nil, thumbnail: nil) }
+ await withTaskGroup(of: (String, RemoteExport?).self) { group in
+ for summary in remote {
+ group.addTask { (summary.id, (try? await service.fetchExports(projectId: summary.id))?.first) }
+ }
+ for await (id, latest) in group {
+ latestExports[id] = latest
+ guard let summary = summaries[id],
+ let index = projects.firstIndex(where: { $0.id == id }) else { continue }
+ projects[index] = project(for: summary, latest: latest, thumbnail: projects[index].thumbnail)
+ }
+ }
+ await withTaskGroup(of: (String, URL?).self) { group in
+ for summary in remote {
+ group.addTask { (summary.id, await service.thumbnailFile(for: summary)) }
+ }
+ for await (id, file) in group {
+ guard let file, let index = projects.firstIndex(where: { $0.id == id }) else { continue }
+ projects[index].thumbnail = file
+ }
+ }
+ }
+
+ /// The URL a tap streams: the newest export, or the composited preview
+ /// proxy. Resolved at tap time because the CDN links expire.
+ public func streamURL(for project: Project) async -> URL? {
+ guard let service, let summary = summaries[project.id] else { return nil }
+ return try? await service.streamURL(project: summary, export: latestExports[project.id])
+ }
- /// Empty until projects stream from the cloud projects API.
- public init() {
- projects = []
+ private func project(for summary: RemoteProject, latest: RemoteExport?, thumbnail: URL?) -> Project {
+ let export: ProjectExport =
+ if let latest {
+ .ready(renderedOn: latest.modifiedAt.formatted(date: .abbreviated, time: .omitted))
+ } else if summary.hasPreview {
+ .ready(renderedOn: summary.updatedAt.formatted(date: .abbreviated, time: .omitted))
+ } else {
+ .none
+ }
+ return Project(
+ id: summary.id,
+ name: summary.name,
+ duration: summary.duration,
+ export: export,
+ thumbnail: thumbnail
+ )
}
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
new file mode 100644
index 00000000..ad581ae1
--- /dev/null
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
@@ -0,0 +1,391 @@
+import Foundation
+
+// The phone's side of sync. One engine owns every queue — recordings up,
+// inspiration up, notes both ways, deletes replayed — against a journal the
+// store persists, so nothing depends on the app staying open: whatever was
+// mid-flight when the app died is picked up from the journal on the next
+// kick. Every byte moves at most once; the policy in CloudSync.swift decides
+// what may move on which network.
+
+nonisolated public struct SyncTombstone: Equatable, Sendable, Identifiable {
+ nonisolated public enum Kind: String, Sendable {
+ /// A synced note deleted here; the cloud keeps a tombstone row.
+ case note
+ /// A synced recording or inspiration item deleted here; the cloud
+ /// asset goes with it.
+ case libraryAsset
+ }
+
+ public var id: UUID
+ public var kind: Kind
+ /// The cloud id: the note's UUID string, or the library asset id.
+ public var remoteId: String
+ public var stamp: Date
+
+ public init(id: UUID = UUID(), kind: Kind, remoteId: String, stamp: Date = .now) {
+ self.id = id
+ self.kind = kind
+ self.remoteId = remoteId
+ self.stamp = stamp
+ }
+}
+
+/// What the engine reads and writes in the store beyond the records
+/// themselves: which items are synced, which notes are dirty, and the
+/// tombstones deletes leave behind. DonkeyStore conforms.
+public protocol SyncJournalStoring: AnyObject {
+ // Notes: local edits mark rows dirty; the merge writes clean rows.
+ func dirtyNotes() throws -> [Note]
+ /// Upsert a note the cloud won with, clean. Never touches a dirty row —
+ /// a local edit outranks the pull that raced it.
+ func applyRemoteNote(_ note: Note) throws
+ /// Clear a note's dirty flag after a push, only if it still carries the
+ /// stamp that was pushed — an edit made mid-push stays dirty.
+ func clearNoteDirty(id: UUID, ifUpdatedAt: Date) throws
+ /// Remove a note the cloud deleted. No tombstone: the delete came down.
+ func removeNoteFromCloudDelete(id: UUID) throws
+
+ // Recordings
+ func recordingRemote(_ id: UUID) throws -> (assetId: String?, claimedFileName: String?)
+ /// Journal a recording's cloud copy. Returns false when the row is gone —
+ /// deleted while the bytes were in flight — in which case the store
+ /// leaves a libraryAsset tombstone for `assetId`, so the replay takes the
+ /// fresh cloud copy down with it.
+ @discardableResult
+ func setRecordingRemote(_ id: UUID, assetId: String?, claimedFileName: String?) throws -> Bool
+
+ // Inspiration
+ func inspirationRemoteAssetId(_ id: UUID) throws -> String?
+ func isInspirationLinkSynced(_ id: UUID) throws -> Bool
+ func markInspirationMediaSynced(_ id: UUID, remoteAssetId: String) throws
+ func markInspirationLinkSynced(_ id: UUID) throws
+
+ // Tombstones
+ func tombstones() throws -> [SyncTombstone]
+ func removeTombstone(id: UUID) throws
+}
+
+@Observable
+public final class SyncEngine {
+ /// The account is out of cloud storage. The Library banner reads this;
+ /// media uploads pause while it holds.
+ public private(set) var storageFull = false
+ /// The current network, reported by the app target's path monitor.
+ public var network: NetworkPath = .offline {
+ didSet { if network != oldValue, network != .offline { kick() } }
+ }
+
+ /// Live upload progress per recording, layered over the journal.
+ private var uploadStates: [UUID: RecordingSyncState] = [:]
+ private var uploading: Set<UUID> = []
+
+ public weak var media: MediaModel?
+ public weak var ideas: IdeasModel?
+
+ private let journal: any SyncJournalStoring
+ private let service: any CloudSyncServicing
+ private let cellularAllowed: () -> Bool
+ private let signedIn: () -> Bool
+ /// Reads a recording's upload payload (bytes, dimensions, poster) off the
+ /// file; the app target implements it with AVFoundation.
+ private let uploadFor: (Recording) async -> LibraryUpload?
+ private var running = false
+ private var runAgain = false
+
+ public init(
+ journal: any SyncJournalStoring,
+ service: any CloudSyncServicing,
+ cellularAllowed: @escaping () -> Bool,
+ signedIn: @escaping () -> Bool,
+ uploadFor: @escaping (Recording) async -> LibraryUpload?
+ ) {
+ self.journal = journal
+ self.service = service
+ self.cellularAllowed = cellularAllowed
+ self.signedIn = signedIn
+ self.uploadFor = uploadFor
+ }
+
+ /// Journal answers memoized per recording, so a badge read is a set
+ /// lookup instead of a SwiftData fetch per visible card. The engine is
+ /// the journal's only writer, so it refreshes these on its own writes.
+ @ObservationIgnored private var syncedIds: Set<UUID> = []
+ @ObservationIgnored private var checkedIds: Set<UUID> = []
+
+ /// The badge state the Library shows for a recording.
+ public func state(for recording: Recording) -> RecordingSyncState {
+ if let live = uploadStates[recording.id] { return live }
+ if syncedIds.contains(recording.id) { return .synced }
+ if checkedIds.contains(recording.id) { return .onDevice }
+ checkedIds.insert(recording.id)
+ guard (try? journal.recordingRemote(recording.id))?.assetId != nil else { return .onDevice }
+ syncedIds.insert(recording.id)
+ return .synced
+ }
+
+ /// Something changed — a new recording, a note edit, the network, a
+ /// sign-in. One runner drains every queue; a kick during a run schedules
+ /// one more pass so nothing lands between checks.
+ public func kick() {
+ guard signedIn(), network != .offline else { return }
+ if running {
+ runAgain = true
+ return
+ }
+ running = true
+ Task { [weak self] in
+ await self?.run()
+ }
+ }
+
+ /// One full pass over every queue. kick() is the entry point; tests call
+ /// this directly to drain synchronously.
+ func run() async {
+ defer {
+ running = false
+ if runAgain {
+ runAgain = false
+ kick()
+ }
+ }
+ await replayTombstones()
+ await syncNotes()
+ // Link imports are small payloads: they move on any connection, so
+ // they queue ahead of the media gate.
+ await uploadPendingInspirationLinks()
+ guard allowed(.media) else { return }
+ await refreshStorage()
+ guard !storageFull else { return }
+ await uploadPendingRecordings()
+ await uploadPendingInspirationMedia()
+ }
+
+ private func allowed(_ kind: TransferClass) -> Bool {
+ transferAllowed(kind, on: network, cellularAllowed: cellularAllowed())
+ }
+
+ // MARK: Deletes
+
+ private func replayTombstones() async {
+ for tombstone in (try? journal.tombstones()) ?? [] {
+ do {
+ switch tombstone.kind {
+ case .note:
+ guard let id = UUID(uuidString: tombstone.remoteId) else { break }
+ try await service.deleteNote(id: id)
+ case .libraryAsset:
+ try await service.deleteLibraryAsset(id: tombstone.remoteId)
+ }
+ try? journal.removeTombstone(id: tombstone.id)
+ // Freed bytes may reopen a full account.
+ if tombstone.kind == .libraryAsset { storageFull = false }
+ } catch CloudSyncError.unauthorized {
+ return
+ } catch {
+ // Transient; the tombstone stays for the next kick.
+ }
+ }
+ }
+
+ // MARK: Notes (two-way, last writer wins)
+
+ private func syncNotes() async {
+ guard allowed(.small) else { return }
+ // Push local edits first so the pull that follows can't overwrite them.
+ for note in (try? journal.dirtyNotes()) ?? [] {
+ do {
+ let won = try await service.putNote(
+ RemoteNote(
+ id: note.id,
+ title: note.title,
+ body: note.body,
+ colorIndex: note.color.rawValue,
+ updatedAt: note.updatedAt,
+ createdAt: note.createdAt
+ )
+ )
+ try? journal.clearNoteDirty(id: note.id, ifUpdatedAt: note.updatedAt)
+ if won.updatedAt > note.updatedAt {
+ try? journal.applyRemoteNote(localNote(from: won))
+ }
+ } catch CloudSyncError.unauthorized {
+ return
+ } catch {
+ // Transient; stays dirty.
+ }
+ }
+ do {
+ let remote = try await service.fetchNotes()
+ try mergeRemoteNotes(remote)
+ ideas?.reloadFromStore()
+ } catch {
+ // The next kick pulls again.
+ }
+ }
+
+ private func mergeRemoteNotes(_ remote: [RemoteNote]) throws {
+ let localById = Dictionary(
+ uniqueKeysWithValues: (ideas?.notes ?? []).map { ($0.id, $0) }
+ )
+ let pendingDeletes = Set(
+ ((try? journal.tombstones()) ?? [])
+ .filter { $0.kind == .note }
+ .compactMap { UUID(uuidString: $0.remoteId) }
+ )
+ for note in remote {
+ if pendingDeletes.contains(note.id) { continue }
+ if note.deletedAt != nil {
+ // The cloud deleted it; a newer local edit revives instead.
+ if let local = localById[note.id], local.updatedAt <= note.updatedAt {
+ try journal.removeNoteFromCloudDelete(id: note.id)
+ }
+ continue
+ }
+ let local = localById[note.id]
+ if local == nil || note.updatedAt > local!.updatedAt {
+ try journal.applyRemoteNote(localNote(from: note))
+ }
+ }
+ }
+
+ private func localNote(from remote: RemoteNote) -> Note {
+ Note(
+ id: remote.id,
+ title: remote.title,
+ body: remote.body,
+ color: NoteColor(rawValue: remote.colorIndex) ?? .butter,
+ createdAt: remote.createdAt,
+ updatedAt: remote.updatedAt
+ )
+ }
+
+ // MARK: Recordings
+
+ /// A finished recording heads for the cloud at once (policy permitting).
+ public func recordingAdded(_ recording: Recording) {
+ kick()
+ }
+
+ private func uploadPendingRecordings() async {
+ for recording in media?.recordings ?? [] {
+ guard allowed(.media), !storageFull else { return }
+ let remote = try? journal.recordingRemote(recording.id)
+ guard remote?.assetId == nil, !uploading.contains(recording.id) else { continue }
+ guard var upload = await uploadFor(recording) else { continue }
+ upload.resume = remote?.claimedFileName != nil
+ if let claimed = remote?.claimedFileName { upload.fileName = claimed }
+ uploading.insert(recording.id)
+ uploadStates[recording.id] = .uploading(percent: 0)
+ defer { uploading.remove(recording.id) }
+ do {
+ let asset = try await service.uploadLibraryMedia(
+ upload,
+ allowCellular: cellularAllowed()
+ ) { [weak self] fraction in
+ Task { @MainActor [weak self] in
+ self?.setUploadProgress(recording.id, fraction)
+ }
+ }
+ let journaled = ((try? journal.setRecordingRemote(recording.id, assetId: asset.id, claimedFileName: asset.fileName)) ?? false)
+ if journaled {
+ uploadStates[recording.id] = .synced
+ syncedIds.insert(recording.id)
+ checkedIds.remove(recording.id)
+ } else {
+ // Deleted mid-upload: the journal left a tombstone for
+ // the fresh asset; another pass replays it.
+ uploadStates[recording.id] = nil
+ kick()
+ }
+ storageFull = false
+ } catch CloudSyncError.storageFull {
+ uploadStates[recording.id] = nil
+ // Remember the claim if one was minted before the refusal —
+ // the retry resumes under the same name.
+ _ = try? journal.setRecordingRemote(recording.id, assetId: nil, claimedFileName: upload.resume ? upload.fileName : nil)
+ storageFull = true
+ return
+ } catch CloudSyncError.unauthorized {
+ uploadStates[recording.id] = nil
+ return
+ } catch {
+ // Transient: keep the claim so the retry resumes, drop the bar.
+ uploadStates[recording.id] = nil
+ _ = try? journal.setRecordingRemote(recording.id, assetId: nil, claimedFileName: upload.fileName)
+ }
+ }
+ }
+
+ private func setUploadProgress(_ id: UUID, _ fraction: Double) {
+ guard uploading.contains(id) else { return }
+ uploadStates[id] = .uploading(percent: Int((fraction * 100).rounded()))
+ }
+
+ // MARK: Inspiration
+
+ private func uploadPendingInspirationLinks() async {
+ for item in ideas?.inspiration ?? [] {
+ guard case .link(let url) = item.kind else { continue }
+ guard allowed(.small) else { continue }
+ guard ((try? journal.isInspirationLinkSynced(item.id)) ?? true) == false else { continue }
+ do {
+ try await service.importInspirationLink(url)
+ try? journal.markInspirationLinkSynced(item.id)
+ } catch CloudSyncError.unauthorized {
+ return
+ } catch {
+ // Transient or capped for the day; the next kick retries.
+ }
+ }
+ }
+
+ private func uploadPendingInspirationMedia() async {
+ for item in ideas?.inspiration ?? [] {
+ guard case .media(let fileName, let isVideo) = item.kind else { continue }
+ guard allowed(.media), !storageFull else { continue }
+ guard ((try? journal.inspirationRemoteAssetId(item.id)) ?? nil) == nil else { continue }
+ guard let fileURL = ideas?.mediaURL(fileName: fileName),
+ let bytes = fileSize(fileURL) else { continue }
+ let upload = LibraryUpload(
+ fileURL: fileURL,
+ fileName: fileName,
+ mime: isVideo ? "video/quicktime" : "image/jpeg",
+ bytes: bytes,
+ name: fileName,
+ type: isVideo ? "video" : "image",
+ duration: 0,
+ origin: "inspiration",
+ resume: true
+ )
+ do {
+ let asset = try await service.uploadLibraryMedia(
+ upload,
+ allowCellular: cellularAllowed(),
+ progress: { _ in }
+ )
+ try? journal.markInspirationMediaSynced(item.id, remoteAssetId: asset.id)
+ storageFull = false
+ } catch CloudSyncError.storageFull {
+ storageFull = true
+ return
+ } catch CloudSyncError.unauthorized {
+ return
+ } catch {
+ // Transient; retried on the next kick.
+ }
+ }
+ }
+
+ private nonisolated func fileSize(_ url: URL) -> Int64? {
+ let size = (try? FileManager.default.attributesOfItem(atPath: url.path()))?[.size] as? NSNumber
+ guard let size, size.int64Value > 0 else { return nil }
+ return size.int64Value
+ }
+
+ // MARK: Storage
+
+ private func refreshStorage() async {
+ guard let usage = try? await service.fetchUsage() else { return }
+ storageFull = usage.isFull
+ }
+}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift
index cc20d6d5..9c034c59 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift
@@ -1,20 +1,61 @@
import Foundation
nonisolated public struct TeleprompterSettings: Equatable, Codable, Sendable {
- /// Scroll speed in points per second.
- public var speed: Double
+ /// Reading speed in words per minute. The scroll rate is derived from the
+ /// script: however the words are spaced, they pass the reader at this pace.
+ public var wordsPerMinute: Double
/// Body text size in points.
public var textSize: Double
- public static let speedRange: ClosedRange<Double> = 10...100
+ public static let speedRange: ClosedRange<Double> = 80...220
public static let textSizeRange: ClosedRange<Double> = 16...40
- public init(speed: Double = 40, textSize: Double = 24) {
- self.speed = speed
+ public init(wordsPerMinute: Double = 150, textSize: Double = 24) {
+ self.wordsPerMinute = wordsPerMinute
self.textSize = textSize
}
}
+/// Prompter copy from a raw note. Spacing is the prompter's job: runs of
+/// spaces collapse, the writer's own line breaks hold as paragraph breaks,
+/// and a long unbroken paragraph wraps into short lines at clause boundaries
+/// so the eye has a rhythm to follow. Nobody has to format a note to read it.
+nonisolated public func pacedScript(_ raw: String) -> String {
+ let paragraphs = raw
+ .split(separator: "\n", omittingEmptySubsequences: true)
+ .map { pacedParagraph(String($0)) }
+ .filter { !$0.isEmpty }
+ return paragraphs.joined(separator: "\n\n")
+}
+
+/// Words a line holds before it breaks anyway.
+private nonisolated let lineWordCap = 6
+/// Words after which a clause end (comma, period, dash…) takes the break.
+private nonisolated let clauseBreakMin = 2
+
+private nonisolated func pacedParagraph(_ text: String) -> String {
+ let words = text.split(whereSeparator: { $0.isWhitespace }).map(String.init)
+ var lines: [String] = []
+ var line: [String] = []
+ for word in words {
+ line.append(word)
+ let clauseEnd = word.last.map { ",.;:!?—".contains($0) } ?? false
+ if line.count >= lineWordCap || (clauseEnd && line.count >= clauseBreakMin) {
+ lines.append(line.joined(separator: " "))
+ line = []
+ }
+ }
+ if !line.isEmpty { lines.append(line.joined(separator: " ")) }
+ return lines.joined(separator: "\n")
+}
+
+/// How long the script takes to read aloud at the given pace.
+nonisolated public func readDuration(of script: String, wordsPerMinute: Double) -> TimeInterval {
+ let words = script.split(whereSeparator: { $0.isWhitespace }).count
+ guard words > 0, wordsPerMinute > 0 else { return 0 }
+ return Double(words) / wordsPerMinute * 60
+}
+
nonisolated public struct TeleprompterState: Equatable, Sendable {
public var script: String = ""
public var isCardShown = false
@@ -26,9 +67,22 @@ nonisolated public struct TeleprompterState: Equatable, Sendable {
!script.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
- /// Vertical offset of the script at `elapsed` seconds into a recording:
- /// text starts 60% down the overlay and scrolls up at the set speed.
- public func scrollOffset(elapsed: TimeInterval, overlayHeight: Double) -> Double {
- overlayHeight * 0.6 - settings.speed * elapsed
+ /// The text the overlay renders: the raw script, paced.
+ public var displayScript: String { pacedScript(script) }
+
+ /// Seconds the whole script takes at the set pace.
+ public var duration: TimeInterval { readDuration(of: script, wordsPerMinute: settings.wordsPerMinute) }
+
+ /// Vertical offset of the script at `elapsed` seconds into a recording.
+ /// The text starts 60% down the overlay and travels its own rendered
+ /// height plus that lead-in over the read duration, so the last words
+ /// leave the top exactly when the speaker should be finishing them.
+ /// Paragraph gaps are part of the height, so they read as natural pauses.
+ public func scrollOffset(elapsed: TimeInterval, overlayHeight: Double, textHeight: Double) -> Double {
+ let lead = overlayHeight * 0.6
+ let total = duration
+ guard total > 0 else { return lead }
+ let speed = (textHeight + lead) / total
+ return lead - speed * elapsed
}
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift
index 48f6f0d0..74f07c47 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift
@@ -372,10 +372,10 @@ struct TeleprompterSettingsView: View {
var body: some View {
VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 6) {
- Text("Teleprompter speed")
+ Text("Reading speed · \(Int(camera.teleprompter.settings.wordsPerMinute)) wpm")
.font(.footnote)
.foregroundStyle(.secondary)
- Slider(value: $camera.teleprompter.settings.speed, in: TeleprompterSettings.speedRange)
+ Slider(value: $camera.teleprompter.settings.wordsPerMinute, in: TeleprompterSettings.speedRange)
}
VStack(alignment: .leading, spacing: 6) {
Text("Text size")
@@ -392,17 +392,28 @@ struct TeleprompterSettingsView: View {
struct TeleprompterOverlay: View {
var camera: CameraModel
+ /// Rendered height of the paced script, measured off the Text itself so
+ /// the scroll rate can pace the exact copy on screen.
+ @State private var textHeight: Double = 0
+
var body: some View {
GeometryReader { geometry in
let height = geometry.size.height * 0.42
TimelineView(.animation) { context in
let elapsed = camera.recordingStartedAt.map { context.date.timeIntervalSince($0) } ?? 0
- Text(camera.teleprompter.script)
+ Text(camera.teleprompter.displayScript)
.font(.system(size: camera.teleprompter.settings.textSize, weight: .heavy))
.foregroundStyle(.white)
.lineSpacing(4)
.frame(maxWidth: .infinity, alignment: .leading)
- .offset(y: camera.teleprompter.scrollOffset(elapsed: elapsed, overlayHeight: height))
+ .onGeometryChange(for: Double.self, of: { $0.size.height }) { textHeight = $0 }
+ .offset(
+ y: camera.teleprompter.scrollOffset(
+ elapsed: elapsed,
+ overlayHeight: height,
+ textHeight: textHeight
+ )
+ )
.padding(.horizontal, 24)
}
.frame(height: height, alignment: .top)
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift
index c6433eee..eadd7623 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift
@@ -33,6 +33,7 @@ struct AvatarMenu: View {
Text("Dark").tag(AppearancePreference.dark)
}
.pickerStyle(.menu)
+ Toggle("Sync over Cellular", systemImage: "antenna.radiowaves.left.and.right", isOn: $app.syncOverCellular)
Divider()
Button("Log Out", systemImage: "rectangle.portrait.and.arrow.right", role: .destructive) {
Task { await auth.signOut() }
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift
index b2a6e9a4..100db948 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift
@@ -14,6 +14,9 @@ struct MediaScreen: View {
var body: some View {
VStack(spacing: 0) {
+ if media.storageFull {
+ StorageBanner()
+ }
ScreenHeader(title: "Library", app: app, auth: auth)
Group {
if media.recordings.isEmpty {
@@ -53,6 +56,20 @@ struct MediaScreen: View {
}
}
+/// Pinned above everything in the library when the cloud is full: edge to
+/// edge, under the status bar, just tall enough to say why clips stay local.
+struct StorageBanner: View {
+ var body: some View {
+ Text("Not enough cloud storage — recordings stay on this phone")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(.white)
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, 20)
+ .padding(.vertical, 8)
+ .background(Color(hex: "#b3261e").ignoresSafeArea(edges: [.top, .horizontal]))
+ }
+}
+
struct RecordingCard: View {
let recording: Recording
var media: MediaModel
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift
index fc1b29f7..5353bdc0 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift
@@ -1,4 +1,5 @@
#if os(iOS)
+import AVKit
import SwiftUI
import DonkeyKitModels
@@ -15,11 +16,16 @@ struct ProjectsScreen: View {
VStack(spacing: 0) {
ScreenHeader(title: "Projects", app: app, auth: auth)
if projects.projects.isEmpty {
- EmptyState(
- title: "No projects yet",
- message: "Projects you create in Donkey Cut will show up here."
- )
- .frame(maxHeight: .infinity)
+ if projects.isLoading {
+ ProgressView()
+ .frame(maxHeight: .infinity)
+ } else {
+ EmptyState(
+ title: "No projects yet",
+ message: "Projects you create in Donkey Cut will show up here."
+ )
+ .frame(maxHeight: .infinity)
+ }
} else {
ScrollView {
LazyVGrid(columns: columns, spacing: 12) {
@@ -31,10 +37,12 @@ struct ProjectsScreen: View {
.padding(.top, 14)
.padding(.bottom, 24)
}
+ .refreshable { await projects.refresh() }
}
}
+ .task { await projects.refresh() }
.fullScreenCover(item: $playing) { project in
- ProjectPlayerView(project: project)
+ ProjectPlayerView(project: project, projects: projects)
}
}
}
@@ -49,17 +57,25 @@ struct ProjectCard: View {
case .ready(let renderedOn):
Button(action: onPlay) {
ZStack {
- RoundedRectangle(cornerRadius: 16).fill(.fill.secondary)
+ if let thumbnail = project.thumbnail,
+ let image = UIImage(contentsOfFile: thumbnail.path()) {
+ Image(uiImage: image)
+ .resizable()
+ .scaledToFill()
+ } else {
+ RoundedRectangle(cornerRadius: 16).fill(.fill.secondary)
+ }
Circle()
- .fill(.white.opacity(0.14))
+ .fill(.black.opacity(0.35))
.frame(width: 46, height: 46)
.overlay {
Image(systemName: "play.fill")
.font(.body.weight(.bold))
- .foregroundStyle(.primary)
+ .foregroundStyle(.white)
.offset(x: 2)
}
}
+ .clipShape(RoundedRectangle(cornerRadius: 16))
.overlay(alignment: .topLeading) {
ProjectTag(text: formattedDuration(project.duration))
.padding(8)
@@ -70,13 +86,6 @@ struct ProjectCard: View {
}
}
.buttonStyle(.plain)
- case .exporting(let percent):
- GhostCard(title: project.name, subtitle: "Exporting \(percent)%")
- .overlay(alignment: .bottom) {
- ProgressView(value: Double(percent), total: 100)
- .padding(.horizontal, 12)
- .padding(.bottom, 12)
- }
case .none:
GhostCard(title: project.name, subtitle: "No export yet")
}
@@ -120,104 +129,59 @@ struct GhostCard: View {
}
}
-/// Plays the project's latest render. Playback is a clock over the render's
-/// duration until renders stream from the cloud.
+/// Streams the project's latest export, or the composited preview when no
+/// export exists. The URL resolves at open time because CDN links expire.
struct ProjectPlayerView: View {
let project: Project
+ var projects: ProjectsModel
- @State private var time: TimeInterval = 0
- @State private var isPlaying = false
+ @State private var player: AVPlayer?
+ @State private var failed = false
@Environment(\.dismiss) private var dismiss
var body: some View {
- VStack(spacing: 0) {
+ ZStack(alignment: .topLeading) {
+ Color.black.ignoresSafeArea()
+ if let player {
+ VideoPlayer(player: player)
+ .ignoresSafeArea()
+ } else if failed {
+ Text("Couldn't load this project's video")
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(.white.opacity(0.8))
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ ProgressView()
+ .tint(.white)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
HStack(spacing: 12) {
Button {
dismiss()
} label: {
Image(systemName: "xmark")
.font(.title3.weight(.bold))
+ .foregroundStyle(.white)
.frame(width: 40, height: 40)
}
+ .glassEffect(.regular.interactive())
Text(project.name)
.font(.subheadline.weight(.bold))
+ .foregroundStyle(.white)
.lineLimit(1)
- .frame(maxWidth: .infinity)
- Spacer().frame(width: 40)
- }
- .padding(.horizontal, 16)
- .padding(.top, 8)
-
- Spacer()
-
- Button {
- isPlaying.toggle()
- } label: {
- Image(systemName: isPlaying ? "pause.fill" : "play.fill")
- .font(.title.weight(.bold))
- .frame(width: 76, height: 76)
- .background(.white.opacity(0.15), in: Circle())
- }
-
- Spacer()
-
- VStack(alignment: .leading, spacing: 8) {
- scrubber
- HStack {
- Text(formattedDuration(time))
- Spacer()
- Text(formattedDuration(project.duration))
- }
- .font(.caption.weight(.semibold))
- .foregroundStyle(.white.opacity(0.75))
- if case .ready(let renderedOn) = project.export {
- Text("Latest render · \(renderedOn)")
- .font(.caption2.weight(.bold))
- .padding(.horizontal, 10)
- .padding(.vertical, 4)
- .background(.white.opacity(0.14), in: Capsule())
- .padding(.top, 4)
- }
- }
- .padding(.horizontal, 16)
- .padding(.bottom, 24)
- }
- .foregroundStyle(.white)
- .background(Color.black.ignoresSafeArea())
- .task(id: isPlaying) {
- guard isPlaying else { return }
- while !Task.isCancelled {
- try? await Task.sleep(for: .seconds(0.1))
- time = min(time + 0.1, project.duration)
- if time >= project.duration {
- isPlaying = false
- return
- }
}
+ .padding(16)
}
- }
-
- private var scrubber: some View {
- GeometryReader { proxy in
- ZStack(alignment: .leading) {
- Capsule().fill(.white.opacity(0.22))
- Capsule()
- .fill(.white)
- .frame(width: max(0, proxy.size.width * progress))
+ .task {
+ guard let url = await projects.streamURL(for: project) else {
+ failed = true
+ return
}
- .contentShape(Rectangle())
- .gesture(
- DragGesture(minimumDistance: 0).onChanged { value in
- let fraction = min(max(value.location.x / proxy.size.width, 0), 1)
- time = fraction * project.duration
- }
- )
+ let player = AVPlayer(url: url)
+ self.player = player
+ player.play()
}
- .frame(height: 5)
- }
-
- private var progress: Double {
- project.duration > 0 ? time / project.duration : 0
+ .onDisappear { player?.pause() }
}
}
#endif
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift
index 2f283265..8974c888 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift
@@ -63,6 +63,16 @@ public struct RootView<CameraPreview: View>: View {
.animation(.default, value: auth.isSignedIn)
.preferredColorScheme(app.appearance.colorScheme)
.task { await auth.restore() }
+ .onChange(of: scenePhase) { _, phase in
+ if phase == .active, auth.isSignedIn {
+ media.sync?.kick()
+ }
+ }
+ .onChange(of: auth.isSignedIn) { _, signedIn in
+ guard signedIn else { return }
+ media.sync?.kick()
+ Task { await projects.refresh() }
+ }
.onChange(of: cameraShouldRun) { _, run in
if run {
camera.appeared()
diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
index acebedc7..6edf0d01 100644
--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
@@ -63,10 +63,22 @@ import Testing
@Suite struct TeleprompterTests {
@Test func scrollStartsLowAndMovesUp() {
var state = TeleprompterState()
- state.settings.speed = 40
- let start = state.scrollOffset(elapsed: 0, overlayHeight: 300)
+ state.settings.wordsPerMinute = 120
+ state.script = Array(repeating: "word", count: 120).joined(separator: " ")
+ // 120 words at 120 wpm = 60s. Lead-in is 60% of the overlay; the text
+ // travels its own height plus the lead over the minute.
+ #expect(state.duration == 60)
+ let start = state.scrollOffset(elapsed: 0, overlayHeight: 300, textHeight: 420)
#expect(start == 180)
- #expect(state.scrollOffset(elapsed: 2, overlayHeight: 300) == 100)
+ let mid = state.scrollOffset(elapsed: 30, overlayHeight: 300, textHeight: 420)
+ #expect(mid == 180 - (420 + 180) / 2)
+ let end = state.scrollOffset(elapsed: 60, overlayHeight: 300, textHeight: 420)
+ #expect(end == -420)
+ }
+
+ @Test func emptyScriptHoldsAtLead() {
+ let state = TeleprompterState()
+ #expect(state.scrollOffset(elapsed: 5, overlayHeight: 300, textHeight: 0) == 180)
}
@Test func hasScriptIgnoresWhitespace() {
@@ -76,6 +88,267 @@ import Testing
state.script = "Hello"
#expect(state.hasScript)
}
+
+ @Test func readDurationCountsWordsNotSpacing() {
+ #expect(readDuration(of: "one two\n\nthree", wordsPerMinute: 60) == 3)
+ #expect(readDuration(of: "", wordsPerMinute: 150) == 0)
+ }
+
+ @Test func pacingRespectsUserNewlines() {
+ let paced = pacedScript("First thought\nSecond thought")
+ #expect(paced == "First thought\n\nSecond thought")
+ }
+
+ @Test func pacingCollapsesSpaceRuns() {
+ #expect(pacedScript("hello there friend") == "hello there friend")
+ }
+
+ @Test func pacingWrapsLongParagraphsAtClauses() {
+ let paced = pacedScript("Hey everyone, welcome back to the channel where we talk about editing")
+ let lines = paced.split(separator: "\n").map(String.init)
+ // The clause end takes the first break; no line outruns the word cap.
+ #expect(lines.first == "Hey everyone,")
+ #expect(lines.allSatisfy { $0.split(separator: " ").count <= 6 })
+ // Every word survives the wrap.
+ #expect(paced.split(whereSeparator: { $0.isWhitespace }).count == 12)
+ }
+}
+
+@Suite struct SyncPolicyTests {
+ @Test func wifiMovesEverything() {
+ #expect(transferAllowed(.media, on: .wifi, cellularAllowed: false))
+ #expect(transferAllowed(.small, on: .wifi, cellularAllowed: false))
+ }
+
+ @Test func cellularHoldsMediaUntilAllowed() {
+ #expect(!transferAllowed(.media, on: .cellular, cellularAllowed: false))
+ #expect(transferAllowed(.media, on: .cellular, cellularAllowed: true))
+ // Notes and links are small; they always move.
+ #expect(transferAllowed(.small, on: .cellular, cellularAllowed: false))
+ }
+
+ @Test func offlineMovesNothing() {
+ #expect(!transferAllowed(.small, on: .offline, cellularAllowed: true))
+ #expect(!transferAllowed(.media, on: .offline, cellularAllowed: true))
+ }
+}
+
+@MainActor
+@Suite struct SyncEngineTests {
+ final class FakeCloud: CloudSyncServicing {
+ var notes: [UUID: RemoteNote] = [:]
+ var uploads: [String] = []
+ var deletedAssets: [String] = []
+ var deletedNotes: [UUID] = []
+ var links: [URL] = []
+ var usage = StorageUsage(bytes: 0, quotaBytes: 1_000_000)
+ var uploadResult: Result<RemoteAsset, CloudSyncError> =
+ .success(RemoteAsset(id: "asset-1", fileName: "clip.mov"))
+ /// Runs while the bytes are "in flight", before the upload returns.
+ var onUpload: (() -> Void)?
+
+ func uploadLibraryMedia(
+ _ upload: LibraryUpload,
+ allowCellular: Bool,
+ progress: @escaping @Sendable (Double) -> Void
+ ) async throws -> RemoteAsset {
+ uploads.append(upload.fileName)
+ onUpload?()
+ return try uploadResult.get()
+ }
+
+ func deleteLibraryAsset(id: String) async throws { deletedAssets.append(id) }
+ func importInspirationLink(_ url: URL) async throws { links.append(url) }
+ func fetchUsage() async throws -> StorageUsage { usage }
+ func fetchNotes() async throws -> [RemoteNote] { Array(notes.values) }
+
+ func putNote(_ note: RemoteNote) async throws -> RemoteNote {
+ if let existing = notes[note.id], existing.updatedAt > note.updatedAt { return existing }
+ notes[note.id] = note
+ return note
+ }
+
+ func deleteNote(id: UUID) async throws {
+ deletedNotes.append(id)
+ notes[id] = nil
+ }
+ }
+
+ struct Rig {
+ let store: DonkeyStore
+ let cloud: FakeCloud
+ let ideas: IdeasModel
+ let media: MediaModel
+ let engine: SyncEngine
+ }
+
+ func makeRig() throws -> Rig {
+ let store = try DonkeyStore(inMemory: true)
+ let cloud = FakeCloud()
+ let ideas = IdeasModel(store: store)
+ let media = MediaModel(store: store)
+ let engine = SyncEngine(
+ journal: store,
+ service: cloud,
+ cellularAllowed: { false },
+ signedIn: { true },
+ uploadFor: { recording in
+ LibraryUpload(
+ fileURL: media.movieURL(for: recording),
+ fileName: recording.fileName,
+ mime: "video/quicktime",
+ bytes: 100,
+ name: "Recording",
+ type: "video",
+ duration: recording.duration,
+ origin: "camera"
+ )
+ }
+ )
+ engine.media = media
+ engine.ideas = ideas
+ media.sync = engine
+ // Assigned before the engine is observed so the didSet kick (a no-op
+ // pass) can't race the manual run() calls below.
+ engine.network = .wifi
+ return Rig(store: store, cloud: cloud, ideas: ideas, media: media, engine: engine)
+ }
+
+ func ingestClip(_ rig: Rig) throws -> Recording {
+ let temp = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString + ".mov")
+ try Data("movie".utf8).write(to: temp)
+ rig.media.ingest(movieAt: temp, duration: 2, thumbnail: nil)
+ return rig.media.recordings[0]
+ }
+
+ @Test func recordingUploadsOnceAndJournals() async throws {
+ let rig = try makeRig()
+ let recording = try ingestClip(rig)
+ await rig.engine.run()
+ #expect(rig.cloud.uploads == [recording.fileName])
+ #expect(rig.engine.state(for: recording) == .synced)
+ // A second pass moves nothing: the journal already holds the asset.
+ await rig.engine.run()
+ #expect(rig.cloud.uploads.count == 1)
+ }
+
+ @Test func fullStoragePausesUploadsAndRaisesBanner() async throws {
+ let rig = try makeRig()
+ rig.cloud.usage = StorageUsage(bytes: 10, quotaBytes: 10)
+ _ = try ingestClip(rig)
+ await rig.engine.run()
+ #expect(rig.engine.storageFull)
+ #expect(rig.cloud.uploads.isEmpty)
+ }
+
+ @Test func transientFailureKeepsClaimForResume() async throws {
+ let rig = try makeRig()
+ let recording = try ingestClip(rig)
+ rig.cloud.uploadResult = .failure(.transport)
+ await rig.engine.run()
+ let journaled = try rig.store.recordingRemote(recording.id)
+ #expect(journaled.assetId == nil)
+ #expect(journaled.claimedFileName == recording.fileName)
+ #expect(rig.engine.state(for: recording) == .onDevice)
+ rig.cloud.uploadResult = .success(RemoteAsset(id: "asset-9", fileName: recording.fileName))
+ await rig.engine.run()
+ #expect(rig.engine.state(for: recording) == .synced)
+ }
+
+ @Test func deleteDuringUploadTombstonesTheFreshAsset() async throws {
+ let rig = try makeRig()
+ let recording = try ingestClip(rig)
+ rig.cloud.onUpload = { rig.media.delete(recording) }
+ await rig.engine.run()
+ // The finished upload found its row gone, so the journal holds a
+ // tombstone for the asset; the next pass takes the cloud copy down.
+ await rig.engine.run()
+ #expect(rig.cloud.deletedAssets == ["asset-1"])
+ #expect(try rig.store.tombstones().isEmpty)
+ }
+
+ @Test func deleteOfSyncedRecordingReachesCloud() async throws {
+ let rig = try makeRig()
+ let recording = try ingestClip(rig)
+ await rig.engine.run()
+ rig.media.delete(recording)
+ await rig.engine.run()
+ #expect(rig.cloud.deletedAssets == ["asset-1"])
+ #expect(try rig.store.tombstones().isEmpty)
+ }
+
+ @Test func localNotePushesAndRemoteNewerWins() async throws {
+ let rig = try makeRig()
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "phone words"
+ let note = rig.ideas.saveDraft()!
+ await rig.engine.run()
+ #expect(rig.cloud.notes[note.id]?.body == "phone words")
+
+ // The desktop edits later; the next pass adopts its version.
+ rig.cloud.notes[note.id] = RemoteNote(
+ id: note.id,
+ title: note.title,
+ body: "desktop words",
+ colorIndex: 2,
+ updatedAt: note.updatedAt.addingTimeInterval(60)
+ )
+ await rig.engine.run()
+ #expect(rig.ideas.notes.first?.body == "desktop words")
+ #expect(rig.ideas.notes.first?.color == .sky)
+ }
+
+ @Test func noteDeleteTombstonePropagates() async throws {
+ let rig = try makeRig()
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "short lived"
+ let note = rig.ideas.saveDraft()!
+ await rig.engine.run()
+ rig.ideas.deleteNote(id: note.id)
+ await rig.engine.run()
+ #expect(rig.cloud.deletedNotes == [note.id])
+ #expect(rig.ideas.notes.isEmpty)
+ }
+
+ @Test func cloudDeleteComesDownAsRemoval() async throws {
+ let rig = try makeRig()
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "doomed"
+ let note = rig.ideas.saveDraft()!
+ await rig.engine.run()
+ // The desktop deleted it; the cloud keeps a newer tombstone.
+ rig.cloud.notes[note.id] = RemoteNote(
+ id: note.id,
+ title: note.title,
+ body: note.body,
+ colorIndex: 0,
+ updatedAt: note.updatedAt.addingTimeInterval(30),
+ deletedAt: note.updatedAt.addingTimeInterval(30)
+ )
+ await rig.engine.run()
+ #expect(rig.ideas.notes.isEmpty)
+ }
+
+ @Test func inspirationLinkImportsOnce() async throws {
+ let rig = try makeRig()
+ #expect(rig.ideas.addInspiration(urlText: "youtube.com/watch?v=9"))
+ await rig.engine.run()
+ #expect(rig.cloud.links.map(\.host) == ["youtube.com"])
+ await rig.engine.run()
+ #expect(rig.cloud.links.count == 1)
+ }
+
+ @Test func cellularHoldsMediaButMovesNotes() async throws {
+ let rig = try makeRig()
+ rig.engine.network = .cellular
+ _ = try ingestClip(rig)
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "typed on the train"
+ let note = rig.ideas.saveDraft()!
+ await rig.engine.run()
+ #expect(rig.cloud.uploads.isEmpty)
+ #expect(rig.cloud.notes[note.id] != nil)
+ }
}
@Suite struct DurationTests {
diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.md
index b1d8c000..a9aa4c60 100644
--- a/docs/guides/ios-app.md
+++ b/docs/guides/ios-app.md
@@ -1,10 +1,56 @@
# The iOS App
-Donkey's iOS app lives at `apps/ios/`. It records videos on the phone and
-keeps everything local: notes and inspiration in the Library tab, the camera
-with a teleprompter in the middle, and the recordings grid in Media. Sign-in
-is Google or Apple, exchanged for a Donkey Cut session on donkeycut.com; the
-recordings themselves never leave the device today.
+Donkey's iOS app lives at `apps/ios/`. It is the phone end of Donkey Cut:
+record clips with a teleprompter, jot notes and collect inspiration, and let
+everything flow to the desktop editor through the cloud shelf. Sign-in is
+Google or Apple, exchanged for a Donkey Cut session on donkeycut.com; the same
+bearer session authenticates every cloud call.
+
+## Sync
+
+One engine (`SyncEngine` in `DonkeyKitModels`) owns every queue: recordings
+up, inspiration up, notes both ways, deletes replayed. It works off a journal
+kept in the app's SwiftData store, so nothing depends on the app staying open
+— whatever was mid-flight when the app died is picked up on the next launch,
+foreground, network change, or edit.
+
+**The one rule on data:** a transfer moves when the network is Wi-Fi, or the
+user turned on "Sync over Cellular" (avatar menu), or the payload is small
+(notes, link imports, JSON). Media otherwise waits for Wi-Fi, and requests are
+stamped with that decision so an upload started on Wi-Fi never quietly
+continues over cell.
+
+Every byte moves at most once. Uploads go straight to storage on presigned
+URLs; an interrupted upload re-presigns under the name it already claimed, and
+a retried completion lands on the asset it already made. Recordings arrive in
+the desktop library marked as camera clips (the Camera Roll tab), inspiration
+media lands in the Inspiration folder, and inspiration links queue a
+cloud-side import that fetches the media there. Notes merge both ways by
+last-writer-wins on the edit stamp, with tombstones so a delete made offline
+on either side still lands on the other. Deleting a synced recording on the
+phone deletes the cloud copy too.
+
+When the account is out of cloud storage, uploads pause and the Library shows
+a slim banner pinned over the notch; clips stay on the phone and the banner
+clears once space frees up.
+
+Projects sync down as thumbnails only: the Projects tab lists cloud projects
+with cached poster images, and a tap streams the latest export — or the
+composited preview when none exists — straight from the CDN.
+
+Every request carries an `x-donkey-cut-client: ios` header. The server
+remembers accounts it has seen it from, and the desktop shows its phone
+surfaces (Camera Roll and Notes tabs) only to those accounts.
+
+## Teleprompter
+
+The teleprompter paces raw notes by itself. Reading speed is words per
+minute; the scroll rate is derived from the script's word count and the
+rendered height, so however the words are spaced they pass the reader at the
+set pace. Runs of spaces collapse, the writer's own line breaks hold as
+paragraph breaks, and long unbroken paragraphs wrap into short lines at
+clause boundaries. Speed and text size persist across sessions — set once,
+kept forever.
## How It Is Put Together