Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / VisionTransportSmoke.swift

Raw 30.8 KB on f7455f5645a899a3879cf752f3536fe6de471c90
1import Foundation
2import CryptoKit
3import Combine
4
5@main struct VisionTransportSmoke {
6 @MainActor static func main() async throws {
7 setbuf(stdout, nil)
8 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("VisionStudio-test-" + UUID().uuidString)
9 defer { try? FileManager.default.removeItem(at: directory) }
10 let suite = "VisionStudio-test-" + UUID().uuidString
11 let defaults = UserDefaults(suiteName: suite)!
12 defer { defaults.removePersistentDomain(forName: suite) }
13 let presets = ProjectMPresets(defaults: defaults)
14 let studio = VisionStudio(directory: directory, library: presets)
15 studio.volume = 0
16 await studio.importAudio(URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"))
17 precondition(studio.message == nil && studio.transport.duration > 30 && !studio.loading)
18 precondition(studio.project.clips.count > 1 && studio.project.barBoundaries != nil)
19 let analyzer = try SoundtrackAnalyzer(url: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"))
20 let macGrid = analyzer.segmentPlan(beatsPerSection: 4)
21 precondition(studio.project.barBoundaries == macGrid.boundaries)
22 precondition(studio.segments[0].end == macGrid.boundaries[4])
23 let defaultMacCuts = Array(analyzer.segmentPlan().boundaries.dropFirst())
24 precondition(studio.segments.count == defaultMacCuts.count
25 && zip(studio.segments.map(\.end), defaultMacCuts).allSatisfy { abs($0 - $1) < 0.001 },
26 "The default four-bar timing must match Mac's 16-beat section plan")
27 let untouched = studio.project.looks
28 studio.applyCommonSettings(VisionCommonSettings(bars: 1))
29 precondition(studio.project.looks == untouched && studio.project.clips.allSatisfy { $0.bars == 1 })
30 precondition(studio.segments.map(\.end) == Array(macGrid.boundaries.dropFirst()))
31 studio.seek(macGrid.boundaries[1] - 0.1); studio.togglePlayback()
32 try await Task.sleep(for: .milliseconds(350))
33 precondition(studio.selectedIndex == 1 && studio.transport.playing)
34 studio.applyCommonSettings(VisionCommonSettings(chaos: 0.72, zoomSpeed: 2, motionSpeed: 1.2,
35 strobeEnabled: true, strobeSensitivity: 1.7, strobeStrength: 0.4))
36 precondition(studio.transport.playing && NativeEffects.activeIDs.allSatisfy {
37 let look = studio.project.looks[$0]!
38 return look.chaos == 0.72 && look.zoomSpeed == 2 && look.speed == 1.2 && look.strobeEnabled && look.strobeStrength == 0.4
39 && look.palette == (untouched[$0] ?? VisionLook(scene: $0)).palette
40 })
41 let beforeRemoval = studio.look
42 studio.applyCommonSettings(VisionCommonSettings(strobeEnabled: false))
43 precondition(!studio.render.strobeEnabled && studio.look.chaos == beforeRemoval.chaos && studio.look.strobeSensitivity == 1.7)
44 let beforeInvalid = studio.project.clips
45 studio.applyCommonSettings(VisionCommonSettings(bars: 0, chaos: .nan))
46 precondition(studio.project.clips == beforeInvalid)
47 studio.suspend()
48 studio.applyCommonSettings(VisionCommonSettings(bars: 4))
49 studio.seek(0); studio.select(studio.project.clips[0])
50 precondition(studio.segments.last?.end == studio.transport.duration)
51 print("PASS Mac timing parity: identical bar grid, one-bar live scene switch, four-bar refill, selective apply-all/strobe removal/invalid input")
52 let first = studio.project.clips[0]
53 studio.bars(2, clip: first.id)
54 precondition(studio.project.clips[0].bars == 2)
55 studio.assign(22); studio.updateLook { $0.chaos = 0.91; $0.palette = 3 }
56 precondition(studio.render.scene == 22 && studio.render.chaos == 0.91 && studio.render.palette == 3)
57 let savedLooks = studio.project.looks
58 let category = presets.category(for: 22)
59 presets.setRandomizerGroup(.category(category))
60 let eligible = Set(presets.filteredScenes())
61 precondition(!eligible.isEmpty && eligible.allSatisfy { presets.category(for: $0) == category })
62 for _ in 0..<30 {
63 precondition(studio.randomizeVisualizer() && eligible.contains(studio.selectedScene))
64 precondition(studio.look.isValid && studio.look != savedLooks[studio.selectedScene], "New non-favorite selections get fresh looks")
65 }
66 presets.setRandomizerGroup(.favorites)
67 precondition(presets.filteredScenes().count == NativeEffects.activeCount && studio.randomizeVisualizer())
68 precondition(presets.favoritesFallbackMessage != nil)
69 presets.toggleFavorite(22, appearance: savedLooks[22]?.preset)
70 precondition(presets.filteredScenes() == [22] && studio.randomizeVisualizer() && studio.selectedScene == 22)
71 precondition(studio.look.preset == presets.favoriteAppearance(for: 22))
72 let favoriteSnapshot = studio.look
73 let barsBefore = studio.project.clips.map(\.bars)
74 studio.randomizeLook()
75 precondition(studio.look.isValid && studio.look != savedLooks[22] && studio.project.clips.map(\.bars) == barsBefore)
76 studio.updateLook { $0.chaos = 0.91; $0.palette = 3 }
77 presets.setRandomizerGroup(.all)
78 precondition(presets.filteredScenes().count == NativeEffects.activeCount)
79 let count = studio.project.clips.count
80 studio.addClip(); precondition(studio.project.clips.count == count + 1)
81 studio.assign(22); precondition(studio.look == favoriteSnapshot && studio.look.preset == presets.favoriteAppearance(for: 22))
82 studio.moveClip(1); studio.removeClip(); precondition(studio.project.clips.count == count)
83 studio.seek(8); precondition(abs(studio.transport.seconds - 8) < 0.05)
84 precondition(studio.render.audioBands.contains { $0 > 0 })
85 studio.togglePlayback()
86 try await Task.sleep(for: .milliseconds(350))
87 precondition(studio.transport.playing && (studio.render.playbackTime ?? 0) > 8.1)
88 studio.suspend(); precondition(!studio.transport.playing && studio.render.paused)
89 let editing = studio.project.clips[0].id
90 let following = studio.project.clips[1].id
91 let otherScenes = NativeEffects.activeIDs.filter { $0 != 22 }
92 studio.assign(22, to: editing)
93 studio.assign(otherScenes[1], to: following)
94 studio.seek(studio.segments[0].end - 0.1)
95 studio.togglePlayback()
96 try await Task.sleep(for: .milliseconds(350))
97 precondition(studio.selected == following && studio.transport.playing)
98 let playheadBeforeEdit = studio.transport.seconds
99 studio.assign(otherScenes[0], to: editing)
100 precondition(studio.project.clips.first(where: { $0.id == editing })?.scene == otherScenes[0])
101 precondition(studio.selected == following && studio.render.scene == otherScenes[1])
102 precondition(studio.transport.seconds == playheadBeforeEdit && studio.transport.playing,
103 "A card picker must edit its original clip without moving playback to a different section")
104 studio.updateLook(for: editing) { $0.chaos = 0.13 }
105 precondition(studio.look(for: editing)?.chaos == 0.13 && studio.render.chaos != 0.13)
106 studio.updateLook(for: editing) {
107 $0.strobeEnabled = true; $0.strobeSensitivity = 2.3; $0.strobeStrength = 0.65
108 }
109 let strobeLook = studio.look(for: editing)!
110 precondition(strobeLook.strobeEnabled && strobeLook.strobeSensitivity == 2.3 && strobeLook.strobeStrength == 0.65)
111 let strobeRoundTrip = try JSONDecoder().decode(VisionProject.self, from: JSONEncoder().encode(studio.project))
112 precondition(strobeRoundTrip.looks[otherScenes[0]] == strobeLook && studio.selected == following)
113 studio.resetLook(for: editing)
114 precondition(studio.look(for: editing) == VisionLook(scene: otherScenes[0]))
115 let pickerLooks = studio.project.looks
116 precondition(studio.randomizeVisualizer(for: editing))
117 precondition(studio.selected == following && studio.look(for: editing)?.isValid == true)
118 studio.randomizeLook(for: editing)
119 precondition(studio.look(for: editing)?.isValid == true && studio.selected == following)
120 let missingClip = UUID()
121 let beforeMissing = studio.project.clips
122 studio.assign(22, to: missingClip); studio.updateLook(for: missingClip) { $0.chaos = 0.2 }
123 studio.resetLook(for: missingClip)
124 precondition(!studio.randomizeVisualizer(for: missingClip) && studio.project.clips == beforeMissing)
125 studio.suspend()
126 // Restore the appearance used by the independent autosave assertions below.
127 studio.assign(22, to: editing); studio.updateLook(for: editing) { $0.chaos = 0.91; $0.palette = 3 }
128 print("PASS card picker: stable clip targeting during playback, no seek, shared style edits/reset, randomizers and missing-clip safety")
129 var completions = 0
130 studio.onPlaybackFinished = { completions += 1 }
131 studio.loopPlayback = true
132 studio.seek(studio.transport.duration - 0.2); studio.togglePlayback()
133 try await Task.sleep(for: .milliseconds(650))
134 precondition(studio.transport.playing && studio.transport.seconds < 2 && studio.selectedIndex == 0)
135 precondition(completions == 0, "Looping must not finish or stop at the track boundary")
136 studio.loopPlayback = false
137 studio.seek(studio.transport.duration - 0.2)
138 try await Task.sleep(for: .milliseconds(650))
139 precondition(!studio.transport.playing && completions == 1)
140 let restored = VisionStudio(directory: directory, library: presets)
141 restored.volume = 0; await restored.start()
142 precondition(restored.message == nil && restored.project.looks[22]?.chaos == 0.91)
143 precondition(restored.project.clips.count == count && restored.transport.duration > 30)
144 precondition(!restored.loopPlayback, "Loop preference must survive autosave restoration")
145 let filesBefore = Set(try FileManager.default.contentsOfDirectory(atPath: directory.path))
146 let loaded = await studio.loadRadioAudio(URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"), title: "Cached Radio test")
147 precondition(loaded && studio.project.audioTitle == "Cached Radio test" && studio.project.audioFile == nil)
148 let filesAfter = Set(try FileManager.default.contentsOfDirectory(atPath: directory.path))
149 precondition(filesAfter == filesBefore,
150 "Radio playback must not duplicate cached audio on each song")
151 precondition(!studio.transport.playing && studio.render.audioBands.count == 32)
152 print("PASS cached Radio audio: title, analysis, paused start, no duplicate audio copies")
153 // Local server-schema fixtures exercise the real Radio downloader and transport.
154 let fixtures = directory.appendingPathComponent("RadioFixtures")
155 try FileManager.default.createDirectory(at: fixtures, withIntermediateDirectories: true)
156 let soundtrack = try Data(contentsOf: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"))
157 try soundtrack.write(to: fixtures.appendingPathComponent("song.mp3"))
158 let hash = SHA256.hash(data: soundtrack).map { String(format: "%02x", $0) }.joined()
159 let tracks = (1...3).map { i in RadioTrack(id: UUID().uuidString, title: "Fixture song \(i)", genre: "Electronic",
160 duration: 60, audio: "song.mp3", sha256: hash, byteCount: soundtrack.count) }
161 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Test music", tracks: tracks))
162 .write(to: fixtures.appendingPathComponent("catalog.json"))
163 try JSONEncoder().encode(RadioStationDirectory(version: 1, stations: [
164 RadioStation(id: "all-music", title: "All Music", description: "Fixture", catalog: "catalog.json")]))
165 .write(to: fixtures.appendingPathComponent("stations.json"))
166 let radio = VisionRadio(directory: directory.appendingPathComponent("RadioCache"),
167 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
168 presets.setRandomizerGroup(.category(category))
169 radio.studio.volume = 0
170 let session = VisionSession(editor: restored, radio: radio)
171 let editorBefore = try Data(contentsOf: directory.appendingPathComponent("Studio-autosave.json"))
172 session.setRadioMode(true)
173 precondition(session.activeStudio === radio.studio && session.activeStudio !== restored)
174 precondition(radio.stations.isEmpty && radio.studio.transport.duration == 0)
175 radio.togglePlayback()
176 precondition(radio.loading, "First Play must immediately queue a song without preloaded stations or audio")
177 radio.togglePlayback() // Ignore repeated taps while preparing the first song.
178 await radio.waitForTrack()
179 precondition(radio.stations.map(\.title) == ["All Music"] && !radio.loadingStations && !radio.loading)
180 precondition(radio.error == nil && radio.studio.transport.playing && !radio.studio.loopPlayback)
181 let firstTitle = radio.studio.project.audioTitle
182 radio.togglePlayback()
183 precondition(!radio.studio.transport.playing)
184 radio.togglePlayback()
185 precondition(radio.studio.transport.playing && radio.studio.project.audioTitle == firstTitle,
186 "After cold-start playback, Play must resume the same song rather than choosing another")
187 precondition(radio.studio.project.clips.allSatisfy { eligible.contains($0.scene) },
188 "Radio's generated timeline must use the same selected category as the library and randomizer")
189 let title = radio.studio.project.audioTitle
190 radio.studio.seek(radio.studio.transport.duration - 0.2)
191 try await Task.sleep(for: .milliseconds(700)); await radio.waitForTrack()
192 precondition(radio.error == nil && radio.studio.transport.playing && radio.studio.project.audioTitle != title,
193 "Radio must automatically advance rather than loop one track")
194 session.setRadioMode(false)
195 precondition(session.activeStudio === restored && !radio.studio.transport.playing)
196 let editorAfter = try Data(contentsOf: directory.appendingPathComponent("Studio-autosave.json"))
197 precondition(editorAfter == editorBefore,
198 "Radio must never overwrite the user's Studio session")
199 print("PASS Vision Radio: station JSON, verified audio, autoplay next track, mode switching and independent Studio storage")
200 let loadingRadio = VisionRadio(directory: directory.appendingPathComponent("LoadingRadioCache"),
201 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
202 loadingRadio.studio.volume = 0
203 // Request Play as soon as the UI observes loading, before the directory can finish.
204 let startOnLoading = loadingRadio.$loadingStations.filter { $0 }.prefix(1).sink { _ in
205 loadingRadio.togglePlayback()
206 }
207 await loadingRadio.refreshStations()
208 await loadingRadio.waitForTrack()
209 withExtendedLifetime(startOnLoading) {}
210 precondition(loadingRadio.error == nil && loadingRadio.studio.transport.playing
211 && !loadingRadio.loading && !loadingRadio.loadingStations,
212 "Play must await the in-flight station directory and start a track")
213 loadingRadio.suspend()
214 print("PASS Radio first Play: cold start, repeated taps, pause/resume and Play during initial station loading")
215 let currentSong = radio.playingTrack!
216 radio.toggleFavoriteSong(currentSong)
217 precondition(radio.isFavoriteSong(currentSong) && radio.favoriteSongs.count == 1)
218 let reopenedRadio = VisionRadio(directory: directory.appendingPathComponent("ReopenedRadio"),
219 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
220 precondition(reopenedRadio.isFavoriteSong(currentSong), "Song hearts must survive a new Radio instance")
221 radio.selectStation("favorite-songs"); await radio.waitForTrack()
222 precondition(radio.error == nil && radio.favoriteSongsOnly && radio.playingTrack == currentSong)
223 radio.nextSong(); await radio.waitForTrack()
224 precondition(radio.playingTrack == currentSong && radio.studio.transport.playing,
225 "One favorite must form a favorites-only station, without falling back to other music")
226 let secondFavorite = tracks.first { $0.id != currentSong.id }!
227 radio.toggleFavoriteSong(secondFavorite)
228 for _ in 0..<4 {
229 let previous = radio.playingTrack
230 radio.nextSong(); await radio.waitForTrack()
231 precondition(radio.playingTrack != previous && radio.playingTrack.map(radio.isFavoriteSong) == true)
232 }
233 let favoritesReopened = VisionRadio(directory: directory.appendingPathComponent("FavoritesReopenedRadio"),
234 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
235 precondition(favoritesReopened.favoriteSongsOnly && favoritesReopened.favoriteSongs.count == 2)
236 let genreTrack = tracks.first { $0.id != currentSong.id && $0.id != secondFavorite.id }!
237 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Genre", tracks: [genreTrack]))
238 .write(to: fixtures.appendingPathComponent("genre.json"))
239 try JSONEncoder().encode(RadioStationDirectory(version: 1, stations: [
240 RadioStation(id: "all-music", title: "All Music", description: "Fixture", catalog: "catalog.json"),
241 RadioStation(id: "genre", title: "Genre", description: "Subset", catalog: "genre.json")]))
242 .write(to: fixtures.appendingPathComponent("stations.json"))
243 await radio.refreshStations()
244 radio.selectStation("genre"); await radio.waitForTrack()
245 precondition(radio.playingTrack == genreTrack && radio.favoriteSongs.count == 2,
246 "A genre subset must not remove saved songs from other stations")
247 radio.playFavoriteSong(radio.favoriteSongs.first { $0.id == currentSong.id }!); await radio.waitForTrack()
248 precondition(radio.playingTrack == currentSong, "Selecting a saved song must play that exact song")
249 radio.toggleFavoriteSong(currentSong); radio.toggleFavoriteSong(secondFavorite)
250 radio.togglePlayback(); await radio.waitForTrack()
251 precondition(!radio.studio.transport.playing && radio.error != nil && radio.favoriteSongs.isEmpty,
252 "Empty favorites must pause, explain what to do, and never fall back to all songs")
253 radio.selectStation("all-music"); await radio.waitForTrack()
254 precondition(radio.error == nil && !radio.favoriteSongsOnly && radio.studio.transport.playing)
255 radio.toggleFavoriteSong(currentSong); radio.suspend()
256 let catalogPath = fixtures.appendingPathComponent("catalog.json")
257 let originalCatalog = try Data(contentsOf: catalogPath)
258 try Data("invalid".utf8).write(to: catalogPath)
259 await radio.refreshFavoriteSongs()
260 precondition(radio.isFavoriteSong(currentSong), "Offline or invalid catalogs must not erase favorites")
261 let removedSong = radio.favoriteSongs.first!
262 radio.toggleFavoriteSong(secondFavorite)
263 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Retired song", tracks: tracks.filter { $0.id != currentSong.id }))
264 .write(to: catalogPath)
265 let startupCleanup = VisionRadio(directory: directory.appendingPathComponent("StartupCleanupRadio"),
266 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
267 await startupCleanup.refreshFavoriteSongs()
268 precondition(!startupCleanup.isFavoriteSong(currentSong) && startupCleanup.isFavoriteSong(secondFavorite)
269 && startupCleanup.stations.isEmpty && startupCleanup.playingTrack == nil && !startupCleanup.studio.transport.playing,
270 "Startup cleanup must keep available songs and remove retired songs without starting Radio")
271 let startupReopened = VisionRadio(directory: directory.appendingPathComponent("StartupReopenedRadio"),
272 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
273 precondition(!startupReopened.isFavoriteSong(currentSong) && startupReopened.isFavoriteSong(secondFavorite),
274 "Startup cleanup must stay persisted after relaunch")
275 radio.playFavoriteSong(removedSong); await radio.waitForTrack()
276 precondition(radio.error != nil && !radio.studio.transport.playing && !radio.isFavoriteSong(currentSong),
277 "A retired saved song must be pruned and reported instead of playing a different song")
278 radio.toggleFavoriteSong(secondFavorite)
279 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Removed song", tracks: tracks.filter { $0.id != currentSong.id }))
280 .write(to: catalogPath)
281 await radio.refreshFavoriteSongs()
282 precondition(radio.favoriteSongs.isEmpty)
283 let prunedRadio = VisionRadio(directory: directory.appendingPathComponent("PrunedRadio"),
284 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
285 precondition(prunedRadio.favoriteSongs.isEmpty, "Removed songs must stay removed after reopening")
286 try originalCatalog.write(to: catalogPath)
287 print("PASS Vision song favorites: persisted hearts, one/multiple/empty favorites stations, exact song playback, All restore, failed refresh retention and removed-song pruning")
288 let portable = VisionStudio(directory: directory.appendingPathComponent("Portable"), library: presets)
289 portable.volume = 0
290 var incoming = VisionProject()
291 incoming.clips = [VisionClip(scene: 22, bars: 1), VisionClip(scene: otherScenes[1], bars: 4)]
292 incoming.looks[22] = VisionLook(scene: 22); incoming.looks[22]!.chaos = 0.37
293 incoming.externalAudioURL = URL(fileURLWithPath: "/Missing/Track.wav")
294 incoming.importedTimeline = [StudioSegment(start: 0, end: 1.5, scene: 22, bars: 1),
295 StudioSegment(start: 1.5, end: studio.transport.duration, scene: otherScenes[1], bars: 4)]
296 await portable.replaceProject(incoming)
297 precondition(portable.needsSoundtrack && portable.audioURL == nil && portable.project.clips == incoming.clips)
298 await portable.importAudio(URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"), generateTimeline: false)
299 precondition(!portable.needsSoundtrack && portable.audioURL != nil && portable.project.clips == incoming.clips)
300 precondition(portable.look(for: incoming.clips[0].id)?.chaos == 0.37
301 && portable.segments.map(\.end) == incoming.importedTimeline!.map(\.end))
302 print("PASS portable project audio relocation: missing audio waits without demo substitution; locating the song preserves exact cuts, card IDs and looks")
303 presets.setRandomizerGroup(.all)
304 let importedEnds = portable.segments.map(\.end)
305 let importedIDs = portable.project.clips.map(\.id)
306 let importedLooks = portable.project.looks
307 precondition(portable.randomizeTimeline())
308 precondition(portable.segments.map(\.end) == importedEnds && portable.project.clips.map(\.id) == importedIDs
309 && portable.project.looks != importedLooks && portable.project.importedTimeline != nil,
310 "Visualizers-only randomization must preserve exact imported cuts and IDs while creating fresh looks")
311 portable.updateLook { $0.size = 5.75; $0.rotation = 1.2; $0.motionBlur = 0.65; $0.fog = 0.2; $0.detail = 0.85; $0.haloCount = 10 }
312 precondition(portable.render.particleSize == 5.75 && portable.render.rotation == 1.2
313 && portable.render.motionBlur == 0.65 && portable.render.fog == 0.2
314 && portable.render.liquidDetail == 0.85 && portable.render.haloCount == 10)
315 let looksBeforeTimeline = portable.project.looks
316 let urlBeforeTimeline = portable.audioURL
317 portable.seek(8); portable.togglePlayback()
318 precondition(portable.randomizeTimeline(barLengths: true, chooseLength: { 2 }))
319 precondition(portable.transport.playing && abs(portable.transport.seconds - 8) < 0.1
320 && portable.project.looks != looksBeforeTimeline && portable.audioURL == urlBeforeTimeline)
321 precondition(portable.project.importedTimeline == nil && portable.segments.last?.end == portable.transport.duration
322 && portable.project.clips.allSatisfy { $0.bars == 2 }
323 && Set(portable.project.clips.map(\.scene)).count == portable.project.clips.count)
324 portable.suspend()
325 let encoder = JSONEncoder(); encoder.outputFormatting = .sortedKeys
326 for scene in NativeEffects.activeIDs where presets.isFavorite(scene) { presets.toggleFavorite(scene) }
327 presets.setRandomizerGroup(.favorites)
328 precondition(portable.randomizeTimeline(barLengths: true, chooseLength: { 4 })
329 && presets.favoritesFallbackMessage != nil,
330 "An empty favorites selection must still randomize the full timeline")
331 presets.setRandomizerGroup(.category("Missing category"))
332 let beforeEmptyPool = try encoder.encode(portable.project)
333 precondition(!portable.randomizeTimeline(barLengths: true, chooseLength: { 8 }))
334 let afterEmptyPool = try encoder.encode(portable.project)
335 precondition(afterEmptyPool == beforeEmptyPool, "Combined randomization failures must be atomic")
336 let barsOnlyLooks = portable.project.looks
337 let orderedScenes = portable.project.clips.map(\.scene)
338 precondition(portable.randomizeTimeline(visualizers: false, barLengths: true, chooseLength: { 8 }))
339 precondition(zip(portable.project.clips.map(\.scene), orderedScenes).allSatisfy { $0.0 == $0.1 }
340 && portable.project.looks == barsOnlyLooks, "Bars-only must preserve visualizer order and shared looks")
341 presets.setRandomizerGroup(.favorites)
342 presets.toggleFavorite(22)
343 precondition(portable.randomizeTimeline(barLengths: true, chooseLength: { 1 }))
344 precondition(portable.project.clips.allSatisfy { $0.scene == 22 && $0.bars == 1 }
345 && portable.segments.last?.end == portable.transport.duration)
346 let afterSinglePool = try encoder.encode(portable.project)
347 precondition(!portable.randomizeTimeline(visualizers: false, barLengths: false))
348 precondition(!portable.randomizeTimeline(barLengths: true, chooseLength: { 9 }))
349 let afterRejectedInput = try encoder.encode(portable.project)
350 precondition(afterRejectedInput == afterSinglePool)
351 let autosavedTimeline = try JSONDecoder().decode(VisionProject.self,
352 from: Data(contentsOf: directory.appendingPathComponent("Portable/Studio-autosave.json")))
353 precondition(autosavedTimeline.clips == portable.project.clips && autosavedTimeline.looks == portable.project.looks)
354 print("PASS whole timeline: exact cuts, shared styles/render bindings, playback position, atomic failures, empty/single pools, bars-only order, full coverage and autosave")
355 print("PASS loop boundary/restart, loop persistence, category/favorites cascade, empty/single pools and independent style dice")
356 print("PASS Vision transport: actual soundtrack import/analysis, per-scene bars, shared appearance, add/move/remove, seek, playback clock/audio bands, pause and autosave restoration")
357 let librarySong = directory.appendingPathComponent("Library song.m4a")
358 try FileManager.default.copyItem(at: studio.audioURL!, to: librarySong)
359 let libraryStudio = VisionStudio(directory: directory.appendingPathComponent("LibraryStudio"), library: presets)
360 let imported = await libraryStudio.importAudio(librarySong, title: "Picked from music")
361 precondition(imported && libraryStudio.project.audioTitle == "Picked from music")
362 let permanentURL = libraryStudio.audioURL!
363 try FileManager.default.removeItem(at: librarySong)
364 precondition(FileManager.default.fileExists(atPath: permanentURL.path) && !libraryStudio.segments.isEmpty)
365 let restoredLibraryStudio = VisionStudio(directory: directory.appendingPathComponent("LibraryStudio"), library: presets)
366 await restoredLibraryStudio.start()
367 precondition(restoredLibraryStudio.audioURL == permanentURL && restoredLibraryStudio.project.audioTitle == "Picked from music")
368 precondition(restoredLibraryStudio.transport.duration > 0 && !restoredLibraryStudio.needsSoundtrack)
369 print("PASS Studio library song: chosen title, permanent copy, timeline and reopening after source removal")
370
371 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Test Radio", tracks: tracks))
372 .write(to: fixtures.appendingPathComponent("catalog.json"))
373 let personalLibrary = RadioLibrary(directory: directory.appendingPathComponent("PersonalCache"))
374 let album = directory.appendingPathComponent("Personal album")
375 try FileManager.default.createDirectory(at: album, withIntermediateDirectories: true)
376 let localSong = fixtures.appendingPathComponent(tracks[0].audio)
377 try FileManager.default.copyItem(at: localSong, to: album.appendingPathComponent("Personal song.mp3"))
378 let personal = try await personalLibrary.importMusicFolder(album, into: directory.appendingPathComponent("PersonalRadio"))
379 defaults.set(personal.url, forKey: PersonalRadioMusic.catalogKey)
380 defaults.set(true, forKey: PersonalRadioMusic.activeKey)
381 let personalRadio = VisionRadio(directory: directory.appendingPathComponent("PersonalPlayback"),
382 source: fixtures.appendingPathComponent("stations.json"), presets: presets, defaults: defaults)
383 personalRadio.studio.volume = 0
384 personalRadio.nextSong(); await personalRadio.waitForTrack()
385 precondition(personalRadio.error == nil && personalRadio.isPersonalMusic && personalRadio.studio.transport.playing)
386 precondition(personalRadio.playingTrack?.title == "Personal song")
387 precondition(personalRadio.studioMusicSource == fixtures.appendingPathComponent("stations.json"))
388 let personalID = personalRadio.playingTrack!.id
389 personalRadio.studio.seek(personalRadio.studio.transport.duration - 0.2)
390 try await Task.sleep(for: .milliseconds(700)); await personalRadio.waitForTrack()
391 precondition(personalRadio.playingTrack?.id == personalID && personalRadio.studio.transport.playing)
392 await personalRadio.refreshStations()
393 personalRadio.selectStation("all-music"); await personalRadio.waitForTrack()
394 precondition(!personalRadio.isPersonalMusic && personalRadio.studio.transport.playing && personalRadio.error == nil)
395 personalRadio.suspend()
396 print("PASS Vision personal Radio: restored folder, looping, Studio catalog isolation, returning to server music")
397 }
398}