Round 2 of adversarial review confirmed defects 2,3,4,5,7 fixed and raised three new ones; all three are fixed here, plus the guard-message nit. NEW-1 (the FAIL driver): the OneDrive send path overwrote the truthful status from handleDidShareItems with its own success text, silently dropping an archive failure and any state-refresh problem. The seam now takes the caller's success summary and composes ONE truthful message: summary (the share itself did complete) + archive error if any + refresh problems if any. Both callers (AirDrop delegate, OneDrive) pass their summary; the OneDrive text is never clobbered. NEW-2: if the replacement open session could not be created after the archive rename (disk full), the store kept reporting the already-archived session as the open one. SpoolStore now has a truth guard (ensureOpenSession): the open session is verified to really exist on disk and be in state .open before any read/mutate; a stale one is replaced by a genuinely fresh session, or the call fails loudly. Never a lie. NEW-3: archivedSessions() read the folder tie-break dates AFTER reconciliation, so a healed same-second session could bump its own modification date and outrank a genuinely newer peer. The dates are now read BEFORE reconciling. Nit: the startNewSession guard now reports "A new session is already being started." when the refusal is about a concurrent session start, not a send. Also added REDLINE_SELFTEST_PHASE=sendtruth (mirroring the existing =onedrive escape hatch) so the SEND-TRUTH selftest can run without the picker chain's display-dependent REGION-PERSIST phase. Evidence: 136 swift tests pass (2 new: OneDrive summary survives archiving; stale open session never returned as current). REDLINE_SELFTEST_PHASE=sendtruth -> SEND-TRUTH PASS. REDLINE_SELFTEST_PHASE=onedrive -> ONEDRIVE-SELFTEST PASS against the real OneDrive sync root.
272 lines
11 KiB
Swift
272 lines
11 KiB
Swift
import CoreGraphics
|
|
import Foundation
|
|
import ImageIO
|
|
import Testing
|
|
import ShotdeckCore
|
|
|
|
// Session lifecycle + retention (MMDB-2925): "Start new session" keeps the current
|
|
// screenshots as a past session, and the newest 10 sessions are retained in the one
|
|
// archive folder.
|
|
|
|
// MARK: - 1. closeCurrentSession keeps the captures as a past session
|
|
|
|
@Test
|
|
func closeCurrentSessionKeepsCapturesAsAPastSessionAndStartsFresh() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
let c1 = try await store.append(
|
|
pngData: try makePNGData(width: 8, height: 8, red: 1, green: 0, blue: 0),
|
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
|
let c2 = try await store.append(
|
|
pngData: try makePNGData(width: 8, height: 8, red: 0, green: 1, blue: 0),
|
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
|
|
|
let closedID = try await store.currentSession().id
|
|
let archived = try #require(try await store.closeCurrentSession())
|
|
|
|
#expect(archived.id == closedID)
|
|
#expect(archived.state == .archived)
|
|
#expect(archived.pdfFileName == nil) // never sent — shown as "Not sent"
|
|
#expect(archived.captures.map(\.id) == [c1.id, c2.id])
|
|
|
|
// Nothing is deleted: both PNGs live on under archive/<id>/.
|
|
let archiveDir = paths.archiveDirectory(closedID)
|
|
for capture in archived.captures {
|
|
#expect(FileManager.default.fileExists(
|
|
atPath: archiveDir.appendingPathComponent(capture.fileName).path))
|
|
}
|
|
#expect(!FileManager.default.fileExists(atPath: paths.sessionDirectory(closedID).path))
|
|
|
|
let fresh = try await store.currentSession()
|
|
#expect(fresh.id != closedID)
|
|
#expect(fresh.state == .open)
|
|
#expect(fresh.isEmpty)
|
|
|
|
let past = try await store.archivedSessions()
|
|
#expect(past.map(\.id) == [closedID])
|
|
#expect(past.first?.captures.count == 2)
|
|
}
|
|
|
|
// MARK: - 2. closeCurrentSession on an empty open session just starts fresh
|
|
|
|
@Test
|
|
func closeCurrentSessionOnAnEmptyOpenSessionStartsFreshWithoutArchiving() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
let before = try await store.currentSession().id
|
|
|
|
let archived = try await store.closeCurrentSession()
|
|
#expect(archived == nil)
|
|
|
|
let after = try await store.currentSession()
|
|
#expect(after.id != before)
|
|
#expect(after.isEmpty)
|
|
let past = try await store.archivedSessions()
|
|
#expect(past.isEmpty)
|
|
}
|
|
|
|
// MARK: - 3. sent and unsent sessions are distinguishable in the past list
|
|
|
|
@Test
|
|
func pastSessionsDistinguishSentFromUnsentByPDFFileName() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
_ = try await store.append(
|
|
pngData: try makePNGData(width: 6, height: 6, red: 1, green: 0, blue: 0),
|
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
|
let sent = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120000.pdf")
|
|
|
|
_ = try await store.append(
|
|
pngData: try makePNGData(width: 6, height: 6, red: 0, green: 0, blue: 1),
|
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
|
let closed = try #require(try await store.closeCurrentSession())
|
|
|
|
#expect(sent.pdfFileName == "Redline-20261011-120000.pdf")
|
|
#expect(closed.pdfFileName == nil)
|
|
|
|
let past = try await store.archivedSessions()
|
|
#expect(past.map(\.id) == [closed.id, sent.id]) // newest first
|
|
#expect(past.map(\.pdfFileName) == [nil, "Redline-20261011-120000.pdf"])
|
|
}
|
|
|
|
// MARK: - 4. retention keeps the newest 10 sessions, in the one archive folder
|
|
|
|
@Test
|
|
func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
var closedIDs: [UUID] = []
|
|
for index in 0..<12 {
|
|
_ = try await store.append(
|
|
pngData: try makePNGData(width: 4, height: 4, red: 0.1, green: 0.1, blue: 0.1),
|
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
|
|
capturedAt: Date(timeIntervalSince1970: 1_700_000_000 + Double(index)))
|
|
let closed = try #require(try await store.closeCurrentSession())
|
|
closedIDs.append(closed.id)
|
|
}
|
|
|
|
// All 12 sessions live in the single archive/ folder as UUID session folders.
|
|
let fm = FileManager.default
|
|
let entries = try fm.contentsOfDirectory(at: paths.archive, includingPropertiesForKeys: nil)
|
|
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
|
|
#expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount)
|
|
|
|
let kept = try await store.archivedSessions().map(\.id)
|
|
#expect(kept == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
|
|
|
// The two oldest sessions are gone; the newest ten are fully on disk.
|
|
for id in closedIDs.prefix(2) {
|
|
#expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path))
|
|
}
|
|
for id in closedIDs.suffix(SpoolStore.defaultRetainedSessionCount) {
|
|
#expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path))
|
|
}
|
|
|
|
// The open session is never touched by retention.
|
|
let open = try await store.currentSession()
|
|
#expect(open.state == .open)
|
|
#expect(open.isEmpty)
|
|
#expect(fm.fileExists(atPath: paths.sessionDirectory(open.id).path))
|
|
}
|
|
|
|
// MARK: - 5. explicit prune keeps exactly the requested count
|
|
|
|
@Test
|
|
func pruneArchivedSessionsKeepingNRemovesExactlyTheOldest() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
var closedIDs: [UUID] = []
|
|
for _ in 0..<4 {
|
|
_ = try await store.append(
|
|
pngData: try makePNGData(width: 4, height: 4, red: 0.2, green: 0.2, blue: 0.2),
|
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date())
|
|
closedIDs.append(try #require(try await store.closeCurrentSession()).id)
|
|
}
|
|
|
|
let removed = try await store.pruneArchivedSessions(keeping: 2)
|
|
#expect(removed == Array(closedIDs.prefix(2).reversed())) // newest-first walk order
|
|
let kept = try await store.archivedSessions().map(\.id)
|
|
#expect(kept == Array(closedIDs.suffix(2).reversed()))
|
|
|
|
// Idempotent: nothing left to prune at that limit.
|
|
let removedAgain = try await store.pruneArchivedSessions(keeping: 2)
|
|
#expect(removedAgain.isEmpty)
|
|
}
|
|
|
|
// MARK: - 6. retention runs on the send path too
|
|
|
|
@Test
|
|
func theSendArchivePathAppliesRetention() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
var sentIDs: [UUID] = []
|
|
for index in 0..<(SpoolStore.defaultRetainedSessionCount + 3) {
|
|
_ = try await store.append(
|
|
pngData: try makePNGData(width: 4, height: 4, red: 0.3, green: 0.3, blue: 0.3),
|
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
|
|
capturedAt: Date(timeIntervalSince1970: 1_700_100_000 + Double(index)))
|
|
let archived = try await store.archiveCurrent(pdfFileName: "Redline-\(index).pdf")
|
|
sentIDs.append(archived.id)
|
|
}
|
|
|
|
let kept = try await store.archivedSessions()
|
|
#expect(kept.count == SpoolStore.defaultRetainedSessionCount)
|
|
#expect(kept.map(\.id) == Array(sentIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
|
#expect(kept.allSatisfy { $0.pdfFileName != nil })
|
|
}
|
|
|
|
// MARK: - 7. a stale open session is never returned as current (truth guard)
|
|
|
|
@Test
|
|
func aStaleOpenSessionIsNeverReturnedAsCurrent() async throws {
|
|
let (root, paths) = try makeIsolatedPaths()
|
|
defer { try? FileManager.default.removeItem(at: root) }
|
|
|
|
let store = try SpoolStore(paths: paths)
|
|
_ = try await store.append(
|
|
pngData: try makePNGData(width: 6, height: 6, red: 0.7, green: 0.7, blue: 0.1),
|
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
|
let archived = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120200.pdf")
|
|
|
|
// Simulate the mid-run failure the truth guard exists for: the archived session
|
|
// moved away and the replacement open session's folder is gone (e.g. the fresh
|
|
// session could not be created / survive). The store must mint a real fresh
|
|
// session — never report the already-archived one as open.
|
|
let fresh = try await store.currentSession()
|
|
try FileManager.default.removeItem(at: paths.sessionDirectory(fresh.id))
|
|
|
|
let recovered = try await store.currentSession()
|
|
#expect(recovered.id != fresh.id)
|
|
#expect(recovered.id != archived.id)
|
|
#expect(recovered.state == .open)
|
|
#expect(recovered.isEmpty)
|
|
let past = try await store.archivedSessions()
|
|
#expect(past.map(\.id) == [archived.id])
|
|
}
|
|
|
|
// MARK: - Fixtures
|
|
|
|
private enum FixtureError: Error {
|
|
case pngGenerationFailed
|
|
}
|
|
|
|
private func makeIsolatedPaths() throws -> (root: URL, paths: AppSupportPaths) {
|
|
let root = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("shotdeck-retention-\(UUID().uuidString)", isDirectory: true)
|
|
let paths = try AppSupportPaths(
|
|
root: root,
|
|
outbox: root.appendingPathComponent("outbox", isDirectory: true),
|
|
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
|
|
)
|
|
return (root, paths)
|
|
}
|
|
|
|
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 data = NSMutableData()
|
|
guard let destination = CGImageDestinationCreateWithData(
|
|
data, "public.png" as CFString, 1, nil
|
|
) else {
|
|
throw FixtureError.pngGenerationFailed
|
|
}
|
|
CGImageDestinationAddImage(destination, image, nil)
|
|
guard CGImageDestinationFinalize(destination) else {
|
|
throw FixtureError.pngGenerationFailed
|
|
}
|
|
return data as Data
|
|
}
|