From 2d17a3a934885467c6024bb9d8a38879480e9ba7 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 14:35:02 +0000 Subject: [PATCH 1/7] feat(app): Siri, Shortcuts, Control Center and Spotlight for the iOS app Ported from perminder-klair/subwave#2113, rebased onto stream recovery (#2114/#2139) and the idle skip (#9). --- CLAUDE.md | 3 +- app.json | 7 +- docs/RELEASE.md | 7 + docs/TESTING.md | 132 ++++++++++++- eas.json | 18 +- index.ts | 4 + modules/app-intents/expo-module.config.json | 6 + modules/app-intents/index.ts | 96 +++++++++ .../app-intents/ios/SubwaveAppIntents.podspec | 19 ++ .../ios/SubwaveAppIntentsModule.swift | 133 +++++++++++++ modules/live-activity/index.ts | 20 +- scripts/intent-on-air.test.ts | 92 +++++++++ scripts/intent-request.test.ts | 117 +++++++++++ scripts/intent-stations.test.ts | 51 +++++ src/audio/player.ts | 26 +++ src/config/StationContext.tsx | 73 +++++-- src/hooks/useLiveActivity.ts | 42 +++- src/hooks/usePlayer.ts | 65 ++++++- src/hooks/useStationFeed.ts | 20 +- src/hooks/useTrackLike.ts | 15 ++ src/intents/handlers.ts | 32 +++ src/intents/on-air-reply.ts | 63 ++++++ src/intents/on-air.ts | 68 +++++++ src/intents/request-reply.ts | 77 ++++++++ src/intents/station.ts | 28 +++ src/intents/tune.ts | 164 ++++++++++++++++ src/lib/heard-track.ts | 40 ++++ src/lib/like-events.ts | 28 +++ src/lib/station-store.ts | 46 ++++- src/lib/station.ts | 22 +++ .../live-activity/SubwaveLiveActivity.swift | 91 ++++++++- targets/live-activity/TuneControl.swift | 45 +++++ .../_shared/AudioSchemaIntents.swift | 184 ++++++++++++++++++ .../_shared/LikeTrackIntent.swift | 5 + .../live-activity/_shared/OnAirIntents.swift | 43 ++++ .../_shared/RequestSongIntent.swift | 37 ++++ .../_shared/StationEntities.swift | 142 ++++++++++++++ .../_shared/SubwaveIntentBridge.swift | 120 ++++++++++++ .../_shared/SubwaveShortcuts.swift | 76 ++++++++ .../_shared/ToggleTuneIntent.swift | 31 +++ .../live-activity/_shared/TuneIntents.swift | 54 +++++ targets/live-activity/index.swift | 33 +++- 42 files changed, 2323 insertions(+), 52 deletions(-) create mode 100644 modules/app-intents/expo-module.config.json create mode 100644 modules/app-intents/index.ts create mode 100644 modules/app-intents/ios/SubwaveAppIntents.podspec create mode 100644 modules/app-intents/ios/SubwaveAppIntentsModule.swift create mode 100644 scripts/intent-on-air.test.ts create mode 100644 scripts/intent-request.test.ts create mode 100644 scripts/intent-stations.test.ts create mode 100644 src/intents/handlers.ts create mode 100644 src/intents/on-air-reply.ts create mode 100644 src/intents/on-air.ts create mode 100644 src/intents/request-reply.ts create mode 100644 src/intents/station.ts create mode 100644 src/intents/tune.ts create mode 100644 src/lib/heard-track.ts create mode 100644 src/lib/like-events.ts create mode 100644 targets/live-activity/TuneControl.swift create mode 100644 targets/live-activity/_shared/AudioSchemaIntents.swift create mode 100644 targets/live-activity/_shared/OnAirIntents.swift create mode 100644 targets/live-activity/_shared/RequestSongIntent.swift create mode 100644 targets/live-activity/_shared/StationEntities.swift create mode 100644 targets/live-activity/_shared/SubwaveIntentBridge.swift create mode 100644 targets/live-activity/_shared/SubwaveShortcuts.swift create mode 100644 targets/live-activity/_shared/ToggleTuneIntent.swift create mode 100644 targets/live-activity/_shared/TuneIntents.swift diff --git a/CLAUDE.md b/CLAUDE.md index 1e40698..88fe093 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,8 @@ The Expo / React Native player for iOS and Android, with its own `package.json`, - **New Architecture is mandatory**, and `patches/react-native-track-player+4.1.2.patch` is what makes RNTP run under it (Android crashes on the first playback event without it). Editing the patch or upgrading RNTP/KotlinAudio follows TESTING.md's adapter and device-check rules. - **`ios/` and `android/` are generated** (Continuous Native Generation, gitignored). Change `app.json`, `plugins/` or `assets/`, never the native folders. -- **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. `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. +- **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. - **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. 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 b63bedd..2035f01 100644 --- a/app.json +++ b/app.json @@ -31,6 +31,10 @@ "UIInterfaceOrientationLandscapeRight" ], "NSSupportsLiveActivities": true, + "INAlternativeAppNames": [ + { "INAlternativeAppName": "Sub Wave" }, + { "INAlternativeAppName": "Subwave" } + ], "NSLocalNetworkUsageDescription": "SUB/WAVE uses the local network to find Google Cast speakers and TVs on your Wi-Fi so you can send the station to them.", "UIBackgroundModes": [ "audio" @@ -87,7 +91,8 @@ "usesCleartextTraffic": true }, "ios": { - "deploymentTarget": "16.4" + "deploymentTarget": "16.4", + "enableSceneSupport": true } } ], diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 61d507f..3b0e78f 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -71,6 +71,13 @@ a branch at update time. (`production` auto-increments). Don't hand-edit `ios.buildNumber` / `android.versionCode`. +Every iOS profile pins `ios.image` to an **Xcode 27** image. EAS builds SDK 57 +with Xcode 26.6 by default, and the iOS 27 Siri support +(`targets/live-activity/_shared/AudioSchemaIntents.swift`) compiles only under +Xcode 27, so a default build would ship without it. Building with the iOS 27 +SDK in turn needs the UIScene life cycle (`ios.enableSceneSupport` in +`app.json`; TESTING.md). Move the pin forward with an Expo SDK upgrade. + --- ## OTA workflow diff --git a/docs/TESTING.md b/docs/TESTING.md index 7a4d77a..5192cef 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -65,6 +65,23 @@ On iOS, confirm the LIVE controls, artwork, and Live Activity still work; Cast should still tear down the local session. Bluetooth display of artwork and progress must also be checked in the car. +### The app uses the UIScene life cycle + +An app built with the **iOS 27 SDK** (Xcode 27) that has no scene manifest is +killed at launch on iOS 27, in +`_UIApplicationEvaluateRuntimeIssueForNoSceneLifecycleAdoption`. The SDK 57 +template still starts React Native from the app delegate, so `expo-build-properties` +`ios.enableSceneSupport` (Expo's own SDK 57 opt-in, expo 57.0.23+) does what the +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. + +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 +(`AudioSchemaIntents.swift`). Shipping that needs an Xcode 27 image +(`macos-tahoe-26.6-xcode-27.1`, also `latest`). + ### Other load-bearing facts - **Expo Go does not work** — native modules (RNTP, Skia, Reanimated worklets) @@ -233,7 +250,8 @@ stream in the phone app first, then connect the car. RNTP feeds the iOS surface - **iOS** — run on a device, or use the **CarPlay Simulator** (Simulator app → **I/O → External Displays → CarPlay**). Start the stream, open the CarPlay screen → SUB/WAVE shows under **Now Playing** with title/artist/album + artwork; - Play/Pause work; no scrubber (the `isLiveStream` track hides it). + 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. > **Android Auto is intentionally not declared.** The earlier > `plugins/withAndroidAuto.js` declaration (#444) was **rejected by Google Play** @@ -276,9 +294,17 @@ that drives ActivityKit, started and stopped by `src/hooks/useLiveActivity.ts`. The reason it exists is the **Apple Watch**: React Native does not run on watchOS, so a real watch app is a second, Swift-only codebase. iOS 18+ mirrors an iPhone -Live Activity into the **watch Smart Stack** for free — the same lock-screen -SwiftUI view, rendered on the wrist. One target, no watchOS project, no second -release path. +Live Activity into the **watch Smart Stack** for free, and iOS 26 puts it on the +**CarPlay Dashboard** too, with no CarPlay entitlement. One target, no watchOS +project, no second release path. + +Both of those surfaces draw the **`.small` activity family** (`SmallView`), not +the lock-screen view. Without the opt-in they fall back to the Dynamic Island's +compact views, an 18pt cover and a clock. The opt-in, +`supplementalActivityFamilies([.small])`, is iOS 18 API on a 17.0 target, so it +lives on its own widget (`SubwaveLiveActivityWithSmall`) and `index.swift` +registers exactly one of the two. CarPlay renders Live Activities +non-interactive, which is why `SmallView` has no heart. **The floor is iOS 17** (the widget target builds at 17.0 for the interactive heart). `isLiveActivitySupported()` is the only gate; below it the app behaves @@ -319,6 +345,104 @@ carries a `#Preview` so the layout can be worked on without a device. It cannot run in Expo Go, and the Dynamic Island needs a Pro-class device or the matching simulator. +### App Intents — Siri, Shortcuts, Spotlight (iOS only) + +"Tune in" and "Tune out" are `AudioPlaybackIntent`s with Siri phrases +("Tune in to SUB/WAVE", "Play SUB/WAVE"). The system runs an audio intent in the +**app's** process without bringing it forward, launching it into the background +when it is not running. iOS 18 adds the **tune control** (`TuneControl.swift`), +a toggle for Control Center, the Lock Screen and the Action button, driven by +`ToggleTuneIntent` through the same bridge. **Request a song** ("Request a song +on SUB/WAVE") has Siri ask what to play, sends it through the request drawer's +own `POST /request` and polling, and reads back the DJ's answer. It waits up to +10 s for the match, then says the request is in. **What's playing** and **Like +this song** both mean the track the listener is hearing: while the app is +playing, that is the previous track for the stream buffer's length after a +change (`src/lib/heard-track.ts`, the rule `useStationFeed` promotes tracks by). +The like goes through `POST /like`, which refuses a song that has ended, and +the in-app heart and the Live Activity fill straight away (`like-events.ts`). +The Live Activity's own heart is `LikeTrackIntent`, hidden from Shortcuts so +there is one "like" action there. + +**Saved stations** reach Siri, Shortcuts and Spotlight (iOS 18) as entities +(`StationEntities.swift`): "Play Night Shift on SUB/WAVE", Tune in's Station +parameter, and a Spotlight result that opens the app tuned to it. Swift cannot +read the station store, so `StationContext` mirrors names and credential-free +bases into the App Group (`setStations`), and the module then calls the +app-target `SubwaveStationIndex.reindex` by class name to refresh Spotlight and +the Siri phrases. A switch away from the active station is JS +(`src/intents/tune.ts`): it writes the store, stops the old stream, starts the +new one, and only then tells `StationContext`, so `usePlayer` finds the +playing stream already belongs to the new base (`streamBelongsTo`) and keeps +it. On iOS 27, `AudioSchemaIntents.swift` exposes the same stations to Siri's +audio search. + +The intents are thin. Each hands its action to JS and waits for the answer: + +- `targets/live-activity/_shared/`: the intents, and the Siri phrases in + `SubwaveShortcuts.swift`. +- `targets/live-activity/_shared/SubwaveIntentBridge.swift`: posts the request, + re-posts until acknowledged, waits for the reply. +- `modules/app-intents/`: the Expo module that acknowledges, holds requests + until JS subscribes, and posts JS's reply back. +- `src/intents/`: the JS that does the work, registered from `index.ts` beside + the playback service, not from a screen. + +What is easy to get wrong: + +- **The two Swift halves meet on NotificationCenter names, matched by string.** + `_shared/` also compiles into the widget extension, which cannot import the + module's pod. Change a name on one side, change it on the other. +- **The Siri phrases must not compile into the widget.** A second + `AppShortcutsProvider` in the extension made Shortcuts fail a shortcut with a + parameter to ask for ("Couldn't find AppShortcutsProvider"), though Tune in + still ran. `SubwaveShortcuts.swift` and `RequestSongIntent.swift` sit inside + `#if canImport(ExpoModulesCore)`, true only in the app target, because only it + links the Expo pods. Check the widget's `Metadata.appintents` lists no + shortcuts after a change there. +- **Intents must compile into the app target**, which is what `_shared/` does. + App Intents metadata is extracted per target, and an intent the system cannot + find in the app does not exist to Siri or Shortcuts. +- **A cold start depends on JS booting in the background.** The app uses the + UIScene life cycle (`ios.enableSceneSupport`), so React Native starts + when a scene connects. iOS connects one for an intent launch even though the + app is never shown, so JS boots (checked on iOS 18.5 and 27). If an intent + ever times out cold, look there first. +- **`usePlayer` must adopt audio it did not start.** A cold tune-in can reach + Playing before any screen mounts, so the hook reads the player's state on + mount. A tune-out goes through `externalTuneOut()`, or the hook reads the + Stopped event as a dead stream and reconnects. +- **ActivityKit refuses a background app.** `liveactivitiesd` logs "Requester + is not foreground" and the card never appears, though the audio plays. + Inside a `LiveActivityIntent`'s run the request is allowed, which is why + `TuneInIntent` is one and `tune.ts` holds its answer (up to 2 s) until the + card has been asked for. `useLiveActivity` also retries when the app comes + forward, for a tune-in that missed the window. +- **The control cannot ask the player.** It reads an on-air flag in the App + Group that `usePlayer` writes through `setOnAir`, which also reloads the + control. An app killed mid-song leaves the flag on until the next tap or + launch. The flag key and the control kind are matched by string between + `TuneControl.swift` and the app-intents module. +- **A control never resolves parameters.** `ToggleTuneIntent` is built with + `init(turningOn:)`; an instance with `value` unset installs and renders, then + does nothing when tapped. + +Test it cold, in a **Release** build: a Debug dev client loads its bundle from +Metro and the dev launcher, which a background launch does not exercise the way +the shipped app does. Kill the app, run **Tune in** from the Shortcuts app, and +confirm audio starts with the app still in the background; then open the app +and check the transport shows it as on air. + +Test **Request a song** and **Like this song** against a local stand-in, never +a live station: a test request really queues and the DJ may announce it, and a +like stars the song in the station's Navidrome. Any server answering +`/api/health`, `POST /api/request`, `GET /api/request/:id`, `/api/now-playing`, +`/api/state` and `POST /api/like` will do; add it in onboarding as +`http://localhost:`. **What's playing** only reads, so a live station is +fine, and the place to check the lag: tune in, wait for `/api/now-playing` to +change, and ask at once; it should name the previous track. Keep test files +out of `ios/build/`, which `expo prebuild` wipes. + --- diff --git a/eas.json b/eas.json index b0bc766..b229767 100644 --- a/eas.json +++ b/eas.json @@ -8,22 +8,32 @@ "developmentClient": true, "distribution": "internal", "ios": { - "simulator": true + "simulator": true, + "image": "macos-tahoe-26.6-xcode-27.1" } }, "development-device": { "developmentClient": true, - "distribution": "internal" + "distribution": "internal", + "ios": { + "image": "macos-tahoe-26.6-xcode-27.1" + } }, "preview": { "distribution": "internal", "channel": "preview", - "ios": { "simulator": false }, + "ios": { + "simulator": false, + "image": "macos-tahoe-26.6-xcode-27.1" + }, "android": { "buildType": "apk" } }, "production": { "autoIncrement": true, - "channel": "production" + "channel": "production", + "ios": { + "image": "macos-tahoe-26.6-xcode-27.1" + } } }, "submit": { diff --git a/index.ts b/index.ts index 23b0ee7..bbdf33e 100644 --- a/index.ts +++ b/index.ts @@ -1,10 +1,14 @@ // App entry: register the RNTP playback service so OS media controls reach our // remote handlers even when the JS UI isn't mounted, then hand off to // expo-router. The service MUST be registered before the router entry runs. +// App Intents register here for the same reason: Siri or a Control can launch +// the app into the background, where no screen may ever mount. import TrackPlayer from 'react-native-track-player'; +import { registerIntentHandlers } from '@/intents/handlers'; import { PlaybackService } from './service'; TrackPlayer.registerPlaybackService(() => PlaybackService); +registerIntentHandlers(); // Registration must run before the router starts the app. // eslint-disable-next-line import/first diff --git a/modules/app-intents/expo-module.config.json b/modules/app-intents/expo-module.config.json new file mode 100644 index 0000000..5d624e7 --- /dev/null +++ b/modules/app-intents/expo-module.config.json @@ -0,0 +1,6 @@ +{ + "platforms": ["apple"], + "apple": { + "modules": ["SubwaveAppIntentsModule"] + } +} diff --git a/modules/app-intents/index.ts b/modules/app-intents/index.ts new file mode 100644 index 0000000..26f789a --- /dev/null +++ b/modules/app-intents/index.ts @@ -0,0 +1,96 @@ +// The JS half of the App Intents bridge. A Swift intent (Siri, Shortcuts, a +// Control) names an action; the handler set here performs it and its answer +// goes back to the waiting intent. A no-op outside iOS. + +import { requireNativeModule } from 'expo-modules-core'; +import { Platform } from 'react-native'; + +export interface IntentReply { + ok: boolean; + /** Spoken by Siri, or shown by Shortcuts: the error when `ok` is false, the + * answer for an intent that has one (a song request). */ + message?: string; +} + +export type IntentHandler = ( + action: string, + args: Record, +) => Promise; + +interface IntentRequest { + token: string; + action: string; + args?: Record; +} + +interface Subscription { + remove(): void; +} + +interface NativeAppIntents { + reply(token: string, ok: boolean, message: string | null): void; + setOnAir(onAir: boolean): void; + setStations(json: string): void; + addListener(event: 'onIntent', fn: (request: IntentRequest) => void): Subscription; +} + +// Android and binaries older than the bridge lack this module, and an OTA +// update must not crash them. +const native: NativeAppIntents | null = (() => { + if (Platform.OS !== 'ios') return null; + try { + return requireNativeModule('SubwaveAppIntents') as unknown as NativeAppIntents; + } catch { + return null; + } +})(); + +/** Tell the tune control (Control Center, Lock Screen, Action button) whether + * the station is on. The control cannot ask the player, so it shows this. */ +export function setOnAir(onAir: boolean): void { + try { + native?.setOnAir(onAir); + } catch { + /* a binary older than the control */ + } +} + +export interface SiriStation { + /** The credential-free base URL, which is how Siri and Spotlight refer back + * to it. */ + id: string; + name: string; +} + +/** The saved stations and the active one, for Siri, Shortcuts and Spotlight, + * which cannot read the station store. Names and bases only: never a login + * or a station password. Re-indexes Spotlight. */ +export function setStations(active: string | null, stations: SiriStation[]): void { + try { + native?.setStations(JSON.stringify({ active, stations })); + } catch { + /* a binary older than station support for Siri */ + } +} + +/** Subscribing is what releases requests the module held while JS booted, so + * call this once, early, outside the React tree. */ +export function setIntentHandler(handler: IntentHandler): Subscription | null { + if (!native) return null; + const bridge = native; + try { + return bridge.addListener('onIntent', ({ token, action, args }) => { + void handler(action, args ?? {}) + .catch((): IntentReply => ({ ok: false })) + .then((reply) => { + try { + bridge.reply(token, reply.ok, reply.message ?? null); + } catch { + /* the intent gives up on its own */ + } + }); + }); + } catch { + return null; + } +} diff --git a/modules/app-intents/ios/SubwaveAppIntents.podspec b/modules/app-intents/ios/SubwaveAppIntents.podspec new file mode 100644 index 0000000..33fd6f7 --- /dev/null +++ b/modules/app-intents/ios/SubwaveAppIntents.podspec @@ -0,0 +1,19 @@ +Pod::Spec.new do |s| + s.name = 'SubwaveAppIntents' + s.version = '1.0.0' + s.summary = 'The app half of the SUB/WAVE App Intents bridge' + s.description = 'Hands Siri, Shortcuts and Control requests to JS and posts the answer back to the waiting intent.' + s.author = 'SUB/WAVE' + s.homepage = 'https://www.getsubwave.com' + s.platforms = { :ios => '16.4' } + s.source = { git: '' } + s.static_framework = true + + s.dependency 'ExpoModulesCore' + + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES' + } + + s.source_files = '**/*.{h,m,swift}' +end diff --git a/modules/app-intents/ios/SubwaveAppIntentsModule.swift b/modules/app-intents/ios/SubwaveAppIntentsModule.swift new file mode 100644 index 0000000..d82edfc --- /dev/null +++ b/modules/app-intents/ios/SubwaveAppIntentsModule.swift @@ -0,0 +1,133 @@ +import ExpoModulesCore +import Foundation +import WidgetKit + +// The app half of the App Intents bridge: Siri, Shortcuts and Controls ask, +// JS answers. +// +// The intent half is targets/live-activity/_shared/SubwaveIntentBridge.swift. +// It compiles into the app target (and the widget, which needs the intent +// types for its controls) and cannot import this pod, so the two meet on +// in-process NotificationCenter names, matched by STRING. Change one side, +// change both. +// +// An intent can run before React Native has finished booting: Siri, Shortcuts +// or a Control can launch a killed app straight into the background. So a +// request is acknowledged as soon as this module exists, held until JS +// subscribes, and the intent keeps re-posting until it sees the ack. The work +// itself is all JS (src/intents/), through the same station store, credential +// vault and player the UI uses, which keeps station URLs and credentials out +// of Swift, as LikeTrackIntent does. + +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. +private let appGroup = "group.com.getsubwave.app" +private let onAirKey = "subwave.onAir" +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. +private let stationsKey = "subwave.stations" +private let stationIndexClass = "SubwaveStationIndex" + +public class SubwaveAppIntentsModule: Module { + private var requestObserver: NSObjectProtocol? + // Main-queue only: the observer delivers there and the JS-thread hooks hop + // onto it. + private var listening = false + private var pending: [[String: Any]] = [] + /// Tokens already taken in. The intent re-posts until it sees an ack, so a + /// request can arrive more than once. + private var seen = Set() + + public func definition() -> ModuleDefinition { + Name("SubwaveAppIntents") + + Events("onIntent") + + OnCreate { + self.requestObserver = NotificationCenter.default.addObserver( + forName: requestName, + object: nil, + queue: .main + ) { [weak self] note in + self?.receive(note.userInfo) + } + } + + OnDestroy { + if let observer = self.requestObserver { + NotificationCenter.default.removeObserver(observer) + } + self.requestObserver = nil + } + + OnStartObserving { + DispatchQueue.main.async { + self.listening = true + let queued = self.pending + self.pending = [] + queued.forEach { self.sendEvent("onIntent", $0) } + } + } + + OnStopObserving { + DispatchQueue.main.async { + self.listening = false + } + } + + /// JS's answer to one request. `message` is what Siri says or Shortcuts + /// shows: the error when `ok` is false, the answer when an intent has one. + Function("reply") { (token: String, ok: Bool, message: String?) in + var info: [String: Any] = ["token": token, "ok": ok] + if let message { + info["message"] = message + } + NotificationCenter.default.post(name: replyName, object: nil, userInfo: info) + } + + /// Whether the station is on, for the tune control, which cannot ask the + /// player. Reloads the control only on a change. + Function("setOnAir") { (onAir: Bool) in + guard let defaults = UserDefaults(suiteName: appGroup) else { return } + if defaults.object(forKey: onAirKey) as? Bool == onAir { return } + defaults.set(onAir, forKey: onAirKey) + if #available(iOS 18.0, *) { + ControlCenter.shared.reloadControls(ofKind: tuneControlKind) + } + } + + /// 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. + Function("setStations") { (json: String) in + UserDefaults(suiteName: appGroup)?.set(json, forKey: stationsKey) + if let index: AnyClass = NSClassFromString(stationIndexClass) { + _ = (index as AnyObject).perform(NSSelectorFromString("reindex")) + } + } + } + + private func receive(_ info: [AnyHashable: Any]?) { + guard + let token = info?["token"] as? String, + let action = info?["action"] as? String + else { return } + NotificationCenter.default.post(name: ackName, object: nil, userInfo: ["token": token]) + guard seen.insert(token).inserted else { return } + let args = info?["args"] as? [String: String] ?? [:] + let request: [String: Any] = ["token": token, "action": action, "args": args] + if listening { + sendEvent("onIntent", request) + } else { + pending.append(request) + } + } +} diff --git a/modules/live-activity/index.ts b/modules/live-activity/index.ts index b9fba8f..313a0ff 100644 --- a/modules/live-activity/index.ts +++ b/modules/live-activity/index.ts @@ -74,16 +74,32 @@ export function isLiveActivitySupported(): boolean { } } +// Start outcomes, for a caller that has to wait for the card: an App Intent +// tune-in (src/intents/tune.ts). ActivityKit refuses a background app, so the +// intent's own run is the only window a card can start in, and it closes when +// the intent returns. +const startListeners = new Set<(ok: boolean) => void>(); + +export function onLiveActivityStart(fn: (ok: boolean) => void): () => void { + startListeners.add(fn); + return () => { + startListeners.delete(fn); + }; +} + /** Put the card up. Resolves false when the system refused it; never throws. */ export async function startLiveActivity( config: LiveActivityConfig, state: LiveActivityState, ): Promise { + let ok = false; try { - return (await native?.start(config, state)) ?? false; + ok = (await native?.start(config, state)) ?? false; } catch { - return false; + ok = false; } + startListeners.forEach((fn) => fn(ok)); + return ok; } /** Push a new snapshot to whatever card is up. No-op when none is. */ diff --git a/scripts/intent-on-air.test.ts b/scripts/intent-on-air.test.ts new file mode 100644 index 0000000..d98496f --- /dev/null +++ b/scripts/intent-on-air.test.ts @@ -0,0 +1,92 @@ +// "What's playing" and "like this song" from Siri: which track a tuned-in +// listener is hearing (src/lib/heard-track.ts, the rule useStationFeed +// promotes tracks by), and what Siri says about it +// (src/intents/on-air-reply.ts). + +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { audibleAt, heardTrack, leadMsFrom } from '../src/lib/heard-track.ts'; +import { + likeReply, + likeTarget, + whatsPlayingReply, + type OnAirSnapshot, +} from '../src/intents/on-air-reply.ts'; + +const live = { title: 'Teardrop', artist: 'Massive Attack', subsonic_id: 'tear' }; +const previous = { title: 'Unfinished Sympathy', artist: 'Massive Attack', subsonic_id: 'unfin' }; + +test('the stream buffer is clamped to 0–60 s, and absent when the station sent none', () => { + assert.equal(leadMsFrom(22), 22_000); + assert.equal(leadMsFrom(-5), 0); + assert.equal(leadMsFrom(600), 60_000); + assert.equal(leadMsFrom(undefined), null); + assert.equal(leadMsFrom(Number.NaN), null); + assert.equal(audibleAt(1_000, 22_000), 23_000); +}); + +test('for the buffer’s length after a change, the listener still hears the previous track', () => { + const at = (now: number) => heardTrack({ live, previous, liveStartMs: 100_000, leadMs: 22_000, now }); + assert.equal(at(110_000), previous); + assert.equal(at(121_999), previous); + assert.equal(at(122_000), live); +}); + +test('with no live-edge stamp, or nothing before it, the live track is the answer', () => { + assert.equal(heardTrack({ live, previous, liveStartMs: null, leadMs: 22_000, now: 0 }), live); + assert.equal(heardTrack({ live, previous: null, liveStartMs: 100_000, leadMs: 22_000, now: 110_000 }), live); +}); + +const snap = (over: Partial = {}): OnAirSnapshot => ({ + reachable: true, + online: true, + track: live, + ...over, +}); + +test('what’s playing names the track, or says why there is none', () => { + assert.deepEqual(whatsPlayingReply('SUB/WAVE', snap()), { + ok: true, + message: 'On SUB/WAVE: Teardrop by Massive Attack.', + }); + assert.deepEqual(whatsPlayingReply('SUB/WAVE', snap({ track: { title: 'Teardrop' } })), { + ok: true, + message: 'On SUB/WAVE: Teardrop.', + }); + assert.equal(whatsPlayingReply('SUB/WAVE', snap({ online: false })).message, 'SUB/WAVE is off air right now.'); + assert.equal( + whatsPlayingReply('SUB/WAVE', snap({ track: null })).message, + "Nothing's playing on SUB/WAVE right now.", + ); + assert.equal(whatsPlayingReply('SUB/WAVE', snap({ reachable: false })).ok, false); +}); + +test('a like needs a song id: a jingle or a spoken link never reaches POST /like', () => { + assert.deepEqual(likeTarget('SUB/WAVE', snap()), { songId: 'tear' }); + assert.deepEqual(likeTarget('SUB/WAVE', snap({ track: { title: 'Station ID' } })), { + ok: false, + message: 'Nothing likeable on air right now.', + }); + assert.equal((likeTarget('SUB/WAVE', snap({ reachable: false })) as { ok: boolean }).ok, false); +}); + +test('POST /like’s answer is said back, refusals in the station’s own words', () => { + assert.deepEqual(likeReply('SUB/WAVE', live, { ok: true, count: 3 }), { + ok: true, + message: 'Liked Teardrop by Massive Attack.', + }); + assert.deepEqual(likeReply('SUB/WAVE', live, { ok: true, alreadyLiked: true }), { + ok: true, + message: "You've already liked Teardrop by Massive Attack.", + }); + assert.deepEqual(likeReply('SUB/WAVE', live, { error: 'That track just ended' }), { + ok: false, + message: 'That track just ended.', + }); + assert.deepEqual(likeReply('SUB/WAVE', live, { error: 'Likes are disabled on this station.' }), { + ok: false, + message: 'Likes are disabled on this station.', + }); + assert.equal(likeReply('SUB/WAVE', live, {}).ok, false); + assert.equal(likeReply('SUB/WAVE', live, null).ok, false); +}); diff --git a/scripts/intent-request.test.ts b/scripts/intent-request.test.ts new file mode 100644 index 0000000..fe05e16 --- /dev/null +++ b/scripts/intent-request.test.ts @@ -0,0 +1,117 @@ +// "Request a song" from Siri (src/intents/request-reply.ts): what Siri says for +// each thing the station can answer, and that a slow match never keeps Siri +// waiting past the cap. + +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + ACCEPTED_MESSAGE, + askForSong, + REQUEST_WAIT_MS, + spokenAnswer, +} from '../src/intents/request-reply.ts'; +import type { RequestResult } from '../src/lib/types.ts'; + +/** A station whose POST answers `posted` and whose polls answer `polls` in + * turn, the last one repeating. A fake clock advances on every sleep. */ +function station(posted: RequestResult | Error, polls: RequestResult[] = []) { + let t = 0; + const sent: string[] = []; + let pollCount = 0; + return { + sent, + get pollCount() { + return pollCount; + }, + deps: { + api: { + postRequest: async (body: { text: string }) => { + sent.push(body.text); + if (posted instanceof Error) throw posted; + return posted; + }, + pollRequest: async () => { + pollCount += 1; + return polls[Math.min(pollCount - 1, polls.length - 1)]; + }, + }, + sleep: async (ms: number) => { + t += ms; + }, + now: () => t, + }, + }; +} + +const accepted: RequestResult = { success: true, requestId: 'r1', status: 'pending' }; + +test('a matched request is answered with the DJ’s own acknowledgement', async () => { + const s = station(accepted, [ + { success: false, status: 'pending' }, + { + success: true, + status: 'resolved', + outcome: 'matched', + ack: 'Teardrop, coming right up.', + track: { title: 'Teardrop', artist: 'Massive Attack' }, + }, + ]); + const reply = await askForSong(' teardrop by massive attack ', s.deps); + assert.deepEqual(reply, { ok: true, message: 'Teardrop, coming right up.' }); + assert.deepEqual(s.sent, ['teardrop by massive attack']); + assert.equal(s.pollCount, 2); +}); + +test('without an acknowledgement, the drawer’s label names the track', () => { + const track = { title: 'Teardrop', artist: 'Massive Attack' }; + assert.equal(spokenAnswer({ success: true, outcome: 'matched', track }), 'Queued: Teardrop by Massive Attack.'); + assert.equal( + spokenAnswer({ success: true, outcome: 'cooldown', track }), + 'Played recently: Teardrop by Massive Attack.', + ); + assert.equal(spokenAnswer({ success: true, outcome: 'matched', track: { title: 'Teardrop' } }), 'Queued: Teardrop.'); +}); + +test('a station refusal is passed on in the station’s own words', async () => { + const closed = station({ success: false, message: 'Requests are temporarily closed.' }); + assert.deepEqual(await askForSong('anything', closed.deps), { + ok: false, + message: 'Requests are temporarily closed.', + }); + + // A 400 carries `error`, not `message`. + const unreadable = station({ success: false, error: 'Empty request' } as RequestResult); + assert.deepEqual(await askForSong('anything', unreadable.deps), { ok: false, message: 'Empty request' }); +}); + +test('a failed match and an unreachable station are errors', async () => { + const noMatch = station(accepted, [{ success: false, status: 'failed', outcome: 'no-match' }]); + assert.deepEqual(await askForSong('zzz', noMatch.deps), { + ok: false, + message: 'No match — try different words.', + }); + + const offline = station(new Error('network')); + const reply = await askForSong('anything', offline.deps); + assert.equal(reply.ok, false); +}); + +test('a slow match stops polling at the cap and says the request is in', async () => { + const s = station(accepted, [{ success: false, status: 'pending' }]); + assert.deepEqual(await askForSong('something slow', s.deps), { ok: true, message: ACCEPTED_MESSAGE }); + assert.ok(s.pollCount > 0); + assert.ok(s.pollCount <= Math.ceil(REQUEST_WAIT_MS / 1500)); +}); + +test('a request the station lost stops polling at once', async () => { + const s = station(accepted, [{ success: false, status: 'unknown' }]); + assert.deepEqual(await askForSong('anything', s.deps), { ok: true, message: ACCEPTED_MESSAGE }); + assert.equal(s.pollCount, 1); +}); + +test('an empty request never reaches the station', async () => { + const s = station(accepted); + const reply = await askForSong(' ', s.deps); + assert.equal(reply.ok, false); + assert.deepEqual(s.sent, []); +}); diff --git a/scripts/intent-stations.test.ts b/scripts/intent-stations.test.ts new file mode 100644 index 0000000..dadc36b --- /dev/null +++ b/scripts/intent-stations.test.ts @@ -0,0 +1,51 @@ +// Saved stations for Siri, Shortcuts and Spotlight (src/lib/station-store.ts): +// the list they are given, finding a station by the id they hand back, and +// usePlayer keeping a stream a switch from Siri already started. + +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { findSavedStation, stationsForSiri, streamBelongsTo } from '../src/lib/station-store.ts'; + +const recents = [ + { url: 'https://radio.example.com', name: 'Night Shift', lastUsed: 2 }, + { url: 'https://www.getsubwave.com', name: 'SUB/WAVE', lastUsed: 1 }, +]; + +test('Siri gets names and credential-free bases, never a login', () => { + const list = stationsForSiri([ + ...recents, + { url: 'https://dj:secret@private.example.com/', name: 'Private' }, + ]); + assert.deepEqual(list, [ + { id: 'https://radio.example.com', name: 'Night Shift' }, + { id: 'https://www.getsubwave.com', name: 'SUB/WAVE' }, + { id: 'https://private.example.com', name: 'Private' }, + ]); + assert.ok(!JSON.stringify(list).includes('secret')); +}); + +test('a station saved without a name goes by its host, and a repeat is listed once', () => { + assert.deepEqual( + stationsForSiri([ + { url: 'https://radio.example.com', name: ' ' }, + { url: 'https://radio.example.com/', name: 'Night Shift' }, + ]), + [{ id: 'https://radio.example.com', name: 'radio.example.com' }], + ); +}); + +test('a station is found by the id Siri hands back, trailing slash or not', () => { + assert.equal(findSavedStation(recents, 'https://radio.example.com')?.name, 'Night Shift'); + assert.equal(findSavedStation(recents, 'https://radio.example.com/')?.name, 'Night Shift'); + assert.equal(findSavedStation(recents, 'https://elsewhere.example.com'), null); +}); + +test('a stream belongs to the station whose base it is built on', () => { + const base = 'https://radio.example.com'; + assert.ok(streamBelongsTo('https://radio.example.com/stream.mp3', base)); + assert.ok(streamBelongsTo('https://radio.example.com/stream.aac?auth=pw', base)); + assert.ok(streamBelongsTo('https://radio.example.com/stream.mp3', 'https://dj:pw@radio.example.com/')); + assert.ok(!streamBelongsTo('https://www.getsubwave.com/stream.mp3', base)); + // A host that merely starts the same is a different station. + assert.ok(!streamBelongsTo('https://radio.example.com.evil.net/stream.mp3', base)); +}); diff --git a/src/audio/player.ts b/src/audio/player.ts index b7d07d2..4e889f9 100644 --- a/src/audio/player.ts +++ b/src/audio/player.ts @@ -89,6 +89,32 @@ export async function loadAndPlay(meta: LiveTrackMeta): Promise { await TrackPlayer.play(); } +// A tune-out that reaches the player from outside the React tree without an +// RNTP remote event: an App Intent (src/intents/tune.ts). usePlayer must hear +// it before the Stopped event lands, or it reads Stopped as a dead stream and +// reconnects, the same trap RemotePause is handled for. +const tuneOutListeners = new Set<() => void>(); + +export function onExternalTuneOut(fn: () => void): () => void { + tuneOutListeners.add(fn); + return () => { + tuneOutListeners.delete(fn); + }; +} + +/** stop(), not teardown(): the Icecast connection drops, and lastLiveMeta + * survives so the next tune-in resumes at the live edge. */ +export async function externalTuneOut(): Promise { + tuneOutListeners.forEach((fn) => { + try { + fn(); + } catch { + /* a broken subscriber must not keep the stream running */ + } + }); + await TrackPlayer.stop(); +} + export async function teardown(): Promise { lastLiveMeta = null; try { diff --git a/src/config/StationContext.tsx b/src/config/StationContext.tsx index a8a16e1..9251028 100644 --- a/src/config/StationContext.tsx +++ b/src/config/StationContext.tsx @@ -7,6 +7,7 @@ import React, { useRef, useState, } from 'react'; +import { setStations } from '../../modules/app-intents'; import { teardown } from '@/audio/player'; import { createApi, type StationApi } from '@/lib/api'; import { @@ -16,6 +17,7 @@ import { loadStationCredentials, loadStationPassword, loadStations, + onStationStoreChanged, removeRecent, saveStationCredentials, saveStationPassword, @@ -24,6 +26,7 @@ import { type StationStore, } from '@/lib/station'; import { splitStationAddress, type StationCredentials } from '@/lib/station-credentials'; +import { stationsForSiri } from '@/lib/station-store'; interface StationContextValue { ready: boolean; @@ -51,6 +54,33 @@ interface StationContextValue { const Ctx = createContext(null); +/** The stored store plus the active station's login and password, as the + * screens need them. A keychain failure leaves either null rather than + * failing the read. */ +async function readStationState(): Promise<{ + store: StationStore; + credentials: StationCredentials | null; + password: string | null; +}> { + const s = await loadStations(); + let activeCredentials: StationCredentials | null = null; + let activePassword: string | null = null; + try { + activeCredentials = s.activeStation + ? await loadStationCredentials(s.activeStation) + : null; + } catch { + // Boot without credentials if the keychain fails; later actions report failure + // and leave the vault intact. + } + try { + activePassword = s.activeStation ? await loadStationPassword(s.activeStation) : null; + } catch { + // Same: a locked station then asks again rather than failing to boot. + } + return { store: s, credentials: activeCredentials, password: activePassword }; +} + export function StationProvider({ children }: { children: React.ReactNode }) { const [store, setStore] = useState({ activeStation: null, recents: [] }); const [credentials, setCredentials] = useState(null); @@ -65,23 +95,11 @@ export function StationProvider({ children }: { children: React.ReactNode }) { useEffect(() => { let alive = true; - loadStations().then(async (s) => { - let activeCredentials: StationCredentials | null = null; - let activePassword: string | null = null; - try { - activeCredentials = s.activeStation - ? await loadStationCredentials(s.activeStation) - : null; - } catch { - } - try { - activePassword = s.activeStation ? await loadStationPassword(s.activeStation) : null; - } catch { - } + readStationState().then((s) => { if (alive) { - setStore(s); - setCredentials(activeCredentials); - setStationPassword(activePassword); + setStore(s.store); + setCredentials(s.credentials); + setStationPassword(s.password); setReady(true); } }).catch(() => { @@ -92,6 +110,23 @@ export function StationProvider({ children }: { children: React.ReactNode }) { }; }, [setStationPassword]); + // A station switch from Siri, Shortcuts or Spotlight (src/intents/tune.ts) + // writes the store and starts the new stream itself; follow it. No teardown, + // unlike selectStation: the stream already playing is the new station's. + useEffect( + () => + onStationStoreChanged(() => { + readStationState() + .then((s) => { + setCredentials(s.credentials); + setStationPassword(s.password); + setStore(s.store); + }) + .catch(() => {}); + }), + [setStationPassword], + ); + const selectStation = useCallback(async ( ref: StationRef, suppliedCredentials?: StationCredentials | null, @@ -162,6 +197,12 @@ export function StationProvider({ children }: { children: React.ReactNode }) { return store.recents.find((r) => r.url === base)?.name ?? null; }, [base, store.recents]); + // Siri, Shortcuts and Spotlight know the saved stations by name, and cannot + // read this store. + useEffect(() => { + if (ready) setStations(base, stationsForSiri(store.recents)); + }, [ready, base, store.recents]); + const value = useMemo( () => ({ ready, diff --git a/src/hooks/useLiveActivity.ts b/src/hooks/useLiveActivity.ts index 9832985..7f89f58 100644 --- a/src/hooks/useLiveActivity.ts +++ b/src/hooks/useLiveActivity.ts @@ -9,6 +9,7 @@ import { updateLiveActivity, type LiveActivityState, } from '../../modules/live-activity'; +import { useAppActive } from '@/hooks/useAppActive'; import { useTalking } from '@/hooks/useTalking'; import type { TrackLike } from '@/hooks/useTrackLike'; import { resolveAirCard } from '@/lib/air-card'; @@ -91,21 +92,60 @@ export function useLiveActivity({ void updateLiveActivity(state); }, [state]); - // Accent is immutable in ActivityKit attributes. + // Two starts in flight at once can each clear the old card before either + // requests a new one, which stacks two. + const startingRef = useRef(false); + // Bumped on every teardown, so a start that resolves after one can tell. + const lifecycleRef = useRef(0); + const tunedInRef = useRef(tunedIn); + useEffect(() => { + tunedInRef.current = tunedIn; + }, [tunedIn]); + + // Accent is immutable in ActivityKit attributes; a theme change restarts the card. useEffect(() => { if (!supported || !api || !tunedIn) return; let cancelled = false; void (async () => { + startingRef.current = true; const ok = await startLiveActivity({ station, accent }, stateRef.current); + startingRef.current = false; if (!cancelled) startedRef.current = ok; })(); return () => { cancelled = true; + lifecycleRef.current += 1; startedRef.current = false; void stopLiveActivity(); }; }, [supported, api, tunedIn, station, accent]); + // ActivityKit refuses a background app outside a LiveActivityIntent's run, + // so a tune-in from Siri or a Shortcut can miss its card (src/intents/tune.ts + // waits for it, up to a cap). Put it up the next time the app comes forward. + // Keyed on the transition, so an in-app tune-in is left to the effect above. + const active = useAppActive(); + const wasActiveRef = useRef(active); + useEffect(() => { + const cameForward = active && !wasActiveRef.current; + wasActiveRef.current = active; + if (!cameForward || !supported || !api || !tunedIn) return; + if (startedRef.current || startingRef.current) return; + const lifecycle = lifecycleRef.current; + void (async () => { + startingRef.current = true; + const ok = await startLiveActivity({ station, accent }, stateRef.current); + startingRef.current = false; + if (lifecycleRef.current === lifecycle) { + startedRef.current = ok; + } else if (ok && !tunedInRef.current) { + // Tuned out while this was in flight: the teardown's stop ran first. + void stopLiveActivity(); + } + })(); + }, [active, supported, api, tunedIn, station, accent]); + + // The persistent listener must call the current track's like closure. const likeRef = useRef(like); useEffect(() => { likeRef.current = like; diff --git a/src/hooks/usePlayer.ts b/src/hooks/usePlayer.ts index 59d4158..3c0f72e 100644 --- a/src/hooks/usePlayer.ts +++ b/src/hooks/usePlayer.ts @@ -9,13 +9,21 @@ import { addAudioRouteChangeListener, ROUTE_REASON_OLD_DEVICE_UNAVAILABLE, } from '../../modules/airplay-route-picker'; -import { getLastLiveMeta, loadAndPlay, setupPlayer, teardown } from '@/audio/player'; +import { setOnAir } from '../../modules/app-intents'; +import { + getLastLiveMeta, + loadAndPlay, + onExternalTuneOut, + setupPlayer, + teardown, +} from '@/audio/player'; import type { StationApi } from '@/lib/api'; import { SKIP_CUSHION_SECONDS } from '@/lib/idle-skip'; import { IdleSkip } from '@/lib/idle-skip-playback'; import { playbackEventLine, playbackLog } from '@/lib/playback-log'; import { claimRemotePlay } from '@/lib/remote-play'; import { MAX_LEAD_SECONDS } from '@/lib/sessionFeed'; +import { streamBelongsTo } from '@/lib/station-store'; import { StreamRecovery } from '@/lib/stream-recovery'; import type { StreamFormat } from '@/lib/streamFormat'; import { loadVolumePref, saveVolumePref } from '@/lib/volume'; @@ -219,6 +227,50 @@ export function usePlayer( }, ); + // A tune-in that started before this hook mounted: an App Intent can launch + // the app into the background and start the stream (src/intents/tune.ts) + // while the screens are still loading, so the Playing event that would + // adopt it has already fired. + useEffect(() => { + let alive = true; + TrackPlayer.getPlaybackState() + .then(({ state }) => { + if (!alive || tunedInRef.current || !getLastLiveMeta()) return; + if (state !== State.Playing && state !== State.Buffering && state !== State.Loading) { + return; + } + tunedInRef.current = true; + setTunedIn(true); + setStatus(state === State.Playing ? 'playing' : 'connecting'); + recoveryRef.current?.adopt(); + }) + .catch(() => {}); + return () => { + alive = false; + }; + }, []); + + // The tune control (targets/live-activity/TuneControl.swift) cannot ask the + // player, so it shows this. Written on mount too, which clears a flag an + // app killed mid-song left on. + useEffect(() => { + setOnAir(tunedIn); + }, [tunedIn]); + + // An App Intent tune-out (src/intents/tune.ts): the same synchronous ref + // flip as the RemotePause handler above, ahead of the Stopped event. + useEffect( + () => + onExternalTuneOut(() => { + recoveryRef.current?.tuneOut(); + endIdleSkip(); + tunedInRef.current = false; + setTunedIn(false); + setStatus('idle'); + }), + [endIdleSkip], + ); + // iOS: an oldDeviceUnavailable route change (Bluetooth speaker off, CarPlay // disconnected, headphones unplugged) is a tune-out (#992) — the // longFormAudio session policy keeps AVPlayer "playing" to the vanished @@ -257,12 +309,21 @@ export function usePlayer( teardown().catch(() => {}); }, [endIdleSkip]); + // On a station switch selectStation has already torn the stream down at the + // RNTP level; drop local tuned-in state so the UI doesn't claim "on air" + // over dead audio. (The event handler ignores State.None because reset() + // also fires it mid tune-in and mid reconnect.) + // One exception: a switch from Siri, Shortcuts or Spotlight + // (src/intents/tune.ts) starts the new station's stream before the base + // changes here. A stream that already belongs to the new base is kept. const prevBaseRef = useRef(api?.base ?? null); useEffect(() => { const nextBase = api?.base ?? null; if (prevBaseRef.current === nextBase) return; prevBaseRef.current = nextBase; - if (tunedInRef.current) stop(); + const meta = getLastLiveMeta(); + const adopted = !!(nextBase && meta && streamBelongsTo(meta.url, nextBase)); + if (tunedInRef.current && !adopted) stop(); }, [api, stop]); const prevFormatRef = useRef(streamFormat); diff --git a/src/hooks/useStationFeed.ts b/src/hooks/useStationFeed.ts index 7d874ed..9ea9969 100644 --- a/src/hooks/useStationFeed.ts +++ b/src/hooks/useStationFeed.ts @@ -4,7 +4,8 @@ import type { StationApi } from '@/lib/api'; import { feedState } from '@/lib/feed-state'; import { pollAsync } from '@/lib/poll'; import { DEFAULT_STATION_LOCALE, type StationLocale } from '@/lib/format'; -import { MAX_LEAD_SECONDS, splitAudibleTurns } from '@/lib/sessionFeed'; +import { audibleAt as audibleAtLiveEdge, leadMsFrom } from '@/lib/heard-track'; +import { splitAudibleTurns } from '@/lib/sessionFeed'; import { trackElapsedSeconds } from '@/lib/track-progress'; import type { ActiveShow, @@ -158,10 +159,12 @@ export function useStationFeed( const applyNowPlaying = (npRes: NowPlayingResponse, current?: StationState['current']) => { const np = npRes.nowPlaying; - const bufSec = npRes.stream?.bufferSeconds; - if (typeof bufSec === 'number' && Number.isFinite(bufSec)) { - bufferMsRef.current = Math.min(Math.max(bufSec, 0), MAX_LEAD_SECONDS) * 1000; - leadMsRef.current = Math.max(0, bufferMsRef.current - trimMsRef.current); + // Buffer depth first; everything below is measured against it, less + // whatever the idle skip shed. + const buf = leadMsFrom(npRes.stream?.bufferSeconds); + if (buf != null) { + bufferMsRef.current = buf; + leadMsRef.current = Math.max(0, buf - trimMsRef.current); setLeadMs(leadMsRef.current); } const trackKey = np ? `${np.title}\0${np.artist}` : null; @@ -171,7 +174,12 @@ export function useStationFeed( const t = Date.parse(current.startedAt); if (Number.isFinite(t) && t <= Date.now()) serverStart = t; } - const audibleAt = Number.isFinite(serverStart) ? serverStart + leadMsRef.current : Date.now(); + // Shift into listener-time: the audio arrives leadMs after the live edge. + // With no server stamp, fall back to first-seen (no offset); the next + // foreground tick carries /state and repairs it in the converge branch. + const audibleAt = Number.isFinite(serverStart) + ? audibleAtLiveEdge(serverStart, leadMsRef.current) + : Date.now(); if (trackKey !== lastTrackKeyRef.current) { const commit = () => { diff --git a/src/hooks/useTrackLike.ts b/src/hooks/useTrackLike.ts index aa7edd0..390b00c 100644 --- a/src/hooks/useTrackLike.ts +++ b/src/hooks/useTrackLike.ts @@ -1,5 +1,6 @@ import { useCallback, useEffect, useState } from 'react'; import type { StationApi } from '@/lib/api'; +import { onExternalLike } from '@/lib/like-events'; export interface TrackLike { available: boolean; @@ -33,6 +34,20 @@ export function useTrackLike(api: StationApi | null, songId: string | null): Tra }; }, [api, songId]); + // A like from Siri for this same song. + useEffect( + () => + onExternalLike((ext) => { + if (!songId || ext.songId !== songId) return; + setState((prev) => ({ + songId, + liked: true, + count: ext.count ?? (prev.songId === songId ? prev.count : 0), + })); + }), + [songId], + ); + const like = useCallback(async () => { if (!api || !songId || pending || (state.liked && state.songId === songId)) return; setPending(true); diff --git a/src/intents/handlers.ts b/src/intents/handlers.ts new file mode 100644 index 0000000..f486d0e --- /dev/null +++ b/src/intents/handlers.ts @@ -0,0 +1,32 @@ +// Routes App Intents (modules/app-intents) to the code that performs them. +// Registered from index.ts beside the playback service rather than from a +// screen, because an intent can launch the app into the background before any +// screen mounts. + +import { setIntentHandler } from '../../modules/app-intents'; +import { likeHeardTrack, whatsPlaying } from './on-air'; +import { askForSong } from './request-reply'; +import { activeStation, NO_STATION_MESSAGE } from './station'; +import { tuneIn, tuneOut } from './tune'; + +export function registerIntentHandlers(): void { + setIntentHandler(async (action, args) => { + switch (action) { + case 'tuneIn': + return tuneIn(args.station); + case 'tuneOut': + return tuneOut(); + case 'request': + case 'nowPlaying': + case 'like': { + const station = await activeStation(); + if (!station) return { ok: false, message: NO_STATION_MESSAGE }; + if (action === 'request') return askForSong(args.text ?? '', { api: station.api }); + if (action === 'nowPlaying') return whatsPlaying(station); + return likeHeardTrack(station); + } + default: + return { ok: false, message: 'Update SUB/WAVE to use this.' }; + } + }); +} diff --git a/src/intents/on-air-reply.ts b/src/intents/on-air-reply.ts new file mode 100644 index 0000000..3d7e4fe --- /dev/null +++ b/src/intents/on-air-reply.ts @@ -0,0 +1,63 @@ +// What Siri says for "what's playing on SUB/WAVE" and "like this song on +// SUB/WAVE". Pure, so scripts/intent-on-air.test.ts can drive it; the fetching +// and the choice of track are in src/intents/on-air.ts. + +import type { IntentReply } from '../../modules/app-intents'; +import type { LikeResult } from '../lib/types'; + +/** Enough of a now-playing track or a history entry to name it and like it. */ +export interface OnAirTrack { + title?: string; + artist?: string; + subsonic_id?: string; +} + +/** One read of the station for the listener: whether it answered, whether + * the stream is up, and the track they are hearing. */ +export interface OnAirSnapshot { + reachable: boolean; + /** False only when the station said its stream is down. */ + online: boolean; + track: OnAirTrack | null; +} + +export function unreachableReply(station: string): IntentReply { + return { ok: false, message: `Couldn't reach ${station}. Check your connection and try again.` }; +} + +/** Ends a sentence once: POST /like's messages carry no full stop. */ +function sentence(text: string): string { + return /[.!?]$/.test(text) ? text : `${text}.`; +} + +function named(track: OnAirTrack): string { + return track.artist ? `${track.title} by ${track.artist}` : `${track.title}`; +} + +export function whatsPlayingReply(station: string, snap: OnAirSnapshot): IntentReply { + if (!snap.reachable) return unreachableReply(station); + if (!snap.online) return { ok: true, message: `${station} is off air right now.` }; + if (!snap.track?.title) return { ok: true, message: `Nothing's playing on ${station} right now.` }; + return { ok: true, message: `On ${station}: ${named(snap.track)}.` }; +} + +// Mirrors POST /like's own refusal, for the case that never reaches it: a +// jingle or a spoken segment carries no song id. +const NOTHING_TO_LIKE = 'Nothing likeable on air right now'; + +/** Whether there is a song to send to POST /like, and if not, what to say. */ +export function likeTarget(station: string, snap: OnAirSnapshot): { songId: string } | IntentReply { + if (!snap.reachable) return unreachableReply(station); + if (!snap.online || !snap.track?.subsonic_id) return { ok: false, message: sentence(NOTHING_TO_LIKE) }; + return { songId: snap.track.subsonic_id }; +} + +/** POST /like's answer in words. A refusal (likes off, the song just ended, + * too many likes) is the station's own message. */ +export function likeReply(station: string, track: OnAirTrack, result: LikeResult | null): IntentReply { + if (!result) return unreachableReply(station); + if (result.error) return { ok: false, message: sentence(result.error) }; + if (result.alreadyLiked) return { ok: true, message: `You've already liked ${named(track)}.` }; + if (!result.ok) return { ok: false, message: `${station} didn't take the like.` }; + return { ok: true, message: `Liked ${named(track)}.` }; +} diff --git a/src/intents/on-air.ts b/src/intents/on-air.ts new file mode 100644 index 0000000..711f32b --- /dev/null +++ b/src/intents/on-air.ts @@ -0,0 +1,68 @@ +// "What's playing on SUB/WAVE" and "like this song on SUB/WAVE". Both mean the +// track the listener is hearing: the live edge, or, while this app is playing, +// the previous track for the stream buffer's length after a change +// (heardTrack, the rule useStationFeed promotes tracks by). + +import TrackPlayer, { State } from 'react-native-track-player'; +import type { IntentReply } from '../../modules/app-intents'; +import { heardTrack, leadMsFrom } from '@/lib/heard-track'; +import { announceLike } from '@/lib/like-events'; +import type { StationApi } from '@/lib/api'; +import { + likeReply, + likeTarget, + whatsPlayingReply, + type OnAirSnapshot, + type OnAirTrack, +} from './on-air-reply'; +import type { IntentStation } from './station'; + +async function playingHere(): Promise { + const { state } = await TrackPlayer.getPlaybackState().catch(() => ({ state: State.None })); + return state === State.Playing || state === State.Buffering; +} + +async function snapshot(api: StationApi): Promise { + const [npRes, stateRes] = await Promise.allSettled([api.nowPlaying(), api.state()]); + if (npRes.status !== 'fulfilled') return { reachable: false, online: false, track: null }; + const np = npRes.value; + const live: OnAirTrack | null = np.nowPlaying; + const online = np.streamOnline !== false; + if (!(await playingHere()) || stateRes.status !== 'fulfilled') { + return { reachable: true, online, track: live }; + } + // The same pairing useStationFeed makes: /state's live-edge stamp only + // counts when it is for the track /now-playing names. + const current = stateRes.value.current; + const stamp = live?.title && current?.title === live.title && current.startedAt + ? Date.parse(current.startedAt) + : NaN; + const track = heardTrack({ + live, + previous: stateRes.value.history?.[0] ?? null, + liveStartMs: Number.isFinite(stamp) ? stamp : null, + leadMs: leadMsFrom(np.stream?.bufferSeconds) ?? 0, + now: Date.now(), + }); + return { reachable: true, online, track }; +} + +function stationName(station: IntentStation): string { + return station.name || 'SUB/WAVE'; +} + +export async function whatsPlaying(station: IntentStation): Promise { + return whatsPlayingReply(stationName(station), await snapshot(station.api)); +} + +export async function likeHeardTrack(station: IntentStation): Promise { + const name = stationName(station); + const snap = await snapshot(station.api); + const target = likeTarget(name, snap); + if (!('songId' in target)) return target; + const result = await station.api.likeCurrent(target.songId); + if (result && !result.error && (result.ok || result.alreadyLiked)) { + announceLike({ songId: target.songId, count: result.count }); + } + return likeReply(name, snap.track ?? {}, result); +} diff --git a/src/intents/request-reply.ts b/src/intents/request-reply.ts new file mode 100644 index 0000000..6e40f76 --- /dev/null +++ b/src/intents/request-reply.ts @@ -0,0 +1,77 @@ +// What Siri says back to "request a song on SUB/WAVE" (RequestSongIntent). The +// same POST /request and polling the request drawer does, cut short: Siri has +// to answer while the listener waits, where the drawer can wait a minute. +// Pure, so scripts/intent-request.test.ts can drive it. + +import type { IntentReply } from '../../modules/app-intents'; +import type { StationApi } from '../lib/api'; +import { requestResultLabel } from '../lib/request-outcome'; +import type { RequestResult } from '../lib/types'; + +// How long Siri is kept waiting for the DJ to match the request. Matching is +// a model call on the station's own LLM and can run longer; past this, Siri +// says the request is in and it carries on resolving without anyone waiting. +export const REQUEST_WAIT_MS = 10_000; +// The drawer's interval. +const POLL_INTERVAL_MS = 1500; + +// The drawer's own line for a request still being matched. +export const ACCEPTED_MESSAGE = 'Got it — taking it to the booth.'; + +export interface AskForSongDeps { + api: Pick; + sleep?: (ms: number) => Promise; + now?: () => number; + waitMs?: number; +} + +export async function askForSong(text: string, deps: AskForSongDeps): Promise { + const asked = text.trim(); + if (!asked) return { ok: false, message: 'Tell me a song, an artist or a mood.' }; + const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + const now = deps.now ?? Date.now; + + // A refusal is answered in the station's words: requests closed, nobody + // tuned in, a rate limit, a full queue. A 400 carries `error`, not `message`. + let posted: RequestResult & { error?: string }; + try { + posted = await deps.api.postRequest({ text: asked }); + } catch { + return { ok: false, message: "Couldn't reach the station. Check your connection and try again." }; + } + if (!posted.success) { + return { + ok: false, + message: posted.message || posted.error || "The station didn't take the request.", + }; + } + if (!posted.requestId) return { ok: true, message: ACCEPTED_MESSAGE }; + + const deadline = now() + (deps.waitMs ?? REQUEST_WAIT_MS); + while (now() < deadline) { + await sleep(POLL_INTERVAL_MS); + let data: RequestResult | null; + try { + data = await deps.api.pollRequest(posted.requestId); + } catch { + data = null; + } + if (data?.status === 'resolved') return { ok: true, message: spokenAnswer(data) }; + if (data?.status === 'failed') { + return { ok: false, message: data.message || 'No match — try different words.' }; + } + if (data?.status === 'unknown') break; + } + return { ok: true, message: ACCEPTED_MESSAGE }; +} + +/** The DJ's own acknowledgement when there is one; otherwise the drawer's + * label with the track it names. */ +export function spokenAnswer(result: RequestResult): string { + if (result.ack) return result.ack; + const label = requestResultLabel({ ...result, pending: false }); + const title = result.track?.title; + if (!title) return `${label}.`; + const artist = result.track?.artist; + return artist ? `${label}: ${title} by ${artist}.` : `${label}: ${title}.`; +} diff --git a/src/intents/station.ts b/src/intents/station.ts new file mode 100644 index 0000000..d98bf46 --- /dev/null +++ b/src/intents/station.ts @@ -0,0 +1,28 @@ +// The station an App Intent acts on: the one the listener tuned to last, read +// from storage the way StationContext reads it at boot. An intent can run +// before any screen has mounted, so it cannot borrow the context's client. + +import { createApi, type StationApi } from '@/lib/api'; +import { loadStationCredentials, loadStationPassword, loadStations } from '@/lib/station'; + +export interface IntentStation { + base: string; + /** Display name from recents, when the store has one. */ + name: string | null; + api: StationApi; +} + +export const NO_STATION_MESSAGE = 'Open SUB/WAVE and pick a station first.'; + +export async function activeStation(): Promise { + const store = await loadStations(); + const base = store.activeStation; + if (!base) return null; + const credentials = await loadStationCredentials(base).catch(() => null); + const password = await loadStationPassword(base).catch(() => null); + return { + base, + name: store.recents.find((r) => r.url === base)?.name ?? null, + api: createApi(base, credentials, () => password), + }; +} diff --git a/src/intents/tune.ts b/src/intents/tune.ts new file mode 100644 index 0000000..7112614 --- /dev/null +++ b/src/intents/tune.ts @@ -0,0 +1,164 @@ +// Tune in and out on behalf of an App Intent (Siri, Shortcuts, Spotlight, a +// Control), including to another saved station. +// Module-level, not a hook: an intent can launch the app straight into the +// background, where this runs before any screen has mounted, or with none +// mounting at all. usePlayer adopts the audio when it does mount. + +import TrackPlayer, { Event, State } from 'react-native-track-player'; +import type { IntentReply } from '../../modules/app-intents'; +import { isLiveActivitySupported, onLiveActivityStart } from '../../modules/live-activity'; +import { externalTuneOut, getLastLiveMeta, loadAndPlay, teardown } from '@/audio/player'; +import { announceStationStoreChanged, loadStations, setActiveStation } from '@/lib/station'; +import { splitStationAddress, type StoredStationRef } from '@/lib/station-credentials'; +import { findSavedStation } from '@/lib/station-store'; +import { activeStation, NO_STATION_MESSAGE } from './station'; + +// How long a tune-in waits for audio before answering. Long enough that a +// refused or unreachable stream is reported to Siri rather than silently +// failing; short enough to stay inside the bridge's reply window. +const START_WAIT_MS = 8000; + +// How long a tune-in holds its answer, once audio is playing, for +// useLiveActivity to put the card up. ActivityKit only starts one for a +// background app inside a LiveActivityIntent's run (TuneInIntent is one), so +// answering first would close that window. Past the cap, the card comes up +// the next time the app is opened. +const CARD_WAIT_MS = 2000; + +const ON_AIR = new Set([State.Playing, State.Buffering, State.Loading]); + +const NOT_SAVED_MESSAGE = "That station isn't saved in SUB/WAVE. Add it in the app first."; + +/** Tune in to `stationId` (a saved station's base, as Siri and Spotlight know + * it), or to the station listened to last when there is none. */ +export async function tuneIn(stationId?: string): Promise { + if (stationId) { + const store = await loadStations(); + const wanted = findSavedStation(store.recents, stationId); + if (!wanted) return { ok: false, message: NOT_SAVED_MESSAGE }; + const active = store.activeStation ? splitStationAddress(store.activeStation).base : null; + if (splitStationAddress(wanted.url).base !== active) return switchTo(wanted); + } + + const { state } = await TrackPlayer.getPlaybackState().catch(() => ({ state: State.None })); + if (ON_AIR.has(state)) return { ok: true }; + + // Warm: the same reload a lock-screen Play does (service.ts). + const meta = getLastLiveMeta(); + if (meta) return startAndWait(() => loadAndPlay(meta), null); + + // Cold, or after an in-app stop: rebuild the stream from the stored + // station, as StationContext does at boot. Always the MP3 mount: a stored + // format preference is only honoured once the station's feed confirms the + // mount, and usePlayer retunes onto it when the feed loads. + const station = await activeStation(); + if (!station) return { ok: false, message: NO_STATION_MESSAGE }; + const { api } = station; + return startAndWait( + () => loadAndPlay({ url: api.streamUrl('mp3'), headers: api.streamHeaders() }), + station.name, + ); +} + +/** Another saved station. The store is written and the old stream stopped + * first, and StationContext is told only once the new stream is loaded: by + * the time the screens' base changes, the stream playing belongs to it, so + * usePlayer keeps it instead of stopping a stale one. */ +async function switchTo(ref: StoredStationRef): Promise { + await setActiveStation({ url: ref.url, name: ref.name }); + await teardown(); + const station = await activeStation(); + if (!station) return { ok: false, message: NO_STATION_MESSAGE }; + const { api } = station; + return startAndWait(async () => { + try { + await loadAndPlay({ url: api.streamUrl('mp3'), headers: api.streamHeaders() }); + } finally { + // The station switched even if its stream did not start. + announceStationStoreChanged(); + } + }, station.name); +} + +export async function tuneOut(): Promise { + await externalTuneOut().catch(() => {}); + return { ok: true }; +} + +async function startAndWait( + start: () => Promise, + stationName: string | null, +): Promise { + // Listen before starting so a fast Playing, or a fast card, is not missed. + const outcome = untilPlaying(); + const card = untilCardStarts(); + try { + await start(); + } catch { + outcome.cancel(); + card.cancel(); + return failed(stationName); + } + if (!(await outcome.result)) { + card.cancel(); + return failed(stationName); + } + await card.result; + return { ok: true }; +} + +/** Settles on the next Live Activity start attempt, whatever its outcome, + * or at the cap. Immediately where there is no card to wait for. */ +function untilCardStarts(): { result: Promise; cancel: () => void } { + if (!isLiveActivitySupported()) return { result: Promise.resolve(), cancel: () => {} }; + let settle: () => void = () => {}; + const result = new Promise((resolve) => { + settle = resolve; + }); + const unsubscribe = onLiveActivityStart(() => done()); + const timer = setTimeout(done, CARD_WAIT_MS); + let finished = false; + function done() { + if (finished) return; + finished = true; + clearTimeout(timer); + unsubscribe(); + settle(); + } + return { result, cancel: done }; +} + +function failed(stationName: string | null): IntentReply { + const station = stationName ?? 'the station'; + return { + ok: false, + message: `Couldn't reach ${station}. If it's private, open SUB/WAVE to unlock it.`, + }; +} + +/** True on Playing; false on an error. Still buffering when the wait runs out + * counts as started: the player keeps trying, and usePlayer's watchdog takes + * over once a screen mounts. */ +function untilPlaying(): { result: Promise; cancel: () => void } { + let settle: (ok: boolean) => void = () => {}; + const result = new Promise((resolve) => { + settle = resolve; + }); + const subs = [ + TrackPlayer.addEventListener(Event.PlaybackState, ({ state }) => { + if (state === State.Playing) done(true); + else if (state === State.Error) done(false); + }), + TrackPlayer.addEventListener(Event.PlaybackError, () => done(false)), + ]; + const timer = setTimeout(() => done(true), START_WAIT_MS); + let finished = false; + function done(ok: boolean) { + if (finished) return; + finished = true; + clearTimeout(timer); + subs.forEach((s) => s.remove()); + settle(ok); + } + return { result, cancel: () => done(false) }; +} diff --git a/src/lib/heard-track.ts b/src/lib/heard-track.ts new file mode 100644 index 0000000..60b99b6 --- /dev/null +++ b/src/lib/heard-track.ts @@ -0,0 +1,40 @@ +// Which track a tuned-in listener is hearing. The station reports the live +// edge; the stream reaches the listener stream.bufferSeconds later, so for that +// long after a change they still hear the previous track. useStationFeed +// promotes a new track at audibleAt(); the App Intents (src/intents/on-air.ts) +// answer "what's playing" and "like this song" with heardTrack(), which reads +// the same rule from one /now-playing + /state snapshot. + +import { MAX_LEAD_SECONDS } from './sessionFeed'; + +/** stream.bufferSeconds as milliseconds, clamped to 0–60 s so a bad value + * can't park the clock in the far future. Null when the station sent none. */ +export function leadMsFrom(bufferSeconds: number | null | undefined): number | null { + if (typeof bufferSeconds !== 'number' || !Number.isFinite(bufferSeconds)) return null; + return Math.min(Math.max(bufferSeconds, 0), MAX_LEAD_SECONDS) * 1000; +} + +/** When a track that started at the live edge at `liveStartMs` reaches the + * listener. */ +export function audibleAt(liveStartMs: number, leadMs: number): number { + return liveStartMs + leadMs; +} + +/** The live track once it is audible, the previous one before that. With no + * live-edge start time to measure from, the live track. */ +export function heardTrack({ + live, + previous, + liveStartMs, + leadMs, + now, +}: { + live: T | null; + previous: T | null; + liveStartMs: number | null; + leadMs: number; + now: number; +}): T | null { + if (liveStartMs == null || !Number.isFinite(liveStartMs)) return live; + return now < audibleAt(liveStartMs, leadMs) ? (previous ?? live) : live; +} diff --git a/src/lib/like-events.ts b/src/lib/like-events.ts new file mode 100644 index 0000000..4ef4981 --- /dev/null +++ b/src/lib/like-events.ts @@ -0,0 +1,28 @@ +// A like made away from the heart: "like this song" from Siri +// (src/intents/on-air.ts). useTrackLike listens, so the heart and the Live +// Activity it drives fill now instead of on the next song's status fetch. + +export interface ExternalLike { + songId: string; + /** Likes for the song, all airings, when the station said. */ + count?: number; +} + +const listeners = new Set<(like: ExternalLike) => void>(); + +export function onExternalLike(fn: (like: ExternalLike) => void): () => void { + listeners.add(fn); + return () => { + listeners.delete(fn); + }; +} + +export function announceLike(like: ExternalLike): void { + listeners.forEach((fn) => { + try { + fn(like); + } catch { + /* a broken subscriber must not fail the like */ + } + }); +} diff --git a/src/lib/station-store.ts b/src/lib/station-store.ts index f79c853..38be385 100644 --- a/src/lib/station-store.ts +++ b/src/lib/station-store.ts @@ -1,4 +1,8 @@ -import { splitStationAddress, type StoredStationStore } from './station-credentials'; +import { + splitStationAddress, + type StoredStationRef, + type StoredStationStore, +} from './station-credentials'; export interface ForgetStoredStationDeps { load(): Promise; @@ -20,3 +24,43 @@ export async function forgetStoredStation( await deps.persist(next); return next; } + +/** Whether a stream URL (StationApi.streamUrl) is one of this station's + * mounts. Compared on the credential-free base, which is what streamUrl() + * builds on. usePlayer uses it to keep a stream a station switch from Siri + * started (src/intents/tune.ts) rather than stopping it as stale. */ +export function streamBelongsTo(streamUrl: string, rawBase: string): boolean { + const base = splitStationAddress(rawBase).base; + return !!base && streamUrl.startsWith(`${base}/`); +} + +/** A saved station by the id Siri and Spotlight know it by: its + * credential-free base URL. */ +export function findSavedStation( + recents: StoredStationRef[], + id: string, +): StoredStationRef | null { + const wanted = splitStationAddress(id).base; + return recents.find((r) => splitStationAddress(r.url).base === wanted) ?? null; +} + +export interface MirroredStation { + id: string; + name: string; +} + +/** The saved stations as Siri, Shortcuts and Spotlight see them + * (modules/app-intents setStations): names and credential-free bases only, + * never a login or a station password. A station saved without a name goes + * by its host. */ +export function stationsForSiri(recents: StoredStationRef[]): MirroredStation[] { + const seen = new Set(); + const out: MirroredStation[] = []; + for (const r of recents) { + const id = splitStationAddress(r.url).base; + if (!id || seen.has(id)) continue; + seen.add(id); + out.push({ id, name: r.name?.trim() || id.replace(/^https?:\/\//i, '') }); + } + return out; +} diff --git a/src/lib/station.ts b/src/lib/station.ts index 14b7488..f4d160c 100644 --- a/src/lib/station.ts +++ b/src/lib/station.ts @@ -144,3 +144,25 @@ export async function clearActiveStation(): Promise { await persist(next); return next; } + +// A change to the stored active station made outside StationContext: a +// station switch from Siri, Shortcuts or Spotlight (src/intents/tune.ts). +// StationContext reloads the store on it, so the screens follow. +const storeListeners = new Set<() => void>(); + +export function onStationStoreChanged(fn: () => void): () => void { + storeListeners.add(fn); + return () => { + storeListeners.delete(fn); + }; +} + +export function announceStationStoreChanged(): void { + storeListeners.forEach((fn) => { + try { + fn(); + } catch { + /* a broken subscriber must not stop the switch */ + } + }); +} diff --git a/targets/live-activity/SubwaveLiveActivity.swift b/targets/live-activity/SubwaveLiveActivity.swift index 233d651..cf7d891 100644 --- a/targets/live-activity/SubwaveLiveActivity.swift +++ b/targets/live-activity/SubwaveLiveActivity.swift @@ -5,8 +5,11 @@ import UIKit import WidgetKit // The on-air Live Activity: Lock Screen, Dynamic Island, and — the reason this -// target exists — the Apple Watch Smart Stack, which iOS 18+ mirrors this same -// lock-screen presentation into with no watchOS target of its own. +// target exists — the Apple Watch Smart Stack, which iOS 18+ mirrors this +// activity into with no watchOS target of its own. iOS 26 adds the CarPlay +// Dashboard, with no CarPlay entitlement. Both of those render the `.small` +// activity family (SmallView), and fall back to the Dynamic Island's compact +// views unless the configuration opts into it (SubwaveLiveActivityWithSmall). // // Everything here renders from the content state alone. A widget extension gets // no network turn, so nothing in this file fetches: the cover art is read off @@ -220,11 +223,10 @@ private struct TrackLines: View { } } -// MARK: - Lock Screen / Smart Stack +// MARK: - Lock Screen -/// Also the Apple Watch presentation: watchOS renders the Smart Stack card from -/// this same view, at a narrower width. Keep it a single row that degrades — no -/// fixed widths, everything `lineLimit(1)`. +/// The `.medium` family: the Lock Screen banner and StandBy. Keep it a single +/// row that degrades — no fixed widths, everything `lineLimit(1)`. private struct LockScreenView: View { let context: ActivityViewContext @@ -256,12 +258,77 @@ private struct LockScreenView: View { } } +// MARK: - Smart Stack / CarPlay + +/// The `.small` family: the Apple Watch Smart Stack and the CarPlay Dashboard. +/// No heart: CarPlay renders Live Activities non-interactive, and the two +/// surfaces share this one view, so a button here would be a dead one in the +/// car. +private struct SmallView: View { + let context: ActivityViewContext + + private var accent: Color { Color(subwaveHex: context.attributes.accent) } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .center, spacing: 8) { + Cover(state: context.state, accent: accent, side: 36) + VStack(alignment: .leading, spacing: 2) { + OnAirLine(station: context.attributes.station, accent: accent) + Text(context.state.title) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(subwaveInk) + .lineLimit(1) + Text(context.state.artist) + .font(.system(size: 11, weight: .regular)) + .foregroundStyle(subwaveMuted) + .lineLimit(1) + } + } + AirClock(state: context.state, accent: accent) + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + } +} + +/// Picks the view for the family being drawn. The family is only readable on +/// iOS 18, and is only ever `.small` when the configuration opted into it. +private struct ActivityContentView: View { + let context: ActivityViewContext + + var body: some View { + if #available(iOS 18.0, *) { + FamilySwitch(context: context) + } else { + LockScreenView(context: context) + } + } +} + +@available(iOS 18.0, *) +private struct FamilySwitch: View { + let context: ActivityViewContext + @Environment(\.activityFamily) private var family + + var body: some View { + switch family { + case .small: + SmallView(context: context) + default: + LockScreenView(context: context) + } + } +} + // MARK: - Widget +/// The iOS 17 configuration, and the base the iOS 18 one adds a family to. +/// Only one of the two is ever registered (SubwaveWidgets in index.swift). struct SubwaveLiveActivity: Widget { var body: some WidgetConfiguration { ActivityConfiguration(for: SubwaveLiveAttributes.self) { context in - LockScreenView(context: context) + ActivityContentView(context: context) .widgetURL(URL(string: "subwave://")) .activityBackgroundTint(Color.black.opacity(0.55)) .activitySystemActionForegroundColor(subwaveInk) @@ -300,6 +367,16 @@ struct SubwaveLiveActivity: Widget { } } +/// `supplementalActivityFamilies` is iOS 18 API and the target's floor is 17, +/// so the opt-in lives on its own widget rather than behind a branch inside +/// one `body`: the two branches would be different opaque types. +@available(iOS 18.0, *) +struct SubwaveLiveActivityWithSmall: Widget { + var body: some WidgetConfiguration { + SubwaveLiveActivity().body.supplementalActivityFamilies([.small]) + } +} + // MARK: - Previews extension SubwaveLiveAttributes { diff --git a/targets/live-activity/TuneControl.swift b/targets/live-activity/TuneControl.swift new file mode 100644 index 0000000..818e4b1 --- /dev/null +++ b/targets/live-activity/TuneControl.swift @@ -0,0 +1,45 @@ +import AppIntents +import SwiftUI +import WidgetKit + +// The tune control: Control Center, the Lock Screen, and the Action button on +// an iPhone 15 Pro or later. iOS 18. +// +// A control cannot ask the player whether it is playing, so it reads the +// on-air flag the app keeps in the App Group (usePlayer, through the +// app-intents module's setOnAir). The key and the kind are matched by STRING +// with modules/app-intents/ios/SubwaveAppIntentsModule.swift; change one +// side, change both. +// +// The flag can outlive the audio: an app killed mid-song never clears it. The +// toggle then reads on until it is tapped, which tunes out a stream that has +// already stopped and flips it off, or until the app next launches. + +@available(iOS 18.0, *) +struct TuneControl: ControlWidget { + static let kind = "com.getsubwave.app.tune" + + var body: some ControlWidgetConfiguration { + StaticControlConfiguration(kind: Self.kind, provider: OnAirProvider()) { isOn in + ControlWidgetToggle( + "SUB/WAVE", isOn: isOn, action: ToggleTuneIntent(turningOn: !isOn) + ) { on in + Label( + on ? "On air" : "Off air", + systemImage: on ? "dot.radiowaves.left.and.right" : "radio") + } + .tint(Color(red: 0.851, green: 0.294, blue: 0.165)) + } + .displayName("SUB/WAVE") + .description("Tune in to the station you listened to last, or tune out.") + } +} + +@available(iOS 18.0, *) +private struct OnAirProvider: ControlValueProvider { + var previewValue: Bool { false } + + func currentValue() async throws -> Bool { + UserDefaults(suiteName: subwaveAppGroup)?.bool(forKey: "subwave.onAir") ?? false + } +} diff --git a/targets/live-activity/_shared/AudioSchemaIntents.swift b/targets/live-activity/_shared/AudioSchemaIntents.swift new file mode 100644 index 0000000..f05879c --- /dev/null +++ b/targets/live-activity/_shared/AudioSchemaIntents.swift @@ -0,0 +1,184 @@ +import AppIntents + +// "Hey Siri, play SUB/WAVE" on iOS 27. +// +// iOS 27 sends a bare "play " through Siri's audio search, and an app +// that has not adopted the audio App Schema loses it to Apple Music, App +// Shortcut phrase or not (WXYC's radio app hit exactly this on iOS 27.0.1). +// Adopting it takes three pieces: a `.audio.liveRadioStation` entity, a query +// that answers Siri's AudioSearch (`IntentValueQuery`: a bare "play SUB/WAVE" +// arrives as `.unspecified`, which a string query never sees), and a +// `.audio.playAudio` intent, which tunes in exactly as TuneInIntent does. +// +// One entity per saved station (SavedStations, StationEntities.swift), so +// "play Night Shift on SUB/WAVE" reaches that station; a bare "play SUB/WAVE" +// is the station listened to last. +// +// Gated on Swift 6.4 (the iOS 27 SDK), where these schema symbols exist; an +// older Xcode compiles this out and "play SUB/WAVE" stays on the App Shortcut +// phrase. App target only, like SubwaveShortcuts.swift. +#if compiler(>=6.4) && canImport(ExpoModulesCore) +#if canImport(MediaIntents) +import MediaIntents +#endif + +@available(iOS 27.0, *) +@AppEntity(schema: .audio.liveRadioStation) +struct LiveStationEntity { + static let defaultQuery = LiveStationQuery() + /// The stand-in before the app has saved a station: playing it says to + /// pick one first. + static let noStationID = "none" + + /// A saved station's credential-free base (StationEntities.swift). + let id: String + /// What Siri says back: the station's own name. + var title: String + var providerName: String? + + init(_ station: SavedStations.Station) { + self.id = station.id + self.title = station.name + self.providerName = "SUB/WAVE" + } + + init() { + self.id = Self.noStationID + self.title = "SUB/WAVE" + self.providerName = "SUB/WAVE" + } + + /// The station listened to last, or the stand-in. + static func active(_ saved: SavedStations = .load()) -> LiveStationEntity { + saved.activeStation.map(LiveStationEntity.init) ?? LiveStationEntity() + } + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation(title: "\(title)") + } +} + +@available(iOS 27.0, *) +struct LiveStationQuery: EntityStringQuery { + func entities(for identifiers: [String]) async throws -> [LiveStationEntity] { + var found = SavedStations.load().stations + .filter { identifiers.contains($0.id) } + .map(LiveStationEntity.init) + if identifiers.contains(LiveStationEntity.noStationID) { found.append(LiveStationEntity()) } + return found + } + + /// Shortcuts' text search, typed against every entity type the app has: a + /// saved station's name, or the app's own for the station listened to last. + func entities(matching string: String) async throws -> [LiveStationEntity] { + let saved = SavedStations.load() + let named = saved.matching(string).map(LiveStationEntity.init) + if !named.isEmpty { return named } + let term = string.trimmingCharacters(in: .whitespaces) + let appNames = ["SUB/WAVE", "subwave", "sub wave"] + let namesApp = !term.isEmpty + && appNames.contains { $0.localizedStandardContains(term) || term.localizedStandardContains($0) } + return namesApp ? [LiveStationEntity.active(saved)] : [] + } + + func suggestedEntities() async throws -> [LiveStationEntity] { + let saved = SavedStations.load() + return saved.stations.isEmpty ? [LiveStationEntity()] : saved.stations.map(LiveStationEntity.init) + } +} + +#if canImport(MediaIntents) +/// Siri's audio search, consulted once Siri has chosen SUB/WAVE. `.unspecified` +/// is "play SUB/WAVE" and nothing else: the station listened to last. +/// `.searchQuery` is whatever words were left over: a saved station they name, +/// else the station listened to last, since a word like "radio" or a song +/// title should still tune in rather than come back "not found". A link is +/// never claimed: a station lives at the listener's own host. +@available(iOS 27.0, *) +extension LiveStationQuery: IntentValueQuery { + func values(for search: AudioSearch) async throws -> [LiveStationEntity] { + let saved = SavedStations.load() + switch search.criteria { + case .unspecified: + return [LiveStationEntity.active(saved)] + case .searchQuery(let words): + let named = saved.matching(words).map(LiveStationEntity.init) + return named.isEmpty ? [LiveStationEntity.active(saved)] : named + case .url: + return [] + @unknown default: + return [] + } + } +} +#endif + +@available(iOS 27.0, *) +@UnionValue +enum AudioItem { + case liveRadioStation(LiveStationEntity) +} + +/// Required by the schema. A live stream has no shuffle or repeat, so these +/// are accepted and ignored. +@available(iOS 27.0, *) +@AppEnum(schema: .audio.playbackAttributes) +enum PlaybackAttributes: String { + case shuffle + case `repeat` + + static let caseDisplayRepresentations: [Self: DisplayRepresentation] = [ + .shuffle: "Shuffle", + .repeat: "Repeat", + ] +} + +/// Required by the schema; there is no queue to insert into. +@available(iOS 27.0, *) +@AppEnum(schema: .audio.queueInsertionLocation) +enum QueueInsertionLocation: String { + case next + case tail + + static let caseDisplayRepresentations: [Self: DisplayRepresentation] = [ + .next: "Next", + .tail: "Tail", + ] +} + +/// Required by the schema; SUB/WAVE has nothing to warm up. +@available(iOS 27.0, *) +@AppEntity(schema: .audio.warmupAudioQueueResult) +struct WarmupAudioQueueResult: TransientAppEntity { + init() {} + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation(title: "Queue") + } +} + +/// Assistant-only: Shortcuts already lists Tune in, and a schema intent beside +/// an App Shortcut for the same action shows as a duplicate there. +/// LiveActivityIntent for the same reason as TuneInIntent: the card can only +/// start inside its run. +@available(iOS 27.0, *) +@AppIntent(schema: .audio.playAudio) +struct PlayStationAudioIntent: AudioPlaybackIntent, LiveActivityIntent { + static let isAssistantOnly = true + + var audioEntity: AudioItem + var playbackAttributes: Set + var warmupAudioQueueResult: WarmupAudioQueueResult? + var queueLocation: QueueInsertionLocation? + + func perform() async throws -> some IntentResult { + switch audioEntity { + case .liveRadioStation(let station): + let args = station.id == LiveStationEntity.noStationID ? [:] : ["station": station.id] + try await SubwaveIntentBridge.perform("tuneIn", args) + } + return .result() + } +} + +#endif diff --git a/targets/live-activity/_shared/LikeTrackIntent.swift b/targets/live-activity/_shared/LikeTrackIntent.swift index 3a614e5..a167b27 100644 --- a/targets/live-activity/_shared/LikeTrackIntent.swift +++ b/targets/live-activity/_shared/LikeTrackIntent.swift @@ -31,6 +31,11 @@ struct LikeTrackIntent: AppIntent, LiveActivityIntent { /// does not have to open anything. static var openAppWhenRun: Bool = false + /// The card's button only. Siri and Shortcuts have LikeSongIntent + /// (OnAirIntents.swift), which works with no screen mounted; this one goes + /// through the in-app heart. + static var isDiscoverable: Bool = false + func perform() async throws -> some IntentResult { NotificationCenter.default.post( name: Notification.Name("SubwaveLiveActivityLikePressed"), diff --git a/targets/live-activity/_shared/OnAirIntents.swift b/targets/live-activity/_shared/OnAirIntents.swift new file mode 100644 index 0000000..ff2908a --- /dev/null +++ b/targets/live-activity/_shared/OnAirIntents.swift @@ -0,0 +1,43 @@ +import AppIntents + +// App target only, like SubwaveShortcuts.swift: an intent the widget also +// declared could be performed there, where nothing answers the bridge. +#if canImport(ExpoModulesCore) + +// "What's playing on SUB/WAVE" and "like this song on SUB/WAVE". Both mean the +// track the listener is hearing, which src/intents/on-air.ts works out: while +// the app is playing, the stream runs behind the live edge, and for that long +// after a change the song in their ears is the previous one. + +@available(iOS 17.0, *) +struct WhatsPlayingIntent: AppIntent { + static var title: LocalizedStringResource = "What's playing" + static var description = IntentDescription( + "Tells you the song on SUB/WAVE: the one you're hearing when you're tuned in." + ) + static var openAppWhenRun: Bool = false + + func perform() async throws -> some IntentResult & ProvidesDialog & ReturnsValue { + let answer = try await SubwaveIntentBridge.perform("nowPlaying") ?? "" + return .result(value: answer, dialog: IntentDialog(stringLiteral: answer)) + } +} + +/// Hearts the song through the station's own POST /like, which refuses a +/// song that has already ended. The Live Activity's button is +/// LikeTrackIntent, which likes through the in-app heart instead. +@available(iOS 17.0, *) +struct LikeSongIntent: AppIntent { + static var title: LocalizedStringResource = "Like this song" + static var description = IntentDescription( + "Hearts the song you're hearing on SUB/WAVE." + ) + static var openAppWhenRun: Bool = false + + func perform() async throws -> some IntentResult & ProvidesDialog { + let answer = try await SubwaveIntentBridge.perform("like") ?? "Liked." + return .result(dialog: IntentDialog(stringLiteral: answer)) + } +} + +#endif diff --git a/targets/live-activity/_shared/RequestSongIntent.swift b/targets/live-activity/_shared/RequestSongIntent.swift new file mode 100644 index 0000000..6efe82e --- /dev/null +++ b/targets/live-activity/_shared/RequestSongIntent.swift @@ -0,0 +1,37 @@ +import AppIntents + +// App target only, like SubwaveShortcuts.swift: the widget never shows a +// request button, and an intent it also declares could be performed there, +// where nothing answers the bridge. +#if canImport(ExpoModulesCore) + +// "Hey Siri, request a song on SUB/WAVE." Siri asks what to play, the request +// goes to the station the listener has tuned to last, and Siri reads back the +// DJ's answer. Hands-free, so it works on AirPods and in the car without a +// CarPlay app. +// +// The request itself is JS (src/intents/request-reply.ts), through the same +// POST /request and polling the request drawer uses, so the station's gates +// (requests closed, rate limits, a full queue) answer Siri in their own words. +@available(iOS 17.0, *) +struct RequestSongIntent: AppIntent { + static var title: LocalizedStringResource = "Request a song" + static var description = IntentDescription( + "Asks the SUB/WAVE DJ for a song, an artist or a mood, and tells you what they said." + ) + static var openAppWhenRun: Bool = false + + @Parameter( + title: "Request", + description: "A song, an artist, or a mood.", + requestValueDialog: "What would you like to hear?" + ) + var request: String + + func perform() async throws -> some IntentResult & ProvidesDialog { + let answer = try await SubwaveIntentBridge.perform("request", ["text": request]) + return .result(dialog: IntentDialog(stringLiteral: answer ?? "Sent to the DJ.")) + } +} + +#endif diff --git a/targets/live-activity/_shared/StationEntities.swift b/targets/live-activity/_shared/StationEntities.swift new file mode 100644 index 0000000..aa5d023 --- /dev/null +++ b/targets/live-activity/_shared/StationEntities.swift @@ -0,0 +1,142 @@ +import AppIntents +import CoreSpotlight +import Foundation + +// The listener's saved stations, for Siri ("play Night Shift on SUB/WAVE"), +// Shortcuts (Tune in's Station parameter) and Spotlight (iOS 18). +// +// Swift cannot read the app's station store, so StationContext mirrors the +// list into the App Group (modules/app-intents setStations), and every type +// here reads that. Names and credential-free bases only: a station's login and +// password stay in the app's keychain, and tuning in is JS's job +// (src/intents/tune.ts), handed a station's base as its id. +// +// App target only, like SubwaveShortcuts.swift. +#if canImport(ExpoModulesCore) + +/// The stations as the app last wrote them. The key is matched by STRING with +/// modules/app-intents/ios/SubwaveAppIntentsModule.swift. +struct SavedStations: Decodable { + struct Station: Decodable { + let id: String + let name: String + } + + let active: String? + let stations: [Station] + + static func load() -> SavedStations { + guard + let json = UserDefaults(suiteName: "group.com.getsubwave.app")?.string(forKey: "subwave.stations"), + let decoded = try? JSONDecoder().decode(SavedStations.self, from: Data(json.utf8)) + else { return SavedStations(active: nil, stations: []) } + return decoded + } + + var activeStation: Station? { + stations.first { $0.id == active } ?? stations.first + } + + /// Stations a spoken or typed term names. Compared folded, because Siri + /// transcribes "ChillWave Radio" as "chill wave radio": an exact name first, + /// else a name containing the term or contained in it ("night shift" against + /// "Night Shift Radio"). A generic word names no station, so "play radio on + /// SUB/WAVE" stays on the one listened to last instead of landing on + /// whichever station has Radio in its name. + func matching(_ term: String) -> [Station] { + let wanted = Self.fold(term) + guard wanted.count >= 3, !Self.genericTerms.contains(wanted) else { return [] } + let exact = stations.filter { Self.fold($0.name) == wanted } + if !exact.isEmpty { return exact } + return stations.filter { + let name = Self.fold($0.name) + return !name.isEmpty && (name.contains(wanted) || wanted.contains(name)) + } + } + + /// Lowercased, accents dropped, letters and digits only. + static func fold(_ text: String) -> String { + text.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) + .filter { $0.isLetter || $0.isNumber } + } + + private static let genericTerms: Set = [ + "radio", "theradio", "station", "mystation", "music", "somemusic", "live", "subwave", + ] +} + +@available(iOS 17.0, *) +struct StationEntity: AppEntity { + static var typeDisplayRepresentation: TypeDisplayRepresentation = "Station" + static var defaultQuery = StationQuery() + + /// The station's credential-free base URL. + let id: String + let name: String + + init(_ station: SavedStations.Station) { + id = station.id + name = station.name + } + + var displayRepresentation: DisplayRepresentation { + let host = URL(string: id)?.host() ?? id + return DisplayRepresentation(title: "\(name)", subtitle: "\(host)") + } +} + +@available(iOS 18.0, *) +extension StationEntity: IndexedEntity {} + +@available(iOS 17.0, *) +struct StationQuery: EntityStringQuery { + func entities(for identifiers: [String]) async throws -> [StationEntity] { + SavedStations.load().stations.filter { identifiers.contains($0.id) }.map(StationEntity.init) + } + + func entities(matching string: String) async throws -> [StationEntity] { + SavedStations.load().matching(string).map(StationEntity.init) + } + + func suggestedEntities() async throws -> [StationEntity] { + SavedStations.load().stations.map(StationEntity.init) + } +} + +/// A station tapped in Spotlight: open SUB/WAVE on it, playing. +@available(iOS 17.0, *) +struct OpenStationIntent: OpenIntent { + static var title: LocalizedStringResource = "Open station" + static var description = IntentDescription("Opens SUB/WAVE on a saved station and tunes in.") + + @Parameter(title: "Station") + var target: StationEntity + + func perform() async throws -> some IntentResult { + try await SubwaveIntentBridge.perform("tuneIn", ["station": target.id]) + return .result() + } +} + +/// Rebuilds what the system holds about the saved stations: the Siri phrases +/// with a station in them, and the Spotlight index. The app-intents module +/// calls `reindex` by class name after it writes a new list, because this +/// target sees the entity types and that pod does not. +@objc(SubwaveStationIndex) +final class StationIndex: NSObject { + @objc static func reindex() { + if #available(iOS 17.0, *) { + SubwaveShortcuts.updateAppShortcutParameters() + } + guard #available(iOS 18.0, *) else { return } + let entities = SavedStations.load().stations.map(StationEntity.init) + Task { + // Delete first: a station the listener forgot must leave Spotlight too. + let index = CSSearchableIndex.default() + try? await index.deleteAppEntities(ofType: StationEntity.self) + try? await index.indexAppEntities(entities) + } + } +} + +#endif diff --git a/targets/live-activity/_shared/SubwaveIntentBridge.swift b/targets/live-activity/_shared/SubwaveIntentBridge.swift new file mode 100644 index 0000000..e220fdd --- /dev/null +++ b/targets/live-activity/_shared/SubwaveIntentBridge.swift @@ -0,0 +1,120 @@ +import AppIntents +import Foundation + +// The intent half of the App Intents bridge. An intent hands its action to JS +// and waits for the answer; the app half is +// modules/app-intents/ios/SubwaveAppIntentsModule.swift, which this file +// cannot import (it compiles into the widget extension too), so the two meet +// on NotificationCenter names, matched by STRING. Change one side, change both. +// +// 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. + +@available(iOS 17.0, *) +enum SubwaveIntentBridge { + private static let requestName = Notification.Name("SubwaveIntentRequest") + private static let ackName = Notification.Name("SubwaveIntentAck") + private static let replyName = Notification.Name("SubwaveIntentReply") + + /// How long a cold launch gets for React Native to boot far enough to load + /// the module. + private static let ackWindow: TimeInterval = 10 + /// Ceiling on the whole round trip, ack included. A tune-in waits for the + /// stream to start playing, so this covers a slow first connection. + private static let replyWindow: TimeInterval = 20 + + /// Runs `action` in JS with `args`. Returns the message JS answered with, if + /// any; throws the message JS gave for a failure, or a generic one when the + /// app never answered. + @discardableResult + static func perform(_ action: String, _ args: [String: String] = [:]) async throws -> String? { + let token = UUID().uuidString + let box = ReplyBox() + let center = NotificationCenter.default + let ackObserver = center.addObserver(forName: ackName, object: nil, queue: nil) { note in + if note.userInfo?["token"] as? String == token { box.markAcked() } + } + let replyObserver = center.addObserver(forName: replyName, object: nil, queue: nil) { note in + guard note.userInfo?["token"] as? String == token else { return } + box.resolve( + ok: note.userInfo?["ok"] as? Bool ?? false, + message: note.userInfo?["message"] as? String) + } + defer { + center.removeObserver(ackObserver) + center.removeObserver(replyObserver) + } + + let started = Date() + while true { + if let reply = box.reply { + guard reply.ok else { throw SubwaveIntentError(reply.message) } + return reply.message + } + let waited = Date().timeIntervalSince(started) + if waited > replyWindow || (!box.acked && waited > ackWindow) { + throw SubwaveIntentError(nil) + } + if !box.acked { + center.post( + name: requestName, object: nil, + userInfo: ["token": token, "action": action, "args": args]) + } + try await Task.sleep(nanoseconds: 200_000_000) + } + } +} + +/// Written from NotificationCenter's posting thread, read from the intent's. +private final class ReplyBox: @unchecked Sendable { + struct Reply { + let ok: Bool + let message: String? + } + + private let lock = NSLock() + private var _acked = false + private var _reply: Reply? + + var acked: Bool { + lock.lock() + defer { lock.unlock() } + return _acked + } + + var reply: Reply? { + lock.lock() + defer { lock.unlock() } + return _reply + } + + func markAcked() { + lock.lock() + _acked = true + lock.unlock() + } + + func resolve(ok: Bool, message: String?) { + lock.lock() + _acked = true + if _reply == nil { + _reply = Reply(ok: ok, message: message) + } + lock.unlock() + } +} + +/// What Siri says, and Shortcuts shows, when an intent could not do its job. +struct SubwaveIntentError: Error, CustomLocalizedStringResourceConvertible { + let message: String + + init(_ message: String?) { + self.message = message ?? "SUB/WAVE didn't respond. Open the app and try again." + } + + var localizedStringResource: LocalizedStringResource { + LocalizedStringResource(stringLiteral: message) + } +} diff --git a/targets/live-activity/_shared/SubwaveShortcuts.swift b/targets/live-activity/_shared/SubwaveShortcuts.swift new file mode 100644 index 0000000..4eed93c --- /dev/null +++ b/targets/live-activity/_shared/SubwaveShortcuts.swift @@ -0,0 +1,76 @@ +import AppIntents + +// App target only. `_shared/` also compiles into the widget extension, and a +// second AppShortcutsProvider there sends Shortcuts to the wrong bundle for a +// shortcut with a parameter to ask for: "Couldn't find AppShortcutsProvider". +// Only the app target links the Expo pods, which is what this tests; if the +// widget ever joins the Podfile, find another switch. +#if canImport(ExpoModulesCore) + +/// Siri phrases. Every phrase must carry the app's name; "Sub Wave" and +/// "Subwave" reach it through INAlternativeAppNames (app.json), since nobody +/// says the slash. A free-text parameter cannot be part of a phrase, so a +/// request is asked for after the phrase (RequestSongIntent's dialog). +@available(iOS 17.0, *) +struct SubwaveShortcuts: AppShortcutsProvider { + static var appShortcuts: [AppShortcut] { + AppShortcut( + intent: TuneInIntent(), + phrases: [ + "Tune in to \(.applicationName)", + "Play \(.applicationName)", + "Turn on \(.applicationName)", + "Start \(.applicationName)", + // A saved station by name. The names come from StationQuery's + // suggestions, refreshed by StationIndex.reindex. + "Play \(\.$station) on \(.applicationName)", + "Tune in to \(\.$station) on \(.applicationName)", + "Listen to \(\.$station) on \(.applicationName)", + ], + shortTitle: "Tune in", + systemImageName: "dot.radiowaves.left.and.right" + ) + AppShortcut( + intent: TuneOutIntent(), + phrases: [ + "Tune out of \(.applicationName)", + "Stop \(.applicationName)", + "Turn off \(.applicationName)", + ], + shortTitle: "Tune out", + systemImageName: "stop.fill" + ) + AppShortcut( + intent: RequestSongIntent(), + phrases: [ + "Request a song on \(.applicationName)", + "Make a request on \(.applicationName)", + "Ask \(.applicationName) for a song", + ], + shortTitle: "Request a song", + systemImageName: "music.note" + ) + AppShortcut( + intent: WhatsPlayingIntent(), + phrases: [ + "What's playing on \(.applicationName)", + "What's on \(.applicationName)", + "What song is this on \(.applicationName)", + ], + shortTitle: "What's playing", + systemImageName: "waveform" + ) + AppShortcut( + intent: LikeSongIntent(), + phrases: [ + "Like this song on \(.applicationName)", + "Like this track on \(.applicationName)", + "Heart this song on \(.applicationName)", + ], + shortTitle: "Like this song", + systemImageName: "heart" + ) + } +} + +#endif diff --git a/targets/live-activity/_shared/ToggleTuneIntent.swift b/targets/live-activity/_shared/ToggleTuneIntent.swift new file mode 100644 index 0000000..c8bf96a --- /dev/null +++ b/targets/live-activity/_shared/ToggleTuneIntent.swift @@ -0,0 +1,31 @@ +import AppIntents + +// The intent behind the tune control (TuneControl.swift): Control Center, the +// Lock Screen and the Action button. A SetValueIntent so ControlWidgetToggle +// can bind to it; the audio and Live Activity conformances do what they do for +// TuneInIntent (TuneIntents.swift): run in the app's process, start playback +// from the background, and let the card start. +// +// Not discoverable: Siri and Shortcuts already have Tune in and Tune out. +@available(iOS 18.0, *) +struct ToggleTuneIntent: SetValueIntent, AudioPlaybackIntent, LiveActivityIntent { + static var title: LocalizedStringResource = "Turn SUB/WAVE on or off" + static var isDiscoverable: Bool = false + static var openAppWhenRun: Bool = false + + @Parameter(title: "On air") + var value: Bool + + init() {} + + /// A control never resolves parameters, so it must hand over an instance + /// with `value` already set; left unset, the tap never reaches perform(). + init(turningOn: Bool) { + self.value = turningOn + } + + func perform() async throws -> some IntentResult { + try await SubwaveIntentBridge.perform(value ? "tuneIn" : "tuneOut") + return .result() + } +} diff --git a/targets/live-activity/_shared/TuneIntents.swift b/targets/live-activity/_shared/TuneIntents.swift new file mode 100644 index 0000000..203bfde --- /dev/null +++ b/targets/live-activity/_shared/TuneIntents.swift @@ -0,0 +1,54 @@ +import AppIntents + +// Tune in and tune out, for Siri, Shortcuts, Spotlight and automations. +// +// AudioPlaybackIntent is what lets these run in the APP's process without +// bringing it forward, launching it into the background when it is not +// running: the system grants an audio intent the right to start playback +// from there. The intents themselves only hand the action to JS +// (SubwaveIntentBridge); src/intents/tune.ts decides what tuning in means. +// +// Tune in is a LiveActivityIntent too. ActivityKit refuses a Live Activity +// request from a background app ("Requester is not foreground") unless it +// arrives inside a LiveActivityIntent's run, so without it a tune-in from +// Siri plays with no card on the Lock Screen. tune.ts holds its answer until +// the card has been asked for, keeping the request inside that run. +// +// No skip: every listener shares one live stream. Tune in takes an optional +// saved station (StationEntities.swift); without one it plays the station +// listened to last. +// +// App target only, like SubwaveShortcuts.swift: the widget's control has its +// own ToggleTuneIntent, and StationEntity is app-only. +#if canImport(ExpoModulesCore) + +@available(iOS 17.0, *) +struct TuneInIntent: AudioPlaybackIntent, LiveActivityIntent { + static var title: LocalizedStringResource = "Tune in" + static var description = IntentDescription( + "Plays a saved SUB/WAVE station live, or the one you listened to last." + ) + static var openAppWhenRun: Bool = false + + @Parameter(title: "Station", description: "Leave empty for the station you listened to last.") + var station: StationEntity? + + func perform() async throws -> some IntentResult { + try await SubwaveIntentBridge.perform("tuneIn", station.map { ["station": $0.id] } ?? [:]) + return .result() + } +} + +@available(iOS 17.0, *) +struct TuneOutIntent: AudioPlaybackIntent { + static var title: LocalizedStringResource = "Tune out" + static var description = IntentDescription("Stops SUB/WAVE.") + static var openAppWhenRun: Bool = false + + func perform() async throws -> some IntentResult { + try await SubwaveIntentBridge.perform("tuneOut") + return .result() + } +} + +#endif diff --git a/targets/live-activity/index.swift b/targets/live-activity/index.swift index f8073ba..f7ef719 100644 --- a/targets/live-activity/index.swift +++ b/targets/live-activity/index.swift @@ -1,15 +1,34 @@ import SwiftUI import WidgetKit -// The extension's entry point. Only the Live Activity is exported — this target -// deliberately ships no Home Screen or Lock Screen widget: a widget refreshes on -// WidgetKit's timeline budget (a handful of updates an hour), which would show a -// song that finished twenty minutes ago. The Live Activity is push-updated by -// the app while the listener is actually tuned in, which is the only window -// where "what's on air" can be told truthfully. +// The extension's entry point: the Live Activity and the tune control. This +// target deliberately ships no Home Screen or Lock Screen widget: a widget +// refreshes on WidgetKit's timeline budget (a handful of updates an hour), which +// would show a song that finished twenty minutes ago. The Live Activity is +// push-updated by the app while the listener is actually tuned in, which is the +// only window where "what's on air" can be told truthfully. The control only +// says whether the station is on, which the app updates as it changes. @main struct SubwaveWidgets: WidgetBundle { var body: some Widget { - SubwaveLiveActivity() + liveActivity + if #available(iOS 18.0, *) { + TuneControl() + } + } + + /// Exactly one configuration for SubwaveLiveAttributes: two registered for + /// the same attributes type leaves which one renders up to the system. + /// WidgetBundleBuilder only accepts a bare `if #available` (no else), so the + /// choice is made with explicit returns, each wrapped by the builder's own + /// functions so both branches are the same type. + private var liveActivity: some Widget { + if #available(iOS 18.0, *) { + return WidgetBundleBuilder.buildOptional( + WidgetBundleBuilder.buildLimitedAvailability(SubwaveLiveActivityWithSmall())) + } else { + return WidgetBundleBuilder.buildOptional( + WidgetBundleBuilder.buildLimitedAvailability(SubwaveLiveActivity())) + } } } From 9e929c7499fdd0d85f6abbe83ba62bb339747c6a Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 15:03:40 +0000 Subject: [PATCH 2/7] refactor(app): share the intent announcers, on-air states and station read One announcer for the tune-out, station-switch and like subscribers; one on-air state set for the intent tune-in, usePlayer's mount-time adoption and "what's playing"; one store-and-credentials read for StationContext and the intents; one usePlayer tune-out for RemotePause, an intent and a vanished route. StreamRecovery.adopt's doc names the intent path. --- scripts/announcer.test.ts | 30 +++++++++++++++++ src/audio/player.ts | 37 +++++++++++++-------- src/config/StationContext.tsx | 33 ++----------------- src/hooks/usePlayer.ts | 61 ++++++++++++++--------------------- src/intents/on-air.ts | 9 ++---- src/intents/station.ts | 6 ++-- src/lib/announcer.ts | 31 ++++++++++++++++++ src/lib/like-events.ts | 22 +++---------- src/lib/station.ts | 35 ++++++++++++-------- src/lib/stream-recovery.ts | 5 +-- 10 files changed, 145 insertions(+), 124 deletions(-) create mode 100644 scripts/announcer.test.ts create mode 100644 src/lib/announcer.ts diff --git a/scripts/announcer.test.ts b/scripts/announcer.test.ts new file mode 100644 index 0000000..e6e79af --- /dev/null +++ b/scripts/announcer.test.ts @@ -0,0 +1,30 @@ +// The subscriber sets an App Intent tells about a tune-out, a station switch +// or a like (src/lib/announcer.ts). + +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createAnnouncer } from '../src/lib/announcer.ts'; + +test('every subscriber hears an announcement until it unsubscribes', () => { + const a = createAnnouncer(); + const heard: string[] = []; + const off = a.subscribe((n) => heard.push(`a${n}`)); + a.subscribe((n) => heard.push(`b${n}`)); + a.announce(1); + off(); + a.announce(2); + assert.deepEqual(heard, ['a1', 'b1', 'b2']); +}); + +test('a subscriber that throws reaches neither the others nor the announcer', () => { + const a = createAnnouncer(); + let heard = 0; + a.subscribe(() => { + throw new Error('broken'); + }); + a.subscribe(() => { + heard += 1; + }); + assert.doesNotThrow(() => a.announce()); + assert.equal(heard, 1); +}); diff --git a/src/audio/player.ts b/src/audio/player.ts index 4e889f9..a604b4f 100644 --- a/src/audio/player.ts +++ b/src/audio/player.ts @@ -4,7 +4,9 @@ import TrackPlayer, { Capability, type PlayerOptions, RatingType, + State, } from 'react-native-track-player'; +import { createAnnouncer } from '@/lib/announcer'; import { playbackLog } from '@/lib/playback-log'; const STREAM_TRACK_ID = 'subwave-live'; @@ -93,28 +95,35 @@ export async function loadAndPlay(meta: LiveTrackMeta): Promise { // RNTP remote event: an App Intent (src/intents/tune.ts). usePlayer must hear // it before the Stopped event lands, or it reads Stopped as a dead stream and // reconnects, the same trap RemotePause is handled for. -const tuneOutListeners = new Set<() => void>(); +const externalTuneOuts = createAnnouncer(); -export function onExternalTuneOut(fn: () => void): () => void { - tuneOutListeners.add(fn); - return () => { - tuneOutListeners.delete(fn); - }; -} +export const onExternalTuneOut = externalTuneOuts.subscribe; /** stop(), not teardown(): the Icecast connection drops, and lastLiveMeta * survives so the next tune-in resumes at the live edge. */ export async function externalTuneOut(): Promise { - tuneOutListeners.forEach((fn) => { - try { - fn(); - } catch { - /* a broken subscriber must not keep the stream running */ - } - }); + externalTuneOuts.announce(); await TrackPlayer.stop(); } +/** The native states that mean a stream is on its way to the listener or + * reaching them: what an App Intent's tune-in leaves alone, what usePlayer + * adopts at mount, and when "what's playing" measures from the buffer. */ +const ON_AIR_STATES: ReadonlySet = new Set([State.Playing, State.Buffering, State.Loading]); + +export function isOnAir(state: State | null | undefined): boolean { + return state != null && ON_AIR_STATES.has(state); +} + +/** The native state, or None when the player isn't set up yet. */ +export async function playbackStateNow(): Promise { + try { + return (await TrackPlayer.getPlaybackState()).state; + } catch { + return State.None; + } +} + export async function teardown(): Promise { lastLiveMeta = null; try { diff --git a/src/config/StationContext.tsx b/src/config/StationContext.tsx index 9251028..4ccea2c 100644 --- a/src/config/StationContext.tsx +++ b/src/config/StationContext.tsx @@ -16,8 +16,8 @@ import { featuredStation, loadStationCredentials, loadStationPassword, - loadStations, onStationStoreChanged, + readActiveStationState, removeRecent, saveStationCredentials, saveStationPassword, @@ -54,33 +54,6 @@ interface StationContextValue { const Ctx = createContext(null); -/** The stored store plus the active station's login and password, as the - * screens need them. A keychain failure leaves either null rather than - * failing the read. */ -async function readStationState(): Promise<{ - store: StationStore; - credentials: StationCredentials | null; - password: string | null; -}> { - const s = await loadStations(); - let activeCredentials: StationCredentials | null = null; - let activePassword: string | null = null; - try { - activeCredentials = s.activeStation - ? await loadStationCredentials(s.activeStation) - : null; - } catch { - // Boot without credentials if the keychain fails; later actions report failure - // and leave the vault intact. - } - try { - activePassword = s.activeStation ? await loadStationPassword(s.activeStation) : null; - } catch { - // Same: a locked station then asks again rather than failing to boot. - } - return { store: s, credentials: activeCredentials, password: activePassword }; -} - export function StationProvider({ children }: { children: React.ReactNode }) { const [store, setStore] = useState({ activeStation: null, recents: [] }); const [credentials, setCredentials] = useState(null); @@ -95,7 +68,7 @@ export function StationProvider({ children }: { children: React.ReactNode }) { useEffect(() => { let alive = true; - readStationState().then((s) => { + readActiveStationState().then((s) => { if (alive) { setStore(s.store); setCredentials(s.credentials); @@ -116,7 +89,7 @@ export function StationProvider({ children }: { children: React.ReactNode }) { useEffect( () => onStationStoreChanged(() => { - readStationState() + readActiveStationState() .then((s) => { setCredentials(s.credentials); setStationPassword(s.password); diff --git a/src/hooks/usePlayer.ts b/src/hooks/usePlayer.ts index 3c0f72e..f2aa078 100644 --- a/src/hooks/usePlayer.ts +++ b/src/hooks/usePlayer.ts @@ -12,8 +12,10 @@ import { import { setOnAir } from '../../modules/app-intents'; import { getLastLiveMeta, + isOnAir, loadAndPlay, onExternalTuneOut, + playbackStateNow, setupPlayer, teardown, } from '@/audio/player'; @@ -115,6 +117,17 @@ export function usePlayer( }, []); const recoveryRef = useRef(null); + // Every tune-out the listener makes away from the Stop button: a lock-screen + // pause, an App Intent, a vanished route. The ref flips synchronously, ahead + // of the Stopped event, which would otherwise read as a dead stream. + const tunedOut = useCallback(() => { + recoveryRef.current?.tuneOut(); + endIdleSkip(); + tunedInRef.current = false; + setTunedIn(false); + setStatus('idle'); + }, [endIdleSkip]); + useEffect(() => { const recovery = new StreamRecovery({ position: () => TrackPlayer.getProgress().then((p) => p.position), @@ -191,11 +204,7 @@ export function usePlayer( (event) => { plog(playbackEventLine(event)); if (event.type === Event.RemotePause || event.type === Event.RemoteStop) { - recoveryRef.current?.tuneOut(); - endIdleSkip(); - tunedInRef.current = false; - setTunedIn(false); - setStatus('idle'); + tunedOut(); return; } if (event.type === Event.RemoteDuck) { @@ -233,18 +242,13 @@ export function usePlayer( // adopt it has already fired. useEffect(() => { let alive = true; - TrackPlayer.getPlaybackState() - .then(({ state }) => { - if (!alive || tunedInRef.current || !getLastLiveMeta()) return; - if (state !== State.Playing && state !== State.Buffering && state !== State.Loading) { - return; - } - tunedInRef.current = true; - setTunedIn(true); - setStatus(state === State.Playing ? 'playing' : 'connecting'); - recoveryRef.current?.adopt(); - }) - .catch(() => {}); + void playbackStateNow().then((state) => { + if (!alive || tunedInRef.current || !getLastLiveMeta() || !isOnAir(state)) return; + tunedInRef.current = true; + setTunedIn(true); + setStatus(state === State.Playing ? 'playing' : 'connecting'); + recoveryRef.current?.adopt(); + }); return () => { alive = false; }; @@ -257,19 +261,8 @@ export function usePlayer( setOnAir(tunedIn); }, [tunedIn]); - // An App Intent tune-out (src/intents/tune.ts): the same synchronous ref - // flip as the RemotePause handler above, ahead of the Stopped event. - useEffect( - () => - onExternalTuneOut(() => { - recoveryRef.current?.tuneOut(); - endIdleSkip(); - tunedInRef.current = false; - setTunedIn(false); - setStatus('idle'); - }), - [endIdleSkip], - ); + // An App Intent tune-out (src/intents/tune.ts), handled like RemotePause. + useEffect(() => onExternalTuneOut(tunedOut), [tunedOut]); // iOS: an oldDeviceUnavailable route change (Bluetooth speaker off, CarPlay // disconnected, headphones unplugged) is a tune-out (#992) — the @@ -281,16 +274,12 @@ export function usePlayer( const sub = addAudioRouteChangeListener((e) => { plog(`route change reason=${e.reason} outputs=${e.outputs}`); if (e.reason !== ROUTE_REASON_OLD_DEVICE_UNAVAILABLE || !tunedInRef.current) return; - recoveryRef.current?.tuneOut(); - endIdleSkip(); - tunedInRef.current = false; - setTunedIn(false); - setStatus('idle'); + tunedOut(); // stop(), not pause: unloads the item so the Icecast connection drops. TrackPlayer.stop().catch(() => {}); }); return () => sub?.remove(); - }, [endIdleSkip]); + }, [tunedOut]); const prevConnectedRef = useRef(isConnected); useEffect(() => { diff --git a/src/intents/on-air.ts b/src/intents/on-air.ts index 711f32b..d9e0219 100644 --- a/src/intents/on-air.ts +++ b/src/intents/on-air.ts @@ -3,8 +3,8 @@ // the previous track for the stream buffer's length after a change // (heardTrack, the rule useStationFeed promotes tracks by). -import TrackPlayer, { State } from 'react-native-track-player'; import type { IntentReply } from '../../modules/app-intents'; +import { isOnAir, playbackStateNow } from '@/audio/player'; import { heardTrack, leadMsFrom } from '@/lib/heard-track'; import { announceLike } from '@/lib/like-events'; import type { StationApi } from '@/lib/api'; @@ -17,18 +17,13 @@ import { } from './on-air-reply'; import type { IntentStation } from './station'; -async function playingHere(): Promise { - const { state } = await TrackPlayer.getPlaybackState().catch(() => ({ state: State.None })); - return state === State.Playing || state === State.Buffering; -} - async function snapshot(api: StationApi): Promise { const [npRes, stateRes] = await Promise.allSettled([api.nowPlaying(), api.state()]); if (npRes.status !== 'fulfilled') return { reachable: false, online: false, track: null }; const np = npRes.value; const live: OnAirTrack | null = np.nowPlaying; const online = np.streamOnline !== false; - if (!(await playingHere()) || stateRes.status !== 'fulfilled') { + if (!isOnAir(await playbackStateNow()) || stateRes.status !== 'fulfilled') { return { reachable: true, online, track: live }; } // The same pairing useStationFeed makes: /state's live-edge stamp only diff --git a/src/intents/station.ts b/src/intents/station.ts index d98bf46..19dd4d7 100644 --- a/src/intents/station.ts +++ b/src/intents/station.ts @@ -3,7 +3,7 @@ // before any screen has mounted, so it cannot borrow the context's client. import { createApi, type StationApi } from '@/lib/api'; -import { loadStationCredentials, loadStationPassword, loadStations } from '@/lib/station'; +import { readActiveStationState } from '@/lib/station'; export interface IntentStation { base: string; @@ -15,11 +15,9 @@ export interface IntentStation { export const NO_STATION_MESSAGE = 'Open SUB/WAVE and pick a station first.'; export async function activeStation(): Promise { - const store = await loadStations(); + const { store, credentials, password } = await readActiveStationState(); const base = store.activeStation; if (!base) return null; - const credentials = await loadStationCredentials(base).catch(() => null); - const password = await loadStationPassword(base).catch(() => null); return { base, name: store.recents.find((r) => r.url === base)?.name ?? null, diff --git a/src/lib/announcer.ts b/src/lib/announcer.ts new file mode 100644 index 0000000..20482cc --- /dev/null +++ b/src/lib/announcer.ts @@ -0,0 +1,31 @@ +// A set of subscribers told about something that happened outside the React +// tree: an App Intent's tune-out (src/audio/player.ts), its station switch +// (src/lib/station.ts), its like (src/lib/like-events.ts). A subscriber that +// throws is skipped, so it can never stop the action that announced. + +export interface Announcer { + /** Returns the unsubscribe. */ + subscribe(fn: (value: T) => void): () => void; + announce(value: T): void; +} + +export function createAnnouncer(): Announcer { + const listeners = new Set<(value: T) => void>(); + return { + subscribe(fn) { + listeners.add(fn); + return () => { + listeners.delete(fn); + }; + }, + announce(value) { + listeners.forEach((fn) => { + try { + fn(value); + } catch { + /* one broken subscriber must not reach the announcer */ + } + }); + }, + }; +} diff --git a/src/lib/like-events.ts b/src/lib/like-events.ts index 4ef4981..39a8e86 100644 --- a/src/lib/like-events.ts +++ b/src/lib/like-events.ts @@ -2,27 +2,15 @@ // (src/intents/on-air.ts). useTrackLike listens, so the heart and the Live // Activity it drives fill now instead of on the next song's status fetch. +import { createAnnouncer } from './announcer'; + export interface ExternalLike { songId: string; /** Likes for the song, all airings, when the station said. */ count?: number; } -const listeners = new Set<(like: ExternalLike) => void>(); - -export function onExternalLike(fn: (like: ExternalLike) => void): () => void { - listeners.add(fn); - return () => { - listeners.delete(fn); - }; -} +const likes = createAnnouncer(); -export function announceLike(like: ExternalLike): void { - listeners.forEach((fn) => { - try { - fn(like); - } catch { - /* a broken subscriber must not fail the like */ - } - }); -} +export const onExternalLike = likes.subscribe; +export const announceLike = likes.announce; diff --git a/src/lib/station.ts b/src/lib/station.ts index f4d160c..7691478 100644 --- a/src/lib/station.ts +++ b/src/lib/station.ts @@ -1,6 +1,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage'; import Constants from 'expo-constants'; import * as SecureStore from 'expo-secure-store'; +import { createAnnouncer } from './announcer'; import { createCredentialVault } from './credential-vault'; import { migrateLegacyStationStore, @@ -148,21 +149,27 @@ export async function clearActiveStation(): Promise { // A change to the stored active station made outside StationContext: a // station switch from Siri, Shortcuts or Spotlight (src/intents/tune.ts). // StationContext reloads the store on it, so the screens follow. -const storeListeners = new Set<() => void>(); +const storeChanges = createAnnouncer(); -export function onStationStoreChanged(fn: () => void): () => void { - storeListeners.add(fn); - return () => { - storeListeners.delete(fn); - }; -} +export const onStationStoreChanged = storeChanges.subscribe; export function announceStationStoreChanged(): void { - storeListeners.forEach((fn) => { - try { - fn(); - } catch { - /* a broken subscriber must not stop the switch */ - } - }); + storeChanges.announce(); +} + +/** The store, and the active station's login and station password, read the + * way StationContext reads them at boot and an App Intent reads them with no + * screen mounted. A keychain failure reads as none, so boot never fails on it: + * later actions report the failure and leave the vault intact, and a locked + * station asks again. */ +export async function readActiveStationState(): Promise<{ + store: StationStore; + credentials: StationCredentials | null; + password: string | null; +}> { + const store = await loadStations(); + const base = store.activeStation; + const credentials = base ? await loadStationCredentials(base).catch(() => null) : null; + const password = base ? await loadStationPassword(base).catch(() => null) : null; + return { store, credentials, password }; } diff --git a/src/lib/stream-recovery.ts b/src/lib/stream-recovery.ts index b80fdaf..ba9f37b 100644 --- a/src/lib/stream-recovery.ts +++ b/src/lib/stream-recovery.ts @@ -178,8 +178,9 @@ export class StreamRecovery { void this.reload(reason, null, true); } - /** Playback this hook didn't start (service.ts loaded it while the player - * wasn't mounted): watch it, no reload. */ + /** Playback the player didn't start, loaded while it wasn't mounted: by + * service.ts (Android's headless service) or by an App Intent + * (src/intents/tune.ts, a cold Siri launch). Watch it, no reload. */ adopt(): void { this.begin(); } From 451fddc21637012e456aaf0cbf02acdc40853873 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 15:08:25 +0000 Subject: [PATCH 3/7] fix(app): hand intent tune-ins to the mounted player A Siri, Shortcuts, Spotlight or Control tune-in loaded the stream itself even with the player mounted, outside stream-recovery.ts: beside a backoff's queued reload, with no idle skip, and on a switch with a teardown recovery could read as a failure and answer by reloading the old station. Every tune-in now goes over service.ts's own claim (playOnMountedPlayer) and loads directly only when no player is mounted. A switch with the player mounted writes the store and arms a tune-in for the new base (tuneInOnArrival); usePlayer takes it when StationContext hands it the new station and tunes in through StreamRecovery in place of the stop. The decisions move to tune-flow.ts so scripts/intent-tune.test.ts can drive them. Intent tune-ins and tune-outs set the Control's on-air state for when no player is mounted, log to the playback log, and cut their waits to a deadline the bridge will send (deadline.ts, a conservative fallback until then). --- CLAUDE.md | 2 +- docs/TESTING.md | 27 +++- modules/app-intents/index.ts | 16 +- scripts/intent-tune.test.ts | 249 ++++++++++++++++++++++++++++++++ src/hooks/usePlayer.ts | 24 ++- src/intents/deadline.ts | 38 +++++ src/intents/handlers.ts | 6 +- src/intents/station-messages.ts | 5 + src/intents/station.ts | 2 +- src/intents/tune-flow.ts | 163 +++++++++++++++++++++ src/intents/tune.ts | 214 +++++++++++++-------------- src/lib/remote-play.ts | 59 ++++++++ 12 files changed, 676 insertions(+), 129 deletions(-) create mode 100644 scripts/intent-tune.test.ts create mode 100644 src/intents/deadline.ts create mode 100644 src/intents/station-messages.ts create mode 100644 src/intents/tune-flow.ts diff --git a/CLAUDE.md b/CLAUDE.md index 88fe093..6d04834 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. - **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. 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. +- **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`). 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. - **Playback lines go through `plog` (`src/hooks/usePlayer.ts`), and are redacted before they are stored** (#2140). Release builds keep the last few hundred for the About sheet's Share playback log, so `src/lib/playback-log.ts` strips the station password, the Station login, URL queries and route device names first; a line that can carry a new kind of secret needs a rule and a test there. `PlaybackLog.add` never throws, because `plog` runs mid-reload and ahead of each event's dispatch: a line it can't redact is lost, never stored raw (#2160). - **Every request to a station sends the Station login as a header, from `loginHeaders` (`src/lib/api.ts`)** (#764, #1873): API calls go to the credential-free base, and images get the header too. Android's fetch and image loaders, and AVPlayer, ignore URL userinfo. diff --git a/docs/TESTING.md b/docs/TESTING.md index 5192cef..f23909b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -371,10 +371,13 @@ read the station store, so `StationContext` mirrors names and credential-free bases into the App Group (`setStations`), and the module then calls the app-target `SubwaveStationIndex.reindex` by class name to refresh Spotlight and the Siri phrases. A switch away from the active station is JS -(`src/intents/tune.ts`): it writes the store, stops the old stream, starts the -new one, and only then tells `StationContext`, so `usePlayer` finds the -playing stream already belongs to the new base (`streamBelongsTo`) and keeps -it. On iOS 27, `AudioSchemaIntents.swift` exposes the same stations to Siri's +(`src/intents/tune-flow.ts`). With the player mounted it writes the store, arms +a tune-in for the new base (`tuneInOnArrival`, `src/lib/remote-play.ts`) and +tells `StationContext`; `usePlayer`, seeing its base change, takes it and tunes +in through `StreamRecovery` in place of the stop a switch makes. With none +mounted it stops the old stream, starts the new one, and only then tells +`StationContext`, so a player mounting mid-switch finds the playing stream +already belongs to the new base (`streamBelongsTo`) and keeps it. On iOS 27, `AudioSchemaIntents.swift` exposes the same stations to Siri's audio search. The intents are thin. Each hands its action to JS and waits for the answer: @@ -408,19 +411,31 @@ What is easy to get wrong: when a scene connects. iOS connects one for an intent launch even though the app is never shown, so JS boots (checked on iOS 18.5 and 27). If an intent ever times out cold, look there first. +- **An intent loads only when no player is mounted.** With one mounted, every + tune-in is handed to it over `service.ts`'s own claim (`playOnMountedPlayer`), + so it goes through `stream-recovery.ts` like any listener's load: one at a + time, with the idle skip, never beside a backoff's reload (CLAUDE.md). + `scripts/intent-tune.test.ts` holds the routing. - **`usePlayer` must adopt audio it did not start.** A cold tune-in can reach Playing before any screen mounts, so the hook reads the player's state on mount. A tune-out goes through `externalTuneOut()`, or the hook reads the Stopped event as a dead stream and reconnects. +- **Every answer must beat the bridge's 20 s window**, or Siri says the app + didn't respond for work that went through, and the listener asks again. + The bridge sends its deadline with each request and JS cuts every wait to it + (`src/intents/deadline.ts`): the tune-in's wait for audio and the card, the + song request's POST and polling. - **ActivityKit refuses a background app.** `liveactivitiesd` logs "Requester is not foreground" and the card never appears, though the audio plays. Inside a `LiveActivityIntent`'s run the request is allowed, which is why - `TuneInIntent` is one and `tune.ts` holds its answer (up to 2 s) until the + `TuneInIntent` is one and `tune.ts` holds its answer (up to 2 s, inside the + deadline) until the card has been asked for. `useLiveActivity` also retries when the app comes forward, for a tune-in that missed the window. - **The control cannot ask the player.** It reads an on-air flag in the App Group that `usePlayer` writes through `setOnAir`, which also reloads the - control. An app killed mid-song leaves the flag on until the next tap or + control; an intent's tune-in and tune-out write it too, for when no player + is mounted. An app killed mid-song leaves the flag on until the next tap or launch. The flag key and the control kind are matched by string between `TuneControl.swift` and the app-intents module. - **A control never resolves parameters.** `ToggleTuneIntent` is built with diff --git a/modules/app-intents/index.ts b/modules/app-intents/index.ts index 26f789a..789c626 100644 --- a/modules/app-intents/index.ts +++ b/modules/app-intents/index.ts @@ -12,15 +12,25 @@ export interface IntentReply { message?: string; } +/** What a Swift intent asks for (SubwaveIntentAction in + * targets/live-activity/_shared/SubwaveIntentBridge.swift). A string, since an + * OTA update can meet a binary with actions it doesn't know yet. */ +export type IntentAction = 'tuneIn' | 'tuneOut' | 'request' | 'nowPlaying' | 'like' | (string & {}); + export type IntentHandler = ( - action: string, + action: IntentAction, args: Record, + /** Epoch ms at which the Swift bridge stops waiting; absent from a binary + * that sends none (src/intents/deadline.ts). */ + deadline: number | undefined, ) => Promise; interface IntentRequest { token: string; action: string; args?: Record; + /** Epoch ms at which the Swift bridge stops waiting. */ + deadline?: number; } interface Subscription { @@ -79,8 +89,8 @@ export function setIntentHandler(handler: IntentHandler): Subscription | null { if (!native) return null; const bridge = native; try { - return bridge.addListener('onIntent', ({ token, action, args }) => { - void handler(action, args ?? {}) + return bridge.addListener('onIntent', ({ token, action, args, deadline }) => { + void handler(action, args ?? {}, deadline) .catch((): IntentReply => ({ ok: false })) .then((reply) => { try { diff --git a/scripts/intent-tune.test.ts b/scripts/intent-tune.test.ts new file mode 100644 index 0000000..7052322 --- /dev/null +++ b/scripts/intent-tune.test.ts @@ -0,0 +1,249 @@ +// Tune-ins and tune-outs from Siri, Shortcuts, Spotlight and the Control +// (src/intents/tune-flow.ts): with the player mounted every load is handed to +// it, so it goes through StreamRecovery; only with none mounted does the +// intent load the stream itself. Also the mounted player's side of a station +// switch (src/lib/remote-play.ts) and the bridge's deadline +// (src/intents/deadline.ts). + +import assert from 'node:assert/strict'; +import test, { type TestContext } from 'node:test'; +import { + FALLBACK_BUDGET_MS, + intentDeadline, + REPLY_MARGIN_MS, + timeLeft, + TIMED_OUT, + within, +} from '../src/intents/deadline.ts'; +import { NO_STATION_MESSAGE } from '../src/intents/station-messages.ts'; +import { NOT_SAVED_MESSAGE, tuneIn, tuneOut, type TuneDeps } from '../src/intents/tune-flow.ts'; +import { + claimRemotePlay, + playerMounted, + playOnMountedPlayer, + takeArrival, + tuneInOnArrival, +} from '../src/lib/remote-play.ts'; + +const NIGHT = { url: 'https://radio.example.com', name: 'Night Shift', lastUsed: 2 }; +const WAVE = { url: 'https://www.getsubwave.com', name: 'SUB/WAVE', lastUsed: 1 }; +const DEADLINE = 1_000_000; + +interface Opts { + mounted?: boolean; + /** The mounted player has a station to load (the claim returns true). */ + playerTakes?: boolean; + /** The mounted player reaches the new station on a switch. */ + arrives?: boolean; + onAir?: boolean; + hasStream?: boolean; + active?: string | null; + plays?: boolean; +} + +function intents(o: Opts = {}) { + const calls: string[] = []; + const onAirStates: boolean[] = []; + let active = o.active === undefined ? NIGHT.url : o.active; + const deps: TuneDeps = { + loadStore: async () => ({ activeStation: active, recents: [NIGHT, WAVE] }), + setActiveStation: async (ref) => { + active = ref.url; + calls.push(`store ${ref.name}`); + }, + announceSwitch: () => calls.push('announce'), + onAir: async () => o.onAir ?? false, + playerMounted: () => o.mounted ?? false, + playOnMountedPlayer: () => { + if (!(o.mounted && (o.playerTakes ?? true))) return false; + calls.push('player tunes in'); + return true; + }, + tuneInOnArrival: (base) => { + calls.push(`arm ${base}`); + return { + taken: Promise.resolve(o.arrives ?? true), + cancel: () => calls.push('disarm'), + }; + }, + hasStream: () => o.hasStream ?? false, + reloadLast: async () => { + calls.push('direct reload'); + }, + teardown: async () => { + calls.push('teardown'); + }, + activeStation: async () => + active + ? { + name: [NIGHT, WAVE].find((s) => s.url === active)?.name ?? null, + load: async () => { + calls.push(`direct load ${active}`); + }, + } + : null, + startAndWait: async (start, deadline) => { + assert.equal(deadline, DEADLINE); + try { + await start(); + } catch { + return false; + } + return o.plays ?? true; + }, + tuneOut: async () => { + calls.push('tune out'); + }, + setOnAir: (on) => onAirStates.push(on), + log: () => {}, + }; + return { deps, calls, onAirStates }; +} + +test('with the player mounted, a tune-in is handed to it, never loaded directly', async () => { + for (const hasStream of [true, false]) { + const s = intents({ mounted: true, hasStream }); + assert.deepEqual(await tuneIn(s.deps, undefined, DEADLINE), { ok: true }); + assert.deepEqual(s.calls, ['player tunes in']); + assert.deepEqual(s.onAirStates, [true]); + } +}); + +test('with no player mounted, the intent loads the stream itself', async () => { + const warm = intents({ hasStream: true }); + await tuneIn(warm.deps, undefined, DEADLINE); + assert.deepEqual(warm.calls, ['direct reload']); + + const cold = intents(); + assert.deepEqual(await tuneIn(cold.deps, undefined, DEADLINE), { ok: true }); + assert.deepEqual(cold.calls, [`direct load ${NIGHT.url}`]); + assert.deepEqual(cold.onAirStates, [true]); +}); + +test('a mounted player with no station leaves the load to the intent', async () => { + const s = intents({ mounted: true, playerTakes: false }); + await tuneIn(s.deps, undefined, DEADLINE); + assert.deepEqual(s.calls, [`direct load ${NIGHT.url}`]); +}); + +test('a stream already on air is left alone, and the control says so', async () => { + const s = intents({ mounted: true, onAir: true }); + assert.deepEqual(await tuneIn(s.deps, undefined, DEADLINE), { ok: true }); + assert.deepEqual(s.calls, []); + assert.deepEqual(s.onAirStates, [true]); +}); + +test('naming the station already active tunes in to it without a switch', async () => { + const s = intents({ mounted: true }); + await tuneIn(s.deps, `${NIGHT.url}/`, DEADLINE); + assert.deepEqual(s.calls, ['player tunes in']); +}); + +test('a switch with the player mounted lets the player tune in on the new station', async () => { + const s = intents({ mounted: true }); + assert.deepEqual(await tuneIn(s.deps, WAVE.url, DEADLINE), { ok: true }); + // Armed before StationContext hears of it; no teardown or load here. + assert.deepEqual(s.calls, ['store SUB/WAVE', `arm ${WAVE.url}`, 'announce', 'disarm']); + assert.deepEqual(s.onAirStates, [true]); +}); + +test('a switch the player never reaches is a failure, and the control is the player’s', async () => { + const s = intents({ mounted: true, arrives: false }); + const reply = await tuneIn(s.deps, WAVE.url, DEADLINE); + assert.equal(reply.ok, false); + assert.match(reply.message ?? '', /SUB\/WAVE/); + assert.ok(!s.calls.some((c) => c.startsWith('direct'))); + assert.deepEqual(s.onAirStates, []); +}); + +test('a switch with no player mounted loads the new station, then tells StationContext', async () => { + const s = intents(); + assert.deepEqual(await tuneIn(s.deps, WAVE.url, DEADLINE), { ok: true }); + assert.deepEqual(s.calls, ['store SUB/WAVE', 'teardown', `direct load ${WAVE.url}`, 'announce']); +}); + +test('a stream that never starts is reported, and the control turns off with no player', async () => { + const s = intents({ plays: false }); + const reply = await tuneIn(s.deps, undefined, DEADLINE); + assert.equal(reply.ok, false); + assert.match(reply.message ?? '', /Night Shift/); + assert.deepEqual(s.onAirStates, [false]); +}); + +test('an unsaved station or no station at all is said, and nothing loads', async () => { + const unsaved = intents(); + assert.deepEqual(await tuneIn(unsaved.deps, 'https://elsewhere.example.com', DEADLINE), { + ok: false, + message: NOT_SAVED_MESSAGE, + }); + const none = intents({ active: null }); + assert.deepEqual(await tuneIn(none.deps, undefined, DEADLINE), { + ok: false, + message: NO_STATION_MESSAGE, + }); + assert.deepEqual([...unsaved.calls, ...none.calls], []); +}); + +test('a tune-out stops the player and turns the control off', async () => { + const s = intents({ mounted: true }); + assert.deepEqual(await tuneOut(s.deps), { ok: true }); + assert.deepEqual(s.calls, ['tune out']); + assert.deepEqual(s.onAirStates, [false]); +}); + +function claim(t: TestContext, handler: () => boolean) { + t.after(claimRemotePlay(handler)); +} + +test('the mounted player’s claim takes an intent’s tune-in', (t) => { + assert.equal(playerMounted(), false); + assert.equal(playOnMountedPlayer(), false); + let plays = 0; + claim(t, () => { + plays += 1; + return true; + }); + assert.equal(playerMounted(), true); + assert.equal(playOnMountedPlayer(), true); + assert.equal(plays, 1); +}); + +test('the player takes a switch once, only on the station it was armed for', async () => { + const arrival = tuneInOnArrival('https://www.getsubwave.com', 10_000); + assert.equal(takeArrival('https://radio.example.com'), false); + assert.equal(takeArrival('https://www.getsubwave.com/'), true); + assert.equal(takeArrival('https://www.getsubwave.com'), false); + assert.equal(await arrival.taken, true); +}); + +test('a newer switch replaces an older one, and a cancelled one is not taken', async () => { + const older = tuneInOnArrival('https://radio.example.com', 10_000); + const newer = tuneInOnArrival('https://www.getsubwave.com', 10_000); + assert.equal(await older.taken, false); + assert.equal(takeArrival('https://radio.example.com'), false); + newer.cancel(); + assert.equal(await newer.taken, false); + assert.equal(takeArrival('https://www.getsubwave.com'), false); +}); + +test('an arrival the player never reaches lapses at its cap', async () => { + const arrival = tuneInOnArrival('https://www.getsubwave.com', 5); + assert.equal(await arrival.taken, false); + assert.equal(takeArrival('https://www.getsubwave.com'), false); +}); + +test('the answer is due a margin before the bridge stops waiting', () => { + assert.equal(intentDeadline(20_000, 3_000), 20_000 - REPLY_MARGIN_MS); + // A binary that sends none: the worst case, a whole ack window spent booting. + assert.equal(intentDeadline(undefined, 3_000), 3_000 + FALLBACK_BUDGET_MS - REPLY_MARGIN_MS); + assert.equal(intentDeadline(Number.NaN, 3_000), 3_000 + FALLBACK_BUDGET_MS - REPLY_MARGIN_MS); + // A deadline far ahead (a clock change) is capped. + assert.ok(intentDeadline(10_000_000, 3_000) <= 3_000 + 30_000); + assert.equal(timeLeft(10, 25), 0); + assert.equal(timeLeft(25, 10), 15); +}); + +test('within gives the work’s answer, or TIMED_OUT once the wait ends first', async () => { + assert.equal(await within(Promise.resolve('done'), new Promise(() => {})), 'done'); + assert.equal(await within(new Promise(() => {}), Promise.resolve()), TIMED_OUT); +}); diff --git a/src/hooks/usePlayer.ts b/src/hooks/usePlayer.ts index f2aa078..6a40bf0 100644 --- a/src/hooks/usePlayer.ts +++ b/src/hooks/usePlayer.ts @@ -23,7 +23,7 @@ import type { StationApi } from '@/lib/api'; import { SKIP_CUSHION_SECONDS } from '@/lib/idle-skip'; import { IdleSkip } from '@/lib/idle-skip-playback'; import { playbackEventLine, playbackLog } from '@/lib/playback-log'; -import { claimRemotePlay } from '@/lib/remote-play'; +import { claimRemotePlay, takeArrival } from '@/lib/remote-play'; import { MAX_LEAD_SECONDS } from '@/lib/sessionFeed'; import { streamBelongsTo } from '@/lib/station-store'; import { StreamRecovery } from '@/lib/stream-recovery'; @@ -302,18 +302,32 @@ export function usePlayer( // RNTP level; drop local tuned-in state so the UI doesn't claim "on air" // over dead audio. (The event handler ignores State.None because reset() // also fires it mid tune-in and mid reconnect.) - // One exception: a switch from Siri, Shortcuts or Spotlight - // (src/intents/tune.ts) starts the new station's stream before the base - // changes here. A stream that already belongs to the new base is kept. + // Two exceptions, both a switch from Siri, Shortcuts or Spotlight + // (src/intents/tune.ts). With this player mounted, the intent asks for a + // tune-in on the new station, which goes through StreamRecovery in place of + // the stop: its load replaces the old item, so nothing is torn down under + // it. With none mounted, the intent started the new stream itself before + // the base changed here, and a stream that already belongs to the new base + // is kept. const prevBaseRef = useRef(api?.base ?? null); useEffect(() => { const nextBase = api?.base ?? null; if (prevBaseRef.current === nextBase) return; prevBaseRef.current = nextBase; + const recovery = recoveryRef.current; + if (nextBase && recovery && takeArrival(nextBase)) { + plog('intent station switch: tuning in on the new station'); + endIdleSkip(); + tunedInRef.current = true; + setTunedIn(true); + setStatus('connecting'); + recovery.tuneIn('remote'); + return; + } const meta = getLastLiveMeta(); const adopted = !!(nextBase && meta && streamBelongsTo(meta.url, nextBase)); if (tunedInRef.current && !adopted) stop(); - }, [api, stop]); + }, [api, stop, endIdleSkip]); const prevFormatRef = useRef(streamFormat); useEffect(() => { diff --git a/src/intents/deadline.ts b/src/intents/deadline.ts new file mode 100644 index 0000000..d8aae89 --- /dev/null +++ b/src/intents/deadline.ts @@ -0,0 +1,38 @@ +// When an App Intent's answer must be in. The Swift bridge gives up on JS at +// its reply window (SubwaveIntentBridge.swift) and Siri then says the app +// didn't respond, even for work that went through, so every wait in +// src/intents/ is cut to fit. Pure, so scripts/intent-tune.test.ts can drive it. + +/** Kept back for the reply's trip to Swift and the bridge's 200 ms poll. */ +export const REPLY_MARGIN_MS = 1500; + +/** A request that names no deadline (a binary from before the bridge sent + * one) is assumed to have spent the bridge's whole 10 s ack window booting, + * out of its 20 s: the worst case. */ +export const FALLBACK_BUDGET_MS = 10_000; + +/** Never trusted for longer than this: a clock change on the device mid-intent + * must not hold Siri open. */ +const MAX_BUDGET_MS = 30_000; + +/** The moment, in epoch ms, by which JS must have answered: the bridge's own + * deadline less the margin, or the fallback from when JS received it. */ +export function intentDeadline(sent: unknown, receivedAt: number): number { + if (typeof sent !== 'number' || !Number.isFinite(sent)) { + return receivedAt + FALLBACK_BUDGET_MS - REPLY_MARGIN_MS; + } + return Math.min(sent, receivedAt + MAX_BUDGET_MS) - REPLY_MARGIN_MS; +} + +/** What is left of the budget, never negative. */ +export function timeLeft(deadline: number, now: number): number { + return Math.max(0, deadline - now); +} + +export const TIMED_OUT: unique symbol = Symbol('timed out'); + +/** `work`, or TIMED_OUT once `wait` settles first. `wait` is a timer, so a + * test can hand in one it controls. */ +export function within(work: Promise, wait: Promise): Promise { + return Promise.race([work, wait.then((): typeof TIMED_OUT => TIMED_OUT)]); +} diff --git a/src/intents/handlers.ts b/src/intents/handlers.ts index f486d0e..9414c15 100644 --- a/src/intents/handlers.ts +++ b/src/intents/handlers.ts @@ -4,16 +4,18 @@ // screen mounts. import { setIntentHandler } from '../../modules/app-intents'; +import { intentDeadline } from './deadline'; import { likeHeardTrack, whatsPlaying } from './on-air'; import { askForSong } from './request-reply'; import { activeStation, NO_STATION_MESSAGE } from './station'; import { tuneIn, tuneOut } from './tune'; export function registerIntentHandlers(): void { - setIntentHandler(async (action, args) => { + setIntentHandler(async (action, args, sentDeadline) => { + const deadline = intentDeadline(sentDeadline, Date.now()); switch (action) { case 'tuneIn': - return tuneIn(args.station); + return tuneIn(args.station, deadline); case 'tuneOut': return tuneOut(); case 'request': diff --git a/src/intents/station-messages.ts b/src/intents/station-messages.ts new file mode 100644 index 0000000..548478c --- /dev/null +++ b/src/intents/station-messages.ts @@ -0,0 +1,5 @@ +// What Siri says when an intent has no station to act on. Apart from +// src/intents/station.ts, which reads the store, so the pure intent code and +// its tests can use it. + +export const NO_STATION_MESSAGE = 'Open SUB/WAVE and pick a station first.'; diff --git a/src/intents/station.ts b/src/intents/station.ts index 19dd4d7..99a4e32 100644 --- a/src/intents/station.ts +++ b/src/intents/station.ts @@ -12,7 +12,7 @@ export interface IntentStation { api: StationApi; } -export const NO_STATION_MESSAGE = 'Open SUB/WAVE and pick a station first.'; +export { NO_STATION_MESSAGE } from './station-messages'; export async function activeStation(): Promise { const { store, credentials, password } = await readActiveStationState(); diff --git a/src/intents/tune-flow.ts b/src/intents/tune-flow.ts new file mode 100644 index 0000000..5ce7b46 --- /dev/null +++ b/src/intents/tune-flow.ts @@ -0,0 +1,163 @@ +// How an App Intent tunes in and out: which station, and who loads it. Pure, +// so scripts/intent-tune.test.ts can drive it; src/intents/tune.ts wires it to +// the player, the station store and the bridge. +// +// While the player is mounted every load goes through it, and so through +// StreamRecovery (CLAUDE.md): one at a time, with its watchdog, backoff and +// idle skip. Only with no player mounted, as after a cold Siri launch, does +// the intent load the stream itself; usePlayer adopts it when it mounts. A +// station switch with the player mounted writes the store and lets the player +// tune in once StationContext hands it the new station. + +import type { IntentReply } from '../../modules/app-intents'; +import { splitStationAddress, type StoredStationRef } from '../lib/station-credentials'; +import { findSavedStation } from '../lib/station-store'; +import { NO_STATION_MESSAGE } from './station-messages'; + +export const NOT_SAVED_MESSAGE = "That station isn't saved in SUB/WAVE. Add it in the app first."; + +/** How long a switch waits for StationContext to hand the player the new + * station: a store read and a render. */ +export const ARRIVAL_WAIT_MS = 3000; + +export interface TuneDeps { + loadStore(): Promise<{ activeStation: string | null; recents: StoredStationRef[] }>; + setActiveStation(ref: StoredStationRef): Promise; + /** Tells StationContext the store changed. */ + announceSwitch(): void; + /** The stream is playing or on its way (isOnAir). */ + onAir(): Promise; + playerMounted(): boolean; + /** Hand a tune-in on the current station to the mounted player. */ + playOnMountedPlayer(): boolean; + /** Arm the mounted player to tune in when it reaches `base`. */ + tuneInOnArrival(base: string, timeoutMs: number): { taken: Promise; cancel(): void }; + /** A live stream was loaded and not torn down since. */ + hasStream(): boolean; + /** Direct loads, for when no player is mounted. */ + reloadLast(): Promise; + teardown(): Promise; + /** The active station's name and a direct load of its MP3 mount. */ + activeStation(): Promise<{ name: string | null; load(): Promise } | null>; + /** Runs `start`, listening first; true once the stream plays and the Live + * Activity has had its chance, false if it fails or `start` throws. */ + startAndWait(start: () => Promise, deadline: number): Promise; + tuneOut(): Promise; + /** The tune control's state (Control Center, Lock Screen, Action button). */ + setOnAir(onAir: boolean): void; + log(line: string): void; +} + +/** Tune in to `stationId` (a saved station's base, as Siri and Spotlight know + * it), or to the station listened to last when there is none. */ +export async function tuneIn( + deps: TuneDeps, + stationId: string | undefined, + deadline: number, +): Promise { + if (stationId) { + const store = await deps.loadStore(); + const wanted = findSavedStation(store.recents, stationId); + if (!wanted) return { ok: false, message: NOT_SAVED_MESSAGE }; + const active = store.activeStation ? splitStationAddress(store.activeStation).base : null; + if (splitStationAddress(wanted.url).base !== active) return switchTo(deps, wanted, deadline); + } + + if (await deps.onAir()) { + deps.setOnAir(true); + return { ok: true }; + } + + // Warm: the same reload a lock-screen Play does (service.ts). + if (deps.hasStream()) { + return started(deps, null, await deps.startAndWait(() => load(deps, deps.reloadLast), deadline)); + } + + // Cold, or after an in-app stop: the stored station. Always the MP3 mount + // when loaded here: a stored format preference is only honoured once the + // station's feed confirms the mount, and usePlayer retunes onto it then. + const station = await deps.activeStation(); + if (!station) return { ok: false, message: NO_STATION_MESSAGE }; + return started( + deps, + station.name, + await deps.startAndWait(() => load(deps, station.load), deadline), + ); +} + +/** Through the mounted player when there is one, else directly. */ +async function load(deps: TuneDeps, direct: () => Promise): Promise { + if (deps.playOnMountedPlayer()) { + deps.log('intent tune-in: handed to the player'); + return; + } + deps.log('intent tune-in: no player mounted, loading directly'); + await direct(); +} + +/** Another saved station. */ +async function switchTo( + deps: TuneDeps, + ref: StoredStationRef, + deadline: number, +): Promise { + const base = splitStationAddress(ref.url).base; + await deps.setActiveStation(ref); + + if (deps.playerMounted()) { + // The player stops the old station and tunes in to this one when its + // base changes; armed first, so a fast store read is not missed. + deps.log('intent station switch: handed to the player'); + const arrival = deps.tuneInOnArrival(base, ARRIVAL_WAIT_MS); + deps.announceSwitch(); + const ok = await deps.startAndWait(async () => { + if (!(await arrival.taken)) throw new Error('the player did not reach the station'); + }, deadline); + arrival.cancel(); + return started(deps, ref.name, ok); + } + + // No player: stop the old stream, start the new one, and tell + // StationContext only once it is loaded, so that when the screens' base + // changes the stream playing already belongs to it and usePlayer keeps it + // (streamBelongsTo) instead of stopping a stale one. + deps.log('intent station switch: no player mounted, loading directly'); + await deps.teardown(); + const station = await deps.activeStation(); + if (!station) { + deps.announceSwitch(); + return { ok: false, message: NO_STATION_MESSAGE }; + } + const ok = await deps.startAndWait(async () => { + try { + await station.load(); + } finally { + // The station switched even if its stream did not start. + deps.announceSwitch(); + } + }, deadline); + return started(deps, station.name ?? ref.name, ok); +} + +function started(deps: TuneDeps, stationName: string | null, ok: boolean): IntentReply { + // With a player mounted it owns the control's state, failures included: it + // stays tuned in through its own backoff. + if (ok) deps.setOnAir(true); + else if (!deps.playerMounted()) deps.setOnAir(false); + return ok ? { ok: true } : failed(stationName); +} + +export function failed(stationName: string | null): IntentReply { + const station = stationName ?? 'the station'; + return { + ok: false, + message: `Couldn't reach ${station}. If it's private, open SUB/WAVE to unlock it.`, + }; +} + +export async function tuneOut(deps: TuneDeps): Promise { + deps.log('intent tune-out'); + await deps.tuneOut().catch(() => {}); + deps.setOnAir(false); + return { ok: true }; +} diff --git a/src/intents/tune.ts b/src/intents/tune.ts index 7112614..b1f10b3 100644 --- a/src/intents/tune.ts +++ b/src/intents/tune.ts @@ -1,21 +1,35 @@ // Tune in and out on behalf of an App Intent (Siri, Shortcuts, Spotlight, a -// Control), including to another saved station. +// Control), including to another saved station. The decisions are in +// tune-flow.ts; this wires them to the player, the store and the bridge. // Module-level, not a hook: an intent can launch the app straight into the // background, where this runs before any screen has mounted, or with none // mounting at all. usePlayer adopts the audio when it does mount. import TrackPlayer, { Event, State } from 'react-native-track-player'; -import type { IntentReply } from '../../modules/app-intents'; +import { setOnAir, type IntentReply } from '../../modules/app-intents'; import { isLiveActivitySupported, onLiveActivityStart } from '../../modules/live-activity'; -import { externalTuneOut, getLastLiveMeta, loadAndPlay, teardown } from '@/audio/player'; +import { + externalTuneOut, + getLastLiveMeta, + isOnAir, + loadAndPlay, + playbackStateNow, + teardown, +} from '@/audio/player'; +import { playbackLog } from '@/lib/playback-log'; +import { + playerMounted, + playOnMountedPlayer, + tuneInOnArrival, +} from '@/lib/remote-play'; import { announceStationStoreChanged, loadStations, setActiveStation } from '@/lib/station'; -import { splitStationAddress, type StoredStationRef } from '@/lib/station-credentials'; -import { findSavedStation } from '@/lib/station-store'; -import { activeStation, NO_STATION_MESSAGE } from './station'; +import { timeLeft } from './deadline'; +import { activeStation } from './station'; +import * as flow from './tune-flow'; -// How long a tune-in waits for audio before answering. Long enough that a -// refused or unreachable stream is reported to Siri rather than silently -// failing; short enough to stay inside the bridge's reply window. +// How long a tune-in waits for audio before answering, at most. Long enough +// that a refused or unreachable stream is reported to Siri rather than +// silently failing; cut shorter when the bridge's deadline is nearer. const START_WAIT_MS = 8000; // How long a tune-in holds its answer, once audio is playing, for @@ -25,140 +39,118 @@ const START_WAIT_MS = 8000; // the next time the app is opened. const CARD_WAIT_MS = 2000; -const ON_AIR = new Set([State.Playing, State.Buffering, State.Loading]); +const deps: flow.TuneDeps = { + loadStore: loadStations, + setActiveStation: async (ref) => { + await setActiveStation({ url: ref.url, name: ref.name }); + }, + announceSwitch: announceStationStoreChanged, + onAir: async () => isOnAir(await playbackStateNow()), + playerMounted, + playOnMountedPlayer, + tuneInOnArrival, + hasStream: () => getLastLiveMeta() !== null, + reloadLast: async () => { + const meta = getLastLiveMeta(); + if (meta) await loadAndPlay(meta); + }, + teardown, + activeStation: async () => { + const station = await activeStation(); + if (!station) return null; + const { api } = station; + return { + name: station.name, + load: () => loadAndPlay({ url: api.streamUrl('mp3'), headers: api.streamHeaders() }), + }; + }, + startAndWait, + tuneOut: externalTuneOut, + setOnAir, + log: (line) => playbackLog.add(line), +}; -const NOT_SAVED_MESSAGE = "That station isn't saved in SUB/WAVE. Add it in the app first."; - -/** Tune in to `stationId` (a saved station's base, as Siri and Spotlight know - * it), or to the station listened to last when there is none. */ -export async function tuneIn(stationId?: string): Promise { - if (stationId) { - const store = await loadStations(); - const wanted = findSavedStation(store.recents, stationId); - if (!wanted) return { ok: false, message: NOT_SAVED_MESSAGE }; - const active = store.activeStation ? splitStationAddress(store.activeStation).base : null; - if (splitStationAddress(wanted.url).base !== active) return switchTo(wanted); - } - - const { state } = await TrackPlayer.getPlaybackState().catch(() => ({ state: State.None })); - if (ON_AIR.has(state)) return { ok: true }; - - // Warm: the same reload a lock-screen Play does (service.ts). - const meta = getLastLiveMeta(); - if (meta) return startAndWait(() => loadAndPlay(meta), null); - - // Cold, or after an in-app stop: rebuild the stream from the stored - // station, as StationContext does at boot. Always the MP3 mount: a stored - // format preference is only honoured once the station's feed confirms the - // mount, and usePlayer retunes onto it when the feed loads. - const station = await activeStation(); - if (!station) return { ok: false, message: NO_STATION_MESSAGE }; - const { api } = station; - return startAndWait( - () => loadAndPlay({ url: api.streamUrl('mp3'), headers: api.streamHeaders() }), - station.name, - ); -} - -/** Another saved station. The store is written and the old stream stopped - * first, and StationContext is told only once the new stream is loaded: by - * the time the screens' base changes, the stream playing belongs to it, so - * usePlayer keeps it instead of stopping a stale one. */ -async function switchTo(ref: StoredStationRef): Promise { - await setActiveStation({ url: ref.url, name: ref.name }); - await teardown(); - const station = await activeStation(); - if (!station) return { ok: false, message: NO_STATION_MESSAGE }; - const { api } = station; - return startAndWait(async () => { - try { - await loadAndPlay({ url: api.streamUrl('mp3'), headers: api.streamHeaders() }); - } finally { - // The station switched even if its stream did not start. - announceStationStoreChanged(); - } - }, station.name); +export function tuneIn(stationId: string | undefined, deadline: number): Promise { + return flow.tuneIn(deps, stationId, deadline); } -export async function tuneOut(): Promise { - await externalTuneOut().catch(() => {}); - return { ok: true }; +export function tuneOut(): Promise { + return flow.tuneOut(deps); } -async function startAndWait( - start: () => Promise, - stationName: string | null, -): Promise { +async function startAndWait(start: () => Promise, deadline: number): Promise { + // The card's wait comes out of the budget first; the rest is for audio. + const startWait = Math.min(START_WAIT_MS, timeLeft(deadline, Date.now()) - CARD_WAIT_MS); // Listen before starting so a fast Playing, or a fast card, is not missed. - const outcome = untilPlaying(); + const outcome = untilPlaying(Math.max(0, startWait)); const card = untilCardStarts(); try { await start(); } catch { outcome.cancel(); card.cancel(); - return failed(stationName); + return false; } if (!(await outcome.result)) { card.cancel(); - return failed(stationName); + return false; } - await card.result; - return { ok: true }; + await Promise.race([card.result, wait(timeLeft(deadline, Date.now()))]); + card.cancel(); + return true; } -/** Settles on the next Live Activity start attempt, whatever its outcome, - * or at the cap. Immediately where there is no card to wait for. */ -function untilCardStarts(): { result: Promise; cancel: () => void } { - if (!isLiveActivitySupported()) return { result: Promise.resolve(), cancel: () => {} }; - let settle: () => void = () => {}; - const result = new Promise((resolve) => { +function wait(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Settles once: on `done(value)`, or with `onTimeout` at the cap. `listen` + * subscribes and returns the unsubscribe, run on settling. */ +function settleOnce( + timeoutMs: number, + onTimeout: T, + listen: (done: (value: T) => void) => () => void, +): { result: Promise; cancel: (value: T) => void } { + let settle: (value: T) => void = () => {}; + const result = new Promise((resolve) => { settle = resolve; }); - const unsubscribe = onLiveActivityStart(() => done()); - const timer = setTimeout(done, CARD_WAIT_MS); let finished = false; - function done() { + let unsubscribe: () => void = () => {}; + const done = (value: T) => { if (finished) return; finished = true; clearTimeout(timer); unsubscribe(); - settle(); - } + settle(value); + }; + const timer = setTimeout(() => done(onTimeout), timeoutMs); + unsubscribe = listen(done); + if (finished) unsubscribe(); return { result, cancel: done }; } -function failed(stationName: string | null): IntentReply { - const station = stationName ?? 'the station'; - return { - ok: false, - message: `Couldn't reach ${station}. If it's private, open SUB/WAVE to unlock it.`, - }; +/** Settles on the next Live Activity start attempt, whatever its outcome, + * or at the cap. Immediately where there is no card to wait for. */ +function untilCardStarts(): { result: Promise; cancel: () => void } { + if (!isLiveActivitySupported()) return { result: Promise.resolve(), cancel: () => {} }; + const s = settleOnce(CARD_WAIT_MS, undefined, (done) => onLiveActivityStart(() => done())); + return { result: s.result, cancel: () => s.cancel() }; } /** True on Playing; false on an error. Still buffering when the wait runs out * counts as started: the player keeps trying, and usePlayer's watchdog takes * over once a screen mounts. */ -function untilPlaying(): { result: Promise; cancel: () => void } { - let settle: (ok: boolean) => void = () => {}; - const result = new Promise((resolve) => { - settle = resolve; +function untilPlaying(timeoutMs: number): { result: Promise; cancel: () => void } { + const s = settleOnce(timeoutMs, true, (done) => { + const subs = [ + TrackPlayer.addEventListener(Event.PlaybackState, ({ state }) => { + if (state === State.Playing) done(true); + else if (state === State.Error) done(false); + }), + TrackPlayer.addEventListener(Event.PlaybackError, () => done(false)), + ]; + return () => subs.forEach((sub) => sub.remove()); }); - const subs = [ - TrackPlayer.addEventListener(Event.PlaybackState, ({ state }) => { - if (state === State.Playing) done(true); - else if (state === State.Error) done(false); - }), - TrackPlayer.addEventListener(Event.PlaybackError, () => done(false)), - ]; - const timer = setTimeout(() => done(true), START_WAIT_MS); - let finished = false; - function done(ok: boolean) { - if (finished) return; - finished = true; - clearTimeout(timer); - subs.forEach((s) => s.remove()); - settle(ok); - } - return { result, cancel: () => done(false) }; + return { result: s.result, cancel: () => s.cancel(false) }; } diff --git a/src/lib/remote-play.ts b/src/lib/remote-play.ts index 6c5ad51..4636f24 100644 --- a/src/lib/remote-play.ts +++ b/src/lib/remote-play.ts @@ -3,6 +3,8 @@ // 4.1.2's Android service runs it as a headless task in the app's React // context. On Android it can also run with no player mounted. +import { splitStationAddress } from './station-credentials'; + /** Takes a remote Play; returns false to leave it to the service. */ export type RemotePlayHandler = () => boolean; @@ -41,3 +43,60 @@ export async function remotePlay(deps: RemotePlayDeps): Promise { } catch {} await deps.resume().catch(() => {}); } + +// App Intents (src/intents/tune.ts) hand their tune-ins over the same claim, +// so a mounted player loads every stream through StreamRecovery (CLAUDE.md). + +/** Whether a player is mounted to take a tune-in. */ +export function playerMounted(): boolean { + return handler !== null; +} + +/** An App Intent's tune-in on the current station, through the mounted player. + * False when none is mounted or it has no station: the intent loads itself. */ +export function playOnMountedPlayer(): boolean { + return handler?.() ?? false; +} + +// A station switch from an App Intent while the player is mounted. The intent +// writes the store and arms this; StationContext hands the player the new +// station's client, and the player, seeing its base change, takes the tune-in +// in place of the stop a station switch makes. +let arrival: { base: string; settle: (taken: boolean) => void } | null = null; + +export interface Arrival { + /** True once the player took the tune-in; false on cancel or at the cap. */ + taken: Promise; + cancel(): void; +} + +/** Arm a tune-in for when the player reaches `base`. One at a time: a newer + * switch replaces an older one, which then reads as not taken. */ +export function tuneInOnArrival(base: string, timeoutMs: number): Arrival { + arrival?.settle(false); + const wanted = splitStationAddress(base).base; + let settle: (taken: boolean) => void = () => {}; + const taken = new Promise((resolve) => { + settle = resolve; + }); + const timer = setTimeout(() => entry.settle(false), timeoutMs); + const entry = { + base: wanted, + settle: (ok: boolean) => { + clearTimeout(timer); + if (arrival === entry) arrival = null; + settle(ok); + }, + }; + arrival = entry; + return { taken, cancel: () => entry.settle(false) }; +} + +/** The player reached `base`: true, once, when an App Intent asked to tune + * in there. */ +export function takeArrival(base: string): boolean { + const pending = arrival; + if (!pending || pending.base !== splitStationAddress(base).base) return false; + pending.settle(true); + return true; +} From e72d869db97e49dd9cbdef7040778209b833a562 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 15:10:04 +0000 Subject: [PATCH 4/7] fix(app): fit every intent answer inside the bridge's reply window The bridge gives up on JS 20 s after an intent starts, up to 10 s of it spent on a cold boot, while a song request could spend 16 s on its POST and 10 s more polling: Siri said the app didn't respond for a request the station took, and the listener asked again. The bridge now sends its deadline with each request and the module passes it to JS, which keeps a margin for the reply (deadline.ts). The song request races its POST and each poll against it and stops polling an interval early; a POST still out at the deadline is said as sent, since an error would queue it twice. The tune-in's waits were cut to it in the previous commit. Also: intent actions are an enum on the Swift side and a union in JS, and the module's dedupe set keeps only the last 32 tokens. --- docs/TESTING.md | 4 +- .../ios/SubwaveAppIntentsModule.swift | 14 +++++-- scripts/intent-request.test.ts | 26 +++++++++++++ src/intents/handlers.ts | 2 +- src/intents/request-reply.ts | 38 ++++++++++++++++--- .../_shared/AudioSchemaIntents.swift | 2 +- .../live-activity/_shared/OnAirIntents.swift | 4 +- .../_shared/RequestSongIntent.swift | 2 +- .../_shared/StationEntities.swift | 2 +- .../_shared/SubwaveIntentBridge.swift | 21 +++++++++- .../_shared/ToggleTuneIntent.swift | 2 +- .../live-activity/_shared/TuneIntents.swift | 4 +- 12 files changed, 99 insertions(+), 22 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index f23909b..c86260c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -355,7 +355,9 @@ a toggle for Control Center, the Lock Screen and the Action button, driven by `ToggleTuneIntent` through the same bridge. **Request a song** ("Request a song on SUB/WAVE") has Siri ask what to play, sends it through the request drawer's own `POST /request` and polling, and reads back the DJ's answer. It waits up to -10 s for the match, then says the request is in. **What's playing** and **Like +10 s for the match, less when the bridge's deadline is nearer, then says the +request is in; a POST still unanswered at the deadline is said as sent too, +since "try again" would queue it twice. **What's playing** and **Like this song** both mean the track the listener is hearing: while the app is playing, that is the previous track for the stream buffer's length after a change (`src/lib/heard-track.ts`, the rule `useStationFeed` promotes tracks by). diff --git a/modules/app-intents/ios/SubwaveAppIntentsModule.swift b/modules/app-intents/ios/SubwaveAppIntentsModule.swift index d82edfc..c816dad 100644 --- a/modules/app-intents/ios/SubwaveAppIntentsModule.swift +++ b/modules/app-intents/ios/SubwaveAppIntentsModule.swift @@ -43,8 +43,10 @@ public class SubwaveAppIntentsModule: Module { private var listening = false private var pending: [[String: Any]] = [] /// Tokens already taken in. The intent re-posts until it sees an ack, so a - /// request can arrive more than once. - private var seen = Set() + /// request can arrive more than once; only the latest few can still be + /// re-posting, so older ones are dropped. + private var seen: [String] = [] + private let seenCap = 32 public func definition() -> ModuleDefinition { Name("SubwaveAppIntents") @@ -121,9 +123,13 @@ public class SubwaveAppIntentsModule: Module { let action = info?["action"] as? String else { return } NotificationCenter.default.post(name: ackName, object: nil, userInfo: ["token": token]) - guard seen.insert(token).inserted else { return } + guard !seen.contains(token) else { return } + seen.append(token) + if seen.count > seenCap { seen.removeFirst(seen.count - seenCap) } let args = info?["args"] as? [String: String] ?? [:] - let request: [String: Any] = ["token": token, "action": action, "args": args] + var request: [String: Any] = ["token": token, "action": action, "args": args] + // When the intent stops waiting, in epoch ms (src/intents/deadline.ts). + if let deadline = info?["deadline"] as? Double { request["deadline"] = deadline } if listening { sendEvent("onIntent", request) } else { diff --git a/scripts/intent-request.test.ts b/scripts/intent-request.test.ts index fe05e16..c9ad1e2 100644 --- a/scripts/intent-request.test.ts +++ b/scripts/intent-request.test.ts @@ -8,6 +8,7 @@ import { ACCEPTED_MESSAGE, askForSong, REQUEST_WAIT_MS, + SLOW_MESSAGE, spokenAnswer, } from '../src/intents/request-reply.ts'; import type { RequestResult } from '../src/lib/types.ts'; @@ -115,3 +116,28 @@ test('an empty request never reaches the station', async () => { assert.equal(reply.ok, false); assert.deepEqual(s.sent, []); }); + +test('a POST still unanswered at the deadline is said as sent, not as a failure', async () => { + // Siri saying "try again" would send it twice. + const s = station(accepted); + s.deps.api.postRequest = () => new Promise(() => {}); + const reply = await askForSong('anything', { ...s.deps, deadline: 5000, timer: async () => {} }); + assert.deepEqual(reply, { ok: true, message: SLOW_MESSAGE }); + assert.equal(s.pollCount, 0); +}); + +test('polling stops an interval before the deadline, well inside the cap', async () => { + const s = station(accepted, [{ success: false, status: 'pending' }]); + const never = () => new Promise(() => {}); + const reply = await askForSong('something slow', { ...s.deps, deadline: 4000, timer: never }); + assert.deepEqual(reply, { ok: true, message: ACCEPTED_MESSAGE }); + // 1.5 s apart, stopping at 4000 - 1500: polls at 1500 and 3000, none after. + assert.equal(s.pollCount, 2); +}); + +test('a poll still out at the deadline ends the wait with the request in', async () => { + const s = station(accepted); + s.deps.api.pollRequest = () => new Promise(() => {}); + const reply = await askForSong('anything', { ...s.deps, deadline: 9000, timer: async () => {} }); + assert.deepEqual(reply, { ok: true, message: ACCEPTED_MESSAGE }); +}); diff --git a/src/intents/handlers.ts b/src/intents/handlers.ts index 9414c15..c827fc3 100644 --- a/src/intents/handlers.ts +++ b/src/intents/handlers.ts @@ -23,7 +23,7 @@ export function registerIntentHandlers(): void { case 'like': { const station = await activeStation(); if (!station) return { ok: false, message: NO_STATION_MESSAGE }; - if (action === 'request') return askForSong(args.text ?? '', { api: station.api }); + if (action === 'request') return askForSong(args.text ?? '', { api: station.api, deadline }); if (action === 'nowPlaying') return whatsPlaying(station); return likeHeardTrack(station); } diff --git a/src/intents/request-reply.ts b/src/intents/request-reply.ts index 6e40f76..7d93938 100644 --- a/src/intents/request-reply.ts +++ b/src/intents/request-reply.ts @@ -6,6 +6,7 @@ import type { IntentReply } from '../../modules/app-intents'; import type { StationApi } from '../lib/api'; import { requestResultLabel } from '../lib/request-outcome'; +import { timeLeft, TIMED_OUT, within } from './deadline'; import type { RequestResult } from '../lib/types'; // How long Siri is kept waiting for the DJ to match the request. Matching is @@ -18,27 +19,46 @@ const POLL_INTERVAL_MS = 1500; // The drawer's own line for a request still being matched. export const ACCEPTED_MESSAGE = 'Got it — taking it to the booth.'; +// Said when the station hasn't answered the POST by the deadline. It may well +// have taken the request, so this is no error: Siri saying "try again" would +// send it twice. +export const SLOW_MESSAGE = "Sent. The station's slow to answer, so it may take a moment."; + export interface AskForSongDeps { api: Pick; sleep?: (ms: number) => Promise; + /** The timer the deadline races the station's answers against; apart from + * `sleep` so a test's clock moves only on the polling interval. */ + timer?: (ms: number) => Promise; now?: () => number; waitMs?: number; + /** Epoch ms by which Siri must have its answer (src/intents/deadline.ts). + * Every wait, the POST and each poll included, is cut to it. */ + deadline?: number; } export async function askForSong(text: string, deps: AskForSongDeps): Promise { const asked = text.trim(); if (!asked) return { ok: false, message: 'Tell me a song, an artist or a mood.' }; - const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + const realSleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + const sleep = deps.sleep ?? realSleep; + const timer = deps.timer ?? realSleep; const now = deps.now ?? Date.now; // A refusal is answered in the station's words: requests closed, nobody // tuned in, a rate limit, a full queue. A 400 carries `error`, not `message`. - let posted: RequestResult & { error?: string }; + const end = deps.deadline ?? Number.POSITIVE_INFINITY; + const untilEnd = () => timer(timeLeft(end, now())); + + let posted: (RequestResult & { error?: string }) | typeof TIMED_OUT; try { - posted = await deps.api.postRequest({ text: asked }); + posted = Number.isFinite(end) + ? await within(deps.api.postRequest({ text: asked }), untilEnd()) + : await deps.api.postRequest({ text: asked }); } catch { return { ok: false, message: "Couldn't reach the station. Check your connection and try again." }; } + if (posted === TIMED_OUT) return { ok: true, message: SLOW_MESSAGE }; if (!posted.success) { return { ok: false, @@ -47,12 +67,18 @@ export async function askForSong(text: string, deps: AskForSongDeps): Promise some IntentResult & ProvidesDialog & ReturnsValue { - let answer = try await SubwaveIntentBridge.perform("nowPlaying") ?? "" + let answer = try await SubwaveIntentBridge.perform(.nowPlaying) ?? "" return .result(value: answer, dialog: IntentDialog(stringLiteral: answer)) } } @@ -35,7 +35,7 @@ struct LikeSongIntent: AppIntent { static var openAppWhenRun: Bool = false func perform() async throws -> some IntentResult & ProvidesDialog { - let answer = try await SubwaveIntentBridge.perform("like") ?? "Liked." + let answer = try await SubwaveIntentBridge.perform(.like) ?? "Liked." return .result(dialog: IntentDialog(stringLiteral: answer)) } } diff --git a/targets/live-activity/_shared/RequestSongIntent.swift b/targets/live-activity/_shared/RequestSongIntent.swift index 6efe82e..4431251 100644 --- a/targets/live-activity/_shared/RequestSongIntent.swift +++ b/targets/live-activity/_shared/RequestSongIntent.swift @@ -29,7 +29,7 @@ struct RequestSongIntent: AppIntent { var request: String func perform() async throws -> some IntentResult & ProvidesDialog { - let answer = try await SubwaveIntentBridge.perform("request", ["text": request]) + let answer = try await SubwaveIntentBridge.perform(.request, ["text": request]) return .result(dialog: IntentDialog(stringLiteral: answer ?? "Sent to the DJ.")) } } diff --git a/targets/live-activity/_shared/StationEntities.swift b/targets/live-activity/_shared/StationEntities.swift index aa5d023..f98938e 100644 --- a/targets/live-activity/_shared/StationEntities.swift +++ b/targets/live-activity/_shared/StationEntities.swift @@ -113,7 +113,7 @@ struct OpenStationIntent: OpenIntent { var target: StationEntity func perform() async throws -> some IntentResult { - try await SubwaveIntentBridge.perform("tuneIn", ["station": target.id]) + try await SubwaveIntentBridge.perform(.tuneIn, ["station": target.id]) return .result() } } diff --git a/targets/live-activity/_shared/SubwaveIntentBridge.swift b/targets/live-activity/_shared/SubwaveIntentBridge.swift index e220fdd..1a3e6a2 100644 --- a/targets/live-activity/_shared/SubwaveIntentBridge.swift +++ b/targets/live-activity/_shared/SubwaveIntentBridge.swift @@ -12,6 +12,16 @@ import Foundation // widget extension nothing is listening and `perform` fails after the ack // window. +/// 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. +enum SubwaveIntentAction: String { + case tuneIn + case tuneOut + case request + case nowPlaying + case like +} + @available(iOS 17.0, *) enum SubwaveIntentBridge { private static let requestName = Notification.Name("SubwaveIntentRequest") @@ -29,7 +39,9 @@ enum SubwaveIntentBridge { /// any; throws the message JS gave for a failure, or a generic one when the /// app never answered. @discardableResult - static func perform(_ action: String, _ args: [String: String] = [:]) async throws -> String? { + static func perform( + _ action: SubwaveIntentAction, _ args: [String: String] = [:] + ) async throws -> String? { let token = UUID().uuidString let box = ReplyBox() let center = NotificationCenter.default @@ -48,6 +60,9 @@ enum SubwaveIntentBridge { } let started = Date() + // Sent with the request so JS cuts its waits to fit (src/intents/deadline.ts): + // an answer after this is never heard, and Siri says the app didn't respond. + let deadline = started.addingTimeInterval(replyWindow).timeIntervalSince1970 * 1000 while true { if let reply = box.reply { guard reply.ok else { throw SubwaveIntentError(reply.message) } @@ -60,7 +75,9 @@ enum SubwaveIntentBridge { if !box.acked { center.post( name: requestName, object: nil, - userInfo: ["token": token, "action": action, "args": args]) + userInfo: [ + "token": token, "action": action.rawValue, "args": args, "deadline": deadline, + ]) } try await Task.sleep(nanoseconds: 200_000_000) } diff --git a/targets/live-activity/_shared/ToggleTuneIntent.swift b/targets/live-activity/_shared/ToggleTuneIntent.swift index c8bf96a..c52bd17 100644 --- a/targets/live-activity/_shared/ToggleTuneIntent.swift +++ b/targets/live-activity/_shared/ToggleTuneIntent.swift @@ -25,7 +25,7 @@ struct ToggleTuneIntent: SetValueIntent, AudioPlaybackIntent, LiveActivityIntent } func perform() async throws -> some IntentResult { - try await SubwaveIntentBridge.perform(value ? "tuneIn" : "tuneOut") + try await SubwaveIntentBridge.perform(value ? .tuneIn : .tuneOut) return .result() } } diff --git a/targets/live-activity/_shared/TuneIntents.swift b/targets/live-activity/_shared/TuneIntents.swift index 203bfde..2a3223b 100644 --- a/targets/live-activity/_shared/TuneIntents.swift +++ b/targets/live-activity/_shared/TuneIntents.swift @@ -34,7 +34,7 @@ struct TuneInIntent: AudioPlaybackIntent, LiveActivityIntent { var station: StationEntity? func perform() async throws -> some IntentResult { - try await SubwaveIntentBridge.perform("tuneIn", station.map { ["station": $0.id] } ?? [:]) + try await SubwaveIntentBridge.perform(.tuneIn, station.map { ["station": $0.id] } ?? [:]) return .result() } } @@ -46,7 +46,7 @@ struct TuneOutIntent: AudioPlaybackIntent { static var openAppWhenRun: Bool = false func perform() async throws -> some IntentResult { - try await SubwaveIntentBridge.perform("tuneOut") + try await SubwaveIntentBridge.perform(.tuneOut) return .result() } } From 116659df76a427091f07c52a11ed5319cf824c58 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 15:11:29 +0000 Subject: [PATCH 5/7] fix(app): measure "what's playing" from the trimmed lead After an idle skip the listener is nearer the live edge by what it shed, up to about 17 s on a 22 s buffer, but heardTrack measured "what's playing" and "like this song" from the whole buffer and named the previous song for that long. usePlayer now writes the trim to heard-track.ts beside PlayerScreen's leadTrimMs, loadAndPlay clears it, and on-air.ts and useStationFeed both take the lead from listenerLeadMs. --- docs/TESTING.md | 3 ++- scripts/intent-on-air.test.ts | 31 ++++++++++++++++++++++++++++++- src/audio/player.ts | 3 +++ src/hooks/usePlayer.ts | 14 ++++++++++---- src/hooks/useStationFeed.ts | 6 +++--- src/intents/on-air.ts | 4 ++-- src/lib/heard-track.ts | 23 ++++++++++++++++++++++- 7 files changed, 72 insertions(+), 12 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index c86260c..757fbbc 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -360,7 +360,8 @@ request is in; a POST still unanswered at the deadline is said as sent too, since "try again" would queue it twice. **What's playing** and **Like this song** both mean the track the listener is hearing: while the app is playing, that is the previous track for the stream buffer's length after a -change (`src/lib/heard-track.ts`, the rule `useStationFeed` promotes tracks by). +change, less whatever the idle skip shed (`src/lib/heard-track.ts`, the rule +`useStationFeed` promotes tracks by). The like goes through `POST /like`, which refuses a song that has ended, and the in-app heart and the Live Activity fill straight away (`like-events.ts`). The Live Activity's own heart is `LikeTrackIntent`, hidden from Shortcuts so diff --git a/scripts/intent-on-air.test.ts b/scripts/intent-on-air.test.ts index d98496f..1765e50 100644 --- a/scripts/intent-on-air.test.ts +++ b/scripts/intent-on-air.test.ts @@ -5,7 +5,14 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { audibleAt, heardTrack, leadMsFrom } from '../src/lib/heard-track.ts'; +import { + audibleAt, + heardTrack, + leadMsFrom, + leadTrimMs, + listenerLeadMs, + setLeadTrimMs, +} from '../src/lib/heard-track.ts'; import { likeReply, likeTarget, @@ -37,6 +44,28 @@ test('with no live-edge stamp, or nothing before it, the live track is the answe assert.equal(heardTrack({ live, previous: null, liveStartMs: 100_000, leadMs: 22_000, now: 110_000 }), live); }); +test('after an idle skip the listener is nearer the live edge by what it shed', () => { + // A 22 s buffer with 17 s of a woken station's silence played fast: the new + // track reaches the listener 5 s after the live edge, not 22. + const leadMs = listenerLeadMs(22_000, 17_000); + assert.equal(leadMs, 5_000); + const at = (now: number) => heardTrack({ live, previous, liveStartMs: 100_000, leadMs, now }); + assert.equal(at(104_999), previous); + assert.equal(at(105_000), live); + // Never ahead of the live edge, and a bad trim sheds nothing. + assert.equal(listenerLeadMs(5_000, 9_000), 0); + assert.equal(listenerLeadMs(22_000, -1), 22_000); +}); + +test('the trim the intents read follows the player, and a bad value reads as none', () => { + setLeadTrimMs(12_000); + assert.equal(leadTrimMs(), 12_000); + setLeadTrimMs(Number.NaN); + assert.equal(leadTrimMs(), 0); + setLeadTrimMs(-3); + assert.equal(leadTrimMs(), 0); +}); + const snap = (over: Partial = {}): OnAirSnapshot => ({ reachable: true, online: true, diff --git a/src/audio/player.ts b/src/audio/player.ts index a604b4f..d0b022c 100644 --- a/src/audio/player.ts +++ b/src/audio/player.ts @@ -7,6 +7,7 @@ import TrackPlayer, { State, } from 'react-native-track-player'; import { createAnnouncer } from '@/lib/announcer'; +import { setLeadTrimMs } from '@/lib/heard-track'; import { playbackLog } from '@/lib/playback-log'; const STREAM_TRACK_ID = 'subwave-live'; @@ -76,6 +77,8 @@ export async function loadAndPlay(meta: LiveTrackMeta): Promise { // RNTP carries the rate over to the next item; an idle skip's 8x must never // reach a new connection's music (src/lib/idle-skip-playback.ts). await TrackPlayer.setRate(1).catch(() => {}); + // A new connection carries its whole buffer again. + setLeadTrimMs(0); const bust = `${meta.url}${meta.url.includes('?') ? '&' : '?'}t=${Date.now()}`; await TrackPlayer.load({ id: STREAM_TRACK_ID, diff --git a/src/hooks/usePlayer.ts b/src/hooks/usePlayer.ts index 6a40bf0..617e9dd 100644 --- a/src/hooks/usePlayer.ts +++ b/src/hooks/usePlayer.ts @@ -20,6 +20,7 @@ import { teardown, } from '@/audio/player'; import type { StationApi } from '@/lib/api'; +import { setLeadTrimMs } from '@/lib/heard-track'; import { SKIP_CUSHION_SECONDS } from '@/lib/idle-skip'; import { IdleSkip } from '@/lib/idle-skip-playback'; import { playbackEventLine, playbackLog } from '@/lib/playback-log'; @@ -81,11 +82,16 @@ export function usePlayer( useEffect(() => { bufferSecondsRef.current = idle.bufferSeconds; }, [idle.bufferSeconds]); useEffect(() => { onLeadTrimRef.current = idle.onLeadTrim; }, [idle.onLeadTrim]); const idleSkipRef = useRef(null); + // To the feed, and to the App Intents, which have no screen to ask. + const reportTrim = useCallback((ms: number) => { + setLeadTrimMs(ms); + onLeadTrimRef.current?.(ms); + }, []); const endIdleSkip = useCallback(() => { idleSkipRef.current?.cancel(); idleSkipRef.current = null; - onLeadTrimRef.current?.(0); - }, []); + reportTrim(0); + }, [reportTrim]); // MP3 only: its burst is CBR, so bufferSeconds sizes it. An older broadcast // image's Opus burst is VBR and reaches back past the pause into music. const startIdleSkip = useCallback((a: StationApi): IdleSkip | null => { @@ -98,12 +104,12 @@ export function usePlayer( readState: (signal) => a.state(signal), position: () => TrackPlayer.getProgress().then((p) => p.position), setRate: (rate) => TrackPlayer.setRate(rate), - onTrim: (ms) => onLeadTrimRef.current?.(ms), + onTrim: reportTrim, log: plog, }); idleSkipRef.current = skip; return skip; - }, [endIdleSkip]); + }, [endIdleSkip, reportTrim]); useEffect(() => { const sub = AppState.addEventListener('change', (s) => { diff --git a/src/hooks/useStationFeed.ts b/src/hooks/useStationFeed.ts index 9ea9969..e4dab05 100644 --- a/src/hooks/useStationFeed.ts +++ b/src/hooks/useStationFeed.ts @@ -4,7 +4,7 @@ import type { StationApi } from '@/lib/api'; import { feedState } from '@/lib/feed-state'; import { pollAsync } from '@/lib/poll'; import { DEFAULT_STATION_LOCALE, type StationLocale } from '@/lib/format'; -import { audibleAt as audibleAtLiveEdge, leadMsFrom } from '@/lib/heard-track'; +import { audibleAt as audibleAtLiveEdge, leadMsFrom, listenerLeadMs } from '@/lib/heard-track'; import { splitAudibleTurns } from '@/lib/sessionFeed'; import { trackElapsedSeconds } from '@/lib/track-progress'; import type { @@ -140,7 +140,7 @@ export function useStationFeed( useEffect(() => { if (leadTrimMs === trimMsRef.current) return; trimMsRef.current = leadTrimMs; - const next = Math.max(0, bufferMsRef.current - leadTrimMs); + const next = listenerLeadMs(bufferMsRef.current, leadTrimMs); const delta = next - leadMsRef.current; leadMsRef.current = next; setLeadMs(next); @@ -164,7 +164,7 @@ export function useStationFeed( const buf = leadMsFrom(npRes.stream?.bufferSeconds); if (buf != null) { bufferMsRef.current = buf; - leadMsRef.current = Math.max(0, buf - trimMsRef.current); + leadMsRef.current = listenerLeadMs(buf, trimMsRef.current); setLeadMs(leadMsRef.current); } const trackKey = np ? `${np.title}\0${np.artist}` : null; diff --git a/src/intents/on-air.ts b/src/intents/on-air.ts index d9e0219..dfa2518 100644 --- a/src/intents/on-air.ts +++ b/src/intents/on-air.ts @@ -5,7 +5,7 @@ import type { IntentReply } from '../../modules/app-intents'; import { isOnAir, playbackStateNow } from '@/audio/player'; -import { heardTrack, leadMsFrom } from '@/lib/heard-track'; +import { heardTrack, leadMsFrom, leadTrimMs, listenerLeadMs } from '@/lib/heard-track'; import { announceLike } from '@/lib/like-events'; import type { StationApi } from '@/lib/api'; import { @@ -36,7 +36,7 @@ async function snapshot(api: StationApi): Promise { live, previous: stateRes.value.history?.[0] ?? null, liveStartMs: Number.isFinite(stamp) ? stamp : null, - leadMs: leadMsFrom(np.stream?.bufferSeconds) ?? 0, + leadMs: listenerLeadMs(leadMsFrom(np.stream?.bufferSeconds) ?? 0, leadTrimMs()), now: Date.now(), }); return { reachable: true, online, track }; diff --git a/src/lib/heard-track.ts b/src/lib/heard-track.ts index 60b99b6..82fc043 100644 --- a/src/lib/heard-track.ts +++ b/src/lib/heard-track.ts @@ -3,7 +3,8 @@ // long after a change they still hear the previous track. useStationFeed // promotes a new track at audibleAt(); the App Intents (src/intents/on-air.ts) // answer "what's playing" and "like this song" with heardTrack(), which reads -// the same rule from one /now-playing + /state snapshot. +// the same rule from one /now-playing + /state snapshot. Both measure from the +// buffer less the idle skip's trim (listenerLeadMs). import { MAX_LEAD_SECONDS } from './sessionFeed'; @@ -14,6 +15,26 @@ export function leadMsFrom(bufferSeconds: number | null | undefined): number | n return Math.min(Math.max(bufferSeconds, 0), MAX_LEAD_SECONDS) * 1000; } +/** How far behind the live edge the listener is: the buffer, less what the + * idle skip shed from this connection by playing its silence fast. */ +export function listenerLeadMs(bufferMs: number, trimMs: number): number { + return Math.max(0, bufferMs - Math.max(0, trimMs)); +} + +// What the idle skip shed from the connection playing now. usePlayer writes it +// beside PlayerScreen's leadTrimMs, and loadAndPlay clears it, so an App +// Intent with no screen to ask (src/intents/on-air.ts) measures from the same +// point the feed does. +let currentTrimMs = 0; + +export function setLeadTrimMs(ms: number): void { + currentTrimMs = Number.isFinite(ms) ? Math.max(0, ms) : 0; +} + +export function leadTrimMs(): number { + return currentTrimMs; +} + /** When a track that started at the live edge at `liveStartMs` reaches the * listener. */ export function audibleAt(liveStartMs: number, leadMs: number): number { From 51255de32116346a8853c6aca587129e7c0fd073 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 15:30:35 +0000 Subject: [PATCH 6/7] fix(app): cut "like this song" to the bridge's deadline The like intent ignored the deadline: its /now-playing and /state reads and POST /like could each run 16 s, past the bridge's window, so Siri said the app didn't respond. likeHeard (on-air-reply.ts, pure and tested) races both steps against the deadline and aborts the reads there. A station too slow to say what's on gets no like. A like still unanswered at the deadline is a failure that asks for a repeat, unlike the song request: a repeat like counts once (alreadyLiked), where saying "liked" for one that never landed would lose it. --- docs/TESTING.md | 4 +- scripts/intent-on-air.test.ts | 70 +++++++++++++++++++++++++++++++++++ src/intents/handlers.ts | 2 +- src/intents/on-air-reply.ts | 58 +++++++++++++++++++++++++++++ src/intents/on-air.ts | 25 ++++++------- 5 files changed, 143 insertions(+), 16 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 757fbbc..45eb49e 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -427,7 +427,9 @@ What is easy to get wrong: didn't respond for work that went through, and the listener asks again. The bridge sends its deadline with each request and JS cuts every wait to it (`src/intents/deadline.ts`): the tune-in's wait for audio and the card, the - song request's POST and polling. + song request's POST and polling, the like's reads and `POST /like`. A request + still out at the deadline is said as sent, since a repeat queues it twice; a + like is said as unconfirmed, since a repeat counts once. - **ActivityKit refuses a background app.** `liveactivitiesd` logs "Requester is not foreground" and the card never appears, though the audio plays. Inside a `LiveActivityIntent`'s run the request is allowed, which is why diff --git a/scripts/intent-on-air.test.ts b/scripts/intent-on-air.test.ts index 1765e50..15030b8 100644 --- a/scripts/intent-on-air.test.ts +++ b/scripts/intent-on-air.test.ts @@ -14,8 +14,11 @@ import { setLeadTrimMs, } from '../src/lib/heard-track.ts'; import { + likeHeard, likeReply, likeTarget, + likeUnconfirmedReply, + slowReply, whatsPlayingReply, type OnAirSnapshot, } from '../src/intents/on-air-reply.ts'; @@ -119,3 +122,70 @@ test('POST /like’s answer is said back, refusals in the station’s own words' assert.equal(likeReply('SUB/WAVE', live, {}).ok, false); assert.equal(likeReply('SUB/WAVE', live, null).ok, false); }); + +/** A like against a station whose reads answer `snapshot` and whose POST + * /like answers `liked`; `null` for either never answers. The deadline's + * timer fires at once only when `late`. */ +function liking(o: { + snapshot?: OnAirSnapshot | null; + liked?: Parameters[2] | 'never'; + late?: boolean; +}) { + const calls: string[] = []; + const signals: AbortSignal[] = []; + const announced: string[] = []; + return { + calls, + signals, + announced, + run: () => + likeHeard({ + station: 'SUB/WAVE', + snapshot: (signal) => { + signals.push(signal); + const s = o.snapshot === undefined ? snap() : o.snapshot; + return s ? Promise.resolve(s) : new Promise(() => {}); + }, + like: (songId) => { + calls.push(songId); + return o.liked === 'never' + ? new Promise(() => {}) + : Promise.resolve(o.liked === undefined ? { ok: true, count: 3 } : o.liked); + }, + announce: (like) => announced.push(like.songId), + deadline: 10_000, + now: () => 0, + timer: () => (o.late ? Promise.resolve() : new Promise(() => {})), + }), + }; +} + +test('a like in time is liked, and the heart follows', async () => { + const l = liking({}); + assert.deepEqual(await l.run(), { ok: true, message: 'Liked Teardrop by Massive Attack.' }); + assert.deepEqual(l.calls, ['tear']); + assert.deepEqual(l.announced, ['tear']); +}); + +test('a station too slow to say what’s on gets no like, and its reads are stopped', async () => { + const l = liking({ snapshot: null, late: true }); + assert.deepEqual(await l.run(), slowReply('SUB/WAVE')); + assert.deepEqual(l.calls, []); + assert.equal(l.signals[0]?.aborted, true); +}); + +test('a like still unanswered at the deadline is a failure, to be asked again', async () => { + // A repeat like counts once (alreadyLiked), so "ask again" is safe; saying + // "liked" for one that never landed would lose it. + const l = liking({ liked: 'never', late: true }); + const reply = await l.run(); + assert.deepEqual(reply, likeUnconfirmedReply('SUB/WAVE')); + assert.equal(reply.ok, false); + assert.deepEqual(l.announced, []); +}); + +test('a refused like is said in the station’s words, and the heart stays as it was', async () => { + const l = liking({ liked: { ok: false, error: 'Likes are off' } }); + assert.deepEqual(await l.run(), { ok: false, message: 'Likes are off.' }); + assert.deepEqual(l.announced, []); +}); diff --git a/src/intents/handlers.ts b/src/intents/handlers.ts index c827fc3..b9a607a 100644 --- a/src/intents/handlers.ts +++ b/src/intents/handlers.ts @@ -25,7 +25,7 @@ export function registerIntentHandlers(): void { if (!station) return { ok: false, message: NO_STATION_MESSAGE }; if (action === 'request') return askForSong(args.text ?? '', { api: station.api, deadline }); if (action === 'nowPlaying') return whatsPlaying(station); - return likeHeardTrack(station); + return likeHeardTrack(station, deadline); } default: return { ok: false, message: 'Update SUB/WAVE to use this.' }; diff --git a/src/intents/on-air-reply.ts b/src/intents/on-air-reply.ts index 3d7e4fe..d72ee22 100644 --- a/src/intents/on-air-reply.ts +++ b/src/intents/on-air-reply.ts @@ -4,6 +4,7 @@ import type { IntentReply } from '../../modules/app-intents'; import type { LikeResult } from '../lib/types'; +import { timeLeft, TIMED_OUT, within } from './deadline'; /** Enough of a now-playing track or a history entry to name it and like it. */ export interface OnAirTrack { @@ -61,3 +62,60 @@ export function likeReply(station: string, track: OnAirTrack, result: LikeResult if (!result.ok) return { ok: false, message: `${station} didn't take the like.` }; return { ok: true, message: `Liked ${named(track)}.` }; } + +/** Said when the station hasn't told us what's on by the deadline: nothing + * was sent, so asking again is the whole remedy. */ +export function slowReply(station: string): IntentReply { + return { ok: false, message: `${station} is slow to answer. Try again in a moment.` }; +} + +/** Said when POST /like is still out at the deadline. A failure, not "liked": + * a repeat like is harmless (the station answers alreadyLiked and counts it + * once), so the listener asking again costs nothing, while saying "liked" + * for a like that never landed would lose it for good. The song request + * answers the other way because a repeat request queues the song twice. */ +export function likeUnconfirmedReply(station: string): IntentReply { + return { + ok: false, + message: `${station} didn't confirm the like in time. Ask again: it won't count twice.`, + }; +} + +export interface LikeHeardDeps { + station: string; + /** The track the listener is hearing, read until `signal` aborts. */ + snapshot(signal: AbortSignal): Promise; + like(songId: string): Promise; + /** The in-app heart and the Live Activity follow a like that landed. */ + announce(like: { songId: string; count?: number }): void; + /** Epoch ms by which Siri must have its answer (deadline.ts). */ + deadline: number; + now?: () => number; + /** The timer the deadline races the station's answers against. */ + timer?: (ms: number) => Promise; +} + +/** "Like this song": the heard track, liked, both reads cut to the deadline. */ +export async function likeHeard(deps: LikeHeardDeps): Promise { + const now = deps.now ?? Date.now; + const timer = deps.timer ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + const untilEnd = () => timer(timeLeft(deps.deadline, now())); + + // The reads stop at the deadline too (readJson honours the signal), so + // nothing keeps fetching for an answer no one will hear. + const abort = new AbortController(); + const snap = await within(deps.snapshot(abort.signal), untilEnd()); + if (snap === TIMED_OUT) { + abort.abort(); + return slowReply(deps.station); + } + const target = likeTarget(deps.station, snap); + if (!('songId' in target)) return target; + + const result = await within(deps.like(target.songId), untilEnd()); + if (result === TIMED_OUT) return likeUnconfirmedReply(deps.station); + if (result && !result.error && (result.ok || result.alreadyLiked)) { + deps.announce({ songId: target.songId, count: result.count }); + } + return likeReply(deps.station, snap.track ?? {}, result); +} diff --git a/src/intents/on-air.ts b/src/intents/on-air.ts index dfa2518..493da2b 100644 --- a/src/intents/on-air.ts +++ b/src/intents/on-air.ts @@ -9,16 +9,15 @@ import { heardTrack, leadMsFrom, leadTrimMs, listenerLeadMs } from '@/lib/heard- import { announceLike } from '@/lib/like-events'; import type { StationApi } from '@/lib/api'; import { - likeReply, - likeTarget, + likeHeard, whatsPlayingReply, type OnAirSnapshot, type OnAirTrack, } from './on-air-reply'; import type { IntentStation } from './station'; -async function snapshot(api: StationApi): Promise { - const [npRes, stateRes] = await Promise.allSettled([api.nowPlaying(), api.state()]); +async function snapshot(api: StationApi, signal?: AbortSignal): Promise { + const [npRes, stateRes] = await Promise.allSettled([api.nowPlaying(signal), api.state(signal)]); if (npRes.status !== 'fulfilled') return { reachable: false, online: false, track: null }; const np = npRes.value; const live: OnAirTrack | null = np.nowPlaying; @@ -50,14 +49,12 @@ export async function whatsPlaying(station: IntentStation): Promise return whatsPlayingReply(stationName(station), await snapshot(station.api)); } -export async function likeHeardTrack(station: IntentStation): Promise { - const name = stationName(station); - const snap = await snapshot(station.api); - const target = likeTarget(name, snap); - if (!('songId' in target)) return target; - const result = await station.api.likeCurrent(target.songId); - if (result && !result.error && (result.ok || result.alreadyLiked)) { - announceLike({ songId: target.songId, count: result.count }); - } - return likeReply(name, snap.track ?? {}, result); +export function likeHeardTrack(station: IntentStation, deadline: number): Promise { + return likeHeard({ + station: stationName(station), + snapshot: (signal) => snapshot(station.api, signal), + like: (songId) => station.api.likeCurrent(songId), + announce: announceLike, + deadline, + }); } From 0a4f6c486b5285519657796beefc9e828f1d9197 Mon Sep 17 00:00:00 2001 From: Parminder Klair Date: Fri, 27 Nov 2026 16:45:46 +0000 Subject: [PATCH 7/7] fix(app): cut "what's playing" to the bridge's deadline, and cancel a late like "What's playing" now races its /now-playing and /state reads against the deadline the bridge sends, aborts them when it passes, and says the station is slow to answer, the way "like this song" already did. Both go through one inTime helper in on-air-reply.ts. likeCurrent takes an optional abort signal, so POST /like is cancelled at the deadline instead of finishing in the background. The reply is still "didn't confirm": the station may have counted it before the cancel, and a repeat answers alreadyLiked. --- docs/TESTING.md | 9 +++-- scripts/api.test.ts | 16 +++++++++ scripts/intent-on-air.test.ts | 67 ++++++++++++++++++++++++++++++++++- src/intents/handlers.ts | 2 +- src/intents/on-air-reply.ts | 57 +++++++++++++++++++---------- src/intents/on-air.ts | 14 +++++--- src/lib/api.ts | 8 +++-- 7 files changed, 142 insertions(+), 31 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 45eb49e..6b7f512 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -427,9 +427,12 @@ What is easy to get wrong: didn't respond for work that went through, and the listener asks again. The bridge sends its deadline with each request and JS cuts every wait to it (`src/intents/deadline.ts`): the tune-in's wait for audio and the card, the - song request's POST and polling, the like's reads and `POST /like`. A request - still out at the deadline is said as sent, since a repeat queues it twice; a - like is said as unconfirmed, since a repeat counts once. + song request's POST and polling, the reads behind "what's playing" and the + like, and `POST /like`. The reads and the like are cancelled at the deadline + (their signal reaches `readJson`); reads still out are said as the station + being slow. A request still out at the deadline is said as sent, since a + repeat queues it twice; a like is said as unconfirmed, since a repeat counts + once. - **ActivityKit refuses a background app.** `liveactivitiesd` logs "Requester is not foreground" and the card never appears, though the audio plays. Inside a `LiveActivityIntent`'s run the request is allowed, which is why diff --git a/scripts/api.test.ts b/scripts/api.test.ts index 9f756ff..6f56611 100644 --- a/scripts/api.test.ts +++ b/scripts/api.test.ts @@ -691,6 +691,22 @@ for (const [name, call] of SIGNALLED) { } } +for (const aborted of ABORTED_READS) { + test(`a caller's abort mid-body cancels likeCurrent's POST, answered as no answer (a read that ${aborted})`, async (t) => { + // Siri's "like this song" lands here at the bridge's deadline. + t.mock.timers.enable({ apis: ['setTimeout'] }); + const sent = stubFetch(t, (signal) => new Response(stalledBody(signal, aborted, '{"ok":true'))); + const caller = new AbortController(); + const liking = watch(createApi('https://radio.example', LOGIN).likeCurrent('song-1', caller.signal)); + await settle(); + assert.equal(sent[0].signal.aborted, false); + caller.abort(); + assert.equal(sent[0].signal.aborted, true); + await settle(); + assert.deepEqual(liking.outcome, { value: null }); + }); +} + test("a caller's abort that lands with the headers still ends the read", async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const caller = new AbortController(); diff --git a/scripts/intent-on-air.test.ts b/scripts/intent-on-air.test.ts index 15030b8..2e011ea 100644 --- a/scripts/intent-on-air.test.ts +++ b/scripts/intent-on-air.test.ts @@ -19,6 +19,7 @@ import { likeTarget, likeUnconfirmedReply, slowReply, + whatsPlayingHeard, whatsPlayingReply, type OnAirSnapshot, } from '../src/intents/on-air-reply.ts'; @@ -133,10 +134,12 @@ function liking(o: { }) { const calls: string[] = []; const signals: AbortSignal[] = []; + const likeSignals: AbortSignal[] = []; const announced: string[] = []; return { calls, signals, + likeSignals, announced, run: () => likeHeard({ @@ -146,8 +149,9 @@ function liking(o: { const s = o.snapshot === undefined ? snap() : o.snapshot; return s ? Promise.resolve(s) : new Promise(() => {}); }, - like: (songId) => { + like: (songId, signal) => { calls.push(songId); + likeSignals.push(signal); return o.liked === 'never' ? new Promise(() => {}) : Promise.resolve(o.liked === undefined ? { ok: true, count: 3 } : o.liked); @@ -182,6 +186,67 @@ test('a like still unanswered at the deadline is a failure, to be asked again', assert.deepEqual(reply, likeUnconfirmedReply('SUB/WAVE')); assert.equal(reply.ok, false); assert.deepEqual(l.announced, []); + // The reads answered in time and are left be; the POST is cancelled. + assert.equal(l.signals[0]?.aborted, false); + assert.equal(l.likeSignals[0]?.aborted, true); +}); + +test('a like in time leaves its POST to finish', async () => { + const l = liking({}); + await l.run(); + assert.equal(l.likeSignals[0]?.aborted, false); +}); + +/** What's playing against a station whose reads answer `snapshot`, or never + * when it is null; the deadline's timer fires at once only when `late`. */ +function asking(o: { snapshot?: OnAirSnapshot | null; late?: boolean }) { + const signals: AbortSignal[] = []; + return { + signals, + run: () => + whatsPlayingHeard({ + station: 'SUB/WAVE', + snapshot: (signal) => { + signals.push(signal); + const s = o.snapshot === undefined ? snap() : o.snapshot; + return s ? Promise.resolve(s) : new Promise(() => {}); + }, + deadline: 10_000, + now: () => 0, + timer: () => (o.late ? Promise.resolve() : new Promise(() => {})), + }), + }; +} + +test('what’s playing in time names the heard track', async () => { + const a = asking({}); + assert.deepEqual(await a.run(), { ok: true, message: 'On SUB/WAVE: Teardrop by Massive Attack.' }); + assert.equal(a.signals[0]?.aborted, false); + assert.deepEqual(await asking({ snapshot: snap({ online: false }) }).run(), { + ok: true, + message: 'SUB/WAVE is off air right now.', + }); +}); + +test('what’s playing from a station too slow to answer says so, and its reads are stopped', async () => { + const a = asking({ snapshot: null, late: true }); + assert.deepEqual(await a.run(), slowReply('SUB/WAVE')); + assert.equal(a.signals[0]?.aborted, true); +}); + +test('the deadline is what is left of the budget when the reads start', async () => { + const waits: number[] = []; + await whatsPlayingHeard({ + station: 'SUB/WAVE', + snapshot: async () => snap(), + deadline: 10_000, + now: () => 4_000, + timer: (ms) => { + waits.push(ms); + return new Promise(() => {}); + }, + }); + assert.deepEqual(waits, [6_000]); }); test('a refused like is said in the station’s words, and the heart stays as it was', async () => { diff --git a/src/intents/handlers.ts b/src/intents/handlers.ts index b9a607a..cb3ce6f 100644 --- a/src/intents/handlers.ts +++ b/src/intents/handlers.ts @@ -24,7 +24,7 @@ export function registerIntentHandlers(): void { const station = await activeStation(); if (!station) return { ok: false, message: NO_STATION_MESSAGE }; if (action === 'request') return askForSong(args.text ?? '', { api: station.api, deadline }); - if (action === 'nowPlaying') return whatsPlaying(station); + if (action === 'nowPlaying') return whatsPlaying(station, deadline); return likeHeardTrack(station, deadline); } default: diff --git a/src/intents/on-air-reply.ts b/src/intents/on-air-reply.ts index d72ee22..3a31eec 100644 --- a/src/intents/on-air-reply.ts +++ b/src/intents/on-air-reply.ts @@ -64,7 +64,7 @@ export function likeReply(station: string, track: OnAirTrack, result: LikeResult } /** Said when the station hasn't told us what's on by the deadline: nothing - * was sent, so asking again is the whole remedy. */ + * was liked, so asking again is the whole remedy. */ export function slowReply(station: string): IntentReply { return { ok: false, message: `${station} is slow to answer. Try again in a moment.` }; } @@ -81,13 +81,11 @@ export function likeUnconfirmedReply(station: string): IntentReply { }; } -export interface LikeHeardDeps { +/** A read of the station on behalf of an intent, cut to its deadline. */ +export interface OnAirDeps { station: string; /** The track the listener is hearing, read until `signal` aborts. */ snapshot(signal: AbortSignal): Promise; - like(songId: string): Promise; - /** The in-app heart and the Live Activity follow a like that landed. */ - announce(like: { songId: string; count?: number }): void; /** Epoch ms by which Siri must have its answer (deadline.ts). */ deadline: number; now?: () => number; @@ -95,24 +93,47 @@ export interface LikeHeardDeps { timer?: (ms: number) => Promise; } -/** "Like this song": the heard track, liked, both reads cut to the deadline. */ -export async function likeHeard(deps: LikeHeardDeps): Promise { - const now = deps.now ?? Date.now; - const timer = deps.timer ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); - const untilEnd = () => timer(timeLeft(deps.deadline, now())); +export interface LikeHeardDeps extends OnAirDeps { + /** POST /like, sent until `signal` aborts. */ + like(songId: string, signal: AbortSignal): Promise; + /** The in-app heart and the Live Activity follow a like that landed. */ + announce(like: { songId: string; count?: number }): void; +} + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - // The reads stop at the deadline too (readJson honours the signal), so - // nothing keeps fetching for an answer no one will hear. +/** `call`'s answer, or TIMED_OUT once the deadline passes first, its request + * aborted then (readJson honours the signal), so nothing keeps fetching for + * an answer no one will hear. */ +function inTime( + deps: OnAirDeps, + call: (signal: AbortSignal) => Promise, +): Promise { + const now = deps.now ?? Date.now; + const timer = deps.timer ?? wait; const abort = new AbortController(); - const snap = await within(deps.snapshot(abort.signal), untilEnd()); - if (snap === TIMED_OUT) { - abort.abort(); - return slowReply(deps.station); - } + return within(call(abort.signal), timer(timeLeft(deps.deadline, now()))).then((result) => { + if (result === TIMED_OUT) abort.abort(); + return result; + }); +} + +/** "What's playing": the heard track, its reads cut to the deadline. */ +export async function whatsPlayingHeard(deps: OnAirDeps): Promise { + const snap = await inTime(deps, deps.snapshot); + return snap === TIMED_OUT ? slowReply(deps.station) : whatsPlayingReply(deps.station, snap); +} + +/** "Like this song": the heard track, liked, both steps cut to the deadline. */ +export async function likeHeard(deps: LikeHeardDeps): Promise { + const snap = await inTime(deps, deps.snapshot); + if (snap === TIMED_OUT) return slowReply(deps.station); const target = likeTarget(deps.station, snap); if (!('songId' in target)) return target; - const result = await within(deps.like(target.songId), untilEnd()); + // Cancelled at the deadline. The station may still have counted it before + // the cancel reached it; the listener's repeat then hears alreadyLiked. + const result = await inTime(deps, (signal) => deps.like(target.songId, signal)); if (result === TIMED_OUT) return likeUnconfirmedReply(deps.station); if (result && !result.error && (result.ok || result.alreadyLiked)) { deps.announce({ songId: target.songId, count: result.count }); diff --git a/src/intents/on-air.ts b/src/intents/on-air.ts index 493da2b..672ce1f 100644 --- a/src/intents/on-air.ts +++ b/src/intents/on-air.ts @@ -10,13 +10,13 @@ import { announceLike } from '@/lib/like-events'; import type { StationApi } from '@/lib/api'; import { likeHeard, - whatsPlayingReply, + whatsPlayingHeard, type OnAirSnapshot, type OnAirTrack, } from './on-air-reply'; import type { IntentStation } from './station'; -async function snapshot(api: StationApi, signal?: AbortSignal): Promise { +async function snapshot(api: StationApi, signal: AbortSignal): Promise { const [npRes, stateRes] = await Promise.allSettled([api.nowPlaying(signal), api.state(signal)]); if (npRes.status !== 'fulfilled') return { reachable: false, online: false, track: null }; const np = npRes.value; @@ -45,15 +45,19 @@ function stationName(station: IntentStation): string { return station.name || 'SUB/WAVE'; } -export async function whatsPlaying(station: IntentStation): Promise { - return whatsPlayingReply(stationName(station), await snapshot(station.api)); +export function whatsPlaying(station: IntentStation, deadline: number): Promise { + return whatsPlayingHeard({ + station: stationName(station), + snapshot: (signal) => snapshot(station.api, signal), + deadline, + }); } export function likeHeardTrack(station: IntentStation, deadline: number): Promise { return likeHeard({ station: stationName(station), snapshot: (signal) => snapshot(station.api, signal), - like: (songId) => station.api.likeCurrent(songId), + like: (songId, signal) => station.api.likeCurrent(songId, signal), announce: announceLike, deadline, }); diff --git a/src/lib/api.ts b/src/lib/api.ts index abf6ab9..6f7b672 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -64,8 +64,9 @@ export interface StationApi { /** Like the currently playing track (#991). `songId` is what the client * believes is on air; the controller rejects a stale tap. Error statuses * come back as a LikeResult with `error`; null when no answer could be read: - * a network error, a body that is not JSON, or one that never arrives. */ - likeCurrent(songId: string): Promise; + * a network error, a body that is not JSON, one that never arrives, or + * the caller's abort. */ + likeCurrent(songId: string, signal?: AbortSignal): Promise; /** Liked-state + count for the current airing. null as for likeCurrent. */ likeStatus(): Promise; /** Fire-and-forget audience beacon; all failures are swallowed. */ @@ -272,10 +273,11 @@ export function createApi( if (res.status === 404) return { success: false, status: 'unknown' }; return (await readJson(res)) as RequestResult; }, - likeCurrent: async (songId) => { + likeCurrent: async (songId, signal) => { try { const res = await send('/like', { method: 'POST', + signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ songId }), });