SPB Git

Repository Public

DevSelfTest.swift 53.2 KB 627 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/DevSelfTest.swift3// Description: Development variant only: the signed, sandboxed application exercises its own actions against the test backend — journal, transfer queue, downloads into the Downloads folder, versions, trash, share links, keychain — and writes a report. Nothing is simulated: every check reads the server or the disk.4#if SPD_DEV5import AppKit6import QuartzCore7import CryptoKit8import Foundation9import UniformTypeIdentifiers10import CoreImage11import SPDriveCore12import SPDriveNext13import SPDriveSync1415@MainActor16enum DevSelfTest {17    struct Check: Codable { var name: String; var ok: Bool; var detail: String }18    static func run(_ model: AppModel) async {19        var checks: [Check] = []20        func check(_ name: String, _ ok: Bool, _ detail: String = "") { checks.append(Check(name: name, ok: ok, detail: detail)) }21        func wait(_ seconds: Double = 20, _ cond: @MainActor () async -> Bool) async -> Bool {22            let end = Date().addingTimeInterval(seconds)23            while Date() < end { if await cond() { return true }; try? await Task.sleep(nanoseconds: 150_000_000) }24            return false25        }26        let out = AppEnvironment.containerURL.appendingPathComponent("selftest.json")27        try? FileManager.default.removeItem(at: out)28        defer { try? JSONEncoder().encode(checks).write(to: out) }29        guard let api = model.api, let store = model.store, await wait(20, { model.rootID != nil && model.status.lastSync != nil }), let root = model.rootID else { check("first sync", false, "no root"); return }30        check("first sync", true, "root known, \((try? store.counts().files) ?? 0) files mirrored")31        // the token really is in the shared keychain group (what the File Provider extension will read)32        check("keychain: device token readable", ((try? AppEnvironment.tokens.readToken()) ?? nil)?.isEmpty == false)33        let state = try? await api.authState()34        check("session is a device session", state?.kind == "device", state?.user?.email ?? "")3536        // --- folder, rename, star through the journal ---37        let name = "Autotest \(Int(Date().timeIntervalSince1970))"38        let local = model.createFolder(in: root, name: name)39        check("create folder: appears at once in the mirror", local != nil && model.children(of: root).contains { $0.name == name })40        let created = await wait(20) { (try? await api.listFolder(root).folders.contains { $0.name == name }) ?? false }41        check("create folder: confirmed by the server", created)42        guard await wait(20, { model.children(of: root).contains { $0.name == name && !model.isPending($0.id) } }), let folder = model.children(of: root).first(where: { $0.name == name }) else { check("folder id resolved", false); return }43        model.rename(folder, to: name + " renommé"); model.setStarred([folder], true)44        let renamed = await wait(20) { let i = (try? await api.item(folder.id, kind: .folder)) ?? nil; return i?.name == name + " renommé" && i?.starred == true }45        check("rename + favourite: confirmed by the server", renamed)4647        // --- upload through the queue (file created inside the sandbox), verified by hash ---48        let work = AppEnvironment.containerURL.appendingPathComponent("selftest-src", isDirectory: true)49        try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)50        let src = work.appendingPathComponent("données.bin")51        var bytes = Data(count: 3 * 1024 * 1024 + 17); bytes.withUnsafeMutableBytes { _ = SecRandomCopyBytes(kSecRandomDefault, $0.count, $0.baseAddress!) }52        try? bytes.write(to: src)53        let sha = Hashing.sha256Hex(bytes)54        await model.upload([src], to: folder.id)55        let uploaded = await wait(40) { (try? await api.listFolder(folder.id).files.first { $0.name == "données.bin" }?.sha256) == sha }56        check("upload: on the server with the same SHA-256", uploaded)57        guard let file = try? await api.listFolder(folder.id).files.first(where: { $0.name == "données.bin" }) else { check("uploaded file listed", false); return }58        _ = await wait(20) { model.item(file.id) != nil }59        check("upload: the mirror learnt the file", model.item(file.id)?.sha256 == sha)6061        // --- download into ~/Downloads (sandbox entitlement), verified ---62        let before = Set((try? FileManager.default.contentsOfDirectory(atPath: model.downloadsFolder.path)) ?? [])63        await model.download([file])64        let done = await wait(40) { model.transfers.contains { $0.direction == .download && $0.itemID == file.id && $0.state == .done } }65        let dest = model.transfers.first { $0.direction == .download && $0.itemID == file.id }.map { URL(fileURLWithPath: $0.localPath) }66        let same = dest.flatMap { try? Hashing.sha256Hex(of: $0).sha256 } == sha67        check("download: file in Downloads with the same SHA-256", done && same, dest?.lastPathComponent ?? "")68        if let dest, !before.contains(dest.lastPathComponent) { try? FileManager.default.removeItem(at: dest) }6970        // --- preview cache copy ---71        let copy = try? await model.localCopy(of: file)72        check("preview copy: verified local copy", copy.flatMap { try? Hashing.sha256Hex(of: $0).sha256 } == sha)7374        // --- new version, history, restore ---75        try? Data("version deux".utf8).write(to: src)76        await model.uploadNewVersion(of: file, from: src)77        let v2 = await wait(30) { ((try? await api.item(file.id, kind: .file)) ?? nil)?.versionSeq == 2 }78        check("new version: version 2 on the server", v2)79        if let d = try? await api.fileDetails(file.id), let first = d.versions.last {80            _ = try? await api.restoreVersion(fileID: file.id, versionID: first.id)81            let restored = (try? await api.item(file.id, kind: .file)) ?? nil82            check("restore version: creates version 3 with the first content", restored?.versionSeq == 3 && restored?.sha256 == sha)83        } else { check("version history readable", false) }8485        // --- share link, public access, revocation ---86        if let made = try? await api.createShare(for: file, settings: ShareSettings(label: "autotest", password: .some("autotest-1"))) {87            await model.refreshShares()88            check("share: listed and badge set", model.sharedIDs.contains(file.id))89            try? await api.revokeShare(made.share.id); await model.refreshShares()90            check("share: revoked", !model.sharedIDs.contains(file.id))91        } else { check("share: created", false) }9293        // --- duplicate, move, trash, restore ---94        model.duplicate([file])95        let dup = await wait(20) { ((try? await api.listFolder(folder.id).files.count) ?? 0) == 2 }96        check("duplicate: a second file on the server", dup)97        if let current = model.item(file.id) { model.trash([current]) }98        let trashed = await wait(20) { ((try? await api.item(file.id, kind: .file)) ?? nil)?.trashedAt != nil }99        check("delete: in the trash on the server (not destroyed)", trashed && model.trash().contains { $0.id == file.id })100        if let t = model.trash().first(where: { $0.id == file.id }) { model.restore([t]) }101        let back = await wait(20) { let i = (try? await api.item(file.id, kind: .file)) ?? nil; return i != nil && i?.trashedAt == nil }102        check("restore from trash: live again on the server", back)103104        // --- offline pin needs the Finder location; without it the app says so instead of pretending ---105        if !model.finderReady {106            await model.setPinned([file], true)107            check("offline pin without Finder location: refused with an explanation", !model.isPinned(file.id) && model.banner != nil)108        } else {109            await model.setPinned([file], true)110            let local = await wait(40) { model.isLocal(file.id) }111            check("offline pin: file materialised by the Finder location", local && model.isPinned(file.id))112        }113        await next(model, api: api, store: store, folder: folder, file: file, sha: sha, record: { check($0, $1, $2) }, wait: { s, c in await wait(s, c) })114        // --- clean up: everything this run created goes to the trash ---115        if let f = model.item(folder.id) { model.trash([f]) }116        _ = await wait(20) { ((try? await api.item(folder.id, kind: .folder)) ?? nil)?.trashedAt != nil }117        try? FileManager.default.removeItem(at: work)118        check("journal empty at the end", (try? model.engine?.journal.pendingCount()) == 0, "\(model.status.pendingOperations) pending")119    }120121    // MARK: SP Drive 2.0122    /// Checks of the 2.0 interface and engine, inside the signed, sandboxed app. Keys are posted to this app's own event queue (no global event, no other app involved).123    static func next(_ model: AppModel, api: APIClient, store: MetadataStore, folder: DriveItem, file: DriveItem, sha: String, record: (String, Bool, String) -> Void,124                     wait: (Double, @MainActor () async -> Bool) async -> Bool) async {125        func check(_ n: String, _ ok: Bool, _ detail: String = "") { record(n, ok, detail) }126        let nav = model.nav127        // a launch that goes through device linking may still be putting its window up: give it a moment, and say what is there if it never comes128        _ = await wait(10) { NSApp.windows.contains { $0.isVisible && $0.canBecomeMain } }129        guard let window = NSApp.windows.first(where: { $0.isVisible && $0.canBecomeMain }) else {130            let seen = NSApp.windows.map { "\($0.title.isEmpty ? "(untitled)" : $0.title):visible=\($0.isVisible),mini=\($0.isMiniaturized),main=\($0.canBecomeMain),\(type(of: $0))" }.joined(separator: "; ")131            check("a main window exists", false, "hidden=\(NSApp.isHidden) active=\(NSApp.isActive) windows=[\(seen)]"); return132        }133        func key(_ code: UInt16, _ chars: String = "", flags: NSEvent.ModifierFlags = []) async {134            if let e = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil,135                                        characters: chars, charactersIgnoringModifiers: chars, isARepeat: false, keyCode: code) { NSApp.postEvent(e, atStart: false) }136            try? await Task.sleep(nanoseconds: 250_000_000)137        }138        window.makeFirstResponder(nil)139140        // --- engine policy as the app sees it ---141        await model.refreshPolicy()142        check("policy: adaptive concurrency within 1…6", (1...6).contains(model.policy.concurrency) && model.policy.manual == nil, "\(model.policy.concurrency) now, measured limit \(model.policy.measuredLimit)")143        let wantStream = model.has(.events)144        let channel = await wait(15) { model.status.events == (wantStream ? .stream : .polling) }145        check(wantStream ? "events: the server's event stream is live" : "events: polling fallback is listening", channel, model.status.events.rawValue)146        check("power: state read from the system", model.power.lowPowerMode == ProcessInfo.processInfo.isLowPowerModeEnabled, "battery \(model.power.onBattery) level \(model.power.level.map { String($0) } ?? "none")")147148        // --- three more files, one of them a real image, to navigate among ---149        let work = AppEnvironment.containerURL.appendingPathComponent("selftest-next", isDirectory: true)150        try? FileManager.default.removeItem(at: work); try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)151        let img = NSImage(size: NSSize(width: 320, height: 200)); img.lockFocus(); NSColor.systemIndigo.setFill(); NSRect(x: 0, y: 0, width: 320, height: 200).fill(); NSColor.white.setFill(); NSBezierPath(ovalIn: NSRect(x: 110, y: 50, width: 100, height: 100)).fill(); img.unlockFocus()152        let png = img.tiffRepresentation.flatMap { NSBitmapImageRep(data: $0)?.representation(using: .png, properties: [:]) } ?? Data()153        try? png.write(to: work.appendingPathComponent("image.png"))154        try? Data("alpha".utf8).write(to: work.appendingPathComponent("alpha.txt")); try? Data("zoulou".utf8).write(to: work.appendingPathComponent("zoulou.txt"))155        // dropped on the folder exactly as a drag from the Finder would arrive (file URL providers)156        let providers = ["image.png", "alpha.txt", "zoulou.txt"].map { NSItemProvider(object: work.appendingPathComponent($0) as NSURL) }157        let accepted = Drops.handle(providers, into: folder.id, model: model)158        let arrived = await wait(40) { ((try? await api.listFolder(folder.id).files.map(\.name)) ?? []).filter { ["image.png", "alpha.txt", "zoulou.txt"].contains($0) }.count == 3 }159        check("drop in: file URLs dropped on a folder are uploaded there", accepted && arrived)160        _ = await wait(20) { model.children(of: folder.id).count >= 4 }161        let serverImage = await wait(30) { ((try? await api.listFolder(folder.id).files.first { $0.name == "image.png" }?.hasThumbnail) ?? false) }162        // the mirror learnt of the file before the server drew its thumbnail, and the change feed does not announce a thumbnail: the app must find it anyway163        let mirrorKnows = model.children(of: folder.id).first { $0.name == "image.png" }?.hasThumbnail == true164165        // --- grid with a real thumbnail ---166        nav.go(to: folder.id); model.settings.gridView = true; model.settings.gridSize = 1167        try? await Task.sleep(nanoseconds: 900_000_000)168        let rows = model.children(of: folder.id).sorted { NameRules.searchKey($0.name) < NameRules.searchKey($1.name) }169        if let pic = rows.first(where: { $0.name == "image.png" }) {170            let got = await wait(45) { model.thumbnails.cached(pic) != nil }171            check("thumbnails: the grid shows the server's real thumbnail", serverImage && got, "mirror flag \(mirrorKnows), \(model.thumbnails.fetched) fetched, \(model.thumbnails.cached(pic).map { "\(Int($0.size.width))×\(Int($0.size.height))" } ?? "none")")172        } else { check("thumbnails: image listed", false) }173174        // --- keyboard: arrows in the grid, type-select, Return renames in place, Space opens Quick Look ---175        guard rows.count >= 4 else { check("keyboard: four items to navigate", false, "\(rows.count)"); return }176        nav.selection = [rows[0].id]; nav.anchorID = rows[0].id177        await key(Key.right)178        check("keyboard: → moves the selection to the next item of the grid", nav.selection == [rows[1].id], nav.selection.compactMap { model.item($0)?.name }.joined())179        await key(Key.left); await key(Key.right, flags: .shift)180        check("keyboard: ⇧→ extends the selection", nav.selection == [rows[0].id, rows[1].id])181        nav.selection = []182        await key(6, "z"); await key(31, "o")183        check("keyboard: typing “zo” selects the item whose name starts with it", nav.selection.compactMap { model.item($0)?.name } == ["zoulou.txt"])184        await key(Key.return, "\r")185        let renaming = nav.renamingID != nil && window.firstResponder is NSText186        check("keyboard: Return starts renaming in place, the name field has the focus", renaming, "renaming \(nav.renamingID != nil), responder \(type(of: window.firstResponder as Any))")187        if let editor = window.firstResponder as? NSText { editor.string = "zèbre.txt" }188        await key(Key.return, "\r")189        let renamed = await wait(15) { ((try? await api.listFolder(folder.id).files.contains { $0.name == "zèbre.txt" }) ?? false) }190        check("rename in place: confirmed by the server", renamed && nav.renamingID == nil)191        model.settings.gridView = false; try? await Task.sleep(nanoseconds: 700_000_000)192        if let a = model.children(of: folder.id).first(where: { $0.name == "alpha.txt" }) {193            window.makeFirstResponder(nil); nav.selection = [a.id]194            let before = QuickLookCoordinator.shared.presentations195            await key(Key.space, " ")196            let shown = await wait(10) { QuickLookCoordinator.shared.isVisible && QuickLookCoordinator.shared.itemID == a.id }197            let frame = AnchorRegistry.shared.screenFrame(a.id)198            check("Quick Look: Space opens the system panel on the selected file", shown && QuickLookCoordinator.shared.presentations == before + 1)199            check("Quick Look: the zoom starts from the item's picture on screen", frame.map { window.frame.intersects($0) && $0.width > 4 } ?? false, frame.map { "\(Int($0.width))×\(Int($0.height)) at \(Int($0.minX)),\(Int($0.minY))" } ?? "no frame")200            await key(Key.space, " ")201            let closed = await wait(5) { !QuickLookCoordinator.shared.isVisible }202            check("Quick Look: Space again closes it", closed)203            QuickLookCoordinator.shared.close()204        }205        if let k = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "k", charactersIgnoringModifiers: "k", isARepeat: false, keyCode: 40) {206            _ = k207            // the real menu item: its key equivalent is ⌘K and performing it opens the palette of the focused window208            func find(_ menu: NSMenu?) -> (NSMenu, Int)? {209                guard let menu else { return nil }210                menu.delegate?.menuNeedsUpdate?(menu); menu.update() // what happens when the person opens the menu211                for (i, item) in menu.items.enumerated() { if item.title.hasPrefix("Palette de commandes") { return (menu, i) }; if let hit = find(item.submenu) { return hit } }212                return nil213            }214            // menu commands are only valid for the active app's focused window: activate for a moment (under a second), then step back215            NSApp.activate(ignoringOtherApps: true); window.makeKeyAndOrderFront(nil)216            try? await Task.sleep(nanoseconds: 500_000_000)217            defer { NSApp.deactivate() }218            NSApp.mainMenu?.update()219            let hit = find(NSApp.mainMenu)220            let equivalent = hit.map { $0.0.items[$0.1].keyEquivalent == "k" && $0.0.items[$0.1].keyEquivalentModifierMask == .command } ?? false221            if let hit { hit.0.performActionForItem(at: hit.1) }222            try? await Task.sleep(nanoseconds: 400_000_000)223            // menus validate from the focused window: with nothing selected "Dupliquer" is off, with one file selected it is on224            func enabled(_ title: String) -> Bool? { func f(_ m: NSMenu?) -> NSMenuItem? { guard let m else { return nil }; m.delegate?.menuNeedsUpdate?(m); m.update(); for it in m.items { if it.title == title { return it }; if let h = f(it.submenu) { return h } }; return nil }; return f(NSApp.mainMenu)?.isEnabled }225            nav.selection = []; try? await Task.sleep(nanoseconds: 400_000_000)226            let offWhenEmpty = enabled("Dupliquer") == false227            if let a = model.children(of: folder.id).first(where: { !$0.isFolder }) { nav.selection = [a.id] }228            try? await Task.sleep(nanoseconds: 400_000_000)229            let onWhenSelected = enabled("Dupliquer") == true230            nav.selection = []231            check("menus: commands enable and disable with the focused window's selection", offWhenEmpty && onWhenSelected, "empty→off \(offWhenEmpty), selected→on \(onWhenSelected)")232            check("⌘K: the menu command exists with that key equivalent and opens the command palette", equivalent && nav.showPalette, "item \(hit != nil), equivalent \(equivalent), enabled \(hit.map { $0.0.items[$0.1].isEnabled } ?? false), key window is main \(NSApp.keyWindow === window), active \(NSApp.isActive)")233        }234        await key(Key.escape)235        check("Escape closes it", !nav.showPalette)236        nav.showPalette = false237238        // --- command palette: real commands ---239        nav.selection = []240        var openedWindow = false241        let commands = CommandCatalog.commands(model: model, nav: nav, openWindow: { openedWindow = true }, openSettings: {})242        CommandCatalog.results(for: "récents", commands: commands, model: model, nav: nav).first?.run()243        let went = nav.section == .recent244        nav.go(to: folder.id)245        CommandCatalog.results(for: "nouveau dossier", commands: commands, model: model, nav: nav).first?.run()246        let asked = nav.sheet == .newFolder(parent: folder.id); nav.sheet = nil247        CommandCatalog.results(for: "grille", commands: commands, model: model, nav: nav).first?.run()248        let grid = model.settings.gridView; model.settings.gridView = false249        CommandCatalog.results(for: "nouvelle fenêtre", commands: commands, model: model, nav: nav).first?.run()250        nav.go(to: nil)251        let hits = CommandCatalog.results(for: "alpha", commands: commands, model: model, nav: nav).filter { $0.group == .item }252        hits.first?.run()253        check("palette: \(commands.count) commands; go to section, new folder, grid, new window run for real", commands.count >= 20 && went && asked && grid && openedWindow)254        check("palette: finds a file of the mirror and takes you to it", nav.folderID == folder.id && nav.selection.compactMap { model.item($0)?.name } == ["alpha.txt"], "\(hits.count) hit(s)")255256        // --- drag out: what a drop in the Finder would receive ---257        if let current = model.item(file.id) {258            let provider = Drops.provider(for: current, model: model)259            let type = (UTType(filenameExtension: current.fileExtension) ?? .data).identifier260            let got: String = await withCheckedContinuation { c in261                _ = provider.loadFileRepresentation(forTypeIdentifier: type) { url, error in262                    guard let url else { c.resume(returning: "error: \(error?.localizedDescription ?? "no file")"); return }263                    do { c.resume(returning: try Hashing.sha256Hex(of: url).sha256) } catch { c.resume(returning: "unreadable: \(error.localizedDescription)") }264                }265            }266            check("drag out: the dragged item delivers a verified file (same SHA-256 as the server)", got == current.sha256 && provider.hasItemConformingToTypeIdentifier(UTType.spdriveItem.identifier), "\(provider.suggestedName ?? "") \(type) \(got == current.sha256 ? "" : got)")267        }268269        // --- a second window has its own navigator ---270        let mainsBefore = NSApp.windows.filter { $0.isVisible && $0.canBecomeMain }.count271        AppDelegate.openMainWindow?()272        let two = await wait(6) { NSApp.windows.filter { $0.isVisible && $0.canBecomeMain }.count == mainsBefore + 1 }273        check("multiple windows: a second main window opens on the same account", two)274        if let extra = NSApp.windows.filter({ $0.isVisible && $0.canBecomeMain }).first(where: { $0 !== window }) { extra.close() }275276        // --- a real conflict, settled as "keep mine as a new version" ---277        try? Data("version de départ".utf8).write(to: work.appendingPathComponent("accord.txt"))278        await model.upload([work.appendingPathComponent("accord.txt")], to: folder.id)279        _ = await wait(30) { model.children(of: folder.id).contains { $0.name == "accord.txt" && $0.versionID != nil } }280        if let base = model.children(of: folder.id).first(where: { $0.name == "accord.txt" }), let engine = model.engine {281            try? Data("version de l’autre appareil".utf8).write(to: work.appendingPathComponent("autre.txt"))282            _ = try? await UploadEngine(api: api, store: nil, deviceName: "Autre appareil").upload(file: work.appendingPathComponent("autre.txt"), to: .newVersion(fileID: base.id, folderID: folder.id, name: base.name, baseVersionID: base.versionID))283            // this Mac sends an edit derived from the version it knew: the queue names that version284            try? Data("version de ce Mac".utf8).write(to: work.appendingPathComponent("mien.txt"))285            _ = engine286            await model.uploadNewVersion(of: base, from: work.appendingPathComponent("mien.txt")) // `base` is what this Mac's mirror knew: now stale287            let raised = await wait(30) { model.conflicts.contains { $0.isOpen && $0.itemID == base.id } }288            let untouched = (try? await api.data(for: api.contentRequest(fileID: base.id)).0).map { String(decoding: $0, as: UTF8.self) }289            check("conflict: a stale edit raises a conflict and overwrites nothing", raised && untouched == "version de l’autre appareil", untouched ?? "")290            if let c = model.conflicts.first(where: { $0.isOpen && $0.itemID == base.id }) {291                nav.sheet = .conflict(c)292                let presented = await wait(6) { window.attachedSheet != nil }293                try? await Task.sleep(nanoseconds: 2_500_000_000)294                DevTour.snapshot("conflict-sheet", into: AppEnvironment.containerURL)295                check("conflict: the comparison sheet is presented", presented)296                nav.sheet = nil; try? await Task.sleep(nanoseconds: 700_000_000)297                let ok = await model.resolve(c, .mineAsVersion)298                let now = (try? await api.data(for: api.contentRequest(fileID: base.id)).0).map { String(decoding: $0, as: UTF8.self) }299                let d = try? await api.fileDetails(base.id)300                let copyGone = (c.copyID != nil) ? (((try? await api.item(c.copyID!, kind: .file)) ?? nil)?.trashedAt != nil) : false301                check("conflict: “keep mine” makes it version 3; the server's version stays in the history; the copy goes to the trash", ok && now == "version de ce Mac" && d?.versions.count == 3 && copyGone && !model.conflicts.contains { $0.isOpen && $0.id == c.id }, "\(d?.versions.count ?? 0) versions")302            }303        } else { check("conflict: base file uploaded", false) }304305        // --- desktop drop zone: off by default, on and off again ---306        let wasOff = !model.settings.dropZone && !DropZoneController.shared.isShown307        model.settings.dropZone = true; DropZoneController.shared.update(model: model)308        let on = DropZoneController.shared.isShown, stillKey = NSApp.keyWindow !== NSApp.windows.first { $0 is NSPanel && $0.level == .floating }309        try? await Task.sleep(nanoseconds: 400_000_000)310        model.settings.dropZone = false; DropZoneController.shared.update(model: model)311        check("drop zone: off by default, shows without taking the key window, hides", wasOff && on && stillKey && !DropZoneController.shared.isShown)312313        // --- Spotlight: metadata only, removable ---314        let attrs = SpotlightIndexer.attributes(for: file, path: "Autotest")315        check("Spotlight: the attribute set carries metadata only (no text content)", attrs.textContent == nil && attrs.contentDescription == nil && attrs.title == file.name)316        model.settings.spotlightIndex = true317        await SpotlightIndexer.shared.sync(model: model)318        let indexed = SpotlightIndexer.shared.lastIndexed319        let found = await wait(20) { await SpotlightIndexer.shared.count(named: "alpha.txt") >= 1 }320        model.settings.spotlightIndex = false321        await SpotlightIndexer.shared.removeAll()322        let removed = await wait(20) { await SpotlightIndexer.shared.count(named: "alpha.txt") == 0 }323        check("Spotlight: items indexed, found by name, then removed", indexed > 0 && found && removed, "\(indexed) indexed, found \(found), removed \(removed)")324        if model.meta.api >= 2 { await next2(model, api: api, store: store, folder: folder, work: work, record: record, wait: wait) }325        try? FileManager.default.removeItem(at: work)326        nav.go(to: nil); model.settings.gridView = false327    }328329    /// SP Drive 2.0 against a 2.0 server. The AI provider of the test backend is a FAKE (Scripts/fake-ai.mjs): these checks prove the app's side of the protocol, not a model.330    static func next2(_ model: AppModel, api: APIClient, store: MetadataStore, folder: DriveItem, work: URL, record: (String, Bool, String) -> Void,331                      wait: (Double, @MainActor () async -> Bool) async -> Bool) async {332        func check(_ n: String, _ ok: Bool, _ detail: String = "") { record(n, ok, detail) }333        guard let next = model.next else { check("2.0: client available", false); return }334        let nav = model.nav335        check("2.0: capabilities read from GET /meta", model.meta.api == 2 && model.has(.collab) && model.has(.collections), model.meta.features.joined(separator: " "))336        let sessions = (try? await next.sessions()) ?? []337        let me = sessions.first(where: \.current)338        check("X-SPD-Client: this session is known to the server as macos/2.0.0", me?.client?.platform == "macos" && me?.client?.version == "2.0.0", "\(me?.client?.platform ?? "?")/\(me?.client?.version ?? "?") (\(me?.client?.os ?? "?"))")339340        // --- a change made by another client arrives through the stream, without a poll ---341        let t0 = Date()342        let remote = try? await api.createFolder(parent: folder.id, name: "créé par un autre client")343        let pushed = await wait(4) { remote.map { model.item($0.id) != nil } ?? false }344        check("events: a change made elsewhere reaches the mirror in under 4 s (stream, not the 30 s poll)", pushed && model.status.events == .stream, String(format: "%.2f s", Date().timeIntervalSince(t0)))345346        // --- search 2.0 ---347        let word = "zq\(Int(Date().timeIntervalSince1970) % 100000)x"348        try? Data("Procès-verbal\nLe \(word) de la coopérative est adopté.\nDépôt de garantie : 500 dollars avant le 1er juin.".utf8).write(to: work.appendingPathComponent("Procès-verbal.txt"))349        await model.upload([work.appendingPathComponent("Procès-verbal.txt")], to: folder.id)350        _ = await wait(30) { model.children(of: folder.id).contains { $0.name == "Procès-verbal.txt" && $0.versionID != nil } }351        guard let pv = model.children(of: folder.id).first(where: { $0.name == "Procès-verbal.txt" }) else { check("search: test document uploaded", false); return }352        let indexed = await wait(45) { ((try? await next.fileText(pv.id).status) ?? "") == "ready" }353        let hits = try? await next.search(word)354        let hit = hits?.files.first { $0.id == pv.id }355        check("search 2.0: a word found only inside a document is returned with a highlighted passage", indexed && hit?.match?.where == "content" && (hit?.match?.snippetRuns.contains { $0.matched && $0.text.lowercased() == word } ?? false), hit?.match?.snippet ?? "no hit")356        nav.go(to: nil); nav.searchText = word357        try? await Task.sleep(nanoseconds: 1_800_000_000)358        DevTour.snapshot("search-content", into: AppEnvironment.containerURL)359        nav.searchText = ""360361        // --- AI (fake provider) ---362        let providers = try? await next.aiProviders()363        let session = AskSession(); await session.load(model)364        session.question = "Quel est le montant du dépôt de garantie ?"; session.ask(model, scope: .files([pv.id]))365        _ = await wait(30) { session.turns.last?.streaming == false }366        let turn = session.turns.last367        check("AI: providers listed; creator and provider are told apart", providers?.enabled == true && providers?.providers.first { $0.id == "maclustr" }?.models.first?.creator != nil, "default \(providers?.default?.model ?? "none")")368        check("AI: a streamed answer with numbered sources (FAKE provider — no real model)", turn?.failure == nil && (turn?.answer.contains("[1]") ?? false) && turn?.sources.first?.fileId == pv.id && turn?.done != nil, turn?.failure ?? String((turn?.answer ?? "").prefix(80)))369        session.question = "xyzzyqq wobblefrotz"; session.ask(model, scope: .folder(folder.id))370        _ = await wait(30) { session.turns.last?.streaming == false }371        check("AI: nothing retrieved is said as such, without calling the model", session.turns.last?.done?.empty == true && session.turns.last?.answer.isEmpty == true)372373        // --- collections ---374        let rule = CollectionRule(conditions: [RuleCondition(field: "name", op: "contains", value: .string("Procès")), RuleCondition(field: "folder", op: "is", value: .string(folder.id))])375        let made = try? await next.createCollection(CollectionDraft(name: "Autotest \(word)", icon: "doc.text", color: "teal", rule: rule))376        await model.refreshCollections()377        let listed = model.collections.first { $0.id == made?.id }378        check("collections: created, listed in the sidebar with its live count", listed?.count == 1, "count \(listed?.count ?? -1)")379        if let made { nav.collectionID = made.id; nav.section = .collections; try? await Task.sleep(nanoseconds: 1_200_000_000); DevTour.snapshot("collection", into: AppEnvironment.containerURL); try? await next.deleteCollection(made.id); await model.refreshCollections() }380        check("collections: deleted (files untouched)", !model.collections.contains { $0.id == made?.id } && model.item(pv.id) != nil)381        nav.section = .drive382383        // --- versions and comparison ---384        try? Data("Procès-verbal\nLe \(word) de la coopérative est adopté à l'unanimité.\nDépôt de garantie : 750 dollars avant le 1er juin.\nProchaine assemblée en janvier.".utf8).write(to: work.appendingPathComponent("pv2.txt"))385        await model.uploadNewVersion(of: pv, from: work.appendingPathComponent("pv2.txt"))386        let two = await wait(30) { ((try? await next.versions(of: pv.id).versions.count) ?? 0) == 2 }387        let versions = (try? await next.versions(of: pv.id).versions) ?? []388        var diff: [LineDiff.Line] = []389        if versions.count == 2 {390            let a = work.appendingPathComponent("a.txt"), b = work.appendingPathComponent("b.txt")391            let s1 = try? await next.downloadVersion(fileID: pv.id, versionID: versions[1].id, to: a), s2 = try? await next.downloadVersion(fileID: pv.id, versionID: versions[0].id, to: b)392            if s1 == versions[1].sha256, s2 == versions[0].sha256, let x = try? String(contentsOf: a, encoding: .utf8), let y = try? String(contentsOf: b, encoding: .utf8) { diff = LineDiff.lines(x, y) ?? [] }393        }394        check("versions: timeline with author; text comparison shows what changed", two && versions.first?.createdBy?.me == true && diff.filter { $0.kind == .added }.count == 3 && diff.filter { $0.kind == .removed }.count == 2 && diff.filter { $0.kind == .same }.count == 1,395              "+\(diff.filter { $0.kind == .added }.count) −\(diff.filter { $0.kind == .removed }.count)")396        if let current = model.item(pv.id) { nav.go(to: folder.id); nav.sheet = .versions(current); try? await Task.sleep(nanoseconds: 2_000_000_000); DevTour.snapshot("versions-timeline", into: AppEnvironment.containerURL); nav.sheet = nil; try? await Task.sleep(nanoseconds: 700_000_000) }397398        // --- activity, storage, duplicates ---399        let feed = (try? await next.fileActivity(pv.id).events) ?? []400        check("activity: the file's real audit trail (upload, then new version)", feed.map(\.action) == ["file.version_added", "file.uploaded"] && feed.allSatisfy { $0.actor.me == true }, feed.map(\.action).joined(separator: ", "))401        let overview = try? await next.storageOverview()402        let drill = try? await next.storageFolder(folder.id)403        check("storage: overview by kind and by folder, drill-down into a folder", (overview?.byKind.isEmpty == false) && (overview?.byFolder.isEmpty == false) && drill?.breadcrumbs.last?.id == folder.id, "\(overview?.byKind.count ?? 0) kinds, \(drill?.direct.files ?? 0) files here")404        let before = model.children(of: folder.id).count405        let dup = try? await next.duplicates()406        check("duplicates: listed, and looking deletes nothing", dup != nil && model.children(of: folder.id).count == before, "\(dup?.groups.count ?? -1) group(s)")407408        // --- private sharing: owner side, then a folder shared WITH this account by the second test account ---409        let team = model.createFolder(in: folder.id, name: "Équipe")410        _ = await wait(20) { model.children(of: folder.id).contains { $0.name == "Équipe" && !model.isPending($0.id) } }411        if let teamFolder = model.children(of: folder.id).first(where: { $0.name == "Équipe" }), team != nil {412            let who = try? await next.resolveUser(email: "member@example.test")413            let added = try? await next.addMember(to: teamFolder.id, email: "member@example.test", as: .viewer, workspaceName: "Équipe test")414            let members = try? await next.members(of: teamFolder.id)415            check("sharing: a member is added by exact e-mail with a role; the folder becomes a named workspace", added?.role == .viewer && members?.members.count == 1 && members?.folder.workspaceName == "Équipe test", who?.displayName ?? "second account not found")416            nav.go(to: folder.id); nav.sheet = .members(teamFolder); try? await Task.sleep(nanoseconds: 1_800_000_000); DevTour.snapshot("members-sheet", into: AppEnvironment.containerURL); nav.sheet = nil; try? await Task.sleep(nanoseconds: 600_000_000)417            if let who { try? await next.removeMember(of: teamFolder.id, userID: who.userId) }418            let gone = try? await next.members(of: teamFolder.id); check("sharing: access removed", gone?.members.isEmpty == true)419        } else { check("sharing: folder created", false) }420        await model.refreshGrants()421        if let g = model.grants.first(where: { $0.role == .editor }) {422            let listing = try? await next.sharedChildren(grant: g.grantId)423            try? Data("apport de l’autotest".utf8).write(to: work.appendingPathComponent("apport.txt"))424            let sent = try? await next.uploadShared(grant: g.grantId, file: work.appendingPathComponent("apport.txt"), name: "apport \(word).txt")425            let after = try? await next.sharedChildren(grant: g.grantId)426            check("shared with me: an editor browses the folder and uploads into it", listing?.folder.isGrantRoot == true && (listing?.files.isEmpty == false) && sent != nil && (after?.files.contains { $0.id == sent?.file.id } ?? false), "\(g.displayName), \(after?.files.count ?? 0) files")427            if let sent { try? await next.sharedTrash(grant: g.grantId, fileIDs: [sent.file.id]) }428        } else { check("shared with me: a folder shared by the second account is listed (run Scripts/seed-next.sh --collab)", false, "\(model.grants.count) grant(s)") }429        if let u = model.grants.first(where: { $0.role == .uploader }) {430            var forbidden = false431            do { _ = try await next.sharedChildren(grant: u.grantId) } catch { forbidden = NextError.wrap(error).isForbidden }432            let dropped = try? await next.uploadShared(grant: u.grantId, file: work.appendingPathComponent("apport.txt"), name: "dépôt \(word).txt")433            check("shared with me: a depositor cannot list (403) but can send a file in", forbidden && dropped?.file.name == "dépôt \(word).txt")434        }435436        // --- QR code, devices, administration ---437        let link = "https://drive.spboucher.ai/s/EXEMPLE-\(word)"438        var decoded: String?439        if let img = QRCode.image(link), let tiff = img.tiffRepresentation, let ci = CIImage(data: tiff) {440            decoded = (CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])?.features(in: ci).first as? CIQRCodeFeature)?.messageString441        }442        check("QR code: generated on this Mac and reads back as the link", decoded == link)443        check("devices: sessions listed with platform and app version", sessions.contains { $0.client != nil } && sessions.contains(where: \.current), "\(sessions.count) session(s)")444        if model.isAdmin { let sys = try? await next.adminSystem(); check("administration: infrastructure view readable by an administrator", sys?.version == "2.0.0" && sys?.worker != nil, "worker alive \(String(describing: sys?.worker?.alive))") }445        await onScreen(model, api: api, next: next, folder: folder, pv: pv, record: record, wait: wait)446        nav.section = .drive; nav.go(to: nil)447    }448449    /// The same things done ON SCREEN: sheets and windows are really presented, and their own controls are pressed450    /// through the accessibility tree of this app (what a click does), then the server or the model is read.451    static func onScreen(_ model: AppModel, api: APIClient, next: NextClient, folder: DriveItem, pv: DriveItem, record: (String, Bool, String) -> Void,452                         wait: (Double, @MainActor () async -> Bool) async -> Bool) async {453        func check(_ n: String, _ ok: Bool, _ detail: String = "") { record("on screen — " + n, ok, detail) }454        func pause(_ s: Double) async { try? await Task.sleep(nanoseconds: UInt64(s * 1e9)) }455        func appear(_ id: String, _ seconds: Double = 12) async -> Bool { await wait(seconds) { AX.element(id: id) != nil } }456        func shot(_ name: String, window: NSWindow? = nil) { DevTour.snapshot(name, into: AppEnvironment.containerURL, window: window) }457        let nav = model.nav458        nav.section = .drive; nav.go(to: folder.id); nav.selection = [pv.id]; await pause(0.6)459        record("on screen — the accessibility API answers for this process (the checks below press real controls through it)", AX.available, "")460461        // --- ask a document, then click the citation ---462        UserDefaults.standard.set("Quel est le montant du dépôt de garantie ?", forKey: "spdAsk")463        nav.sheet = .ask(pv)464        let cited = await wait(30) { AX.element(labelPrefix: "Source 1") != nil }465        shot("ask-sheet")466        UserDefaults.standard.removeObject(forKey: "spdAsk")467        nav.go(to: nil); nav.selection = []468        AX.press(AX.element(labelPrefix: "Source 1"))469        let revealed = await wait(6) { nav.sheet == nil && nav.selection == [pv.id] && nav.folderID == folder.id }470        check("a citation of the answer, pressed, closes the sheet and shows its file selected in its folder", cited && revealed, "source shown \(cited)")471        nav.sheet = nil; await pause(0.6)472473        // --- the "Demander à mon Drive" window ---474        AskWindow.open()475        let askWindow = await wait(8) { NSApp.windows.contains { $0.isVisible && $0.title == "Demander à mon Drive" } }476        let field = await appear("ask-field", 10)477        if let w = NSApp.windows.first(where: { $0.title == "Demander à mon Drive" }) { shot("ask-window", window: w); w.close() }478        NSApp.deactivate()479        check("the “Demander à mon Drive” window opens with its question field", askWindow && field, "window \(askWindow), field \(field), opener \(AppDelegate.openAskWindow != nil), titles \(NSApp.windows.filter(\.isVisible).map(\.title))")480481        // --- Settings › Compte: devices list, and the external-AI consent switch ---482        UserDefaults.standard.set("account", forKey: "settingsTab")483        NSApp.activate(ignoringOtherApps: true); AppDelegate.openSettings?()484        let toggle = await appear("ai-external-toggle", 12)485        let devices = AX.count(id: "device-row")486        let settings = NSApp.windows.first { w in w.isVisible && !w.canBecomeMain || w.title == "Compte" || w.identifier?.rawValue.contains("Settings") == true }487        shot("settings-account", window: settings)488        check("Settings › Compte lists the connected devices", toggle && devices >= 1, "\(devices) device row(s)")489        let before = (try? await next.aiProviders().external?.account) ?? false490        AX.press(AX.element(id: "ai-external-toggle"))491        let flipped = await wait(8) { ((try? await next.aiProviders().external?.account) ?? before) != before }492        AX.press(AX.element(id: "ai-external-toggle"))493        let restored = await wait(8) { ((try? await next.aiProviders().external?.account) ?? !before) == before }494        check("the external-AI consent switch changes the account's flag on the server, and back", flipped && restored, "was \(before)")495        settings?.close(); UserDefaults.standard.set("general", forKey: "settingsTab"); NSApp.deactivate()496497        // --- saving a collection from the rule editor ---498        let rule = CollectionRule(conditions: [RuleCondition(field: "folder", op: "is", value: .string(folder.id)), RuleCondition(field: "ext", op: "is", value: .string("txt"))])499        if let made = try? await next.createCollection(CollectionDraft(name: "Écran \(Int(Date().timeIntervalSince1970) % 100000)", icon: "doc.text", color: "green", rule: rule)) {500            await model.refreshCollections(); try? await Task.sleep(nanoseconds: 1_100_000_000)501            nav.sheet = .collection(model.collections.first { $0.id == made.id })502            let button = await appear("save-collection")503            _ = await wait(6) { AX.element(labelPrefix: "Enregistrer") != nil }504            await pause(1.2) // the live preview settles505            shot("collection-editor")506            AX.press(AX.element(id: "save-collection"))507            let saved = await wait(8) { nav.sheet == nil && nav.section == .collections && nav.collectionID == made.id }508            let after = try? await next.collections().first { $0.id == made.id }509            check("the rule editor's Save button saves the collection and shows it", button && saved && (after?.updatedAt ?? .distantPast) > (made.updatedAt ?? .distantFuture), "updated \(after?.updatedAt.map { Fmt.date($0) } ?? "?")")510            nav.sheet = nil; try? await next.deleteCollection(made.id); await model.refreshCollections()511        } else { check("collection created for the editor", false) }512513        // --- storage: drill down into a folder by pressing its bar ---514        nav.section = .storage515        let bars = await appear("storage-folder", 15)516        let rootOnly = AX.element(id: "storage-crumb-1") == nil517        AX.press(AX.element(id: "storage-folder"))518        let inside = await wait(8) { AX.element(id: "storage-crumb-1") != nil }519        shot("storage-drilldown")520        check("Storage: pressing a folder's bar drills down into it (breadcrumb grows)", bars && rootOnly && inside, "bars \(bars) (\(AX.count(id: "storage-folder"))), root crumb \(AX.element(id: "storage-crumb-0") != nil)")521522        // --- share sheet: create a link with the sheet's button, see its QR code ---523        nav.section = .drive; nav.go(to: folder.id); nav.selection = [pv.id]; await pause(0.5)524        let linksBefore = ((try? await api.shares(of: pv)) ?? []).count525        nav.sheet = .share(pv)526        let createShare = await appear("create-share")527        AX.press(AX.element(id: "create-share"))528        let qr = await wait(10) { AX.element(labelPrefix: "Code QR de l’adresse du lien") != nil }529        shot("share-sheet-qr")530        let links = (try? await api.shares(of: pv)) ?? []531        check("Share sheet: its button creates the link on the server and the QR code of the address is shown", createShare && qr && links.count == linksBefore + 1, "\(links.count) link(s)")532        for l in links { try? await api.revokeShare(l.id) }533        nav.sheet = nil; await pause(0.7)534535        // --- deposit portal created from the extended sheet ---536        let portalsBefore = Set(((try? await api.portals()) ?? []).map(\.id))537        if let f = model.item(folder.id) {538            nav.sheet = .portal(folder: f)539            let createPortal = await appear("create-portal")540            await pause(0.5); shot("portal-sheet")541            AX.press(AX.element(id: "create-portal"))542            let made = await wait(10) { ((try? await api.portals()) ?? []).contains { !portalsBefore.contains($0.id) && $0.folderId == folder.id } }543            let portal = ((try? await api.portals()) ?? []).first { !portalsBefore.contains($0.id) }544            check("Portal sheet: its button creates the deposit link on the server", createPortal && made && portal?.state == "open", portal?.title ?? "none")545            if let portal { try? await api.revokePortal(portal.id, delete: true) }546            nav.sheet = nil; await pause(0.7)547        }548549        // --- AI organisation suggestions: nothing changes until "Appliquer" is pressed on a line ---550        if model.has(.ai), let target = model.children(of: folder.id).first(where: { $0.name == "alpha.txt" }) {551            nav.sheet = .suggest([target])552            let offered = await appear("apply-name", 30)553            shot("suggestions-sheet")554            let untouched = ((try? await api.item(target.id, kind: .file)) ?? nil)?.name == "alpha.txt"555            AX.press(AX.element(id: "apply-name"))556            let applied = await wait(15) { (((try? await api.item(target.id, kind: .file)) ?? nil)?.name ?? "").hasPrefix("Classé") }557            check("Suggestions (FAKE provider): the proposal changes nothing by itself; pressing “Appliquer” renames the file on the server", offered && untouched && applied, ((try? await api.item(target.id, kind: .file)) ?? nil)?.name ?? "?")558            nav.sheet = nil; await pause(0.6)559        }560    }561562    /// Dumps the state of the menu commands as AppKit sees them (diagnostic).563    static func menuProbe(_ model: AppModel) async {564        try? await Task.sleep(nanoseconds: 3_000_000_000)565        guard let window = NSApp.windows.first(where: { $0.isVisible && $0.canBecomeMain }) else { return }566        NSApp.activate(ignoringOtherApps: true); window.makeKeyAndOrderFront(nil)567        try? await Task.sleep(nanoseconds: 800_000_000)568        if let any = model.children(of: model.rootID ?? "").first { model.nav.selection = [any.id] }569        try? await Task.sleep(nanoseconds: 500_000_000)570        var lines: [String] = ["bridge \(String(describing: model.menuBridge.focus))", "active \(NSApp.isActive) key \(NSApp.keyWindow === window) phase \(model.phase) activeNav \(model.activeNav != nil)"]571        func walk(_ m: NSMenu?, _ depth: Int) { guard let m else { return }; m.delegate?.menuNeedsUpdate?(m); m.update(); for it in m.items where !it.isSeparatorItem { lines.append(String(repeating: "  ", count: depth) + "\(it.isEnabled ? "on " : "off") \(it.title) [\(it.keyEquivalent)] action=\(it.action.map { NSStringFromSelector($0) } ?? "nil") target=\(it.target.map { String(describing: type(of: $0)) } ?? "nil")"); walk(it.submenu, depth + 1) } }572        walk(NSApp.mainMenu, 0)573        NSApp.deactivate()574        try? lines.joined(separator: "\n").write(to: AppEnvironment.containerURL.appendingPathComponent("menuprobe.txt"), atomically: true, encoding: .utf8)575    }576577    /// Times how long the window takes to show a large folder (from the navigation to the frame being committed), in list and in grid.578    static func perfProbe(_ model: AppModel) async {579        try? await Task.sleep(nanoseconds: 4_000_000_000)580        guard let root = model.rootID, let big = model.children(of: root).first(where: { $0.name == "Mille fichiers" }) else { return }581        let nav = model.nav582        var lines: [String] = ["items \(model.children(of: big.id).count)"]583        func frame() async { await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in DispatchQueue.main.async { CATransaction.setCompletionBlock { c.resume() }; CATransaction.flush() } } }584        for grid in [false, true] {585            model.settings.gridView = grid586            var samples: [Double] = []587            for _ in 0..<5 {588                nav.go(to: nil); await frame(); try? await Task.sleep(nanoseconds: 500_000_000)589                let t = CFAbsoluteTimeGetCurrent()590                nav.go(to: big.id); await frame()591                samples.append((CFAbsoluteTimeGetCurrent() - t) * 1000)592                try? await Task.sleep(nanoseconds: 500_000_000)593            }594            lines.append("\(grid ? "grid" : "list") ms: " + samples.map { String(format: "%.0f", $0) }.joined(separator: " ") + String(format: " (median %.0f)", samples.sorted()[2]))595        }596        model.settings.gridView = false; nav.go(to: nil)597        try? lines.joined(separator: "\n").write(to: AppEnvironment.containerURL.appendingPathComponent("perf.txt"), atomically: true, encoding: .utf8)598    }599600    /// Only the on-screen checks (`-spdOnScreen YES`), with their own small set-up: quicker to iterate on than the whole self-test.601    static func onScreenOnly(_ model: AppModel) async {602        var checks: [Check] = []603        func wait(_ seconds: Double, _ cond: @MainActor () async -> Bool) async -> Bool {604            let end = Date().addingTimeInterval(seconds)605            while Date() < end { if await cond() { return true }; try? await Task.sleep(nanoseconds: 150_000_000) }606            return false607        }608        let out = AppEnvironment.containerURL.appendingPathComponent("onscreen.json")609        try? FileManager.default.removeItem(at: out)610        defer { try? JSONEncoder().encode(checks).write(to: out) }611        guard let api = model.api, let next = model.next, await wait(20, { model.rootID != nil && model.status.lastSync != nil }), let root = model.rootID else { return }612        let work = AppEnvironment.containerURL.appendingPathComponent("onscreen-src", isDirectory: true)613        try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true); defer { try? FileManager.default.removeItem(at: work) }614        let name = "Écran \(Int(Date().timeIntervalSince1970))"615        _ = model.createFolder(in: root, name: name)616        guard await wait(20, { model.children(of: root).contains { $0.name == name && !model.isPending($0.id) } }), let folder = model.children(of: root).first(where: { $0.name == name }) else { return }617        try? Data("Procès-verbal\nDépôt de garantie : 500 dollars avant le 1er juin.".utf8).write(to: work.appendingPathComponent("Procès-verbal.txt"))618        try? Data("alpha".utf8).write(to: work.appendingPathComponent("alpha.txt"))619        await model.upload([work.appendingPathComponent("Procès-verbal.txt"), work.appendingPathComponent("alpha.txt")], to: folder.id)620        guard await wait(30, { model.children(of: folder.id).filter { $0.versionID != nil }.count == 2 }), let pv = model.children(of: folder.id).first(where: { $0.name == "Procès-verbal.txt" }) else { return }621        _ = await wait(45) { ((try? await next.fileText(pv.id).status) ?? "") == "ready" }622        await onScreen(model, api: api, next: next, folder: folder, pv: pv, record: { n, ok, d in checks.append(Check(name: n, ok: ok, detail: d)) }, wait: wait)623        if let f = model.item(folder.id) { model.trash([f]) }624    }625}626#endif627
Files main
Menu

Theme