SPB Git

Repository Public

LiveFeaturesSmokeTests.swift 12.8 KB 214 lines swift

1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/LiveFeaturesSmokeTests.swift3// Description: Smoke test of the feature view models against the real INTEGRATION backend (scratch database, never4//              production): every screen's main load, and a few create / delete round trips (task, canvas, reference).5//              Nothing paid is called (no ask, no AI summary, no semantic search, no transcription). Skipped unless6//              SPN_LIVE_URL and SPN_LIVE_TOKEN are set; everything it creates is deleted at the end.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//11// Run:12//   ssh -f -N -L 8486:127.0.0.1:8486 M4M64c13//   SPN_LIVE_URL=http://localhost:8486 SPN_LIVE_TOKEN=<dev token> swift test --filter LiveFeatures14import Foundation15import SPNotesAPI16import SPNotesDocument17import SPNotesStore18import SPNotesSync19import Testing20@testable import SPNotesFeatures21@testable import SPNotesFeaturesCatalog2223private final class LiveWorld: @unchecked Sendable {24    static var enabled: Bool {25        let env = ProcessInfo.processInfo.environment26        guard let url = env["SPN_LIVE_URL"].flatMap(URL.init(string:)), let host = url.host, env["SPN_LIVE_TOKEN"]?.isEmpty == false else { return false }27        return !host.hasSuffix("spboucher.ai")28    }2930    let directory: URL31    let store: NotesStore32    let api: NotesAPI33    let engine: SyncEngine34    let repositories: NotesRepositories3536    init() throws {37        let env = ProcessInfo.processInfo.environment38        directory = FileManager.default.temporaryDirectory.appendingPathComponent("spn-live-features-\(UUID().uuidString)")39        try FileManager.default.createDirectory(at: directory.appendingPathComponent("files"), withIntermediateDirectories: true)40        store = try NotesStore(url: directory.appendingPathComponent("notes.sqlite"))41        api = NotesAPI(client: HTTPClient(configuration: APIConfiguration(baseURL: URL(string: env["SPN_LIVE_URL"]!)!, userAgent: APIConfiguration.userAgent(appVersion: "2.0.0")),42                                          tokenStore: InMemoryTokenStore(token: env["SPN_LIVE_TOKEN"])))43        engine = SyncEngine(store: store, api: api, files: FeatureWorldFiles(root: directory.appendingPathComponent("files")))44        repositories = NotesRepositories(store: store, api: api, engine: engine)45    }4647    deinit { try? FileManager.default.removeItem(at: directory) }48}4950/// A load is healthy when it ended loaded, or when the integration server honestly does not have the feature.51private func healthy(_ phase: LoadPhase) -> Bool {52    if phase == .loaded { return true }53    if case .failed(let failure) = phase { return failure.kind == .unsupported }54    return false55}5657@Suite("Live: feature view models against the integration backend", .serialized)58struct LiveFeaturesSmokeTests {59    @Test("read-only: every screen's model loads from the real server", .enabled(if: LiveWorld.enabled))60    @MainActor func reads() async throws {61        let world = try LiveWorld()62        #expect(await world.engine.sync() == .completed)63        let repos = world.repositories64        var report: [String] = []65        func note(_ name: String, _ phase: LoadPhase, _ detail: String) {66            report.append("\(name): \(phase == .loaded ? "loaded" : String(describing: phase)) — \(detail)")67            #expect(healthy(phase), "\(name): \(phase)")68        }6970        let tasks = TasksModel(repositories: repos); await tasks.load()71        note("tasks", tasks.phase, "\(tasks.tasks.count) tasks")72        let inbox = InboxModel(repositories: repos); await inbox.load()73        note("inbox", inbox.phase, "\(inbox.items.count) items")74        let databases = try await repos.databases.list()75        if let first = databases.first {76            let database = DatabaseModel(repositories: repos, databaseId: first.id); await database.load()77            note("database", database.phase, "\(database.rows.count) rows, \(database.database?.views.count ?? 0) views")78        } else { report.append("database: no database on the server") }79        let search = UnifiedSearchModel(repositories: repos, debounce: .milliseconds(1)); await search.load()80        search.query = "note"; await search.submit()81        #expect(search.semantic == false)82        report.append("search: \(search.results.count) results for « note » (lexical, free)")8384        for view in [GraphView.global, GraphView.timeline, GraphView.concepts, GraphView.documents, GraphView.references] {85            let graph = GraphModel(repositories: repos, view: view); await graph.load()86            note("graph/\(view)", graph.phase, "\(graph.nodes.count) nodes, \(graph.edges.count) edges")87        }88        let insights = GraphModel(repositories: repos); await insights.loadInsights()89        note("graph insights", insights.insightsPhase, "\(insights.insights?.insights.count ?? 0) insights")90        let constellation = ConstellationModel(repositories: repos); await constellation.load()91        note("constellation", constellation.phase, constellation.caption ?? "")92        let timeline = TimelineModel(repositories: repos); await timeline.load()93        note("timeline", timeline.phase, "\(timeline.events.count) events, more: \(timeline.canLoadMore)")94        let health = KnowledgeHealthModel(repositories: repos); await health.load()95        note("health", health.phase, "healthy: \(health.isHealthy)")96        let brief = DailyBriefModel(repositories: repos); await brief.load()97        // The server may hand back a summary generated earlier (stored with the brief): it is shown under the AI badge;98        // this test itself never asks for one.99        note("brief", brief.phase, "\(brief.taskCount) tasks; stored AI summary present: \(brief.summary != nil); requested here: no")100101        let picker = ModelPickerModel(repositories: repos); await picker.load()102        note("models", picker.phase, "\(picker.catalog?.models.count ?? 0) models in \(picker.groups.count) groups")103        let research = ResearchModel(repositories: repos); await research.load()104        note("research", research.phase, "\(research.references.count) references")105        let ask = AskModel(repositories: repos); await ask.load()106        note("ask history", ask.phase, "\(ask.conversations.count) conversations; nothing sent")107        #expect(ask.turns.isEmpty)108109        report.append("zoom / time machine / database / search hit: exercised in the round-trip test on pages it creates")110        print("LIVE FEATURES READS\n" + report.joined(separator: "\n"))111    }112113    @Test("round trips on the scratch database: a task, a canvas and a reference are created through the models, then deleted", .enabled(if: LiveWorld.enabled))114    @MainActor func roundTrips() async throws {115        let world = try LiveWorld()116        #expect(await world.engine.sync() == .completed)117        let repos = world.repositories118        let tag = String(UUID().uuidString.prefix(6))119120        // 1. task: created offline-first through the model, pushed by a sync, deleted, pushed again121        let tasks = TasksModel(repositories: repos); await tasks.load()122        tasks.draftTitle = "Live features · tâche \(tag)"123        #expect(await tasks.add())124        #expect(await world.engine.sync() == .completed)125        await tasks.load()126        let created = try #require(tasks.tasks.first { $0.title.hasSuffix(tag) })127        #expect(try await world.api.tasks().contains { $0.id == created.id })128        await tasks.delete(id: created.id)129        #expect(await world.engine.sync() == .completed)130        #expect(try await world.api.tasks().contains { $0.id == created.id } == false)131132        // 2. canvas: created, edited through the canvas model, saved, read back from the server, trashed133        let pageId = try await repos.canvases.create(title: "Live features · canvas \(tag)")134        do {135            #expect(await world.engine.sync() == .completed)136            let canvas = CanvasModel(repositories: repos, pageId: pageId)137            canvas.saveDelay = .milliseconds(1)138            await canvas.load()139            #expect(canvas.phase == .loaded)140            canvas.addNode(.text) { $0.text = "Bonjour \(tag)" }141            canvas.addNode(.shape) { $0.shape = .diamond }142            let ids = canvas.document.nodes.map(\.id)143            #expect(ids.count == 2)144            canvas.connect(from: ids[0], to: ids[1])145            await canvas.saveNow()146            #expect(await world.engine.sync() == .completed)147            let remote = try await world.api.canvas(pageID: pageId)148            let document = try CanvasDocument(data: remote.data.data)149            #expect(document.nodes.count == 2)150            #expect(document.edges.count == 1)151            #expect(document.nodes.contains { $0.text == "Bonjour \(tag)" })152        } catch {153            _ = try? await world.api.trashPage(id: pageId)154            throw error155        }156        _ = try await world.api.trashPage(id: pageId)157158        // 3. reference: created through the research model, found again, deleted159        let research = ResearchModel(repositories: repos); await research.load()160        research.startNew()161        research.form.title = "Live features · référence \(tag)"162        research.form.authors = "Boucher, Simon-Pierre"163        research.form.year = "2026"164        #expect(await research.saveForm(), "\(String(describing: research.actionFailure))")165        let reference = try #require(research.references.first { $0.title.hasSuffix(tag) })166        #expect(await research.delete(reference))167        #expect(research.references.contains { $0.id == reference.id } == false)168169        // 4. a note with two sections: outline (zoom 2), time machine, local graph, health, search hit — then trashed170        let noteId = NotesAPI.newID()171        let content = """172        {"type":"doc","content":[{"type":"heading","attrs":{"id":"h1","level":1},"content":[{"type":"text","text":"Volatilité \(tag)"}]},{"type":"paragraph","attrs":{"id":"p1"},"content":[{"type":"text","text":"Première phrase de la section. Deuxième phrase."}]},{"type":"heading","attrs":{"id":"h2","level":2},"content":[{"type":"text","text":"Méthode"}]},{"type":"paragraph","attrs":{"id":"p2"},"content":[{"type":"text","text":"Un modèle GARCH zeta\(tag) simple."}]}]}173        """174        _ = try await world.api.createPage(PageDraft(id: noteId, title: "Live features · note \(tag)", content: RawJSON(string: content)))175        var databaseHost: String?176        do {177            #expect(await world.engine.sync() == .completed)178            let zoom = SemanticZoomModel(repositories: repos, pageId: noteId); await zoom.load()179            #expect(zoom.outlinePhase == .loaded, "\(zoom.outlinePhase)")180            #expect(zoom.sections.count >= 2)181            #expect(zoom.synopsis == nil)   // level 1 is AI: never generated here182            let machine = TimeMachineModel(repositories: repos, scope: .page(noteId)); await machine.load()183            #expect(machine.phase == .loaded, "\(machine.phase)")184            let local = GraphModel(repositories: repos, view: GraphView.local, pageId: noteId); await local.load()185            #expect(local.phase == .loaded, "\(local.phase)")186            #expect(local.nodes.contains { $0.id == noteId })187            let timeline = TimelineModel(repositories: repos, scope: .page(noteId)); await timeline.load()188            #expect(timeline.events.contains { $0.kind == "page.created" })189            let search = UnifiedSearchModel(repositories: repos, debounce: .milliseconds(1)); await search.load()190            search.query = "zeta\(tag)"; await search.submit()191            #expect(search.results.contains { $0.pageId == noteId }, "\(search.results.map(\.title))")192193            // 5. a database: host page, a row created and renamed through the model, deleted, restored, deleted194            let host = try await world.api.createPage(PageDraft(id: NotesAPI.newID(), title: "Live features · base \(tag)", section: .databases, type: .database)).value.id195            databaseHost = host196            let database = DatabaseModel(repositories: repos, databaseId: host); await database.load()197            #expect(database.phase == .loaded, "\(database.phase)")198            #expect(await database.createRow(title: "Ligne \(tag)"), "\(String(describing: database.actionFailure))")199            let row = try #require(database.rows.first { $0.title == "Ligne \(tag)" })200            #expect(await database.deleteRows([row.id]))201            #expect(database.rows.contains { $0.id == row.id } == false)202            #expect(await database.undoDelete())203            #expect(database.rows.contains { $0.id == row.id })204            #expect(await database.deleteRows([row.id]))205        } catch {206            _ = try? await world.api.trashPage(id: noteId)207            if let databaseHost { _ = try? await world.api.trashPage(id: databaseHost) }208            throw error209        }210        _ = try await world.api.trashPage(id: noteId)211        if let databaseHost { _ = try await world.api.trashPage(id: databaseHost) }212    }213}214
Files main
Menu

Theme