import Foundation import SwiftUI import Testing @testable import EquipoKit #if os(macOS) import AppKit @MainActor @Suite struct MarkdownLayoutTests { @Test func closingFenceKeepsItsAnchorAndMeasuredBoxAtBothWidths() throws { let origin = URL(string: "https://team.example.test")! let open = "**Run this:**\n\n```sh\nprintf 'a deliberately long command that scrolls horizontally instead of expanding the transcript width'\n" let closed = open + "```\n" let before = ChatMarkdown.parse(open, draft: true) let after = ChatMarkdown.parse(closed, draft: true) #expect(before.map(\.sourceOffset) == after.map(\.sourceOffset)) #expect(Set(before.map(\.sourceOffset)).count == before.count) for width in [390.0, 760.0] { func render(_ source: String) throws -> NSImage { let view = ChatMarkdownView(rendered: ChatMarkdown.parse(source, draft: true), origin: origin, openTask: { _ in }) .padding(16).frame(width: width).background(.white).environment(\.colorScheme, .light) let renderer = ImageRenderer(content: view) return try #require(renderer.nsImage) } let first = try render(open), last = try render(closed) #expect(abs(first.size.width - width) < 0.5) #expect(first.size.height > 60) #expect(first.size == last.size, "only Copy changes when the fence closes") try save(first, name: "open-\(Int(width))") try save(last, name: "closed-\(Int(width))") if ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_SCREENSHOTS"] != nil { // ImageRenderer omits AppKit-backed scroll content. Capture a // hosting view too, so the scrollable command is reviewable. let host = NSHostingView(rootView: ChatMarkdownView(rendered: ChatMarkdown.parse(closed, draft: true), origin: origin, openTask: { _ in }) .padding(16).frame(width: width).background(.white).environment(\.colorScheme, .light)) host.frame.size = host.fittingSize host.layoutSubtreeIfNeeded() let bitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds)) host.cacheDisplay(in: host.bounds, to: bitmap) let image = NSImage(size: host.bounds.size) image.addRepresentation(bitmap) try save(image, name: "host-\(Int(width))") } } } @Test func renderScreenshotReplyAndProseBoxes() throws { let fixtures = try JSONDecoder().decode([MarkdownGolden].self, from: Fixture.data("markdown/golden")) let reply = try #require(fixtures.first).source 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)." for width in [390.0, 760.0] { let renderer = ImageRenderer(content: ChatMarkdownView(rendered: ChatMarkdown.parse(text, draft: false), origin: URL(string: "https://team.example.test")!, openTask: { _ in }) .padding(16).frame(width: width).background(.white).environment(\.colorScheme, .light)) let image = try #require(renderer.nsImage) #expect(abs(image.size.width - width) < 0.5) #expect(image.size.height > 150) try save(image, name: "reply-\(Int(width))") } } @Test func deeplyNestedListsFitPhoneWidth() throws { let text = (0..<60).map { String(repeating: " ", count: $0) + "- level \($0)" }.joined(separator: "\n") let clock = ContinuousClock() let start = clock.now let renderer = ImageRenderer(content: ChatMarkdownView(rendered: ChatMarkdown.parse(text, draft: false), origin: URL(string: "https://team.example.test")!, openTask: { _ in }).frame(width: 390)) let image = try #require(renderer.nsImage) #expect(image.size.width == 390) #expect(image.size.height > 100) #expect(start.duration(to: clock.now) < .seconds(3)) } @Test func liveHostAppliesBackgroundParseAndNotifiesItsHeight() async throws { let transcript = MarkdownTranscript() var changes = 0 let host = NSHostingView(rootView: ChatMarkdownView("**First reply**", origin: URL(string: "https://team.example.test")!, transcript: transcript, openTask: { _ in }, onHeightChange: { changes += 1 }).frame(width: 390)) let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 390, height: 500), styleMask: [.borderless], backing: .buffered, defer: false) window.contentView = host defer { window.contentView = nil } host.layoutSubtreeIfNeeded() #expect(host.fittingSize.height > 10, "the very first layout must contain the reply") let initial = host.fittingSize.height #expect(initial > 10) 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) for _ in 0..<100 where host.fittingSize.height <= initial { try await Task.sleep(for: .milliseconds(10)) } #expect(host.fittingSize.height > initial + 20) #expect(changes >= 2) } @Test func fastDeltasKeepA64KiBReplyGrowing() async throws { let transcript = MarkdownTranscript() let text = String(String(repeating: "A streaming reply with words and **emphasis**. ", count: 2000).prefix(65_536)) let origin = URL(string: "https://stream.example.test")! let id = UUID().uuidString func view(_ length: Int) -> some View { ChatMarkdownView(String(text.prefix(length)), draft: true, messageID: id, origin: origin, transcript: transcript, openTask: { _ in }).frame(width: 390) } let host = NSHostingView(rootView: view(16_000)) let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 390, height: 500), styleMask: [.borderless], backing: .buffered, defer: false) window.contentView = host defer { window.contentView = nil } var heights: [CGFloat] = [] for step in 1...67 { let length = 16_000 + (65_536 - 16_000) * step / 67 host.rootView = view(length) try await Task.sleep(for: .milliseconds(5)) heights.append(host.fittingSize.height) } #expect(Set(heights.dropLast()).count >= 6, "visible text must grow during the fast stream, not only after it stops") let deadline = ContinuousClock.now.advanced(by: .seconds(3)) let before = heights.first ?? 0 while host.fittingSize.height < before * 3 && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } #expect(host.fittingSize.height > before * 3) } @Test func rehostingDoesNotEndTheMessageParse() async throws { let transcript = MarkdownTranscript() let text = String(repeating: "Words in a reply with **emphasis**. ", count: 1000) let id = UUID().uuidString let origin = URL(string: "https://rehost.example.test")! func view(_ count: Int) -> some View { ChatMarkdownView(String(text.prefix(count)), draft: true, messageID: id, origin: origin, transcript: transcript, openTask: { _ in }).frame(width: 620) } let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 700, height: 500), styleMask: [.borderless], backing: .buffered, defer: false) let host = NSHostingView(rootView: view(16000)) window.contentView = host host.layoutSubtreeIfNeeded() defer { window.contentView = nil } var heights: [CGFloat] = [] for step in 1...67 { host.removeFromSuperview() window.contentView = NSView() host.rootView = view(17000 + 8000 * step / 67) window.contentView?.addSubview(host) try await Task.sleep(for: .milliseconds(5)) heights.append(host.fittingSize.height) } #expect(Set(heights.dropLast()).count >= 5, "re-hosting must not cancel the message's in-flight parse") } @Test func largeReplyHasMultilineContentOnItsFirstFrame() { let transcript = MarkdownTranscript() let text = String(repeating: "A line of this large reply.\n", count: 800) for draft in [false, true] { 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)) #expect(host.fittingSize.height > 8000, "the fallback preserves line breaks before any async parse") } } @Test func cacheKeepsRevisionsAndLargeRepliesVisible() { var parses = 0 let cache = MarkdownRenderCache { text, draft in parses += 1 return ChatMarkdown.parse(text, draft: draft) } let first = MarkdownRenderCache.Request(messageID: "one", text: "**hello**", draft: false) #expect(cache.initial(first).complete) #expect(cache.initial(first).tree.first?.children.first?.kind == "strong") #expect(parses == 1, "scrolling back to the same revision does not reparse") let updated = MarkdownRenderCache.Request(messageID: "one", text: "**new**", draft: true) #expect(cache.initial(updated).complete) #expect(parses == 2) let large = MarkdownRenderCache.Request(messageID: "two", text: String(repeating: "words\n", count: 5000), draft: true) let fallback = cache.initial(large) #expect(!fallback.complete) #expect(fallback.tree.first?.text == large.text) #expect(parses == 2) let empty = MarkdownRenderCache.Request(messageID: "empty", text: "", draft: true) _ = cache.initial(empty) let fromEmpty = MarkdownRenderCache.Request(messageID: "empty", text: large.text, draft: true) #expect(!cache.initial(fromEmpty).tree.isEmpty) let continued = MarkdownRenderCache.Request(messageID: "one", text: large.text, draft: true) #expect(cache.initial(continued).tree == cache.initial(updated).tree) #expect(cache.initial(first).tree.first?.children.first?.kind == "strong") #expect(parses == 3) let fence = "```sh\nx" #expect(cache.initial(.init(messageID: "fence", text: fence, draft: true)).tree.first?.copyEnabled == false) #expect(cache.initial(.init(messageID: "fence", text: fence, draft: false)).tree.first?.copyEnabled == true) } @Test func macHeightChangesOnlyResizeTheAffectedRow() throws { let apple = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() let source = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoMac/LiveTranscript.swift"), encoding: .utf8) let callback = source.components(separatedBy: "onHeightChange: { [weak self]").last!.components(separatedBy: "let host = replyHosts").first! #expect(!callback.contains("self.rebuild()")) #expect(callback.contains("self.resizeReply(id)")) } @Test func macReplyTypeAndPasteLabelsMatchTheExistingInterface() { #expect(MarkdownTypography.macPointSize == 14) #expect(MarkdownPresentation.pasteLabel(ChatMarkdownNode(kind: "paste", label: "Prompt")) == "Prompt") #expect(MarkdownPresentation.pasteLabel(ChatMarkdownNode(kind: "paste")) == "Text") let text = (0..<60).map { String(repeating: " ", count: $0) + "- level \($0)" }.joined(separator: "\n") let rows = MarkdownPresentation.rows(ChatMarkdown.parse(text, draft: false)) #expect(rows.allSatisfy { $0.indentation <= 4 }) } private func save(_ image: NSImage, name: String) throws { guard let directory = ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_SCREENSHOTS"] else { return } let folder = URL(fileURLWithPath: directory) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) let data = try #require(image.tiffRepresentation) let bitmap = try #require(NSBitmapImageRep(data: data)) try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent(name + ".png")) } } #endif