Files
shotdeck/Tests/ShotdeckTests/SessionWorkflowTests.swift
Claude Fable 5 02fa791b78 feat(sessions): keep every session, record review details, name and stamp the PDF
Sessions are now the unit of the product instead of an implicit capture run.

- Nothing is deleted by default: the fixed 10-session cap is gone. An age limit
  (Never / 7 / 14 / 30 / 90 / 180 / 365 days) is chosen in Settings > Sessions and
  applied on launch, after archiving, and by "Clean up now". Sent PDFs are never
  touched.
- Each session carries review details: lane, deployed version, commit, reviewer
  (pre-filled with the Mac user) and a free note. They persist in session.json and
  are inherited by the next session, so a review run is typed once.
- PDF file names are Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf, and every page
  carries a two-line reference footer (tool, build time, session / lane, deployed
  build, commit, reviewer, note). The PDF document info carries the same values in
  Author and Keywords.
- Verification: 159 tests, a headless panel self-test, and a LaunchServices-driven
  end-to-end run that types and clicks the real panel.
2026-10-31 11:32:54 +04:00

346 lines
14 KiB
Swift

import AppKit
import CoreGraphics
import Foundation
import ImageIO
import Testing
import ShotdeckCore
@testable import Shotdeck
/// 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 sessions state reflects what was sent, every session is kept by default,
/// and a chosen age limit is what removes one. `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 and lists past submissions")
func startNewSessionKeepsCapturesAndListsPastSessions() 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 are all kept by default")
func twelveSessionsStayOnDiskByDefault() 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.retention == .never)
#expect(model.pastSessions.map(\.id) == closedIDs.reversed())
let entries = try fm.contentsOfDirectory(at: model.paths.archive, includingPropertiesForKeys: nil)
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
#expect(sessionDirs.count == closedIDs.count)
for id in closedIDs {
#expect(fm.fileExists(atPath: model.paths.archiveDirectory(id).path))
}
#expect(model.expiredSessionCount == 0)
}
@MainActor
@Test("A review detail typed in the panel is saved and inherited by the next session")
func reviewDetailsPersistThroughTheModel() 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 context = ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout")
await model.setContextField(context)
#expect(model.session.context == context)
#expect(model.sessionContext.summaryLine == "dev03 · v1.4.2 · a1b2c3d4 · Ben Hippler")
#expect(model.nextPDFFileNameHint.contains("-DEV03-"))
_ = try await addCapture(to: model, red: 0.1, green: 0.4, blue: 0.9)
await model.startNewSession()
// The closed session keeps its details; the new one inherits them.
#expect(model.pastSessions.first?.context == context)
#expect(model.session.context == context)
}
@MainActor
@Test("Settings age limit: cleanup removes only expired sessions, never a sent PDF")
func cleanUpHonorsTheAgeLimit() 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 suite = try makeIsolatedDefaults()
defer { suite.defaults.removePersistentDomain(forName: suite.name) }
let model = AppDelegate.makeLaunchModel(
appSupportRoot: root, retentionDefaults: suite.defaults)
await model.bootstrap()
// One real session that was sent (its PDF is in the outbox) …
_ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2)
let sentName = "Redline-20261001-0900-A1B2C3D4.pdf"
_ = try await model.spool.archiveCurrent(pdfFileName: sentName)
try Data("%PDF-1.4\n% test\n".utf8)
.write(to: model.paths.outbox.appendingPathComponent(sentName))
// … and one archived session backdated past the limit, written in the exact shape
// production writes, so the age comparison runs against real manifest dates.
let expiredID = try await writeBackdatedSession(in: model.paths, daysAgo: 40)
await model.reloadFromSpool()
#expect(model.pastSessions.count == 2)
// Nothing expires under .never, even with a cleanup.
await model.cleanUpExpiredSessions()
#expect(model.pastSessions.count == 2)
#expect(model.expiredSessionCount == 0)
#expect(model.statusLine?.contains("Nothing to remove") == true)
// A 30-day limit expires only the backdated session, and says so before deleting.
await model.setRetention(.days(30))
#expect(model.retention == .days(30))
#expect(RetentionSettings.load(defaults: suite.defaults) == .days(30))
#expect(model.expiredSessionCount == 1)
await model.cleanUpExpiredSessions()
#expect(model.pastSessions.count == 1)
#expect(model.statusLine?.contains("Removed 1 past session") == true)
#expect(!fm.fileExists(atPath: model.paths.archiveDirectory(expiredID).path))
#expect(fm.fileExists(atPath: model.paths.outbox.appendingPathComponent(sentName).path))
// Back to the default in this isolated suite, so the next test starts clean.
await model.setRetention(.never)
#expect(model.expiredSessionCount == 0)
}
@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
}
// MARK: - Fixtures
private struct IsolatedDefaults {
let name: String
let defaults: UserDefaults
}
/// A throwaway UserDefaults suite — never `.standard` — so the age-limit setting a
/// test writes can never change Ben's real app preference.
private func makeIsolatedDefaults() throws -> IsolatedDefaults {
let name = "shotdeck-session-workflow-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: name) else {
throw FixtureError.pngGenerationFailed
}
defaults.removePersistentDomain(forName: name)
return IsolatedDefaults(name: name, defaults: defaults)
}
/// Writes an archived session folder dated `daysAgo` days in the past, in the exact
/// on-disk shape the store produces, so an age policy can act on a real manifest date.
@discardableResult
private func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) async throws -> UUID {
let id = UUID()
let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400)
let dir = paths.archiveDirectory(id)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png"
try makePNGData(width: 8, height: 8, red: 0.3, green: 0.3, blue: 0.3)
.write(to: dir.appendingPathComponent(pngName))
let capture = Capture(
id: UUID(), sequence: 1, fileName: pngName,
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: createdAt)
let session = CaptureSession(
id: id, createdAt: createdAt, state: .archived, captures: [capture],
pdfFileName: nil,
context: ReviewContext(lane: "DEV03", deployedVersion: "v1.0.0", commit: "abc1234"))
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
try encoder.encode(session).write(to: dir.appendingPathComponent("session.json"))
return id
}
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
}