Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd621608b0 | ||
|
|
01252b90da | ||
|
|
0506ce04e9 | ||
|
|
eaa5bd5884 | ||
|
|
6ab398c3f2 | ||
|
|
2a3af20d04 |
+2
-2
@@ -13,9 +13,9 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>0.3.2</string>
|
<string>0.4.0</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>5</string>
|
<string>6</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>14.0</string>
|
<string>14.0</string>
|
||||||
<key>LSUIElement</key>
|
<key>LSUIElement</key>
|
||||||
|
|||||||
@@ -14,6 +14,11 @@ public protocol SettingsWindowPresenting: AnyObject {
|
|||||||
func presentSettingsWindow()
|
func presentSettingsWindow()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
public protocol SubmissionsWindowPresenting: AnyObject {
|
||||||
|
func presentSubmissionsWindow()
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
public protocol ReturnsSectionProviding: AnyObject {
|
public protocol ReturnsSectionProviding: AnyObject {
|
||||||
@ViewBuilder func returnsSection() -> AnyView
|
@ViewBuilder func returnsSection() -> AnyView
|
||||||
@@ -27,10 +32,17 @@ public final class AppModel {
|
|||||||
public private(set) var screenRecordingGranted: Bool
|
public private(set) var screenRecordingGranted: Bool
|
||||||
public private(set) var allReturns: [ReturnedDocument] = []
|
public private(set) var allReturns: [ReturnedDocument] = []
|
||||||
public private(set) var commentedReturns: [ReturnedDocument] = []
|
public private(set) var commentedReturns: [ReturnedDocument] = []
|
||||||
|
/// Retained past sessions (newest first) — what the Past submissions window lists.
|
||||||
|
public private(set) var pastSessions: [CaptureSession] = []
|
||||||
public private(set) var statusLine: String?
|
public private(set) var statusLine: String?
|
||||||
public private(set) var updateStatus: String?
|
public private(set) var updateStatus: 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
|
||||||
@@ -126,6 +138,9 @@ public final class AppModel {
|
|||||||
func setStatus(_ text: String?) { statusLine = text }
|
func setStatus(_ text: String?) { statusLine = text }
|
||||||
func setUpdateStatus(_ text: String?) { updateStatus = text }
|
func setUpdateStatus(_ text: String?) { updateStatus = 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 }
|
||||||
@@ -133,6 +148,7 @@ public final class AppModel {
|
|||||||
allReturns = all
|
allReturns = all
|
||||||
commentedReturns = commented
|
commentedReturns = commented
|
||||||
}
|
}
|
||||||
|
func setPastSessions(_ value: [CaptureSession]) { pastSessions = value }
|
||||||
func setFolderDisplayNames(outbox: String, watch: String) {
|
func setFolderDisplayNames(outbox: String, watch: String) {
|
||||||
outboxDisplayName = outbox
|
outboxDisplayName = outbox
|
||||||
watchFolderDisplayName = watch
|
watchFolderDisplayName = watch
|
||||||
@@ -226,6 +242,12 @@ public final class AppModel {
|
|||||||
// Empty ledger on first run is not an error.
|
// Empty ledger on first run is not an error.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
setPastSessions(try await spool.archivedSessions())
|
||||||
|
} catch {
|
||||||
|
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not load past sessions.")
|
||||||
|
}
|
||||||
|
|
||||||
// OneDrive mode: outbox == watch folder, so a freshly written, unmarked PDF must
|
// OneDrive mode: outbox == watch folder, so a freshly written, unmarked PDF must
|
||||||
// never show up as a return; only a document that already carries a mark does.
|
// never show up as a return; only a document that already carries a mark does.
|
||||||
// Also make sure the resolved OneDrive folder actually exists before the
|
// Also make sure the resolved OneDrive folder actually exists before the
|
||||||
@@ -388,6 +410,100 @@ public final class AppModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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(isSending ? "Finish the current send first." : "A new session is already being started.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isStartingNewSession = true
|
||||||
|
defer { isStartingNewSession = false }
|
||||||
|
|
||||||
|
var message: String
|
||||||
|
do {
|
||||||
|
if let archived = try await spool.closeCurrentSession() {
|
||||||
|
let count = archived.captures.count
|
||||||
|
message = "New session — \(count) capture\(count == 1 ? "" : "s") kept as a past session."
|
||||||
|
} else {
|
||||||
|
message = "New session started."
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
message = (error as? ShotdeckError)?.errorDescription ?? "Could not start a new session."
|
||||||
|
}
|
||||||
|
if let refreshProblem = await reloadFromSpool() {
|
||||||
|
message += " \(refreshProblem)"
|
||||||
|
}
|
||||||
|
setStatus(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-reads the open session and the past-session list from the store. Returns a
|
||||||
|
/// problem description when either read failed (the caller decides how to surface
|
||||||
|
/// it), nil when everything was refreshed — never silently substitutes stale state.
|
||||||
|
func reloadFromSpool() async -> String? {
|
||||||
|
var problems: [String] = []
|
||||||
|
do {
|
||||||
|
replaceSession(try await spool.currentSession())
|
||||||
|
} catch {
|
||||||
|
problems.append(
|
||||||
|
"Could not reload the current session: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
setPastSessions(try await spool.archivedSessions())
|
||||||
|
} catch {
|
||||||
|
problems.append(
|
||||||
|
"Could not load past sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
|
||||||
|
}
|
||||||
|
return problems.isEmpty ? nil : problems.joined(separator: " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a past session's sent PDF lives now (the outbox in AirDrop mode, the
|
||||||
|
/// OneDrive folder in OneDrive mode), or nil when it was never sent / is gone.
|
||||||
|
public func sentPDFURL(for session: CaptureSession) -> URL? {
|
||||||
|
guard let name = session.pdfFileName else { return nil }
|
||||||
|
let url = outboxURL.appendingPathComponent(name)
|
||||||
|
return FileManager.default.fileExists(atPath: url.path) ? url : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "PDF" action on a past-submission row: reveals the exact PDF that was sent.
|
||||||
|
public func revealSentPDF(_ session: CaptureSession) {
|
||||||
|
guard session.pdfFileName != nil else {
|
||||||
|
setStatus("That session was never sent.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let url = sentPDFURL(for: session) else {
|
||||||
|
setStatus("The PDF is no longer in \(outboxDisplayName).")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([url])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Captures" action on a past-submission row: reveals that session's folder.
|
||||||
|
public func revealSessionCaptures(_ session: CaptureSession) {
|
||||||
|
let dir = paths.archiveDirectory(session.id)
|
||||||
|
guard FileManager.default.fileExists(atPath: dir.path) else {
|
||||||
|
setStatus("That past session is no longer on disk.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([dir])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The single folder every retained session lives in.
|
||||||
|
public func openSessionsFolder() {
|
||||||
|
NSWorkspace.shared.open(paths.archive)
|
||||||
|
}
|
||||||
|
|
||||||
public func copyCommentedLinks() async {
|
public func copyCommentedLinks() async {
|
||||||
do {
|
do {
|
||||||
let text = try await ledger.clipboardText()
|
let text = try await ledger.clipboardText()
|
||||||
|
|||||||
@@ -119,6 +119,26 @@ struct MenuBarView: View {
|
|||||||
}
|
}
|
||||||
.disabled(!model.canRevealLastPDF)
|
.disabled(!model.canRevealLastPDF)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
Task { await model.startNewSession() }
|
||||||
|
} label: {
|
||||||
|
actionLabel("Start new session")
|
||||||
|
}
|
||||||
|
.disabled(!model.canStartNewSession)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
if let presenter = model as? SubmissionsWindowPresenting {
|
||||||
|
presenter.presentSubmissionsWindow()
|
||||||
|
} else {
|
||||||
|
model.setStatus("Past submissions are not available in this build.")
|
||||||
|
}
|
||||||
|
} label: {
|
||||||
|
actionLabel(
|
||||||
|
"Past submissions…",
|
||||||
|
trailing: model.pastSessions.isEmpty ? nil : "\(model.pastSessions.count)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Button {
|
Button {
|
||||||
Task { await model.captureNow() }
|
Task { await model.captureNow() }
|
||||||
} label: {
|
} label: {
|
||||||
|
|||||||
@@ -46,6 +46,11 @@ enum PanelSnapshot {
|
|||||||
|
|
||||||
let region = sampleRegion()
|
let region = sampleRegion()
|
||||||
|
|
||||||
|
// Two real past sessions through the REAL store paths (one sent with a PDF in
|
||||||
|
// the outbox, one closed without ever sending) so panel-06b has the exact two
|
||||||
|
// states the Past submissions window must distinguish.
|
||||||
|
try await seedPastSessions(to: model)
|
||||||
|
|
||||||
// 01 — Screen Recording missing (no public mutator; snapshot-only seam).
|
// 01 — Screen Recording missing (no public mutator; snapshot-only seam).
|
||||||
model.snapshotSetScreenRecordingGranted(false)
|
model.snapshotSetScreenRecordingGranted(false)
|
||||||
model.replaceRegion(nil)
|
model.replaceRegion(nil)
|
||||||
@@ -74,6 +79,15 @@ enum PanelSnapshot {
|
|||||||
to: directory.appendingPathComponent("panel-06-settings.png")
|
to: directory.appendingPathComponent("panel-06-settings.png")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 06b — Past submissions window against the same isolated model: the two
|
||||||
|
// seeded past sessions plus the live session's three captures from panel 04.
|
||||||
|
model.setPastSessions(try await model.spool.archivedSessions())
|
||||||
|
try render(
|
||||||
|
PastSubmissionsView().environment(model),
|
||||||
|
to: directory.appendingPathComponent("panel-06b-past-submissions.png"),
|
||||||
|
width: 440
|
||||||
|
)
|
||||||
|
|
||||||
// 07/08/09 — OneDrive-mode Settings + menu bar, on a SEPARATE isolated model so
|
// 07/08/09 — OneDrive-mode Settings + menu bar, on a SEPARATE isolated model so
|
||||||
// this transport switch never bleeds into the AirDrop-mode panels above.
|
// this transport switch never bleeds into the AirDrop-mode panels above.
|
||||||
try await captureOneDrivePanels(to: directory)
|
try await captureOneDrivePanels(to: directory)
|
||||||
@@ -188,6 +202,27 @@ enum PanelSnapshot {
|
|||||||
try renderMenuBar(model: updateModel, to: directory, name: "14-update-revert")
|
try renderMenuBar(model: updateModel, to: directory, name: "14-update-revert")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private static func seedPastSessions(to model: AppModel) async throws {
|
||||||
|
_ = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 192, height: 108, red: 0.55, green: 0.35, blue: 0.85),
|
||||||
|
pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date())
|
||||||
|
_ = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 192, height: 108, red: 0.25, green: 0.7, blue: 0.6),
|
||||||
|
pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date())
|
||||||
|
let sentName = "Redline-\(DubaiTime.fileStamp(Date())).pdf"
|
||||||
|
_ = try await model.spool.archiveCurrent(pdfFileName: sentName)
|
||||||
|
// The real send writes the PDF to the outbox; the fixture does the same so the
|
||||||
|
// row's PDF action is genuinely live in the snapshot.
|
||||||
|
try Data("%PDF-1.4\n% snapshot fixture\n".utf8).write(
|
||||||
|
to: model.paths.outbox.appendingPathComponent(sentName))
|
||||||
|
|
||||||
|
_ = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 160, height: 90, red: 0.9, green: 0.55, blue: 0.2),
|
||||||
|
pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date())
|
||||||
|
_ = try await model.spool.closeCurrentSession()
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private static func renderMenuBar(model: AppModel, to directory: URL, name: String) throws {
|
private static func renderMenuBar(model: AppModel, to directory: URL, name: String) throws {
|
||||||
try render(
|
try render(
|
||||||
@@ -197,9 +232,9 @@ enum PanelSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private static func render(_ view: some View, to url: URL) throws {
|
private static func render(_ view: some View, to url: URL, width: CGFloat = panelWidth) throws {
|
||||||
let wrapped = view
|
let wrapped = view
|
||||||
.frame(width: panelWidth, alignment: .topLeading)
|
.frame(width: width, alignment: .topLeading)
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
.background(Color(nsColor: .windowBackgroundColor))
|
.background(Color(nsColor: .windowBackgroundColor))
|
||||||
|
|
||||||
@@ -227,7 +262,7 @@ enum PanelSnapshot {
|
|||||||
size.height = hosting.intrinsicContentSize.height
|
size.height = hosting.intrinsicContentSize.height
|
||||||
}
|
}
|
||||||
if size.height < 1 { size.height = 240 }
|
if size.height < 1 { size.height = 240 }
|
||||||
size.width = panelWidth
|
size.width = width
|
||||||
size.height = ceil(size.height)
|
size.height = ceil(size.height)
|
||||||
|
|
||||||
hosting.setFrameSize(size)
|
hosting.setFrameSize(size)
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
import ShotdeckCore
|
||||||
|
|
||||||
|
/// "Past submissions…" window: every retained session and what was sent for it.
|
||||||
|
/// Read-and-reveal only — keeping/starting sessions is driven from the menu rows
|
||||||
|
/// (and the button on the current-session row below).
|
||||||
|
struct PastSubmissionsView: View {
|
||||||
|
@Environment(AppModel.self) private var model
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
currentSessionRow
|
||||||
|
Divider()
|
||||||
|
if model.pastSessions.isEmpty {
|
||||||
|
Text("No past sessions yet. Use “Start new session” to keep the current captures.")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
} else {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
ForEach(model.pastSessions) { session in
|
||||||
|
PastSessionRow(session: session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxHeight: 320)
|
||||||
|
}
|
||||||
|
Divider()
|
||||||
|
footer
|
||||||
|
}
|
||||||
|
.padding(10)
|
||||||
|
.frame(width: 420, alignment: .leading)
|
||||||
|
.controlSize(.small)
|
||||||
|
.task {
|
||||||
|
if let problem = await model.reloadFromSpool() {
|
||||||
|
model.setStatus(problem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentSessionRow: some View {
|
||||||
|
HStack(alignment: .center, spacing: 8) {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text("Current session")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text(currentSessionSummary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
Spacer(minLength: 8)
|
||||||
|
Button("Start new session") {
|
||||||
|
Task { await model.startNewSession() }
|
||||||
|
}
|
||||||
|
.disabled(!model.canStartNewSession)
|
||||||
|
.help("Keeps these captures as a past session and starts a fresh one.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentSessionSummary: String {
|
||||||
|
let count = model.session.captures.count
|
||||||
|
if count == 0 {
|
||||||
|
return "Nothing captured yet."
|
||||||
|
}
|
||||||
|
return "\(count) capture\(count == 1 ? "" : "s") · started \(DubaiTime.stamp(model.session.createdAt))"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var footer: some View {
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
Text("Sessions are kept in one folder — the newest \(SpoolStore.defaultRetainedSessionCount).")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
Spacer(minLength: 8)
|
||||||
|
Button("Open sessions folder") {
|
||||||
|
model.openSessionsFolder()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct PastSessionRow: View {
|
||||||
|
@Environment(AppModel.self) private var model
|
||||||
|
let session: CaptureSession
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(alignment: .center, spacing: 8) {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(DubaiTime.stamp(session.createdAt))
|
||||||
|
Text(submissionLabel)
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(session.pdfFileName == nil ? .secondary : .primary)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
Spacer(minLength: 8)
|
||||||
|
Button("PDF") {
|
||||||
|
model.revealSentPDF(session)
|
||||||
|
}
|
||||||
|
.disabled(model.sentPDFURL(for: session) == nil)
|
||||||
|
.help(pdfHelpText)
|
||||||
|
Button("Captures") {
|
||||||
|
model.revealSessionCaptures(session)
|
||||||
|
}
|
||||||
|
.help("Reveal this session's screenshots")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
return "\(pages) · not sent"
|
||||||
|
}
|
||||||
|
return "\(pages) · sent as \(name)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension AppModel: SubmissionsWindowPresenting {
|
||||||
|
private static var submissionsWindowController: NSWindowController?
|
||||||
|
|
||||||
|
public func presentSubmissionsWindow() {
|
||||||
|
if let existing = Self.submissionsWindowController {
|
||||||
|
existing.window?.makeKeyAndOrderFront(nil)
|
||||||
|
NSApp.activate()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let hosting = NSHostingController(rootView: PastSubmissionsView().environment(self))
|
||||||
|
let window = NSWindow(contentViewController: hosting)
|
||||||
|
window.title = "Redline — Past submissions"
|
||||||
|
window.styleMask = [.titled, .closable]
|
||||||
|
window.isReleasedWhenClosed = false
|
||||||
|
window.center()
|
||||||
|
let controller = NSWindowController(window: window)
|
||||||
|
Self.submissionsWindowController = controller
|
||||||
|
controller.showWindow(nil)
|
||||||
|
NSApp.activate()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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`.
|
||||||
|
|||||||
@@ -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/
|
||||||
@@ -88,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)
|
||||||
|
|
||||||
@@ -106,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)
|
||||||
@@ -187,17 +195,26 @@ 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 = sentSummary
|
||||||
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"
|
|
||||||
setStatus("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,
|
||||||
|
|||||||
@@ -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() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import Foundation
|
|||||||
|
|
||||||
public enum SessionState: String, Codable, Sendable {
|
public enum SessionState: String, Codable, Sendable {
|
||||||
case open // accepting captures
|
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.
|
/// 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 let createdAt: Date
|
||||||
public private(set) var state: SessionState
|
public private(set) var state: SessionState
|
||||||
public private(set) var captures: [Capture]
|
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 private(set) var pdfFileName: String?
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
@@ -61,7 +63,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
/// 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(
|
CaptureSession(
|
||||||
id: id,
|
id: id,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
|
|||||||
@@ -4,6 +4,13 @@ import CoreGraphics
|
|||||||
import Darwin
|
import Darwin
|
||||||
|
|
||||||
public actor SpoolStore {
|
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 let paths: AppSupportPaths
|
||||||
private var openSession: CaptureSession
|
private var openSession: CaptureSession
|
||||||
|
|
||||||
@@ -28,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
|
||||||
@@ -40,32 +66,38 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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 {
|
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)
|
||||||
@@ -87,35 +119,110 @@ public actor SpoolStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Closes the open session (must be non-empty), moves its directory under archive/, records
|
/// 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 {
|
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 = openSession.markArchived(pdfFileName: pdfFileName)
|
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
|
||||||
let sessionDir = paths.sessionDirectory(openSession.id)
|
openSession = try Self.createFreshSession(paths: paths)
|
||||||
|
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? {
|
||||||
|
let open = try ensureOpenSession()
|
||||||
|
guard !open.isEmpty else {
|
||||||
|
openSession = try Self.createFreshSession(paths: paths)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
let archived = try moveOpenSessionToArchive(
|
||||||
|
open.markArchived(pdfFileName: open.pdfFileName))
|
||||||
|
openSession = try Self.createFreshSession(paths: paths)
|
||||||
|
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: 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
|
||||||
|
/// 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"))
|
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 {
|
guard rename(sessionDir.path, archiveDir.path) == 0 else {
|
||||||
throw ShotdeckError.spoolWriteFailed(
|
throw ShotdeckError.spoolWriteFailed(
|
||||||
path: sessionDir.path,
|
path: sessionDir.path,
|
||||||
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
|
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
|
||||||
}
|
}
|
||||||
try AtomicFile.fsyncDirectory(at: paths.archive)
|
try AtomicFile.fsyncDirectory(at: paths.archive)
|
||||||
let fresh = try Self.createFreshSession(paths: paths)
|
|
||||||
openSession = fresh
|
|
||||||
return archived
|
return archived
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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
|
||||||
@@ -129,19 +236,44 @@ public actor SpoolStore {
|
|||||||
return dir.appendingPathComponent(capture.fileName)
|
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
|
/// 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
|
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
|
||||||
/// ever losing a PNG.
|
/// 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 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] {
|
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 sessions: [CaptureSession] = []
|
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
|
||||||
for id in ids {
|
for id in ids {
|
||||||
sessions.append(
|
let dir = paths.archiveDirectory(id)
|
||||||
try Self.reconcileSessionDirectory(
|
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
|
||||||
at: paths.archiveDirectory(id), id: id, assumedStateIfRebuilt: .archived, fileManager: .default))
|
// 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)
|
||||||
|
// 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))
|
||||||
}
|
}
|
||||||
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.folderModifiedAt, lhs.session.id.uuidString)
|
||||||
|
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
|
||||||
|
}
|
||||||
|
.map(\.session)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Reconciliation (static so they can run inside init)
|
// MARK: - Reconciliation (static so they can run inside init)
|
||||||
|
|||||||
@@ -0,0 +1,271 @@
|
|||||||
|
import CoreGraphics
|
||||||
|
import Foundation
|
||||||
|
import ImageIO
|
||||||
|
import Testing
|
||||||
|
import ShotdeckCore
|
||||||
|
|
||||||
|
// Session lifecycle + retention (MMDB-2925): "Start new session" keeps the current
|
||||||
|
// screenshots as a past session, and the newest 10 sessions are retained in the one
|
||||||
|
// archive folder.
|
||||||
|
|
||||||
|
// MARK: - 1. closeCurrentSession keeps the captures as a past session
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func closeCurrentSessionKeepsCapturesAsAPastSessionAndStartsFresh() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
let c1 = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 8, height: 8, red: 1, green: 0, blue: 0),
|
||||||
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
||||||
|
let c2 = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 8, height: 8, red: 0, green: 1, blue: 0),
|
||||||
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
||||||
|
|
||||||
|
let closedID = try await store.currentSession().id
|
||||||
|
let archived = try #require(try await store.closeCurrentSession())
|
||||||
|
|
||||||
|
#expect(archived.id == closedID)
|
||||||
|
#expect(archived.state == .archived)
|
||||||
|
#expect(archived.pdfFileName == nil) // never sent — shown as "Not sent"
|
||||||
|
#expect(archived.captures.map(\.id) == [c1.id, c2.id])
|
||||||
|
|
||||||
|
// Nothing is deleted: both PNGs live on under archive/<id>/.
|
||||||
|
let archiveDir = paths.archiveDirectory(closedID)
|
||||||
|
for capture in archived.captures {
|
||||||
|
#expect(FileManager.default.fileExists(
|
||||||
|
atPath: archiveDir.appendingPathComponent(capture.fileName).path))
|
||||||
|
}
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: paths.sessionDirectory(closedID).path))
|
||||||
|
|
||||||
|
let fresh = try await store.currentSession()
|
||||||
|
#expect(fresh.id != closedID)
|
||||||
|
#expect(fresh.state == .open)
|
||||||
|
#expect(fresh.isEmpty)
|
||||||
|
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.map(\.id) == [closedID])
|
||||||
|
#expect(past.first?.captures.count == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 2. closeCurrentSession on an empty open session just starts fresh
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func closeCurrentSessionOnAnEmptyOpenSessionStartsFreshWithoutArchiving() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
let before = try await store.currentSession().id
|
||||||
|
|
||||||
|
let archived = try await store.closeCurrentSession()
|
||||||
|
#expect(archived == nil)
|
||||||
|
|
||||||
|
let after = try await store.currentSession()
|
||||||
|
#expect(after.id != before)
|
||||||
|
#expect(after.isEmpty)
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 3. sent and unsent sessions are distinguishable in the past list
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func pastSessionsDistinguishSentFromUnsentByPDFFileName() 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: 1, green: 0, blue: 0),
|
||||||
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
||||||
|
let sent = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120000.pdf")
|
||||||
|
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 6, height: 6, red: 0, green: 0, blue: 1),
|
||||||
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
||||||
|
let closed = try #require(try await store.closeCurrentSession())
|
||||||
|
|
||||||
|
#expect(sent.pdfFileName == "Redline-20261011-120000.pdf")
|
||||||
|
#expect(closed.pdfFileName == nil)
|
||||||
|
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.map(\.id) == [closed.id, sent.id]) // newest first
|
||||||
|
#expect(past.map(\.pdfFileName) == [nil, "Redline-20261011-120000.pdf"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 4. retention keeps the newest 10 sessions, in the one archive folder
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
var closedIDs: [UUID] = []
|
||||||
|
for index in 0..<12 {
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 4, height: 4, red: 0.1, green: 0.1, blue: 0.1),
|
||||||
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
|
||||||
|
capturedAt: Date(timeIntervalSince1970: 1_700_000_000 + Double(index)))
|
||||||
|
let closed = try #require(try await store.closeCurrentSession())
|
||||||
|
closedIDs.append(closed.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// All 12 sessions live in the single archive/ folder as UUID session folders.
|
||||||
|
let fm = FileManager.default
|
||||||
|
let entries = try fm.contentsOfDirectory(at: paths.archive, includingPropertiesForKeys: nil)
|
||||||
|
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
|
||||||
|
#expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
|
||||||
|
let kept = try await store.archivedSessions().map(\.id)
|
||||||
|
#expect(kept == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
||||||
|
|
||||||
|
// The two oldest sessions are gone; the newest ten are fully on disk.
|
||||||
|
for id in closedIDs.prefix(2) {
|
||||||
|
#expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path))
|
||||||
|
}
|
||||||
|
for id in closedIDs.suffix(SpoolStore.defaultRetainedSessionCount) {
|
||||||
|
#expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The open session is never touched by retention.
|
||||||
|
let open = try await store.currentSession()
|
||||||
|
#expect(open.state == .open)
|
||||||
|
#expect(open.isEmpty)
|
||||||
|
#expect(fm.fileExists(atPath: paths.sessionDirectory(open.id).path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 5. explicit prune keeps exactly the requested count
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func pruneArchivedSessionsKeepingNRemovesExactlyTheOldest() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
var closedIDs: [UUID] = []
|
||||||
|
for _ in 0..<4 {
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 4, height: 4, red: 0.2, green: 0.2, blue: 0.2),
|
||||||
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date())
|
||||||
|
closedIDs.append(try #require(try await store.closeCurrentSession()).id)
|
||||||
|
}
|
||||||
|
|
||||||
|
let removed = try await store.pruneArchivedSessions(keeping: 2)
|
||||||
|
#expect(removed == Array(closedIDs.prefix(2).reversed())) // newest-first walk order
|
||||||
|
let kept = try await store.archivedSessions().map(\.id)
|
||||||
|
#expect(kept == Array(closedIDs.suffix(2).reversed()))
|
||||||
|
|
||||||
|
// Idempotent: nothing left to prune at that limit.
|
||||||
|
let removedAgain = try await store.pruneArchivedSessions(keeping: 2)
|
||||||
|
#expect(removedAgain.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 6. retention runs on the send path too
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func theSendArchivePathAppliesRetention() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
var sentIDs: [UUID] = []
|
||||||
|
for index in 0..<(SpoolStore.defaultRetainedSessionCount + 3) {
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 4, height: 4, red: 0.3, green: 0.3, blue: 0.3),
|
||||||
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
|
||||||
|
capturedAt: Date(timeIntervalSince1970: 1_700_100_000 + Double(index)))
|
||||||
|
let archived = try await store.archiveCurrent(pdfFileName: "Redline-\(index).pdf")
|
||||||
|
sentIDs.append(archived.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
let kept = try await store.archivedSessions()
|
||||||
|
#expect(kept.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
#expect(kept.map(\.id) == Array(sentIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
||||||
|
#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 {
|
||||||
|
case pngGenerationFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeIsolatedPaths() throws -> (root: URL, paths: AppSupportPaths) {
|
||||||
|
let root = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-retention-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
let paths = try AppSupportPaths(
|
||||||
|
root: root,
|
||||||
|
outbox: root.appendingPathComponent("outbox", isDirectory: true),
|
||||||
|
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
|
||||||
|
)
|
||||||
|
return (root, paths)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makePNGData(
|
||||||
|
width: Int,
|
||||||
|
height: Int,
|
||||||
|
red: CGFloat,
|
||||||
|
green: CGFloat,
|
||||||
|
blue: CGFloat
|
||||||
|
) throws -> Data {
|
||||||
|
let colorSpace = CGColorSpaceCreateDeviceRGB()
|
||||||
|
guard let context = CGContext(
|
||||||
|
data: nil,
|
||||||
|
width: width,
|
||||||
|
height: height,
|
||||||
|
bitsPerComponent: 8,
|
||||||
|
bytesPerRow: width * 4,
|
||||||
|
space: colorSpace,
|
||||||
|
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
|
||||||
|
) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
context.setFillColor(red: red, green: green, blue: blue, alpha: 1)
|
||||||
|
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
|
||||||
|
guard let image = context.makeImage() else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
let data = NSMutableData()
|
||||||
|
guard let destination = CGImageDestinationCreateWithData(
|
||||||
|
data, "public.png" as CFString, 1, nil
|
||||||
|
) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
CGImageDestinationAddImage(destination, image, nil)
|
||||||
|
guard CGImageDestinationFinalize(destination) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
return data as Data
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
import AppKit
|
||||||
|
import CoreGraphics
|
||||||
|
import Foundation
|
||||||
|
import ImageIO
|
||||||
|
import Testing
|
||||||
|
import ShotdeckCore
|
||||||
|
@testable import Shotdeck
|
||||||
|
|
||||||
|
/// MMDB-2925, through the REAL app-target seams the menu rows invoke (`AppModel`
|
||||||
|
/// actions + `SpoolStore`): "Start new session" keeps the current screenshots as a
|
||||||
|
/// past session, the Past submissions state reflects what was sent, and session
|
||||||
|
/// retention keeps the newest 10 sessions in the one archive folder. `bootstrap()`
|
||||||
|
/// itself is covered by LaunchWiringTests; here `addCapture` refreshes the session
|
||||||
|
/// from the store exactly the way `AppModel.captureNow()` does after a real capture.
|
||||||
|
@MainActor
|
||||||
|
@Test("Menu actions: start new session keeps captures, lists past submissions, retains 10")
|
||||||
|
func startNewSessionKeepsCapturesListsPastSubmissionsAndRetainsTen() 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)
|
||||||
|
|
||||||
|
// Two captures in the open session, then the menu's "Start new session".
|
||||||
|
let c1 = try await addCapture(to: model, red: 1, green: 0, blue: 0)
|
||||||
|
let c2 = try await addCapture(to: model, red: 0, green: 1, blue: 0)
|
||||||
|
let closedID = model.session.id
|
||||||
|
#expect(model.canStartNewSession)
|
||||||
|
|
||||||
|
await model.startNewSession()
|
||||||
|
|
||||||
|
// The fresh session is active and the captures are kept as a past session.
|
||||||
|
#expect(model.session.id != closedID)
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
#expect(!model.canStartNewSession)
|
||||||
|
#expect(model.pastSessions.map(\.id) == [closedID])
|
||||||
|
#expect(model.pastSessions.first?.captures.map(\.id) == [c1.id, c2.id])
|
||||||
|
#expect(model.pastSessions.first?.pdfFileName == nil) // never sent
|
||||||
|
#expect(model.statusLine?.contains("kept as a past session") == true)
|
||||||
|
|
||||||
|
// Nothing was deleted on close: both PNGs live in the single archive folder.
|
||||||
|
let archiveDir = model.paths.archiveDirectory(closedID)
|
||||||
|
for capture in [c1, c2] {
|
||||||
|
#expect(fm.fileExists(atPath: archiveDir.appendingPathComponent(capture.fileName).path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// "PDF" on a never-sent row: visible missing state, no silent substitute.
|
||||||
|
#expect(model.sentPDFURL(for: model.pastSessions[0]) == nil)
|
||||||
|
model.revealSentPDF(model.pastSessions[0])
|
||||||
|
#expect(model.statusLine == "That session was never sent.")
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("Retention: 12 sessions through the menu action leave the newest 10 on disk")
|
||||||
|
func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() 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)
|
||||||
|
|
||||||
|
var closedIDs: [UUID] = []
|
||||||
|
for _ in 0..<12 {
|
||||||
|
_ = try await addCapture(to: model, red: 0.2, green: 0.2, blue: 0.2)
|
||||||
|
closedIDs.append(model.session.id)
|
||||||
|
await model.startNewSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
#expect(model.pastSessions.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
#expect(model.pastSessions.map(\.id)
|
||||||
|
== Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
||||||
|
|
||||||
|
let entries = try fm.contentsOfDirectory(at: model.paths.archive, includingPropertiesForKeys: nil)
|
||||||
|
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
|
||||||
|
#expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
for id in closedIDs.prefix(2) {
|
||||||
|
#expect(!fm.fileExists(atPath: model.paths.archiveDirectory(id).path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("Menu action on an empty session reports it started without inventing a past session")
|
||||||
|
func startNewSessionOnEmptySessionCreatesNoPastSession() 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)
|
||||||
|
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
await model.startNewSession()
|
||||||
|
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
#expect(model.pastSessions.isEmpty)
|
||||||
|
#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", sentSummary: "Sent — 1 page.")
|
||||||
|
|
||||||
|
#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])
|
||||||
|
}
|
||||||
|
|
||||||
|
@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
|
||||||
|
/// it — the same refresh `AppModel.captureNow()` performs after a real capture.
|
||||||
|
@MainActor
|
||||||
|
private func addCapture(
|
||||||
|
to model: AppModel,
|
||||||
|
red: CGFloat,
|
||||||
|
green: CGFloat,
|
||||||
|
blue: CGFloat
|
||||||
|
) async throws -> Capture {
|
||||||
|
let capture = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 8, height: 8, red: red, green: green, blue: blue),
|
||||||
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
||||||
|
model.replaceSession(try await model.spool.currentSession())
|
||||||
|
return capture
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum FixtureError: Error {
|
||||||
|
case pngGenerationFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makePNGData(
|
||||||
|
width: Int,
|
||||||
|
height: Int,
|
||||||
|
red: CGFloat,
|
||||||
|
green: CGFloat,
|
||||||
|
blue: CGFloat
|
||||||
|
) throws -> Data {
|
||||||
|
let colorSpace = CGColorSpaceCreateDeviceRGB()
|
||||||
|
guard let context = CGContext(
|
||||||
|
data: nil,
|
||||||
|
width: width,
|
||||||
|
height: height,
|
||||||
|
bitsPerComponent: 8,
|
||||||
|
bytesPerRow: width * 4,
|
||||||
|
space: colorSpace,
|
||||||
|
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
|
||||||
|
) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
context.setFillColor(red: red, green: green, blue: blue, alpha: 1)
|
||||||
|
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
|
||||||
|
guard let image = context.makeImage() else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
let buffer = NSMutableData()
|
||||||
|
guard let destination = CGImageDestinationCreateWithData(buffer, "public.png" as CFString, 1, nil) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
CGImageDestinationAddImage(destination, image, nil)
|
||||||
|
guard CGImageDestinationFinalize(destination) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
return buffer as Data
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user