| 1 | import Foundation |
| 2 | import SwiftUI |
| 3 | import Testing |
| 4 | @testable import EquipoKit |
| 5 | #if os(macOS) |
| 6 | import AppKit |
| 7 | |
| 8 | @MainActor @Suite struct MarkdownLayoutTests { |
| 9 | @Test func closingFenceKeepsItsAnchorAndMeasuredBoxAtBothWidths() throws { |
| 10 | let origin = URL(string: "https://team.example.test")! |
| 11 | let open = "**Run this:**\n\n```sh\nprintf 'a deliberately long command that scrolls horizontally instead of expanding the transcript width'\n" |
| 12 | let closed = open + "```\n" |
| 13 | let before = ChatMarkdown.parse(open, draft: true) |
| 14 | let after = ChatMarkdown.parse(closed, draft: true) |
| 15 | #expect(before.map(\.sourceOffset) == after.map(\.sourceOffset)) |
| 16 | #expect(Set(before.map(\.sourceOffset)).count == before.count) |
| 17 | for width in [390.0, 760.0] { |
| 18 | func render(_ source: String) throws -> NSImage { |
| 19 | let view = ChatMarkdownView(rendered: ChatMarkdown.parse(source, draft: true), origin: origin, openTask: { _ in }) |
| 20 | .padding(16).frame(width: width).background(.white).environment(\.colorScheme, .light) |
| 21 | let renderer = ImageRenderer(content: view) |
| 22 | return try #require(renderer.nsImage) |
| 23 | } |
| 24 | let first = try render(open), last = try render(closed) |
| 25 | #expect(abs(first.size.width - width) < 0.5) |
| 26 | #expect(first.size.height > 60) |
| 27 | #expect(first.size == last.size, "only Copy changes when the fence closes") |
| 28 | try save(first, name: "open-\(Int(width))") |
| 29 | try save(last, name: "closed-\(Int(width))") |
| 30 | if ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_SCREENSHOTS"] != nil { |
| 31 | // ImageRenderer omits AppKit-backed scroll content. Capture a |
| 32 | // hosting view too, so the scrollable command is reviewable. |
| 33 | let host = NSHostingView(rootView: ChatMarkdownView(rendered: ChatMarkdown.parse(closed, draft: true), origin: origin, openTask: { _ in }) |
| 34 | .padding(16).frame(width: width).background(.white).environment(\.colorScheme, .light)) |
| 35 | host.frame.size = host.fittingSize |
| 36 | host.layoutSubtreeIfNeeded() |
| 37 | let bitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds)) |
| 38 | host.cacheDisplay(in: host.bounds, to: bitmap) |
| 39 | let image = NSImage(size: host.bounds.size) |
| 40 | image.addRepresentation(bitmap) |
| 41 | try save(image, name: "host-\(Int(width))") |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | @Test func renderScreenshotReplyAndProseBoxes() throws { |
| 47 | let fixtures = try JSONDecoder().decode([MarkdownGolden].self, from: Fixture.data("markdown/golden")) |
| 48 | let reply = try #require(fixtures.first).source |
| 49 | let text = reply + "\n\n```prompt\nCompare both sign-in pages at narrow and wide widths. Keep the page content unchanged.\n```\n\n1. **Review** both screenshots.\n2. Open [the task](/tasks/tkwkpraqeeer)." |
| 50 | for width in [390.0, 760.0] { |
| 51 | let renderer = ImageRenderer(content: ChatMarkdownView(rendered: ChatMarkdown.parse(text, draft: false), origin: URL(string: "https://team.example.test")!, openTask: { _ in }) |
| 52 | .padding(16).frame(width: width).background(.white).environment(\.colorScheme, .light)) |
| 53 | let image = try #require(renderer.nsImage) |
| 54 | #expect(abs(image.size.width - width) < 0.5) |
| 55 | #expect(image.size.height > 150) |
| 56 | try save(image, name: "reply-\(Int(width))") |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | @Test func deeplyNestedListsFitPhoneWidth() throws { |
| 61 | let text = (0..<60).map { String(repeating: " ", count: $0) + "- level \($0)" }.joined(separator: "\n") |
| 62 | let clock = ContinuousClock() |
| 63 | let start = clock.now |
| 64 | let renderer = ImageRenderer(content: ChatMarkdownView(rendered: ChatMarkdown.parse(text, draft: false), origin: URL(string: "https://team.example.test")!, openTask: { _ in }).frame(width: 390)) |
| 65 | let image = try #require(renderer.nsImage) |
| 66 | #expect(image.size.width == 390) |
| 67 | #expect(image.size.height > 100) |
| 68 | #expect(start.duration(to: clock.now) < .seconds(3)) |
| 69 | } |
| 70 | |
| 71 | @Test func liveHostAppliesBackgroundParseAndNotifiesItsHeight() async throws { |
| 72 | let transcript = MarkdownTranscript() |
| 73 | var changes = 0 |
| 74 | let host = NSHostingView(rootView: ChatMarkdownView("**First reply**", origin: URL(string: "https://team.example.test")!, transcript: transcript, openTask: { _ in }, onHeightChange: { changes += 1 }).frame(width: 390)) |
| 75 | let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 390, height: 500), styleMask: [.borderless], backing: .buffered, defer: false) |
| 76 | window.contentView = host |
| 77 | defer { window.contentView = nil } |
| 78 | host.layoutSubtreeIfNeeded() |
| 79 | #expect(host.fittingSize.height > 10, "the very first layout must contain the reply") |
| 80 | let initial = host.fittingSize.height |
| 81 | #expect(initial > 10) |
| 82 | host.rootView = ChatMarkdownView("**First reply**\n\nSecond paragraph.\n\n```text\nA complete paste box.\n```", origin: URL(string: "https://team.example.test")!, transcript: transcript, openTask: { _ in }, onHeightChange: { changes += 1 }).frame(width: 390) |
| 83 | for _ in 0..<100 where host.fittingSize.height <= initial { try await Task.sleep(for: .milliseconds(10)) } |
| 84 | #expect(host.fittingSize.height > initial + 20) |
| 85 | #expect(changes >= 2) |
| 86 | } |
| 87 | |
| 88 | @Test func fastDeltasKeepA64KiBReplyGrowing() async throws { |
| 89 | let transcript = MarkdownTranscript() |
| 90 | let text = String(String(repeating: "A streaming reply with words and **emphasis**. ", count: 2000).prefix(65_536)) |
| 91 | let origin = URL(string: "https://stream.example.test")! |
| 92 | let id = UUID().uuidString |
| 93 | func view(_ length: Int) -> some View { |
| 94 | ChatMarkdownView(String(text.prefix(length)), draft: true, messageID: id, origin: origin, transcript: transcript, openTask: { _ in }).frame(width: 390) |
| 95 | } |
| 96 | let host = NSHostingView(rootView: view(16_000)) |
| 97 | let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 390, height: 500), styleMask: [.borderless], backing: .buffered, defer: false) |
| 98 | window.contentView = host |
| 99 | defer { window.contentView = nil } |
| 100 | var heights: [CGFloat] = [] |
| 101 | for step in 1...67 { |
| 102 | let length = 16_000 + (65_536 - 16_000) * step / 67 |
| 103 | host.rootView = view(length) |
| 104 | try await Task.sleep(for: .milliseconds(5)) |
| 105 | heights.append(host.fittingSize.height) |
| 106 | } |
| 107 | #expect(Set(heights.dropLast()).count >= 6, "visible text must grow during the fast stream, not only after it stops") |
| 108 | let deadline = ContinuousClock.now.advanced(by: .seconds(3)) |
| 109 | let before = heights.first ?? 0 |
| 110 | while host.fittingSize.height < before * 3 && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| 111 | #expect(host.fittingSize.height > before * 3) |
| 112 | } |
| 113 | |
| 114 | @Test func rehostingDoesNotEndTheMessageParse() async throws { |
| 115 | let transcript = MarkdownTranscript() |
| 116 | let text = String(repeating: "Words in a reply with **emphasis**. ", count: 1000) |
| 117 | let id = UUID().uuidString |
| 118 | let origin = URL(string: "https://rehost.example.test")! |
| 119 | func view(_ count: Int) -> some View { |
| 120 | ChatMarkdownView(String(text.prefix(count)), draft: true, messageID: id, origin: origin, transcript: transcript, openTask: { _ in }).frame(width: 620) |
| 121 | } |
| 122 | let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 700, height: 500), styleMask: [.borderless], backing: .buffered, defer: false) |
| 123 | let host = NSHostingView(rootView: view(16000)) |
| 124 | window.contentView = host |
| 125 | host.layoutSubtreeIfNeeded() |
| 126 | defer { window.contentView = nil } |
| 127 | var heights: [CGFloat] = [] |
| 128 | for step in 1...67 { |
| 129 | host.removeFromSuperview() |
| 130 | window.contentView = NSView() |
| 131 | host.rootView = view(17000 + 8000 * step / 67) |
| 132 | window.contentView?.addSubview(host) |
| 133 | try await Task.sleep(for: .milliseconds(5)) |
| 134 | heights.append(host.fittingSize.height) |
| 135 | } |
| 136 | #expect(Set(heights.dropLast()).count >= 5, "re-hosting must not cancel the message's in-flight parse") |
| 137 | } |
| 138 | |
| 139 | @Test func largeReplyHasMultilineContentOnItsFirstFrame() { |
| 140 | let transcript = MarkdownTranscript() |
| 141 | let text = String(repeating: "A line of this large reply.\n", count: 800) |
| 142 | for draft in [false, true] { |
| 143 | let host = NSHostingView(rootView: ChatMarkdownView(text, draft: draft, messageID: "large-first-frame-\(draft)", origin: URL(string: "https://team.example.test")!, transcript: transcript, openTask: { _ in }).frame(width: 390)) |
| 144 | #expect(host.fittingSize.height > 8000, "the fallback preserves line breaks before any async parse") |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | @Test func cacheKeepsRevisionsAndLargeRepliesVisible() { |
| 149 | var parses = 0 |
| 150 | let cache = MarkdownRenderCache { text, draft in |
| 151 | parses += 1 |
| 152 | return ChatMarkdown.parse(text, draft: draft) |
| 153 | } |
| 154 | let first = MarkdownRenderCache.Request(messageID: "one", text: "**hello**", draft: false) |
| 155 | #expect(cache.initial(first).complete) |
| 156 | #expect(cache.initial(first).tree.first?.children.first?.kind == "strong") |
| 157 | #expect(parses == 1, "scrolling back to the same revision does not reparse") |
| 158 | let updated = MarkdownRenderCache.Request(messageID: "one", text: "**new**", draft: true) |
| 159 | #expect(cache.initial(updated).complete) |
| 160 | #expect(parses == 2) |
| 161 | let large = MarkdownRenderCache.Request(messageID: "two", text: String(repeating: "words\n", count: 5000), draft: true) |
| 162 | let fallback = cache.initial(large) |
| 163 | #expect(!fallback.complete) |
| 164 | #expect(fallback.tree.first?.text == large.text) |
| 165 | #expect(parses == 2) |
| 166 | let empty = MarkdownRenderCache.Request(messageID: "empty", text: "", draft: true) |
| 167 | _ = cache.initial(empty) |
| 168 | let fromEmpty = MarkdownRenderCache.Request(messageID: "empty", text: large.text, draft: true) |
| 169 | #expect(!cache.initial(fromEmpty).tree.isEmpty) |
| 170 | let continued = MarkdownRenderCache.Request(messageID: "one", text: large.text, draft: true) |
| 171 | #expect(cache.initial(continued).tree == cache.initial(updated).tree) |
| 172 | #expect(cache.initial(first).tree.first?.children.first?.kind == "strong") |
| 173 | #expect(parses == 3) |
| 174 | let fence = "```sh\nx" |
| 175 | #expect(cache.initial(.init(messageID: "fence", text: fence, draft: true)).tree.first?.copyEnabled == false) |
| 176 | #expect(cache.initial(.init(messageID: "fence", text: fence, draft: false)).tree.first?.copyEnabled == true) |
| 177 | } |
| 178 | |
| 179 | @Test func macHeightChangesOnlyResizeTheAffectedRow() throws { |
| 180 | let apple = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() |
| 181 | let source = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoMac/LiveTranscript.swift"), encoding: .utf8) |
| 182 | let callback = source.components(separatedBy: "onHeightChange: { [weak self]").last!.components(separatedBy: "let host = replyHosts").first! |
| 183 | #expect(!callback.contains("self.rebuild()")) |
| 184 | #expect(callback.contains("self.resizeReply(id)")) |
| 185 | } |
| 186 | |
| 187 | @Test func macReplyTypeAndPasteLabelsMatchTheExistingInterface() { |
| 188 | #expect(MarkdownTypography.macPointSize == 14) |
| 189 | #expect(MarkdownPresentation.pasteLabel(ChatMarkdownNode(kind: "paste", label: "Prompt")) == "Prompt") |
| 190 | #expect(MarkdownPresentation.pasteLabel(ChatMarkdownNode(kind: "paste")) == "Text") |
| 191 | let text = (0..<60).map { String(repeating: " ", count: $0) + "- level \($0)" }.joined(separator: "\n") |
| 192 | let rows = MarkdownPresentation.rows(ChatMarkdown.parse(text, draft: false)) |
| 193 | #expect(rows.allSatisfy { $0.indentation <= 4 }) |
| 194 | } |
| 195 | |
| 196 | private func save(_ image: NSImage, name: String) throws { |
| 197 | guard let directory = ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_SCREENSHOTS"] else { return } |
| 198 | let folder = URL(fileURLWithPath: directory) |
| 199 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 200 | let data = try #require(image.tiffRepresentation) |
| 201 | let bitmap = try #require(NSBitmapImageRep(data: data)) |
| 202 | try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent(name + ".png")) |
| 203 | } |
| 204 | } |
| 205 | #endif |
| 206 | |