Repository Public
1// ORIX Sonata2// File: Packages/SonataUI/Tests/SonataUITests/ComposerTests.swift3// Description: Compose from a prompt without any network: the language knowledge is assembled4// from the shipped files, the request marks it cacheable, and the loop makes a scripted model's5// program compile with the real compiler, bounded and honest about failure.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11@testable import SonataUI1213let composerRepositoryRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()1415@Test func knowledgeContainsTheWholeLanguageAndIsStable() {16 let k = LanguageKnowledge.load(from: composerRepositoryRoot, inRepository: true)17 #expect(k.missing.isEmpty, "\(k.missing)")18 for needle in ["Sonata language specification", "Grammar (EBNF)", "composition", "instrument GrandPiano", "reverb", "tuplet", "swing", "graph", "T3001", "plucked_string", "model patch"] {19 #expect(k.text.contains(needle), "\(needle)")20 }21 #expect(k.text.utf8.count > 80_000 && k.text.utf8.count < 600_000, "\(k.text.utf8.count) bytes")22 #expect(LanguageKnowledge.load(from: composerRepositoryRoot, inRepository: true).text == k.text, "byte-identical every time, so the provider can cache it")23 let none = LanguageKnowledge.load(from: URL(fileURLWithPath: "/nonexistent"))24 #expect(none.missing.count == LanguageKnowledge.parts.count)25}2627@Test func anthropicRequestMarksTheSystemPromptCacheable() throws {28 let system = Composer.systemPrompt(knowledge: "KNOWLEDGE")29 let request = try AnthropicProvider(settings: ProviderSettings(kind: .anthropic), key: "k").request(system: system, turns: [.user("a waltz")], tools: [])30 let data = try #require(request.httpBody)31 let body = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])32 let blocks = try #require(body["system"] as? [[String: Any]])33 #expect(blocks.count == 1 && (blocks[0]["text"] as? String)?.hasSuffix("KNOWLEDGE") == true)34 #expect((blocks[0]["cache_control"] as? [String: Any])?["type"] as? String == "ephemeral")35 #expect(body["tools"] == nil)36}3738@Test func programExtraction() {39 #expect(Composer.extractProgram("Here.\n```sonata\ncomposition \"A\" { }\n```\nDone.") == "composition \"A\" { }\n")40 #expect(Composer.extractProgram("```sonata\ncomposition \"A\" { }\n```\n```sonata\ncomposition \"B\" { }\n```")?.contains("\"B\"") == true, "the last block wins")41 #expect(Composer.extractProgram("```\ncomposition \"A\" { }\n```") != nil, "a single untagged block is accepted")42 #expect(Composer.extractProgram("```python\nprint(1)\n```") == nil)43 #expect(Composer.extractProgram("```sonata\ncomposition \"A\" {") == nil, "an unterminated block is not a program")44 #expect(Composer.extractProgram("no code") == nil)45}4647@Test @MainActor func composeRepairsWithRealDiagnosticsAndMeasuresTheResult() async throws {48 let broken = "```sonata\ncomposition \"Lullaby\" {\n tempo 80bpm\n instrument p: GrandPiana {\n play F4 duration 1/4\n }\n}\n```"49 let fixed = "It is fixed.\n```sonata\ncomposition \"Lullaby\" {\n tempo 80bpm\n signature 3/4\n key F major\n instrument p: GrandPiano {\n play F4 duration 1/4\n play A4 duration 1/4\n play C5 duration 1/4\n }\n}\n```"50 let provider = ScriptedProvider([reply("I'll write it."), reply(broken), reply(fixed)])51 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("sonata-compose-" + UUID().uuidString)52 defer { try? FileManager.default.removeItem(at: dir) }53 let piece = try await Composer.compose(prompt: "a lullaby", provider: provider, knowledge: "K", renderDirectory: dir)54 #expect(piece.title == "Lullaby" && piece.tracks == 1 && piece.notes == 3 && piece.attempts >= 3)55 #expect(abs(piece.durationSec - 2.25) < 1e-9)56 let peak = try #require(piece.peakDb)57 #expect(peak > -40 && peak < -1 + 0.01, "really rendered: \(peak) dBFS")58 #expect(piece.preview != nil)59 // What the model was sent: no code -> asked for a block; real compiler diagnostics on the second try.60 #expect(provider.received.count >= 3)61 guard case .user(let ask) = provider.received[1].last!, case .user(let repair) = provider.received[2].last! else {62 Issue.record("the follow-ups are not user turns")63 return64 }65 #expect(ask.contains("`sonata` code block"))66 #expect(repair.contains("line 3") && repair.contains("GrandPiana"), "\(repair)")67 // Saving never overwrites.68 let a = try ComposerModel.save(piece, in: dir)69 let b = try ComposerModel.save(piece, in: dir)70 #expect(a.lastPathComponent == "Lullaby.sonata" && b.lastPathComponent == "Lullaby 2.sonata")71}7273@Test @MainActor func composeGivesUpHonestly() async throws {74 let bad = "```sonata\ncomposition \"X\" {\n instrument p: Nope {\n play C4\n }\n}\n```"75 let stubborn = ScriptedProvider((0..<10).map { _ in reply(bad) })76 await #expect(throws: ComposerError.self) { try await Composer.compose(prompt: "x", provider: stubborn, knowledge: "K") }77 #expect(stubborn.received.count == Composer.maxAttempts, "bounded")78 await #expect(throws: ComposerError.refused("no")) { try await Composer.compose(prompt: "x", provider: ScriptedProvider([reply(stop: .refusal("no"))]), knowledge: "K") }79 let silent = "```sonata\ncomposition \"S\" {\n instrument p: GrandPiano {\n rest 1/1\n }\n}\n```"80 let quiet = ScriptedProvider((0..<10).map { _ in reply(silent) })81 await #expect(throws: ComposerError.self) { try await Composer.compose(prompt: "x", provider: quiet, knowledge: "K") }82 await #expect(throws: ComposerError.truncated) { try await Composer.compose(prompt: "x", provider: ScriptedProvider([reply("```sonata\ncomposition", stop: .maxTokens)]), knowledge: "K") }83}8485@Test @MainActor func aQuietRenderIsReportedOnceWithItsMeasurement() async throws {86 func program(_ gain: String) -> String {87 "```sonata\ncomposition \"Quiet\" {\n tempo 100bpm\n instrument p: GrandPiano {\n gain \(gain)\n play C4 duration 1/2\n play E4 duration 1/2\n }\n}\n```"88 }89 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("sonata-compose-" + UUID().uuidString)90 defer { try? FileManager.default.removeItem(at: dir) }91 // Too quiet first; the revision is louder and is the one returned.92 let provider = ScriptedProvider([reply(program("-30dB")), reply(program("4dB"))])93 let piece = try await Composer.compose(prompt: "x", provider: provider, knowledge: "K", renderDirectory: dir)94 #expect(provider.received.count == 2 && piece.attempts == 2)95 guard case .user(let message) = provider.received[1].last! else {96 Issue.record("no level message")97 return98 }99 #expect(message.contains("dBFS") && message.contains("do not change the notes"), "\(message)")100 let peak = try #require(piece.peakDb)101 #expect(peak > Composer.quietPeakDb, "\(peak)")102 #expect(piece.source.contains("gain 4dB"))103 // A revision that breaks the program does not lose the version that compiled.104 let breaking = ScriptedProvider([reply(program("-30dB")), reply("```sonata\ncomposition \"Quiet\" { instrument p: Nope { play C4 } }\n```")])105 let kept = try await Composer.compose(prompt: "x", provider: breaking, knowledge: "K", renderDirectory: dir)106 #expect(kept.source.contains("-30dB") && kept.attempts == 2 && breaking.received.count == 2)107 // The level is reported once only.108 let stubborn = ScriptedProvider((0..<6).map { _ in reply(program("-30dB")) })109 _ = try await Composer.compose(prompt: "x", provider: stubborn, knowledge: "K", renderDirectory: dir)110 #expect(stubborn.received.count == 2)111}112