Repository Public
1// SP Notes Core2// File: Tests/SPNotesDocumentTests/NextNodeTests.swift3// Description: The 3.0 nodes (SPEC §2): Markdown, plain text, word count and HTML against expectations written by4// hand from the specification, parity with outputs recorded from the server's own code, the lossless5// round trip (unknown attributes inside known nodes), typed views, schema and block ids.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11@testable import SPNotesDocument1213private func node(_ json: String) throws -> PMNode { try PMNode(data: Data(json.utf8)) }14private func doc(_ blocks: String) throws -> NoteDocument { try NoteDocument(json: Data(#"{"type":"doc","content":[\#(blocks)]}"#.utf8)) }1516@Suite struct NextNodeExportTests {17 // Written by hand from SPEC §2 — not produced by the code under test.18 static let expectedMarkdown = """19 # Atelier du 19 novembre2021 Comme le montre [@Black & Scholes 1973] et [@0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4e], puis [@?].2223 ```mermaid24 graph TD25 A-->B26 ```2728 ```javascript29 console.log(1 + 1)30 ```3132 ```output33 234 ```3536 ```python37 print('x')38 ```3940 Ventes par trimestre4142 | Trimestre | Ventes | Marge |43 | --- | --- | --- |44 | T1 | 120 | 0.25 |45 | T2 | 135.5 | |46 | T3 \\| été | 1 000 | |4748 [Graphique]4950 5152 [Dessin]5354 [PDF: Rapport annuel.pdf](/api/files/44444444-2222-4333-8444-555555555555)5556 > p.2 — La liquidité diminue — À vérifier57 > p.7 — Contredit le chapitre 258 > p.95960 [Audio: Réunion budget](/api/files/55555555-2222-4333-8444-555555555555)6162 [00:00] Bonjour à tous63 [01:05] Le budget est adopté64 [125:03] Fin de la séance6566 [Vue: Tâches ouvertes]6768 [Vue]6970 [[66666666-2222-4333-8444-555555555555#Xy_-12abCD]]7172 [[]]7374 [Canvas](/p/77777777-2222-4333-8444-555555555555)7576 - [ ] Relancer le client77 - [x] Ancienne tâche 2.x7879 > [!DECISION] ⚖️80 > On retient l'option B.8182 > [!AI] claude-haiku83 > Synthèse générée.8485 ## Références8687 """8889 static let expectedText = """90 Atelier du 19 novembre91 Comme le montre Black & Scholes 1973 et , puis .92 graph TD93 A-->B94 console.log(1 + 1)95 296 print('x')97 Ventes par trimestre98 Trimestre Ventes Marge99 T1 120 0.25100 T2 135.5101 T3 | été 1 000102103 Dessin104 Dessin105 PDF: Rapport annuel.pdf106 p.2 — La liquidité diminue — À vérifier107 p.7 — Contredit le chapitre 2108 p.9109 Audio: Réunion budget110 Bonjour à tous111 Le budget est adopté112 Fin de la séance113 Vue: Tâches ouvertes114 Vue115 116 Canvas117 Relancer le client118 Ancienne tâche 2.x119 On retient l'option B.120 Synthèse générée.121 Références122 """123124 @Test func markdownFollowsTheSpecification() throws {125 let d = try Fixture.doc("next-nodes")126 #expect(d.markdown() == Self.expectedMarkdown)127 }128129 @Test func plainTextFollowsTheSpecification() throws {130 let d = try Fixture.doc("next-nodes")131 #expect(d.plainText() == Self.expectedText)132 // Transcript and annotation text are indexed; ids, time codes and attachment paths are not.133 let text = d.plainText()134 for indexed in ["Le budget est adopté", "La liquidité diminue", "À vérifier", "Contredit le chapitre 2", "graph TD", "Ventes par trimestre", "Tâches ouvertes"] {135 #expect(text.contains(indexed), "\(indexed) must be searchable")136 }137 for hidden in ["44444444", "/api/files", "01:05", "Xy_-12abCD", "whisper", "Budget adopté.", "#ffd54a"] {138 #expect(!text.contains(hidden), "\(hidden) must not be indexed")139 }140 #expect(d.wordCount == NoteDocument.wordCount(of: Self.expectedText))141 #expect(d.wordCount == 94) // counted by hand on the text above142 }143144 @Test func htmlOfEachNode() throws {145 let d = try Fixture.doc("next-nodes")146 let html = d.htmlBody()147 let expected = [148 #"<span class="nx nx-citation">[Black & Scholes 1973, p. 12]</span>"#,149 #"<span class="nx nx-citation">[0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4E]</span>"#,150 #"<span class="nx nx-citation">[?]</span>"#,151 #"<figure class="nx nx-mermaid"><img src="/api/files/11111111-2222-4333-8444-555555555555" alt="Diagramme"><pre><code class="language-mermaid">graph TD\#n A-->B</code></pre></figure>"#,152 #"<div class="nx nx-runcode"><pre><code class="language-javascript">console.log(1 + 1)</code></pre><pre class="nx-output"><code>2</code></pre></div>"#,153 #"<div class="nx nx-runcode"><pre><code class="language-python">print('x')</code></pre></div>"#,154 #"<figure class="nx nx-chart"><figcaption>Ventes par trimestre</figcaption><table><tr><th>Trimestre</th><th>Ventes</th><th>Marge</th></tr><tr><td>T1</td><td>120</td><td>0.25</td></tr><tr><td>T2</td><td>135.5</td><td></td></tr><tr><td>T3 | été</td><td>1 000</td><td></td></tr></table></figure>"#,155 #"<figure class="nx nx-chart"></figure>"#,156 #"<figure class="nx nx-drawing"><img src="/api/files/33333333-2222-4333-8444-555555555555" alt="Dessin"></figure>"#,157 #"<p class="nx nx-drawing">[Dessin]</p>"#,158 #"<div class="nx nx-pdf"><p class="file">📎 <a href="/api/files/44444444-2222-4333-8444-555555555555">PDF: Rapport annuel.pdf</a></p><ul><li>p.2 — La liquidité diminue — À vérifier</li><li>p.7 — Contredit le chapitre 2</li><li>p.9</li></ul></div>"#,159 #"<div class="nx nx-audio"><p class="file">🎙 <a href="/api/files/55555555-2222-4333-8444-555555555555">Audio: Réunion budget</a></p><p class="nx-seg"><small>[00:00]</small> Bonjour à tous</p><p class="nx-seg"><small>[01:05]</small> Le budget est adopté</p><p class="nx-seg"><small>[125:03]</small> Fin de la séance</p></div>"#,160 #"<p class="nx nx-query">[Vue: Tâches ouvertes]</p>"#,161 #"<p class="nx nx-query">[Vue]</p>"#,162 #"<p class="nx nx-blockref"><a href="/p/66666666-2222-4333-8444-555555555555#block-Xy_-12abCD">↗ 66666666-2222-4333-8444-555555555555#Xy_-12abCD</a></p>"#,163 #"<p class="nx nx-blockref">Référence introuvable</p>"#,164 #"<p class="nx nx-canvas"><a href="/p/77777777-2222-4333-8444-555555555555">Canvas</a></p>"#,165 #"<div class="callout callout-decision">"#,166 #"<h2 class="nx nx-bibliography">Références</h2>"#,167 ]168 var cursor = html.startIndex169 for piece in expected {170 guard let range = html.range(of: piece, range: cursor..<html.endIndex) else {171 Issue.record("missing or out of order in the HTML: \(piece)")172 continue173 }174 cursor = range.upperBound175 }176 #expect(d.html(title: "T").contains(".nx{"))177 #expect(!html.contains("<script"))178 }179180 @Test func edgeCasesOfTheTextRules() throws {181 // Time codes: floor, no cap on minutes, invalid → 00:00.182 #expect(NextNodes.timecode(.double(59.99)) == "00:59")183 #expect(NextNodes.timecode(.int(60)) == "01:00")184 #expect(NextNodes.timecode(.int(3600)) == "60:00")185 #expect(NextNodes.timecode(.int(-5)) == "00:00")186 #expect(NextNodes.timecode(.string("12")) == "00:00")187 #expect(NextNodes.timecode(nil) == "00:00")188 #expect(NextNodes.timecode(.double(.nan)) == "00:00")189 // Cells.190 #expect(NextNodes.cellText(.double(3.0)) == "3")191 #expect(NextNodes.cellText(.double(0.1)) == "0.1")192 #expect(NextNodes.cellText(.int(-7)) == "-7")193 #expect(NextNodes.cellText(.bool(true)) == "true")194 #expect(NextNodes.cellText(.null) == "")195 #expect(NextNodes.cellText(nil) == "")196 #expect(NextNodes.cellText(.double(.infinity)) == "")197 #expect(NextNodes.cellText(.string(" a \n\n b ")) == "a b")198 // Numbers as ECMAScript prints them (the server's String(number)).199 let numbers: [(Double, String)] = [200 (0, "0"), (-0.0, "0"), (1, "1"), (-1.5, "-1.5"), (0.1, "0.1"), (100, "100"), (123456789.125, "123456789.125"), (1e21, "1e+21"),201 (1e20, "100000000000000000000"), (123456789012345680000, "123456789012345680000"), (1.5e22, "1.5e+22"), (1e-6, "0.000001"),202 (1e-7, "1e-7"), (1.25e-7, "1.25e-7"), (0.000123, "0.000123"), (5e-324, "5e-324"), (1.7976931348623157e308, "1.7976931348623157e+308"),203 (9007199254740993, "9007199254740992"), (0.5, "0.5"), (-2.5e-9, "-2.5e-9"), (1234.5678, "1234.5678"), (4.35, "4.35"), (1e300, "1e+300"),204 ]205 for (value, expected) in numbers { #expect(JS.numberToString(value) == expected, "\(value)") }206 // One line: only white space around a line feed collapses.207 #expect(NextNodes.oneLine("a b") == "a b")208 #expect(NextNodes.oneLine("a \t\n \n b\r\nc") == "a b c")209 #expect(NextNodes.oneLine("\n a \n") == "a")210 // Ids: a UUID in any case, lower-cased; anything else is not an id.211 #expect(NextNodes.id(.string("0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D")) == "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")212 #expect(NextNodes.id(.string("0a1b2c3d4e5f4a6b8c7d9e0f1a2b3c4d")) == nil)213 #expect(NextNodes.id(.string("../../etc/passwd")) == nil)214 #expect(NextNodes.id(.int(3)) == nil)215 // An invalid attachment id never becomes a link.216 let bad = try doc(#"{"type":"pdf","attrs":{"attachmentId":"../x","name":"a"}},{"type":"audio","attrs":{"attachmentId":7,"title":""}},{"type":"drawing","attrs":{"preview":"nope"}},{"type":"canvasLink","attrs":{"pageId":"x"}}"#)217 #expect(bad.markdown() == "[PDF: a]\n\n[Audio]\n\n[Dessin]\n\n[Canvas]\n")218 #expect(bad.attachmentReferences().isEmpty && bad.pageReferences().isEmpty)219 // Missing attrs altogether.220 let bare = try doc(NodeType.nextBlocks.map { #"{"type":"\#($0)"}"# }.joined(separator: ","))221 #expect(bare.markdown() == "```mermaid\n\n```\n\n[Dessin]\n\n[Graphique]\n\n[Vue]\n\n## Références\n\n[PDF]\n\n[[]]\n\n```\n\n```\n\n[Audio]\n\n[Canvas]\n")222 #expect(bare.plainText() == "Dessin\n\nVue\nRéférences\nPDF\n\nAudio\nCanvas")223 // A chart whose rows are shorter or longer than the columns, with a pipe and a line feed in a cell.224 let chart = try doc(#"{"type":"chart","attrs":{"title":" T \n U ","columns":["a|b","c"],"rows":[[1],[1,2,3],"oops",["x\ny",true]]}}"#)225 #expect(chart.markdown() == "T U\n\n| a\\|b | c |\n| --- | --- |\n| 1 | |\n| 1 | 2 |\n| x y | true |\n")226 #expect(chart.plainText() == "T U\na|b c\n1\n1 2 3\nx y true")227 // runCode: an output object without text prints nothing; an empty text prints an empty block.228 let noText = try doc(#"{"type":"runCode","attrs":{"language":"js","code":"a","output":{"error":true}}}"#)229 #expect(noText.markdown() == "```js\na\n```\n")230 let emptyText = try doc(#"{"type":"runCode","attrs":{"language":null,"code":"a","output":{"text":""}}}"#)231 #expect(emptyText.markdown() == "```\na\n```\n\n```output\n\n```\n")232 // Annotation page numbers.233 let pages = try doc(#"{"type":"pdf","attrs":{"name":"","annotations":[{"page":0,"text":"a"},{"page":"4","text":"b"},{"page":2.9,"note":"c"},{"text":"d"},"x",null,{"page":-3}]}}"#)234 #expect(pages.markdown() == "[PDF]\n\n> p.1 — a\n> p.4 — b\n> p.2 — c\n> p.1 — d\n> p.1\n")235 }236237 @Test func citationInsideBlocksAndLists() throws {238 let d = try doc(#"{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Voir "},{"type":"citation","attrs":{"refId":null,"label":"Fama 1970","locator":""}}]}]}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"type":"citation","attrs":{"label":"A\nB"}}]}]}"#)239 #expect(d.markdown() == "- Voir [@Fama 1970]\n\n> [@A B]\n")240 #expect(d.plainText() == "Voir Fama 1970\nA B")241 // A citation is one inline atom of a text line: one UTF-16 unit for the editors.242 #expect(d.lines[0].type == NodeType.paragraph)243 guard case .inline(let runs) = d.lines[0].content, case .atom(let atom)? = runs.last else { Issue.record("citation is not an inline atom"); return }244 #expect(CitationInline(node: atom)?.label == "Fama 1970")245 }246247 @Test func referencesOfTheNewNodes() throws {248 let d = try Fixture.doc("next-nodes")249 #expect(d.attachmentReferences() == [250 "11111111-2222-4333-8444-555555555555", "22222222-2222-4333-8444-555555555555", "33333333-2222-4333-8444-555555555555",251 "44444444-2222-4333-8444-555555555555", "55555555-2222-4333-8444-555555555555",252 ])253 #expect(d.pageReferences() == ["66666666-2222-4333-8444-555555555555", "77777777-2222-4333-8444-555555555555"])254 #expect(d.citedReferences() == ["0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d", "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4e"])255 let tasks = d.taskItemDetails()256 #expect(tasks == [257 TaskItemDetail(blockId: "ti1", taskId: "88888888-2222-4333-8444-555555555555", checked: false, text: "Relancer le client", due: "2026-12-01", priority: .high),258 TaskItemDetail(blockId: nil, taskId: nil, checked: true, text: "Ancienne tâche 2.x", due: nil, priority: nil),259 ])260 #expect(d.taskItems() == TaskCounts(total: 2, checked: 1))261 // A drawing with PencilKit data references three files; duplicates are listed once.262 let pk = try doc(#"{"type":"drawing","attrs":{"ink":"22222222-2222-4333-8444-555555555555","preview":"33333333-2222-4333-8444-555555555555","pk":"99999999-2222-4333-8444-555555555555"}},{"type":"pdf","attrs":{"attachmentId":"22222222-2222-4333-8444-555555555555"}}"#)263 #expect(pk.attachmentReferences() == ["22222222-2222-4333-8444-555555555555", "33333333-2222-4333-8444-555555555555", "99999999-2222-4333-8444-555555555555"])264 }265266 /// Outputs recorded from the server's own functions (`toMarkdown`, `docText`, `wordCount`, `docToHtml` of the267 /// worktree M4M64c:~/dev/note-next) for the documents of next-server.json. Regenerate: see docs/DOCUMENT_API.md.268 @Test func parityWithTheServerRecording() throws {269 guard let url = Bundle.module.url(forResource: "next-server", withExtension: "json", subdirectory: "Fixtures") else {270 Issue.record("Fixtures/next-server.json is missing")271 return272 }273 let cases = try #require(try JSONValue(data: Data(contentsOf: url)).arrayValue)274 #expect(cases.count >= 300)275 var failures = 0276 for (i, c) in cases.enumerated() {277 let d = NoteDocument(node: try PMNode(json: try #require(c["doc"])))278 let checks: [(String, String, String?)] = [279 ("markdown", d.markdown(), c["markdown"]?.stringValue), ("text", d.plainText(), c["text"]?.stringValue),280 ("words", String(d.wordCount), c["words"]?.intValue.map(String.init)), ("html", d.htmlBody(), c["html"]?.stringValue),281 ("refs", d.pageReferences().joined(separator: ","), c["refs"]?.arrayValue?.compactMap(\.stringValue).joined(separator: ",")),282 ]283 for (what, mine, theirs) in checks where theirs != nil && mine != theirs {284 failures += 1285 if failures <= 5 { Issue.record("case \(i) \(what) differs\nmine: \(mine.debugDescription)\nserver: \(theirs!.debugDescription)\ndoc: \(c["doc"]!.canonicalString())") }286 }287 }288 #expect(failures == 0)289 }290291 /// The fixtures published by the backend team (M4M64c:~/dev/note-next/tests/fixtures/next-nodes, copied 2026-11-19): for292 /// each document, the Markdown, plain text and HTML the server expects. Compared byte for byte, nothing trimmed.293 @Test(arguments: ["all-nodes", "defaults", "edge-cases", "mixed-document"])294 func serverFixture(_ name: String) throws {295 func file(_ ext: String) throws -> Data {296 let url = try #require(Bundle.module.url(forResource: name, withExtension: ext, subdirectory: "Fixtures/next-nodes"), "\(name).\(ext)")297 return try Data(contentsOf: url)298 }299 let d = try NoteDocument(json: file("json"))300 #expect(d.markdown() == String(decoding: try file("md"), as: UTF8.self), "\(name).md")301 #expect(d.plainText() == String(decoding: try file("txt"), as: UTF8.self), "\(name).txt")302 // The server's own test compares `docToHtml(doc).html + "\n"` with the file: the fixture ends with one line feed.303 #expect(d.htmlBody() + "\n" == String(decoding: try file("html"), as: UTF8.self), "\(name).html")304 // The fixture documents also survive the codec untouched and are valid for the 3.0 schema.305 #expect(try d.jsonData() == JSONValue(data: file("json")).canonicalData())306 if name != "edge-cases" { #expect(d.schemaViolations() == [], "\(name)") }307 }308309 /// Writes the documents the server recording is made from (hand-made cases + seeded random attrs). Only with SPN_DUMP_NEXT=<path>.310 @Test func dumpDocumentsForTheServerRecording() throws {311 guard let path = ProcessInfo.processInfo.environment["SPN_DUMP_NEXT"], !path.isEmpty else { return }312 var docs: [JSONValue] = [try Fixture.node("next-nodes").jsonValue]313 var r = SplitMix64(seed: 20261119)314 let uuids = ["11111111-2222-4333-8444-555555555555", "0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D", "not-an-id", ""]315 let texts = ["", "x", "Deux mots", " espace \n\n saut ", "a|b", "<b>&\"", "été 😀", "l'été d'après", "tab\there", "\r\nwin", "1 000,5", "`code`", "# titre"]316 func scalar() -> JSONValue {317 switch r.int(12) {318 case 0: return .null319 case 1: return .bool(r.chance(50))320 case 2: return .int(Int64(r.int(400)) - 100)321 case 3: return .double(Double(r.int(100000)) / 64 - 300)322 case 4: return .double([0.1, 1e21, 1e-7, 123456789.125, -0.0, 5e-324, 2.5][r.int(7)])323 case 5: return .string(uuids[r.int(uuids.count)])324 default: return .string(texts[r.int(texts.count)])325 }326 }327 func any(_ depth: Int = 2) -> JSONValue {328 if depth > 0, r.chance(18) { return .array((0..<r.int(4)).map { _ in any(depth - 1) }) }329 if depth > 0, r.chance(10) { return .object(["k": any(depth - 1)]) } // one key: no key-order question330 return scalar()331 }332 func segments() -> JSONValue { .array((0..<r.int(5)).map { _ in r.chance(85) ? .object(["t": scalar(), "text": scalar()]) : any() }) }333 func annotations() -> JSONValue {334 .array((0..<r.int(5)).map { _ in r.chance(85) ? .object(["page": scalar(), "text": scalar(), "note": scalar(), "kind": "highlight"]) : any() })335 }336 func attrs(_ type: String) -> [String: JSONValue] {337 var a: [String: JSONValue] = [:]338 func put(_ key: String, _ make: () -> JSONValue) { if r.chance(88) { a[key] = make() } }339 switch type {340 case "mermaid": put("code") { scalar() }; put("preview") { scalar() }341 case "runCode": put("language") { scalar() }; put("code") { scalar() }; put("output") { r.chance(70) ? .object(["text": scalar(), "error": scalar()]) : any() }342 case "chart":343 put("title") { scalar() }344 put("columns") { r.chance(85) ? .array((0..<r.int(4)).map { _ in scalar() }) : any() }345 put("rows") { r.chance(85) ? .array((0..<r.int(4)).map { _ in r.chance(85) ? .array((0..<r.int(5)).map { _ in any(1) }) : any() }) : any() }346 case "drawing": put("preview") { scalar() }; put("ink") { scalar() }; put("pk") { scalar() }347 case "pdf": put("attachmentId") { scalar() }; put("name") { scalar() }; put("annotations") { r.chance(85) ? annotations() : any() }348 case "audio": put("attachmentId") { scalar() }; put("title") { scalar() }; put("transcript") { r.chance(85) ? segments() : any() }349 case "queryView": put("title") { scalar() }350 case "blockRef": put("pageId") { scalar() }; put("blockId") { scalar() }351 case "citation": put("refId") { scalar() }; put("label") { scalar() }; put("locator") { scalar() }352 case "bibliography": put("title") { scalar() }353 case "canvasLink": put("pageId") { scalar() }354 default: break355 }356 return a357 }358 func block(_ type: String) -> JSONValue {359 let n: JSONValue = r.chance(8) ? .object(["type": .string(type)]) : .object(["type": .string(type), "attrs": .object(attrs(type))])360 if type == "citation" { return .object(["type": "paragraph", "content": .array([.object(["type": "text", "text": "voir "]), n, .object(["type": "text", "text": " fin"])])]) }361 return n362 }363 let types = NodeType.nextBlocks + [NodeType.citation]364 for type in types { for _ in 0..<40 { docs.append(.object(["type": "doc", "content": .array([block(type)])])) } }365 for _ in 0..<80 {366 // Several nodes together, some inside containers, between paragraphs.367 var content: [JSONValue] = []368 for _ in 0..<(2 + r.int(5)) {369 let b = block(types[r.int(types.count)])370 switch r.int(6) {371 case 0: content.append(.object(["type": "blockquote", "content": .array([b])]))372 case 1: content.append(.object(["type": "bulletList", "content": .array([.object(["type": "listItem", "content": .array([.object(["type": "paragraph", "content": .array([.object(["type": "text", "text": "item"])])]), b])])])]))373 case 2: content.append(.object(["type": "callout", "attrs": .object(["kind": "decision", "icon": "⚖️"]), "content": .array([b])]))374 default: content.append(b)375 }376 if r.chance(40) { content.append(.object(["type": "paragraph", "content": .array([.object(["type": "text", "text": .string(texts[1 + r.int(texts.count - 1)])])])])) }377 }378 docs.append(.object(["type": "doc", "content": .array(content)]))379 }380 try JSONValue.array(docs).canonicalData().write(to: URL(fileURLWithPath: path))381 }382}383384@Suite struct NextNodeModelTests {385 /// Every known 3.0 node with attributes and keys no build knows, next to nodes nobody knows.386 static let exotic = #"""387 {"type":"doc","content":[388 {"type":"mermaid","attrs":{"id":"m","code":"graph","preview":null,"previewHash":null,"theme":"dark","zz":{"deep":[1,2.5,null,{"a":"b"}]}},"futureKey":{"x":1}},389 {"type":"drawing","attrs":{"id":"d","ink":null,"preview":null,"pk":null,"width":10.5,"height":3,"background":"#ffffff","layers":[{"n":1}]}},390 {"type":"chart","attrs":{"id":"c","kind":"sankey","title":"T","columns":["a"],"rows":[[1],"not a row",[null]],"x":null,"y":[],"source":{"databaseId":"11111111-2222-4333-8444-555555555555","viewId":null,"refresh":"live"},"palette":["#fff"]}},391 {"type":"queryView","attrs":{"id":"q","source":"galaxy","databaseId":null,"viewId":null,"filter":{"tag":"x","assignee":"moi","nested":{"k":[1]}},"layout":"timeline","limit":25,"title":"","groupBy":"status"}},392 {"type":"bibliography","attrs":{"id":"b","style":"chicago","title":"Sources","numbered":true}},393 {"type":"pdf","attrs":{"id":"p","attachmentId":"44444444-2222-4333-8444-555555555555","name":"a.pdf","page":2,"annotations":[{"id":"a1","page":1,"kind":"underline","color":"#000000","rects":[[0,0,1,1,9]],"text":"t","note":"","createdAt":"x","author":"sp","reactions":["👍"]},"stray",7],"zoom":1.5}},394 {"type":"blockRef","attrs":{"id":"r","pageId":"66666666-2222-4333-8444-555555555555","blockId":"abc","mode":"mirror","collapsed":true}},395 {"type":"runCode","attrs":{"id":"u","language":"rust","code":"fn main(){}","output":{"text":"ok","error":false,"ms":1.5,"at":"2026-01-01","stdout":["a"]},"timeout":5}},396 {"type":"audio","attrs":{"id":"s","attachmentId":null,"duration":1.25,"title":"","recordedAt":null,"transcript":[{"t":1,"text":"un","speaker":"A","confidence":0.93},{"t":"bad"},3],"transcriptStatus":"queued","transcriptEngine":null,"summary":null,"waveform":[0,1,0]}},397 {"type":"canvasLink","attrs":{"id":"k","pageId":null,"thumbnail":"x"}},398 {"type":"paragraph","attrs":{"id":"pp","textAlign":null},"content":[{"type":"citation","attrs":{"refId":null,"locator":"","label":"L","prefix":"cf.","suppressAuthor":true},"mystery":[1]},{"type":"sparkle","attrs":{"n":1}}]},399 {"type":"hologram","attrs":{"id":"h","frames":[1,2,3],"nested":{"a":{"b":null}}},"version":3},400 {"type":"taskList","attrs":{"id":"tl"},"content":[{"type":"taskItem","attrs":{"checked":false,"id":"ti","due":"2026-12-01","priority":"urgent","taskId":null,"estimate":3},"content":[{"type":"paragraph","attrs":{"id":"tp","textAlign":null}}]}]},401 {"type":"aiBlock","attrs":{"id":"ai","model":null,"prompt":null,"at":null,"sources":[{"pageId":"p","blockId":null,"title":"t","score":0.5}],"action":"links","tokens":12},"content":[{"type":"paragraph","attrs":{"id":"ap","textAlign":null}}]}402 ]}403 """#404405 @Test func unknownAttrsInsideKnownNodesAndUnknownNodesRoundTripByteForByte() throws {406 let input = try JSONValue(data: Data(Self.exotic.utf8))407 let d = try NoteDocument(json: Data(Self.exotic.utf8))408 #expect(try d.jsonData() == input.canonicalData())409 // …also through every typed view: reading a node and giving it back changes nothing.410 func walk(_ n: PMNode) throws {411 if let typed = TypedBlock(node: n) { #expect(typed.node() == n, "\(n.type)") }412 for c in n.content ?? [] { try walk(c) }413 }414 try walk(d.pmNode())415 // …and through block id assignment and a second decode.416 var again = try NoteDocument(json: d.jsonData())417 again.ensureBlockIds()418 #expect(try again.jsonData() == input.canonicalData())419 // The server fixtures too.420 for name in ["next-nodes", "rich", "unknown"] {421 let data = try Fixture.data(name)422 let decoded = try NoteDocument(json: data), canonical = try JSONValue(data: data).canonicalData()423 #expect(try decoded.jsonData() == canonical, "\(name)")424 }425 }426427 @Test func editingOneTypedPropertyKeepsEverythingElse() throws {428 let d = try NoteDocument(json: Data(Self.exotic.utf8))429 func atom(_ type: String) -> PMNode { d.lines.compactMap(\.atomNode).first { $0.type == type }! }430 func expectOnlyChanged(_ before: PMNode, _ after: PMNode, _ keys: Set<String>, sourceLocation: SourceLocation = #_sourceLocation) {431 #expect(after.type == before.type && after.extra == before.extra, sourceLocation: sourceLocation)432 let a = before.attrs ?? [:], b = after.attrs ?? [:]433 #expect(Set(a.keys) == Set(b.keys), sourceLocation: sourceLocation)434 for key in a.keys where !keys.contains(key) { #expect(a[key] == b[key], "\(before.type).\(key) changed", sourceLocation: sourceLocation) }435 for key in keys { #expect(a[key] != b[key], "\(before.type).\(key) did not change", sourceLocation: sourceLocation) }436 }437 var mermaid = try #require(MermaidBlock(node: atom("mermaid")))438 mermaid.code = "graph LR"439 expectOnlyChanged(atom("mermaid"), mermaid.node(), ["code"])440 #expect(mermaid.node().extra["futureKey"] == ["x": 1])441 var chart = try #require(ChartBlock(node: atom("chart")))442 #expect(chart.kind == "sankey" && !chart.kind.isKnown)443 chart.title = "Nouveau"444 expectOnlyChanged(atom("chart"), chart.node(), ["title"])445 #expect(chart.node().attrs?["rows"] == atom("chart").attrs?["rows"]) // the stray row is still there446 chart.source = ChartSource(databaseId: "11111111-2222-4333-8444-555555555555", viewId: "22222222-2222-4333-8444-555555555555")447 #expect(chart.node().attrs?["source"]?["refresh"] == "live")448 var query = try #require(QueryViewBlock(node: atom("queryView")))449 var filter = query.filter450 #expect(filter.tag == "x" && filter.fields["assignee"] == "moi")451 filter.status = "open"452 filter.tag = nil453 query.filter = filter454 #expect(query.node().attrs?["filter"] == ["assignee": "moi", "nested": ["k": [1]], "status": "open"])455 #expect(query.source == "galaxy" && query.layout == "timeline" && query.node().attrs?["groupBy"] == "status")456 var pdf = try #require(PDFBlock(node: atom("pdf")))457 #expect(pdf.annotations.count == 1 && pdf.annotations[0].kind == "underline" && pdf.annotations[0].rects == [PDFRect(x: 0, y: 0, width: 1, height: 1)])458 var note = pdf.annotations[0]459 note.note = "revu"460 check(pdf.update(note))461 let stored = try #require(pdf.node().attrs?["annotations"]?.arrayValue)462 #expect(stored.count == 3 && stored[1] == "stray" && stored[2] == 7)463 #expect(stored[0]["author"] == "sp" && stored[0]["reactions"] == ["👍"] && stored[0]["note"] == "revu" && stored[0]["rects"] == [[0, 0, 1, 1, 9]])464 pdf.add(PDFAnnotation(id: "a2", page: 3, kind: .note, note: "n", createdAt: Date(timeIntervalSince1970: 0)))465 #expect(pdf.node().attrs?["annotations"]?.arrayValue?.count == 4)466 check(pdf.remove(annotationId: "a1") && !pdf.remove(annotationId: "a1") && !pdf.remove(annotationId: ""))467 #expect(pdf.node().attrs?["annotations"]?.arrayValue?.prefix(2) == ["stray", 7])468 #expect(pdf.node().attrs?["zoom"] == 1.5)469 var run = try #require(RunCodeBlock(node: atom("runCode")))470 #expect(run.output == RunCodeOutput(text: "ok", isError: false, milliseconds: 1.5, at: "2026-01-01"))471 run.code = "fn main(){ }"472 #expect(run.node().attrs?["output"]?["stdout"] == ["a"] && run.node().attrs?["timeout"] == 5)473 var audio = try #require(AudioBlock(node: atom("audio")))474 #expect(audio.transcript == [TranscriptSegment(t: 1, text: "un")] && audio.transcriptStatus == "queued" && !audio.transcriptStatus.isKnown)475 audio.title = "Titre"476 #expect(audio.node().attrs?["transcript"] == atom("audio").attrs?["transcript"] && audio.node().attrs?["waveform"] == [0, 1, 0])477 var ref = try #require(BlockRefBlock(node: atom("blockRef")))478 #expect(ref.mode == "mirror")479 ref.blockId = nil480 expectOnlyChanged(atom("blockRef"), ref.node(), ["blockId"])481 }482483 @Test func classificationOfTheNewNodes() throws {484 let d = try Fixture.doc("next-nodes")485 for type in NodeType.nextBlocks {486 let lines = d.lines.filter { $0.type == type }487 #expect(!lines.isEmpty, "\(type) is in the fixture")488 for line in lines {489 guard case .blockAtom(let n) = line.content else { Issue.record("\(type) must be a block atom line"); continue }490 #expect(n.type == type && TypedBlock(node: n) != nil && n.isKnownType)491 #expect(line.path.isEmpty)492 }493 }494 #expect(NodeType.nextBlocks.count == 10)495 let hologram = try node(#"{"type":"hologram"}"#)496 #expect(hologram.isKnownType == false && TypedBlock(node: hologram) == nil)497 #expect(d.typedBlock(at: 0) == nil)498 if case .mermaid(let m)? = d.typedBlock(at: 2) { #expect(m.code == "graph TD\n A-->B") } else { Issue.record("line 2 is the mermaid block") }499 // The fixture is valid for the 3.0 schema in strict mode (2.x task items without the new attrs included).500 #expect(d.schemaViolations(strict: true) == [])501 // A 3.0 leaf never has content; an unknown attribute is reported in strict mode only.502 let leafWithContent = try node(#"{"type":"doc","content":[{"type":"mermaid","attrs":{"id":null,"code":"","preview":null,"previewHash":null},"content":[{"type":"text","text":"x"}]}]}"#)503 #expect(leafWithContent.schemaViolations().contains { $0.contains("has no content") })504 let extra = try NoteDocument(json: Data(Self.exotic.utf8))505 #expect(extra.schemaViolations().filter { !$0.contains("hologram") && !$0.contains("sparkle") }.isEmpty)506 #expect(extra.schemaViolations(strict: true).contains { $0.contains("mermaid") && $0.contains("attrs") })507 // A citation is not allowed at block level, a block atom not inside a paragraph.508 let blockCitation = try node(#"{"type":"doc","content":[{"type":"citation","attrs":{"refId":null,"locator":"","label":""}}]}"#)509 #expect(blockCitation.schemaViolations().contains { $0.contains("citation is not allowed here") })510 let inlineAudio = try node(#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"audio"}]}]}"#)511 #expect(inlineAudio.schemaViolations().contains { $0.contains("audio is not allowed here") })512 }513514 @Test func buildersWriteTheSchemaDefaults() throws {515 let alphabet = Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")516 let a = "11111111-2222-4333-8444-555555555555"517 let built: [PMNode] = [518 MermaidBlock(code: "graph TD").node(), DrawingBlock(width: 800, height: 600).node(),519 ChartBlock(kind: .line, title: "T", columns: ["x", "y"], rows: [["a", 1], ["b", 2.5], ["c", nil]], x: "x", y: ["y"]).node(),520 QueryViewBlock(source: .tasks, title: "Ouvertes", filter: QueryFilter(tag: "projet", status: "open"), layout: .board, limit: 9999).node(),521 BibliographyBlock().node(), PDFBlock(attachmentId: a, name: "a.pdf").node(), BlockRefBlock(pageId: a, blockId: "abc").node(),522 RunCodeBlock(code: "1").node(), AudioBlock(attachmentId: a, duration: 12.5, title: "Mémo", recordedAt: Date(timeIntervalSince1970: 0)).node(),523 CanvasLinkBlock(pageId: a).node(),524 ]525 #expect(Set(built.map(\.type)) == Set(NodeType.nextBlocks))526 var d = NoteDocument()527 for n in built {528 #expect(Set((n.attrs ?? [:]).keys) == Set((Schema.nodeDefaults[n.type] ?? [:]).keys), "\(n.type) attrs")529 let id = try #require(n.attrs?["id"]?.stringValue)530 #expect(id.count == 10 && id.allSatisfy(alphabet.contains))531 d.insertBlockAtom(n, after: d.lines.count - 1)532 }533 let citation = CitationInline(refId: a, label: "Fama 1970", locator: "p. 3")534 #expect(citation.node().attrs?.keys.sorted() == ["label", "locator", "refId"]) // inline: no block id535 #expect(citation.displayText == "Fama 1970, p. 3" && CitationInline(refId: a).displayText == a)536 check(d.insertInlineAtom(citation.node(), at: 0, line: 0))537 expectValid(d, "built document")538 #expect(d.schemaViolations(strict: true) == [])539 // SPEC §2 defaults, spelled out.540 #expect(MermaidBlock().node().attrs?.filter { $0.key != "id" } == ["code": "", "preview": nil, "previewHash": nil])541 #expect(DrawingBlock().node().attrs?.filter { $0.key != "id" } == ["ink": nil, "preview": nil, "pk": nil, "width": 0, "height": 0, "background": "none"])542 #expect(ChartBlock().node().attrs?.filter { $0.key != "id" } == ["kind": "bar", "title": "", "columns": [], "rows": [], "x": nil, "y": [], "source": nil])543 #expect(QueryViewBlock().node().attrs?.filter { $0.key != "id" } == ["source": "tasks", "databaseId": nil, "viewId": nil, "filter": [:], "layout": "list", "limit": 25, "title": ""])544 #expect(BibliographyBlock().node().attrs?.filter { $0.key != "id" } == ["style": "apa", "title": "Références"])545 #expect(RunCodeBlock().node().attrs?.filter { $0.key != "id" } == ["language": "javascript", "code": "", "output": nil])546 #expect(BlockRefBlock(pageId: a).node().attrs?.filter { $0.key != "id" } == ["pageId": .string(a), "blockId": nil, "mode": "embed"])547 #expect(PDFBlock(attachmentId: a, name: "n").node().attrs?.filter { $0.key != "id" } == ["attachmentId": .string(a), "name": "n", "page": 1, "annotations": []])548 #expect(AudioBlock(attachmentId: a).node().attrs?.filter { $0.key != "id" } == ["attachmentId": .string(a), "duration": 0, "title": "", "recordedAt": nil, "transcript": [],549 "transcriptStatus": "none", "transcriptEngine": nil, "summary": nil])550 #expect(CanvasLinkBlock(pageId: a).node().attrs?.filter { $0.key != "id" } == ["pageId": .string(a)])551 #expect(QueryViewBlock(limit: 9999).limit == 500 && QueryViewBlock(limit: 0).limit == 1)552 // A typed view refuses a node of another type.553 #expect(MermaidBlock(node: RunCodeBlock().node()) == nil && CitationInline(node: .hardBreak()) == nil)554 }555556 @Test func blockIdsOfTheNewTypes() throws {557 var d = try doc(NodeType.nextBlocks.map { #"{"type":"\#($0)"}"# }.joined(separator: ",") + #","# +558 #"{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"citation"}]}]},{"type":"listItem","content":[{"type":"paragraph"},{"type":"taskList","content":[{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph"},{"type":"paragraph"}]}]}]}]},"# +559 #"{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableCell","content":[{"type":"mermaid"},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph"}]}]}]}]}]}"#)560 check(d.assignBlockIds())561 var ids: [String: [String]] = [:]562 TextTools.walk(d.pmNode()) { n in if let id = n.attrs?["id"]?.stringValue { ids[n.type, default: []].append(id) } }563 for type in NodeType.nextBlocks { #expect(ids[type]?.count == (type == "mermaid" ? 2 : 1), "\(type)") }564 #expect(ids["listItem"]?.count == 3 && ids["taskItem"]?.count == 1)565 #expect(ids["citation"] == nil && ids["tableRow"] == nil && ids["tableCell"] == nil)566 #expect(Set(ids.values.joined()).count == ids.values.joined().count)567 // Every line of one list item carries the same item id.568 let itemIds = d.lines.compactMap { line in line.path.last { $0.type == "taskItem" }?.attrs["id"]?.stringValue }569 #expect(itemIds.count == 2 && Set(itemIds).count == 1)570 check(!d.assignBlockIds())571 // A duplicated id on two list items: the second one is replaced (as for any block).572 var dup = try doc(#"{"type":"bulletList","attrs":{"id":"l"},"content":[{"type":"listItem","attrs":{"id":"same"},"content":[{"type":"paragraph","attrs":{"id":"a"}}]},{"type":"listItem","attrs":{"id":"same"},"content":[{"type":"paragraph","attrs":{"id":"b"}}]}]}"#)573 check(dup.assignBlockIds())574 #expect(dup.lines[0].path[1].attrs["id"] == "same" && dup.lines[1].path[1].attrs["id"] != "same")575 }576577 @Test func mermaidPreviewState() {578 #expect(MermaidBlock.hash(of: "abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")579 #expect(MermaidBlock.hash(of: "") == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")580 var m = MermaidBlock(code: "graph TD\n A-->B")581 #expect(!m.isPreviewCurrent)582 m.setPreview(attachmentId: "11111111-2222-4333-8444-555555555555")583 #expect(m.isPreviewCurrent && m.previewHash?.count == 64)584 m.code += "\n B-->C" // edited natively: the render is now stale, and still referenced585 #expect(!m.isPreviewCurrent && m.preview == "11111111-2222-4333-8444-555555555555")586 m.previewHash = MermaidBlock.hash(of: m.code).uppercased()587 #expect(m.isPreviewCurrent)588 m.preview = nil589 #expect(!m.isPreviewCurrent && m.node().attrs?["preview"] == .null)590 var invalid = m591 invalid[attr: "preview"] = "not-a-uuid"592 #expect(invalid.preview == nil && invalid.node().attrs?["preview"] == "not-a-uuid")593 }594595 @Test func drawingInkAndPencilKitRule() throws {596 var drawing = DrawingBlock(width: 400, height: 300)597 drawing.setInk(attachmentId: "22222222-2222-4333-8444-555555555555", preview: "33333333-2222-4333-8444-555555555555", width: 400, height: 300,598 pk: "99999999-2222-4333-8444-555555555555")599 #expect(drawing.pk == "99999999-2222-4333-8444-555555555555")600 // An editor without PencilKit changes the ink: `pk` is cleared.601 drawing.setInk(attachmentId: "aaaaaaaa-2222-4333-8444-555555555555", preview: "bbbbbbbb-2222-4333-8444-555555555555", width: 500, height: 320.5)602 #expect(drawing.pk == nil && drawing.node().attrs?["pk"] == .null)603 #expect(drawing.width == 500 && drawing.height == 320.5)604 #expect(drawing.node().attrs?["width"] == .int(500) && drawing.node().attrs?["height"] == .double(320.5))605 // The ink document the block points to is the neutral model both platforms render.606 let ink = InkDocument(width: drawing.width, height: drawing.height, strokes: [InkStroke(tool: .pen, color: .black, width: 3, points: [InkPoint(x: 10, y: 10), InkPoint(x: 200, y: 150, pressure: 0.5)])])607 let decoded = try InkDocument(data: ink.jsonData())608 #expect(decoded == ink && decoded.width == 500)609 #expect(InkRenderer.pngData(decoded)?.prefix(4) == Data([0x89, 0x50, 0x4E, 0x47]))610 let d = try doc(String(decoding: drawing.node().jsonValue.canonicalData(), as: UTF8.self))611 #expect(d.attachmentReferences() == ["aaaaaaaa-2222-4333-8444-555555555555", "bbbbbbbb-2222-4333-8444-555555555555"])612 }613614 @Test func chartSeries() {615 var chart = ChartBlock(kind: .line, title: "Ventes", columns: ["Mois", "2025", "2026", "Note"],616 rows: [["janv.", 10, 12.5, "ok"], ["févr.", "1 000", "3,5", nil], ["mars"]], x: "Mois", y: ["2025", "2026"])617 #expect(chart.resolvedX == "Mois" && chart.resolvedY == ["2025", "2026"])618 let series = chart.series()619 #expect(series.map(\.name) == ["2025", "2026"])620 #expect(series[0].points.map(\.y) == [10, nil, nil])621 #expect(series[1].points.map(\.y) == [12.5, 3.5, nil])622 #expect(series[0].points.map(\.x) == ["janv.", "févr.", "mars"])623 chart.x = "absent"624 chart.y = []625 #expect(chart.resolvedX == "Mois" && chart.resolvedY == ["2025", "2026", "Note"])626 #expect(ChartBlock().series().isEmpty)627 #expect(ChartCell.number(3).text == "3" && ChartCell.string(" a\nb ").text == "a b" && ChartCell.null.text == "")628 #expect(chart.rows[1] == ["févr.", "1 000", "3,5", nil])629 #expect(ChartKind.known.count == 5 && ChartKind.area.isKnown)630 chart.source = nil631 #expect(chart.source == nil && chart.node().attrs?["source"] == .null)632 }633634 @Test func pdfAnnotations() {635 var pdf = PDFBlock(attachmentId: "44444444-2222-4333-8444-555555555555", name: "Rapport.pdf", page: 0)636 #expect(pdf.page == 1)637 let h = PDFAnnotation(id: "h1", page: 2, kind: .highlight, color: "#ffd54a", rects: [PDFRect(x: 0.1, y: 0.2, width: 0.5, height: 0.03)], text: "Texte\nsurligné", note: "Note",638 createdAt: Date(timeIntervalSince1970: 1_800_000_000))639 let i = PDFAnnotation(id: "i1", page: 2, kind: .ink, ink: [PDFPoint(x: 0.1, y: 0.1), PDFPoint(x: 0.2, y: 0.25)])640 pdf.add(h); pdf.add(i); pdf.add(PDFAnnotation(page: 5, kind: .note, note: "seule"))641 #expect(pdf.annotations.count == 3 && pdf.annotations(onPage: 2).map(\.id) == ["h1", "i1"])642 #expect(pdf.annotations[0].rects == [PDFRect(x: 0.1, y: 0.2, width: 0.5, height: 0.03)] && pdf.annotations[0].ink == nil)643 #expect(pdf.annotations[1].ink == [PDFPoint(x: 0.1, y: 0.1), PDFPoint(x: 0.2, y: 0.25)])644 #expect(pdf.annotations[0].createdAt == "2027-01-15T08:00:00.000Z")645 #expect(pdf.annotations[0].summaryLine == "p.2 — Texte surligné — Note" && pdf.annotations[2].summaryLine == "p.5 — seule")646 #expect(pdf.annotations[2].id.count == 36)647 check(!pdf.update(PDFAnnotation(id: "absent", page: 1, kind: .note)))648 pdf.page = 4649 let d = NoteDocument(node: PMNode(type: "doc", content: [pdf.node()]))650 #expect(d.markdown() == "[PDF: Rapport.pdf](/api/files/44444444-2222-4333-8444-555555555555)\n\n> p.2 — Texte surligné — Note\n> p.2\n> p.5 — seule\n")651 #expect(d.plainText().contains("Texte surligné"))652 }653654 @Test func audioTranscript() {655 var audio = AudioBlock(attachmentId: "55555555-2222-4333-8444-555555555555", duration: 90, title: "Mémo")656 #expect(audio.transcript.isEmpty && audio.transcriptStatus == .none && audio.summary == nil && audio.segmentIndex(at: 3) == nil)657 audio.transcript = [TranscriptSegment(t: 0, text: "Bonjour"), TranscriptSegment(t: 12.5, text: "Deuxième\nphrase"), TranscriptSegment(t: 61, text: "Fin")]658 audio.transcriptStatus = .done659 audio.transcriptEngine = "whisper"660 #expect(audio.transcript.map(\.timecode) == ["00:00", "00:12", "01:01"])661 #expect(audio.transcriptText == "Bonjour\nDeuxième phrase\nFin")662 #expect(audio.segmentIndex(at: 0) == 0 && audio.segmentIndex(at: 12.4) == 0 && audio.segmentIndex(at: 60) == 1 && audio.segmentIndex(at: 999) == 2 && audio.segmentIndex(at: -1) == nil)663 #expect(audio.node().attrs?["transcript"] == [["t": 0, "text": "Bonjour"], ["t": 12.5, "text": "Deuxième\nphrase"], ["t": 61, "text": "Fin"]])664 audio[attr: "summary"] = ["text": "Résumé", "decisions": ["d1", 3], "tasks": [], "model": "m", "at": nil]665 #expect(audio.summary == AudioSummary(text: "Résumé", decisions: ["d1"], tasks: [], model: "m", at: nil))666 let d = NoteDocument(node: PMNode(type: "doc", content: [audio.node()]))667 #expect(d.plainText() == "Audio: Mémo\nBonjour\nDeuxième phrase\nFin")668 #expect(!d.plainText().contains("Résumé")) // the AI summary is not the user's words: not indexed as note text669 #expect(d.wordCount == 6)670 }671672 @Test func taskAttributesAndListCommands() throws {673 var d = md("- [ ] un\n- [x] deux\n\nfin")674 #expect(d.taskAttributes(at: 0)?.due == nil && d.taskAttributes(at: 2) == nil)675 let item = d.lines[0].path[1]676 #expect(Set(item.attrs.keys) == ["checked", "id", "due", "priority", "taskId"]) // a new item is written as the 3.0 editor writes it677 check(d.setTaskDue("2026-12-01", at: 0) && !d.setTaskDue("2026-12-01", at: 0))678 check(d.setTaskPriority(.high, at: 0) && d.setTaskId("88888888-2222-4333-8444-555555555555", at: 0))679 check(!d.setTaskDue("x", at: 2))680 #expect(d.taskAttributes(at: 0)?.due == "2026-12-01" && d.taskAttributes(at: 0)?.priority == .high && d.taskAttributes(at: 0)?.taskId == "88888888-2222-4333-8444-555555555555")681 expectValid(d)682 #expect(d.taskItemDetails().map(\.due) == ["2026-12-01", nil])683 // Enter in a task: the new item is a new block and a new, unlinked task.684 let firstId = d.lines[0].path[1].attrs["id"]685 _ = d.splitLine(at: 0, offset: 1)686 #expect(d.lines[0].path[1].attrs["id"] == firstId && d.lines[0].path[1].attrs["due"] == "2026-12-01")687 let second = d.lines[1].path[1]688 #expect(second.attrs["id"] != firstId && second.attrs["id"]?.stringValue?.count == 10)689 #expect(second.attrs["due"] == .null && second.attrs["priority"] == .null && second.attrs["taskId"] == .null && second.attrs["checked"] == false)690 expectValid(d)691 var again = d692 check(!again.assignBlockIds())693 // Converting to a bullet list keeps the block id and drops what only a task has; converting back restores the defaults.694 check(d.toggleList(.bullet, at: 0..<1))695 #expect(d.lines[0].path[1].type == "listItem" && d.lines[0].path[1].attrs == ["id": firstId!])696 expectValid(d)697 check(d.toggleList(.task, at: 0..<1))698 #expect(d.lines[0].path[1].attrs == ["id": firstId!, "checked": false, "due": nil, "priority": nil, "taskId": nil])699 check(d.setTaskPriority(nil, at: 0) == false && d.setTaskDue(nil, at: 0) == false)700 expectValid(d)701 // Dates.702 #expect(TaskItemDetail.isDate("2026-12-01") && TaskItemDetail.isDate("2026-12-01T10:00:00Z") && TaskItemDetail.isDate("2026-12-01T10:00:00.000+02:00"))703 #expect(!TaskItemDetail.isDate("demain") && !TaskItemDetail.isDate("") && !TaskItemDetail.isDate("2026-13-45"))704 #expect(TaskItemDetail.date(from: "2026-12-01") == Date(timeIntervalSince1970: 1_796_083_200))705 #expect(TaskItemDetail.dayString(Date(timeIntervalSince1970: 1_796_083_200), timeZone: TimeZone(identifier: "UTC")!) == "2026-12-01")706 #expect(TaskPriority.allCases.map(\.rawValue) == ["low", "medium", "high"])707 }708709 @Test func aiBlockAndCalloutKinds() throws {710 let d = try Fixture.doc("next-nodes")711 let aiLine = try #require(d.lines.firstIndex { $0.path.contains { $0.type == "aiBlock" } })712 let info = try #require(d.aiBlockInfo(at: aiLine))713 #expect(info == AIBlockInfo(model: "claude-haiku", prompt: nil, at: "2026-11-19T12:00:00.000Z", action: "synthesis",714 sources: [AISource(pageId: "66666666-2222-4333-8444-555555555555", blockId: "Xy_-12abCD", title: "Source")]))715 #expect(d.aiBlockInfo(at: 0) == nil)716 let attrs = d.lines[aiLine].path[0].attrs717 #expect(info.applied(to: attrs) == attrs)718 #expect(AIBlockInfo(attrs: ["model": "m", "sources": [["pageId": ""], ["title": "x"], 4], "future": 1]).sources.isEmpty)719 #expect(AIBlockInfo().applied(to: ["id": "x", "future": 1]) == ["id": "x", "future": 1, "model": nil, "prompt": nil, "at": nil, "action": nil, "sources": nil])720 let callout = try #require(d.lines.firstIndex { $0.path.contains { $0.type == "callout" } })721 #expect(d.calloutKind(at: callout) == .decision && d.calloutKind(at: 0) == nil)722 #expect(CalloutKind.known.map(\.rawValue) == ["note", "info", "warning", "danger", "success", "decision", "question", "hypothesis"])723 var m = md("Une hypothèse\n\nautre")724 check(m.toggleCallout(.hypothesis, at: 0..<1))725 #expect(m.calloutKind(at: 0) == .hypothesis && m.markdown().hasPrefix("> [!HYPOTHESIS] 🧪\n> Une hypothèse"))726 check(m.toggleCallout(.question, at: 0..<1))727 #expect(m.calloutKind(at: 0) == .question)728 expectValid(m)729 #expect(CalloutKind(rawValue: "sparkly").isKnown == false && CalloutKind(rawValue: "sparkly").defaultIcon == "💡")730 }731732 @Test func threeWayMergeTreatsEachNewBlockAsAWhole() throws {733 let base = try Fixture.doc("next-nodes")734 func edit(_ type: String, _ d: inout NoteDocument, _ change: (inout PMNode) -> Void) {735 let i = d.lines.firstIndex { $0.type == type }!736 var n = d.lines[i].atomNode!737 change(&n)738 _ = d.replaceBlockAtom(at: i, with: n)739 }740 var mine = base, theirs = base741 edit("mermaid", &mine) { n in var m = MermaidBlock(node: n)!; m.code = "graph LR"; n = m.node() }742 edit("audio", &theirs) { n in var a = AudioBlock(node: n)!; a.title = "Renommé"; n = a.node() }743 guard case .merged(let merged) = NoteDocument.merge(base: base, mine: mine, theirs: theirs) else { Issue.record("different blocks must merge"); return }744 #expect(merged.markdown().contains("graph LR") && merged.markdown().contains("[Audio: Renommé]"))745 guard case .merged(let other) = NoteDocument.merge(base: base, mine: theirs, theirs: mine) else { Issue.record("must merge both ways"); return }746 #expect(try other.jsonData() == merged.jsonData())747 // The same block edited on both sides (an annotation here, the page there) is a conflict: nothing is merged silently.748 var a = base, b = base749 edit("pdf", &a) { n in var p = PDFBlock(node: n)!; p.add(PDFAnnotation(id: "new", page: 1, kind: .note, note: "x")); n = p.node() }750 edit("pdf", &b) { n in var p = PDFBlock(node: n)!; p.page = 9; n = p.node() }751 if case .merged = NoteDocument.merge(base: base, mine: a, theirs: b) { Issue.record("same block on both sides must conflict") }752 }753}754