// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import CryptoKit import Foundation import PDFKit import WebKit import XCTest import SQLite3 @MainActor final class LibraryContinuityTests: XCTestCase { private var directory: URL! override func setUpWithError() throws { directory = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryContinuity-" + UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) } override func tearDownWithError() throws { try FileManager.default.removeItem(at: directory) } func testBrowseReadingAndIndependentBookmarksRoundTripAcrossRelaunch() async throws { let store = LibraryContinuityStore(directory: directory) var browse = LibraryBrowseState() browse.scope = "Games"; browse.query = "adventure"; browse.selectedID = "personal:one" browse.filters = ["format":"disk", "sort":"name"]; browse.topVisibleID = "personal:two" store.setBrowse(browse, for: "software-main") let first = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "alpha", offset: 0.25) let second = LibraryReadingPosition(documentID: "book-two", relativePath: "book-two/chapter.html", anchor: "beta", offset: 0.5) let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Alpha", position: first)) store.setReading(second, for: "manual-last") store.renameBookmark(mark.id, label: "My reference") await store.flush() let restored = LibraryContinuityStore(directory: directory) XCTAssertEqual(restored.browse(for: "software-main"), browse) XCTAssertEqual(restored.reading(for: "manual-last"), second) XCTAssertEqual(restored.bookmarks.first?.position, first) XCTAssertEqual(restored.bookmarks.first?.displayName, "My reference") } func testDuplicateBookmarkPreservesOriginalLabelAndPosition() async throws { let store = LibraryContinuityStore(directory: directory) let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/a.html", anchor: "section", offset: 0.2) let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "Section", position: position)) store.renameBookmark(mark.id, label: "Keep this") var moved = position; moved.offset = 0.8 let again = store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "New heading", position: moved) XCTAssertEqual(again?.id, mark.id) XCTAssertEqual(store.bookmarks.count, 1) XCTAssertEqual(store.bookmarks.first?.position.offset, 0.2) XCTAssertEqual(store.bookmarks.first?.label, "Keep this") store.removeBookmark(mark.id) await store.flush() XCTAssertTrue(LibraryContinuityStore(directory: directory).bookmarks.isEmpty) } func testNewerOrUnreadableStateIsNeverOverwritten() async throws { let file = directory.appendingPathComponent("LibraryContinuity.json") for bytes in [Data("{\"version\":999,\"browse\":{},\"reading\":{},\"bookmarks\":[]}".utf8), Data("invalid json".utf8)] { try bytes.write(to: file, options: .atomic) let store = LibraryContinuityStore(directory: directory) XCTAssertNotNil(store.saveError) store.setBrowse(LibraryBrowseState(), for: "archive-main") await store.flush() XCTAssertEqual(try Data(contentsOf: file), bytes) } } func testInvalidPositionsCannotEscapeContentRootOrPersistNonfiniteValues() async throws { let store = LibraryContinuityStore(directory: directory) store.setReading(LibraryReadingPosition(documentID: "one", relativePath: "../private.html"), for: "bad-path") store.setReading(LibraryReadingPosition(documentID: "one", offset: .nan), for: "bad-offset") var browse = LibraryBrowseState(); browse.pageOffset = -1 store.setBrowse(browse, for: "bad-browse") await store.flush() XCTAssertNil(store.reading(for: "bad-path")); XCTAssertNil(store.reading(for: "bad-offset")) XCTAssertNil(store.browse(for: "bad-browse")) } func testManualScrollBookmarkAndResumeUseStableSectionInSeparateReader() async throws { _ = NSApplication.shared let contentRoot = directory.appendingPathComponent("Manuals") let book = contentRoot.appendingPathComponent("book-one") try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true) let page = book.appendingPathComponent("chapter.html") try """ One

Chapter

Alpha

Beta

""".write(to: page, atomically: true, encoding: .utf8) try "Home".write(to: contentRoot.appendingPathComponent("index.html"), atomically: true, encoding: .utf8) let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) let reader = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: store) reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) reader.webView.loadFileURL(page, allowingReadAccessTo: contentRoot) try await waitFor { reader.currentPosition?.relativePath == "book-one/chapter.html" } _ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();") try await waitFor { reader.currentPosition?.anchor == "beta" } reader.bookmarkCurrentLocation() try await waitFor { store.bookmarks.count == 1 } XCTAssertEqual(store.bookmarks.first?.sectionTitle, "Beta") await store.flush() let restoredStore = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) let reopened = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: restoredStore) reopened.webView.frame = reader.webView.frame reopened.resume() try await waitFor { reopened.currentPosition?.anchor == "beta" } XCTAssertGreaterThan(reopened.currentPosition?.offset ?? 0, 0) XCTAssertEqual(reopened.currentBookTitle, "Book One") XCTAssertEqual(restoredStore.bookmarks.count, 1) } func testImmediateBookmarkSamplesFreshScrollAndIgnoresSupersedingNavigation() async throws { _ = NSApplication.shared let root = directory.appendingPathComponent("Manuals") let book = root.appendingPathComponent("book-one") try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true) let page = book.appendingPathComponent("chapter.html") try """ One

Chapter

Alpha

Beta

""".write(to: page, atomically: true, encoding: .utf8) try "Home".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8) let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store) reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) reader.webView.loadFileURL(page, allowingReadAccessTo: root) try await waitFor { reader.currentPosition != nil } XCTAssertNotEqual(reader.currentPosition?.anchor, "beta") // Deliberately do not call the checkpoint or wait for its one-second // scroll timer before performing the user's bookmark action. _ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100)") reader.bookmarkCurrentLocation() try await waitFor { store.bookmarks.count == 1 } XCTAssertEqual(store.bookmarks[0].position.anchor, "beta") XCTAssertEqual(store.bookmarks[0].sectionTitle, "Beta") XCTAssertGreaterThan(store.bookmarks[0].position.offset, 0) store.removeBookmark(store.bookmarks[0].id) reader.bookmarkCurrentLocation() reader.showHome() try await waitFor { reader.currentPosition?.relativePath == "index.html" } XCTAssertTrue(store.bookmarks.isEmpty, "A checkpoint from a superseded page must not create a bookmark") } func testArchiveDeepLinkFindsExactDocumentOutsideFirstBrowseBatch() async throws { let database = directory.appendingPathComponent("Archive.sqlite") var handle: OpaquePointer? XCTAssertEqual(sqlite3_open(database.path, &handle), SQLITE_OK) defer { sqlite3_close(handle) } var sql = """ PRAGMA application_id=0x56434341; PRAGMA user_version=2; CREATE TABLE document(id INTEGER PRIMARY KEY,sha256 TEXT,title TEXT,collection TEXT,format TEXT,source_url TEXT,page_count INTEGER,issue_year TEXT); """ for n in 0..<72 { let digest = String(format: "%064x", n+1) sql += "INSERT INTO document VALUES(\(n+1),'\(digest)','Title \(String(format: "%03d", n))','Books','text','https://colorcomputerarchive.com/repo/Documents/Books/\(n).txt',1,NULL);" } XCTAssertEqual(sqlite3_exec(handle, sql, nil, nil, nil), SQLITE_OK) let catalog = ArchiveLibraryCatalog(url: database) let digest = String(format: "%064x", 61) let exact = try await catalog.document(id: digest) XCTAssertEqual(exact?.title, "Title 060") let offset = try await catalog.browseOffset(documentID: digest, collection: "Books", batchSize: 35) XCTAssertEqual(offset, 35) let rows = try await catalog.browse(collection: "Books", limit: 35, offset: offset ?? 0) XCTAssertTrue(rows.contains { $0.id == digest }) let malformed = try await catalog.document(id: "not-a-content-identity") XCTAssertNil(malformed) } func testTwoBookReadingPositionsAndBookmarksSurviveReaderAndStoreRecreation() async throws { _ = NSApplication.shared let root = try makeTwoBookManuals() let state = directory.appendingPathComponent("State") let store = LibraryContinuityStore(directory: state) let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store) reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) for book in ["book-one", "book-two"] { reader.webView.loadFileURL(root.appendingPathComponent(book + "/chapter.html"), allowingReadAccessTo: root) try await waitFor { reader.currentBookID == book } _ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();") try await waitFor { reader.currentPosition?.anchor == "beta" } reader.bookmarkCurrentLocation() try await waitFor { store.bookmarks.contains { $0.bookID == book } } } let originalBookmarks = store.bookmarks func assertSavedBookmarks(_ actual: [ManualBookmark], file: StaticString = #filePath, line: UInt = #line) { // Successful navigation may update location validation metadata; // the user's saved identity, label and position must stay fixed. XCTAssertEqual(actual.map(\.id), originalBookmarks.map(\.id), file: file, line: line) XCTAssertEqual(actual.map(\.position), originalBookmarks.map(\.position), file: file, line: line) XCTAssertEqual(actual.map(\.displayName), originalBookmarks.map(\.displayName), file: file, line: line) } let firstPosition = try XCTUnwrap(store.reading(for: "manual-book:book-one")) let secondPosition = try XCTUnwrap(store.reading(for: "manual-book:book-two")) XCTAssertNotEqual(firstPosition.relativePath, secondPosition.relativePath) await store.flush() let recreatedStore = LibraryContinuityStore(directory: state) let reopened = ManualReader(content: ManualLibraryContent(root: root), continuity: recreatedStore) reopened.webView.frame = reader.webView.frame reopened.resume() try await waitFor { reopened.currentBookID == "book-two" && reopened.currentPosition?.anchor == "beta" } XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-one"), firstPosition) assertSavedBookmarks(recreatedStore.bookmarks) // An explicit bookmark in another book wins over the last-active book. reopened.openBookmark(try XCTUnwrap(originalBookmarks.first { $0.bookID == "book-one" })) try await waitFor { reopened.currentBookID == "book-one" && reopened.currentPosition?.anchor == "beta" } _ = try await reopened.webView.evaluateJavaScript("window.scrollTo(0,0);window.vccLibraryCheckpoint();") try await waitFor { reopened.currentPosition?.anchor == nil } assertSavedBookmarks(recreatedStore.bookmarks) XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-two"), secondPosition) reopened.showHome() try await waitFor { reopened.currentPosition?.relativePath == "index.html" } reopened.resume() XCTAssertEqual(reopened.currentPosition?.relativePath, "index.html", "Explicit Library Home must not be replaced by automatic resume") await recreatedStore.flush() assertSavedBookmarks(LibraryContinuityStore(directory: state).bookmarks) } func testUpdatedManualMissingSectionAndPagePreserveBookmarksWithoutOpeningOtherContent() async throws { _ = NSApplication.shared let root = try makeTwoBookManuals() let state = directory.appendingPathComponent("State") let store = LibraryContinuityStore(directory: state) let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "removed-section", offset: 0.7) let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Removed section", position: position)) store.renameBookmark(mark.id, label: "Keep my reference") let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store) reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) reader.openBookmark(mark) try await waitFor { reader.error?.contains("Location changed") == true } XCTAssertEqual(reader.webView.url?.lastPathComponent, "chapter.html") let fallbackScroll = try await reader.webView.evaluateJavaScript("window.scrollY") as? Double XCTAssertEqual(fallbackScroll, 0) XCTAssertFalse(reader.bookmarkAvailable(try XCTUnwrap(store.bookmarks.first))) await store.flush() let preserved = try XCTUnwrap(LibraryContinuityStore(directory: state).bookmarks.first) XCTAssertEqual(preserved.id, mark.id) XCTAssertEqual(preserved.position, position) XCTAssertEqual(preserved.displayName, "Keep my reference") XCTAssertEqual(preserved.locationChanged, true) reader.showHome() try await waitFor { reader.currentPosition?.relativePath == "index.html" } try FileManager.default.removeItem(at: root.appendingPathComponent("book-one/chapter.html")) reader.openBookmark(preserved) XCTAssertTrue(reader.error?.contains("page is no longer") == true) XCTAssertEqual(reader.currentPosition?.relativePath, "index.html") XCTAssertEqual(store.bookmarks.first?.position, position) XCTAssertEqual(store.bookmarks.count, 1) } func testLegacyArchivePageMigratesToPersistentStateIndependentOfAssetCache() async throws { let pdf = PDFDocument() for color in [NSColor.white, .gray] { let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true } pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount) } let bytes = try XCTUnwrap(pdf.dataRepresentation()) let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() let key = "archive-library.page." + digest let original = UserDefaults.standard.object(forKey: key) defer { if let original { UserDefaults.standard.set(original, forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } } UserDefaults.standard.set(2, forKey: key) let cached = directory.appendingPathComponent(digest + ".pdf") try bytes.write(to: cached) let state = directory.appendingPathComponent("State") let store = LibraryContinuityStore(directory: state) let reader = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: store) defer { reader.reset() } reader.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300) let item = ArchiveDocument(id: digest, title: "Migration fixture", collection: "Books", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Migration.pdf")!, memberPath: nil, pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Migration.pdf")!, deliveryBytes: Int64(bytes.count)) reader.open(item, page: reader.savedPage(for: digest), resumePosition: true) try await waitFor { reader.progress == nil } XCTAssertNil(reader.error) XCTAssertEqual(reader.page, 2) reader.reset() await store.flush() // Clearing an asset cache or moving away from old preferences must not // clear the user's newly migrated reading position. try FileManager.default.removeItem(at: cached) UserDefaults.standard.removeObject(forKey: key) let recreated = LibraryContinuityStore(directory: state) let reopened = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: recreated) defer { reopened.reset() } XCTAssertEqual(reopened.savedPage(for: digest), 2) XCTAssertEqual(recreated.reading(for: "archive:" + digest)?.documentID, digest) XCTAssertFalse(FileManager.default.fileExists(atPath: cached.path)) } private func makeTwoBookManuals() throws -> URL { let root = directory.appendingPathComponent("Manuals") for book in ["book-one", "book-two"] { let folder = root.appendingPathComponent(book) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) try """ \(book)

Chapter

Alpha

Beta

""".write(to: folder.appendingPathComponent("chapter.html"), atomically: true, encoding: .utf8) } try "Library Home".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8) return root } private func waitFor(_ condition: () -> Bool) async throws { let deadline = ContinuousClock.now + .seconds(8) while !condition() { guard ContinuousClock.now < deadline else { XCTFail("Reader did not reach its expected state"); throw CocoaError(.fileReadUnknown) } try await Task.sleep(for: .milliseconds(25)) } } }