> ## Documentation Index
> Fetch the complete documentation index at: https://setup.despia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Background Recorder

> A ready-made V3 extension that records audio in the background and uploads it to your server when recording stops.

Source: [Background Recorder repository](https://github.com/despia-legacy/recorder). Read its [LICENSE](https://github.com/despia-legacy/recorder/blob/main/LICENSE) before using or modifying the extension.

This extension records audio from the microphone, keeps recording when the app goes to the background, and uploads the file to your server when recording stops. It shows its state in a Lock Screen widget on iOS, and in a foreground service notification and a home screen widget on Android.

The page only ever sees a recording id and its state. The audio never crosses the bridge.

> [!WARNING]
>
> **Experimental. V3 only.** You own and maintain this ready-made extension once it is in your app. First-party V4 support comes through the new package registry. Despia does not support customised code. Read [V3 Extensions](https://setup.despia.com/experiments/v3-extensions.md) first.

***

## Before installing the extension

Extension files must be compiled into a rebuilt native app. Uploading files does not change an installed binary. Automatic discovery of hosted `/despia/extensions.json` during a normal rebuild is under review and is not yet confirmed in deployed builds. See [Troubleshooting extension builds](https://setup.despia.com/experiments/extension-troubleshooting.md).

## Files

Copy every file to the path in its title. Paths are under `public/despia/recorder/` in your web app, except `extensions.json`, which goes in `public/despia/`.

Before you build, change these values to your own:

* `client_id` (the id after `/builder/` in your Despia editor URL), `ios_bundle_id` and `android_package` in `public/despia/extensions.json`;
* the upload host `upload.example.com` in both `hosts` lists in `manifest.json`.

The build policy is part of the trusted build inputs and is not served from your site. Signed-source checks verify the exact files and dependency graph; artifact checks verify the build before signing. You own the behavior and maintenance of your native code.

> [tab] Manifest
>
> ```json manifest.json theme={null}
> {
>   "version": "1.0.0",
>   "bridge": {
>     "routes": [
>       {
>         "name": "start",
>         "params": {
>           "upload": {
>             "type": "https_url",
>             "hosts": [
>               "upload.example.com"
>             ],
>             "required": true
>           }
>         },
>         "output": {
>           "variable": "recorderStart",
>           "callback": "onRecorderStart"
>         }
>       },
>       {
>         "name": "stop",
>         "params": {
>           "id": {
>             "type": "string",
>             "max": 64,
>             "required": true
>           }
>         },
>         "output": {
>           "variable": "recorderStop",
>           "callback": "onRecorderStop"
>         }
>       },
>       {
>         "name": "status",
>         "params": {
>           "id": {
>             "type": "string",
>             "max": 64
>           }
>         },
>         "output": {
>           "variable": "recorderStatus",
>           "callback": "onRecorderStatus"
>         }
>       },
>       {
>         "name": "discard",
>         "params": {
>           "id": {
>             "type": "string",
>             "max": 64,
>             "required": true
>           }
>         },
>         "output": {
>           "variable": "recorderDiscard",
>           "callback": "onRecorderDiscard"
>         }
>       },
>       {
>         "name": "upload",
>         "params": {
>           "id": {
>             "type": "string",
>             "max": 64,
>             "required": true
>           },
>           "upload": {
>             "type": "https_url",
>             "hosts": [
>               "upload.example.com"
>             ],
>             "required": true
>           }
>         },
>         "output": {
>           "variable": "recorderUpload",
>           "callback": "onRecorderUpload"
>         }
>       }
>     ],
>     "events": [
>       {
>         "name": "state",
>         "callback": "onRecorderState",
>         "scope": "document"
>       }
>     ]
>   },
>   "ios": {
>     "app": {
>       "entry_type": "RecorderExtension",
>       "sources": [
>         "ios/app/RecorderExtension.swift",
>         "ios/app/RecorderUploader.swift",
>         "ios/shared/RecorderStatus.swift"
>       ],
>       "frameworks": [
>         "AVFAudio",
>         "WidgetKit"
>       ],
>       "requires": {
>         "usage_descriptions": [
>           "NSMicrophoneUsageDescription"
>         ]
>       },
>       "info_plist": {
>         "UIBackgroundModes": [
>           "audio",
>           "processing"
>         ]
>       },
>       "entitlements": {
>         "com.apple.security.application-groups": [
>           "nativeext"
>         ]
>       },
>       "lifecycle": [
>         "launch",
>         "scene",
>         "background_task"
>       ],
>       "background_tasks": [
>         "upload"
>       ]
>     },
>     "targets": [
>       {
>         "kind": "widgetkit",
>         "name": "RecorderStatusWidget",
>         "sources": [
>           "ios/targets/RecorderStatusWidget/RecorderStatusWidget.swift"
>         ],
>         "shared_sources": [
>           "ios/shared/RecorderStatus.swift"
>         ],
>         "info_plist": {
>           "NSWidgetDescription": "Recording status"
>         },
>         "entitlements": {
>           "com.apple.security.application-groups": [
>             "nativeext"
>           ]
>         },
>         "deployment_target": "16.6"
>       }
>     ]
>   },
>   "android": {
>     "entry_class": "despia.ext.recorder.RecorderExtension",
>     "requires": {
>       "permissions": [
>         "android.permission.RECORD_AUDIO"
>       ]
>     },
>     "lifecycle": [
>       "application_create"
>     ],
>     "modules": [
>       {
>         "kind": "typed",
>         "name": "recorder",
>         "namespace": "despia.ext.recorder",
>         "sources": [
>           "android/recorder/java/despia/ext/recorder/RecorderExtension.java",
>           "android/recorder/java/despia/ext/recorder/RecorderStore.java",
>           "android/recorder/java/despia/ext/recorder/RecorderOwner.java",
>           "android/recorder/java/despia/ext/recorder/RecorderService.java",
>           "android/recorder/java/despia/ext/recorder/StopReceiver.java",
>           "android/recorder/java/despia/ext/recorder/UploadWorker.java",
>           "android/recorder/java/despia/ext/recorder/StatusWidgetProvider.java"
>         ],
>         "res": [
>           "android/recorder/res/layout/nx_recorder_widget.xml",
>           "android/recorder/res/xml/nx_recorder_widget_info.xml",
>           "android/recorder/res/values/nx_recorder_strings.xml"
>         ],
>         "permissions": [
>           "android.permission.FOREGROUND_SERVICE",
>           "android.permission.FOREGROUND_SERVICE_MICROPHONE",
>           "android.permission.POST_NOTIFICATIONS"
>         ],
>         "components": [
>           {
>             "type": "service",
>             "class": "despia.ext.recorder.RecorderService",
>             "exported": false,
>             "foreground_service_type": [
>               "microphone"
>             ]
>           },
>           {
>             "type": "receiver",
>             "class": "despia.ext.recorder.StopReceiver",
>             "exported": false
>           },
>           {
>             "type": "receiver",
>             "class": "despia.ext.recorder.StatusWidgetProvider",
>             "exported": true,
>             "intent_actions": [
>               "android.appwidget.action.APPWIDGET_UPDATE"
>             ],
>             "meta_data": [
>               {
>                 "name": "android.appwidget.provider",
>                 "resource": "@xml/nx_recorder_widget_info"
>               }
>             ]
>           }
>         ],
>         "dependencies": [
>           "androidx.core:core:1.18.0",
>           "androidx.work:work-runtime:2.11.2"
>         ]
>       }
>     ]
>   }
> }
> ```
>
> ```json public/despia/extensions.json theme={null}
> {
>   "app": {
>     "client_id": "<your client id>",
>     "ios_bundle_id": "com.example.app",
>     "android_package": "com.example.app"
>   },
>   "extensions": [
>     "recorder"
>   ]
> }
> ```

> [tab] iOS
>
> ```swift ios/app/RecorderExtension.swift theme={null}
> import AVFAudio
> import BackgroundTasks
> import Foundation
> import UIKit
> import WidgetKit
>
> /// Background microphone recorder. Native code owns capture, the files and the upload; the page
> /// only ever sees a recording id and its state, never audio and never the upload URL. State lives in
> /// an index file (RecorderStore) so `status` answers correctly after suspension and termination.
> ///
> /// Upload (RecorderUploader): an in-process ephemeral URLSession that refuses every HTTP redirect, so
> /// the recording reaches only the approved host of the URL the page supplied; the stored URL is
> /// re-checked against the approved hosts before every attempt. Uploads run only while this process
> /// runs: in the foreground, during the limited background time iOS may grant after backgrounding,
> /// and during a background processing launch if and when iOS grants one. iOS guarantees neither
> /// when nor whether those grants happen. A suspended or terminated upload keeps its file and queue
> /// entry and restarts from the beginning when the app next runs; until then the state stays
> /// `uploading`.
> ///
> /// States: recording, interrupted (paused by the system, still owns the recorder), uploading,
> /// uploaded, failed (upload failed; `reason` says why; `upload` with a fresh URL retries the saved
> /// file), terminated (the app died while recording; the file was never finalized, so it is never
> /// uploaded), discarding (a discard tombstone: its file is being deleted, then the record goes).
> ///
> /// Main actor, as NativeExtension requires: every route, callback and uploader call runs there.
> @MainActor
> final class RecorderExtension: NSObject, NativeExtension {
>     private var ctx: NativeExtContext!
>     private var recorder: AVAudioRecorder?
>     /// The record that owns `recorder`, and a reservation taken before any await in start().
>     private var activeId: String?
>     private var starting = false
>     private var store: RecorderStore!
>     private var uploader: RecorderUploader!
>     /// The UIKit background-time assertion held while an upload attempt runs; finite and not guaranteed.
>     private var assertion: UIBackgroundTaskIdentifier = .invalid
>     private var loggedFailure: String?
>     /// This fixture's claim on the process-wide audio session (RecorderUploader.swift).
>     private var session = RecorderSessionLease(record: RecorderExtension.recordConfig)
>     private static let recordConfig = RecorderSessionConfig(category: AVAudioSession.Category.record.rawValue,
>                                                             mode: AVAudioSession.Mode.default.rawValue, options: 0)
>     private static let sessionPort = RecorderSessionPort(
>         config: {
>             let s = AVAudioSession.sharedInstance()
>             return RecorderSessionConfig(category: s.category.rawValue, mode: s.mode.rawValue, options: s.categoryOptions.rawValue)
>         },
>         setConfig: { c in
>             try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: c.category),
>                                                             mode: AVAudioSession.Mode(rawValue: c.mode),
>                                                             options: AVAudioSession.CategoryOptions(rawValue: c.options))
>         },
>         setActive: { active, notifyOthers in
>             try AVAudioSession.sharedInstance().setActive(active, options: notifyOthers ? .notifyOthersOnDeactivation : [])
>         })
>     /// Records whose last event said durable:false; re-emitted once, durable, after the next good write.
>     private var durableEvents = RecorderDurableEvents()
>
>     required override init() { super.init() }
>
>     func didLaunch(_ context: NativeExtContext) {
>         ctx = context
>         // A recording read back from disk did not survive its process, and its file was never
>         // finalized (a "starting" one may not even have audio). The load that first reads the index,
>         // now or at any later save once it becomes readable, finishes the tombstones an earlier
>         // process left before that load returns, so nothing builds on an index that still lists them.
>         store = RecorderStore(directory: context.dataDirectory, adopt: { r in
>             if r.state == "starting" || r.state == "recording" || r.state == "interrupted" { r.state = "terminated" }
>         }, justLoaded: { [weak self] s in
>             let finished = s.recoverDiscards()
>             // After this load returns: the events and the upload restart build on the finished index.
>             Task { @MainActor [weak self] in self?.indexLoaded(finished) }
>         })
>         save()
>         if let aside = store.movedAside { ctx.log("recorder index did not decode; copied aside to \(aside.lastPathComponent)") }
>         uploader = RecorderUploader(
>             store: store,
>             isApproved: { [weak self] url, route in
>                 self?.ctx.isApprovedURL(url, route: route, param: "upload") ?? false
>             },
>             changed: { [weak self] id in self?.changed(id) },
>             inBackground: UIApplication.shared.applicationState == .background)
>         uploader.onIdle = { [weak self] in self?.endAssertion() }
>         NotificationCenter.default.addObserver(self, selector: #selector(interruption(_:)),
>                                                name: AVAudioSession.interruptionNotification, object: nil)
>         // Any record left uploading by a previous process has no live task: resume it now.
>         resumeUploads()
>     }
>
>     func sceneDidChange(_ phase: NativeExtScenePhase) {
>         switch phase {
>         case .didBecomeActive:
>             // The user returning is the most dependable opportunity: retry now, not at the backoff time.
>             if !store.durable { save() }
>             uploader.becameActive()
>             if uploader.isBusy { beginAssertion() }
>         case .didEnterBackground:
>             uploader.didEnterBackground()
>             if uploader.isBusy, assertion == .invalid {
>                 // Not granted (or already ended): requeue rather than be suspended mid-attempt.
>                 uploader.expireInFlight()
>             }
>             if uploader.hasWork { scheduleProcessing() }
>         default:
>             break
>         }
>     }
>
>     func handleBackgroundTask(name: String, task: BGTask) {
>         guard name == "upload" else {
>             task.setTaskCompleted(success: false)
>             return
>         }
>         // Completed exactly once, by whichever comes first: the queue going idle or expiry.
>         var finished = false
>         let previousIdle = uploader.onIdle
>         let finish: (Bool) -> Void = { [weak self] success in
>             guard !finished else { return }
>             finished = true
>             self?.uploader.onIdle = previousIdle
>             task.setTaskCompleted(success: success)
>         }
>         ctx.onExpiration(of: task) { [weak self] in
>             // Delivered after the task already finished (the hop can trail): nothing of it is left to stop.
>             guard !finished, let self = self else { return }
>             self.uploader.expireInFlight()
>             finish(false)
>             if self.uploader.hasWork { self.scheduleProcessing() }
>         }
>         uploader.onIdle = { [weak self] in
>             previousIdle?()
>             guard let self = self else { return }
>             if !self.uploader.isBusy && !self.uploader.hasWork { finish(true) }
>         }
>         if !store.durable { save() }
>         uploader.drain()
>         if !uploader.isBusy && !uploader.hasWork { finish(true) }
>     }
>
>     func handle(_ call: NativeExtCall) async -> NativeExtResult {
>         // A recording this process holds (the active one included) is answered from memory; any
>         // other lookup needs the index. start needs it too: a recording is indexed before it exists.
>         let known = (call.params["id"] as? String).map { store[$0] != nil } ?? (store.latest != nil)
>         if call.route == "start" || !known, let e = unavailable() { return e }
>         switch call.route {
>         case "start": return await start(call)
>         case "stop": return stop(call.params["id"] as? String ?? "")
>         case "status": return status(call.params["id"] as? String)
>         case "discard": return discard(call.params["id"] as? String ?? "")
>         case "upload": return upload(call.params["id"] as? String ?? "", call.params["upload"] as? String ?? "")
>         default: return .error(code: "not_registered", message: call.route)
>         }
>     }
>
>     private func start(_ call: NativeExtCall) async -> NativeExtResult {
>         // Calls run on the main actor but interleave at the permission await: reserve first.
>         guard recorder == nil, !starting else { return .error(code: "busy", message: "a recording is already running") }
>         guard let upload = call.params["upload"] as? String else { return .error(code: "bad_request", message: "upload") }
>         starting = true
>         defer { starting = false }
>         let granted = await withCheckedContinuation { (c: CheckedContinuation<Bool, Never>) in
>             AVAudioSession.sharedInstance().requestRecordPermission { c.resume(returning: $0) }
>         }
>         // A late allow: the route timed out while the permission prompt was up, so the page already
>         // has the timeout and would never learn of a recording begun now. Begin nothing; the defer
>         // releases the reservation, so the next start is not busy. A recording an earlier start
>         // reported is untouched.
>         guard call.isActive else { return .error(code: "timeout", message: "start timed out before the microphone was allowed") }
>         guard granted else { return .error(code: "permission_denied", message: "microphone access was denied") }
>         // Indexed before any audio can exist: a "starting" record is saved before the directory or
>         // the recorder is created. Not saved: nothing is started. Every later failure goes through
>         // the tombstone path (abandon), and a process death leaves "starting", which the next load
>         // adopts as terminated, so audio is never on disk without an index entry.
>         let id = UUID().uuidString.lowercased()
>         let previousLatest = store.latest
>         store.set(RecorderRecord(id: id, state: "starting", startedAt: Date(), durationMs: 0, bytes: 0, uploadURL: upload,
>                                  httpStatus: nil, urlRoute: "start", attempts: nil, nextAttemptAt: nil, reason: nil))
>         store.latest = id
>         guard save() else {
>             store.remove(id)
>             store.latest = previousLatest
>             return .error(code: storageCode(), message: "the recording index could not be saved; nothing was started")
>         }
>         let url = store.fileURL(id)
>         do {
>             try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
>             // Owned only once our own activation returned; a failure before it deactivates nothing.
>             try session.acquire(Self.sessionPort)
>             let r = try AVAudioRecorder(url: url, settings: [
>                 AVFormatIDKey: kAudioFormatMPEG4AAC,
>                 AVSampleRateKey: 44_100,
>                 AVNumberOfChannelsKey: 1,
>                 AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue,
>             ])
>             guard r.record() else {
>                 r.stop()
>                 return abandon(id, previousLatest, failedStart("the recorder did not start"))
>             }
>             recorder = r
>             activeId = id
>         } catch {
>             return abandon(id, previousLatest, failedStart(error.localizedDescription))
>         }
>         if var r = store[id] {
>             r.state = "recording"
>             store.set(r)
>         }
>         changed(id)
>         return .ok(storageFields(["recordingId": id, "state": "recording"]))
>     }
>
>     /// A start that failed after its "starting" record was saved: the record goes through the
>     /// tombstone path, so its directory (which may hold a partial file) is deleted before the record
>     /// is removed. A tombstone that cannot finish stays listed as discarding for the next discard or
>     /// load; one that cannot be saved leaves the record, now terminated, which a discard removes.
>     private func abandon(_ id: String, _ previousLatest: String?, _ result: NativeExtResult) -> NativeExtResult {
>         if store.discard(id) == .notSaved, var r = store[id] {
>             r.state = "terminated"
>             store.set(r)
>         }
>         store.latest = previousLatest
>         save()
>         // The page never received this id (the reply is an error): a record the failed start leaves
>         // behind (a tombstone that could not finish, or terminated) is announced so it can be discarded.
>         if store[id] != nil { changed(id) }
>         return result
>     }
>
>     /// A start that failed: the fixture's own session activation is relinquished (another client's
>     /// audio is left alone), the original error is kept, and a cleanup failure is appended and logged.
>     private func failedStart(_ message: String) -> NativeExtResult {
>         if case .failed(let why) = session.relinquish(Self.sessionPort) {
>             ctx.log("recorder audio session not released after a failed start: \(why)")
>             return .error(code: "record_failed", message: message + "; the audio session could not be released")
>         }
>         return .error(code: "record_failed", message: message)
>     }
>
>     /// An id the index does not hold. After an index was set aside, the recording may be listed only
>     /// in the aside copy, so the reply says that instead of a plain not_found.
>     private func unknown() -> NativeExtResult {
>         if store.recovered != nil {
>             return .error(code: "index_recovered",
>                           message: "unknown recording; the recording index could not be read and was replaced, so it may be listed only in the set-aside copy")
>         }
>         return .error(code: "not_found", message: "unknown recording")
>     }
>
>     /// Same codes as Android: an index that cannot be read yet is unavailable, any other failure is failed.
>     private func storageCode() -> String {
>         store.failure == "index_unreadable" ? "storage_unavailable" : "storage_failed"
>     }
>
>     private func stop(_ id: String) -> NativeExtResult {
>         guard var r = store[id] else { return unknown() }
>         // Stop and release in every state that owns the recorder, so the file is finalized.
>         if activeId == id, let active = recorder {
>             r.durationMs = Int(active.currentTime * 1000)
>             active.stop()
>             recorder = nil
>             activeId = nil
>             // Before the audio session goes inactive: a stop while the app is alive only because of
>             // the audio mode would otherwise be suspended at once, before the upload starts.
>             beginAssertion()
>             switch session.relinquish(Self.sessionPort) {
>             case .released:
>                 break
>             case .failed(let why):
>                 ctx.log("recorder audio session not released after stop: \(why)")
>             case let kept:
>                 // Not an error (another client holds the session), but visible in the device log.
>                 ctx.log("recorder audio session left active after stop: \(kept)")
>             }
>         } else if r.state == "recording" || r.state == "interrupted" {
>             // No recorder owns it any more (it died with the process): nothing to finalize.
>             r.state = "terminated"
>             store.set(r)
>             changed(id)
>             return .ok(snapshot(r))
>         } else {
>             return .ok(snapshot(r))
>         }
>         return beginUpload(&r, fromUploadRoute: false)
>     }
>
>     /// Re-upload a saved recording with a fresh URL (an expired presigned URL is the usual reason).
>     /// The stored URL is replaced; neither URL is ever logged or emitted.
>     private func upload(_ id: String, _ url: String) -> NativeExtResult {
>         guard var r = store[id] else { return unknown() }
>         guard r.state == "failed" || r.state == "uploaded" else {
>             return .error(code: "busy", message: "only a stopped recording whose upload failed or finished can be uploaded again")
>         }
>         r.uploadURL = url
>         r.urlRoute = "upload"
>         return beginUpload(&r, fromUploadRoute: true)
>     }
>
>     private func beginUpload(_ r: inout RecorderRecord, fromUploadRoute: Bool) -> NativeExtResult {
>         let id = r.id
>         let file = store.fileURL(id)
>         r.bytes = ((try? FileManager.default.attributesOfItem(atPath: file.path))?[.size] as? NSNumber)?.int64Value ?? 0
>         r.state = "uploading"
>         r.httpStatus = nil
>         r.reason = nil
>         store.set(r)
>         changed(id)
>         beginAssertion()
>         uploader.enqueue(id, fromUploadRoute: fromUploadRoute)
>         return .ok(snapshot(store[id] ?? r))
>     }
>
>     private func resumeUploads() {
>         guard uploader.hasWork else { return }
>         beginAssertion()
>         uploader.drain()
>     }
>
>     private func status(_ id: String?) -> NativeExtResult {
>         // A named recording the index does not hold is unknown, never idle.
>         if let id = id, store[id] == nil { return unknown() }
>         guard let key = id ?? store.latest, var r = store[key] else { return .ok(storageFields(["state": "idle"])) }
>         if r.state == "recording", let active = recorder { r.durationMs = Int(active.currentTime * 1000) }
>         return .ok(snapshot(r))
>     }
>
>     private func discard(_ id: String) -> NativeExtResult {
>         guard let r = store[id] else { return unknown() }
>         guard activeId != id, r.state != "starting", r.state != "recording", r.state != "interrupted", r.state != "uploading" else {
>             return .error(code: "busy", message: "stop the recording or wait for the upload")
>         }
>         switch store.discard(id) {
>         case .notSaved:
>             return .error(code: storageCode(), message: "the recording index could not be saved; nothing was discarded")
>         case .fileKept:
>             changed(id)
>             return .error(code: "discard_failed",
>                           message: "the recording file could not be deleted; it stays listed as discarding and is deleted by the next discard or launch")
>         case .discarded:
>             changed(id)
>             return .ok(storageFields(["recordingId": id, "state": "discarded"]))
>         }
>     }
>
>     /// After the load that first read the index (the store's justLoaded hook already finished the
>     /// tombstones an earlier process left): report each discard it finished, and restart uploads.
>     private func indexLoaded(_ finished: [String]) {
>         for id in finished {
>             ctx.log("recorder discard finished at index load")
>             changed(id)
>         }
>         if uploader != nil { resumeUploads() }
>     }
>
>     private func snapshot(_ r: RecorderRecord) -> [String: Any] {
>         var out: [String: Any] = ["recordingId": r.id, "state": r.state, "durationMs": r.durationMs, "bytes": r.bytes]
>         if let code = r.httpStatus { out["httpStatus"] = code }
>         if r.state == "failed", let reason = r.reason { out["reason"] = reason }
>         return storageFields(out)
>     }
>
>     /// Storage conditions every reply and event carries: state held in memory only (after a
>     /// termination it is lost and the index on disk applies), and an index that did not decode and
>     /// was set aside on this install (persisted, never cleared), so earlier recordings may be listed
>     /// only in the aside copy.
>     private func storageFields(_ base: [String: Any]) -> [String: Any] {
>         var out = base
>         if !store.durable {
>             out["durable"] = false
>             out["storage"] = store.failure ?? "not_saved"
>         }
>         if let flag = store.recovered { out["indexRecovered"] = flag }
>         return out
>     }
>
>     /// While the index cannot be read, no recording is known to be absent and none may start: a reply
>     /// would wrongly say idle or not_found, and a new recording could not be indexed. Each call
>     /// retries the read first; a read that succeeds runs the store's justLoaded recovery.
>     private func unavailable() -> NativeExtResult? {
>         if !store.isLoaded { save() }
>         guard !store.isLoaded else { return nil }
>         return .error(code: storageCode(), message: "the recording index cannot be read yet; retry later")
>     }
>
>     /// Persists the index; a failure is logged once per kind and stays visible in every snapshot.
>     @discardableResult
>     private func save() -> Bool {
>         if store.persist() {
>             loggedFailure = nil
>             // Every state the page was told is not durable is durable now: say so, once per record.
>             for id in durableEvents.saved() {
>                 ctx.emit("state", store[id].map(snapshot) ?? storageFields(["recordingId": id, "state": "discarded"]))
>             }
>             return true
>         }
>         let failure = store.failure ?? "not_saved"
>         if loggedFailure != failure {
>             loggedFailure = failure
>             ctx.log("recorder index not saved: \(failure)")
>         }
>         return false
>     }
>
>     private func changed(_ id: String) {
>         // This event reports the record's current state, so a pending re-emission of it is superseded.
>         durableEvents.willEmit(id)
>         save()
>         let r = store[id]
>         RecorderStatus(recordingId: r?.id, state: r?.state ?? "idle", durationMs: r?.durationMs ?? 0, updatedAt: Date()).save()
>         WidgetCenter.shared.reloadTimelines(ofKind: "NXRecorderStatus")
>         ctx.emit("state", r.map(snapshot) ?? storageFields(["recordingId": id, "state": "discarded"]))
>         durableEvents.emitted(id, durable: store.durable)
>     }
>
>     // MARK: Background execution (finite, never guaranteed)
>
>     /// One assertion while upload work runs. iOS may grant little or no time, and may end it early;
>     /// on expiry the in-flight attempt is cancelled and requeued without counting it.
>     private func beginAssertion() {
>         guard assertion == .invalid else { return }
>         assertion = UIApplication.shared.beginBackgroundTask(withName: "nativeext.recorder.upload") { [weak self] in
>             guard let self = self else { return }
>             self.uploader.expireInFlight()
>             if self.uploader.hasWork { self.scheduleProcessing() }
>             self.endAssertion()
>         }
>     }
>
>     private func endAssertion() {
>         guard assertion != .invalid else { return }
>         let a = assertion
>         assertion = .invalid
>         UIApplication.shared.endBackgroundTask(a)
>     }
>
>     /// Asks for a background processing launch for queued uploads. The system decides whether and
>     /// when it runs (only when the device is idle, possibly hours later); a refused request is logged.
>     private func scheduleProcessing() {
>         let request = BGProcessingTaskRequest(identifier: "nativeext.\(ctx.extensionId).upload")
>         request.requiresNetworkConnectivity = true
>         request.requiresExternalPower = false
>         do {
>             try BGTaskScheduler.shared.submit(request)
>         } catch {
>             ctx.log("background processing request not accepted: \(error.localizedDescription)")
>         }
>     }
>
>     /// NotificationCenter calls a selector observer on the posting thread, which AVAudioSession does
>     /// not promise is the main one: hop to the main actor, where the recorder state lives.
>     @objc private nonisolated func interruption(_ note: Notification) {
>         let info = note.userInfo
>         Task { @MainActor [weak self] in self?.interrupted(info) }
>     }
>
>     private func interrupted(_ userInfo: [AnyHashable: Any]?) {
>         guard let raw = userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
>               let type = AVAudioSession.InterruptionType(rawValue: raw),
>               let id = activeId, let active = recorder, var r = store[id] else { return }
>         if type == .began, r.state == "recording" {
>             r.durationMs = Int(active.currentTime * 1000)
>             active.pause()
>             // The system deactivated the session: it is no longer this fixture's activation.
>             session.lost()
>             r.state = "interrupted"
>             store.set(r)
>             changed(id)
>         } else if type == .ended, r.state == "interrupted" {
>             let opts = AVAudioSession.InterruptionOptions(rawValue: userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0)
>             if opts.contains(.shouldResume), (try? AVAudioSession.sharedInstance().setActive(true)) != nil {
>                 session.regained()
>             }
>             if opts.contains(.shouldResume), session.owned, active.record() {
>                 r.state = "recording"
>                 store.set(r)
>                 changed(id)
>             }
>         }
>     }
> }
> ```
>
> ```swift ios/app/RecorderUploader.swift theme={null}
> import Foundation
> #if canImport(FoundationNetworking)
> import FoundationNetworking
> #endif
>
> /// One recording in `index.json`. The fields after `httpStatus` were added for the upload queue;
> /// they are optional so an index written before them decodes unchanged, and nil fields are not
> /// encoded, so the file stays readable by the older format.
> struct RecorderRecord: Codable, Equatable {
>     var id: String
>     /// starting (indexed before any audio exists), recording, interrupted, uploading, uploaded, failed,
>     /// terminated, discarding (a tombstone)
>     var state: String
>     var startedAt: Date
>     var durationMs: Int
>     var bytes: Int64
>     var uploadURL: String
>     var httpStatus: Int?
>     /// The route that supplied `uploadURL` ("start" or "upload"); nil means "start".
>     var urlRoute: String?
>     /// Counted attempts; nil means 0.
>     var attempts: Int?
>     var nextAttemptAt: Date?
>     /// Why a record is failed: redirect_refused, http, network, url_not_approved, no_file.
>     var reason: String?
> }
>
> /// `index.json`: the records keyed by id (the format every earlier version wrote and reads), plus,
> /// once an index was set aside on this install, the reserved key `"indexRecovered": "moved_aside"`
> /// (ids are UUIDs, so they never collide with it). Without the flag the file is in the earlier
> /// format; with it an earlier version would itself set the file aside, which loses nothing. The
> /// format is iOS's own (Android keeps `{"records": ..., "indexRecovered": ...}`); the flag's meaning
> /// and every route code are the same on both.
> struct RecorderIndexFile: Codable {
>     static let recoveredKey = "indexRecovered"
>
>     var records: [String: RecorderRecord] = [:]
>     var indexRecovered: String?
>
>     init(records: [String: RecorderRecord] = [:], indexRecovered: String? = nil) {
>         self.records = records
>         self.indexRecovered = indexRecovered
>     }
>
>     private struct Key: CodingKey {
>         var stringValue: String
>         var intValue: Int? { nil }
>         init(stringValue: String) { self.stringValue = stringValue }
>         init?(intValue: Int) { nil }
>     }
>
>     init(from decoder: Decoder) throws {
>         let c = try decoder.container(keyedBy: Key.self)
>         for key in c.allKeys {
>             if key.stringValue == RecorderIndexFile.recoveredKey {
>                 indexRecovered = try c.decode(String.self, forKey: key)
>             } else {
>                 records[key.stringValue] = try c.decode(RecorderRecord.self, forKey: key)
>             }
>         }
>     }
>
>     func encode(to encoder: Encoder) throws {
>         var c = encoder.container(keyedBy: Key.self)
>         for (id, r) in records { try c.encode(r, forKey: Key(stringValue: id)) }
>         if let flag = indexRecovered { try c.encode(flag, forKey: Key(stringValue: RecorderIndexFile.recoveredKey)) }
>     }
> }
>
> /// Which records' last `state` event said `durable: false`. When a later write of the index
> /// succeeds, `saved()` hands each of them back exactly once, so the owner emits that record's
> /// state again, now durable (no `durable` field). An event that already reports a record's current
> /// state supersedes its pending one (`willEmit` before the write, `emitted` after it).
> struct RecorderDurableEvents {
>     private(set) var pending: Set<String> = []
>
>     /// Before the write that precedes an event for `id`: that event will report the current state.
>     mutating func willEmit(_ id: String) {
>         pending.remove(id)
>     }
>
>     /// After the event for `id` went out, with the durability it reported.
>     mutating func emitted(_ id: String, durable: Bool) {
>         if durable { pending.remove(id) } else { pending.insert(id) }
>     }
>
>     /// After a write succeeded: the ids whose now-durable state must be emitted, once.
>     mutating func saved() -> [String] {
>         let ids = pending.sorted()
>         pending = []
>         return ids
>     }
> }
>
> /// The durable index. Every `uploading` record in it is queued or in flight.
> ///
> /// Durability is reported, never assumed: `durable` is true only while the records in memory are
> /// the ones last written to `index.json`. A failed write keeps the records in memory (so the
> /// upload and the page state go on in this process), sets `durable` to false with `failure`, and
> /// the next `persist()` writes everything again. An index that exists but cannot be read is never
> /// overwritten: nothing is written until it has been read and merged (records changed in this
> /// process win). One that reads but is not an index is copied aside byte for byte to
> /// `index.unreadable-<uuid>.json` (an identical earlier copy is reused; copies are never deleted) and
> /// only then replaced, atomically, by a fresh index that carries `indexRecovered: "moved_aside"`.
> /// The flag is part of every later write and is never cleared, so it survives a crash after the
> /// copy and every relaunch: the aside copy may list recordings this index no longer knows.
> ///
> /// `justLoaded` runs once, inside the load that first reads the index (at launch, or at any later
> /// save or read once the index becomes readable), after the records were merged and adopted and
> /// before that load returns: the owner finishes leftover tombstones there, before anything builds
> /// on the index.
> final class RecorderStore {
>     static let movedAsideFlag = "moved_aside"
>
>     let directory: URL
>     private(set) var records: [String: RecorderRecord] = [:]
>     var latest: String?
>     private(set) var durable = false
>     /// Why the records are not durable: index_unreadable, index_encode_failed or index_write_failed.
>     private(set) var failure: String?
>     /// "moved_aside" once an index that was not an index was set aside on this install (persisted).
>     private(set) var recovered: String?
>     /// Where this process set an index aside (for the log only; `recovered` is the durable fact).
>     private(set) var movedAside: URL?
>     private var loaded = false
>     /// False while the index exists but has not been read: no record is known to be absent.
>     var isLoaded: Bool { loaded }
>     private let adopt: (inout RecorderRecord) -> Void
>     private let justLoaded: ((RecorderStore) -> Void)?
>     private let readIndex: (URL) throws -> Data
>     private let writeIndex: (Data, URL) throws -> Void
>
>     /// `adopt` runs once on every record read from disk, before it is merged: those records were
>     /// written by an earlier process. `readIndex` and `writeIndex` are injected by tests only.
>     init(directory: URL,
>          adopt: @escaping (inout RecorderRecord) -> Void = { _ in },
>          justLoaded: ((RecorderStore) -> Void)? = nil,
>          readIndex: @escaping (URL) throws -> Data = { try Data(contentsOf: $0) },
>          writeIndex: @escaping (Data, URL) throws -> Void = {
>              try $0.write(to: $1, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
>          }) {
>         self.directory = directory
>         self.adopt = adopt
>         self.justLoaded = justLoaded
>         self.readIndex = readIndex
>         self.writeIndex = writeIndex
>     }
>
>     private var indexURL: URL { directory.appendingPathComponent("index.json") }
>
>     /// Reads the index once. Returns false, and leaves the index untouched, when it exists but
>     /// cannot be read now (for example while the device has not been unlocked since boot), or when
>     /// an index that is not an index could not yet be copied aside and replaced.
>     @discardableResult
>     func load() -> Bool {
>         if loaded { return true }
>         let data: Data
>         do {
>             data = try readIndex(indexURL)
>         } catch {
>             guard RecorderStore.isMissing(error) else {
>                 failure = "index_unreadable"
>                 durable = false
>                 return false
>             }
>             return loadedIndex(RecorderIndexFile())
>         }
>         do {
>             return loadedIndex(try JSONDecoder().decode(RecorderIndexFile.self, from: data))
>         } catch {
>             // Not an index: set aside below.
>         }
>         // Not an index: the aside copy first, then the fresh index that records the fact. Either
>         // failing changes nothing; the next load repeats it (reusing an identical copy).
>         guard let aside = asideCopy(data) else {
>             failure = "index_unreadable"
>             durable = false
>             return false
>         }
>         let fresh = RecorderIndexFile(indexRecovered: RecorderStore.movedAsideFlag)
>         do {
>             try writeIndex(try JSONEncoder().encode(fresh), indexURL)
>         } catch {
>             failure = "index_write_failed"
>             durable = false
>             return false
>         }
>         movedAside = aside
>         return loadedIndex(fresh)
>     }
>
>     private func loadedIndex(_ file: RecorderIndexFile) -> Bool {
>         for (id, record) in file.records where records[id] == nil {
>             var r = record
>             adopt(&r)
>             records[id] = r
>         }
>         if recovered == nil { recovered = file.indexRecovered }
>         if latest == nil { latest = records.values.max { $0.startedAt < $1.startedAt }?.id }
>         loaded = true
>         durable = false
>         justLoaded?(self)
>         return true
>     }
>
>     /// A byte-for-byte copy of an index that is not an index; an identical earlier copy is reused.
>     /// The directory is listed only to find such a copy, never to delete anything.
>     private func asideCopy(_ data: Data) -> URL? {
>         let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
>         for name in names.sorted() where name.hasPrefix("index.unreadable-") && name.hasSuffix(".json") {
>             let old = directory.appendingPathComponent(name)
>             if let bytes = try? readIndex(old), bytes == data { return old }
>         }
>         let aside = directory.appendingPathComponent("index.unreadable-\(UUID().uuidString.lowercased()).json")
>         do {
>             try writeIndex(data, aside)
>         } catch {
>             return nil
>         }
>         return aside
>     }
>
>     /// Writes every record. Returns whether `index.json` now holds exactly the records in memory.
>     @discardableResult
>     func persist() -> Bool {
>         guard load() else { return false }
>         let data: Data
>         do {
>             data = try JSONEncoder().encode(RecorderIndexFile(records: records, indexRecovered: recovered))
>         } catch {
>             failure = "index_encode_failed"
>             durable = false
>             return false
>         }
>         do {
>             try writeIndex(data, indexURL)
>         } catch {
>             failure = "index_write_failed"
>             durable = false
>             return false
>         }
>         failure = nil
>         durable = true
>         return true
>     }
>
>     subscript(id: String) -> RecorderRecord? { records[id] }
>
>     func set(_ r: RecorderRecord) {
>         records[r.id] = r
>         durable = false
>     }
>
>     func remove(_ id: String) {
>         records[id] = nil
>         if latest == id { latest = nil }
>         durable = false
>     }
>
>     enum DiscardOutcome: Equatable {
>         /// The file is gone and the record removed (durable only when `durable` is true after it).
>         case discarded
>         /// The tombstone could not be saved: nothing changed.
>         case notSaved
>         /// Removal was not established (the directory is still listed, or the recorder directory
>         /// could not be listed to confirm its absence): the saved tombstone stays for a later
>         /// discard or recovery.
>         case fileKept
>     }
>
>     /// Crash-consistent discard: the record is saved as a `discarding` tombstone, then its
>     /// directory is deleted, and only then is the record removed. A process death at any point
>     /// leaves either the recording intact or a tombstone that `recoverDiscards` finishes; audio is
>     /// never left on disk without an index entry. `removeItem` and `listDirectory` are injected by
>     /// tests only. Absence is confirmed only by listing the recorder directory: `fileExists` is also
>     /// false when the lookup itself fails, so it never decides.
>     func discard(_ id: String,
>                  removeItem: (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) },
>                  listDirectory: (URL) throws -> [String] = RecorderStore.listNames) -> DiscardOutcome {
>         guard let r = records[id] else { return .discarded }
>         if r.state != "discarding" {
>             var t = r
>             t.state = "discarding"
>             set(t)
>             guard persist() else {
>                 set(r)
>                 return .notSaved
>             }
>         }
>         let dir = fileURL(id).deletingLastPathComponent()
>         do {
>             try removeItem(dir)
>         } catch {
>             // Not removed by this call: confirmed absent only when the parent lists and lacks it.
>             guard let names = try? listDirectory(directory), !names.contains(id) else { return .fileKept }
>         }
>         remove(id)
>         persist()
>         return .discarded
>     }
>
>     /// The names in a directory, only to confirm a tombstoned recording's directory is absent.
>     static func listNames(_ url: URL) throws -> [String] {
>         try FileManager.default.contentsOfDirectory(atPath: url.path)
>     }
>
>     /// Finishes every discard an earlier process left as a tombstone; returns the ids finished.
>     func recoverDiscards(removeItem: (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) },
>                          listDirectory: (URL) throws -> [String] = RecorderStore.listNames) -> [String] {
>         records.values.filter { $0.state == "discarding" }.map { $0.id }.sorted()
>             .filter { discard($0, removeItem: removeItem, listDirectory: listDirectory) == .discarded }
>     }
>
>     func fileURL(_ id: String) -> URL {
>         directory.appendingPathComponent(id, isDirectory: true).appendingPathComponent("audio.m4a")
>     }
>
>     private static func isMissing(_ error: Error) -> Bool {
>         let e = error as NSError
>         if e.domain == NSCocoaErrorDomain && e.code == NSFileReadNoSuchFileError { return true }
>         if e.domain == NSPOSIXErrorDomain && e.code == Int(ENOENT) { return true }
>         if let u = e.userInfo[NSUnderlyingErrorKey] as? NSError, u.domain == NSPOSIXErrorDomain, u.code == Int(ENOENT) {
>             return true
>         }
>         return false
>     }
> }
>
> /// Uploads queued recordings with an in-process ephemeral session whose delegate refuses every
> /// HTTP redirect, so the body and `X-Recording-Id` reach only the host of the validated URL.
> /// Uploads run only while this process runs; a terminated or suspended process leaves the record
> /// `uploading` with its file, and the next `drain()` restarts it from byte 0.
> ///
> /// Main thread only: every method, the delegate queue (`.main`) and the backoff timer share it.
> final class RecorderUploader: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
>     private struct Attempt {
>         let id: String
>         let token: String
>         let task: URLSessionTask
>         var spansBackground: Bool
>     }
>
>     private let store: RecorderStore
>     private let isApproved: (_ url: String, _ route: String) -> Bool
>     private let changed: (_ id: String) -> Void
>     private let configuration: URLSessionConfiguration
>     private let now: () -> Date
>     private let backoffBase: TimeInterval
>     private let backoffCap: TimeInterval
>     private let maxAttempts: Int
>     private var current: Attempt?
>     /// The token of the attempt whose redirect this delegate refused; only that makes a 3xx
>     /// `redirect_refused`.
>     private var refusedToken: String?
>     /// Between didEnterBackground() and becameActive(); every attempt started then spans background.
>     private var inBackground: Bool
>     private var timer: Timer?
>     private var invalidated = false
>     private lazy var session: URLSession = URLSession(configuration: self.configuration, delegate: self, delegateQueue: .main)
>
>     /// Called on the main queue when nothing is in flight and nothing is eligible now.
>     var onIdle: (() -> Void)?
>
>     /// `configuration` is injected by tests only; nil selects `productionConfiguration()`.
>     /// `inBackground` is the application state at creation (true for a background launch).
>     init(store: RecorderStore,
>          isApproved: @escaping (_ url: String, _ route: String) -> Bool,
>          changed: @escaping (_ id: String) -> Void,
>          inBackground: Bool = false,
>          configuration: URLSessionConfiguration? = nil,
>          now: @escaping () -> Date = Date.init,
>          backoffBase: TimeInterval = 30,
>          backoffCap: TimeInterval = 15 * 60,
>          maxAttempts: Int = 5) {
>         self.store = store
>         self.isApproved = isApproved
>         self.changed = changed
>         self.inBackground = inBackground
>         self.configuration = configuration ?? RecorderUploader.productionConfiguration()
>         self.now = now
>         self.backoffBase = backoffBase
>         self.backoffCap = backoffCap
>         self.maxAttempts = maxAttempts
>         super.init()
>     }
>
>     /// Ephemeral so the redirect delegate is honoured (a daemon-run session follows redirects
>     /// without asking). Default system trust: no challenge handling here.
>     static func productionConfiguration() -> URLSessionConfiguration {
>         let c = URLSessionConfiguration.ephemeral
>         c.waitsForConnectivity = true
>         c.timeoutIntervalForRequest = 60
>         c.timeoutIntervalForResource = 1800
>         c.httpCookieStorage = nil
>         c.httpShouldSetCookies = false
>         c.urlCache = nil
>         c.urlCredentialStorage = nil
>         c.httpMaximumConnectionsPerHost = 1
>         return c
>     }
>
>     /// Delay before counted attempt `attempt + 1`: base * 2^(attempt-1), capped.
>     static func backoffDelay(attempt: Int, base: TimeInterval, cap: TimeInterval) -> TimeInterval {
>         min(cap, base * pow(2, Double(max(attempt, 1) - 1)))
>     }
>
>     var hasWork: Bool { store.records.values.contains { $0.state == "uploading" } }
>
>     var isBusy: Bool { current != nil }
>
>     /// The token of the attempt in flight, `<id>#<uuid>`.
>     var inFlightToken: String? { current?.token }
>
>     /// The upload route accepts only a failed or uploaded record, which has no attempt in flight.
>     func enqueue(_ id: String, fromUploadRoute: Bool) {
>         assert(Thread.isMainThread)
>         if fromUploadRoute, var r = store[id] {
>             r.attempts = 0
>             r.nextAttemptAt = nil
>             r.reason = nil
>             r.httpStatus = nil
>             store.set(r)
>             changed(id)
>         }
>         drain()
>     }
>
>     func drain() {
>         assert(Thread.isMainThread)
>         guard current == nil, !invalidated else { return }
>         timer?.invalidate()
>         timer = nil
>         let t = now()
>         let queued = store.records.values
>             .filter { $0.state == "uploading" }
>             .sorted { ($0.startedAt, $0.id) < ($1.startedAt, $1.id) }
>         for candidate in queued {
>             // `changed` may re-enter drain(); re-read the record and stop once something runs.
>             guard current == nil else { return }
>             guard let r = store[candidate.id], r.state == "uploading" else { continue }
>             if let due = r.nextAttemptAt, due > t { continue }
>             if start(r) { return }
>         }
>         guard current == nil else { return }
>         scheduleTimer()
>         onIdle?()
>     }
>
>     func becameActive() {
>         assert(Thread.isMainThread)
>         inBackground = false
>         for r in store.records.values where r.state == "uploading" && r.nextAttemptAt != nil {
>             var u = r
>             u.nextAttemptAt = nil
>             store.set(u)
>             changed(u.id)
>         }
>         drain()
>     }
>
>     /// Background time ran out or was not granted: the attempt is abandoned uncounted and the
>     /// record stays queued for the next drain().
>     func expireInFlight() {
>         assert(Thread.isMainThread)
>         guard let a = current else { return }
>         current = nil
>         a.task.cancel()
>         if var r = store[a.id], r.state == "uploading" {
>             r.nextAttemptAt = nil
>             store.set(r)
>         }
>         changed(a.id)
>     }
>
>     /// A transport error on the attempt now in flight, or on any attempt started before the next
>     /// becameActive(), is then not counted.
>     func didEnterBackground() {
>         assert(Thread.isMainThread)
>         inBackground = true
>         current?.spansBackground = true
>     }
>
>     func invalidate() {
>         invalidated = true
>         timer?.invalidate()
>         timer = nil
>         current = nil
>         session.invalidateAndCancel()
>     }
>
>     /// Returns false when the record was failed without a request.
>     private func start(_ r: RecorderRecord) -> Bool {
>         let id = r.id
>         guard isApproved(r.uploadURL, r.urlRoute ?? "start"),
>               let target = RecorderUploader.destination(r.uploadURL) else {
>             settle(id, state: "failed", reason: "url_not_approved", status: nil)
>             return false
>         }
>         let file = store.fileURL(id)
>         let size = ((try? FileManager.default.attributesOfItem(atPath: file.path))?[.size] as? NSNumber)?.int64Value ?? 0
>         guard size > 0 else {
>             settle(id, state: "failed", reason: "no_file", status: nil)
>             return false
>         }
>         var request = URLRequest(url: target)
>         request.httpMethod = "PUT"
>         request.setValue("audio/mp4", forHTTPHeaderField: "Content-Type")
>         request.setValue(id, forHTTPHeaderField: "X-Recording-Id")
>         let task = session.uploadTask(with: request, fromFile: file)
>         let token = id + "#" + UUID().uuidString.lowercased()
>         task.taskDescription = token
>         refusedToken = nil
>         current = Attempt(id: id, token: token, task: task, spansBackground: inBackground)
>         var u = r
>         u.bytes = size
>         u.nextAttemptAt = nil
>         if u != r {
>             store.set(u)
>             changed(id)
>         }
>         task.resume()
>         return true
>     }
>
>     /// The URL the request is built from, only when Foundation's parse agrees with the text the
>     /// https_url rule approved: the raw text is a strict URL text first (`isStrictURLText`, before
>     /// any parse, so nothing is repaired), then https, no user or password, no fragment, the default
>     /// port (or an explicit 443), and a parsed host of letters, digits, dots and hyphens equal to the
>     /// literal host after "https://". Whether that host is approved is the https_url rule's decision,
>     /// made before.
>     static func destination(_ s: String) -> URL? {
>         guard isStrictURLText(s) else { return nil }
>         let hostCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789.-")
>         guard let url = URL(string: s), url.scheme?.lowercased() == "https", url.user == nil, url.password == nil,
>               url.fragment == nil, url.port == nil || url.port == 443,
>               let host = url.host?.lowercased(), !host.isEmpty,
>               host.unicodeScalars.allSatisfy({ hostCharacters.contains($0) }) else { return nil }
>         let rest = s.lowercased().dropFirst("https://".count)
>         guard s.lowercased().hasPrefix("https://"), rest.hasPrefix(host) else { return nil }
>         let after = rest.dropFirst(host.count)
>         guard after.isEmpty || after.hasPrefix("/") || after == ":443" || after.hasPrefix(":443/") else { return nil }
>         return url
>     }
>
>     /// The characters RFC 3986 allows in a URL, plus "%" (checked as an escape separately).
>     private static let urlTextCharacters: Set<UInt8> = Set(
>         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%".utf8)
>
>     /// The raw text, before any parse: ASCII only, and only characters a URL may contain. Whitespace
>     /// (leading, trailing or inside), C0 and C1 controls, DEL, invisible and bidi code points and
>     /// every other non-ASCII character are refused, as are characters a parser would percent-encode
>     /// (`"<>\^`{|}`). Every "%" must start a two-hex-digit escape, so an existing escape stays
>     /// exactly as given and no "%" is re-encoded. Darwin's URL(string:) repairs such input (a
>     /// trailing space became "%20"), so this check, not the parse, decides.
>     static func isStrictURLText(_ s: String) -> Bool {
>         guard !s.isEmpty, s.unicodeScalars.allSatisfy({ $0.isASCII }) else { return false }
>         let bytes = Array(s.utf8)
>         let hex = Set("0123456789ABCDEFabcdef".utf8)
>         var i = 0
>         while i < bytes.count {
>             let b = bytes[i]
>             guard urlTextCharacters.contains(b) else { return false }
>             if b == UInt8(ascii: "%") {
>                 guard i + 2 < bytes.count, hex.contains(bytes[i + 1]), hex.contains(bytes[i + 2]) else { return false }
>                 i += 3
>             } else {
>                 i += 1
>             }
>         }
>         return true
>     }
>
>     /// The outcome of one attempt. Results whose token is not the current one are dropped.
>     func complete(token: String?, statusCode: Int?, error: Error?) {
>         assert(Thread.isMainThread)
>         guard let a = current, token == a.token else { return }
>         current = nil
>         guard let r = store[a.id], r.state == "uploading" else {
>             drain()
>             return
>         }
>         let refused = refusedToken == a.token
>         refusedToken = nil
>         if let code = statusCode, (300..<400).contains(code) {
>             // A 3xx the delegate was never asked about (no Location, 304) is a terminal HTTP failure.
>             settle(a.id, state: "failed", reason: refused ? "redirect_refused" : "http", status: code)
>         } else if let code = statusCode, (400..<500).contains(code) {
>             settle(a.id, state: "failed", reason: "http", status: code)
>         } else if error == nil, let code = statusCode, (200..<300).contains(code) {
>             settle(a.id, state: "uploaded", reason: nil, status: code)
>         } else if error != nil, a.spansBackground {
>             var u = r
>             u.nextAttemptAt = nil
>             store.set(u)
>             changed(a.id)
>         } else {
>             retry(r, reason: error == nil ? "http" : "network", status: error == nil ? statusCode : nil)
>         }
>         drain()
>     }
>
>     private func retry(_ r: RecorderRecord, reason: String, status: Int?) {
>         var u = r
>         let n = (u.attempts ?? 0) + 1
>         u.attempts = n
>         u.httpStatus = status
>         if n >= maxAttempts {
>             u.state = "failed"
>             u.reason = reason
>             u.nextAttemptAt = nil
>         } else {
>             u.reason = nil
>             u.nextAttemptAt = now().addingTimeInterval(RecorderUploader.backoffDelay(attempt: n, base: backoffBase, cap: backoffCap))
>         }
>         store.set(u)
>         changed(u.id)
>     }
>
>     private func settle(_ id: String, state: String, reason: String?, status: Int?) {
>         guard var r = store[id] else { return }
>         r.state = state
>         r.reason = reason
>         r.httpStatus = status
>         r.nextAttemptAt = nil
>         store.set(r)
>         changed(id)
>     }
>
>     private func scheduleTimer() {
>         let t = now()
>         guard let due = store.records.values
>             .filter({ $0.state == "uploading" })
>             .compactMap({ $0.nextAttemptAt })
>             .filter({ $0 > t })
>             .min() else { return }
>         let next = Timer(timeInterval: due.timeIntervalSince(t), repeats: false) { [weak self] _ in self?.drain() }
>         RunLoop.main.add(next, forMode: .common)
>         timer = next
>     }
>
>     /// Every redirect is refused, so the 3xx becomes the task's response. The refusal is
>     /// recorded for the current attempt only. The target is never logged.
>     func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
>                     newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
>         if let a = current, task.taskDescription == a.token { refusedToken = a.token }
>         completionHandler(nil)
>     }
>
>     func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
>         complete(token: task.taskDescription, statusCode: (task.response as? HTTPURLResponse)?.statusCode, error: error)
>     }
> }
>
> // MARK: - Audio session lease
>
> /// The audio session configuration the lease compares: category, mode and options, as raw values.
> struct RecorderSessionConfig: Equatable {
>     var category: String
>     var mode: String
>     var options: UInt
>
>     /// Category and mode only: iOS may report category options back differently from how they were
>     /// set, so options never decide whose configuration the session holds.
>     func sameRoute(_ other: RecorderSessionConfig) -> Bool {
>         category == other.category && mode == other.mode
>     }
> }
>
> /// The three AVAudioSession calls the lease makes; RecorderExtension supplies the real ones, the
> /// Swift harness a recording fake.
> struct RecorderSessionPort {
>     var config: () -> RecorderSessionConfig
>     var setConfig: (RecorderSessionConfig) throws -> Void
>     var setActive: (_ active: Bool, _ notifyOthers: Bool) throws -> Void
> }
>
> enum RecorderSessionRelease: Equatable {
>     /// The fixture's own activation was deactivated (other apps notified) and the prior
>     /// configuration restored.
>     case released
>     /// Another client in this process configured or reconfigured the session: nothing deactivated.
>     case leftToOtherClient
>     /// The fixture never activated: no deactivation was issued.
>     case notOwned
>     /// A release call threw; the text is for the log.
>     case failed(String)
> }
>
> /// The recorder's claim on the process-wide audio session. The platform keeps one session per
> /// process with no per-client ownership, so the only in-process witness of another client is the
> /// configuration: one that is neither the process default nor the recorder's own was set by someone
> /// else, and is never deactivated by the recorder. Other apps are no reason to hold the session:
> /// releasing with notifyOthers is what lets them resume. Named limit: a co-tenant playing under the
> /// default configuration cannot be told from none.
> struct RecorderSessionLease {
>     static let processDefault = RecorderSessionConfig(category: "AVAudioSessionCategorySoloAmbient",
>                                                       mode: "AVAudioSessionModeDefault", options: 0)
>     let record: RecorderSessionConfig
>     /// True only between the fixture's own setActive(true) returning and its release (or the
>     /// system taking the session in an interruption).
>     private(set) var owned = false
>     private(set) var foreign = false
>     private(set) var configChanged = false
>     private var prior: RecorderSessionConfig?
>
>     init(record: RecorderSessionConfig) {
>         self.record = record
>     }
>
>     mutating func acquire(_ port: RecorderSessionPort) throws {
>         let before = port.config()
>         prior = before
>         foreign = !before.sameRoute(record) && !before.sameRoute(Self.processDefault)
>         try port.setConfig(record)
>         configChanged = true
>         try port.setActive(true, false)
>         owned = true
>     }
>
>     /// An interruption began: the system deactivated the session.
>     mutating func lost() {
>         owned = false
>     }
>
>     /// The fixture's own reactivation after an interruption returned.
>     mutating func regained() {
>         if prior != nil { owned = true }
>     }
>
>     /// Ends the claim; synchronous, no await between the read and the calls. The lease is cleared in
>     /// every branch.
>     mutating func relinquish(_ port: RecorderSessionPort) -> RecorderSessionRelease {
>         defer { self = RecorderSessionLease(record: record) }
>         guard let prior = prior else { return .notOwned }
>         if configChanged && !port.config().sameRoute(record) { return .leftToOtherClient }
>         do {
>             if owned && !foreign {
>                 try port.setActive(false, true)
>                 if prior != record { try port.setConfig(prior) }
>                 return .released
>             }
>             if configChanged && prior != record { try port.setConfig(prior) }
>             return owned ? .leftToOtherClient : .notOwned
>         } catch {
>             return .failed(String(describing: error))
>         }
>     }
> }
> ```
>
> ```swift ios/shared/RecorderStatus.swift theme={null}
> import Foundation
>
> /// Shared by the app and the lock-screen widget through the App Group the build provisions
> /// (logical name "nativeext", expanded into NXAppGroups in each bundle's Info.plist).
> struct RecorderStatus: Codable, Equatable {
>     var recordingId: String?
>     var state: String
>     var durationMs: Int
>     var updatedAt: Date
>
>     static let idle = RecorderStatus(recordingId: nil, state: "idle", durationMs: 0, updatedAt: Date(timeIntervalSince1970: 0))
>     static let defaultsKey = "nx.recorder.status"
>
>     static func groupIdentifier() -> String? {
>         (Bundle.main.object(forInfoDictionaryKey: "NXAppGroups") as? [String: String])?["nativeext"]
>     }
>
>     static func load() -> RecorderStatus {
>         guard let id = groupIdentifier(), let defaults = UserDefaults(suiteName: id),
>               let data = defaults.data(forKey: defaultsKey),
>               let status = try? JSONDecoder().decode(RecorderStatus.self, from: data) else { return .idle }
>         return status
>     }
>
>     func save() {
>         guard let id = Self.groupIdentifier(), let defaults = UserDefaults(suiteName: id),
>               let data = try? JSONEncoder().encode(self) else { return }
>         defaults.set(data, forKey: Self.defaultsKey)
>     }
> }
> ```
>
> ```swift ios/targets/RecorderStatusWidget/RecorderStatusWidget.swift theme={null}
> import SwiftUI
> import WidgetKit
>
> struct RecorderEntry: TimelineEntry {
>     let date: Date
>     let status: RecorderStatus
> }
>
> struct RecorderProvider: TimelineProvider {
>     func placeholder(in context: Context) -> RecorderEntry {
>         RecorderEntry(date: Date(), status: .idle)
>     }
>
>     func getSnapshot(in context: Context, completion: @escaping (RecorderEntry) -> Void) {
>         completion(RecorderEntry(date: Date(), status: RecorderStatus.load()))
>     }
>
>     func getTimeline(in context: Context, completion: @escaping (Timeline<RecorderEntry>) -> Void) {
>         let entry = RecorderEntry(date: Date(), status: RecorderStatus.load())
>         // The app reloads this kind on every state change; the 15 minute refresh only covers a
>         // missed reload while the app was suspended.
>         completion(Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(900))))
>     }
> }
>
> struct RecorderStatusView: View {
>     @Environment(\.widgetFamily) private var family
>     let entry: RecorderEntry
>
>     private var label: String {
>         switch entry.status.state {
>         case "recording": return "Recording"
>         case "interrupted": return "Paused"
>         case "uploading": return "Uploading"
>         case "uploaded": return "Uploaded"
>         case "failed": return "Upload failed"
>         case "stopped": return "Stopped"
>         default: return "Idle"
>         }
>     }
>
>     private var symbol: String {
>         entry.status.state == "recording" ? "mic.fill" : "mic"
>     }
>
>     var body: some View {
>         switch family {
>         case .accessoryCircular:
>             ZStack {
>                 AccessoryWidgetBackground()
>                 Image(systemName: symbol)
>             }
>         case .accessoryInline:
>             Label(label, systemImage: symbol)
>         default:
>             VStack(alignment: .leading) {
>                 Label(label, systemImage: symbol).font(.headline)
>                 if entry.status.durationMs > 0 {
>                     Text("\(entry.status.durationMs / 1000)s")
>                 }
>             }
>         }
>     }
> }
>
> @main
> struct RecorderStatusWidgetBundle: WidgetBundle {
>     var body: some Widget {
>         RecorderStatusWidget()
>     }
> }
>
> struct RecorderStatusWidget: Widget {
>     static let kind = "NXRecorderStatus"
>
>     var body: some WidgetConfiguration {
>         StaticConfiguration(kind: Self.kind, provider: RecorderProvider()) { entry in
>             if #available(iOS 17.0, *) {
>                 RecorderStatusView(entry: entry).containerBackground(.clear, for: .widget)
>             } else {
>                 RecorderStatusView(entry: entry)
>             }
>         }
>         .configurationDisplayName("Recorder")
>         .description("Shows whether a recording is in progress.")
>         .supportedFamilies([.accessoryRectangular, .accessoryCircular, .accessoryInline])
>     }
> }
> ```

> [tab] Android
>
> ```java android/recorder/java/despia/ext/recorder/RecorderExtension.java theme={null}
> package despia.ext.recorder;
>
> import android.Manifest;
> import android.content.Context;
> import android.content.Intent;
> import android.content.pm.PackageManager;
>
> import androidx.core.content.ContextCompat;
>
> import com.despia.nativeext.ExtCall;
> import com.despia.nativeext.ExtContext;
> import com.despia.nativeext.ExtResult;
> import com.despia.nativeext.NativeExtension;
>
> import org.json.JSONException;
> import org.json.JSONObject;
>
> /**
>  * Bridge entry for the background recorder. The page passes an upload URL and gets a recording
>  * id and state back; audio never crosses the bridge, the service records to app storage and the
>  * worker uploads from disk.
>  */
> public final class RecorderExtension implements NativeExtension {
>     private static volatile ExtContext policy;
>     private ExtContext ctx;
>
>     /**
>      * This extension's context once the runtime created it (Application.onCreate, before any
>      * activity or WebView, also in a process WorkManager started); null before that. The worker
>      * re-checks a stored upload URL against the declared route through it.
>      */
>     static ExtContext policy() {
>         return policy;
>     }
>
>     @Override
>     public void onCreate(ExtContext context) {
>         ctx = context;
>         policy = context;
>         RecorderStore.setListener(snapshot -> ctx.emit("state", snapshot));
>         if (!recoverLaunch()) {
>             // Unreadable now: left untouched, and every route reports storage_unavailable until it
>             // reads. The first load that succeeds in this process runs the recovery (tombstones,
>             // stale recordings) before anything builds on that index.
>             RecorderStore.armRecovery(new Runnable() {
>                 @Override
>                 public void run() {
>                     if (!recoverLaunch()) RecorderStore.armRecovery(this);
>                 }
>             });
>         }
>     }
>
>     /** False, changing nothing, when the index cannot be read yet. */
>     private boolean recoverLaunch() {
>         // A process killed mid-recording leaves a "recording" or "starting" entry behind whose file
>         // was never finalized: report it as terminated, never upload it.
>         JSONObject latest;
>         try {
>             latest = RecorderStore.get(ctx.app(), null);
>         } catch (RecorderStore.StorageException e) {
>             ctx.log("recorder index unreadable: " + e.reason);
>             return false;
>         }
>         // Discards a previous process did not finish (a tombstone, its file possibly still on disk).
>         try {
>             for (String id : RecorderStore.recoverDiscards(ctx.app())) ctx.log("recorder discard finished: " + id);
>         } catch (RecorderStore.StorageException e) {
>             ctx.log("recorder discard recovery not saved: " + e.reason);
>         }
>         String s = latest == null ? null : latest.optString("state");
>         if (("recording".equals(s) || "starting".equals(s)) && !RecorderService.isRunning()) {
>             String id = latest.optString("recordingId");
>             try {
>                 RecorderStore.update(ctx.app(), id, "terminated", null);
>             } catch (RecorderStore.StorageException e) {
>                 RecorderStore.notSaved(id, "terminated", e);
>             }
>         }
>         // Posted, never inline: recovery can run inside the store's lock (an armed late load), and
>         // reconciliation reads WorkManager asynchronously. Leaves no finalized recording stranded.
>         final Context app = ctx.app();
>         ContextCompat.getMainExecutor(app).execute(() -> UploadWorker.reconcile(app));
>         return true;
>     }
>
>     /** Every ok reply carries indexRecovered while the index was set aside on this install. */
>     private static ExtResult ok(Context app, JSONObject data) throws JSONException {
>         String recovered;
>         try {
>             recovered = RecorderStore.recovered(app);
>         } catch (RecorderStore.StorageException e) {
>             // The reply already happened (a discard whose removal was not saved says so itself).
>             recovered = null;
>         }
>         if (recovered != null && !data.has(RecorderStore.RECOVERED)) data.put(RecorderStore.RECOVERED, recovered);
>         return ExtResult.ok(data);
>     }
>
>     /**
>      * An id the index does not hold. After the index was set aside, the recording may be listed
>      * only in the aside copy, so the reply says that instead of a plain not_found.
>      */
>     private static ExtResult unknown(Context app) throws RecorderStore.StorageException {
>         if (RecorderStore.recovered(app) != null) {
>             return ExtResult.error("index_recovered",
>                     "unknown recording; the recording index could not be read and was replaced, so it may be listed only in the set-aside copy");
>         }
>         return ExtResult.error("not_found", "unknown recording");
>     }
>
>     private static ExtResult storageFailed(RecorderStore.StorageException e, String what) {
>         // Same codes as iOS: an index that cannot be read yet is unavailable, any other failure is failed.
>         String code = "index_unreadable".equals(e.reason) ? "storage_unavailable" : "storage_failed";
>         return ExtResult.error(code, "the recording index could not be " + what + " (" + e.reason + ")");
>     }
>
>     @Override
>     public void handle(ExtCall call, ExtResult.Callback reply) {
>         Context app = ctx.app();
>         try {
>             switch (call.route) {
>                 case "start": {
>                     if (ContextCompat.checkSelfPermission(app, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
>                         reply.reply(ExtResult.error("permission_denied", "RECORD_AUDIO is not granted; request it from the page first"));
>                         return;
>                     }
>                     String id = RecorderStore.newId();
>                     // Atomic reservation: two quick starts cannot both pass.
>                     if (RecorderService.isRunning() || !RecorderService.reserve(id)) {
>                         reply.reply(ExtResult.error("busy", "a recording is already running"));
>                         return;
>                     }
>                     try {
>                         RecorderStore.create(app, id, "starting",
>                                 new JSONObject().put("uploadUrl", call.params.get("upload")).put("urlRoute", "start"));
>                     } catch (RecorderStore.StorageException e) {
>                         RecorderService.release(id);
>                         reply.reply(storageFailed(e, "saved; nothing was started"));
>                         return;
>                     }
>                     Intent i = new Intent(app, RecorderService.class).setAction(RecorderService.ACTION_START).putExtra("id", id);
>                     // Microphone foreground services may only start while the app is visible
>                     // (Android 14+); the page call is that moment.
>                     try {
>                         ContextCompat.startForegroundService(app, i);
>                     } catch (RuntimeException e) {
>                         RecorderService.release(id);
>                         try {
>                             // A capture that never began: record_failed, never captureFinal.
>                             RecorderStore.update(app, id, "failed", RecorderStore.captureFailed());
>                         } catch (RecorderStore.StorageException se) {
>                             // Left "starting" on disk, which the next launch reports as terminated.
>                             RecorderStore.notSaved(id, "failed", se);
>                         }
>                         reply.reply(ExtResult.error("record_failed", "the recording service could not start"));
>                         return;
>                     }
>                     reply.reply(ok(app, new JSONObject().put("recordingId", id).put("state", "starting")));
>                     return;
>                 }
>                 case "stop": {
>                     String id = (String) call.params.get("id");
>                     JSONObject r = RecorderStore.get(app, id);
>                     if (r == null) {
>                         reply.reply(unknown(app));
>                         return;
>                     }
>                     // Only the recording that owns the service stops it, also while it is still
>                     // "starting": the service handles its commands in order, so this stop follows
>                     // the start and either ends the recording or cancels it before the microphone
>                     // opens. Requiring a running service here dropped a stop sent during "starting".
>                     if (id.equals(RecorderService.owner())) {
>                         app.startService(new Intent(app, RecorderService.class).setAction(RecorderService.ACTION_STOP).putExtra("id", id));
>                     }
>                     JSONObject now = RecorderStore.get(app, id);
>                     reply.reply(now == null ? unknown(app) : ok(app, RecorderStore.snapshot(now)));
>                     return;
>                 }
>                 case "upload": {
>                     // Re-upload a saved recording with a fresh URL (an expired presigned URL is the
>                     // usual reason). The stored URL is replaced; neither URL is logged or emitted.
>                     String id = (String) call.params.get("id");
>                     // The URL is bound to the route whose https_url rule approved it; the worker re-checks both.
>                     String url = (String) call.params.get("upload");
>                     try {
>                         // The state check, the URL, the generation and "uploading" are one store step:
>                         // a discard can never land between the check and the write. The reply waits
>                         // for WorkManager to commit the request (heard on the main thread), so an ok
>                         // "uploading" always has work behind it.
>                         JSONObject queued = UploadWorker.requeue(app, id, url, "upload", (committed, saved) -> {
>                             try {
>                                 if (committed) {
>                                     reply.reply(ok(app, saved));
>                                 } else {
>                                     reply.reply(ExtResult.error("storage_failed", "the upload could not be scheduled; no upload was queued"));
>                                 }
>                             } catch (JSONException e) {
>                                 reply.reply(ExtResult.error("handler_error", e.getMessage()));
>                             }
>                         });
>                         if (queued == null) {
>                             reply.reply(unknown(app));
>                             return;
>                         }
>                         if (queued.optBoolean("busy")) {
>                             reply.reply(ExtResult.error("busy", "only a stopped recording whose upload failed or finished can be uploaded again"));
>                             return;
>                         }
>                         if (queued.optBoolean("notFinal")) {
>                             reply.reply(ExtResult.error("record_failed", "the recording was never finalized, so there is no audio to upload; discard it"));
>                             return;
>                         }
>                     } catch (RecorderStore.StorageException e) {
>                         reply.reply(storageFailed(e, "saved; no upload was queued"));
>                     }
>                     return;
>                 }
>                 case "status": {
>                     String id = (String) call.params.get("id");
>                     JSONObject r = RecorderStore.get(app, id);
>                     // A named recording the index does not hold is unknown, never "idle".
>                     if (r == null && id != null) {
>                         reply.reply(unknown(app));
>                         return;
>                     }
>                     reply.reply(ok(app, r == null ? new JSONObject().put("state", "idle") : RecorderStore.snapshot(r)));
>                     return;
>                 }
>                 case "discard": {
>                     String id = (String) call.params.get("id");
>                     JSONObject r = RecorderStore.get(app, id);
>                     if (r == null) {
>                         reply.reply(unknown(app));
>                         return;
>                     }
>                     String state = r.optString("state");
>                     if ("recording".equals(state) || "starting".equals(state) || "uploading".equals(state)
>                             || id.equals(RecorderService.owner())) {
>                         reply.reply(ExtResult.error("busy", "stop the recording or wait for the upload"));
>                         return;
>                     }
>                     JSONObject gone;
>                     try {
>                         gone = RecorderStore.discard(app, id);
>                     } catch (RecorderStore.StorageException e) {
>                         reply.reply(storageFailed(e, "saved; nothing was discarded"));
>                         return;
>                     }
>                     if (gone != null && gone.optBoolean("busy")) {
>                         reply.reply(ExtResult.error("busy", "stop the recording or wait for the upload"));
>                         return;
>                     }
>                     if (gone == null) {
>                         reply.reply(ExtResult.error("discard_failed",
>                                 "the recording could not be deleted or its removal could not be confirmed; it stays listed as discarding and is deleted by the next discard or launch"));
>                         return;
>                     }
>                     reply.reply(ok(app, gone));
>                     return;
>                 }
>                 default:
>                     reply.reply(ExtResult.error("not_registered", call.route));
>             }
>         } catch (RecorderStore.StorageException e) {
>             reply.reply(storageFailed(e, "read"));
>         } catch (JSONException e) {
>             reply.reply(ExtResult.error("handler_error", e.getMessage()));
>         }
>     }
> }
> ```
>
> ```java android/recorder/java/despia/ext/recorder/RecorderOwner.java theme={null}
> package despia.ext.recorder;
>
> import java.util.concurrent.atomic.AtomicReference;
>
> /** The single microphone reservation shared by the bridge and the foreground service. */
> final class RecorderOwner {
>     private final AtomicReference<String> current = new AtomicReference<>();
>
>     boolean reserve(String id) {
>         return current.compareAndSet(null, id);
>     }
>
>     String get() {
>         return current.get();
>     }
>
>     boolean release(String id) {
>         String observed = current.get();
>         // Intent delivery preserves the ID value, but may construct a different String.
>         return observed != null && observed.equals(id) && current.compareAndSet(observed, null);
>     }
> }
> ```
>
> ```java android/recorder/java/despia/ext/recorder/RecorderService.java theme={null}
> package despia.ext.recorder;
>
> import android.app.Notification;
> import android.app.NotificationChannel;
> import android.app.NotificationManager;
> import android.app.PendingIntent;
> import android.app.Service;
> import android.content.Intent;
> import android.content.pm.ServiceInfo;
> import android.media.MediaRecorder;
> import android.os.Build;
> import android.os.IBinder;
> import android.os.SystemClock;
>
> import androidx.core.app.NotificationCompat;
> import androidx.core.app.ServiceCompat;
>
> import org.json.JSONException;
> import org.json.JSONObject;
>
> /** Foreground microphone service. Its notification is the recorder's lock-screen presence. */
> public final class RecorderService extends Service {
>     static final String ACTION_START = "despia.ext.recorder.START";
>     static final String ACTION_STOP = "despia.ext.recorder.STOP";
>     private static final String CHANNEL = "nx_recorder";
>     private static final int NOTIFICATION_ID = 0x4e58;
>     private static volatile boolean running;
>     /** The recording that owns the service, reserved by start() before the service exists. */
>     private static final RecorderOwner OWNER = new RecorderOwner();
>
>     private MediaRecorder recorder;
>     private String id;
>     private long startedAt;
>
>     static boolean isRunning() {
>         return running;
>     }
>
>     /** False when another recording owns or is about to own the microphone. */
>     static boolean reserve(String id) {
>         return OWNER.reserve(id);
>     }
>
>     /** Gives back the matching reservation, including after a service start failure. */
>     static void release(String id) {
>         OWNER.release(id);
>     }
>
>     static String owner() {
>         return OWNER.get();
>     }
>
>     @Override
>     public int onStartCommand(Intent intent, int flags, int startId) {
>         String action = intent == null ? null : intent.getAction();
>         if (ACTION_START.equals(action) && !running) {
>             id = intent.getStringExtra("id");
>             if (id == null || !id.equals(OWNER.get())) {
>                 // Started with startForegroundService(): enter the foreground before stopping even
>                 // here (no owner, e.g. a stop that overtook this start), or Android 8+ kills the
>                 // app with ForegroundServiceDidNotStartInTimeException.
>                 try {
>                     startInForeground();
>                 } catch (RuntimeException ignored) {
>                     // A refused foreground start leaves nothing to clean up beyond stopping.
>                 }
>                 id = null;
>                 stopEverything(startId);
>                 return START_NOT_STICKY;
>             }
>             try {
>                 // Inside the failure path: a refused foreground start must not leave "starting" behind.
>                 startInForeground();
>                 recorder = Build.VERSION.SDK_INT >= 31 ? new MediaRecorder(this) : new MediaRecorder();
>                 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
>                 recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
>                 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
>                 recorder.setAudioSamplingRate(44100);
>                 recorder.setAudioChannels(1);
>                 recorder.setOutputFile(RecorderStore.audioFile(this, id).getAbsolutePath());
>                 recorder.prepare();
>                 recorder.start();
>                 running = true;
>                 startedAt = SystemClock.elapsedRealtime();
>             } catch (Exception e) {
>                 // Capture never finalized: "record_failed" (never captureFinal), so upload refuses it.
>                 save(id, "failed", RecorderStore.captureFailed());
>                 stopEverything(startId);
>                 return START_NOT_STICKY;
>             }
>             // Recording either way: an unsaved "recording" is reported, and the stop saves over it.
>             save(id, "recording", null);
>         } else if (ACTION_STOP.equals(action) && running && id != null && id.equals(intent.getStringExtra("id"))) {
>             finishRecording(startId);
>         } else if (ACTION_STOP.equals(action) && !running) {
>             // A stop for the owner that reached the service before its start did: cancel it, so the
>             // start that follows finds no owner and never opens the microphone.
>             String stopId = intent.getStringExtra("id");
>             if (OWNER.release(stopId)) {
>                 save(stopId, "failed", null);
>             }
>             stopEverything(startId);
>         } else if (!running) {
>             stopEverything(startId);
>         }
>         return START_NOT_STICKY;
>     }
>
>     private void startInForeground() {
>         NotificationManager nm = getSystemService(NotificationManager.class);
>         if (Build.VERSION.SDK_INT >= 26 && nm.getNotificationChannel(CHANNEL) == null) {
>             nm.createNotificationChannel(new NotificationChannel(CHANNEL, "Recording", NotificationManager.IMPORTANCE_LOW));
>         }
>         PendingIntent stop = PendingIntent.getBroadcast(this, 0, new Intent(this, StopReceiver.class),
>                 PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
>         Notification n = new NotificationCompat.Builder(this, CHANNEL)
>                 .setSmallIcon(android.R.drawable.ic_btn_speak_now)
>                 .setContentTitle("Recording")
>                 .setOngoing(true)
>                 .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
>                 .addAction(0, "Stop", stop)
>                 .build();
>         int type = Build.VERSION.SDK_INT >= 30 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE : 0;
>         ServiceCompat.startForeground(this, NOTIFICATION_ID, n, type);
>     }
>
>     /** {@code startId} is the command being handled, or {@link #DESTROYING} from onDestroy. */
>     private void finishRecording(int startId) {
>         long duration = SystemClock.elapsedRealtime() - startedAt;
>         try {
>             recorder.stop();
>         } catch (RuntimeException e) {
>             // stop() throws when no audio was captured; the file is unusable either way, and it is
>             // never marked captureFinal, so neither the upload route nor the worker sends it.
>             save(id, "failed", RecorderStore.captureFailed());
>             stopEverything(startId);
>             return;
>         }
>         JSONObject extra = new JSONObject();
>         try {
>             // captureFinal only here, in the same write as "stopped": stop() returned, the container is final.
>             extra.put("durationMs", duration).put("bytes", RecorderStore.audioFile(this, id).length())
>                     .put(RecorderStore.CAPTURE_FINAL, true);
>         } catch (JSONException ignored) {
>             // put() with a non-null key and a long cannot throw.
>         }
>         if (save(id, "stopped", extra)) {
>             try {
>                 UploadWorker.enqueue(this, id);
>             } catch (RecorderStore.StorageException e) {
>                 RecorderStore.notSaved(id, "uploading", e);
>                 UploadWorker.schedule(this, id, null);
>             }
>         } else {
>             // The file is final: the worker uploads it and retries its own index write until
>             // storage recovers, rather than stranding it as "recording".
>             UploadWorker.schedule(this, id, null);
>         }
>         stopEverything(startId);
>     }
>
>     /** False, after reporting it as not durable, when the state could not be saved. */
>     private boolean save(String recordingId, String state, JSONObject extra) {
>         try {
>             // Null: the recording is no longer in the index (discarded); nothing was written.
>             return RecorderStore.update(this, recordingId, state, extra) != null;
>         } catch (RecorderStore.StorageException e) {
>             RecorderStore.notSaved(recordingId, state, e);
>             return false;
>         }
>     }
>
>     /** onDestroy's finish: the service is already being destroyed, so no stop request is made. */
>     private static final int DESTROYING = Integer.MIN_VALUE;
>
>     /**
>      * Ends this command's work. Stops the service only by {@code stopSelfResult} with this command's id: when
>      * a newer command (a START for the next recording) is already delivered, the service stays for
>      * it, so cleanup of an older command can never end a newer recording.
>      */
>     private void stopEverything(int startId) {
>         if (recorder != null) {
>             recorder.release();
>             recorder = null;
>         }
>         running = false;
>         release(id);
>         id = null;
>         ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE);
>         if (startId != DESTROYING) stopSelfResult(startId);
>     }
>
>     @Override
>     public void onDestroy() {
>         if (running) finishRecording(DESTROYING);
>         super.onDestroy();
>     }
>
>     @Override
>     public IBinder onBind(Intent intent) {
>         return null;
>     }
> }
> ```
>
> ```java android/recorder/java/despia/ext/recorder/RecorderStore.java theme={null}
> package despia.ext.recorder;
>
> import android.appwidget.AppWidgetManager;
> import android.content.ComponentName;
> import android.content.Context;
> import android.content.Intent;
> import android.util.Log;
>
> import org.json.JSONException;
> import org.json.JSONObject;
>
> import java.io.ByteArrayOutputStream;
> import java.io.File;
> import java.io.FileInputStream;
> import java.io.FileOutputStream;
> import java.io.IOException;
> import java.nio.charset.StandardCharsets;
> import java.util.Arrays;
> import java.util.UUID;
>
> /**
>  * Index of recordings, shared by the extension, the service, the worker and the widget.
>  *
>  * <p>Durability contract. An absent index reads as empty. An index that cannot be read (I/O error,
>  * permission, not a file) is never overwritten: reads and writes throw {@link StorageException}
>  * with reason {@code index_unreadable}. An index that reads but is not a JSON index is copied
>  * aside byte for byte to {@code index.unreadable-<uuid>.json} (synced) and only then replaced by a
>  * fresh index that carries {@code indexRecovered: "moved_aside"}, so the fact survives a crash and
>  * every later launch: the aside copy may list recordings this index no longer knows, and callers
>  * report that ({@link #recovered}) instead of a plain "idle" or "not found". The flag is never
>  * cleared by the app. java.io only (minSdk 24 has no java.nio.file). Every
>  * write is a read-modify-write of the index just read, under the class lock, through a synced temp
>  * file and a rename; {@link #update} returns a snapshot only once that rename succeeded and throws
>  * otherwise ({@code index_write_failed}, {@code index_encode_failed}).
>  *
>  * <p>Callers surface a failure instead of claiming the state: bridge routes reply {@code
>  * storage_failed}; the service, the worker and launch recovery emit the state they could not save
>  * with {@code durable:false} and {@code storage:<reason>} ({@link #notSaved}); the worker retries.
>  *
>  * <p>One process (no component sets android:process, WorkManager runs in the default process), so
>  * the class lock serializes every caller and no file lock is needed.
>  *
>  * <p>Records are created only by {@link #create} (the start route). {@link #update} of an id the
>  * index does not hold returns null and writes nothing, so a late writer (a stopped worker, a
>  * service finishing after a discard) can never bring a discarded recording back.
>  *
>  * <p>Uploads. {@link #claimUpload} is the only way a worker run gets a record: the record must
>  * exist, must not be a tombstone, and must carry the generation its work request was enqueued with
>  * ({@code uploadGen}, written by every enqueue). The run is then the record's only writer
>  * ({@link #settleUpload}) until a later run of the same work claims the record or an enqueue
>  * replaces the generation; a run whose claim was taken writes nothing. A run WorkManager stopped
>  * keeps its claim until then, so it may still settle a response it actually received (delivery is
>  * at least once; a rerun then finds the record no longer uploading and claims nothing). Run claims
>  * are in memory: a process death ends every thread that could hold one.
>  *
>  * <p>Re-upload ({@link #requeue}) checks that the record is still failed or uploaded and moves it to
>  * uploading with the new URL, its route and a new generation in one step under the class lock, so
>  * a discard that lands in between can never be overwritten.
>  */
> final class RecorderStore {
>     interface Listener {
>         void changed(JSONObject snapshot);
>     }
>
>     static final class StorageException extends Exception {
>         final String reason;
>
>         StorageException(String reason, Throwable cause) {
>             super(reason, cause);
>             this.reason = reason;
>         }
>     }
>
>     private static final String TAG = "NXRecorder";
>     private static volatile Listener listener;
>
>     static void setListener(Listener l) {
>         listener = l;
>     }
>
>     static File dir(Context c) {
>         File d = new File(c.getFilesDir(), "nativeext/recorder");
>         //noinspection ResultOfMethodCallIgnored
>         d.mkdirs();
>         return d;
>     }
>
>     /** The recording's file, without creating its directory (workers and recovery only read). */
>     static File existingAudioFile(Context c, String id) {
>         return new File(new File(dir(c), id), "audio.m4a");
>     }
>
>     /** The recording's file; creates its directory. The service only, for the recording it owns. */
>     static File audioFile(Context c, String id) {
>         File d = new File(dir(c), id);
>         //noinspection ResultOfMethodCallIgnored
>         d.mkdirs();
>         return new File(d, "audio.m4a");
>     }
>
>     static String newId() {
>         return UUID.randomUUID().toString();
>     }
>
>     static final String RECOVERED = "indexRecovered";
>
>     /**
>      * Internal record field, written true only together with "stopped" after MediaRecorder.stop()
>      * returned (the container is final). Never written false, never in a snapshot. Upload eligibility.
>      */
>     static final String CAPTURE_FINAL = "captureFinal";
>
>     /** True when the recording's capture finalized; legacy records witness it by durationMs. */
>     static boolean captureFinal(JSONObject r) {
>         // Before captureFinal existed, durationMs was written only with "stopped" after a successful
>         // stop(); no failure path wrote it. A record with neither is refused (fail closed).
>         return r != null && (r.optBoolean(CAPTURE_FINAL) || r.has("durationMs"));
>     }
>
>     /** The extra for a capture that failed: "failed" with reason record_failed, never captureFinal. */
>     static JSONObject captureFailed() {
>         try {
>             return new JSONObject().put("reason", "record_failed");
>         } catch (JSONException impossible) {
>             throw new IllegalStateException(impossible);
>         }
>     }
>
>     /** Launch recovery that could not read the index yet; run once by the next successful load. */
>     private static Runnable pendingRecovery;
>
>     static synchronized void armRecovery(Runnable r) {
>         pendingRecovery = r;
>     }
>
>     static synchronized JSONObject load(Context c) throws StorageException {
>         JSONObject all = loadOnce(c);
>         Runnable r = pendingRecovery;
>         if (r == null) return all;
>         pendingRecovery = null;
>         r.run();
>         // Re-read: the caller must build on what recovery wrote, never on the copy read before it.
>         return loadOnce(c);
>     }
>
>     private static JSONObject loadOnce(Context c) throws StorageException {
>         File d = dir(c);
>         File f = new File(d, "index.json");
>         byte[] bytes;
>         try {
>             bytes = read(d, f);
>         } catch (IOException | SecurityException e) {
>             throw new StorageException("index_unreadable", e);
>         }
>         if (bytes == null) return new JSONObject();
>         try {
>             JSONObject all = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
>             if (!all.has("records") || all.optJSONObject("records") != null) return all;
>         } catch (JSONException e) {
>             // Falls through to set it aside.
>         }
>         File aside = asideCopy(d, bytes);
>         JSONObject fresh;
>         try {
>             fresh = new JSONObject().put(RECOVERED, "moved_aside");
>         } catch (JSONException impossible) {
>             throw new IllegalStateException(impossible);
>         }
>         write(d, fresh.toString().getBytes(StandardCharsets.UTF_8));
>         Log.w(TAG, "recorder index did not parse; moved aside to " + aside.getName() + ", starting a fresh index");
>         return fresh;
>     }
>
>     /** The index bytes; null only when the directory lists no index.json (a dangling link is listed). */
>     private static byte[] read(File d, File f) throws IOException {
>         if (!f.exists()) {
>             String[] names = d.list();
>             if (names == null) throw new IOException("the recorder directory cannot be listed");
>             if (Arrays.asList(names).contains("index.json")) throw new IOException("index.json is listed but cannot be read");
>             return null;
>         }
>         try (FileInputStream in = new FileInputStream(f)) {
>             ByteArrayOutputStream out = new ByteArrayOutputStream();
>             byte[] buf = new byte[16 * 1024];
>             int n;
>             while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
>             return out.toByteArray();
>         }
>     }
>
>     /** A synced byte-for-byte copy of an index that is not an index; an identical earlier copy is reused. */
>     private static File asideCopy(File d, byte[] bytes) throws StorageException {
>         String[] names = d.list();
>         if (names != null) {
>             for (String n : names) {
>                 if (!n.startsWith("index.unreadable-") || !n.endsWith(".json")) continue;
>                 File old = new File(d, n);
>                 try {
>                     if (Arrays.equals(bytes, read(d, old))) return old;
>                 } catch (IOException | SecurityException e) {
>                     // Not comparable; a new copy is written.
>                 }
>             }
>         }
>         File aside = new File(d, "index.unreadable-" + UUID.randomUUID() + ".json");
>         try (FileOutputStream out = new FileOutputStream(aside)) {
>             out.write(bytes);
>             out.getFD().sync();
>         } catch (IOException | SecurityException e) {
>             //noinspection ResultOfMethodCallIgnored
>             aside.delete();
>             throw new StorageException("index_unreadable", e);
>         }
>         return aside;
>     }
>
>     /** "moved_aside" when an unreadable index was set aside on this install; otherwise null. */
>     static synchronized String recovered(Context c) throws StorageException {
>         JSONObject all = load(c);
>         return all.has(RECOVERED) ? all.optString(RECOVERED) : null;
>     }
>
>     static synchronized JSONObject get(Context c, String id) throws StorageException {
>         JSONObject all = load(c);
>         String key = id != null ? id : all.optString("latest", null);
>         if (key == null) return null;
>         JSONObject recs = all.optJSONObject("records");
>         return recs == null ? null : recs.optJSONObject(key);
>     }
>
>     /** A new record (the start route). Returns the saved snapshot; throws when nothing was saved. */
>     static synchronized JSONObject create(Context c, String id, String state, JSONObject extra) throws StorageException {
>         return apply(c, id, state, extra, true);
>     }
>
>     /**
>      * A null state removes the record. Returns the saved snapshot, or null when the index does not
>      * hold {@code id} (nothing is written); throws when nothing was saved. A value of
>      * {@link JSONObject#NULL} in {@code extra} removes that field.
>      */
>     static synchronized JSONObject update(Context c, String id, String state, JSONObject extra) throws StorageException {
>         return apply(c, id, state, extra, false);
>     }
>
>     private static JSONObject apply(Context c, String id, String state, JSONObject extra, boolean create) throws StorageException {
>         JSONObject all = load(c);
>         JSONObject snap;
>         try {
>             JSONObject recs = all.optJSONObject("records");
>             if (recs == null) {
>                 recs = new JSONObject();
>                 all.put("records", recs);
>             }
>             if (state == null) {
>                 recs.remove(id);
>                 if (id.equals(all.optString("latest", null))) all.remove("latest");
>                 snap = new JSONObject().put("recordingId", id).put("state", "discarded");
>             } else {
>                 JSONObject r = recs.optJSONObject(id);
>                 if (r == null) {
>                     if (!create) return null;
>                     r = new JSONObject().put("recordingId", id).put("startedAt", System.currentTimeMillis());
>                     recs.put(id, r);
>                     all.put("latest", id);
>                 }
>                 r.put("state", state);
>                 if (extra != null) {
>                     for (java.util.Iterator<String> it = extra.keys(); it.hasNext(); ) {
>                         String k = it.next();
>                         Object v = extra.get(k);
>                         if (v == JSONObject.NULL) r.remove(k);
>                         else r.put(k, v);
>                     }
>                 }
>                 snap = snapshot(r);
>             }
>             if (all.has(RECOVERED)) snap.put(RECOVERED, all.optString(RECOVERED));
>         } catch (JSONException e) {
>             throw new StorageException("index_encode_failed", e);
>         }
>         write(dir(c), all.toString().getBytes(StandardCharsets.UTF_8));
>         Listener l = listener;
>         if (l != null) l.changed(snap);
>         refreshWidget(c);
>         return snap;
>     }
>
>     private static void write(File d, byte[] data) throws StorageException {
>         File f = new File(d, "index.json");
>         File tmp = new File(d, "index.json.tmp");
>         try {
>             try (FileOutputStream out = new FileOutputStream(tmp)) {
>                 out.write(data);
>                 out.getFD().sync();
>             }
>             if (!tmp.renameTo(f)) throw new IOException("rename failed");
>         } catch (IOException | SecurityException e) {
>             //noinspection ResultOfMethodCallIgnored
>             if (tmp.isFile()) tmp.delete();
>             throw new StorageException("index_write_failed", e);
>         }
>     }
>
>     private static final java.util.Map<String, String> RUNS = new java.util.HashMap<>();
>
>     /**
>      * A 2xx this process received for a record of generation {@code gen} whose "uploaded" write
>      * failed (id -> generation and HTTP status). The next run of that generation saves "uploaded"
>      * from it instead of sending the body again, so the page's non-durable "uploaded" is followed by
>      * the durable one rather than by a second transfer that could fail. In memory only: after a
>      * process death the record is still "uploading" on disk and is uploaded again (at least once).
>      */
>     private static final java.util.Map<String, String[]> RECEIVED = new java.util.HashMap<>();
>
>     static synchronized void receivedUnsaved(String id, String gen, int status) {
>         RECEIVED.put(id, new String[]{gen, Integer.toString(status)});
>     }
>
>     /** The HTTP status of an unsaved 2xx for this record and generation, or -1. */
>     static synchronized int receivedFor(String id, String gen) {
>         String[] g = RECEIVED.get(id);
>         return g != null && g[0].equals(String.valueOf(gen)) ? Integer.parseInt(g[1]) : -1;
>     }
>
>     static synchronized void clearReceived(String id) {
>         RECEIVED.remove(id);
>     }
>
>     /**
>      * Claims {@code id} for one worker run. Returns the record, or null when this run may not
>      * upload it (nothing is written): the record is gone or a tombstone, its {@code uploadGen} is not
>      * {@code gen} (the work was replaced), or it is not waiting for an upload. A null {@code gen} is a
>      * request with no generation (enqueued before generations existed, or scheduled by the service
>      * after the "uploading" write failed); it may claim only a record that has none either, and a
>      * "stopped" or "recording" one is moved to "uploading" here. A later claim of the same record
>      * takes it from an earlier run.
>      */
>     static synchronized JSONObject claimUpload(Context c, String id, String gen, String run) throws StorageException {
>         JSONObject r = get(c, id);
>         if (r == null) return null;
>         String state = r.optString("state");
>         String has = r.has("uploadGen") ? r.optString("uploadGen") : null;
>         if (has == null ? gen != null : !has.equals(gen)) return null;
>         if (!"uploading".equals(state)) {
>             if (gen != null || !("stopped".equals(state) || "recording".equals(state))) return null;
>             // Null-generation work is scheduled only after a successful stop() (the service's
>             // fallbacks when its own index write failed): the capture is final, and the claim says so.
>             JSONObject fin;
>             try {
>                 fin = new JSONObject().put(CAPTURE_FINAL, true);
>             } catch (JSONException impossible) {
>                 throw new IllegalStateException(impossible);
>             }
>             r = update(c, id, "uploading", fin);
>             if (r == null) return null;
>             r = get(c, id);
>         }
>         RUNS.put(id, run);
>         return r;
>     }
>
>     /**
>      * Saves a state for the run that holds the claim. Returns the snapshot, or null (nothing written)
>      * when the claim is gone: a later run took it, the work was replaced, the record was discarded
>      * or is a tombstone, or it is no longer "uploading". Throws when nothing was saved.
>      */
>     static synchronized JSONObject settleUpload(Context c, String id, String gen, String run, String state, JSONObject extra)
>             throws StorageException {
>         if (!run.equals(RUNS.get(id))) return null;
>         JSONObject r = get(c, id);
>         if (r == null || !"uploading".equals(r.optString("state"))) return null;
>         String has = r.has("uploadGen") ? r.optString("uploadGen") : null;
>         if (has == null ? gen != null : !has.equals(gen)) return null;
>         return update(c, id, state, extra);
>     }
>
>     /**
>      * The upload route's transition: only a record that is still "failed" or "uploaded" becomes
>      * "uploading" with {@code fields} (the new URL, its route and a new generation), in one step
>      * under the class lock. Returns the snapshot; null when the index does not hold the id; the
>      * record's snapshot with {@code busy: true} when it is in any other state (a tombstone included),
>      * in which case nothing is written; the record's snapshot with {@code notFinal: true} when its
>      * capture never finalized (a failed start or stop: there is no audio to send), nothing written.
>      * Throws when nothing was saved.
>      */
>     static synchronized JSONObject requeue(Context c, String id, JSONObject fields) throws StorageException {
>         JSONObject r = get(c, id);
>         if (r == null) return null;
>         String s = r.optString("state");
>         try {
>             if (!"failed".equals(s) && !"uploaded".equals(s)) return snapshot(r).put("busy", true);
>             if (!captureFinal(r)) return snapshot(r).put("notFinal", true);
>         } catch (JSONException impossible) {
>             throw new IllegalStateException(impossible);
>         }
>         return update(c, id, "uploading", fields);
>     }
>
>     /**
>      * The service's and reconciliation's transition to "uploading" with generation {@code gen}: only
>      * a finalized record that is "stopped", or "uploading" without a generation (a null-generation
>      * claim), moves; anything else (a tombstone, a terminal state, a newer generation) returns null
>      * and writes nothing. Throws when nothing was saved.
>      */
>     static synchronized JSONObject beginUpload(Context c, String id, String gen) throws StorageException {
>         JSONObject r = get(c, id);
>         if (r == null || !captureFinal(r)) return null;
>         String s = r.optString("state");
>         boolean noGen = !r.has("uploadGen");
>         if (!("stopped".equals(s) || ("uploading".equals(s) && noGen))) return null;
>         try {
>             return update(c, id, "uploading", new JSONObject().put("uploadGen", gen));
>         } catch (JSONException impossible) {
>             throw new IllegalStateException(impossible);
>         }
>     }
>
>     /**
>      * WorkManager refused to enqueue generation {@code gen}: the still-"uploading" record of that
>      * generation becomes "failed" with reason not_scheduled (retryable by upload, discardable), so it
>      * is never stranded as uploading. Anything else is left alone. Throws when nothing was saved.
>      */
>     static synchronized JSONObject failUnscheduled(Context c, String id, String gen) throws StorageException {
>         JSONObject r = get(c, id);
>         if (r == null || !"uploading".equals(r.optString("state")) || !gen.equals(r.optString("uploadGen", null))) return null;
>         try {
>             return update(c, id, "failed", new JSONObject().put("reason", "not_scheduled"));
>         } catch (JSONException impossible) {
>             throw new IllegalStateException(impossible);
>         }
>     }
>
>     /** A copy of every record (id -> record) for launch reconciliation. */
>     static synchronized java.util.Map<String, JSONObject> records(Context c) throws StorageException {
>         java.util.Map<String, JSONObject> out = new java.util.LinkedHashMap<>();
>         JSONObject recs = load(c).optJSONObject("records");
>         if (recs == null) return out;
>         for (java.util.Iterator<String> it = recs.keys(); it.hasNext(); ) {
>             String k = it.next();
>             JSONObject r = recs.optJSONObject(k);
>             if (r == null) continue;
>             try {
>                 out.put(k, new JSONObject(r.toString()));
>             } catch (JSONException impossible) {
>                 throw new IllegalStateException(impossible);
>             }
>         }
>         return out;
>     }
>
>     static synchronized void releaseUpload(String id, String run) {
>         if (run.equals(RUNS.get(id))) RUNS.remove(id);
>     }
>
>     /**
>      * Crash-consistent discard. The record is first saved as a "discarding" tombstone, then the
>      * audio file and its directory are deleted, and only then is the record removed. A process
>      * death at any point leaves either the recording intact, or a tombstone that
>      * {@link #recoverDiscards} finishes; audio is never left on disk without an index entry.
>      *
>      * @return the discarded snapshot (marked not durable when the final removal could not be
>      *     saved; the tombstone then stays for recovery), or null when removal was not established:
>      *     the directory could not be deleted, or its absence could not be confirmed because the
>      *     recorder directory cannot be listed. The tombstone stays, and discard or recovery retries. A record that
>      *     became busy (recording, starting, uploading) since the caller looked is not touched: the
>      *     reply is its snapshot with {@code busy: true}.
>      * @throws StorageException when the tombstone could not be saved: nothing changed.
>      */
>     static JSONObject discard(Context c, String id) throws StorageException {
>         synchronized (RecorderStore.class) {
>             JSONObject r = get(c, id);
>             String s = r == null ? null : r.optString("state");
>             if ("recording".equals(s) || "starting".equals(s) || "uploading".equals(s)) {
>                 try {
>                     return snapshot(r).put("busy", true);
>                 } catch (JSONException impossible) {
>                     throw new IllegalStateException(impossible);
>                 }
>             }
>             if (r != null && !"discarding".equals(s)) update(c, id, "discarding", null);
>         }
>         File parent = dir(c);
>         File d = new File(parent, id);
>         // The tombstoned recording's own directory only: its files, then the directory.
>         File[] own = d.listFiles();
>         if (own != null) {
>             for (File f : own) {
>                 //noinspection ResultOfMethodCallIgnored
>                 f.delete();
>             }
>         }
>         if (!d.delete()) {
>             // Not deleted by this call. Absence counts only when the recorder directory was listed
>             // and does not name it: File.exists() is also false when the lookup itself fails, so it
>             // never decides. Unlistable or still listed: removal not established, tombstone kept.
>             String[] names = parent.list();
>             if (names == null || Arrays.asList(names).contains(id)) return null;
>         }
>         try {
>             return update(c, id, null, null);
>         } catch (StorageException e) {
>             notSaved(id, "discarded", e);
>             try {
>                 return new JSONObject().put("recordingId", id).put("state", "discarded")
>                         .put("durable", false).put("storage", e.reason);
>             } catch (JSONException impossible) {
>                 throw new IllegalStateException(impossible);
>             }
>         }
>     }
>
>     /** Finishes every discard a previous process left as a tombstone; returns the ids finished. */
>     static java.util.List<String> recoverDiscards(Context c) throws StorageException {
>         JSONObject recs = load(c).optJSONObject("records");
>         java.util.List<String> done = new java.util.ArrayList<>();
>         if (recs == null) return done;
>         for (java.util.Iterator<String> it = recs.keys(); it.hasNext(); ) {
>             String id = it.next();
>             JSONObject r = recs.optJSONObject(id);
>             if (r != null && "discarding".equals(r.optString("state"))) done.add(id);
>         }
>         java.util.List<String> finished = new java.util.ArrayList<>();
>         for (String id : done) {
>             if (discard(c, id) != null) finished.add(id);
>         }
>         return finished;
>     }
>
>     /** Logs and emits a state the index does not hold, marked not durable. */
>     static void notSaved(String id, String state, StorageException e) {
>         Log.w(TAG, "recorder index not saved: " + e.reason);
>         Listener l = listener;
>         if (l == null) return;
>         try {
>             l.changed(new JSONObject().put("recordingId", id).put("state", state)
>                     .put("durable", false).put("storage", e.reason));
>         } catch (JSONException ignored) {
>             // put() with non-null keys and string or boolean values cannot throw.
>         }
>     }
>
>     static JSONObject snapshot(JSONObject r) throws JSONException {
>         JSONObject s = new JSONObject();
>         s.put("recordingId", r.optString("recordingId"));
>         s.put("state", r.optString("state", "idle"));
>         s.put("durationMs", r.optLong("durationMs", 0));
>         s.put("bytes", r.optLong("bytes", 0));
>         if (r.has("httpStatus")) s.put("httpStatus", r.optInt("httpStatus"));
>         // Why a record failed (url_not_approved, no_file, http, network, policy_unavailable, and on Android
>         // record_failed for a capture that never finalized and not_scheduled for an upload WorkManager refused).
>         if ("failed".equals(r.optString("state")) && r.has("reason")) s.put("reason", r.optString("reason"));
>         return s;
>     }
>
>     static void refreshWidget(Context c) {
>         AppWidgetManager m = AppWidgetManager.getInstance(c);
>         int[] ids = m.getAppWidgetIds(new ComponentName(c, StatusWidgetProvider.class));
>         if (ids.length == 0) return;
>         Intent i = new Intent(c, StatusWidgetProvider.class).setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
>                 .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
>         c.sendBroadcast(i);
>     }
>
>     private RecorderStore() {
>     }
> }
> ```
>
> ```java android/recorder/java/despia/ext/recorder/StatusWidgetProvider.java theme={null}
> package despia.ext.recorder;
>
> import android.appwidget.AppWidgetManager;
> import android.appwidget.AppWidgetProvider;
> import android.content.Context;
> import android.widget.RemoteViews;
>
> import org.json.JSONObject;
>
> /** Home-screen (and, where the device supports it, keyguard) status widget. */
> public final class StatusWidgetProvider extends AppWidgetProvider {
>     @Override
>     public void onUpdate(Context context, AppWidgetManager manager, int[] ids) {
>         JSONObject r;
>         try {
>             r = RecorderStore.get(context, null);
>         } catch (RecorderStore.StorageException e) {
>             // Unknown is not idle: keep what the widget shows until the index reads again.
>             return;
>         }
>         String state = r == null ? "idle" : r.optString("state", "idle");
>         for (int id : ids) {
>             RemoteViews v = new RemoteViews(context.getPackageName(), R.layout.nx_recorder_widget);
>             v.setTextViewText(R.id.nx_recorder_state, label(state));
>             manager.updateAppWidget(id, v);
>         }
>     }
>
>     static String label(String state) {
>         switch (state) {
>             case "recording": return "Recording";
>             case "interrupted": return "Paused";
>             case "uploading": return "Uploading";
>             case "uploaded": return "Uploaded";
>             case "failed": return "Upload failed";
>             case "stopped": return "Stopped";
>             default: return "Idle";
>         }
>     }
> }
> ```
>
> ```java android/recorder/java/despia/ext/recorder/StopReceiver.java theme={null}
> package despia.ext.recorder;
>
> import android.content.BroadcastReceiver;
> import android.content.Context;
> import android.content.Intent;
>
> /** Notification "Stop" action. Not exported: only this app's PendingIntent can reach it. */
> public final class StopReceiver extends BroadcastReceiver {
>     @Override
>     public void onReceive(Context context, Intent intent) {
>         if (RecorderService.isRunning()) {
>             context.startService(new Intent(context, RecorderService.class).setAction(RecorderService.ACTION_STOP)
>                     .putExtra("id", RecorderService.owner()));
>         }
>     }
> }
> ```
>
> ```java android/recorder/java/despia/ext/recorder/UploadWorker.java theme={null}
> package despia.ext.recorder;
>
> import android.content.Context;
>
> import androidx.annotation.NonNull;
> import androidx.core.content.ContextCompat;
> import androidx.work.Constraints;
> import androidx.work.Data;
> import androidx.work.ExistingWorkPolicy;
> import androidx.work.NetworkType;
> import androidx.work.OneTimeWorkRequest;
> import androidx.work.Operation;
> import androidx.work.WorkInfo;
> import androidx.work.WorkManager;
> import androidx.work.Worker;
> import androidx.work.WorkerParameters;
>
> import com.despia.nativeext.ExtContext;
> import com.google.common.util.concurrent.ListenableFuture;
>
> import org.json.JSONException;
> import org.json.JSONObject;
>
> import java.io.File;
> import java.io.FileInputStream;
> import java.io.IOException;
> import java.io.InputStream;
> import java.io.OutputStream;
> import java.net.HttpURLConnection;
> import java.net.MalformedURLException;
> import java.net.URI;
> import java.net.URISyntaxException;
> import java.net.URL;
> import java.util.List;
> import java.util.Locale;
> import java.util.Map;
> import java.util.Set;
> import java.util.UUID;
> import java.util.concurrent.ConcurrentHashMap;
>
> /**
>  * Uploads a finished recording from disk; survives process death and reboot.
>  *
>  * <p>Delivery is at least once (the PUT is idempotent). Authority over the record is the
>  * generation written by {@link #enqueue} or {@link #requeue} and the run claim in
>  * {@link RecorderStore#claimUpload}: WorkManager does not interrupt a stopped Worker's thread and may
>  * start the next run, or a replacement, while it is still blocked, so only the run holding the
>  * claim writes a state. A stopped run that still holds the claim may settle a response it really
>  * received; once a rerun or a replacement takes the claim, the stopped run writes nothing.
>  */
> public final class UploadWorker extends Worker {
>     /** Counted upload attempts (network errors and 5xx), the same budget as iOS. */
>     static final int MAX_ATTEMPTS = 5;
>     /** Runs that find the extension not yet registered (or failed to register) before failing. */
>     static final int MAX_POLICY_WAITS = 10;
>     static final int CONNECT_TIMEOUT_MS = 30_000;
>     /** Per read, as iOS timeoutIntervalForRequest; a stalled body write ends through onStopped. */
>     static final int READ_TIMEOUT_MS = 60_000;
>
>     private volatile HttpURLConnection inFlight;
>
>     public UploadWorker(@NonNull Context context, @NonNull WorkerParameters params) {
>         super(context, params);
>     }
>
>     /** Tag on every request; with {@link #GEN_TAG} + generation it names the request's generation. */
>     static final String TAG = "nx-recorder";
>     static final String GEN_TAG = "nx-gen:";
>
>     /**
>      * Generations this process wrote and scheduled (or is scheduling). Launch reconciliation leaves
>      * them alone; a generation found "uploading" on disk that is not here was written by an earlier
>      * process, whose request may never have been committed.
>      */
>     static final Set<String> LIVE = ConcurrentHashMap.newKeySet();
>
>     /** Told, on the main thread, whether WorkManager committed the request. */
>     interface Scheduled {
>         void done(boolean ok);
>     }
>
>     /** The upload route's answer: whether the request was committed, with the saved snapshot. */
>     interface Queued {
>         void done(boolean ok, JSONObject snapshot);
>     }
>
>     static String uniqueName(String id) {
>         return "nx-recorder-" + id;
>     }
>
>     /**
>      * The service's handoff after a successful stop: a finalized "stopped" record moves to
>      * "uploading" with a fresh generation (one guarded store step), then the work is enqueued and its
>      * result observed. Returns null, scheduling nothing, when the record is gone or not eligible
>      * (a tombstone, a terminal state, not finalized). An enqueue WorkManager refuses settles the
>      * record as failed/not_scheduled, never stranded as uploading.
>      */
>     static JSONObject enqueue(Context c, String id) throws RecorderStore.StorageException {
>         String gen = UUID.randomUUID().toString();
>         LIVE.add(gen);
>         JSONObject snap;
>         try {
>             snap = RecorderStore.beginUpload(c, id, gen);
>         } catch (RecorderStore.StorageException e) {
>             LIVE.remove(gen);
>             throw e;
>         }
>         if (snap == null) {
>             LIVE.remove(gen);
>             return null;
>         }
>         observe(c, id, gen, schedule(c, id, gen), null);
>         return snap;
>     }
>
>     /**
>      * The upload route: a still failed or uploaded, finalized record moves to uploading with the new
>      * URL, the route that approved it and a fresh generation in one store step, and only then is the
>      * work enqueued; {@code then} hears, on the main thread, whether WorkManager committed it.
>      * Returns null (unknown), a busy snapshot or a notFinal snapshot without scheduling anything (and
>      * without calling {@code then}).
>      */
>     static JSONObject requeue(Context c, String id, String url, String route, Queued then) throws RecorderStore.StorageException {
>         String gen = UUID.randomUUID().toString();
>         JSONObject fields = fields("uploadUrl", url);
>         put(fields, "urlRoute", route);
>         put(fields, "uploadGen", gen);
>         put(fields, "attempts", JSONObject.NULL);
>         put(fields, "reason", JSONObject.NULL);
>         put(fields, "httpStatus", JSONObject.NULL);
>         LIVE.add(gen);
>         JSONObject snap;
>         try {
>             snap = RecorderStore.requeue(c, id, fields);
>         } catch (RecorderStore.StorageException e) {
>             LIVE.remove(gen);
>             throw e;
>         }
>         if (snap == null || snap.optBoolean("busy") || snap.optBoolean("notFinal")) {
>             LIVE.remove(gen);
>             return snap;
>         }
>         final JSONObject saved = snap;
>         observe(c, id, gen, schedule(c, id, gen), ok -> then.done(ok, saved));
>         return snap;
>     }
>
>     /** A null generation only from the service, after its own index write failed. */
>     static Operation schedule(Context c, String id, String gen) {
>         Data.Builder input = new Data.Builder().putString("id", id);
>         if (gen != null) input.putString("gen", gen);
>         OneTimeWorkRequest.Builder b = new OneTimeWorkRequest.Builder(UploadWorker.class)
>                 .setInputData(input.build())
>                 .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
>                 .addTag(TAG);
>         if (gen != null) b.addTag(GEN_TAG + gen);
>         // The newest enqueue owns the record (its generation), so it always replaces.
>         return WorkManager.getInstance(c).enqueueUniqueWork(uniqueName(id), ExistingWorkPolicy.REPLACE, b.build());
>     }
>
>     /**
>      * WorkManager's enqueue is asynchronous and can fail. Its result is read on the main executor
>      * (never blocking the main thread); a refused generation is settled as failed/not_scheduled.
>      */
>     static void observe(Context c, String id, String gen, Operation op, Scheduled then) {
>         ListenableFuture<Operation.State.SUCCESS> result = op.getResult();
>         result.addListener(() -> {
>             boolean ok;
>             try {
>                 result.get();
>                 ok = true;
>             } catch (Exception e) {
>                 ok = false;
>             }
>             if (!ok && gen != null) {
>                 LIVE.remove(gen);
>                 try {
>                     RecorderStore.failUnscheduled(c, id, gen);
>                 } catch (RecorderStore.StorageException e) {
>                     // Still "uploading" on disk: the next launch's reconciliation schedules it.
>                     RecorderStore.notSaved(id, "failed", e);
>                 }
>             }
>             if (then != null) then.done(ok);
>         }, ContextCompat.getMainExecutor(c));
>     }
>
>     /**
>      * Launch reconciliation, on the main thread after recovery: no finalized recording is left
>      * "stopped" or "uploading" without work for its current generation. Unfinished work tagged with
>      * the record's generation is left alone (its claim, attempts and progress untouched); terminal
>      * states (failed, uploaded, terminated, discarding) are never touched. Delivery stays at least
>      * once: a 2xx whose "uploaded" write was lost to a process death is sent again.
>      */
>     static void reconcile(Context c) {
>         Map<String, JSONObject> recs;
>         try {
>             recs = RecorderStore.records(c);
>         } catch (RecorderStore.StorageException e) {
>             return;
>         }
>         for (Map.Entry<String, JSONObject> e : recs.entrySet()) {
>             String id = e.getKey();
>             JSONObject r = e.getValue();
>             // The service is still finishing it.
>             if (id.equals(RecorderService.owner())) continue;
>             String state = r.optString("state");
>             boolean hasGen = r.has("uploadGen");
>             if (("stopped".equals(state) && RecorderStore.captureFinal(r)) || ("uploading".equals(state) && !hasGen)) {
>                 try {
>                     enqueue(c, id);
>                 } catch (RecorderStore.StorageException se) {
>                     RecorderStore.notSaved(id, "uploading", se);
>                 }
>                 continue;
>             }
>             if (!"uploading".equals(state)) continue;
>             String gen = r.optString("uploadGen");
>             if (LIVE.contains(gen)) continue;
>             ListenableFuture<List<WorkInfo>> infos = WorkManager.getInstance(c).getWorkInfosForUniqueWork(uniqueName(id));
>             infos.addListener(() -> {
>                 List<WorkInfo> list;
>                 try {
>                     list = infos.get();
>                 } catch (Exception failed) {
>                     // Unknown: treated as no matching work. A restart is allowed (at least once);
>                     // stranding the recording is not.
>                     list = java.util.Collections.emptyList();
>                 }
>                 JSONObject now;
>                 try {
>                     now = RecorderStore.get(c, id);
>                 } catch (RecorderStore.StorageException se) {
>                     return;
>                 }
>                 if (now == null || !"uploading".equals(now.optString("state")) || !gen.equals(now.optString("uploadGen", null))
>                         || LIVE.contains(gen)) {
>                     return;
>                 }
>                 for (WorkInfo w : list) {
>                     if (!w.getState().isFinished() && w.getTags().contains(GEN_TAG + gen)) return;
>                 }
>                 LIVE.add(gen);
>                 observe(c, id, gen, schedule(c, id, gen), null);
>             }, ContextCompat.getMainExecutor(c));
>         }
>     }
>
>     /** A state the index could not take is retried, never reported as done or dropped. */
>     @NonNull
>     @Override
>     public Result doWork() {
>         Context c = getApplicationContext();
>         String id = getInputData().getString("id");
>         if (id == null) return Result.failure();
>         String gen = getInputData().getString("gen");
>         String run = UUID.randomUUID().toString();
>         JSONObject r;
>         try {
>             r = RecorderStore.claimUpload(c, id, gen, run);
>         } catch (RecorderStore.StorageException e) {
>             return Result.retry();
>         }
>         // Gone, a tombstone, replaced, or not waiting for an upload: nothing to do, nothing written.
>         if (r == null) return Result.failure();
>         try {
>             return upload(c, id, gen, run, r);
>         } finally {
>             RecorderStore.releaseUpload(id, run);
>         }
>     }
>
>     /** Unblocks a run WorkManager stopped (cancelled, replaced, constraints lost, timed out). */
>     @Override
>     public void onStopped() {
>         HttpURLConnection conn = inFlight;
>         if (conn != null) conn.disconnect();
>     }
>
>     private Result upload(Context c, String id, String gen, String run, JSONObject r) {
>         // This generation already got a 2xx in this process and only its "uploaded" write failed:
>         // save it now, without sending the body again.
>         int received = RecorderStore.receivedFor(id, gen);
>         if (received >= 0) {
>             return finish(c, id, gen, run, "uploaded", put(fields("httpStatus", received), "reason", JSONObject.NULL), Result.success());
>         }
>         // The declared route table, registered in Application.onCreate before any WebView exists.
>         ExtContext policy = RecorderExtension.policy();
>         if (policy == null) {
>             if (getRunAttemptCount() < MAX_POLICY_WAITS) return Result.retry();
>             return finish(c, id, gen, run, "failed", fields("reason", "policy_unavailable"), Result.failure());
>         }
>         String target = r.optString("uploadUrl", "");
>         // The route whose https_url rule approved the stored URL; "start" for records saved before urlRoute existed.
>         String route = r.optString("urlRoute", "start");
>         URL url = policy.isApprovedUrl(target, route, "upload") ? destination(target) : null;
>         if (url == null) return finish(c, id, gen, run, "failed", fields("reason", "url_not_approved"), Result.failure());
>         // A capture that never finalized is never sent, not even one already queued (legacy, or
>         // requeued before this check existed): refused before any byte, the record says why.
>         if (!RecorderStore.captureFinal(r)) return finish(c, id, gen, run, "failed", fields("reason", "record_failed"), Result.failure());
>         File f = RecorderStore.existingAudioFile(c, id);
>         if (!f.isFile() || f.length() == 0) return finish(c, id, gen, run, "failed", fields("reason", "no_file"), Result.failure());
>         if (isStopped()) return Result.retry();
>         HttpURLConnection conn = null;
>         try {
>             conn = (HttpURLConnection) url.openConnection();
>             inFlight = conn;
>             if (isStopped()) return Result.retry();
>             conn.setConnectTimeout(CONNECT_TIMEOUT_MS);
>             conn.setReadTimeout(READ_TIMEOUT_MS);
>             conn.setUseCaches(false);
>             conn.setRequestMethod("PUT");
>             conn.setDoOutput(true);
>             conn.setInstanceFollowRedirects(false);
>             conn.setFixedLengthStreamingMode(f.length());
>             conn.setRequestProperty("Content-Type", "audio/mp4");
>             conn.setRequestProperty("X-Recording-Id", id);
>             try (InputStream in = new FileInputStream(f); OutputStream out = conn.getOutputStream()) {
>                 byte[] buf = new byte[64 * 1024];
>                 int n;
>                 while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
>             }
>             int code = conn.getResponseCode();
>             JSONObject status = fields("httpStatus", code);
>             if (code >= 200 && code < 300) {
>                 try {
>                     if (RecorderStore.settleUpload(c, id, gen, run, "uploaded", put(status, "reason", JSONObject.NULL)) == null) {
>                         return Result.failure();
>                     }
>                     RecorderStore.clearReceived(id);
>                     return Result.success();
>                 } catch (RecorderStore.StorageException e) {
>                     // The 2xx is real; only its write failed. Remember it so the rerun saves it
>                     // instead of sending the body again.
>                     RecorderStore.notSaved(id, "uploaded", e);
>                     RecorderStore.receivedUnsaved(id, String.valueOf(gen), code);
>                     return Result.retry();
>                 }
>             }
>             if (code >= 500) return counted(c, id, gen, run, r, "http", code);
>             // 3xx (redirects are never followed) and 4xx are final; "upload" with a fresh URL retries.
>             return finish(c, id, gen, run, "failed", put(status, "reason", "http"), Result.failure());
>         } catch (IOException e) {
>             // Disconnected by onStopped: WorkManager reruns it; not a counted attempt, nothing written.
>             if (isStopped()) return Result.retry();
>             return counted(c, id, gen, run, r, "network", null);
>         } finally {
>             inFlight = null;
>             if (conn != null) conn.disconnect();
>         }
>     }
>
>     /**
>      * A failed attempt that may be retried. The count lives in the record, so runs retried for a
>      * storage failure (or a stop) do not use up the upload budget.
>      */
>     private Result counted(Context c, String id, String gen, String run, JSONObject r, String reason, Integer code) {
>         int attempts = r.optInt("attempts", 0) + 1;
>         JSONObject extra = put(fields("attempts", attempts), "httpStatus", code == null ? JSONObject.NULL : code);
>         // A terminal state only when no retry follows; a pending retry stays "uploading".
>         if (attempts < MAX_ATTEMPTS) return finish(c, id, gen, run, "uploading", extra, Result.retry());
>         return finish(c, id, gen, run, "failed", put(extra, "reason", reason), Result.failure());
>     }
>
>     /** Saves for this run's claim; a run whose claim is gone writes nothing and ends. */
>     private static Result finish(Context c, String id, String gen, String run, String state, JSONObject extra, Result saved) {
>         try {
>             if (RecorderStore.settleUpload(c, id, gen, run, state, extra) == null) return Result.failure();
>             RecorderStore.clearReceived(id);
>             return saved;
>         } catch (RecorderStore.StorageException e) {
>             RecorderStore.notSaved(id, state, e);
>             return Result.retry();
>         }
>     }
>
>     /**
>      * The URL the request is built from, only when java.net.URI's parse agrees with the text the
>      * https_url rule approved (same rule as iOS RecorderUploader.destination): https, no user
>      * info, no fragment, the default port or an explicit 443, and a parsed host of letters, digits,
>      * dots and hyphens equal to the literal host after "https://". Whether that host is approved
>      * is the https_url rule's decision ({@link ExtContext#isApprovedUrl}), made before.
>      */
>     static URL destination(String s) {
>         if (!strictUrlText(s)) return null;
>         try {
>             URI u = new URI(s);
>             if (!"https".equalsIgnoreCase(u.getScheme()) || u.getRawUserInfo() != null || u.getRawFragment() != null) return null;
>             if (u.getPort() != -1 && u.getPort() != 443) return null;
>             String host = u.getHost() == null ? null : u.getHost().toLowerCase(Locale.ROOT);
>             if (host == null || host.isEmpty() || !host.matches("[a-z0-9.-]+")) return null;
>             String lower = s.toLowerCase(Locale.ROOT);
>             if (!lower.startsWith("https://" + host)) return null;
>             String after = lower.substring(("https://" + host).length());
>             if (!(after.isEmpty() || after.startsWith("/") || after.equals(":443") || after.startsWith(":443/"))) return null;
>             return u.toURL();
>         } catch (URISyntaxException | MalformedURLException | IllegalArgumentException e) {
>             return null;
>         }
>     }
>
>     /** RFC 3986 characters plus "%" (checked as an escape by strictUrlText). */
>     private static final String URL_TEXT_CHARS =
>             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
>     private static final String HEX_DIGITS = "0123456789ABCDEFabcdef";
>
>     /**
>      * The raw text, before any parse: ASCII-only RFC 3986 text whose every "%" starts a two-hex-digit
>      * escape (the bridge's own text rule, and iOS RecorderUploader.isStrictURLText). java.net.URI
>      * accepts non-ASCII "other" characters such as U+200B and U+202E in a path, so this check, not
>      * the parse, decides.
>      */
>     static boolean strictUrlText(String s) {
>         if (s == null || s.isEmpty()) return false;
>         for (int i = 0; i < s.length(); ) {
>             char c = s.charAt(i);
>             if (c > 0x7e || URL_TEXT_CHARS.indexOf(c) < 0) return false;
>             if (c == '%') {
>                 if (i + 2 >= s.length() || HEX_DIGITS.indexOf(s.charAt(i + 1)) < 0 || HEX_DIGITS.indexOf(s.charAt(i + 2)) < 0) {
>                     return false;
>                 }
>                 i += 3;
>             } else {
>                 i++;
>             }
>         }
>         return true;
>     }
>
>     private static JSONObject fields(String k, Object v) {
>         return put(new JSONObject(), k, v);
>     }
>
>     private static JSONObject put(JSONObject o, String k, Object v) {
>         try {
>             return o.put(k, v);
>         } catch (JSONException impossible) {
>             throw new IllegalStateException(impossible);
>         }
>     }
> }
> ```
>
> ```xml android/recorder/res/layout/nx_recorder_widget.xml theme={null}
> <?xml version="1.0" encoding="utf-8"?>
> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
>     android:layout_width="match_parent"
>     android:layout_height="match_parent"
>     android:padding="8dp">
>     <TextView
>         android:id="@+id/nx_recorder_state"
>         android:layout_width="wrap_content"
>         android:layout_height="wrap_content"
>         android:layout_gravity="center"
>         android:text="@string/nx_recorder_idle"
>         android:textSize="16sp" />
> </FrameLayout>
> ```
>
> ```xml android/recorder/res/values/nx_recorder_strings.xml theme={null}
> <?xml version="1.0" encoding="utf-8"?>
> <resources>
>     <string name="nx_recorder_idle">Idle</string>
> </resources>
> ```
>
> ```xml android/recorder/res/xml/nx_recorder_widget_info.xml theme={null}
> <?xml version="1.0" encoding="utf-8"?>
> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
>     android:initialLayout="@layout/nx_recorder_widget"
>     android:minWidth="110dp"
>     android:minHeight="40dp"
>     android:resizeMode="horizontal"
>     android:updatePeriodMillis="0"
>     android:widgetCategory="home_screen|keyguard" />
> ```

> [tab] Build policy
>
> ```json recorder.policy.json theme={null}
> {
>   "exposed_components": {
>     "android": [
>       {
>         "enabled": null,
>         "exported": true,
>         "intent_filters": [
>           {
>             "attrs": {},
>             "children": [
>               {
>                 "attrs": {
>                   "name": "android.appwidget.action.APPWIDGET_UPDATE"
>                 },
>                 "tag": "action"
>               }
>             ],
>             "tag": "intent-filter"
>           }
>         ],
>         "name": "despia.ext.recorder.StatusWidgetProvider",
>         "permission": null,
>         "tag": "receiver"
>       }
>     ]
>   }
> }
> ```

***

## Permissions and capabilities

The manifest declares everything the recorder needs. The build adds them to your app.

> [tab] iOS
>
> * **Microphone.** `NSMicrophoneUsageDescription`, declared under `requires.usage_descriptions`. Set the purpose text in Despia.
> * **Background modes.** `audio` (keep recording in the background) and `processing` (finish uploads in a background processing task named `upload`).
> * **App Group.** The logical group `nativeext`, shared by the app and the `RecorderStatusWidget` target. It becomes `group.<bundle id>.nx.nativeext`. Register it in the Apple Developer portal and add it to both bundle IDs, as for [Home Widgets](https://setup.despia.com/native-features/home-widgets.md).
> * **Widget.** `RecorderStatusWidget`, a WidgetKit target with a deployment target of iOS 16.6.

> [tab] Android
>
> * **Microphone.** `android.permission.RECORD_AUDIO`, declared under `requires.permissions`. Turn on the microphone permission for your app in Despia. The recorder does not ask for it on Android: it must be granted before `start`, otherwise `start` answers `permission_denied`. See [Asking for the microphone on Android](#asking-for-the-microphone-on-android).
> * **Foreground service.** `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_MICROPHONE`, with the service type `microphone`. Google Play asks you to declare this use.
> * **Notifications.** `POST_NOTIFICATIONS`, for the recording notification and its stop action.
> * **Widget.** `StatusWidgetProvider`, an exported app widget receiver.
> * **Libraries.** `androidx.core:core:1.18.0` and `androidx.work:work-runtime:2.11.2`.

***

## Using it from your web app

The upload URL receives an HTTP `PUT`, with `Content-Type: audio/mp4` and an `X-Recording-Id` header. Its host must be in the route's approved `hosts` list.

Install the SDK with `npm install despia-native`. Import `despia` from `despia-native` and watch the route's declared output variable. Run this function from a client event after obtaining any required microphone permission:

```javascript theme={null}
import despia from 'despia-native';

async function startRecording(uploadUrl) {
  const reply = await despia('extension://recorder/start?upload=' + encodeURIComponent(uploadUrl), ['recorderStart']);
  const answer = reply.recorderStart;
  if (answer === undefined) { console.error('No native reply within 30 seconds'); return; }
  if (!answer.ok) { console.error(answer.code, answer.error); return; }
  return answer.data.recordingId;
}

async function stopRecording(id) {
  const stoppedReply = await despia('extension://recorder/stop?id=' + encodeURIComponent(id), ['recorderStop']);
  const stopped = stoppedReply.recorderStop;
  if (stopped === undefined) { console.error('No native reply within 30 seconds'); return; }
  if (!stopped.ok) { console.error(stopped.code, stopped.error); return; }
  const statusReply = await despia('extension://recorder/status?id=' + encodeURIComponent(id), ['recorderStatus']);
  const status = statusReply.recorderStatus;
  if (status === undefined) { console.error('No native reply within 30 seconds'); return; }
  if (!status.ok) { console.error(status.code, status.error); return; }
  console.log(status.data.state);
}
```

Register `onRecorderState` as described in [Calling a route](https://setup.despia.com/experiments/v3-extensions.md#calling-a-route-with-the-despia-js-sdk) before starting if you need live changes. Read `status` after a page reload; event delivery is not durable.

### Asking for the microphone on Android

On iOS, `start` shows the microphone prompt itself. On Android it does not. Ask for the microphone from the page first with the standard web API. Despia's Android app turns a web microphone request into the system `RECORD_AUDIO` prompt, when the microphone permission is on for your app:

```javascript theme={null}
import despia from 'despia-native';

async function startWithMicrophone(uploadUrl) {
  const stream = await navigator.mediaDevices.getUserMedia({audio: true});
  stream.getTracks().forEach(track => track.stop());
  const reply = await despia('extension://recorder/start?upload=' + encodeURIComponent(uploadUrl), ['recorderStart']);
  const answer = reply.recorderStart;
  if (answer === undefined) { console.error('No native reply within 30 seconds'); return; }
  if (!answer.ok) { console.error(answer.code, answer.error); return; }
  return answer.data.recordingId;
}
```

If the user denies it, `getUserMedia` throws and `start` answers `permission_denied`.

### Routes

| Route | Parameters | Answer variable and callback | What it does |
| - | - | - | - |
| `start` | `upload` (required) | `recorderStart`, `onRecorderStart` | Starts a recording and answers with its `recordingId` |
| `stop` | `id` (required) | `recorderStop`, `onRecorderStop` | Stops the recording and starts the upload |
| `status` | `id` (optional) | `recorderStatus`, `onRecorderStatus` | The state of a recording, or of the latest one without `id`; `idle` when there is none |
| `discard` | `id` (required) | `recorderDiscard`, `onRecorderDiscard` | Deletes a stopped recording and its file |
| `upload` | `id`, `upload` (required) | `recorderUpload`, `onRecorderUpload` | Sends a saved recording again to a fresh URL, for example after a presigned URL expired |

The `state` event calls the declared `onRecorderState(data)` handler on changes.

### States

| State | Meaning |
| - | - |
| `starting` | The recording is being set up |
| `recording` | Recording |
| `interrupted` | Paused by the system |
| `uploading` | Stopped, and the file is being uploaded |
| `uploaded` | The upload finished |
| `failed` | The upload failed. `reason` says why. Call `upload` with a fresh URL to try again |
| `terminated` | The app was closed while recording. The file was never finished and is never uploaded |
| `discarding` | The file is being deleted |
| `discarded` | The recording is gone |

Answers and events carry `recordingId`, `state`, `durationMs` and `bytes`, plus `httpStatus` after an upload attempt and `reason` when the state is `failed`. While the recorder could not save its index, they also carry `durable: false` and `storage`.

### Error codes

Besides the [standard codes](https://setup.despia.com/experiments/v3-extensions.md#error-codes), the recorder answers:

| Code | When |
| - | - |
| `busy` | A recording is already running, or the recording is not in a state that allows this route |
| `permission_denied` | Microphone access is not granted |
| `not_found` | No recording has this id |
| `record_failed` | The recorder could not start, or the recording was never finished, so there is nothing to upload |
| `storage_unavailable` | The recorder's index cannot be read yet. Try again later |
| `storage_failed` | The index could not be saved, or the upload could not be scheduled. Nothing changed |
| `index_recovered` | The index was unreadable and was replaced, so an older recording may be missing |
| `discard_failed` | The file could not be deleted yet. It stays `discarding` and is deleted on the next `discard` or launch |

***

## Platform limits

* **iOS.** Recording must start while the app is in the foreground. It continues in the background while the audio session stays active. A force-quit ends it. Uploads run while the app runs, in the limited background time iOS may give, and in a background processing task if iOS grants one. iOS guarantees neither. An upload that is cut off starts again from the beginning the next time the app runs.
* **Android.** Android 14 and later only start a microphone foreground service while the app is visible, so call `start` from a page the user is looking at. Lock Screen widgets depend on the device; the foreground service notification is always shown. Uploads run through WorkManager.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.