SPB Git

Repository Public

ParityRequestTests.swift 33.2 KB 507 lines swift

1// SP Notes Core2// File: Tests/SPNotesAPITests/ParityRequestTests.swift3// Description: Every parity endpoint sends the method, path, query string and body the server expects (checked on4//              the stub): databases, search, graph links, inbox, research, AI bookkeeping, agents, dashboard, settings.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import XCTest10@testable import SPNotesAPI1112final class ParityRequestTests: XCTestCase {13    private let db = "0d0d0d0d-0000-4000-8000-000000000001"14    private let row = "0d0d0d0d-0000-4000-8000-000000000002"1516    /// Answers every request with `body` and returns the API.17    private func api(_ body: String, status: Int = 200, headers: [String: String] = [:]) -> NotesAPI {18        StubServer.shared.reset { _ in .json(body, status: status, headers: headers) }19        return TestEnv.api().020    }2122    private func expect(_ method: String, _ path: String, query: String? = nil, body: String? = nil, file: StaticString = #filePath, line: UInt = #line) {23        guard let request = StubServer.shared.last else { return XCTFail("no request", file: file, line: line) }24        XCTAssertEqual(request.method, method, file: file, line: line)25        XCTAssertEqual(request.path, path, file: file, line: line)26        XCTAssertEqual(request.query, query, file: file, line: line)27        if let body {28            XCTAssertEqual(jsonObject(request.body), jsonObject(Data(body.utf8)), "body: \(request.bodyText)", file: file, line: line)29        } else {30            XCTAssertTrue(request.body.isEmpty, "unexpected body: \(request.bodyText)", file: file, line: line)31        }32        if method != "GET" { XCTAssertEqual(request.header("Origin"), "https://notes.test", file: file, line: line) }33    }3435    private let databaseJSON = #"{"id":"d","pageId":"p","name":"N"}"#36    private let propertyJSON = #"{"id":"x","databaseId":"d","name":"N","type":"text","config":{}}"#37    private let viewJSON = #"{"id":"v","databaseId":"d","name":"N","type":"table","config":{}}"#38    private let rowJSON = #"{"id":"r","pageId":"p","values":{}}"#39    private let referenceJSON = #"{"id":"r","citeKey":"k","title":"T"}"#4041    func testDatabaseRoutes() async throws {42        var api = api("[]")43        _ = try await api.databases()44        expect("GET", "/api/databases")45        _ = try await api.databaseTemplates()46        expect("GET", "/api/databases/templates")4748        api = self.api(databaseJSON)49        _ = try await api.database(id: db)50        expect("GET", "/api/databases/\(db)")51        _ = try await api.updateDatabase(id: db, DatabaseChanges(name: "N", description: .null, icon: .value("🏠"), isTemplate: false), idempotencyKey: "key-12345678")52        expect("PATCH", "/api/databases/\(db)", body: #"{"name":"N","description":null,"icon":"🏠","isTemplate":false}"#)53        XCTAssertEqual(StubServer.shared.last?.header("Idempotency-Key"), "key-12345678")54        _ = try await api.duplicateDatabase(id: db, DatabaseDuplicateOptions(withRows: true, title: "Copie", parentId: .null))55        expect("POST", "/api/databases/\(db)/duplicate", body: #"{"withRows":true,"title":"Copie","parentId":null}"#)56        _ = try await api.duplicateDatabase(id: db)57        expect("POST", "/api/databases/\(db)/duplicate", body: "{}")5859        api = self.api(#"{"applied":"tasks","properties":7}"#)60        _ = try await api.applyDatabaseTemplate(databaseID: db, template: "tasks")61        expect("POST", "/api/databases/\(db)/apply-template", body: #"{"template":"tasks"}"#)62    }6364    func testPropertyAndViewRoutes() async throws {65        var api = api(propertyJSON, status: 201)66        let config = DatabasePropertyConfig(options: [DatabaseSelectOption(id: "o1", name: "Loué", color: "green")])67        _ = try await api.createDatabaseProperty(databaseID: db, DatabasePropertyDraft(id: "x", name: "État", type: DatabasePropertyType.select, config: config, width: 160))68        expect("POST", "/api/databases/\(db)/properties", body: #"{"id":"x","name":"État","type":"select","config":{"options":[{"id":"o1","name":"Loué","color":"green"}]},"width":160}"#)69        _ = try await api.updateDatabaseProperty(databaseID: db, propertyID: "x", DatabasePropertyChanges(name: "Statut", width: .null))70        expect("PATCH", "/api/databases/\(db)/properties", body: #"{"id":"x","name":"Statut","width":null}"#)7172        api = self.api(#"{"ok":true}"#)73        _ = try await api.reorderDatabaseProperties(databaseID: db, order: ["a", "b"])74        expect("PATCH", "/api/databases/\(db)/properties", body: #"{"order":["a","b"]}"#)75        _ = try await api.deleteDatabaseProperty(databaseID: db, propertyID: "x")76        expect("DELETE", "/api/databases/\(db)/properties", query: "id=x")77        _ = try await api.deleteDatabaseView(databaseID: db, viewID: "v")78        expect("DELETE", "/api/databases/\(db)/views", query: "id=v")7980        api = self.api("[]")81        _ = try await api.databaseViews(databaseID: db)82        expect("GET", "/api/databases/\(db)/views")8384        api = self.api(viewJSON, status: 201)85        let viewConfig = DatabaseViewConfig(filter: .all([.rule("p", DatabaseFilterOp.gt, 5)]), sorts: [DatabaseSort(property: "p", descending: true)], groupBy: "s")86        _ = try await api.createDatabaseView(databaseID: db, DatabaseViewDraft(id: "v", name: "Par état", type: DatabaseViewType.board, config: viewConfig))87        expect("POST", "/api/databases/\(db)/views", body: #"{"id":"v","name":"Par état","type":"board","config":{"filter":{"and":[{"property":"p","op":"gt","value":5}]},"sorts":[{"property":"p","dir":"desc"}],"groupBy":"s"}}"#)88        _ = try await api.updateDatabaseView(databaseID: db, viewID: "v", DatabaseViewChanges(name: "Tableau", isDefault: true))89        expect("PATCH", "/api/databases/\(db)/views", body: #"{"id":"v","name":"Tableau","isDefault":true}"#)90    }9192    func testRowAndQueryRoutes() async throws {93        var api = api("[]")94        _ = try await api.databaseRowRefs(databaseID: db, search: "rue laurel", limit: 5)95        expect("GET", "/api/databases/\(db)/rows", query: "q=rue%20laurel&limit=5")9697        api = self.api(#"{"rows":[],"total":0,"limit":50,"offset":0}"#)98        _ = try await api.databaseRows(databaseID: db, limit: 50, offset: 100)99        expect("GET", "/api/databases/\(db)/rows", query: "full=1&limit=50&offset=100")100        _ = try await api.queryDatabase(id: db)101        expect("POST", "/api/databases/\(db)/query", body: "{}")102        let query = DatabaseQuery(viewId: "v", filter: .null, sorts: [DatabaseSort(property: "p")], search: "dalton", limit: 20, offset: 40)103        _ = try await api.queryDatabase(id: db, query)104        expect("POST", "/api/databases/\(db)/query", body: #"{"viewId":"v","filter":null,"sorts":[{"property":"p","dir":"asc"}],"search":"dalton","limit":20,"offset":40}"#)105        _ = try await api.queryDatabase(id: db, DatabaseQuery(filter: .value(.any([.rule(property: "p", op: DatabaseFilterOp.empty, value: nil)]))))106        expect("POST", "/api/databases/\(db)/query", body: #"{"filter":{"or":[{"property":"p","op":"empty"}]}}"#)107108        api = self.api(rowJSON, status: 201)109        _ = try await api.createDatabaseRow(databaseID: db, DatabaseRowDraft(id: row, pageId: "pg", title: "T", values: RawJSON(string: #"{"p":1}"#), icon: "🏠"), idempotencyKey: "key-12345678")110        expect("POST", "/api/databases/\(db)/rows", body: #"{"id":"\#(row)","pageId":"pg","title":"T","values":{"p":1},"icon":"🏠"}"#)111        _ = try await api.updateDatabaseRow(databaseID: db, rowID: row, values: RawJSON(string: #"{"p":null}"#))112        expect("PATCH", "/api/databases/\(db)/rows", body: #"{"id":"\#(row)","values":{"p":null}}"#)113114        api = self.api("[\(rowJSON)]", status: 201)115        _ = try await api.createDatabaseRows(databaseID: db, [DatabaseRowDraft(title: "A"), DatabaseRowDraft(title: "B")])116        expect("POST", "/api/databases/\(db)/rows", body: #"{"rows":[{"title":"A"},{"title":"B"}]}"#)117        _ = try await api.updateDatabaseRows(databaseID: db, [DatabaseRowUpdate(id: row, values: RawJSON(string: #"{"p":2}"#))])118        expect("PATCH", "/api/databases/\(db)/rows", body: #"{"updates":[{"id":"\#(row)","values":{"p":2}}]}"#)119120        api = self.api(#"{"ok":true,"deleted":2,"restored":2}"#)121        _ = try await api.reorderDatabaseRows(databaseID: db, order: ["b", "a"])122        expect("PATCH", "/api/databases/\(db)/rows", body: #"{"order":["b","a"]}"#)123        let deleted = try await api.deleteDatabaseRows(databaseID: db, ids: ["a", "b"])124        expect("DELETE", "/api/databases/\(db)/rows", query: "ids=a,b")125        XCTAssertEqual(deleted.deleted, 2)126        let restored = try await api.restoreDatabaseRows(databaseID: db, ids: ["a", "b"])127        expect("POST", "/api/databases/\(db)/rows/restore", body: #"{"ids":["a","b"]}"#)128        XCTAssertEqual(restored.restored, 2)129    }130131    func testDatabaseCSV() async throws {132        StubServer.shared.reset { _ in StubReply(status: 200, headers: ["Content-Type": "text/csv; charset=utf-8"], body: Data("\u{FEFF}Name,Prix\nA,1\n".utf8)) }133        let api = TestEnv.api().0134        let csv = try await api.databaseCSV(id: db, viewID: "v", search: "a")135        XCTAssertEqual(csv, "\u{FEFF}Name,Prix\nA,1\n")136        expect("GET", "/api/databases/\(db)/query", query: "format=csv&viewId=v&q=a")137        XCTAssertEqual(StubServer.shared.last?.header("Accept"), "text/csv")138139        let file = FileManager.default.temporaryDirectory.appendingPathComponent("spn-parity-\(UUID().uuidString).csv")140        try Data("Name,Prix\nImport,1\n".utf8).write(to: file)141        defer { try? FileManager.default.removeItem(at: file) }142        StubServer.shared.reset { _ in .json(#"{"created":1,"properties":["Prix"]}"#, status: 201) }143        let imported = try await api.importDatabaseCSV(databaseID: db, fileURL: file, filename: "biens.csv")144        XCTAssertEqual(imported, DatabaseCSVImportResult(created: 1, properties: ["Prix"]))145        let request = try XCTUnwrap(StubServer.shared.last)146        XCTAssertEqual(request.method, "POST")147        XCTAssertEqual(request.path, "/api/databases/\(db)/import")148        XCTAssertTrue(request.header("Content-Type")?.hasPrefix("multipart/form-data; boundary=") ?? false)149        XCTAssertTrue(request.bodyText.contains(#"name="file"; filename="biens.csv""#))150        XCTAssertTrue(request.bodyText.contains("Content-Type: text/csv\r\n\r\nName,Prix\nImport,1\n"))151    }152153    func testSearchRoutes() async throws {154        var api = api("[]")155        var query = SearchQuery("loyers gatineau", mode: .hybrid, limit: 12, semantic: false, section: .research, since: "2026-01-01", until: "2026-12-31", includeArchived: true)156        query.kinds = [SearchKind.page, SearchKind.reference]157        query.group = true158        _ = try await api.search(query)159        expect("GET", "/api/search", query: "q=loyers%20gatineau&mode=hybrid&limit=12&semantic=0&section=research&since=2026-01-01&until=2026-12-31&archived=1&kinds=page,reference&group=1")160        // The 1.x query is unchanged: no new parameter unless asked for.161        _ = try await api.search(SearchQuery("x"))162        expect("GET", "/api/search", query: "q=x&mode=quick")163        _ = try await api.search(.keywords("x", limit: 5, group: true))164        expect("GET", "/api/search", query: "q=x&mode=hybrid&limit=5&semantic=0&group=1")165        _ = try await api.duplicatePages(threshold: 0.9)166        expect("GET", "/api/search/duplicates", query: "threshold=0.9")167        _ = try await api.duplicatePages()168        expect("GET", "/api/search/duplicates")169170        api = self.api(#"{"pages":"3","health":{"pending":[],"failed":[]}}"#)171        let state = try await api.searchIndexState()172        expect("GET", "/api/search/index-state")173        XCTAssertEqual(state.pages, 3)174        api = self.api(#"{"ok":true,"queued":4}"#)175        let queued = try await api.reindexSearch()176        expect("POST", "/api/search/index-state", body: #"{"scope":"pending"}"#)177        XCTAssertEqual(queued.queued, 4)178        _ = try await api.reindexSearch(pendingOnly: false)179        expect("POST", "/api/search/index-state", body: #"{"scope":"all"}"#)180    }181182    func testGraphLinkRoutes() async throws {183        var api = api(#"{"pages":[],"mentions":[]}"#)184        _ = try await api.backlinks()185        expect("GET", "/api/graph/backlinks")186        _ = try await api.backlinks(search: "taux", pageID: "p")187        expect("GET", "/api/graph/backlinks", query: "q=taux&pageId=p")188189        api = self.api(#"{"ok":true,"id":"s","status":"accepted","fromId":"a","toId":"b"}"#)190        _ = try await api.resolveMention(.link, fromID: "a", toID: "b")191        expect("POST", "/api/graph/backlinks", body: #"{"action":"link","fromId":"a","toId":"b"}"#)192        _ = try await api.resolveMention(.undismiss, fromID: "a", toID: "b")193        expect("POST", "/api/graph/backlinks", body: #"{"action":"undismiss","fromId":"a","toId":"b"}"#)194        let decision = try await api.decideLinkSuggestion(id: "s", status: .accepted)195        expect("PATCH", "/api/graph/suggestions", body: #"{"id":"s","status":"accepted"}"#)196        XCTAssertEqual(decision.toId, "b")197        _ = try await api.decideLinkSuggestion(id: "s", status: .suggested)198        expect("PATCH", "/api/graph/suggestions", body: #"{"id":"s","status":"suggested"}"#)199200        api = self.api(#"{"nodes":[],"edges":[]}"#)201        _ = try await api.graphNeighbors(pageID: "p")202        expect("GET", "/api/graph/neighbors", query: "pageId=p")203        _ = try await api.graphNeighbors(pageID: "p", depth: 2, includeSuggestions: false, includeLinked: true)204        expect("GET", "/api/graph/neighbors", query: "pageId=p&depth=2&suggestions=0&linked=1")205206        api = self.api(#"{"items":[{"id":"s","fromId":"a","toId":"b","confidence":0.8}],"counts":{"suggested":1,"accepted":0,"rejected":0}}"#)207        let list = try await api.linkSuggestions()208        expect("GET", "/api/graph/suggestions", query: "status=suggested")209        XCTAssertEqual(list.items.first?.confidence, 0.8)210        _ = try await api.linkSuggestions(status: .rejected, pageID: "p")211        expect("GET", "/api/graph/suggestions", query: "status=rejected&pageId=p")212213        api = self.api(#"{"queued":true,"jobId":"j"}"#)214        let job = try await api.requestLinkSuggestions()215        expect("POST", "/api/graph/suggestions", body: #"{"action":"suggest"}"#)216        XCTAssertEqual(job.jobId, "j")217        _ = try await api.requestLinkSuggestions(pageID: "p", inline: true)218        expect("POST", "/api/graph/suggestions", body: #"{"action":"suggest","pageId":"p","inline":true}"#)219    }220221    func testInboxRoutes() async throws {222        var api = api(#"{"count":7}"#)223        let count = try await api.inboxCount()224        expect("GET", "/api/inbox", query: "count=1")225        XCTAssertEqual(count, 7)226227        api = self.api(#"{"id":"p","title":"T","kind":"screenshot"}"#, status: 201)228        let captured = try await api.capture(CaptureDraft(kind: CaptureKindName.screenshot, text: "T", attachmentIds: ["a"]), idempotencyKey: "key-12345678")229        expect("POST", "/api/capture", body: #"{"kind":"screenshot","text":"T","attachmentIds":["a"]}"#)230        XCTAssertEqual(StubServer.shared.last?.header("Idempotency-Key"), "key-12345678")231        XCTAssertEqual(captured.kind, "screenshot")232233        api = self.api(#"{"pageId":"p","status":"empty","ai":false,"suggestions":{"title":null,"tags":[],"destination":null,"relations":[],"summary":null}}"#)234        let empty = try await api.inboxSuggestions(id: "p")235        expect("GET", "/api/inbox/p/suggestions")236        XCTAssertEqual(empty.status, "empty")237        XCTAssertNil(empty.suggestions?.title)238        _ = try await api.inboxSuggestions(id: "p", refresh: true, cachedOnly: true, model: "claude-haiku-5-5")239        expect("GET", "/api/inbox/p/suggestions", query: "refresh=1&cachedOnly=1&model=claude-haiku-5-5")240241        api = self.api(#"{"actionId":"a","applied":["tags"],"filed":true}"#)242        let applied = try await api.applyInboxSuggestions(id: "p", InboxSuggestionSelection(tags: ["x"], destination: .init(section: "notes")))243        expect("POST", "/api/inbox/p/apply", body: #"{"tags":["x"],"destination":{"section":"notes"}}"#)244        XCTAssertEqual(applied.filed, true)245246        // A server without the AI workstream answers the HTML 404 page of Next.js.247        StubServer.shared.reset { _ in StubReply(status: 404, headers: ["Content-Type": "text/html; charset=utf-8"], body: Data("<!DOCTYPE html><html></html>".utf8)) }248        let missing = await captureAPIError { try await TestEnv.api().0.inboxSuggestions(id: "p", cachedOnly: true) }249        XCTAssertEqual(missing?.isRouteMissing, true)250        XCTAssertEqual(missing?.isNotFound, true)251    }252253    func testReferenceRoutes() async throws {254        var api = api("[]")255        _ = try await api.references()256        expect("GET", "/api/research/references")257        _ = try await api.references(pageID: "p")258        expect("GET", "/api/research/references", query: "pageId=p")259        _ = try await api.references(projectID: "p")260        expect("GET", "/api/research/references", query: "projectId=p")261        _ = try await api.referenceExtracts(referenceID: "r")262        expect("GET", "/api/research/references/r/extracts")263264        api = self.api(referenceJSON, status: 201)265        _ = try await api.createReference(ReferenceDraft(id: "r", pageId: "p", title: "T", authors: ["A B"], year: 2021, fields: RawJSON(string: #"{"volume":"12"}"#)))266        expect("POST", "/api/research/references", body: #"{"id":"r","pageId":"p","title":"T","authors":["A B"],"year":2021,"fields":{"volume":"12"}}"#)267        _ = try await api.reference(id: "r")268        expect("GET", "/api/research/references/r")269        _ = try await api.updateReference(id: "r", ReferenceChanges(pageId: .null, year: .value(2022), journal: .null, fields: RawJSON(string: #"{"pages":""}"#)))270        expect("PATCH", "/api/research/references/r", body: #"{"pageId":null,"year":2022,"journal":null,"fields":{"pages":""}}"#)271        _ = try await api.restoreReference(id: "r")272        expect("POST", "/api/research/references/r", query: "action=restore")273        _ = try await api.verifyReference(id: "r")274        expect("POST", "/api/research/references/r", query: "action=verify")275        _ = try await api.attachReferencePDF(id: "r", attachmentID: nil)276        expect("POST", "/api/research/references/r", query: "action=attach", body: #"{"attachmentId":null}"#)277        _ = try await api.attachReferencePDF(id: "r", attachmentID: "a")278        expect("POST", "/api/research/references/r", query: "action=attach", body: #"{"attachmentId":"a"}"#)279        let added = try await self.api(#"{"id":"r","citeKey":"k","title":"T","duplicate":true,"linked":true}"#).addReferenceByDOI("10.1/x", pageID: "p")280        expect("POST", "/api/research/references/doi", body: #"{"doi":"10.1/x","pageId":"p"}"#)281        XCTAssertTrue(added.duplicate && added.linked)282283        api = self.api(#"{"ok":true}"#)284        _ = try await api.deleteReference(id: "r")285        expect("DELETE", "/api/research/references/r")286287        api = self.api(#"{"attached":null,"citing":[],"experiments":[],"pdf":null}"#)288        _ = try await api.referenceLinks(id: "r")289        expect("GET", "/api/research/references/r/links")290291        api = self.api(#"{"doi":"10.1/x","duplicate":null}"#)292        _ = try await api.lookupDOI("10.1/x y")293        expect("GET", "/api/research/references/doi", query: "doi=10.1/x%20y")294295        api = self.api(#"{"extract":{"id":"e","quote":"q"},"extracts":[{"id":"e","quote":"q"}]}"#)296        _ = try await api.addReferenceExtract(referenceID: "r", ReferenceExtractDraft(id: "e", quote: "q", page: "p. 7"))297        expect("POST", "/api/research/references/r/extracts", body: #"{"id":"e","quote":"q","page":"p. 7"}"#)298        _ = try await api.updateReferenceExtract(referenceID: "r", extractID: "e", ReferenceExtractChanges(page: .value("p. 8"), note: .null))299        expect("PATCH", "/api/research/references/r/extracts", body: #"{"id":"e","page":"p. 8","note":null}"#)300        _ = try await api.deleteReferenceExtract(referenceID: "r", extractID: "e")301        expect("DELETE", "/api/research/references/r/extracts", query: "extractId=e")302        _ = try await api.restoreReferenceExtract(referenceID: "r", ReferenceExtract(id: "e", quote: "q", page: nil, note: nil, createdAt: "2026-11-19T18:45:54.880Z", updatedAt: nil))303        expect("POST", "/api/research/references/r/extracts", query: "restore=1", body: #"{"extract":{"id":"e","quote":"q","createdAt":"2026-11-19T18:45:54.880Z"}}"#)304    }305306    /// `references(ids:)` is right against both servers: the one that filters (and names the missing ids in a307    /// header) and the foundation one that ignores `ids` and answers the whole library.308    func testReferenceLookupByIDs() async throws {309        let rows = #"[{"id":"a","citeKey":"ka","title":"A","label":"A (2021)"},{"id":"b","citeKey":"kb","title":"B"}]"#310        var api = api(rows)311        var lookup = try await api.references(ids: ["a", "zz"])312        expect("GET", "/api/research/references", query: "ids=a,zz")313        XCTAssertEqual(lookup.references.map(\.id), ["a"], "rows that were not asked for are dropped")314        XCTAssertEqual(lookup.missingIDs, ["zz"], "computed when the server sends no header")315316        api = self.api(#"[{"id":"a","citeKey":"ka","title":"A","label":"A (2021)","citation":"A. (2021)."}]"#, headers: ["x-missing-ids": "zz, yy"])317        lookup = try await api.references(ids: ["a", "zz", "yy"])318        XCTAssertEqual(lookup.references.first?.label, "A (2021)")319        XCTAssertEqual(lookup.missingIDs, ["zz", "yy"])320321        StubServer.shared.reset { _ in .json("[]") }322        let none = try await TestEnv.api().0.references(ids: [])323        XCTAssertEqual(none, ReferenceLookup(references: [], missingIDs: []))324        XCTAssertEqual(StubServer.shared.requests.count, 0, "nothing to ask: no request")325    }326327    func testBibTeXAndLaTeXRoutes() async throws {328        var api = api(#"{"dryRun":true,"parsed":0,"created":[],"wouldCreate":[],"skipped":[],"failed":[]}"#)329        _ = try await api.importBibTeX(text: "@misc{a}", pageID: "p", dryRun: true)330        expect("POST", "/api/research/references/import-bibtex", body: #"{"text":"@misc{a}","pageId":"p","dryRun":true}"#)331        _ = try await api.importBibTeX(text: "@misc{a}")332        expect("POST", "/api/research/references/import-bibtex", body: #"{"text":"@misc{a}"}"#)333334        let file = FileManager.default.temporaryDirectory.appendingPathComponent("spn-parity-\(UUID().uuidString).bib")335        try Data("@misc{a}\n".utf8).write(to: file)336        defer { try? FileManager.default.removeItem(at: file) }337        _ = try await api.importBibTeX(fileURL: file, pageID: "p", dryRun: true)338        let upload = try XCTUnwrap(StubServer.shared.last)339        XCTAssertEqual(upload.path, "/api/research/references/import-bibtex")340        XCTAssertTrue(upload.bodyText.contains("name=\"pageId\"\r\n\r\np\r\n"))341        XCTAssertTrue(upload.bodyText.contains("name=\"dryRun\"\r\n\r\n1\r\n"))342        XCTAssertTrue(upload.bodyText.contains("@misc{a}\n"))343344        StubServer.shared.reset { _ in StubReply(status: 200, headers: ["Content-Type": "application/x-bibtex; charset=utf-8", "x-export-count": "2", "Content-Disposition": #"attachment; filename="library.bib""#], body: Data("@misc{a}\n".utf8)) }345        api = TestEnv.api().0346        let bib = try await api.exportBibTeX(projectID: "p")347        expect("GET", "/api/research/references/export.bib", query: "projectId=p")348        XCTAssertEqual(bib, BibTeXExport(text: "@misc{a}\n", count: 2, suggestedFilename: "library.bib"))349        _ = try await api.exportBibTeX(pageID: "p")350        expect("GET", "/api/research/references/export.bib", query: "pageId=p")351352        let report = #"{"pages":2,"sections":1,"citeKeys":0,"missingKeys":0,"missingRefs":0,"figures":0,"hypotheses":0,"experiments":0,"unknownNodes":[]}"#353        StubServer.shared.reset { _ in StubReply(status: 200, headers: ["Content-Type": "application/x-tex", "x-export-report": report, "x-bib-url": "/api/research/references/export.bib?projectId=p"], body: Data("\\documentclass{article}".utf8)) }354        let tex = try await TestEnv.api().0.exportLaTeX(projectID: "p")355        expect("GET", "/api/research/export.tex", query: "projectId=p&inline=1")356        XCTAssertEqual(tex.tex, "\\documentclass{article}")357        XCTAssertEqual(tex.report?.pages, 2)358        XCTAssertEqual(tex.bibURL, "/api/research/references/export.bib?projectId=p")359360        // The `format=json` body is only sketched by the contract (no recorded example): keys from the document.361        api = self.api(#"{"projectId":"p","title":"T","tex":"x","bib":"","citeKeys":[],"missingKeys":["k"],"missingRefs":[],"figures":[{"attachmentId":"a","name":"n.png","file":"n.png"}],"sections":1,"hypotheses":0,"experiments":0,"unknownNodes":[],"bibUrl":"/b"}"#)362        let bundle = try await api.exportLaTeXBundle(projectID: "p")363        expect("GET", "/api/research/export.tex", query: "projectId=p&format=json&inline=1")364        XCTAssertEqual(bundle.missingKeys, ["k"])365        XCTAssertEqual(bundle.figures?.first?.file, "n.png")366    }367368    func testExperimentTaskAndPaperRoutes() async throws {369        var api = api("[]")370        _ = try await api.experiments(pageID: "p")371        expect("GET", "/api/research/experiments", query: "pageId=p")372        _ = try await api.researchTasks(pageID: "p")373        expect("GET", "/api/research/tasks", query: "pageId=p")374        _ = try await api.researchOverview()375        expect("GET", "/api/research/overview")376377        api = self.api(#"{"id":"e","name":"N"}"#)378        _ = try await api.createExperiment(ExperimentDraft(pageId: "p", name: "N", status: ExperimentStatus.running, params: RawJSON(string: #"{"p":1}"#)))379        expect("POST", "/api/research/experiments", body: #"{"pageId":"p","name":"N","status":"running","params":{"p":1}}"#)380        _ = try await api.updateExperiment(id: "e", ExperimentChanges(status: ExperimentStatus.done, notes: .null))381        expect("PATCH", "/api/research/experiments/e", body: #"{"status":"done","notes":null}"#)382        _ = try await self.api(#"{"ok":true}"#).deleteExperiment(id: "e")383        expect("DELETE", "/api/research/experiments/e")384385        let taskJSON = #"{"id":"t","title":"T","status":"todo","createdAt":"2026-11-19T18:00:00.000Z","updatedAt":"2026-11-19T18:00:00.000Z"}"#386        api = self.api(taskJSON, status: 201)387        _ = try await api.createResearchTask(pageID: "p", ResearchTaskDraft(title: "T", status: .doing, priority: .high, dueAt: "2026-12-05", project: "wp"))388        expect("POST", "/api/research/tasks", body: #"{"pageId":"p","title":"T","status":"doing","priority":"high","dueAt":"2026-12-05","project":"wp"}"#)389        _ = try await api.restoreTask(id: "t")390        expect("POST", "/api/research/tasks/t", query: "action=restore")391        _ = try await self.api("[\(taskJSON)]", status: 201).createResearchTasks(pageID: "p", [ResearchTaskDraft(title: "A"), ResearchTaskDraft(title: "B", priority: .low)])392        expect("POST", "/api/research/tasks", body: #"{"pageId":"p","items":[{"title":"A"},{"title":"B","priority":"low"}]}"#)393    }394395    func testAIBookkeepingRoutes() async throws {396        var api = api("[]")397        _ = try await api.aiConversations()398        expect("GET", "/api/ai/conversations")399        _ = try await api.aiConversations(pageID: "p")400        expect("GET", "/api/ai/conversations", query: "pageId=p")401402        api = self.api(#"{"id":"c","title":"T","messages":[]}"#)403        let detail = try await api.aiConversation(id: "c")404        expect("GET", "/api/ai/conversations", query: "id=c")405        XCTAssertEqual(detail.conversation.title, "T")406407        api = self.api(#"{"ok":true}"#)408        _ = try await api.updateAIConversation(id: "c", AIConversationChanges(title: "Nouveau", pinned: true, model: .null))409        expect("PATCH", "/api/ai/conversations", body: #"{"id":"c","title":"Nouveau","pinned":true,"model":null}"#)410        _ = try await api.deleteAIConversation(id: "c")411        expect("DELETE", "/api/ai/conversations", query: "id=c")412        _ = try await api.restoreAIConversation(id: "c")413        expect("DELETE", "/api/ai/conversations", query: "id=c&restore=1")414415        api = self.api(#"{"days":7,"byModel":[],"byDay":[],"byTask":[],"recent":[]}"#)416        _ = try await api.aiUsage(days: 7)417        expect("GET", "/api/ai/usage", query: "days=7")418        _ = try await api.aiUsage()419        expect("GET", "/api/ai/usage")420421        api = self.api(#"{"task":"chat","expensive":{"reason":"long context"},"error":null}"#)422        let plan = try await api.aiChatPlan(mode: .notes, pageID: "p", model: "m", chars: 1200, images: 1)423        expect("GET", "/api/ai/chat/plan", query: "mode=notes&pageId=p&model=m&chars=1200&images=1")424        XCTAssertTrue(plan.needsConfirmation)425        _ = try await api.aiActionPlan(.summarize, chars: 4000)426        expect("GET", "/api/ai/chat/plan", query: "action=summarize&chars=4000")427        _ = try await self.api(#"{"fix":{"task":"quick"}}"#).aiActionPlans(chars: 800)428        expect("GET", "/api/ai/chat/plan", query: "actions=1&chars=800")429    }430431    func testAgentRoutes() async throws {432        var api = api(#"{"agents":[],"executions":[]}"#)433        _ = try await api.agents(limit: 5)434        expect("GET", "/api/agents", query: "limit=5")435436        api = self.api(#"{"id":"e","status":"pending"}"#, status: 201)437        let run = try await api.runAgent("suggest_tags", pageID: "p", confirmCost: true)438        expect("POST", "/api/agents", body: #"{"agent":"suggest_tags","pageId":"p","confirmCost":true}"#)439        XCTAssertEqual(run.id, "e")440441        // Without the owner's confirmation nothing is started: the flag is not even sent.442        StubServer.shared.reset { _ in .json(#"{"error":"Confirm the scope and the cost limit before starting","code":"confirm_required"}"#, status: 409) }443        let refused = await captureAPIError { try await TestEnv.api().0.runAgent("sort_inbox", confirmCost: false) }444        expect("POST", "/api/agents", body: #"{"agent":"sort_inbox"}"#)445        XCTAssertEqual(refused?.needsCostConfirmation, true)446447        api = self.api(#"{"id":"e","status":"awaiting_approval","proposedChanges":[{"idx":0,"status":"proposed"}]}"#)448        let execution = try await api.agentExecution(id: "e")449        expect("GET", "/api/agents/e")450        XCTAssertEqual(execution.pendingProposals.count, 1)451452        api = self.api(#"{"status":"approved","applied":[0],"failed":[],"pending":0,"undone":[0],"ok":true}"#)453        _ = try await api.approveAgentProposals(executionID: "e", changes: [0, 2], confirmDestructive: true)454        expect("POST", "/api/agents/e", body: #"{"action":"approve","changes":[0,2],"confirmDestructive":true}"#)455        _ = try await api.approveAgentProposals(executionID: "e", changes: [1])456        expect("POST", "/api/agents/e", body: #"{"action":"approve","changes":[1]}"#)457        _ = try await api.rejectAgentProposals(executionID: "e", changes: [1])458        expect("POST", "/api/agents/e", body: #"{"action":"reject","changes":[1]}"#)459        _ = try await api.undoAgentProposals(executionID: "e", changes: [0])460        expect("POST", "/api/agents/e", body: #"{"action":"undo","changes":[0]}"#)461        _ = try await api.cancelAgentExecution(id: "e")462        expect("POST", "/api/agents/e", body: #"{"action":"cancel"}"#)463    }464465    func testWorkspaceRoutes() async throws {466        var api = api("[]")467        _ = try await api.pages(view: .section(.research), limit: 5)468        expect("GET", "/api/pages", query: "view=section:research&limit=5")469        _ = try await api.pages(view: .children("p"))470        expect("GET", "/api/pages", query: "view=children:p")471        _ = try await api.trashedPages()472        expect("GET", "/api/pages", query: "view=trash&limit=100")473        _ = try await api.auditLog(limit: 20)474        expect("GET", "/api/settings/audit", query: "limit=20")475476        api = self.api(#"{"ok":true,"purged":3,"remaining":1,"autoPurgeDays":30}"#)477        let purge = try await api.purgeOldTrash()478        expect("POST", "/api/trash", body: #"{"action":"purge-old"}"#)479        XCTAssertEqual(purge.remaining, 1)480        _ = try await api.purgeOldTrash(days: 90)481        expect("POST", "/api/trash", body: #"{"action":"purge-old","days":90}"#)482483        api = self.api("{}")484        _ = try await api.dashboard()485        expect("GET", "/api/dashboard")486        api = self.api(#"{"widgets":[],"custom":false}"#)487        _ = try await api.saveDashboardLayout([DashboardWidget(id: "w", type: DashboardWidgetType.tasksDue, size: "half", config: RawJSON(string: #"{"days":7}"#))])488        expect("PUT", "/api/dashboard", body: #"{"widgets":[{"id":"w","type":"tasks_due","size":"half","config":{"days":7}}]}"#)489        _ = try await api.resetDashboardLayout()490        expect("PUT", "/api/dashboard", body: #"{"reset":true}"#)491492        let none = try await self.api("null").dashboardSummary()493        expect("GET", "/api/dashboard/summary")494        XCTAssertNil(none)495        let digest = try await self.api(#"{"text":"**Semaine**","model":"m","costUsd":0.01,"at":"2026-11-19T18:00:00.000Z","pages":4,"tasks":2}"#).dashboardSummary()496        XCTAssertEqual(digest?.pages, 4)497        XCTAssertNotNil(digest?.at)498499        api = self.api(#"{"id":"u","username":"simon"}"#)500        _ = try await api.settings()501        expect("GET", "/api/settings")502        api = self.api(#"{"displayName":"N","email":null,"preferences":{}}"#)503        _ = try await api.updateSettings(SettingsChanges(displayName: "N", email: .null, preferences: RawJSON(string: #"{"spnotes.mac":{"sidebar":true}}"#)))504        expect("PATCH", "/api/settings", body: #"{"displayName":"N","email":null,"preferences":{"spnotes.mac":{"sidebar":true}}}"#)505    }506}507
Files main
Menu

Theme