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
5 changed files with 144 additions and 29 deletions
Showing only changes of commit eaa5bd5884 - Show all commits
+23 -3
View File
@@ -37,6 +37,11 @@ public final class AppModel {
public private(set) var statusLine: String? public private(set) var statusLine: String?
public private(set) var isCapturing: Bool = false public private(set) var isCapturing: Bool = false
public private(set) var isSending: Bool = false public private(set) var isSending: Bool = false
/// True while "Start new session" is between its guard and its store call — the
/// synchronous flag both this action and send() check BEFORE their first await, so
/// the two can never interleave a session close with an in-flight compose (a
/// SwiftUI `.disabled` render-time guard alone does not stop a queued Task).
public private(set) var isStartingNewSession: Bool = false
public private(set) var outboxDisplayName: String public private(set) var outboxDisplayName: String
public private(set) var watchFolderDisplayName: String public private(set) var watchFolderDisplayName: String
/// Live transport choice; WP-onedrive reads this to pick the send path and to drive /// Live transport choice; WP-onedrive reads this to pick the send path and to drive
@@ -134,6 +139,9 @@ public final class AppModel {
func setStatus(_ text: String?) { statusLine = text } func setStatus(_ text: String?) { statusLine = text }
func setSending(_ value: Bool) { isSending = value } func setSending(_ value: Bool) { isSending = value }
/// Fixture seam (same family as setSending): lets tests/PanelSnapshot stage the
/// in-flight-start state that production only ever reaches inside startNewSession().
func setStartingNewSession(_ value: Bool) { isStartingNewSession = value }
func setCapturing(_ value: Bool) { isCapturing = value } func setCapturing(_ value: Bool) { isCapturing = value }
func replaceSession(_ new: CaptureSession) { session = new } func replaceSession(_ new: CaptureSession) { session = new }
func replaceRegion(_ new: CaptureRegion?) { region = new } func replaceRegion(_ new: CaptureRegion?) { region = new }
@@ -403,15 +411,27 @@ public final class AppModel {
} }
} }
/// True when "Start new session" applies: there is something to keep and no send /// True when "Start new session" applies: there is something to keep and neither a
/// in flight that would archive the session on its own. /// send nor another session start is in flight.
public var canStartNewSession: Bool { !session.isEmpty && !isSending } public var canStartNewSession: Bool {
!session.isEmpty && !isSending && !isStartingNewSession
}
/// Menu "Start new session": keeps the current screenshots as a past session /// Menu "Start new session": keeps the current screenshots as a past session
/// (moved into the single archive folder — never deleted) and opens a fresh empty /// (moved into the single archive folder — never deleted) and opens a fresh empty
/// session. Session retention (newest 10 kept) is applied inside the store, on /// session. Session retention (newest 10 kept) is applied inside the store, on
/// this path and on the send path alike. /// this path and on the send path alike.
public func startNewSession() async { public func startNewSession() async {
// Re-checked here on the main actor, synchronously, before the first await:
// 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.")
return
}
isStartingNewSession = true
defer { isStartingNewSession = false }
var message: String var message: String
do { do {
if let archived = try await spool.closeCurrentSession() { if let archived = try await spool.closeCurrentSession() {
+9 -1
View File
@@ -98,7 +98,7 @@ private struct PastSessionRow: View {
model.revealSentPDF(session) model.revealSentPDF(session)
} }
.disabled(model.sentPDFURL(for: session) == nil) .disabled(model.sentPDFURL(for: session) == nil)
.help(session.pdfFileName.map { "Reveal \($0)" } ?? "This session was never sent.") .help(pdfHelpText)
Button("Captures") { Button("Captures") {
model.revealSessionCaptures(session) model.revealSessionCaptures(session)
} }
@@ -106,6 +106,14 @@ private struct PastSessionRow: View {
} }
} }
private var pdfHelpText: String {
guard let name = session.pdfFileName else { return "This session was never sent." }
guard model.sentPDFURL(for: session) != nil else {
return "The PDF \(name) is no longer in the output folder."
}
return "Reveal \(name)"
}
private var submissionLabel: String { private var submissionLabel: String {
let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")"
guard let name = session.pdfFileName else { guard let name = session.pdfFileName else {
+18 -3
View File
@@ -14,6 +14,13 @@ struct ComposedSend: Sendable {
extension AppModel: SendCapable { extension AppModel: SendCapable {
public func send(anchor: NSView?) async { public func send(anchor: NSView?) async {
guard !session.isEmpty, !isSending else { return } guard !session.isEmpty, !isSending else { return }
// Same synchronous guard as AppModel.startNewSession(): refuse while a session
// start is mid-flight, instead of composing from a session directory that is
// being renamed into the archive.
guard !isStartingNewSession else {
setStatus("Finish starting the new session first.")
return
}
setSending(true) setSending(true)
// Wait for any IN-FLIGHT transport/folder reconcile (chooseTransport/ // Wait for any IN-FLIGHT transport/folder reconcile (chooseTransport/
@@ -190,14 +197,22 @@ extension AppModel: SendCapable {
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam. /// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam.
func handleDidShareItems(fileName: String, pageCount: Int) async { func handleDidShareItems(fileName: String, pageCount: Int) async {
guard !session.isEmpty else { return } guard !session.isEmpty else { return }
var message: String
do { do {
_ = try await spool.archiveCurrent(pdfFileName: fileName) _ = try await spool.archiveCurrent(pdfFileName: fileName)
replaceSession(try await spool.currentSession())
let pageWord = pageCount == 1 ? "page" : "pages" let pageWord = pageCount == 1 ? "page" : "pages"
setStatus("Sent — \(pageCount) \(pageWord).") message = "Sent — \(pageCount) \(pageWord)."
} catch { } catch {
setStatus((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,
// and after a failure the store (not this model) knows whether the session
// actually moved. Any refresh problem is appended to the status, never hidden.
if let refreshProblem = await reloadFromSpool() {
message += " \(refreshProblem)"
}
setStatus(message)
} }
/// `NSSharingServiceDelegate.sharingService(_:didFailToShareItems:error:)` seam, /// `NSSharingServiceDelegate.sharingService(_:didFailToShareItems:error:)` seam,
+39 -22
View File
@@ -64,8 +64,12 @@ public actor SpoolStore {
} }
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops /// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
/// its manifest entry. NEVER unlinks/deletes a user PNG. Throws (no filesystem change) if /// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
/// `captureID` is not present in the open session. /// filesystem change) if `captureID` is not present in the open session.
/// (Session retention is the one place that removes files: when a session falls
/// outside the newest `defaultRetainedSessionCount`, its WHOLE folder — including
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
/// 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 { guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
throw ShotdeckError.spoolWriteFailed( throw ShotdeckError.spoolWriteFailed(
@@ -104,7 +108,7 @@ public actor SpoolStore {
} }
let archived = try moveOpenSessionToArchive(openSession.markArchived(pdfFileName: pdfFileName)) let archived = try moveOpenSessionToArchive(openSession.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths) openSession = try Self.createFreshSession(paths: paths)
try applyRetention() applyRetention()
return archived return archived
} }
@@ -123,7 +127,7 @@ public actor SpoolStore {
let archived = try moveOpenSessionToArchive( let archived = try moveOpenSessionToArchive(
openSession.markArchived(pdfFileName: openSession.pdfFileName)) openSession.markArchived(pdfFileName: openSession.pdfFileName))
openSession = try Self.createFreshSession(paths: paths) openSession = try Self.createFreshSession(paths: paths)
try applyRetention() applyRetention()
return archived return archived
} }
@@ -154,12 +158,22 @@ public actor SpoolStore {
} }
/// The retention policy every archive path funnels through, so it can never be /// The retention policy every archive path funnels through, so it can never be
/// forgotten: new sessions over the default count are pruned. /// forgotten: sessions over the default count are pruned. A retention failure is
private func applyRetention() throws { /// logged loudly (with the exact path) and never thrown — the archive it follows
let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount) /// already succeeded, and converting a completed send into a reported failure
if !removed.isEmpty { /// would be a lie (the safe direction of a failed prune is keeping too much, never
Log.spool.warning( /// losing data). The visible symptom of a failed prune is simply more than 10
"Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).") /// sessions in the Past submissions list.
private func applyRetention() {
do {
let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount)
if !removed.isEmpty {
Log.spool.warning(
"Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).")
}
} catch {
Log.spool.error(
"Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
} }
} }
@@ -204,27 +218,30 @@ public actor SpoolStore {
/// ever losing a PNG. /// ever losing a PNG.
/// ///
/// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is /// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is
/// pinned in AtomicFileTests), then the session folder's creation date to break ties /// pinned in AtomicFileTests), then the session folder's creation date and content
/// at real resolution (two sessions closed in the same second would otherwise order, /// modification date to break ties at real resolution (two sessions closed in the
/// and therefore prune, arbitrarily by UUID), then the id as the final /// same second would otherwise order, and therefore prune, arbitrarily by UUID —
/// deterministic tie-break. The folder date is a tie-break refinement only — the /// and on a volume that reports no creation date the modification date still keeps
/// manifest `createdAt` stays the authoritative timestamp; on a volume that reports no /// retention on real order), then the id as the final deterministic tie-break.
/// creation date the tie-break degrades to the id. /// The folder dates are tie-break refinements only — the manifest `createdAt` stays
/// the authoritative timestamp; if a volume reports neither date the tie-break
/// degrades to the id.
public func archivedSessions() throws -> [CaptureSession] { public func archivedSessions() throws -> [CaptureSession] {
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default) let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
var keyed: [(session: CaptureSession, folderCreatedAt: 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)
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 folderCreatedAt = (try? dir.resourceValues(forKeys: [.creationDateKey]))?.creationDate let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
?? session.createdAt let folderCreatedAt = values?.creationDate ?? session.createdAt
keyed.append((session, folderCreatedAt)) let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
keyed.append((session, folderCreatedAt, folderModifiedAt))
} }
return keyed return keyed
.sorted { lhs, rhs in .sorted { lhs, rhs in
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.session.id.uuidString) (lhs.session.createdAt, lhs.folderCreatedAt, lhs.folderModifiedAt, lhs.session.id.uuidString)
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.session.id.uuidString) > (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
} }
.map(\.session) .map(\.session)
} }
@@ -95,6 +95,61 @@ func startNewSessionOnEmptySessionCreatesNoPastSession() async throws {
#expect(model.statusLine == "New session started.") #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", pageCount: 1)
#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])
}
// 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