From bab97a87415e4fca375cb8bceb0c1d0a499e8c49 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 14:35:24 +0000 Subject: [PATCH 1/2] feat(app): CarPlay station list, behind SUBWAVE_CARPLAY=1 Ported from perminder-klair/subwave#2134. --- CLAUDE.md | 1 + app.json | 1 + docs/TESTING.md | 41 +++- .../ios/SubwaveAppIntentsModule.swift | 4 + plugins/withCarPlay.js | 62 ++++++ .../_shared/StationEntities.swift | 5 + .../_shared/SubwaveCarPlay.swift | 198 ++++++++++++++++++ .../_shared/SubwaveIntentBridge.swift | 3 +- 8 files changed, 311 insertions(+), 4 deletions(-) create mode 100644 plugins/withCarPlay.js create mode 100644 targets/live-activity/_shared/SubwaveCarPlay.swift diff --git a/CLAUDE.md b/CLAUDE.md index a0c6e79..22a1ed7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,6 +7,7 @@ The Expo / React Native player for iOS and Android, with its own `package.json`, - **iOS uses the UIScene life cycle (`expo-build-properties` `ios.enableSceneSupport`).** Without it an iOS 27-SDK build is killed at launch on iOS 27; drop it with the SDK 58 upgrade, whose template does the same (TESTING.md). - **OTA cannot reach native code.** The Live Activity card (Lock Screen, Dynamic Island, the Apple Watch Smart Stack) is SwiftUI under `targets/live-activity/` and `modules/live-activity/ios/`, so a change there ships only in a new binary, like a dependency, `patches/`, plugin or native `app.json` change; the JS that drives it (`src/hooks/useLiveActivity.ts`) is OTA-able. The same holds for the App Intents (Siri, Shortcuts): Swift under `targets/live-activity/_shared/` and `modules/app-intents/ios/`, JS under `src/intents/`. `SubwaveLiveAttributes.swift` is compiled into both and must stay byte-identical (`npm test` checks): a mismatch stops the card rendering instead of failing the build. - **Android Auto's browse session is RNTP's own**, reached through the patch's `MediaBrowserBridge`; `modules/android-auto` only lists stations, and a pick reaches `service.ts` as `remote-play-id`. Play enforced against a TTS-reading app once (#477); TESTING.md has the history and the device check. +- **The CarPlay app is off unless `SUBWAVE_CARPLAY=1` is set at prebuild** (`plugins/withCarPlay.js`), because a device build can't be signed with the CarPlay entitlement until Apple grants it. Unset, the Info.plist and entitlements are unchanged. Its Swift is `targets/live-activity/_shared/SubwaveCarPlay.swift` (TESTING.md). - **The station password is not the station login** (#478). Every check is the fail-closed `POST /station-auth`, and only the controller's own answers count: a 200 with its `{ ok: true }` body is a right password and a 401 with its `{ ok: false }` body a wrong one, while anything else keeps a saved password and saves no typed one (`stationAuthResult`, #2143, #2164); the password rides the stream as `?auth=` so Cast works; `createApi` reads it through a getter because the feed reset and the Live Activity lifecycle key on the `api` object's identity, so rebuilding the client on unlock would reset both. While playback is stuck, `src/lib/stuck-password-check.ts` asks again after every answer but a denial, never within 120 s of the last check or before a 429's `Retry-After` runs out, capped at the route's own window: it allows a household's address 20 attempts per 15 minutes (#2141, #2164). When the gate's stop takes a tuned-in listener off the air, the right typed password tunes them back in with no second press (`src/lib/gate-resume.ts`, the twin of the web's `lib/gateResume.ts`), through `tune`, so it is a listener's own load in `stream-recovery.ts`. `useStationGate` outlives a station switch, so the hold names the `api` it was taken on, and `tune` toggles, so it never runs for a listener already tuned in. - **Every stream reload goes through `src/lib/stream-recovery.ts` while the player is mounted** (#2114, #2139): one at a time, and never on a state event alone. A listener's own load (a tune-in, a retune, a Play from the lock screen, a headset, CarPlay or Bluetooth) always loads, queued behind one in flight. `service.ts` hands a remote Play to the mounted player (`src/lib/remote-play.ts`) and loads directly only when none is mounted, which Android's headless service allows; an App Intent's tune-in and station switch do the same (`src/intents/tune-flow.ts`), and so does an Android Auto pick. The watchdog, churn guard and error backoff each check the native media clock first, because a reload re-sends Icecast's burst and the listener hears audio twice; a regained link reads it through the pending check it brings forward, and with none pending reloads at once. Every load is checked even when it reports no state (iOS drops a repeated Loading, #2143), and an automatic reload is a failure until its item stays up, so a hung station backs off to 60 s. Playing resets that only provisionally: an item that fails after stopping within 4 s of its first Playing, judged from the moment it stopped, takes the reset back, and the reload after it waits at most 16 s, so a stream cut a moment in can't reload 35-60 times a minute. A stall never counts, however early, and stays on the 6 s watchdog: Icecast closes a stalled socket about 15 s after its source stops, so a longer wait hears that close as a failure, and a flapping source climbs to a minute of silence. A hold counts as the item's Playing, because JS can miss the real one. None of this runs during an iOS audio interruption (a call, Siri), which freezes the clock without a state event. - **The idle skip changes only the native rate, never seeks or reloads** (#9, the port of web's `idleSkip.ts`, kept in step with it). It runs on an MP3 load in the foreground, reads `/state` only after that load's first Playing, and ends on any stall, pause, interruption or backgrounding, since JS timers can stop while the 8x would not. `loadAndPlay` resets the rate to 1x because RNTP carries it to the next item. What it shed reaches the feed as `leadTrimMs`, so the track clock and the DJ's lines move with the listener. diff --git a/app.json b/app.json index 2035f01..0d898df 100644 --- a/app.json +++ b/app.json @@ -82,6 +82,7 @@ "backgroundColor": "#100e0c" } ], + "./plugins/withCarPlay", [ "expo-build-properties", { diff --git a/docs/TESTING.md b/docs/TESTING.md index 2188467..6997f63 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -84,7 +84,8 @@ template still starts React Native from the app delegate, so `expo-build-propert SDK 58 template does: a scene manifest naming Expo's `ExpoAppSceneDelegate` (it creates the window, starts React Native and forwards URL and lifecycle events to the app delegate), and an app delegate that only creates the factory. Drop the -option with the SDK 58 upgrade; it warns and does nothing there. +option with the SDK 58 upgrade; it warns and does nothing there. `plugins/withCarPlay.js` +edits that manifest when CarPlay is on, so after the upgrade check it still finds one. EAS builds SDK 57 with **Xcode 26.6** (the `sdk-57` image) unless `eas.json` names another, so a default store build has none of the iOS 27-only code @@ -251,7 +252,7 @@ head unit) should show the new title without unlocking. ### CarPlay — Now-Playing in the car (iOS only) -Scope is **Tier 1**: control the *already-playing* stream from the dash (metadata, +Every build today is **Tier 1**: control the *already-playing* stream from the dash (metadata, artwork, play/pause/stop). There is **no launchable in-car app icon** — start the stream in the phone app first, then connect the car. RNTP feeds the iOS surface (`MPNowPlayingInfoCenter`), so CarPlay needs **no extra app-side wiring**. @@ -262,6 +263,42 @@ stream in the phone app first, then connect the car. RNTP feeds the iOS surface Play/Pause work; no scrubber (the `isLiveStream` track hides it). On iOS 26+ the Live Activity's `.small` card also appears on the CarPlay Dashboard. +**Tier 2, the CarPlay app, is built but switched off.** It puts SUB/WAVE in the +car's app grid: the saved stations as a list, tap one to tune in, then the system +Now Playing screen with a heart. It needs Apple's `com.apple.developer.carplay-audio` +entitlement, which Apple grants on request (developer.apple.com/carplay), and a +device build cannot be signed with it until the grant is on the App ID. So +`plugins/withCarPlay.js` does nothing unless `SUBWAVE_CARPLAY=1` is set at prebuild: +unset, the Info.plist and entitlements are what they were. Once the grant lands, set +it in `eas.json`'s `env` for the iOS profiles. + +- **Swift draws, JS decides.** `targets/live-activity/_shared/SubwaveCarPlay.swift` + reads the stations the app already mirrors for Siri (`SavedStations`, App Group), + and a tap goes through the App Intents bridge as `tuneIn`, so switching and tuning + in are `src/intents/tune.ts`. The heart is the bridge's `like`. The list redraws on + `SubwaveStationsChanged` and `SubwaveOnAirChanged` (posted by `StationIndex.reindex` + and the module's `setOnAir`). +- **The car can launch the app with no phone screen.** Under the scene life cycle + React Native starts when the phone's window scene connects, and a car launch + connects only the CarPlay scene. So the CarPlay delegate starts React Native into a + window with no scene (`ReactBoot`), and the plugin swaps the phone role's delegate + for `SubwavePhoneSceneDelegate`, which moves that window onto the phone's scene + when it connects instead of starting a second copy. +- **Testing it.** Xcode 27 has no Simulator.app, and DeviceHub offers no CarPlay + display for a simulator (FB24785359). The routes are Xcode 26's Simulator.app, + DeviceHub's CarPlay Simulator with a USB iPhone (needs the entitlement in the + profile), or the third-party NeoSimulator (needs Full Disk Access to switch the + display host; the iOS 27.0 runtime has no CarPlay mode, so use iOS 18 or 26). + Build with `SUBWAVE_CARPLAY=1 npx expo prebuild -p ios`, then check: the list shows + each saved station with its host and marks the playing one; a tap spins, then + plays and pushes Now Playing; a failure shows the bridge's message in an alert; + adding a station on the phone updates the list. Then cold: kill the app, connect + CarPlay, open SUB/WAVE from the car, tap a station (it must play), then open the + phone app (it must show the same playback, tuned in, with no second player). +- **Verified so far (2026-10):** it builds with Xcode 27, and a normal phone launch + goes through `SubwavePhoneSceneDelegate`. The CarPlay screens and the car-first + launch are not yet run. + ### Android Auto — the station list in the car (Android only) SUB/WAVE lists in Android Auto as a media app: the saved stations, tap one to tune diff --git a/modules/app-intents/ios/SubwaveAppIntentsModule.swift b/modules/app-intents/ios/SubwaveAppIntentsModule.swift index c816dad..3ba33b5 100644 --- a/modules/app-intents/ios/SubwaveAppIntentsModule.swift +++ b/modules/app-intents/ios/SubwaveAppIntentsModule.swift @@ -27,6 +27,8 @@ private let replyName = Notification.Name("SubwaveIntentReply") // by STRING like the names above. private let appGroup = "group.com.getsubwave.app" private let onAirKey = "subwave.onAir" +// Read by targets/live-activity/_shared/SubwaveCarPlay.swift. +private let onAirChangedName = Notification.Name("SubwaveOnAirChanged") private let tuneControlKind = "com.getsubwave.app.tune" // The saved stations, read by SavedStations in // targets/live-activity/_shared/StationEntities.swift, and the app-target class @@ -104,6 +106,8 @@ public class SubwaveAppIntentsModule: Module { if #available(iOS 18.0, *) { ControlCenter.shared.reloadControls(ofKind: tuneControlKind) } + // The CarPlay station list marks the station that is playing. + NotificationCenter.default.post(name: onAirChangedName, object: nil) } /// The saved stations and the active one, as JSON from JS: diff --git a/plugins/withCarPlay.js b/plugins/withCarPlay.js new file mode 100644 index 0000000..b593cf4 --- /dev/null +++ b/plugins/withCarPlay.js @@ -0,0 +1,62 @@ +// Expo config plugin: the CarPlay app, behind SUBWAVE_CARPLAY=1. +// +// The CarPlay UI is Swift in targets/live-activity/_shared/SubwaveCarPlay.swift. This +// plugin only switches it on: +// +// 1. `com.apple.developer.carplay-audio` in the entitlements. Apple grants +// it on request, and a DEVICE build cannot be signed with it until the +// grant is on the App ID, so it is opt-in: set SUBWAVE_CARPLAY=1 for a +// simulator build (the CarPlay simulator ignores provisioning) and, once +// the grant lands, in eas.json. Unset, the app is exactly as before. +// 2. A CarPlay scene role in the scene manifest that `ios.enableSceneSupport` +// writes, and the phone role's delegate swapped for PhoneSceneDelegate, +// which adopts React Native when the car launched the app first. +// +// Must come BEFORE expo-build-properties in app.json: a later plugin's Info.plist +// mod runs first, and this one edits the manifest that one creates. +// +// Usage in app.json plugins: "./plugins/withCarPlay" + +const { withEntitlementsPlist, withInfoPlist } = require('@expo/config-plugins'); + +const ENTITLEMENT = 'com.apple.developer.carplay-audio'; +const PHONE_ROLE = 'UIWindowSceneSessionRoleApplication'; +const CAR_ROLE = 'CPTemplateApplicationSceneSessionRoleApplication'; + +function enabled() { + return process.env.SUBWAVE_CARPLAY === '1'; +} + +function withCarPlayEntitlement(config) { + return withEntitlementsPlist(config, (cfg) => { + if (enabled()) cfg.modResults[ENTITLEMENT] = true; + else delete cfg.modResults[ENTITLEMENT]; + return cfg; + }); +} + +function withCarPlayScene(config) { + return withInfoPlist(config, (cfg) => { + if (!enabled()) return cfg; + const manifest = cfg.modResults.UIApplicationSceneManifest; + const phone = manifest?.UISceneConfigurations?.[PHONE_ROLE]?.[0]; + if (!phone) { + throw new Error( + 'withCarPlay: no scene manifest. Turn on expo-build-properties ios.enableSceneSupport, ' + + 'and list ./plugins/withCarPlay before expo-build-properties in app.json.', + ); + } + phone.UISceneDelegateClassName = 'SubwavePhoneSceneDelegate'; + manifest.UISceneConfigurations[CAR_ROLE] = [ + { + UISceneConfigurationName: 'CarPlay', + UISceneDelegateClassName: 'SubwaveCarPlaySceneDelegate', + }, + ]; + return cfg; + }); +} + +module.exports = function withCarPlay(config) { + return withCarPlayScene(withCarPlayEntitlement(config)); +}; diff --git a/targets/live-activity/_shared/StationEntities.swift b/targets/live-activity/_shared/StationEntities.swift index f98938e..425ed15 100644 --- a/targets/live-activity/_shared/StationEntities.swift +++ b/targets/live-activity/_shared/StationEntities.swift @@ -14,6 +14,9 @@ import Foundation // App target only, like SubwaveShortcuts.swift. #if canImport(ExpoModulesCore) +/// Posted in-process after a new station list is written and indexed. +let savedStationsChanged = Notification.Name("SubwaveStationsChanged") + /// The stations as the app last wrote them. The key is matched by STRING with /// modules/app-intents/ios/SubwaveAppIntentsModule.swift. struct SavedStations: Decodable { @@ -125,6 +128,8 @@ struct OpenStationIntent: OpenIntent { @objc(SubwaveStationIndex) final class StationIndex: NSObject { @objc static func reindex() { + // The CarPlay station list (SubwaveCarPlay.swift) redraws on this. + NotificationCenter.default.post(name: savedStationsChanged, object: nil) if #available(iOS 17.0, *) { SubwaveShortcuts.updateAppShortcutParameters() } diff --git a/targets/live-activity/_shared/SubwaveCarPlay.swift b/targets/live-activity/_shared/SubwaveCarPlay.swift new file mode 100644 index 0000000..e1970b4 --- /dev/null +++ b/targets/live-activity/_shared/SubwaveCarPlay.swift @@ -0,0 +1,198 @@ +import CarPlay +import Foundation +import UIKit + +// The CarPlay app: the saved stations as a list, and the system Now Playing +// screen once one is tuned in. Present only when the build carries Apple's +// com.apple.developer.carplay-audio entitlement and the CarPlay scene role +// (plugins/withCarPlay.js, SUBWAVE_CARPLAY=1); otherwise these classes are +// never instantiated. +// +// Swift draws, JS decides. The list reads the stations the app mirrors for +// Siri (SavedStations), and a tap hands the station to JS through the same +// bridge Siri's Tune in uses, so switching and tuning in are +// src/intents/tune.ts, and Now Playing is fed by the player as it is for the +// Lock Screen. +// +// App target only, like SubwaveShortcuts.swift. +#if canImport(ExpoModulesCore) +internal import Expo +import React + +/// The CarPlay scene. Named in Info.plist by its Objective-C name. +@available(iOSApplicationExtension, unavailable) +@objc(SubwaveCarPlaySceneDelegate) +final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate { + private var interfaceController: CPInterfaceController? + private var stationsTemplate: CPListTemplate? + private var observers: [NSObjectProtocol] = [] + + func templateApplicationScene( + _ templateApplicationScene: CPTemplateApplicationScene, + didConnect interfaceController: CPInterfaceController + ) { + self.interfaceController = interfaceController + // The car can launch SUB/WAVE with no phone screen at all, and a station + // tap needs JS to answer the bridge. + ReactBoot.startIfNeeded() + + let template = CPListTemplate(title: "Stations", sections: stationSections()) + template.emptyViewTitleVariants = ["No saved stations"] + template.emptyViewSubtitleVariants = ["Add a station in SUB/WAVE on your iPhone."] + stationsTemplate = template + interfaceController.setRootTemplate(template, animated: false, completion: nil) + configureNowPlaying() + + let center = NotificationCenter.default + for name in [savedStationsChanged, Notification.Name("SubwaveOnAirChanged")] { + observers.append( + center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in + self?.refreshStations() + }) + } + } + + func templateApplicationScene( + _ templateApplicationScene: CPTemplateApplicationScene, + didDisconnectInterfaceController interfaceController: CPInterfaceController + ) { + observers.forEach { NotificationCenter.default.removeObserver($0) } + observers = [] + stationsTemplate = nil + self.interfaceController = nil + } + + // MARK: - Stations + + private func stationSections() -> [CPListSection] { + let saved = SavedStations.load() + let onAir = + UserDefaults(suiteName: "group.com.getsubwave.app")?.bool(forKey: "subwave.onAir") ?? false + let icon = UIImage(systemName: "dot.radiowaves.left.and.right") + let items = saved.stations.map { station -> CPListItem in + let host = URL(string: station.id)?.host() ?? station.id + let item = CPListItem(text: station.name, detailText: host, image: icon) + item.isPlaying = onAir && station.id == saved.active + item.handler = { [weak self] _, completion in + self?.tuneIn(station.id, completion: completion) + } + return item + } + return [CPListSection(items: items)] + } + + private func refreshStations() { + stationsTemplate?.updateSections(stationSections()) + } + + /// The row shows a spinner until `completion`, so it is called once the + /// stream has started or failed, not when the tap lands. + private func tuneIn(_ stationID: String, completion: @escaping () -> Void) { + Task { @MainActor in + do { + try await SubwaveIntentBridge.perform(.tuneIn, ["station": stationID]) + showNowPlaying() + } catch { + showAlert((error as? SubwaveIntentError)?.message ?? "SUB/WAVE couldn't tune in.") + } + completion() + } + } + + // MARK: - Now Playing + + /// The system screen, fed from the player's Now Playing info. No skip or + /// scrub (one shared live stream); a heart, liked through the same path as + /// "like this song" from Siri. + private func configureNowPlaying() { + let nowPlaying = CPNowPlayingTemplate.shared + nowPlaying.isUpNextButtonEnabled = false + nowPlaying.isAlbumArtistButtonEnabled = false + if let heart = UIImage(systemName: "heart") { + let like = CPNowPlayingImageButton(image: heart) { _ in + Task { _ = try? await SubwaveIntentBridge.perform(.like) } + } + nowPlaying.updateNowPlayingButtons([like]) + } + } + + private func showNowPlaying() { + guard let controller = interfaceController, + !(controller.topTemplate is CPNowPlayingTemplate) + else { return } + controller.pushTemplate(CPNowPlayingTemplate.shared, animated: true, completion: nil) + } + + private func showAlert(_ message: String) { + guard let controller = interfaceController else { return } + let ok = CPAlertAction(title: "OK", style: .cancel) { _ in + controller.dismissTemplate(animated: true, completion: nil) + } + controller.presentTemplate( + CPAlertTemplate(titleVariants: [message], actions: [ok]), animated: true, completion: nil) + } +} + +// MARK: - Starting JS without the phone + +/// Under the scene life cycle React Native starts when the phone's window +/// scene connects (ExpoAppSceneDelegate). A launch by the car connects only +/// the CarPlay scene, so the CarPlay delegate starts it here instead, into a +/// window with no scene: the same start the app delegate made before scenes, +/// so expo-updates still chooses the bundle. PhoneSceneDelegate then moves that +/// window onto the phone's scene rather than starting a second copy. +@available(iOSApplicationExtension, unavailable) +@MainActor +enum ReactBoot { + static func startIfNeeded() { + guard + let provider = UIApplication.shared.delegate as? ExpoReactNativeFactoryProvider, + provider.window == nil, + let factory = provider.reactNativeFactory + else { return } + let window = UIWindow(frame: .zero) + provider.window = window + factory.startReactNative( + withModuleName: provider.reactNativeFactoryModuleName, in: window, launchOptions: nil) + } +} + +/// The phone's window scene: Expo's own, except when React Native is already +/// running in a window with no scene (ReactBoot, or a scene the system +/// disconnected). That window is moved onto this scene, so there is only ever +/// one React tree. +@available(iOSApplicationExtension, unavailable) +@objc(SubwavePhoneSceneDelegate) +final class PhoneSceneDelegate: ExpoAppSceneDelegate { + override func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + guard + let windowScene = scene as? UIWindowScene, + let provider = UIApplication.shared.delegate as? ExpoReactNativeFactoryProvider, + let running = provider.window, + running.windowScene == nil + else { + super.scene(scene, willConnectTo: session, options: connectionOptions) + return + } + running.windowScene = windowScene + window = running + running.makeKeyAndVisible() + + // What ExpoAppSceneDelegate would forward. React Native was started + // before this scene existed, so a link that opened the app arrives as an + // event rather than as Linking.getInitialURL(). + let app = UIApplication.shared + for context in connectionOptions.urlContexts { + _ = app.delegate?.application?(app, open: context.url, options: [:]) + } + for activity in connectionOptions.userActivities { + _ = app.delegate?.application?(app, continue: activity) { _ in } + } + } +} + +#endif diff --git a/targets/live-activity/_shared/SubwaveIntentBridge.swift b/targets/live-activity/_shared/SubwaveIntentBridge.swift index 1a3e6a2..bd35bd2 100644 --- a/targets/live-activity/_shared/SubwaveIntentBridge.swift +++ b/targets/live-activity/_shared/SubwaveIntentBridge.swift @@ -10,7 +10,7 @@ import Foundation // Only meaningful in the APP's process. Every intent that uses it must be one // the system runs there (AudioPlaybackIntent, LiveActivityIntent): in the // widget extension nothing is listening and `perform` fails after the ack -// window. +// window. The CarPlay scene (SubwaveCarPlay.swift) uses it too, from the app. /// What an intent asks JS to do, matched by STRING with `IntentAction` in /// modules/app-intents/index.ts and the switch in src/intents/handlers.ts. @@ -22,7 +22,6 @@ enum SubwaveIntentAction: String { case like } -@available(iOS 17.0, *) enum SubwaveIntentBridge { private static let requestName = Notification.Name("SubwaveIntentRequest") private static let ackName = Notification.Name("SubwaveIntentAck") From 3b7778f3ef9b0bace712e613eecd989853f1bdc2 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 15:14:55 +0000 Subject: [PATCH 2/2] fix(app): CarPlay review fixes: phone window size, shared on-air flag, Apple's scene manifest - PhoneSceneDelegate sizes the window ReactBoot made to its scene, re-sends a connection's URLs, activities and quick action through Expo's own handlers (open options, RCTLinkingManager fallback and dedupe), and refuses a second window. - With the flag on, the manifest follows Apple's CarPlay one: UIApplicationSupportsMultipleScenes true and UISceneClassName CPTemplateApplicationScene. On iPad that allows a second window, which one React tree can't serve, so the phone delegate destroys it. - OnAirFlag (_shared) is the one reader of the on-air flag, for CarPlay and the tune control, with matched-by-string notes on both sides. ReactBoot clears a flag a killed app left set. - setStations posts SubwaveStationsChanged; StationIndex.reindex no longer doubles as CarPlay's signal. - A failed like from the CarPlay heart shows the bridge's message. - withCarPlay copies expo-build-properties' manifest instead of editing its module-level object, renames enabled() to carPlayEnabled(), and scripts/carplay-plugin.test.ts checks the plist with the flag unset and set. - TESTING.md: the SDK 58 check for the delegate override, and the checklist. --- CLAUDE.md | 2 +- docs/TESTING.md | 44 ++++-- .../ios/SubwaveAppIntentsModule.swift | 15 +- plugins/withCarPlay.js | 31 +++-- scripts/carplay-plugin.test.ts | 128 ++++++++++++++++++ targets/live-activity/TuneControl.swift | 2 +- targets/live-activity/_shared/OnAirFlag.swift | 29 ++++ .../_shared/StationEntities.swift | 6 +- .../_shared/SubwaveCarPlay.swift | 73 ++++++---- 9 files changed, 277 insertions(+), 53 deletions(-) create mode 100644 scripts/carplay-plugin.test.ts create mode 100644 targets/live-activity/_shared/OnAirFlag.swift diff --git a/CLAUDE.md b/CLAUDE.md index 22a1ed7..10faa11 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,7 +7,7 @@ The Expo / React Native player for iOS and Android, with its own `package.json`, - **iOS uses the UIScene life cycle (`expo-build-properties` `ios.enableSceneSupport`).** Without it an iOS 27-SDK build is killed at launch on iOS 27; drop it with the SDK 58 upgrade, whose template does the same (TESTING.md). - **OTA cannot reach native code.** The Live Activity card (Lock Screen, Dynamic Island, the Apple Watch Smart Stack) is SwiftUI under `targets/live-activity/` and `modules/live-activity/ios/`, so a change there ships only in a new binary, like a dependency, `patches/`, plugin or native `app.json` change; the JS that drives it (`src/hooks/useLiveActivity.ts`) is OTA-able. The same holds for the App Intents (Siri, Shortcuts): Swift under `targets/live-activity/_shared/` and `modules/app-intents/ios/`, JS under `src/intents/`. `SubwaveLiveAttributes.swift` is compiled into both and must stay byte-identical (`npm test` checks): a mismatch stops the card rendering instead of failing the build. - **Android Auto's browse session is RNTP's own**, reached through the patch's `MediaBrowserBridge`; `modules/android-auto` only lists stations, and a pick reaches `service.ts` as `remote-play-id`. Play enforced against a TTS-reading app once (#477); TESTING.md has the history and the device check. -- **The CarPlay app is off unless `SUBWAVE_CARPLAY=1` is set at prebuild** (`plugins/withCarPlay.js`), because a device build can't be signed with the CarPlay entitlement until Apple grants it. Unset, the Info.plist and entitlements are unchanged. Its Swift is `targets/live-activity/_shared/SubwaveCarPlay.swift` (TESTING.md). +- **The CarPlay app is off unless `SUBWAVE_CARPLAY=1` is set at prebuild** (`plugins/withCarPlay.js`), because a device build can't be signed with the CarPlay entitlement until Apple grants it. Unset, the Info.plist and entitlements are unchanged (`npm test` checks). Its Swift is `targets/live-activity/_shared/SubwaveCarPlay.swift` (TESTING.md). - **The station password is not the station login** (#478). Every check is the fail-closed `POST /station-auth`, and only the controller's own answers count: a 200 with its `{ ok: true }` body is a right password and a 401 with its `{ ok: false }` body a wrong one, while anything else keeps a saved password and saves no typed one (`stationAuthResult`, #2143, #2164); the password rides the stream as `?auth=` so Cast works; `createApi` reads it through a getter because the feed reset and the Live Activity lifecycle key on the `api` object's identity, so rebuilding the client on unlock would reset both. While playback is stuck, `src/lib/stuck-password-check.ts` asks again after every answer but a denial, never within 120 s of the last check or before a 429's `Retry-After` runs out, capped at the route's own window: it allows a household's address 20 attempts per 15 minutes (#2141, #2164). When the gate's stop takes a tuned-in listener off the air, the right typed password tunes them back in with no second press (`src/lib/gate-resume.ts`, the twin of the web's `lib/gateResume.ts`), through `tune`, so it is a listener's own load in `stream-recovery.ts`. `useStationGate` outlives a station switch, so the hold names the `api` it was taken on, and `tune` toggles, so it never runs for a listener already tuned in. - **Every stream reload goes through `src/lib/stream-recovery.ts` while the player is mounted** (#2114, #2139): one at a time, and never on a state event alone. A listener's own load (a tune-in, a retune, a Play from the lock screen, a headset, CarPlay or Bluetooth) always loads, queued behind one in flight. `service.ts` hands a remote Play to the mounted player (`src/lib/remote-play.ts`) and loads directly only when none is mounted, which Android's headless service allows; an App Intent's tune-in and station switch do the same (`src/intents/tune-flow.ts`), and so does an Android Auto pick. The watchdog, churn guard and error backoff each check the native media clock first, because a reload re-sends Icecast's burst and the listener hears audio twice; a regained link reads it through the pending check it brings forward, and with none pending reloads at once. Every load is checked even when it reports no state (iOS drops a repeated Loading, #2143), and an automatic reload is a failure until its item stays up, so a hung station backs off to 60 s. Playing resets that only provisionally: an item that fails after stopping within 4 s of its first Playing, judged from the moment it stopped, takes the reset back, and the reload after it waits at most 16 s, so a stream cut a moment in can't reload 35-60 times a minute. A stall never counts, however early, and stays on the 6 s watchdog: Icecast closes a stalled socket about 15 s after its source stops, so a longer wait hears that close as a failure, and a flapping source climbs to a minute of silence. A hold counts as the item's Playing, because JS can miss the real one. None of this runs during an iOS audio interruption (a call, Siri), which freezes the clock without a state event. - **The idle skip changes only the native rate, never seeks or reloads** (#9, the port of web's `idleSkip.ts`, kept in step with it). It runs on an MP3 load in the foreground, reads `/state` only after that load's first Playing, and ends on any stall, pause, interruption or backgrounding, since JS timers can stop while the 8x would not. `loadAndPlay` resets the rate to 1x because RNTP carries it to the next item. What it shed reaches the feed as `leadTrimMs`, so the track clock and the DJ's lines move with the listener. diff --git a/docs/TESTING.md b/docs/TESTING.md index 6997f63..37d5795 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -85,7 +85,14 @@ SDK 58 template does: a scene manifest naming Expo's `ExpoAppSceneDelegate` (it creates the window, starts React Native and forwards URL and lifecycle events to the app delegate), and an app delegate that only creates the factory. Drop the option with the SDK 58 upgrade; it warns and does nothing there. `plugins/withCarPlay.js` -edits that manifest when CarPlay is on, so after the upgrade check it still finds one. +edits that manifest when CarPlay is on, so after the upgrade check it still finds one +(`scripts/carplay-plugin.test.ts` builds it through expo-build-properties). Check +`SubwavePhoneSceneDelegate` (`targets/live-activity/_shared/SubwaveCarPlay.swift`) too: +it subclasses `ExpoAppSceneDelegate` and, when it adopts a running window instead +of calling `super`, re-sends the connection's URLs, user activities and quick +action through that class's own `scene(_:openURLContexts:)`, `scene(_:continue:)` +and `windowScene(_:performActionFor:)`. If SDK 58's delegate handles more at +connect time, or renames those, the adopt path must follow. EAS builds SDK 57 with **Xcode 26.6** (the `sdk-57` image) unless `eas.json` names another, so a default store build has none of the iOS 27-only code @@ -275,15 +282,26 @@ it in `eas.json`'s `env` for the iOS profiles. - **Swift draws, JS decides.** `targets/live-activity/_shared/SubwaveCarPlay.swift` reads the stations the app already mirrors for Siri (`SavedStations`, App Group), and a tap goes through the App Intents bridge as `tuneIn`, so switching and tuning - in are `src/intents/tune.ts`. The heart is the bridge's `like`. The list redraws on - `SubwaveStationsChanged` and `SubwaveOnAirChanged` (posted by `StationIndex.reindex` - and the module's `setOnAir`). + in are `src/intents/tune.ts` (`tune-flow.ts` decides): handed to the mounted player + when there is one, and cut to the bridge's deadline like any Siri tune-in. The heart is the bridge's `like`, and a failed like + shows the bridge's message in an alert. The list redraws on `SubwaveStationsChanged` + and `SubwaveOnAirChanged` (posted by the module's `setStations` and `setOnAir`); the + on-air flag is read through `OnAirFlag` (`_shared/OnAirFlag.swift`), shared with the + tune control. - **The car can launch the app with no phone screen.** Under the scene life cycle React Native starts when the phone's window scene connects, and a car launch connects only the CarPlay scene. So the CarPlay delegate starts React Native into a window with no scene (`ReactBoot`), and the plugin swaps the phone role's delegate for `SubwavePhoneSceneDelegate`, which moves that window onto the phone's scene - when it connects instead of starting a second copy. + (sized to it) when it connects instead of starting a second copy. A process the + car started has played nothing, so `ReactBoot` clears an on-air flag a killed app + left set. +- **Multiple scenes are on with the flag.** Apple's CarPlay manifest sets + `UIApplicationSupportsMultipleScenes` (the app declares a phone scene and a CarPlay + one) and names `CPTemplateApplicationScene` as the CarPlay scene class, so the plugin + does both. On iPad that also lets the system open a second window of the app; + `SubwavePhoneSceneDelegate` asks for that session's destruction, because one React + tree plays one stream. Unset, the manifest stays `false`. - **Testing it.** Xcode 27 has no Simulator.app, and DeviceHub offers no CarPlay display for a simulator (FB24785359). The routes are Xcode 26's Simulator.app, DeviceHub's CarPlay Simulator with a USB iPhone (needs the entitlement in the @@ -292,12 +310,16 @@ it in `eas.json`'s `env` for the iOS profiles. Build with `SUBWAVE_CARPLAY=1 npx expo prebuild -p ios`, then check: the list shows each saved station with its host and marks the playing one; a tap spins, then plays and pushes Now Playing; a failure shows the bridge's message in an alert; - adding a station on the phone updates the list. Then cold: kill the app, connect - CarPlay, open SUB/WAVE from the car, tap a station (it must play), then open the - phone app (it must show the same playback, tuned in, with no second player). -- **Verified so far (2026-10):** it builds with Xcode 27, and a normal phone launch - goes through `SubwavePhoneSceneDelegate`. The CarPlay screens and the car-first - launch are not yet run. + a heart with nothing on air shows the bridge's message too; adding a station on + the phone updates the list. Then cold: play a station, kill the app, connect + CarPlay, open SUB/WAVE from the car (no station is marked playing), tap a station + (it must play), then open the phone app (it must fill the screen and show the same + playback, tuned in, with no second player). On an iPad build with the flag, a + second window (drag the app from the Dock) must close rather than open a player. +- **Verified so far (2026-11):** it builds with Xcode 27, a normal phone launch + goes through `SubwavePhoneSceneDelegate` (2026-10), and the plugin's plist edits + are under `npm test`. The CarPlay screens, the car-first launch and the iPad second + window are not yet run. ### Android Auto — the station list in the car (Android only) diff --git a/modules/app-intents/ios/SubwaveAppIntentsModule.swift b/modules/app-intents/ios/SubwaveAppIntentsModule.swift index 3ba33b5..526e192 100644 --- a/modules/app-intents/ios/SubwaveAppIntentsModule.swift +++ b/modules/app-intents/ios/SubwaveAppIntentsModule.swift @@ -23,19 +23,22 @@ private let requestName = Notification.Name("SubwaveIntentRequest") private let ackName = Notification.Name("SubwaveIntentAck") private let replyName = Notification.Name("SubwaveIntentReply") -// The tune control's state (targets/live-activity/TuneControl.swift), matched -// by STRING like the names above. +// Whether the station is on, read by OnAirFlag in +// targets/live-activity/_shared/OnAirFlag.swift for the tune control +// (targets/live-activity/TuneControl.swift) and the CarPlay station list. +// Matched by STRING like the names above. private let appGroup = "group.com.getsubwave.app" private let onAirKey = "subwave.onAir" -// Read by targets/live-activity/_shared/SubwaveCarPlay.swift. private let onAirChangedName = Notification.Name("SubwaveOnAirChanged") private let tuneControlKind = "com.getsubwave.app.tune" // The saved stations, read by SavedStations in // targets/live-activity/_shared/StationEntities.swift, and the app-target class // that re-indexes them for Spotlight and the Siri phrases with a station in // them. That code sees the entity types; this pod does not, so it is reached -// by name. +// by name. The CarPlay station list redraws on the name (savedStationsChanged +// there), also matched by STRING. private let stationsKey = "subwave.stations" +private let stationsChangedName = Notification.Name("SubwaveStationsChanged") private let stationIndexClass = "SubwaveStationIndex" public class SubwaveAppIntentsModule: Module { @@ -112,12 +115,14 @@ public class SubwaveAppIntentsModule: Module { /// The saved stations and the active one, as JSON from JS: /// `{ active, stations: [{ id, name }] }`. Names and credential-free bases - /// only. Writes them for the intents and re-indexes Spotlight. + /// only. Writes them for the intents, re-indexes Spotlight and tells the + /// CarPlay station list. Function("setStations") { (json: String) in UserDefaults(suiteName: appGroup)?.set(json, forKey: stationsKey) if let index: AnyClass = NSClassFromString(stationIndexClass) { _ = (index as AnyObject).perform(NSSelectorFromString("reindex")) } + NotificationCenter.default.post(name: stationsChangedName, object: nil) } } diff --git a/plugins/withCarPlay.js b/plugins/withCarPlay.js index b593cf4..36900b4 100644 --- a/plugins/withCarPlay.js +++ b/plugins/withCarPlay.js @@ -9,11 +9,13 @@ // simulator build (the CarPlay simulator ignores provisioning) and, once // the grant lands, in eas.json. Unset, the app is exactly as before. // 2. A CarPlay scene role in the scene manifest that `ios.enableSceneSupport` -// writes, and the phone role's delegate swapped for PhoneSceneDelegate, -// which adopts React Native when the car launched the app first. +// writes, multiple scenes on, and the phone role's delegate swapped for +// PhoneSceneDelegate, which adopts React Native when the car launched the +// app first and refuses a second window. // // Must come BEFORE expo-build-properties in app.json: a later plugin's Info.plist // mod runs first, and this one edits the manifest that one creates. +// scripts/carplay-plugin.test.ts checks both, flag set and unset. // // Usage in app.json plugins: "./plugins/withCarPlay" @@ -23,13 +25,13 @@ const ENTITLEMENT = 'com.apple.developer.carplay-audio'; const PHONE_ROLE = 'UIWindowSceneSessionRoleApplication'; const CAR_ROLE = 'CPTemplateApplicationSceneSessionRoleApplication'; -function enabled() { +function carPlayEnabled() { return process.env.SUBWAVE_CARPLAY === '1'; } function withCarPlayEntitlement(config) { return withEntitlementsPlist(config, (cfg) => { - if (enabled()) cfg.modResults[ENTITLEMENT] = true; + if (carPlayEnabled()) cfg.modResults[ENTITLEMENT] = true; else delete cfg.modResults[ENTITLEMENT]; return cfg; }); @@ -37,22 +39,33 @@ function withCarPlayEntitlement(config) { function withCarPlayScene(config) { return withInfoPlist(config, (cfg) => { - if (!enabled()) return cfg; - const manifest = cfg.modResults.UIApplicationSceneManifest; - const phone = manifest?.UISceneConfigurations?.[PHONE_ROLE]?.[0]; - if (!phone) { + if (!carPlayEnabled()) return cfg; + const written = cfg.modResults.UIApplicationSceneManifest; + if (!written?.UISceneConfigurations?.[PHONE_ROLE]?.[0]) { throw new Error( 'withCarPlay: no scene manifest. Turn on expo-build-properties ios.enableSceneSupport, ' + 'and list ./plugins/withCarPlay before expo-build-properties in app.json.', ); } - phone.UISceneDelegateClassName = 'SubwavePhoneSceneDelegate'; + // A copy: expo-build-properties hands over its own module-level manifest, + // and compares later ones against it to tell its manifest from the app's. + const manifest = structuredClone(written); + // Apple's CarPlay manifest (developer.apple.com/documentation/carplay/ + // building-your-apps-initial-carplay-interface): multiple scenes on, since + // the app declares a phone scene and a CarPlay one, and the CarPlay class + // named. On iPad that also allows a second window, which + // PhoneSceneDelegate refuses. + manifest.UIApplicationSupportsMultipleScenes = true; + manifest.UISceneConfigurations[PHONE_ROLE][0].UISceneDelegateClassName = + 'SubwavePhoneSceneDelegate'; manifest.UISceneConfigurations[CAR_ROLE] = [ { + UISceneClassName: 'CPTemplateApplicationScene', UISceneConfigurationName: 'CarPlay', UISceneDelegateClassName: 'SubwaveCarPlaySceneDelegate', }, ]; + cfg.modResults.UIApplicationSceneManifest = manifest; return cfg; }); } diff --git a/scripts/carplay-plugin.test.ts b/scripts/carplay-plugin.test.ts new file mode 100644 index 0000000..b414b69 --- /dev/null +++ b/scripts/carplay-plugin.test.ts @@ -0,0 +1,128 @@ +// plugins/withCarPlay.js switches the CarPlay app on only when SUBWAVE_CARPLAY=1 +// is set at prebuild, because a device build cannot be signed with Apple's +// CarPlay entitlement until the grant is on the App ID. Unset, the Info.plist +// and entitlements must be what expo-build-properties alone writes: a stray +// CarPlay role or entitlement fails every store build's signing. +// +// The two plugins run here in app.json's order, with their Info.plist and +// entitlements mods called directly on an empty plist, as prebuild calls them. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import test, { type TestContext } from 'node:test'; +import type { ExpoConfig } from 'expo/config'; +// What prebuild loads for "expo-build-properties" in app.json. +import withBuildProperties from 'expo-build-properties/app.plugin.js'; +import withCarPlay from '../plugins/withCarPlay.js'; + +const ROOT = path.join(import.meta.dirname, '..'); +const ENTITLEMENT = 'com.apple.developer.carplay-audio'; + +type Plist = Record; +type Mod = (config: Plist) => Promise; + +/** Set or unset SUBWAVE_CARPLAY for one test. */ +function flag(t: TestContext, value: string | undefined) { + const before = process.env.SUBWAVE_CARPLAY; + if (value === undefined) delete process.env.SUBWAVE_CARPLAY; + else process.env.SUBWAVE_CARPLAY = value; + t.after(() => { + if (before === undefined) delete process.env.SUBWAVE_CARPLAY; + else process.env.SUBWAVE_CARPLAY = before; + }); +} + +/** What the iOS mods write into an empty Info.plist and entitlements, with + * or without the CarPlay plugin ahead of expo-build-properties. */ +async function prebuild(withPlugin: boolean): Promise<{ info: Plist; entitlements: Plist }> { + let config = { + name: 'SUB/WAVE', + slug: 'subwave', + _internal: { projectRoot: ROOT }, + } as ExpoConfig; + if (withPlugin) config = withCarPlay(config); + config = withBuildProperties(config, { ios: { enableSceneSupport: true } }); + + const run = async (name: 'infoPlist' | 'entitlements') => { + const mod = (config.mods?.ios as Record | undefined)?.[name]; + const base = { ...config, modResults: {}, modRequest: { platform: 'ios', modName: name, projectRoot: ROOT } }; + return ((await mod?.(base)) ?? base).modResults as Plist; + }; + return { info: await run('infoPlist'), entitlements: await run('entitlements') }; +} + +test('unset, the Info.plist and entitlements are what they are without the plugin', async (t) => { + flag(t, undefined); + const without = await prebuild(false); + const withIt = await prebuild(true); + assert.ok(without.info.UIApplicationSceneManifest, 'expo-build-properties wrote no scene manifest'); + assert.deepEqual(withIt, without); + assert.equal(ENTITLEMENT in withIt.entitlements, false); +}); + +test('any value but 1 leaves CarPlay off', async (t) => { + flag(t, 'true'); + const { info, entitlements } = await prebuild(true); + assert.deepEqual(info, (await prebuild(false)).info); + assert.equal(ENTITLEMENT in entitlements, false); +}); + +test('set, it adds the entitlement, the CarPlay role, multiple scenes and the phone delegate', async (t) => { + flag(t, '1'); + const { info, entitlements } = await prebuild(true); + assert.equal(entitlements[ENTITLEMENT], true); + assert.deepEqual(info.UIApplicationSceneManifest, { + // Apple's CarPlay manifest: a phone scene and a CarPlay one. + UIApplicationSupportsMultipleScenes: true, + UISceneConfigurations: { + UIWindowSceneSessionRoleApplication: [ + { + UISceneConfigurationName: 'Default Configuration', + UISceneDelegateClassName: 'SubwavePhoneSceneDelegate', + }, + ], + CPTemplateApplicationSceneSessionRoleApplication: [ + { + UISceneClassName: 'CPTemplateApplicationScene', + UISceneConfigurationName: 'CarPlay', + UISceneDelegateClassName: 'SubwaveCarPlaySceneDelegate', + }, + ], + }, + }); +}); + +test('set, it leaves expo-build-properties’ own manifest as it was', async (t) => { + // That plugin compares a plist's manifest against its module-level one to + // tell its own from the app's, so an edit in place would leak into the next. + flag(t, '1'); + await prebuild(true); + flag(t, undefined); + const after = await prebuild(false); + const phone = (after.info.UIApplicationSceneManifest as { + UISceneConfigurations: Record; + }).UISceneConfigurations.UIWindowSceneSessionRoleApplication[0]; + assert.equal(phone.UISceneDelegateClassName, 'EXExpoAppSceneDelegate'); +}); + +test('set, it fails the prebuild when there is no scene manifest to edit', async (t) => { + flag(t, '1'); + let config = { name: 'SUB/WAVE', slug: 'subwave' } as ExpoConfig; + config = withCarPlay(config); + const mod = (config.mods?.ios as Record).infoPlist; + await assert.rejects( + mod({ ...config, modResults: {}, modRequest: { platform: 'ios', modName: 'infoPlist' } }), + /no scene manifest/, + ); +}); + +test('app.json lists the plugin before expo-build-properties', () => { + // A later plugin's Info.plist mod runs first, and withCarPlay edits the + // manifest that expo-build-properties writes. + const plugins: unknown[] = JSON.parse(readFileSync(path.join(ROOT, 'app.json'), 'utf8')).expo.plugins; + const name = (p: unknown) => (Array.isArray(p) ? p[0] : p); + const carPlay = plugins.findIndex((p) => name(p) === './plugins/withCarPlay'); + const buildProperties = plugins.findIndex((p) => name(p) === 'expo-build-properties'); + assert.ok(carPlay >= 0, 'withCarPlay is not in app.json'); + assert.ok(carPlay < buildProperties, 'withCarPlay must come before expo-build-properties'); +}); diff --git a/targets/live-activity/TuneControl.swift b/targets/live-activity/TuneControl.swift index 818e4b1..cd05b37 100644 --- a/targets/live-activity/TuneControl.swift +++ b/targets/live-activity/TuneControl.swift @@ -40,6 +40,6 @@ private struct OnAirProvider: ControlValueProvider { var previewValue: Bool { false } func currentValue() async throws -> Bool { - UserDefaults(suiteName: subwaveAppGroup)?.bool(forKey: "subwave.onAir") ?? false + OnAirFlag.isOn } } diff --git a/targets/live-activity/_shared/OnAirFlag.swift b/targets/live-activity/_shared/OnAirFlag.swift new file mode 100644 index 0000000..3f0a187 --- /dev/null +++ b/targets/live-activity/_shared/OnAirFlag.swift @@ -0,0 +1,29 @@ +import Foundation + +// Whether the station is on, for the code that cannot ask the player: the +// tune control (TuneControl.swift, widget) and the CarPlay station list +// (SubwaveCarPlay.swift, app). JS writes it through the app-intents module's +// setOnAir, which posts `changed` after a change. +// +// The suite, key and name are matched by STRING with +// modules/app-intents/ios/SubwaveAppIntentsModule.swift, which cannot import +// this file. Change one side, change both. +enum OnAirFlag { + static let changed = Notification.Name("SubwaveOnAirChanged") + private static let suite = "group.com.getsubwave.app" + private static let key = "subwave.onAir" + + static var isOn: Bool { + UserDefaults(suiteName: suite)?.bool(forKey: key) ?? false + } + + /// A process that has just started plays nothing, so a flag still on was + /// left by an app that was killed while it played. Cleared before anything + /// reads it, so neither the CarPlay list nor the tune control (when it next + /// asks) marks a station as playing until JS says one is. + static func clearStale() { + guard let defaults = UserDefaults(suiteName: suite), defaults.bool(forKey: key) else { return } + defaults.set(false, forKey: key) + NotificationCenter.default.post(name: changed, object: nil) + } +} diff --git a/targets/live-activity/_shared/StationEntities.swift b/targets/live-activity/_shared/StationEntities.swift index 425ed15..2171cd5 100644 --- a/targets/live-activity/_shared/StationEntities.swift +++ b/targets/live-activity/_shared/StationEntities.swift @@ -14,7 +14,9 @@ import Foundation // App target only, like SubwaveShortcuts.swift. #if canImport(ExpoModulesCore) -/// Posted in-process after a new station list is written and indexed. +/// Posted in-process by the app-intents module's setStations after it writes +/// a new list. Matched by STRING with +/// modules/app-intents/ios/SubwaveAppIntentsModule.swift. let savedStationsChanged = Notification.Name("SubwaveStationsChanged") /// The stations as the app last wrote them. The key is matched by STRING with @@ -128,8 +130,6 @@ struct OpenStationIntent: OpenIntent { @objc(SubwaveStationIndex) final class StationIndex: NSObject { @objc static func reindex() { - // The CarPlay station list (SubwaveCarPlay.swift) redraws on this. - NotificationCenter.default.post(name: savedStationsChanged, object: nil) if #available(iOS 17.0, *) { SubwaveShortcuts.updateAppShortcutParameters() } diff --git a/targets/live-activity/_shared/SubwaveCarPlay.swift b/targets/live-activity/_shared/SubwaveCarPlay.swift index e1970b4..547ad92 100644 --- a/targets/live-activity/_shared/SubwaveCarPlay.swift +++ b/targets/live-activity/_shared/SubwaveCarPlay.swift @@ -11,8 +11,9 @@ import UIKit // Swift draws, JS decides. The list reads the stations the app mirrors for // Siri (SavedStations), and a tap hands the station to JS through the same // bridge Siri's Tune in uses, so switching and tuning in are -// src/intents/tune.ts, and Now Playing is fed by the player as it is for the -// Lock Screen. +// src/intents/tune.ts (decided in tune-flow.ts), which hands the load to the +// mounted player when there is one, and every wait fits the deadline the +// bridge sends. Now Playing is fed by the player as it is for the Lock Screen. // // App target only, like SubwaveShortcuts.swift. #if canImport(ExpoModulesCore) @@ -44,7 +45,7 @@ final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegat configureNowPlaying() let center = NotificationCenter.default - for name in [savedStationsChanged, Notification.Name("SubwaveOnAirChanged")] { + for name in [savedStationsChanged, OnAirFlag.changed] { observers.append( center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in self?.refreshStations() @@ -66,8 +67,7 @@ final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegat private func stationSections() -> [CPListSection] { let saved = SavedStations.load() - let onAir = - UserDefaults(suiteName: "group.com.getsubwave.app")?.bool(forKey: "subwave.onAir") ?? false + let onAir = OnAirFlag.isOn let icon = UIImage(systemName: "dot.radiowaves.left.and.right") let items = saved.stations.map { station -> CPListItem in let host = URL(string: station.id)?.host() ?? station.id @@ -86,14 +86,15 @@ final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegat } /// The row shows a spinner until `completion`, so it is called once the - /// stream has started or failed, not when the tap lands. + /// stream has started or failed, not when the tap lands: at most the + /// bridge's reply window, which JS's waits are cut to. private func tuneIn(_ stationID: String, completion: @escaping () -> Void) { Task { @MainActor in do { try await SubwaveIntentBridge.perform(.tuneIn, ["station": stationID]) showNowPlaying() } catch { - showAlert((error as? SubwaveIntentError)?.message ?? "SUB/WAVE couldn't tune in.") + showAlert(Self.message(for: error, else: "SUB/WAVE couldn't tune in.")) } completion() } @@ -103,14 +104,20 @@ final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegat /// The system screen, fed from the player's Now Playing info. No skip or /// scrub (one shared live stream); a heart, liked through the same path as - /// "like this song" from Siri. + /// "like this song" from Siri. A like that fails says why, as Siri would. private func configureNowPlaying() { let nowPlaying = CPNowPlayingTemplate.shared nowPlaying.isUpNextButtonEnabled = false nowPlaying.isAlbumArtistButtonEnabled = false if let heart = UIImage(systemName: "heart") { - let like = CPNowPlayingImageButton(image: heart) { _ in - Task { _ = try? await SubwaveIntentBridge.perform(.like) } + let like = CPNowPlayingImageButton(image: heart) { [weak self] _ in + Task { @MainActor in + do { + try await SubwaveIntentBridge.perform(.like) + } catch { + self?.showAlert(Self.message(for: error, else: "SUB/WAVE couldn't like that song.")) + } + } } nowPlaying.updateNowPlayingButtons([like]) } @@ -123,6 +130,12 @@ final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegat controller.pushTemplate(CPNowPlayingTemplate.shared, animated: true, completion: nil) } + /// The bridge's own message (JS's answer, or that the app didn't answer), + /// else `fallback`. + private static func message(for error: Error, else fallback: String) -> String { + (error as? SubwaveIntentError)?.message ?? fallback + } + private func showAlert(_ message: String) { guard let controller = interfaceController else { return } let ok = CPAlertAction(title: "OK", style: .cancel) { _ in @@ -150,6 +163,10 @@ enum ReactBoot { provider.window == nil, let factory = provider.reactNativeFactory else { return } + // No player has run in this process yet, so an on-air flag still set was + // left by an app killed while it played. + OnAirFlag.clearStale() + // Sized when PhoneSceneDelegate gives it a scene. let window = UIWindow(frame: .zero) provider.window = window factory.startReactNative( @@ -158,9 +175,12 @@ enum ReactBoot { } /// The phone's window scene: Expo's own, except when React Native is already -/// running in a window with no scene (ReactBoot, or a scene the system -/// disconnected). That window is moved onto this scene, so there is only ever -/// one React tree. +/// running in a window. A window with no scene (ReactBoot, or a scene the +/// system disconnected) is moved onto this scene. A window on another live +/// scene means a second window: CarPlay needs UIApplicationSupportsMultipleScenes, +/// which also lets iPadOS open more windows of the app, and one React tree +/// plays one stream, so the second is refused rather than given a second +/// player. @available(iOSApplicationExtension, unavailable) @objc(SubwavePhoneSceneDelegate) final class PhoneSceneDelegate: ExpoAppSceneDelegate { @@ -172,25 +192,32 @@ final class PhoneSceneDelegate: ExpoAppSceneDelegate { guard let windowScene = scene as? UIWindowScene, let provider = UIApplication.shared.delegate as? ExpoReactNativeFactoryProvider, - let running = provider.window, - running.windowScene == nil + let running = provider.window else { super.scene(scene, willConnectTo: session, options: connectionOptions) return } + if running.windowScene != nil { + UIApplication.shared.requestSceneSessionDestruction(session, options: nil, errorHandler: nil) + return + } running.windowScene = windowScene + // ReactBoot made it with no screen to size it by. + running.frame = windowScene.coordinateSpace.bounds window = running running.makeKeyAndVisible() - // What ExpoAppSceneDelegate would forward. React Native was started - // before this scene existed, so a link that opened the app arrives as an - // event rather than as Linking.getInitialURL(). - let app = UIApplication.shared - for context in connectionOptions.urlContexts { - _ = app.delegate?.application?(app, open: context.url, options: [:]) + // What ExpoAppSceneDelegate forwards after its own start, through its own + // handlers, so the open options, the RCTLinkingManager fallback and its + // dedupe stay Expo's. React Native was started before this scene existed, + // so a link that opened the app arrives as a `url` event rather than as + // Linking.getInitialURL(). Re-check on the SDK 58 upgrade (TESTING.md). + if !connectionOptions.urlContexts.isEmpty { + self.scene(scene, openURLContexts: connectionOptions.urlContexts) } - for activity in connectionOptions.userActivities { - _ = app.delegate?.application?(app, continue: activity) { _ in } + connectionOptions.userActivities.forEach { self.scene(scene, continue: $0) } + if let shortcutItem = connectionOptions.shortcutItem { + self.windowScene(windowScene, performActionFor: shortcutItem) { _ in } } } }