feat(sessions): past submissions list + start-new-session with 10-session retention

MMDB-2925. Two new menu functions in the Redline app:

- "Start new session" keeps the current screenshots as a past session
  (moved into the single archive/ folder — never deleted on close) and
  opens a fresh empty session. Sessions closed without ever sending keep
  pdfFileName nil and show as "Not sent" in the list.
- "Past submissions…" opens a window listing every retained session
  (timestamp, page count, what was sent) with actions to reveal the sent
  PDF and the session's screenshot folder.

Retention (Ben's rule 2026-10-11: "retain the past 10 sessions"): both
archive paths (send and close) keep the newest 10 archived session
folders in archive/ and remove the rest. Any PDF a pruned session
produced is untouched — it lives in the outbox/OneDrive folder.

archivedSessions() ordering now tie-breaks same-second sessions by the
session folder's creation date, so listing and pruning are deterministic
(manifest timestamps are whole-second ISO8601 — format pinned in
AtomicFileTests).

Tests: 6 core tests in SessionRetentionTests (close/keep/reconcile,
sent-vs-unsent, retention of 10, explicit prune, send-path retention) and
3 app-target tests in SessionWorkflowTests driving the real AppModel menu
actions through AppDelegate.makeLaunchModel(). PanelSnapshot renders the
new window as panel-06b-past-submissions.png.
This commit is contained in:
Claude Fable 5
2026-10-11 13:35:38 +04:00
parent eb1af5bf18
commit 6ab398c3f2
8 changed files with 790 additions and 18 deletions
@@ -2,7 +2,7 @@ import Foundation
public enum SessionState: String, Codable, Sendable {
case open // accepting captures
case archived // its PDF has been built and sent; kept forever, never deleted
case archived // closed and kept as a past session (sent or not); pruned by retention
}
/// The manifest persisted as session.json alongside the PNGs.
@@ -11,7 +11,9 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
public let createdAt: Date
public private(set) var state: SessionState
public private(set) var captures: [Capture]
/// Set when the PDF is built, so a re-send reuses the same file.
/// Set when the PDF is built, so a re-send reuses the same file. nil on a
/// session that was closed without ever sending — the Past submissions list
/// shows that as "Not sent".
public private(set) var pdfFileName: String?
public init(
@@ -61,7 +63,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
}
/// Value-semantic: returns a new session; does not mutate `self`.
public func markArchived(pdfFileName: String) -> CaptureSession {
/// `pdfFileName` is nil when the session is closed without ever sending.
public func markArchived(pdfFileName: String?) -> CaptureSession {
CaptureSession(
id: id,
createdAt: createdAt,
+97 -12
View File
@@ -4,6 +4,13 @@ import CoreGraphics
import Darwin
public actor SpoolStore {
/// How many archived sessions (past submissions) are kept on disk. Ben's
/// retention rule (2026-10-11): "by default, retain the past 10 sessions" —
/// older session folders are removed from `archive/` once this is exceeded.
/// Any PDF a pruned session produced is not touched: it lives in the outbox
/// (or the OneDrive folder) it was sent to.
public static let defaultRetainedSessionCount = 10
private let paths: AppSupportPaths
private var openSession: CaptureSession
@@ -87,25 +94,87 @@ public actor SpoolStore {
}
/// Closes the open session (must be non-empty), moves its directory under archive/, records
/// pdfFileName, and starts a fresh empty open session. Returns the archived one.
/// 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 {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
underlying: "cannot archive an empty session")
}
let archived = openSession.markArchived(pdfFileName: pdfFileName)
let sessionDir = paths.sessionDirectory(openSession.id)
let archived = try moveOpenSessionToArchive(openSession.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
try applyRetention()
return archived
}
/// Closes the open session — sent or not — and keeps its captures as a past
/// session under archive/, then starts a fresh empty open session. Unlike
/// `archiveCurrent(pdfFileName:)` this never requires a PDF: the archived session
/// keeps whatever pdfFileName it already has (nil when it was never sent, which
/// the Past submissions list shows as "Not sent"). An empty open session is
/// 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 {
openSession = try Self.createFreshSession(paths: paths)
return nil
}
let archived = try moveOpenSessionToArchive(
openSession.markArchived(pdfFileName: openSession.pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
try applyRetention()
return archived
}
/// Keeps the newest `limit` archived sessions and removes the rest of the session
/// folders from archive/ (the single folder all sessions live in). Returns the
/// removed ids. Only UUID session folders directly under archive/ are ever
/// touched — never spool/, never anything else. This is the requested retention
/// policy (Ben, 2026-10-11: "retain the past 10 sessions"): a session folder
/// dropped here is gone for good, while any PDF it produced stays in the
/// outbox/OneDrive folder it was sent to.
public func pruneArchivedSessions(keeping limit: Int) throws -> [UUID] {
let sessions = try archivedSessions()
guard sessions.count > limit else { return [] }
var removed: [UUID] = []
for session in sessions.dropFirst(limit) {
let dir = paths.archiveDirectory(session.id)
do {
try FileManager.default.removeItem(at: dir)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: dir.path,
underlying: "could not remove an expired session: \(error.localizedDescription)")
}
removed.append(session.id)
}
try AtomicFile.fsyncDirectory(at: paths.archive)
return removed
}
/// The retention policy every archive path funnels through, so it can never be
/// forgotten: new sessions over the default count are pruned.
private func applyRetention() throws {
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).")
}
}
/// Writes the archived manifest, then renames the whole session directory from
/// spool/ into archive/ in one atomic operation.
private func moveOpenSessionToArchive(_ archived: CaptureSession) throws -> CaptureSession {
let sessionDir = paths.sessionDirectory(archived.id)
try AtomicFile.writeJSON(archived, to: sessionDir.appendingPathComponent("session.json"))
let archiveDir = paths.archiveDirectory(openSession.id)
let archiveDir = paths.archiveDirectory(archived.id)
guard rename(sessionDir.path, archiveDir.path) == 0 else {
throw ShotdeckError.spoolWriteFailed(
path: sessionDir.path,
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
}
try AtomicFile.fsyncDirectory(at: paths.archive)
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
return archived
}
@@ -129,19 +198,35 @@ public actor SpoolStore {
return dir.appendingPathComponent(capture.fileName)
}
/// Archived sessions, newest createdAt first. Lazily reconciles each archive/ directory
/// Archived sessions, newest first. Lazily reconciles each archive/ directory
/// the same way init reconciles spool/ candidates (orphan recovery, missing-drop, corrupt
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
/// ever losing a PNG.
///
/// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is
/// pinned in AtomicFileTests), then the session folder's creation date to break ties
/// at real resolution (two sessions closed in the same second would otherwise order,
/// and therefore prune, arbitrarily by UUID), then the id as the final
/// deterministic tie-break. The folder date is a tie-break refinement only — the
/// manifest `createdAt` stays the authoritative timestamp; on a volume that reports no
/// creation date the tie-break degrades to the id.
public func archivedSessions() throws -> [CaptureSession] {
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
var sessions: [CaptureSession] = []
var keyed: [(session: CaptureSession, folderCreatedAt: Date)] = []
for id in ids {
sessions.append(
try Self.reconcileSessionDirectory(
at: paths.archiveDirectory(id), id: id, assumedStateIfRebuilt: .archived, fileManager: .default))
let dir = paths.archiveDirectory(id)
let session = try Self.reconcileSessionDirectory(
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
let folderCreatedAt = (try? dir.resourceValues(forKeys: [.creationDateKey]))?.creationDate
?? session.createdAt
keyed.append((session, folderCreatedAt))
}
return sessions.sorted { ($0.createdAt, $0.id.uuidString) > ($1.createdAt, $1.id.uuidString) }
return keyed
.sorted { lhs, rhs in
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.session.id.uuidString)
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.session.id.uuidString)
}
.map(\.session)
}
// MARK: - Reconciliation (static so they can run inside init)