fix(sessions): adversarial-review fixes for MMDB-2925 (PR #29 review round 1)

Review verdict FAIL raised 7 defects; this addresses 1-5 and 7. 6 is
accepted as-is (see below).

1. Retention failure after a COMPLETED archive no longer throws: a failed
   prune is logged loudly with the exact path and otherwise ignored, so a
   successful send can never be reported as "The screenshot could not be
   saved". The visible symptom of a failed prune is simply more than 10
   sessions listed.
2. handleDidShareItems now refreshes the current session AND the
   past-submissions list from the store on both the success and the
   failure path (previously the menu count and any open window went stale
   after every send). Any refresh problem is appended to the status line.
3. "Start new session" and send() now guard against each other
   synchronously before their first await (isStartingNewSession flag on
   both sides), instead of relying on the SwiftUI .disabled state alone —
   a queued Task could otherwise rename the session directory out from
   under an in-flight PDF compose.
4. Contract decision, documented in code: session retention prunes the
   whole session folder INCLUDING removed/ parked captures. That is the
   requested retention policy ("retain the past 10 sessions"), and the
   D-11 never-delete note on remove() now says so explicitly.
5. Session ordering tie-break chain extended: manifest createdAt, then the
   folder creation date, then the folder content-modification date, then
   the id — so retention stays on real creation order even on a volume
   that reports no creation date.
7. The PDF button's help text now distinguishes never-sent from
   sent-but-no-longer-on-disk (the button was already disabled in both).

6 (empty close leaves the old empty spool/ folder behind) is left exactly
as the pinned SpoolStoreTests contract has it (startNewSession test 16
asserts the folder remains); it is pre-existing behavior, harmless (the
store reconciles and picks the newest candidate), and out of scope here.

Tests: 2 new app-target regression tests (send refreshes past
submissions; start/send refuse to overlap) — 134 tests pass.
This commit is contained in:
Claude Fable 5
2026-10-11 13:48:31 +04:00
parent 6ab398c3f2
commit eaa5bd5884
5 changed files with 144 additions and 29 deletions
+23 -3
View File
@@ -37,6 +37,11 @@ public final class AppModel {
public private(set) var statusLine: String?
public private(set) var isCapturing: 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 watchFolderDisplayName: String
/// 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 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 replaceSession(_ new: CaptureSession) { session = 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
/// in flight that would archive the session on its own.
public var canStartNewSession: Bool { !session.isEmpty && !isSending }
/// True when "Start new session" applies: there is something to keep and neither a
/// send nor another session start is in flight.
public var canStartNewSession: Bool {
!session.isEmpty && !isSending && !isStartingNewSession
}
/// 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
/// session. Session retention (newest 10 kept) is applied inside the store, on
/// this path and on the send path alike.
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
do {
if let archived = try await spool.closeCurrentSession() {
+9 -1
View File
@@ -98,7 +98,7 @@ private struct PastSessionRow: View {
model.revealSentPDF(session)
}
.disabled(model.sentPDFURL(for: session) == nil)
.help(session.pdfFileName.map { "Reveal \($0)" } ?? "This session was never sent.")
.help(pdfHelpText)
Button("Captures") {
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 {
let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")"
guard let name = session.pdfFileName else {
+18 -3
View File
@@ -14,6 +14,13 @@ struct ComposedSend: Sendable {
extension AppModel: SendCapable {
public func send(anchor: NSView?) async {
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)
// Wait for any IN-FLIGHT transport/folder reconcile (chooseTransport/
@@ -190,14 +197,22 @@ extension AppModel: SendCapable {
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam.
func handleDidShareItems(fileName: String, pageCount: Int) async {
guard !session.isEmpty else { return }
var message: String
do {
_ = try await spool.archiveCurrent(pdfFileName: fileName)
replaceSession(try await spool.currentSession())
let pageWord = pageCount == 1 ? "page" : "pages"
setStatus("Sent — \(pageCount) \(pageWord).")
message = "Sent — \(pageCount) \(pageWord)."
} 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,
+35 -18
View File
@@ -64,8 +64,12 @@ public actor SpoolStore {
}
/// 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
/// `captureID` is not present in the open session.
/// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
/// 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 {
guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
throw ShotdeckError.spoolWriteFailed(
@@ -104,7 +108,7 @@ public actor SpoolStore {
}
let archived = try moveOpenSessionToArchive(openSession.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
try applyRetention()
applyRetention()
return archived
}
@@ -123,7 +127,7 @@ public actor SpoolStore {
let archived = try moveOpenSessionToArchive(
openSession.markArchived(pdfFileName: openSession.pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
try applyRetention()
applyRetention()
return archived
}
@@ -154,13 +158,23 @@ public actor SpoolStore {
}
/// 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 {
/// forgotten: sessions over the default count are pruned. A retention failure is
/// logged loudly (with the exact path) and never thrown — the archive it follows
/// already succeeded, and converting a completed send into a reported failure
/// would be a lie (the safe direction of a failed prune is keeping too much, never
/// losing data). The visible symptom of a failed prune is simply more than 10
/// 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)")
}
}
/// Writes the archived manifest, then renames the whole session directory from
@@ -204,27 +218,30 @@ public actor SpoolStore {
/// 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.
/// pinned in AtomicFileTests), then the session folder's creation date and content
/// modification date to break ties at real resolution (two sessions closed in the
/// same second would otherwise order, and therefore prune, arbitrarily by UUID —
/// and on a volume that reports no creation date the modification date still keeps
/// retention on real order), then the id as the final deterministic tie-break.
/// 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] {
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 {
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))
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
let folderCreatedAt = values?.creationDate ?? session.createdAt
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
keyed.append((session, folderCreatedAt, folderModifiedAt))
}
return keyed
.sorted { lhs, rhs in
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.session.id.uuidString)
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.session.id.uuidString)
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.folderModifiedAt, lhs.session.id.uuidString)
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
}
.map(\.session)
}
@@ -95,6 +95,61 @@ func startNewSessionOnEmptySessionCreatesNoPastSession() async throws {
#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
/// Appends one generated PNG through the store and refreshes `model.session` from