SPB Git

Repository Public

StudioTests.swift 25.7 KB 321 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Tests/StudioTests.swift4//  Description: Cost Intelligence decoding and budget levels, project patches, deep-research events / reducer / session5//               against a scripted server, image-studio DTOs — and live checks against the development backend.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation12import Testing13import UIKit14@testable import SPChat1516@Suite struct CostIntelligenceTests {17    /// Trimmed from a real `GET /api/usage` answer of backend 1.0 (numeric columns arrive as strings).18    static let usageJSON = #"{"totals":{"requests":929,"cost":0.503897,"cost_confirmed":0,"input_tokens":"630411","output_tokens":"193473","cached_tokens":"259142","reasoning_tokens":"3197","avg_latency":2801,"avg_ttft":4421,"errors":2},"daily":[{"day":"2026-11-01T00:00:00.000Z","provider":"anthropic","cost":0.030296,"requests":5,"input_tokens":"4290","output_tokens":"498"},{"day":"2026-11-01T00:00:00.000Z","provider":"openai","cost":2e-06,"requests":2,"input_tokens":"140","output_tokens":"0"}],"byModel":[{"model_id":"claude-opus-5-5","provider":"anthropic","requests":10,"cost":0.223422,"input_tokens":"20529","output_tokens":"8280","errors":0}],"byRoute":[{"route":"direct","provider":"anthropic","requests":614,"cost":0.362813,"cost_exact":0,"input_tokens":"533919","output_tokens":"188662"},{"route":"openrouter","provider":"openrouter","requests":1,"cost":"0.019596","cost_exact":0.019596,"input_tokens":"4607","output_tokens":"385"}],"byConversation":[{"conversation_id":"conv_2upwevv0o3cqyf5j","title":"Histoire des phares en mer","requests":1,"cost":0.121676,"last_at":"2026-11-18T04:34:41.138Z"},{"conversation_id":"conv_73bmktxa0xnzxykm","title":"Dernière version stable de PostgreSQL","requests":2,"cost":0.020646,"last_at":"2026-11-19T14:21:07.970Z"}],"costBasis":{"exact":0.019596,"estimated":0.484301,"note":"« exact » = montant facturé rapporté par le fournisseur."},"spending":{"today":0.020918,"month":0.503897,"limits":{"dailyLimitUsd":10,"alertAtPercent":80,"monthlyLimitUsd":150}}}"#1920    @Test func usageDecodesRoutesConversationsAndCostBasis() throws {21        let r = try JSONDecoder().decode(UsageReport.self, from: Data(Self.usageJSON.utf8))22        #expect(r.totals.requests == 929 && r.totals.inputTokens == 630_411 && r.totals.errors == 2)23        let routes = try #require(r.byRoute)24        #expect(routes.count == 2)25        let or = try #require(routes.first { $0.route == "openrouter" })26        #expect(or.provider == "openrouter" && or.cost == 0.019596 && or.costExact == 0.019596 && or.requests == 1)27        #expect(routes.first?.costExact == 0 && routes.first?.id == "direct-anthropic")28        let convs = try #require(r.byConversation)29        #expect(convs.map(\.conversationId) == ["conv_2upwevv0o3cqyf5j", "conv_73bmktxa0xnzxykm"])30        #expect(convs.first?.title == "Histoire des phares en mer" && convs.first?.lastAt != nil)31        let basis = try #require(r.costBasis)32        #expect(basis.exact == 0.019596 && basis.estimated == 0.484301 && basis.note?.contains("facturé") == true)33        #expect(r.spending.limits.alertAtPercent == 80)34    }3536    @Test func aServerWithoutTheAdditionsStillDecodes() throws {37        let old = #"{"totals":{"requests":1,"cost":0.1,"input_tokens":10,"output_tokens":5,"errors":0},"daily":[],"byModel":[],"spending":{"today":0,"month":0,"limits":{"dailyLimitUsd":0,"alertAtPercent":80,"monthlyLimitUsd":0}}}"#38        let r = try JSONDecoder().decode(UsageReport.self, from: Data(old.utf8))39        #expect(r.byRoute == nil && r.byConversation == nil && r.costBasis == nil && r.totals.cost == 0.1)40    }4142    @Test func budgetLevelsFollowLimitAndAlertThreshold() {43        #expect(BudgetLevel.of(value: 5, limit: 0, alertAtPercent: 80) == .none)44        #expect(BudgetLevel.of(value: 7.9, limit: 10, alertAtPercent: 80) == .ok)45        #expect(BudgetLevel.of(value: 8, limit: 10, alertAtPercent: 80) == .alert)46        #expect(BudgetLevel.of(value: 10, limit: 10, alertAtPercent: 80) == .reached)47        #expect(BudgetLevel.of(value: 12, limit: 10, alertAtPercent: 80) == .reached)48        #expect(BudgetLevel.of(value: 9.9, limit: 10, alertAtPercent: 0) == .ok)          // no alert threshold49        #expect(BudgetLevel.of(value: 9.9, limit: 10, alertAtPercent: 250) == .ok)        // a threshold above 100 % never fires before the limit50    }5152    @Test func budgetAmountsAcceptCommaAndRefuseNonsense() {53        #expect(BudgetEditor.number("12,5") == 12.5 && BudgetEditor.number(" 0 ") == 0 && BudgetEditor.number("150") == 150)54        #expect(BudgetEditor.number("-1") == nil && BudgetEditor.number("abc") == nil && BudgetEditor.number("") == nil)55    }56}5758@Suite struct ProjectPatchTests {59    private func project(_ json: String) throws -> Project { try JSONDecoder().decode(Project.self, from: Data(json.utf8)) }6061    @Test func onlyWhatChangedIsSentAndEmptyTextClearsAField() throws {62        let p = try project(##"{"id":"proj_1","name":"Thèse","description":"Chapitre 3","instructions":"Réponds en français.","default_model":"claude-haiku-5-5","color":"#6d9cff","conversation_count":4,"file_count":2}"##)63        let same = ProjectPatch(from: p, name: "Thèse", description: "Chapitre 3", instructions: "Réponds en français.", defaultModel: "claude-haiku-5-5", color: "#6d9cff")64        #expect(same.isEmpty && same.payload.isEmpty)6566        let edited = ProjectPatch(from: p, name: " Thèse ULaval ", description: "", instructions: "Réponds en français.\nCite tes sources.", defaultModel: nil, color: "#4fd1a5")67        #expect(edited.payload["name"] == .string("Thèse ULaval"))68        #expect(edited.payload["description"] == .null)                       // cleared69        #expect(edited.payload["instructions"] == .string("Réponds en français.\nCite tes sources."))70        #expect(edited.payload["defaultModel"] == .null)                      // back to the account default71        #expect(edited.payload["color"] == .string("#4fd1a5"))72        // the body is valid JSON with explicit nulls (the server distinguishes "absent" from "null")73        let body = String(decoding: try JSONEncoder().encode(JSONValue.object(edited.payload)), as: UTF8.self)74        #expect(body.contains(#""defaultModel":null"#) && body.contains(#""description":null"#))75    }7677    @Test func anEmptyNameIsNeverSentAndLimitsAreApplied() throws {78        let p = try project(#"{"id":"proj_1","name":"A","conversation_count":0,"file_count":0}"#)79        let patch = ProjectPatch(from: p, name: "   ", description: "", instructions: String(repeating: "x", count: 25_000), defaultModel: "or:google/gemini-4-neon", color: nil)80        #expect(patch.payload["name"] == nil)81        #expect(patch.payload["instructions"]?.stringValue?.count == 20_000)82        #expect(patch.payload["defaultModel"] == .string("or:google/gemini-4-neon"))83        #expect(patch.payload["description"] == nil && patch.payload["color"] == nil)   // unchanged: both were already empty84    }8586    @Test func projectDetailDecodesFilesAndCounts() throws {87        let j = try JSONDecoder().decode(JSONValue.self, from: Data(##"{"project":{"id":"proj_1","name":"P","instructions":"I","default_model":null,"color":"#ff6b6b"},"files":[{"id":"att_1","filename":"a.pdf","mime":"application/pdf","size_bytes":1200,"page_count":3,"index_status":"indexed"},{"bad":true}],"memories":[{"id":"m1"}],"artifacts":[]}"##.utf8))88        let d = try #require(ProjectDetail(j))89        #expect(d.project.instructions == "I" && d.project.defaultModel == nil && d.files.count == 1 && d.files.first?.pageCount == 3 && d.memoryCount == 1 && d.artifactCount == 0)90        #expect(ProjectDetail(.object(["files": .array([])])) == nil)91    }9293    @Test func paletteParsesTheWebColours() {94        #expect(ProjectPalette.color("#6d9cff") != nil && ProjectPalette.color("6D9CFF") != nil)95        #expect(ProjectPalette.color(nil) == nil && ProjectPalette.color("") == nil && ProjectPalette.color("#zzz") == nil && ProjectPalette.color("blue") == nil)96        #expect(ProjectPalette.hexes.count == 8)97    }98}99100@Suite struct ResearchTests {101    static func events(end: Bool = true) -> [String] {102        var e: [String] = ["retry: 2000\n\n"]; var i = 0103        func add(_ n: String, _ j: String) { e.append(SSE.event(n, j, id: i)); i += 1 }104        add("run", #"{"runId":"run_r1"}"#)105        add("start", #"{"id":"rs_1","conversationId":"conv_r1","model":"claude-haiku-5-5","extractor":"claude-haiku-5-5","depth":"quick","resumed":false,"question":"Q ?"}"#)106        add("step", #"{"step":"plan","status":"searching","detail":{"subquestions":["a","b"],"queries":["q1","q2","q3"],"evidence_needed":["x"]},"reused":false}"#)107        add("step", #"{"step":"discovery","status":"reading","detail":{"queries":["q1"],"found":9},"reused":false}"#)108        add("source", #"{"n":2,"url":"https://www.example.org/b","title":"B","fetched":true}"#)109        add("evidence", #"{"n":2,"count":3}"#)110        add("source", #"{"n":1,"url":"https://example.com/a","title":"A","fetched":false,"error":true}"#)111        add("step", #"{"step":"synthesis","status":"synthesizing"}"#)112        add("text", ##"{"delta":"# Rapport\n"}"##)113        add("text", #"{"delta":"Fin."}"#)114        if end {115            add("done", #"{"id":"rs_1","conversationId":"conv_r1","costUsd":0.0123,"sources":2,"status":"complete"}"#)116            add("end", "{}")117        }118        return e119    }120121    private func parsed(_ chunks: [String]) -> [SSEEvent] {122        var p = SSEParser()123        return chunks.flatMap { p.feed(Array($0.utf8)) }.compactMap { if case .event(let e) = $0 { return e } else { return nil } }124    }125126    @Test func theReducerBuildsStagesSourcesAndReportFromServerEvents() {127        var p = ResearchProgress()128        for sse in parsed(Self.events()) { p.apply(ResearchEvent(sse: sse), index: sse.id) }129        #expect(p.runId == "run_r1" && p.researchId == "rs_1" && p.conversationId == "conv_r1" && p.model == "claude-haiku-5-5" && p.depth == "quick")130        #expect(p.plan?.subquestions == ["a", "b"] && p.plan?.queries.count == 3 && p.found == 9)131        #expect(p.sources.map(\.n) == [1, 2])                                  // kept in the server's numbering132        #expect(p.sources.first?.failed == true && p.sources.first?.fetched == false && p.sources.last?.evidenceCount == 3 && p.sources.last?.domain == "example.org")133        #expect(p.stage == 5 && p.report == "# Rapport\nFin." && p.costUsd == 0.0123 && p.isComplete && p.ended && p.status == "complete" && p.error == nil)134    }135136    @Test func replayedEventsAreAppliedOnceAndErrorsKeepTheRunResumable() {137        var p = ResearchProgress()138        let all = parsed(Self.events(end: false))139        for sse in all { p.apply(ResearchEvent(sse: sse), index: sse.id) }140        for sse in all.suffix(4) { p.apply(ResearchEvent(sse: sse), index: sse.id) }       // a re-attachment replays the tail141        #expect(p.report == "# Rapport\nFin." && p.sources.count == 2 && !p.ended && !p.isComplete)142        p.apply(ResearchEvent(sse: SSEEvent(event: "error", data: #"{"message":"Recherche interrompue.","status":"interrupted","resumable":true,"code":"cancelled"}"#, id: 99)), index: 99)143        #expect(p.error == "Recherche interrompue." && p.status == "interrupted" && p.resumable)144        #expect(ResearchStatus.resumable.contains(p.status))145        // an event this build does not know changes nothing146        let before = p147        p.apply(ResearchEvent(sse: SSEEvent(event: "telemetry", data: "{}", id: 100)), index: 100)148        var expected = before; expected.lastIndex = 100149        #expect(p == expected)150    }151152    @Test func runsDecodeFromListAndDetailShapes() throws {153        let list = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"runs":[{"id":"rs_1","conversation_id":"conv_r1","question":"Q ?","model_id":"claude-haiku-5-5","status":"interrupted","depth":"quick","cost_usd":"0.004200","error":"Recherche interrompue.","created_at":"2026-11-19T15:00:00.000Z","updated_at":"2026-11-19T15:01:00.000Z","completed_at":null,"source_count":7,"live":null},{"id":"rs_2","question":"Autre","status":"reading","live":"run_x"},{"nope":1}]}"#.utf8))154        let runs = list.list("runs").compactMap { ResearchRun($0) }155        #expect(runs.count == 2)156        let first = try #require(runs.first)157        #expect(first.costUsd == 0.0042 && first.sourceCount == 7 && first.isResumable && !first.isRunning && first.createdAt != nil)158        #expect(runs.last?.isRunning == true && runs.last?.isResumable == false && runs.last?.liveRunId == "run_x" && runs.last?.depth == "standard")159160        let detail = try JSONDecoder().decode(JSONValue.self, from: Data(##"{"run":{"id":"rs_1","conversation_id":"conv_r1","question":"Q ?","model_id":"m","status":"complete","depth":"deep","cost_usd":0.5,"plan":{"subquestions":["a"],"queries":["q"]},"sources":[{"n":2,"url":"https://b.org","title":"B","snippet":"s","fetched":true,"analysed":true,"evidence":[{"claim":"c","quote":"q","confidence":"high"}]},{"n":1,"url":"https://a.org","title":"A","fetched":false}],"report_md":"# R"},"live":null}"##.utf8))161        let run = try #require(detail["run"].flatMap { ResearchRun($0, live: detail.str("live")) })162        #expect(run.report == "# R" && run.plan?.queries == ["q"] && run.sources.map(\.n) == [1, 2] && run.sourceCount == 2)163        #expect(run.sources.last?.evidence.first?.confidence == "high" && run.sources.last?.evidenceCount == 1 && run.sources.first?.evidenceCount == nil)164        #expect(!run.isResumable && !run.isRunning)165    }166167    @MainActor @Test func aSessionFollowsTheStreamReattachesAfterADropAndEndsOnTheStoredRun() async throws {168        let host = "research.test"169        let all = Self.events()170        let stored = ##"{"run":{"id":"rs_1","conversation_id":"conv_r1","question":"Q ?","model_id":"claude-haiku-5-5","status":"complete","depth":"quick","cost_usd":0.0123,"plan":null,"sources":[{"n":1,"url":"https://example.com/a","title":"A","fetched":true,"evidence":[]}],"report_md":"# Rapport\nFin."},"live":null}"##171        StubProtocol.install(host: host) { req, _ in172            let path = req.url?.path ?? ""173            if path == "/api/research" && req.httpMethod == "POST" { return .sse(Array(all.prefix(6)), drop: true) }        // the connection drops after the first source174            if path == "/api/chat/stream" { return .sse(all) }                                                           // the re-attachment replays everything175            if path == "/api/research/rs_1" { return .json(stored) }176            return .json(#"{"error":"nope"}"#, status: 404)177        }178        let env = TestEnv.make(host: host)179        env.network.simulate(online: true)180        let session = ResearchSession(api: env.api, waitUntilOnline: {})181        session.start(question: "Q ?", modelId: "claude-haiku-5-5", projectId: nil, depth: .quick)182        #expect(session.isFollowing && session.progress != nil)183        #expect(await TestEnv.wait(timeout: 10) { !session.isFollowing })184        #expect(session.progress?.report == "# Rapport\nFin." && session.progress?.sources.count == 2 && session.progress?.isComplete == true)185        #expect(session.finished?.status == "complete" && session.finished?.report == "# Rapport\nFin." && session.error == nil)186        // the POST carried the options the API accepts; the re-attachment asked for what followed the last index applied187        let reqs = StubProtocol.requests(host: host)188        let attach = try #require(reqs.first { $0.url?.path == "/api/chat/stream" })189        #expect(attach.url?.query?.contains("run=run_r1") == true && attach.url?.query?.contains("after=4") == true)190    }191192    @MainActor @Test func aRefusedStartReportsTheServerMessageAndFollowsNothing() async {193        let host = "research-refused.test"194        StubProtocol.install(host: host) { _, _ in .json(#"{"error":"Budget du jour atteint.","code":"budget"}"#, status: 402) }195        let env = TestEnv.make(host: host)196        let session = ResearchSession(api: env.api, waitUntilOnline: {})197        session.start(question: "Question ?", modelId: "m", projectId: nil, depth: .quick)198        #expect(await TestEnv.wait(timeout: 5) { !session.isFollowing })199        #expect(session.error == "Budget du jour atteint." && session.progress == nil && session.finished == nil)200    }201}202203@Suite struct ImageStudioTests {204    @Test func galleryRowsAndResultsDecode() throws {205        let j = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"images":[{"id":"att_1","filename":"generated-1.png","meta":{"prompt":"un phare","model":"gpt-image-1-mini","revisedPrompt":"A lighthouse","size":"1024x1024","quality":"low"},"conversation_id":null,"created_at":"2026-11-19T15:00:00.000Z"},{"id":"att_2","filename":"edited-2.png","meta":{"prompt":"plus de brume","model":"gpt-image-1.5","editedFrom":"att_1"},"conversation_id":"conv_1","created_at":"2026-11-19T15:05:00.000Z"},{"id":"att_3","filename":"x.png","meta":null},{"meta":{}}]}"#.utf8))206        let images = j.list("images").compactMap(GeneratedImage.init)207        #expect(images.count == 3)208        #expect(images.first?.prompt == "un phare" && images.first?.quality == "low" && images.first?.editedFrom == nil && images.first?.createdAt != nil)209        #expect(images.dropFirst().first?.editedFrom == "att_1" && images.dropFirst().first?.conversationId == "conv_1" && images.last?.prompt == nil)210        let ok = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"attachmentId":"att_9","model":"gpt-image-1-mini","revisedPrompt":"r","costUsd":0.0061,"note":"Image saved"}"#.utf8))211        #expect(ImageGeneration(ok)?.attachmentId == "att_9" && ImageGeneration(ok)?.costUsd == 0.0061)212        #expect(ImageGeneration(.object(["error": .string("No image returned")])) == nil)213    }214215    @Test func thePayloadCarriesOnlyWhatTheServerAccepts() {216        let gen = ImageOptions.payload(prompt: "  un phare  ", model: "gpt-image-1-mini", size: "1024x1024", quality: "low", editAttachmentId: nil)217        #expect(gen == ["prompt": .string("un phare"), "model": .string("gpt-image-1-mini"), "size": .string("1024x1024"), "quality": .string("low")])218        let edit = ImageOptions.payload(prompt: "plus de brume", model: "", size: "1536x1024", quality: "high", editAttachmentId: "att_1")219        #expect(edit == ["prompt": .string("plus de brume"), "editAttachmentId": .string("att_1")])      // an edit takes neither size nor quality220        #expect(ImageOptions.payload(prompt: String(repeating: "a", count: 5000), model: nil, size: nil, quality: nil, editAttachmentId: nil)["prompt"]?.stringValue?.count == 4000)221    }222223    @MainActor @Test func aGenerationWithoutImageIsAnErrorWithTheServerReason() async {224        let host = "images.test"225        StubProtocol.install(host: host) { req, body in226            guard req.httpMethod == "POST" else { return .json(#"{"images":[]}"#) }227            let sent = (try? JSONDecoder().decode(JSONValue.self, from: body ?? Data())) ?? .null228            return sent.str("prompt") == "ok" ? .json(#"{"attachmentId":"att_9","model":"gpt-image-1-mini","costUsd":0.005}"#) : .json(#"{"error":"No image returned"}"#)229        }230        let env = TestEnv.make(host: host)231        let done = try? await env.api.generateImage(prompt: "ok", model: nil, size: "1024x1024", quality: "low")232        #expect(done?.attachmentId == "att_9")233        do { _ = try await env.api.generateImage(prompt: "vide", model: nil, size: nil, quality: nil); Issue.record("an empty result must throw") }234        catch { #expect((error as? APIError)?.message == "No image returned") }235        #expect((try? await env.api.generatedImages())?.isEmpty == true)236    }237}238239@Suite(.serialized, .enabled(if: Live.enabled)) @MainActor struct LiveStudioTests {240    @Test func usageAdditionsDecodeFromTheRealServer() async throws {241        let env = Live.environment()242        let r = try await env.api.usage(days: 30)243        let routes = try #require(r.byRoute)244        #expect(!routes.isEmpty && routes.allSatisfy { !$0.provider.isEmpty && $0.cost >= 0 && $0.costExact >= 0 && $0.costExact <= $0.cost + 0.000001 })245        #expect(r.byConversation != nil)246        let basis = try #require(r.costBasis)247        #expect(basis.exact >= 0 && basis.estimated >= 0 && basis.note?.isEmpty == false)248        // exact + estimated is the cost of the period, to rounding249        #expect(abs(basis.exact + basis.estimated - r.totals.cost) < 0.01)250    }251252    @Test func aProjectIsCreatedEditedClearedAndDeleted() async throws {253        let env = Live.environment()254        let created = try await env.api.createProject(name: "Projet iOS \(UUID().uuidString.prefix(6))")255        do {256            var p = try await env.api.updateProject(created.id, patch: ProjectPatch(from: created, name: created.name + " v2", description: "Essai", instructions: "Réponds toujours en une phrase.", defaultModel: Live.model, color: "#4fd1a5"))257            #expect(p.name.hasSuffix("v2") && p.description == "Essai" && p.instructions == "Réponds toujours en une phrase." && p.defaultModel == Live.model && p.color == "#4fd1a5")258            let detail = try await env.api.projectDetail(created.id)259            #expect(detail.project.instructions == "Réponds toujours en une phrase." && detail.files.isEmpty)260            await env.catalog.refreshPresetsAndProjects()261            #expect(env.catalog.project(created.id)?.defaultModel == Live.model)262            // clearing: explicit nulls bring the fields back to "none"263            p = try await env.api.updateProject(created.id, patch: ProjectPatch(from: p, name: p.name, description: "", instructions: "", defaultModel: nil, color: nil))264            #expect(p.description == nil && p.instructions == nil && p.defaultModel == nil && p.color == nil)265        } catch { try? await env.api.deleteProject(created.id); throw error }266        try await env.api.deleteProject(created.id)267        await env.catalog.refreshPresetsAndProjects()268        #expect(env.catalog.project(created.id) == nil)269        do { _ = try await env.api.projectDetail(created.id); Issue.record("deleted project still served") } catch { #expect((error as? APIError)?.status == 404) }270    }271272    @Test func galleryAndResearchHistoryDecode() async throws {273        let env = Live.environment()274        let images = try await env.api.generatedImages()275        #expect(images.allSatisfy { !$0.id.isEmpty })276        let runs = try await env.api.researchRuns()277        #expect(runs.allSatisfy { !$0.id.isEmpty && !$0.question.isEmpty })278        if let first = runs.first { let full = try await env.api.research(first.id); #expect(full.id == first.id) }279        do { _ = try await env.api.research("rs_inexistant"); Issue.record("unknown research served") } catch { #expect((error as? APIError)?.status == 404) }280        // image models offered by the studio come from the catalogue281        await env.catalog.refreshModels()282        #expect(env.catalog.models.contains { $0.kind == "image" && $0.available })283    }284285    /// One real image call (cheapest model) through the edit path of `POST /api/images` — opt-in: SPCHAT_LIVE_IMAGE=1.286    /// (The generation path of the frozen backend build answers 500 after producing the image: it saves the287    /// attachment with an empty message id, which violates a foreign key. Reported; not exercised here.)288    @Test(.enabled(if: ProcessInfo.processInfo.environment["SPCHAT_LIVE_IMAGE"] == "1")) func aRealImageEditIsListedDownloadedAndDeleted() async throws {289        let env = Live.environment()290        let png = UIGraphicsImageRenderer(size: CGSize(width: 256, height: 256)).image { ctx in291            UIColor.darkGray.setFill(); ctx.fill(CGRect(x: 0, y: 0, width: 256, height: 256)); UIColor.systemPurple.setFill(); ctx.cgContext.fillEllipse(in: CGRect(x: 78, y: 78, width: 100, height: 100))292        }.pngData()!293        let source = try await env.api.upload(filename: "source.png", mime: "image/png", data: png, conversationId: nil, projectId: nil) { _ in }294        defer { Task { try? await env.api.deleteAttachment(source.id) } }295        let r = try await env.api.generateImage(prompt: "Change le cercle violet en cercle orange.", model: "gpt-image-1-mini", size: nil, quality: nil, editAttachmentId: source.id)296        let listed = try #require(try await env.api.generatedImages().first { $0.id == r.attachmentId })297        #expect(listed.editedFrom == source.id && listed.prompt?.contains("orange") == true && listed.model == r.model)298        #expect(await env.files.thumbnail(for: r.attachmentId, maxPixel: 256) != nil)299        try await env.api.deleteAttachment(r.attachmentId)300        #expect(try await env.api.generatedImages().contains { $0.id == r.attachmentId } == false)301    }302303    /// One real quick research with the cheapest verified model — opt-in: SPCHAT_LIVE_RESEARCH=1.304    @Test(.enabled(if: ProcessInfo.processInfo.environment["SPCHAT_LIVE_RESEARCH"] == "1")) func aRealQuickResearchRunsToItsReport() async throws {305        let env = Live.environment()306        let session = ResearchSession(api: env.api, waitUntilOnline: {})307        session.start(question: "Quelle est la dernière version stable de SQLite et sa date de sortie ?", modelId: Live.model, projectId: nil, depth: .quick)308        #expect(await TestEnv.wait(timeout: 30) { session.progress?.researchId != nil })309        #expect(await TestEnv.wait(timeout: 420) { !session.isFollowing })310        let run = try #require(session.finished)311        defer { Task { try? await env.api.deleteResearch(run.id); if let c = run.conversationId { try? await env.api.deleteConversation(c) } } }312        #expect(run.status == "complete" && (run.report?.count ?? 0) > 200 && !run.sources.isEmpty && run.plan != nil)313        #expect(session.progress?.stage == 5 && session.progress?.plan != nil && session.progress?.sources.contains { $0.fetched } == true)314        #expect(try await env.api.researchRuns().contains { $0.id == run.id })315        let md = String(decoding: try await env.api.researchExport(run.id, format: "md"), as: UTF8.self)316        #expect(md.contains("SQLite"))317        let conv = try #require(run.conversationId)318        #expect(try await env.api.conversation(conv).activeMessages.last?.status == .complete)319    }320}321
Files main
Menu

Theme