import AppKit import CoreGraphics import Foundation import ImageIO import Testing import ShotdeckCore @testable import Shotdeck /// MMDB-2925, through the REAL app-target seams the menu rows invoke (`AppModel` /// actions + `SpoolStore`): "Start new session" keeps the current screenshots as a /// past session, the Past submissions state reflects what was sent, and session /// retention keeps the newest 10 sessions in the one archive folder. `bootstrap()` /// itself is covered by LaunchWiringTests; here `addCapture` refreshes the session /// from the store exactly the way `AppModel.captureNow()` does after a real capture. @MainActor @Test("Menu actions: start new session keeps captures, lists past submissions, retains 10") func startNewSessionKeepsCapturesListsPastSubmissionsAndRetainsTen() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let model = AppDelegate.makeLaunchModel(appSupportRoot: root) // Two captures in the open session, then the menu's "Start new session". let c1 = try await addCapture(to: model, red: 1, green: 0, blue: 0) let c2 = try await addCapture(to: model, red: 0, green: 1, blue: 0) let closedID = model.session.id #expect(model.canStartNewSession) await model.startNewSession() // The fresh session is active and the captures are kept as a past session. #expect(model.session.id != closedID) #expect(model.session.isEmpty) #expect(!model.canStartNewSession) #expect(model.pastSessions.map(\.id) == [closedID]) #expect(model.pastSessions.first?.captures.map(\.id) == [c1.id, c2.id]) #expect(model.pastSessions.first?.pdfFileName == nil) // never sent #expect(model.statusLine?.contains("kept as a past session") == true) // Nothing was deleted on close: both PNGs live in the single archive folder. let archiveDir = model.paths.archiveDirectory(closedID) for capture in [c1, c2] { #expect(fm.fileExists(atPath: archiveDir.appendingPathComponent(capture.fileName).path)) } // "PDF" on a never-sent row: visible missing state, no silent substitute. #expect(model.sentPDFURL(for: model.pastSessions[0]) == nil) model.revealSentPDF(model.pastSessions[0]) #expect(model.statusLine == "That session was never sent.") } @MainActor @Test("Retention: 12 sessions through the menu action leave the newest 10 on disk") func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let model = AppDelegate.makeLaunchModel(appSupportRoot: root) var closedIDs: [UUID] = [] for _ in 0..<12 { _ = try await addCapture(to: model, red: 0.2, green: 0.2, blue: 0.2) closedIDs.append(model.session.id) await model.startNewSession() } #expect(model.pastSessions.count == SpoolStore.defaultRetainedSessionCount) #expect(model.pastSessions.map(\.id) == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed())) let entries = try fm.contentsOfDirectory(at: model.paths.archive, includingPropertiesForKeys: nil) let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil } #expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount) for id in closedIDs.prefix(2) { #expect(!fm.fileExists(atPath: model.paths.archiveDirectory(id).path)) } } @MainActor @Test("Menu action on an empty session reports it started without inventing a past session") func startNewSessionOnEmptySessionCreatesNoPastSession() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let model = AppDelegate.makeLaunchModel(appSupportRoot: root) #expect(model.session.isEmpty) await model.startNewSession() #expect(model.session.isEmpty) #expect(model.pastSessions.isEmpty) #expect(model.statusLine == "New session started.") } @MainActor @Test("Send seam refreshes past submissions after archiving (menu count stays true)") func successfulSendRefreshesPastSubmissions() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let model = AppDelegate.makeLaunchModel(appSupportRoot: root) _ = try await addCapture(to: model, red: 0.4, green: 0.4, blue: 0.4) await model.handleDidShareItems( fileName: "Redline-20261011-120000.pdf", sentSummary: "Sent — 1 page.") #expect(model.statusLine == "Sent — 1 page.") #expect(model.session.isEmpty) #expect(model.pastSessions.count == 1) #expect(model.pastSessions.first?.pdfFileName == "Redline-20261011-120000.pdf") #expect(model.pastSessions.first?.captures.count == 1) } @MainActor @Test("Start new session and send refuse to overlap (no mid-flight session close)") func sessionStartAndSendRefuseToOverlap() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let model = AppDelegate.makeLaunchModel(appSupportRoot: root) let capture = try await addCapture(to: model, red: 0.1, green: 0.1, blue: 0.1) let before = model.session.id // A send in flight: "Start new session" must refuse instead of renaming the // session directory out from under the compose. model.setSending(true) await model.startNewSession() #expect(model.session.id == before) #expect(model.session.captures.map(\.id) == [capture.id]) #expect(model.statusLine == "Finish the current send first.") model.setSending(false) // A session start in flight: send must refuse before composing anything. model.setStartingNewSession(true) await model.send(anchor: nil) #expect(model.statusLine == "Finish starting the new session first.") #expect(model.session.id == before) #expect(model.session.captures.map(\.id) == [capture.id]) model.setStartingNewSession(false) // Both settled: the normal path still works. await model.startNewSession() #expect(model.session.id != before) #expect(model.pastSessions.count == 1) #expect(model.pastSessions.first?.captures.map(\.id) == [capture.id]) } @MainActor @Test("The OneDrive send summary survives archiving (never overwritten by the archive path)") func oneDriveSendSummarySurvivesArchiving() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) defer { try? fm.removeItem(at: root) } let model = AppDelegate.makeLaunchModel(appSupportRoot: root) _ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2) let summary = "Saved to OneDrive — 1 page. Open it in Files on your iPad." await model.handleDidShareItems(fileName: "Redline-20261011-120100.pdf", sentSummary: summary) #expect(model.statusLine == summary) #expect(model.pastSessions.count == 1) #expect(model.pastSessions.first?.pdfFileName == "Redline-20261011-120100.pdf") } // MARK: - Fixtures /// Appends one generated PNG through the store and refreshes `model.session` from /// it — the same refresh `AppModel.captureNow()` performs after a real capture. @MainActor private func addCapture( to model: AppModel, red: CGFloat, green: CGFloat, blue: CGFloat ) async throws -> Capture { let capture = try await model.spool.append( pngData: try makePNGData(width: 8, height: 8, red: red, green: green, blue: blue), pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date()) model.replaceSession(try await model.spool.currentSession()) return capture } private enum FixtureError: Error { case pngGenerationFailed } private func makePNGData( width: Int, height: Int, red: CGFloat, green: CGFloat, blue: CGFloat ) throws -> Data { let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { throw FixtureError.pngGenerationFailed } context.setFillColor(red: red, green: green, blue: blue, alpha: 1) context.fill(CGRect(x: 0, y: 0, width: width, height: height)) guard let image = context.makeImage() else { throw FixtureError.pngGenerationFailed } let buffer = NSMutableData() guard let destination = CGImageDestinationCreateWithData(buffer, "public.png" as CFString, 1, nil) else { throw FixtureError.pngGenerationFailed } CGImageDestinationAddImage(destination, image, nil) guard CGImageDestinationFinalize(destination) else { throw FixtureError.pngGenerationFailed } return buffer as Data }