Integrating your music app with Apple Intelligence
At a glance
| Item | Summary |
|---|---|
| Purpose | Adopt the audio and clock App Intents schemas so Siri and Apple Intelligence can play, search, and organize music and manage alarms and timers in a SwiftUI app. |
| App architecture | CosmoTunesApp is the composition root. It builds every manager once, wires their cross-references, registers them with AppDependencyManager for intents and queries, and injects the observable ones into the SwiftUI environment. ModelManager owns SwiftData and mirrors entity changes into Spotlight. |
| Main patterns | SwiftUI environment injection, a SpotlightWrapping protocol that tests can replace, and actor isolation for Spotlight, on-device generation, and audio rendering |
| Project style | Three targets: the CosmoTunes app, CosmoTunesWidget, and CosmoTunesUITests. App Intents code is split by schema domain (AppIntents/Audio, AppIntents/Clock) and then by role (Entities, Intents, Enums, Queries, Snippets). |
| Execution model | Swift 6. Managers and intent perform() methods are @MainActor. Long-running work runs on the SpotlightIndexer, MIDIGenerationManager, and TrackAudioRenderer actors, reached through unstructured Tasks or await. |
| State/event model | @Observable main-actor managers injected through .environment. SwiftData @Model types. App Intents @Dependency lookup. |
| Key frameworks/packages | AppIntents, SwiftUI, SwiftData, CoreSpotlight, FoundationModels, NowPlaying, MediaIntents, WidgetKit |
Project structure
CosmoTunes/
├── CosmoTunesApp.swift // composition root, dependency registration
├── AppIntents/
│ ├── Audio/
│ │ ├── Entities/ // AlbumEntity, ArtistEntity, PlaylistEntity, SongEntity, AudioEntity (@UnionValue)
│ │ ├── Intents/ // PlayAudioIntent, AddToLibraryIntent, SearchAudioLibraryIntent, …
│ │ ├── Enums/ // AffinityState, PlaybackAttributes, QueueInsertionLocation
│ │ ├── Queries/ // AudioIntentValueQuery
│ │ └── Snippets/ // SwiftUI result snippets
│ ├── Clock/{Alarms,Timers}/ // schema entities, intents, enums
│ ├── CosmoTunesAppShortcuts.swift
│ └── TestSupport/ // debug-only reset intents
├── Managers/ // ModelManager, PlaybackController, TimerController, DonationManager,
│ // SpotlightIndexer, CoreSpotlightWrapper, MIDIGenerationManager, TrackAudioRenderer, …
├── Model/ // SwiftData @Model types (Session, GeneratedTrack, Playlist, Alarm, …)
├── GenerableTypes/ // @Generable MIDINoteSequence
└── Views/ // Library, Player, Chat, Alarms
CosmoTunesWidget/ // widget, sleep-timer and alarm Live Activities
CosmoTunesUITests/ // entity-query, intent-execution, Spotlight tests
Structure observations
- Every schema-adopting type is marked with a schema macro, such as
@AppIntent(schema: .audio.playAudio)or@AppEntity(schema: .audio.album)(CosmoTunes/AppIntents/Audio/Intents/PlayAudioIntent.swift:15,CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift:15). - Each entity file also holds its query.
AlbumEntity.swiftdefinesAlbumQuerywithEntityQuery,EntityStringQuery, andIndexedEntityQueryconformances in separate extensions (CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift:87). - The widget bundle is a separate
@mainentry for the home-screen widget and two Live Activities (CosmoTunesWidget/CosmoTunesWidgetBundle.swift:11).
Overall architecture
flowchart LR
App["CosmoTunesApp"] -->|".environment"| Views["SwiftUI views"]
App -->|"AppDependencyManager"| Intents["App intents and queries"]
Intents -->|"@Dependency"| Model["ModelManager"]
Intents -->|"@Dependency"| Playback["PlaybackController"]
Views --> Model
Model --> Store["SwiftData ModelContext"]
Model --> Indexer["SpotlightIndexer actor"]
Model --> Gen["MIDIGenerationManager actor"]
Playback --> Media["CosmoTunesMediaSession"]
Reference code
CosmoTunes/CosmoTunesApp.swift:94 — dependency registration in CosmoTunesApp.init
init() {
// ...
// Register everything as App Intents dependencies so intents and queries
// can pull them in by annotating them with `@Dependency`.
AppDependencyManager.shared.add(dependency: navigation)
AppDependencyManager.shared.add(dependency: playback)
AppDependencyManager.shared.add(dependency: timerController)
AppDependencyManager.shared.add(dependency: model)
AppDependencyManager.shared.add(dependency: donations)
AppDependencyManager.shared.add(dependency: alarmScheduler)
AppDependencyManager.shared.add(dependency: userPreferences)
// ...
}Interpretation
The same manager instances reach two different consumers. SwiftUI views get them through .environment (CosmoTunes/CosmoTunesApp.swift:132). App intents and entity queries get them through @Dependency (CosmoTunes/AppIntents/Audio/Intents/PlayAudioIntent.swift:45). So an intent run by Siri mutates the same ModelManager and PlaybackController the UI observes. Intents stay thin: they resolve entities to model objects and call manager methods.
Ownership and state
classDiagram
CosmoTunesApp *-- ModelManager : model
CosmoTunesApp *-- PlaybackController : playback
CosmoTunesApp *-- TimerController : timerController
CosmoTunesApp *-- DonationManager : donations
CosmoTunesApp *-- TrackAudioRenderer : trackRenderer
ModelManager *-- SpotlightIndexer : spotlightIndexer
ModelManager *-- MIDIGenerationManager : private
ModelManager o-- DonationManager : weak
ModelManager o-- TrackAudioRenderer : weak renderer
PlaybackController *-- AudioEngine : audioEngine
PlaybackController o-- CosmoTunesMediaSession : weak
Ownership evidence
CosmoTunes/Managers/ModelManager.swift:44 — ModelManager stored collaborators
@MainActor
@Observable
final class ModelManager {
// ...
let modelContext: ModelContext
// ...
private let midiGenerationManager = MIDIGenerationManager()
// ...
let spotlightIndexer: SpotlightIndexer
/// The renderer that clears the rendered CAF for a deleted track.
weak var renderer: TrackAudioRenderer?
// ...
weak var donations: DonationManager?
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
CosmoTunesApp |
All managers and renderers | Creates them in init and stores them as let properties (CosmoTunes/CosmoTunesApp.swift:35) |
CosmoTunesApp wires them once |
ModelManager |
modelContext (SwiftData) |
Creates the container and context in init (CosmoTunes/Managers/ModelManager.swift:88) |
ModelManager methods |
ModelManager |
spotlightIndexer, midiGenerationManager |
Creates and owns them | ModelManager |
ModelManager |
renderer, donations, artwork, userPreferences |
weak references assigned by the app (CosmoTunes/CosmoTunesApp.swift:88) |
CosmoTunesApp |
PlaybackController |
audioEngine, currentTrack, queue |
Creates the engine. The queue is private(set) (CosmoTunes/Managers/PlaybackController.swift:35). |
PlaybackController |
PlaybackController |
onFirstPlayback, onStop |
Closure hooks the app injects (CosmoTunes/CosmoTunesApp.swift:68) |
CosmoTunesApp |
MIDIGenerationManager |
sessions: [UUID: LanguageModelSession] |
Private actor state, one model session per chat session (CosmoTunes/Managers/MIDIGenerationManager.swift:22) |
The actor |
Because the cross-references between managers are weak, the app struct’s let properties are the only strong owners. The source says this directly for the sleep-timer callback: “Weak capture keeps the callback from pinning either controller” (CosmoTunes/CosmoTunesApp.swift:81).
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Main-actor isolation | @MainActor @Observable classes |
ModelManager, PlaybackController, TimerController, and the other managers are main-actor isolated. The source gives the reason: ModelContext isn’t Sendable. |
CosmoTunes/Managers/ModelManager.swift:26, CosmoTunes/Managers/PlaybackController.swift:15 |
| Main-actor isolation | @MainActor func perform() |
Intents run their body on the main actor before touching managers | CosmoTunes/AppIntents/Audio/Intents/PlayAudioIntent.swift:51 |
| Actor isolation | actor SpotlightIndexer |
Serializes calls into the SpotlightWrapping implementation |
CosmoTunes/Managers/SpotlightIndexer.swift:20 |
| Actor isolation | actor MIDIGenerationManager |
Protects the per-session LanguageModelSession dictionary. If the context overflows, it rebuilds the session and retries once. |
CosmoTunes/Managers/MIDIGenerationManager.swift:17, CosmoTunes/Managers/MIDIGenerationManager.swift:47 |
| Actor isolation | actor TrackAudioRenderer |
Owns the offline MIDI-to-CAF render cache for AlarmKit sounds | CosmoTunes/Managers/TrackAudioRenderer.swift:18 |
| Task creation | Unstructured Task { await indexer.apply(change) } |
Each main-actor mutation builds a SpotlightChange value and sends it to the indexer without waiting. Nothing retains or cancels these tasks. |
CosmoTunes/Managers/ModelManager.swift:469 |
| Task creation | Launch reindex Task |
Runs only when the stored Spotlight client state differs from the current one | CosmoTunes/Managers/ModelManager.swift:115 |
| Main-actor hop | Task { @MainActor in } in an undo handler |
Restores deleted alarms from snapshots | CosmoTunes/AppIntents/Clock/Alarms/Intents/DeleteAlarmIntent.swift:44 |
| Transfer contract | Sendable values |
SpotlightChange and AlarmSnapshot are value types marked Sendable so they can cross actor boundaries |
CosmoTunes/Managers/CoreSpotlightWrapper.swift:126, CosmoTunes/Managers/ModelManager.swift:1137 |
Reference code
CosmoTunes/Managers/ModelManager.swift:115 — launch-time reindex is skipped when Spotlight is current
func storeDidFinishLaunching() async throws {
// ...
let current = try currentSpotlightStateHelper()
let currentClientState = current.clientState()
let lastClientState = await spotlightIndexer.fetchLastClientState()
if lastClientState == currentClientState {
return
}
let change = try fullReindexChange()
let indexer = spotlightIndexer
Task {
await indexer.performLaunchBatch(change: change, clientState: currentClientState)
}
}State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| State propagation | .environment(_:) with @Observable objects |
Navigation, playback, timer, preferences, and alarm managers are injected into the view tree | CosmoTunes/CosmoTunesApp.swift:132 |
| State propagation | @Environment(Type.self) |
Views read the injected managers by type | CosmoTunes/Views/ContentView.swift:14 |
| State propagation | .modelContainer |
Shares ModelManager’s SwiftData container with views |
CosmoTunes/CosmoTunesApp.swift:131 |
| Dependency lookup | @Dependency |
Intents and queries resolve the registered managers | CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift:84 |
| Entity display | Deferred-image DisplayRepresentation |
Entities supply the image in a trailing closure. Batched displayRepresentations(for:) skip relationship loading. |
CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift:42, CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift:139 |
| Siri learning | IntentDonationManager |
DonationManager donates intents from UI actions, not from inside perform() |
CosmoTunes/Managers/DonationManager.swift:32 |
| Framework import | AppIntents, NowPlaying, SwiftData, SwiftUI |
Imported by the composition root | CosmoTunes/CosmoTunesApp.swift:8 |
| Framework import | CoreSpotlight |
Imported for indexed entities and the Spotlight wrapper | CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift:8 |
| Framework import | FoundationModels |
Imported by the on-device MIDI generator | CosmoTunes/Managers/MIDIGenerationManager.swift:9 |
| Framework import | MediaIntents |
Imported by the open-ended audio value query | CosmoTunes/AppIntents/Audio/Queries/AudioIntentValueQuery.swift:10 |
Platform boundary
Apple lists iOS, iPadOS, and Mac Catalyst. In the downloaded project, the app target sets SUPPORTS_MACCATALYST = NO and TARGETED_DEVICE_FAMILY = "1,2" (CosmoTunes.xcodeproj/project.pbxproj:505, CosmoTunes.xcodeproj/project.pbxproj:510).
Class and protocol design
classDiagram
class SpotlightWrapping {
<<protocol>>
fetchLastClientState()
performChange(change, clientState)
}
CoreSpotlightWrapper ..|> SpotlightWrapping
SpotlightIndexer --> SpotlightWrapping : wrapper
ModelManager --> SpotlightIndexer
PlayAudioIntent --> AudioEntity
AudioEntity --> SongEntity : song
AudioEntity --> PlaylistEntity : playlist
Reference code
CosmoTunes/Managers/CoreSpotlightWrapper.swift:136 — SpotlightWrapping
protocol SpotlightWrapping: Sendable {
/// Returns the opaque client-state data last committed through
/// `endBatch(withClientState:)`, or nil on first launch or index reset.
func fetchLastClientState() async -> Data?
/// Applies a change and conditionally commits the client state.
///
/// When `clientState` is non-nil and every per-entity index or delete call
/// succeeds, the wrapper commits `clientState` so the next launch can
/// short-circuit.
func performChange(_ change: SpotlightChange, clientState: Data?) async
}| Type | Responsibility | Depends on |
|---|---|---|
ModelManager |
SwiftData reads and writes, entity construction, Spotlight change creation, generation requests | ModelContext, SpotlightIndexer, MIDIGenerationManager |
PlaybackController |
Play queue, transport, Now Playing updates | AudioEngine, CosmoTunesMediaSession |
SpotlightIndexer |
Actor front for index and delete batches | any SpotlightWrapping |
DonationManager |
Donates intents after UI actions. It is non-final so tests can subclass it (CosmoTunes/Managers/DonationManager.swift:18). |
IntentDonationManager |
AudioEntity |
@UnionValue of song or playlist, so one play intent handles both |
SongEntity, PlaylistEntity |
AudioEntity.AudioIntentValueQuery |
Ranks liked songs and tokenized search results for open-ended requests | ModelManager |
ModelManager.init takes spotlightWrapper: any SpotlightWrapping with a production default, so tests can substitute a recorder (CosmoTunes/Managers/ModelManager.swift:71).
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
ModelManager.midiGenerationManager |
private let |
Only ModelManager can start generation |
Inference: generation always goes through the chat-message save path |
PlaybackController.playQueue, queueIndex, currentPlaylist, currentTrackNotes |
private(set) |
Readable across the module, writable only inside the controller | Inference: queue invariants (queueIndex points at the current slot) stay enforced |
PlaybackController.didRequestApplicationPrimary |
private var |
One-shot guard that only the controller can see | Inference: ensures the primary-session request happens at most once |
SpotlightIndexer.wrapper |
private let |
Code outside the actor can reach CoreSpotlight only through actor methods | Inference: every index call goes through the actor |
CoreSpotlightWrapper.index, applyChange |
private |
The named index and the per-entity logic are hidden behind the protocol | Inference: the protocol is the boundary for test substitution |
MIDIGenerationManager.isAvailable |
nonisolated var |
Can be read without await |
Inference: reads only the immutable model availability |
Reference code
CosmoTunes/Managers/PlaybackController.swift:35 — queue state is read-only outside the controller
@MainActor @Observable
final class PlaybackController {
// ...
/// The tracks queued behind the current track.
///
/// `queueIndex` always points at the current track's slot in `playQueue`.
private(set) var playQueue: [GeneratedTrack] = []
private(set) var queueIndex = 0
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Entity → model resolution | Intents (PlayAudioIntent.perform) |
Turns schema entities into GeneratedTrack or Playlist through ModelManager, then calls PlaybackController (CosmoTunes/AppIntents/Audio/Intents/PlayAudioIntent.swift:59) |
| Entity construction from SwiftData | ModelManager (albumEntities(for:loadRelations:) and similar) |
Keeps ModelContext access on the main actor. A loadRelations flag lets batch display requests skip the relationship graph (CosmoTunes/Managers/ModelManager.swift:1066). |
| Spotlight synchronization | ModelManager creates a SpotlightChange, and SpotlightIndexer applies it |
Mutations stay synchronous on the main actor while indexing runs on the actor |
| Undo for destructive intents | DeleteAlarmIntent |
Takes snapshots before deleting so the undo can restore the same IDs (CosmoTunes/AppIntents/Clock/Alarms/Intents/DeleteAlarmIntent.swift:34) |
| Donation timing | DonationManager |
Donates from UI actions only. Its comment says the framework already donates intents run through Siri (CosmoTunes/Managers/DonationManager.swift:14). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| SwiftUI environment injection | CosmoTunes/CosmoTunesApp.swift:132, CosmoTunes/Views/ContentView.swift:14 |
Shared observable managers reach views without passing them through every initializer |
| Protocol-oriented abstraction | CosmoTunes/Managers/CoreSpotlightWrapper.swift:136, CosmoTunes/Managers/ModelManager.swift:71 |
SpotlightWrapping makes CoreSpotlight a dependency that tests can replace |
| Actor isolation | CosmoTunes/Managers/SpotlightIndexer.swift:20, CosmoTunes/Managers/MIDIGenerationManager.swift:17 |
Moves non-UI work and its mutable state behind actor boundaries, while SwiftData stays on the main actor |
Main application flow
sequenceDiagram
actor Siri
participant Intent as AddToLibraryIntent
participant Model as ModelManager
participant Indexer as SpotlightIndexer
participant Wrapper as CoreSpotlightWrapper
Siri->>Intent: perform()
Intent->>Model: saveTrackToLibrary(track)
Model->>Model: modelContext.save()
Model->>Indexer: Task { apply(change) }
Indexer->>Wrapper: performChange(change, clientState: nil)
Reference code
CosmoTunes/AppIntents/Audio/Intents/AddToLibraryIntent.swift:39 — intent resolves the track and calls the manager
@MainActor
func perform() async throws -> some IntentResult {
switch audioEntity {
case .song(let song):
// Look up the SwiftData track on the main context so the save
// happens against a live, observed model object.
guard let track = try model.mainContextTrack(for: song.id) else {
throw AppIntentError(wrapping: AudioIntentError.noAudioEntity)
}
// Persist the library membership flag.
try model.saveTrackToLibrary(track)
// ...
return .result()
// ...
}
}CosmoTunes/Managers/ModelManager.swift:469 — save, then index asynchronously
func saveTrackToLibrary(_ track: GeneratedTrack) throws {
// ...
try modelContext.save()
let entity = SongEntity(track: track)
// ...
var change = SpotlightChange()
change.songs = [entity]
change.albums = albumPush
change.artists = artistPush
let indexer = spotlightIndexer
Task { await indexer.apply(change) }
}CosmoTunes/Managers/SpotlightIndexer.swift:40 — the actor forwards to the wrapper
func apply(_ change: SpotlightChange) async {
await wrapper.performChange(change, clientState: nil)
}Naming conventions
- Types:
…Entityfor App Entities,…Queryfor their queries,…Intentfor App Intents,…Managerand…Controllerfor main-actor state owners,…Rendererfor producers of image or audio output. Suffixes are only hints. For example,MIDIGenerationManageris an actor, whileModelManageris a main-actor class. - Protocols:
SpotlightWrappinguses the-ingcapability form for the abstraction.CoreSpotlightWrapperis the concrete type. - Methods:
donate…onDonationManager,…Entities(for:),…Entities(matching:)andall…Entities()onModelManagermirror theEntityQueryrequirements.storeDidFinishLaunchingnames a lifecycle event. - Files and extensions: one entity and its query per file. Protocol conformances are in
// MARK:extensions (EntityQuery,EntityStringQuery,IndexedEntityQuery).
Architecture takeaways
- One composition root feeds both SwiftUI (
.environment) and App Intents (AppDependencyManager). Siri-driven and UI-driven changes go through the same manager instances. - Keep the SwiftData context on the main actor, and send immutable,
Sendablechange values to an actor for slow side effects like Spotlight indexing. - A protocol around a system service (
SpotlightWrapping) plus a default argument in the owner’s initializer gives you test injection without a separate dependency-injection framework. - Batched display-representation paths load less data: they skip relationships and defer images to a closure the framework resolves only when it needs one.
- Launch-time reindexing compares a stored client-state value, so unchanged launches skip a full Spotlight rebuild.
Source map
| Source file | Relevant symbols |
|---|---|
CosmoTunes/CosmoTunesApp.swift |
CosmoTunesApp, init, AppDependencyManager, .environment |
CosmoTunes/Managers/ModelManager.swift |
ModelManager, storeDidFinishLaunching, saveTrackToLibrary, albumEntities(for:loadRelations:), AlarmSnapshot |
CosmoTunes/Managers/SpotlightIndexer.swift |
SpotlightIndexer, apply, performLaunchBatch |
CosmoTunes/Managers/CoreSpotlightWrapper.swift |
SpotlightWrapping, CoreSpotlightWrapper, SpotlightChange |
CosmoTunes/Managers/PlaybackController.swift |
PlaybackController, playQueue, onFirstPlayback |
CosmoTunes/Managers/MIDIGenerationManager.swift |
MIDIGenerationManager, generate(prompt:sessionID:) |
CosmoTunes/Managers/TrackAudioRenderer.swift |
TrackAudioRenderer |
CosmoTunes/Managers/DonationManager.swift |
DonationManager, donatePlay |
CosmoTunes/AppIntents/Audio/Intents/PlayAudioIntent.swift |
PlayAudioIntent, AudioIntentError |
CosmoTunes/AppIntents/Audio/Intents/AddToLibraryIntent.swift |
AddToLibraryIntent |
CosmoTunes/AppIntents/Audio/Entities/AlbumEntity.swift |
AlbumEntity, AlbumQuery, displayRepresentations(for:) |
CosmoTunes/AppIntents/Audio/Queries/AudioIntentValueQuery.swift |
AudioEntity.AudioIntentValueQuery |
CosmoTunes/AppIntents/Clock/Alarms/Intents/DeleteAlarmIntent.swift |
DeleteAlarmIntent, undo registration |
CosmoTunes/Views/ContentView.swift |
ContentView, @Environment(NavigationManager.self) |
CosmoTunesWidget/CosmoTunesWidgetBundle.swift |
CosmoTunesWidgetBundle |
CosmoTunes.xcodeproj/project.pbxproj |
SUPPORTS_MACCATALYST, TARGETED_DEVICE_FAMILY |