Redline: past submissions list + start-new-session with 10-session retention (MMDB-2925) #29

Merged
kua-agent merged 3 commits from feat/redline-sessions-history-20261011 into main 2026-10-11 10:01:23 +00:00
7 changed files with 148 additions and 30 deletions
Showing only changes of commit 0506ce04e9 - Show all commits
+1 -1
View File
@@ -426,7 +426,7 @@ public final class AppModel {
// the menu's `.disabled` state cannot stop a Task that was queued just before // the menu's `.disabled` state cannot stop a Task that was queued just before
// a send started. // a send started.
guard !isSending, !isStartingNewSession else { 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 return
} }
isStartingNewSession = true isStartingNewSession = true
+36 -1
View File
@@ -241,7 +241,10 @@ enum PickerSelfTest {
sendTruthFail("fail path status missing 'nothing was sent': \(model.statusLine ?? "nil")") 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() let fresh = try await model.spool.currentSession()
guard fresh.isEmpty, fresh.id != openID, fresh.state == .open else { guard fresh.isEmpty, fresh.id != openID, fresh.state == .open else {
sendTruthFail("success path did not mint a fresh empty session") sendTruthFail("success path did not mint a fresh empty session")
@@ -592,6 +595,38 @@ enum PickerSelfTest {
return true 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 /// 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 /// entirely. The harness has no other per-phase selector, so this is the escape
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`. /// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
+12 -10
View File
@@ -95,10 +95,10 @@ extension AppModel: SendCapable {
case .oneDrive: case .oneDrive:
// No AirDrop, no anchor needed — the PDF is already in the watched // No AirDrop, no anchor needed — the PDF is already in the watched
// OneDrive folder. Archive immediately; the iPad marks it up in place. // 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" let pageWord = pending.pageCount == 1 ? "page" : "pages"
setStatus( await handleDidShareItems(
"Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad." fileName: pending.fileName,
sentSummary: "Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
) )
setSending(false) setSending(false)
@@ -113,9 +113,10 @@ extension AppModel: SendCapable {
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
guard let self else { return } guard let self else { return }
if success { if success {
let pageWord = pending.pageCount == 1 ? "page" : "pages"
await self.handleDidShareItems( await self.handleDidShareItems(
fileName: pending.fileName, fileName: pending.fileName,
pageCount: pending.pageCount sentSummary: "Sent — \(pending.pageCount) \(pageWord)."
) )
} else { } else {
self.handleDidFailToShareItems(fileName: pending.fileName) self.handleDidFailToShareItems(fileName: pending.fileName)
@@ -194,16 +195,17 @@ extension AppModel: SendCapable {
) )
} }
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam. /// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam — also the
func handleDidShareItems(fileName: String, pageCount: Int) async { /// 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 } guard !session.isEmpty else { return }
var message: String var message = sentSummary
do { do {
_ = try await spool.archiveCurrent(pdfFileName: fileName) _ = try await spool.archiveCurrent(pdfFileName: fileName)
let pageWord = pageCount == 1 ? "page" : "pages"
message = "Sent — \(pageCount) \(pageWord)."
} catch { } 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 // 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, // the current session and the past-submissions list are stale until reloaded,
+3
View File
@@ -10,6 +10,9 @@ if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil {
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" { if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" {
MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() } MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() }
} }
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" {
MainActor.assumeIsolated { PickerSelfTest.runSendTruthOnlyIfRequested() }
}
if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil { if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil {
MainActor.assumeIsolated { PickerSelfTest.runIfRequested() } MainActor.assumeIsolated { PickerSelfTest.runIfRequested() }
} }
+47 -17
View File
@@ -35,9 +35,28 @@ public actor SpoolStore {
} }
/// The session currently accepting captures. Cheap accessor — all reconciliation already /// 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 { 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 /// 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, pngData: Data, pixelWidth: Int, pixelHeight: Int,
scale: CGFloat, capturedAt: Date scale: CGFloat, capturedAt: Date
) throws -> Capture { ) throws -> Capture {
let open = try ensureOpenSession()
let captureID = UUID() let captureID = UUID()
let sequence = openSession.nextSequence let sequence = open.nextSequence
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png" 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) let fileURL = sessionDir.appendingPathComponent(fileName)
try AtomicFile.write(pngData, to: fileURL) try AtomicFile.write(pngData, to: fileURL)
let capture = Capture( let capture = Capture(
id: captureID, sequence: sequence, fileName: fileName, id: captureID, sequence: sequence, fileName: fileName,
pixelWidth: pixelWidth, pixelHeight: pixelHeight, pixelWidth: pixelWidth, pixelHeight: pixelHeight,
scale: scale, capturedAt: capturedAt) scale: scale, capturedAt: capturedAt)
let updated = openSession.appending(capture) let updated = open.appending(capture)
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json")) try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
openSession = updated openSession = updated
return capture return capture
@@ -71,12 +91,13 @@ public actor SpoolStore {
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11), /// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
/// not this remove path.) /// not this remove path.)
public func remove(captureID: UUID) throws -> CaptureSession { 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( throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path, path: paths.sessionDirectory(open.id).path,
underlying: "capture \(captureID) is not in the open session") 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) let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
do { do {
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true) 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. /// pdfFileName, starts a fresh empty open session, and applies session retention.
/// Returns the archived one. /// Returns the archived one.
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession { public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
guard !openSession.isEmpty else { let open = try ensureOpenSession()
guard !open.isEmpty else {
throw ShotdeckError.spoolWriteFailed( throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path, path: paths.sessionDirectory(open.id).path,
underlying: "cannot archive an empty session") 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) openSession = try Self.createFreshSession(paths: paths)
applyRetention() applyRetention()
return archived return archived
@@ -120,12 +142,13 @@ public actor SpoolStore {
/// simply replaced — there is nothing to keep. Returns the archived session, or /// simply replaced — there is nothing to keep. Returns the archived session, or
/// nil when the open session was empty. /// nil when the open session was empty.
public func closeCurrentSession() throws -> CaptureSession? { public func closeCurrentSession() throws -> CaptureSession? {
guard !openSession.isEmpty else { let open = try ensureOpenSession()
guard !open.isEmpty else {
openSession = try Self.createFreshSession(paths: paths) openSession = try Self.createFreshSession(paths: paths)
return nil return nil
} }
let archived = try moveOpenSessionToArchive( let archived = try moveOpenSessionToArchive(
openSession.markArchived(pdfFileName: openSession.pdfFileName)) open.markArchived(pdfFileName: open.pdfFileName))
openSession = try Self.createFreshSession(paths: paths) openSession = try Self.createFreshSession(paths: paths)
applyRetention() applyRetention()
return archived 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, /// 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. /// with no filesystem change, if the open session has captures.
public func startNewSession() throws -> CaptureSession { public func startNewSession() throws -> CaptureSession {
guard openSession.isEmpty else { let open = try ensureOpenSession()
guard open.isEmpty else {
throw ShotdeckError.spoolWriteFailed( throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path, path: paths.sessionDirectory(open.id).path,
underlying: "cannot start a new session: \(openSession.captures.count) capture(s) present in the open session") underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
} }
let fresh = try Self.createFreshSession(paths: paths) let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh openSession = fresh
@@ -231,9 +255,15 @@ public actor SpoolStore {
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = [] var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
for id in ids { for id in ids {
let dir = paths.archiveDirectory(id) 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( let session = try Self.reconcileSessionDirectory(
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default) 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 folderCreatedAt = values?.creationDate ?? session.createdAt
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
keyed.append((session, folderCreatedAt, folderModifiedAt)) keyed.append((session, folderCreatedAt, folderModifiedAt))
@@ -187,6 +187,35 @@ func theSendArchivePathAppliesRetention() async throws {
#expect(kept.allSatisfy { $0.pdfFileName != nil }) #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 // MARK: - Fixtures
private enum FixtureError: Error { private enum FixtureError: Error {
+20 -1
View File
@@ -105,7 +105,8 @@ func successfulSendRefreshesPastSubmissions() async throws {
let model = AppDelegate.makeLaunchModel(appSupportRoot: root) let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
_ = try await addCapture(to: model, red: 0.4, green: 0.4, blue: 0.4) _ = 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.statusLine == "Sent — 1 page.")
#expect(model.session.isEmpty) #expect(model.session.isEmpty)
@@ -150,6 +151,24 @@ func sessionStartAndSendRefuseToOverlap() async throws {
#expect(model.pastSessions.first?.captures.map(\.id) == [capture.id]) #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 // MARK: - Fixtures
/// Appends one generated PNG through the store and refreshes `model.session` from /// Appends one generated PNG through the store and refreshes `model.session` from