Redline: past submissions list + start-new-session with 10-session retention (MMDB-2925) #29
@@ -426,7 +426,7 @@ public final class AppModel {
|
||||
// the menu's `.disabled` state cannot stop a Task that was queued just before
|
||||
// a send started.
|
||||
guard !isSending, !isStartingNewSession else {
|
||||
setStatus("Finish the current send first.")
|
||||
setStatus(isSending ? "Finish the current send first." : "A new session is already being started.")
|
||||
return
|
||||
}
|
||||
isStartingNewSession = true
|
||||
|
||||
@@ -241,7 +241,10 @@ enum PickerSelfTest {
|
||||
sendTruthFail("fail path status missing 'nothing was sent': \(model.statusLine ?? "nil")")
|
||||
}
|
||||
|
||||
await model.handleDidShareItems(fileName: pending.fileName, pageCount: pending.pageCount)
|
||||
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||||
await model.handleDidShareItems(
|
||||
fileName: pending.fileName,
|
||||
sentSummary: "Sent — \(pending.pageCount) \(pageWord).")
|
||||
let fresh = try await model.spool.currentSession()
|
||||
guard fresh.isEmpty, fresh.id != openID, fresh.state == .open else {
|
||||
sendTruthFail("success path did not mint a fresh empty session")
|
||||
@@ -592,6 +595,38 @@ enum PickerSelfTest {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Entry point for running ONLY the SEND-TRUTH phase, bypassing the on-screen picker
|
||||
/// chain entirely — the chain's REGION-PERSIST phase needs an active display
|
||||
/// (CGDisplayIsActive) and exits before SEND-TRUTH in headless/remote sessions.
|
||||
/// Escape hatch: `REDLINE_SELFTEST_PHASE=sendtruth`.
|
||||
static func runSendTruthOnlyIfRequested() {
|
||||
guard ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" else {
|
||||
return
|
||||
}
|
||||
// Same hop as runOneDriveOnlyIfRequested(): a plain main-queue turn after NSApp
|
||||
// starts, so AppKit/PDFKit calls inside the phase are not racing app launch.
|
||||
DispatchQueue.main.async {
|
||||
MainActor.assumeIsolated {
|
||||
runSendTruthAndExit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func runSendTruthAndExit() {
|
||||
Task { @MainActor in
|
||||
do {
|
||||
try await executeSendTruth()
|
||||
print("SEND-TRUTH PASS")
|
||||
fflush(stdout)
|
||||
exit(0)
|
||||
} catch {
|
||||
print("SEND-TRUTH FAIL \(error)")
|
||||
fflush(stdout)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point for running ONLY this phase, bypassing the on-screen picker chain
|
||||
/// entirely. The harness has no other per-phase selector, so this is the escape
|
||||
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
|
||||
|
||||
@@ -95,10 +95,10 @@ extension AppModel: SendCapable {
|
||||
case .oneDrive:
|
||||
// No AirDrop, no anchor needed — the PDF is already in the watched
|
||||
// OneDrive folder. Archive immediately; the iPad marks it up in place.
|
||||
await handleDidShareItems(fileName: pending.fileName, pageCount: pending.pageCount)
|
||||
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||||
setStatus(
|
||||
"Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
|
||||
await handleDidShareItems(
|
||||
fileName: pending.fileName,
|
||||
sentSummary: "Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
|
||||
)
|
||||
setSending(false)
|
||||
|
||||
@@ -113,9 +113,10 @@ extension AppModel: SendCapable {
|
||||
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
|
||||
guard let self else { return }
|
||||
if success {
|
||||
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||||
await self.handleDidShareItems(
|
||||
fileName: pending.fileName,
|
||||
pageCount: pending.pageCount
|
||||
sentSummary: "Sent — \(pending.pageCount) \(pageWord)."
|
||||
)
|
||||
} else {
|
||||
self.handleDidFailToShareItems(fileName: pending.fileName)
|
||||
@@ -194,16 +195,17 @@ extension AppModel: SendCapable {
|
||||
)
|
||||
}
|
||||
|
||||
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam.
|
||||
func handleDidShareItems(fileName: String, pageCount: Int) async {
|
||||
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam — also the
|
||||
/// OneDrive completion path. Composes ONE truthful status from the caller's success
|
||||
/// summary (the share itself DID complete) plus, when they happened, the archive
|
||||
/// error and any state-refresh problem — nothing is overwritten or hidden.
|
||||
func handleDidShareItems(fileName: String, sentSummary: String) async {
|
||||
guard !session.isEmpty else { return }
|
||||
var message: String
|
||||
var message = sentSummary
|
||||
do {
|
||||
_ = try await spool.archiveCurrent(pdfFileName: fileName)
|
||||
let pageWord = pageCount == 1 ? "page" : "pages"
|
||||
message = "Sent — \(pageCount) \(pageWord)."
|
||||
} catch {
|
||||
message = (error as? ShotdeckError)?.errorDescription ?? "Could not archive the session."
|
||||
message += " \((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")"
|
||||
}
|
||||
// Refresh model state from the store on BOTH paths: after a successful archive
|
||||
// the current session and the past-submissions list are stale until reloaded,
|
||||
|
||||
@@ -10,6 +10,9 @@ if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil {
|
||||
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" {
|
||||
MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() }
|
||||
}
|
||||
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" {
|
||||
MainActor.assumeIsolated { PickerSelfTest.runSendTruthOnlyIfRequested() }
|
||||
}
|
||||
if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil {
|
||||
MainActor.assumeIsolated { PickerSelfTest.runIfRequested() }
|
||||
}
|
||||
|
||||
@@ -35,9 +35,28 @@ public actor SpoolStore {
|
||||
}
|
||||
|
||||
/// The session currently accepting captures. Cheap accessor — all reconciliation already
|
||||
/// happened once, inside init.
|
||||
/// happened once, inside init. A truth guard: if the stored session is no longer really
|
||||
/// open on disk (its directory was archived away and the replacement session could not
|
||||
/// be created — e.g. disk full), a fresh session is minted, or the call fails loudly.
|
||||
/// It never returns an already-archived session as the open one.
|
||||
public func currentSession() throws -> CaptureSession {
|
||||
openSession
|
||||
try ensureOpenSession()
|
||||
}
|
||||
|
||||
/// Mint-or-verify the open session: returns the session that is REALLY open on disk,
|
||||
/// creating a fresh one when the stored one is stale (archived away mid-run). Throws
|
||||
/// loudly when no new session can be created either — never substitutes a lie.
|
||||
private func ensureOpenSession() throws -> CaptureSession {
|
||||
let dir = paths.sessionDirectory(openSession.id)
|
||||
if openSession.state == .open && FileManager.default.fileExists(atPath: dir.path) {
|
||||
return openSession
|
||||
}
|
||||
let staleID = openSession.id.uuidString
|
||||
Log.spool.error(
|
||||
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
|
||||
let fresh = try Self.createFreshSession(paths: paths)
|
||||
openSession = fresh
|
||||
return fresh
|
||||
}
|
||||
|
||||
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
|
||||
@@ -47,17 +66,18 @@ public actor SpoolStore {
|
||||
pngData: Data, pixelWidth: Int, pixelHeight: Int,
|
||||
scale: CGFloat, capturedAt: Date
|
||||
) throws -> Capture {
|
||||
let open = try ensureOpenSession()
|
||||
let captureID = UUID()
|
||||
let sequence = openSession.nextSequence
|
||||
let sequence = open.nextSequence
|
||||
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
|
||||
let sessionDir = paths.sessionDirectory(openSession.id)
|
||||
let sessionDir = paths.sessionDirectory(open.id)
|
||||
let fileURL = sessionDir.appendingPathComponent(fileName)
|
||||
try AtomicFile.write(pngData, to: fileURL)
|
||||
let capture = Capture(
|
||||
id: captureID, sequence: sequence, fileName: fileName,
|
||||
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
|
||||
scale: scale, capturedAt: capturedAt)
|
||||
let updated = openSession.appending(capture)
|
||||
let updated = open.appending(capture)
|
||||
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
|
||||
openSession = updated
|
||||
return capture
|
||||
@@ -71,12 +91,13 @@ public actor SpoolStore {
|
||||
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
|
||||
/// not this remove path.)
|
||||
public func remove(captureID: UUID) throws -> CaptureSession {
|
||||
guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
|
||||
let open = try ensureOpenSession()
|
||||
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: paths.sessionDirectory(openSession.id).path,
|
||||
path: paths.sessionDirectory(open.id).path,
|
||||
underlying: "capture \(captureID) is not in the open session")
|
||||
}
|
||||
let sessionDir = paths.sessionDirectory(openSession.id)
|
||||
let sessionDir = paths.sessionDirectory(open.id)
|
||||
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
|
||||
@@ -101,12 +122,13 @@ public actor SpoolStore {
|
||||
/// pdfFileName, starts a fresh empty open session, and applies session retention.
|
||||
/// Returns the archived one.
|
||||
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
|
||||
guard !openSession.isEmpty else {
|
||||
let open = try ensureOpenSession()
|
||||
guard !open.isEmpty else {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: paths.sessionDirectory(openSession.id).path,
|
||||
path: paths.sessionDirectory(open.id).path,
|
||||
underlying: "cannot archive an empty session")
|
||||
}
|
||||
let archived = try moveOpenSessionToArchive(openSession.markArchived(pdfFileName: pdfFileName))
|
||||
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
|
||||
openSession = try Self.createFreshSession(paths: paths)
|
||||
applyRetention()
|
||||
return archived
|
||||
@@ -120,12 +142,13 @@ public actor SpoolStore {
|
||||
/// simply replaced — there is nothing to keep. Returns the archived session, or
|
||||
/// nil when the open session was empty.
|
||||
public func closeCurrentSession() throws -> CaptureSession? {
|
||||
guard !openSession.isEmpty else {
|
||||
let open = try ensureOpenSession()
|
||||
guard !open.isEmpty else {
|
||||
openSession = try Self.createFreshSession(paths: paths)
|
||||
return nil
|
||||
}
|
||||
let archived = try moveOpenSessionToArchive(
|
||||
openSession.markArchived(pdfFileName: openSession.pdfFileName))
|
||||
open.markArchived(pdfFileName: open.pdfFileName))
|
||||
openSession = try Self.createFreshSession(paths: paths)
|
||||
applyRetention()
|
||||
return archived
|
||||
@@ -195,10 +218,11 @@ public actor SpoolStore {
|
||||
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
|
||||
/// with no filesystem change, if the open session has captures.
|
||||
public func startNewSession() throws -> CaptureSession {
|
||||
guard openSession.isEmpty else {
|
||||
let open = try ensureOpenSession()
|
||||
guard open.isEmpty else {
|
||||
throw ShotdeckError.spoolWriteFailed(
|
||||
path: paths.sessionDirectory(openSession.id).path,
|
||||
underlying: "cannot start a new session: \(openSession.captures.count) capture(s) present in the open session")
|
||||
path: paths.sessionDirectory(open.id).path,
|
||||
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
|
||||
}
|
||||
let fresh = try Self.createFreshSession(paths: paths)
|
||||
openSession = fresh
|
||||
@@ -231,9 +255,15 @@ public actor SpoolStore {
|
||||
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
|
||||
for id in ids {
|
||||
let dir = paths.archiveDirectory(id)
|
||||
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
|
||||
// session.json and bump the folder's modification date to "now", which
|
||||
// would let a healed older session outrank a genuinely newer same-second
|
||||
// peer in the tie-break below.
|
||||
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
|
||||
let session = try Self.reconcileSessionDirectory(
|
||||
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
|
||||
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
|
||||
// The manifest `createdAt` is the authoritative timestamp; the folder dates
|
||||
// only refine ties between same-second sessions.
|
||||
let folderCreatedAt = values?.creationDate ?? session.createdAt
|
||||
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
|
||||
keyed.append((session, folderCreatedAt, folderModifiedAt))
|
||||
|
||||
@@ -187,6 +187,35 @@ func theSendArchivePathAppliesRetention() async throws {
|
||||
#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 {
|
||||
|
||||
@@ -105,7 +105,8 @@ func successfulSendRefreshesPastSubmissions() async throws {
|
||||
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", pageCount: 1)
|
||||
await model.handleDidShareItems(
|
||||
fileName: "Redline-20261011-120000.pdf", sentSummary: "Sent — 1 page.")
|
||||
|
||||
#expect(model.statusLine == "Sent — 1 page.")
|
||||
#expect(model.session.isEmpty)
|
||||
@@ -150,6 +151,24 @@ func sessionStartAndSendRefuseToOverlap() async throws {
|
||||
#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
|
||||
|
||||
Reference in New Issue
Block a user