feat(sessions): keep every session, record review details, name and stamp the PDF
Sessions are now the unit of the product instead of an implicit capture run. - Nothing is deleted by default: the fixed 10-session cap is gone. An age limit (Never / 7 / 14 / 30 / 90 / 180 / 365 days) is chosen in Settings > Sessions and applied on launch, after archiving, and by "Clean up now". Sent PDFs are never touched. - Each session carries review details: lane, deployed version, commit, reviewer (pre-filled with the Mac user) and a free note. They persist in session.json and are inherited by the next session, so a review run is typed once. - PDF file names are Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf, and every page carries a two-line reference footer (tool, build time, session / lane, deployed build, commit, reviewer, note). The PDF document info carries the same values in Author and Keywords. - Verification: 159 tests, a headless panel self-test, and a LaunchServices-driven end-to-end run that types and clicks the real panel.
This commit is contained in:
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
public enum SessionState: String, Codable, Sendable {
|
||||
case open // accepting captures
|
||||
case archived // closed and kept as a past session (sent or not); pruned by retention
|
||||
case archived // closed and kept as a past session (sent or not); pruned only by an age policy the user set
|
||||
}
|
||||
|
||||
/// The manifest persisted as session.json alongside the PNGs.
|
||||
@@ -12,28 +12,39 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
||||
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. nil on a
|
||||
/// session that was closed without ever sending — the Past submissions list
|
||||
/// session that was closed without ever sending — the Past sessions list
|
||||
/// shows that as "Not sent".
|
||||
public private(set) var pdfFileName: String?
|
||||
/// Lane / deployed build / commit / reviewer / note for this session. Absent from
|
||||
/// manifests written before v0.5.0 — those decode as `.empty`, never a guess.
|
||||
public private(set) var context: ReviewContext
|
||||
|
||||
public init(
|
||||
id: UUID,
|
||||
createdAt: Date,
|
||||
state: SessionState,
|
||||
captures: [Capture],
|
||||
pdfFileName: String?
|
||||
pdfFileName: String?,
|
||||
context: ReviewContext = .empty
|
||||
) {
|
||||
self.id = id
|
||||
self.createdAt = createdAt
|
||||
self.state = state
|
||||
self.captures = captures
|
||||
self.pdfFileName = pdfFileName
|
||||
self.context = context
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
captures.isEmpty
|
||||
}
|
||||
|
||||
/// First 8 characters of the UUID, uppercase — the stable short handle used in
|
||||
/// file names, the session list and the PDF header.
|
||||
public var shortID: String {
|
||||
String(id.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)).uppercased()
|
||||
}
|
||||
|
||||
/// max(sequence)+1, or 1 when empty.
|
||||
public var nextSequence: Int {
|
||||
(captures.map(\.sequence).max() ?? 0) + 1
|
||||
@@ -46,7 +57,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
||||
createdAt: createdAt,
|
||||
state: state,
|
||||
captures: captures + [capture],
|
||||
pdfFileName: pdfFileName
|
||||
pdfFileName: pdfFileName,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
@@ -58,7 +70,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
||||
createdAt: createdAt,
|
||||
state: state,
|
||||
captures: captures.filter { $0.id != captureID },
|
||||
pdfFileName: pdfFileName
|
||||
pdfFileName: pdfFileName,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
@@ -70,7 +83,50 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
||||
createdAt: createdAt,
|
||||
state: .archived,
|
||||
captures: captures,
|
||||
pdfFileName: pdfFileName
|
||||
pdfFileName: pdfFileName,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
||||
public func withContext(_ newContext: ReviewContext) -> CaptureSession {
|
||||
CaptureSession(
|
||||
id: id,
|
||||
createdAt: createdAt,
|
||||
state: state,
|
||||
captures: captures,
|
||||
pdfFileName: pdfFileName,
|
||||
context: newContext
|
||||
)
|
||||
}
|
||||
|
||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
||||
public func withPDFFileName(_ name: String?) -> CaptureSession {
|
||||
CaptureSession(
|
||||
id: id,
|
||||
createdAt: createdAt,
|
||||
state: state,
|
||||
captures: captures,
|
||||
pdfFileName: name,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id, createdAt, state, captures, pdfFileName, context
|
||||
}
|
||||
|
||||
/// `context` is decoded leniently so every manifest written before v0.5.0 keeps
|
||||
/// loading; all other keys are required, exactly as before.
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.init(
|
||||
id: try container.decode(UUID.self, forKey: .id),
|
||||
createdAt: try container.decode(Date.self, forKey: .createdAt),
|
||||
state: try container.decode(SessionState.self, forKey: .state),
|
||||
captures: try container.decode([Capture].self, forKey: .captures),
|
||||
pdfFileName: try container.decodeIfPresent(String.self, forKey: .pdfFileName),
|
||||
context: try container.decodeIfPresent(ReviewContext.self, forKey: .context) ?? .empty
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import Foundation
|
||||
|
||||
/// What a review session is ABOUT, recorded once per session and printed on every
|
||||
/// PDF page plus the PDF's document info, so an annotated page that comes back
|
||||
/// weeks later still says which lane, build and commit it referred to, who took it
|
||||
/// and when.
|
||||
///
|
||||
/// Every field is optional in practice (empty string = not recorded); nothing here
|
||||
/// is invented when the user leaves it blank. `note` is free text.
|
||||
public struct ReviewContext: Codable, Sendable, Equatable {
|
||||
/// Hard cap per field: this text ends up on every PDF page, so an unbounded
|
||||
/// paste must not be able to break the layout.
|
||||
public static let maxFieldLength = 120
|
||||
|
||||
public var lane: String
|
||||
public var deployedVersion: String
|
||||
public var commit: String
|
||||
public var reviewer: String
|
||||
public var note: String
|
||||
|
||||
public init(
|
||||
lane: String = "",
|
||||
deployedVersion: String = "",
|
||||
commit: String = "",
|
||||
reviewer: String = "",
|
||||
note: String = ""
|
||||
) {
|
||||
self.lane = Self.cleaned(lane)
|
||||
self.deployedVersion = Self.cleaned(deployedVersion)
|
||||
self.commit = Self.cleaned(commit)
|
||||
self.reviewer = Self.cleaned(reviewer)
|
||||
self.note = Self.cleaned(note)
|
||||
}
|
||||
|
||||
public static let empty = ReviewContext()
|
||||
|
||||
/// The macOS account's own name, used to pre-fill `reviewer` on a fresh session.
|
||||
/// `NSFullUserName()` is empty on a host with no full name set, in which case the
|
||||
/// short login name identifies the same person.
|
||||
public static func currentUser() -> String {
|
||||
let full = NSFullUserName().trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !full.isEmpty { return cleaned(full) }
|
||||
return cleaned(NSUserName())
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
lane.isEmpty && deployedVersion.isEmpty && commit.isEmpty && reviewer.isEmpty && note.isEmpty
|
||||
}
|
||||
|
||||
/// "DEV03 · v1.4.2 · a1b2c3d · Ben Hippler" — empty parts are dropped, never
|
||||
/// replaced with a placeholder.
|
||||
public var summaryLine: String {
|
||||
summaryParts.joined(separator: " · ")
|
||||
}
|
||||
|
||||
/// The individual summary parts in display order, empty ones dropped.
|
||||
public var summaryParts: [String] {
|
||||
var parts: [String] = []
|
||||
if !lane.isEmpty { parts.append(lane) }
|
||||
if !deployedVersion.isEmpty { parts.append(deployedVersion) }
|
||||
if !commit.isEmpty { parts.append(commit) }
|
||||
if !reviewer.isEmpty { parts.append(reviewer) }
|
||||
return parts
|
||||
}
|
||||
|
||||
/// JSON kept tolerant on purpose: an older manifest has no context at all, and a
|
||||
/// newer one may add fields. Any unknown key is ignored; every known field is
|
||||
/// optional.
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.init(
|
||||
lane: try container.decodeIfPresent(String.self, forKey: .lane) ?? "",
|
||||
deployedVersion: try container.decodeIfPresent(String.self, forKey: .deployedVersion) ?? "",
|
||||
commit: try container.decodeIfPresent(String.self, forKey: .commit) ?? "",
|
||||
reviewer: try container.decodeIfPresent(String.self, forKey: .reviewer) ?? "",
|
||||
note: try container.decodeIfPresent(String.self, forKey: .note) ?? ""
|
||||
)
|
||||
}
|
||||
|
||||
/// Trims, collapses line breaks (the value is drawn on one line) and caps length.
|
||||
static func cleaned(_ raw: String) -> String {
|
||||
let collapsed = raw
|
||||
.replacingOccurrences(of: "\r\n", with: " ")
|
||||
.replacingOccurrences(of: "\n", with: " ")
|
||||
.replacingOccurrences(of: "\r", with: " ")
|
||||
.trimmingCharacters(in: .whitespaces)
|
||||
guard collapsed.count > maxFieldLength else { return collapsed }
|
||||
return String(collapsed.prefix(maxFieldLength))
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,17 @@ private let pdfLog = Logger(subsystem: "ai.flowmaster.shotdeck", category: "PDF"
|
||||
public struct PDFComposer: Sendable {
|
||||
public init() {}
|
||||
|
||||
/// `toolVersion` is the running Redline version (CFBundleShortVersionString) and
|
||||
/// `composedAt` the build time; both are printed in the page footer and the PDF's
|
||||
/// document info so a printed or returned page says which tools produced it.
|
||||
@discardableResult
|
||||
public func compose(
|
||||
session: CaptureSession,
|
||||
imageURL: (Capture) -> URL,
|
||||
title: String,
|
||||
to outputURL: URL
|
||||
to outputURL: URL,
|
||||
toolVersion: String = "",
|
||||
composedAt: Date = Date()
|
||||
) throws -> Int {
|
||||
if session.isEmpty {
|
||||
throw ShotdeckError.pdfCompositionFailed(reason: "session has no captures")
|
||||
@@ -43,12 +48,18 @@ public struct PDFComposer: Sendable {
|
||||
.deletingLastPathComponent()
|
||||
.appendingPathComponent(".tmp-\(UUID().uuidString)-\(outputURL.lastPathComponent)")
|
||||
|
||||
let footerLines = Self.footerLines(
|
||||
session: session, toolVersion: toolVersion, composedAt: composedAt)
|
||||
|
||||
do {
|
||||
try Self.writePDF(
|
||||
loaded: loaded,
|
||||
pageCount: pageCount,
|
||||
title: title,
|
||||
sessionID: session.id,
|
||||
footerLines: footerLines,
|
||||
metadata: Self.documentInfo(
|
||||
session: session, title: title, toolVersion: toolVersion, composedAt: composedAt),
|
||||
to: tmpURL
|
||||
)
|
||||
|
||||
@@ -70,8 +81,72 @@ public struct PDFComposer: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
public static func fileName(for _: CaptureSession) -> String {
|
||||
"Redline-\(DubaiTime.fileStamp(Date())).pdf"
|
||||
/// `Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf` — see `PDFFileName`.
|
||||
public static func fileName(for session: CaptureSession) -> String {
|
||||
PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id)
|
||||
}
|
||||
|
||||
/// Both footer lines for a session, untruncated. Line 1 identifies the document
|
||||
/// (tool, build time, session); line 2 states what it reviewed (lane, deployed
|
||||
/// build, commit, reviewer, note). Empty context fields are omitted rather than
|
||||
/// printed as blanks.
|
||||
public static func footerLines(
|
||||
session: CaptureSession,
|
||||
toolVersion: String,
|
||||
composedAt: Date
|
||||
) -> [String] {
|
||||
let tool = toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)"
|
||||
let first = "\(tool) · \(DubaiTime.stamp(composedAt)) · Session \(session.shortID)"
|
||||
|
||||
let context = session.context
|
||||
var review: [String] = []
|
||||
if !context.lane.isEmpty { review.append("Lane \(context.lane)") }
|
||||
if !context.deployedVersion.isEmpty { review.append("Deployed \(context.deployedVersion)") }
|
||||
if !context.commit.isEmpty { review.append("Commit \(context.commit)") }
|
||||
if !context.reviewer.isEmpty { review.append("Reviewer \(context.reviewer)") }
|
||||
if !context.note.isEmpty { review.append("Note \(context.note)") }
|
||||
return review.isEmpty ? [first] : [first, review.joined(separator: " · ")]
|
||||
}
|
||||
|
||||
/// The PDF document info a reader sees in Preview/Acrobat. The subject stays the
|
||||
/// session UUID (it is the stable machine handle); everything a person needs to
|
||||
/// identify the review is in Author/Keywords as well as the page footers.
|
||||
public static func documentInfo(
|
||||
session: CaptureSession,
|
||||
title: String,
|
||||
toolVersion: String,
|
||||
composedAt: Date
|
||||
) -> [String: Any] {
|
||||
let context = session.context
|
||||
// Commas separate keywords in the PDF format itself, so a value containing one
|
||||
// would silently split into two keywords (and PDF readers return a list
|
||||
// instead of a string). Strip them from every keyword value.
|
||||
func keywordValue(_ raw: String) -> String {
|
||||
raw.replacingOccurrences(of: ",", with: " ")
|
||||
.split(whereSeparator: \.isWhitespace)
|
||||
.joined(separator: " ")
|
||||
}
|
||||
var keywords: [String] = ["Redline", "session=\(session.shortID)"]
|
||||
if !context.lane.isEmpty { keywords.append("lane=\(keywordValue(context.lane))") }
|
||||
if !context.deployedVersion.isEmpty {
|
||||
keywords.append("deployed=\(keywordValue(context.deployedVersion))")
|
||||
}
|
||||
if !context.commit.isEmpty { keywords.append("commit=\(keywordValue(context.commit))") }
|
||||
if !context.reviewer.isEmpty { keywords.append("reviewer=\(keywordValue(context.reviewer))") }
|
||||
if !context.note.isEmpty { keywords.append("note=\(keywordValue(context.note))") }
|
||||
keywords.append("built=\(DubaiTime.keywordStamp(composedAt))")
|
||||
if !toolVersion.isEmpty { keywords.append("tool=\(toolVersion)") }
|
||||
|
||||
var info: [String: Any] = [
|
||||
kCGPDFContextCreator as String: toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)",
|
||||
kCGPDFContextTitle as String: title,
|
||||
kCGPDFContextSubject as String: session.id.uuidString.lowercased(),
|
||||
kCGPDFContextKeywords as String: keywords.joined(separator: "; "),
|
||||
]
|
||||
if !context.reviewer.isEmpty {
|
||||
info[kCGPDFContextAuthor as String] = context.reviewer
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
private static func writePDF(
|
||||
@@ -79,17 +154,15 @@ public struct PDFComposer: Sendable {
|
||||
pageCount: Int,
|
||||
title: String,
|
||||
sessionID: UUID,
|
||||
footerLines: [String],
|
||||
metadata: [String: Any],
|
||||
to tmpURL: URL
|
||||
) throws {
|
||||
guard let consumer = CGDataConsumer(url: tmpURL as CFURL) else {
|
||||
throw ShotdeckError.pdfCompositionFailed(reason: "cannot open output location")
|
||||
}
|
||||
|
||||
let auxiliaryInfo: [String: Any] = [
|
||||
kCGPDFContextCreator as String: "Redline",
|
||||
kCGPDFContextTitle as String: title,
|
||||
kCGPDFContextSubject as String: sessionID.uuidString.lowercased(),
|
||||
]
|
||||
let auxiliaryInfo = metadata
|
||||
|
||||
guard let context = CGContext(
|
||||
consumer: consumer,
|
||||
@@ -105,7 +178,9 @@ public struct PDFComposer: Sendable {
|
||||
|
||||
for pageIndex in 1...pageCount {
|
||||
let (capture, cgImage) = loaded[pageIndex - 1]
|
||||
let layout = PageLayout(capture: capture, pageIndex: pageIndex, pageCount: pageCount)
|
||||
let layout = PageLayout(
|
||||
capture: capture, pageIndex: pageIndex, pageCount: pageCount,
|
||||
footerLines: footerLines)
|
||||
|
||||
context.beginPDFPage(Self.pageInfo(mediaBox: layout.pageRect))
|
||||
|
||||
@@ -149,6 +224,17 @@ public struct PDFComposer: Sendable {
|
||||
strokeTickBox(layout.passTickBox, in: context, color: black)
|
||||
strokeTickBox(layout.failTickBox, in: context, color: black)
|
||||
|
||||
for (line, origin) in zip(layout.footerLines, layout.footerOrigins) {
|
||||
drawTruncatedText(
|
||||
line,
|
||||
font: layout.footerFont,
|
||||
color: timestampColor,
|
||||
at: origin,
|
||||
maxWidth: layout.footerRect.width,
|
||||
in: context
|
||||
)
|
||||
}
|
||||
|
||||
context.endPDFPage()
|
||||
}
|
||||
|
||||
@@ -185,6 +271,40 @@ public struct PDFComposer: Sendable {
|
||||
CTLineDraw(line, context)
|
||||
}
|
||||
|
||||
/// Draws one footer line, truncated with an ellipsis when it is wider than the
|
||||
/// page content width — the reference block must never run into the page edge.
|
||||
private static func drawTruncatedText(
|
||||
_ string: String,
|
||||
font: NSFont,
|
||||
color: CGColor,
|
||||
at origin: CGPoint,
|
||||
maxWidth: CGFloat,
|
||||
in context: CGContext
|
||||
) {
|
||||
let attributes: [CFString: Any] = [
|
||||
kCTFontAttributeName: font,
|
||||
kCTForegroundColorAttributeName: color,
|
||||
]
|
||||
guard let attributed = CFAttributedStringCreate(
|
||||
nil, string as CFString, attributes as CFDictionary)
|
||||
else { return }
|
||||
var line = CTLineCreateWithAttributedString(attributed)
|
||||
if CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) > maxWidth,
|
||||
let ellipsisAttributed = CFAttributedStringCreate(
|
||||
nil, "…" as CFString, attributes as CFDictionary)
|
||||
{
|
||||
let ellipsis = CTLineCreateWithAttributedString(ellipsisAttributed)
|
||||
if let truncated = CTLineCreateTruncatedLine(
|
||||
line, Double(maxWidth), .end, ellipsis)
|
||||
{
|
||||
line = truncated
|
||||
}
|
||||
}
|
||||
context.textMatrix = .identity
|
||||
context.textPosition = origin
|
||||
CTLineDraw(line, context)
|
||||
}
|
||||
|
||||
private static func strokeTickBox(_ box: CGRect, in context: CGContext, color: CGColor) {
|
||||
let path = CGPath(
|
||||
roundedRect: box,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import Foundation
|
||||
|
||||
/// The PDF file-name scheme:
|
||||
///
|
||||
/// Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf
|
||||
/// Redline-<yyyyMMdd-HHmm>-<SHORTID>.pdf (no lane recorded)
|
||||
///
|
||||
/// * `yyyyMMdd-HHmm` is Dubai wall-clock time (the time the PDF was built) — the
|
||||
/// file sorts chronologically as plain text on every filesystem.
|
||||
/// * `LANE` is the upper-cased lane/environment, reduced to A–Z, 0–9 and single
|
||||
/// dashes ("OMS test lane" → "OMS-TEST-LANE") so the name is safe everywhere.
|
||||
/// * `SHORTID` is the session's 8-character id, which keeps two lanes in the same
|
||||
/// minute — and a re-send of the same session — distinguishable and unique.
|
||||
public enum PDFFileName {
|
||||
/// Lane token length cap so the whole name stays comfortably short.
|
||||
public static let laneMaxLength = 24
|
||||
|
||||
public static func laneSlug(_ lane: String) -> String {
|
||||
var slug = ""
|
||||
var pendingDash = false
|
||||
for character in lane.uppercased() {
|
||||
if character.isASCII, character.isLetter || character.isNumber {
|
||||
if pendingDash, !slug.isEmpty { slug.append("-") }
|
||||
slug.append(character)
|
||||
pendingDash = false
|
||||
} else {
|
||||
pendingDash = true
|
||||
}
|
||||
}
|
||||
let capped = String(slug.prefix(laneMaxLength))
|
||||
return capped.hasSuffix("-") ? String(capped.dropLast()) : capped
|
||||
}
|
||||
|
||||
public static func make(builtAt: Date, lane: String, sessionID: UUID) -> String {
|
||||
let shortID = String(
|
||||
sessionID.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)
|
||||
).uppercased()
|
||||
let slug = laneSlug(lane)
|
||||
var parts = ["Redline", DubaiTime.fileMinuteStamp(builtAt)]
|
||||
if !slug.isEmpty { parts.append(slug) }
|
||||
parts.append(shortID)
|
||||
return parts.joined(separator: "-") + ".pdf"
|
||||
}
|
||||
|
||||
/// The session folder's own readable label, e.g. "DEV03-4F2A9C1D" — used in the
|
||||
/// UI only; the on-disk folder name stays the session UUID.
|
||||
public static func sessionLabel(lane: String, sessionID: UUID) -> String {
|
||||
let shortID = String(
|
||||
sessionID.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)
|
||||
).uppercased()
|
||||
let slug = laneSlug(lane)
|
||||
return slug.isEmpty ? shortID : "\(slug)-\(shortID)"
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,12 @@ public struct PageLayout: Sendable, Equatable {
|
||||
public let timestampText: String
|
||||
public let timestampOrigin: CGPoint
|
||||
|
||||
/// Reference block under the image (up to two lines): who, when, which lane,
|
||||
/// which deployed build and commit. Empty when the caller passes no lines.
|
||||
public let footerRect: CGRect
|
||||
public let footerLines: [String]
|
||||
public let footerOrigins: [CGPoint]
|
||||
|
||||
public let passLabelOrigin: CGPoint
|
||||
public let failLabelOrigin: CGPoint
|
||||
public let passTickBox: CGRect
|
||||
@@ -25,10 +31,13 @@ public struct PageLayout: Sendable, Equatable {
|
||||
public var pageNumberFont: NSFont { NSFont.systemFont(ofSize: 9, weight: .semibold) }
|
||||
public var timestampFont: NSFont { NSFont.systemFont(ofSize: 9, weight: .regular) }
|
||||
public var tickLabelFont: NSFont { NSFont.systemFont(ofSize: 8, weight: .semibold) }
|
||||
public var footerFont: NSFont { NSFont.systemFont(ofSize: 7.5, weight: .regular) }
|
||||
|
||||
private static let marginAll: CGFloat = 18
|
||||
private static let headerHeight: CGFloat = 26
|
||||
private static let headerImageGap: CGFloat = 10
|
||||
private static let footerLineHeight: CGFloat = 9.5
|
||||
private static let footerImageGap: CGFloat = 7
|
||||
private static let tickBoxSize: CGFloat = 13
|
||||
private static let tickGroupGap: CGFloat = 8
|
||||
private static let portraitPage = CGSize(width: 595, height: 842)
|
||||
@@ -36,10 +45,13 @@ public struct PageLayout: Sendable, Equatable {
|
||||
|
||||
/// `pageIndex` and `pageCount` are 1-based / total, over ACTUALLY-WRITTEN pages
|
||||
/// (see SPEC decision D-D), not `capture.sequence` / `session.captures.count`.
|
||||
public init(capture: Capture, pageIndex: Int, pageCount: Int) {
|
||||
/// `footerLines` is the pre-truncated reference block; an empty array keeps the
|
||||
/// image area exactly as it was before the footer existed.
|
||||
public init(capture: Capture, pageIndex: Int, pageCount: Int, footerLines: [String] = []) {
|
||||
let pageNumberFont = NSFont.systemFont(ofSize: 9, weight: .semibold)
|
||||
let timestampFont = NSFont.systemFont(ofSize: 9, weight: .regular)
|
||||
let tickLabelFont = NSFont.systemFont(ofSize: 8, weight: .semibold)
|
||||
let footerLabelFont = NSFont.systemFont(ofSize: 7.5, weight: .regular)
|
||||
|
||||
isLandscape = capture.isLandscape
|
||||
pageRect = CGRect(origin: .zero, size: isLandscape ? Self.landscapePage : Self.portraitPage)
|
||||
@@ -59,11 +71,23 @@ public struct PageLayout: Sendable, Equatable {
|
||||
height: Self.headerHeight
|
||||
)
|
||||
|
||||
imageBoxRect = CGRect(
|
||||
self.footerLines = footerLines
|
||||
let footerHeight = footerLines.isEmpty
|
||||
? 0
|
||||
: CGFloat(footerLines.count) * Self.footerLineHeight
|
||||
footerRect = CGRect(
|
||||
x: contentMinX,
|
||||
y: contentMinY,
|
||||
width: contentWidth,
|
||||
height: headerRect.minY - Self.headerImageGap - contentMinY
|
||||
height: footerHeight
|
||||
)
|
||||
let imageBoxMinY = contentMinY + (footerLines.isEmpty ? 0 : footerHeight + Self.footerImageGap)
|
||||
|
||||
imageBoxRect = CGRect(
|
||||
x: contentMinX,
|
||||
y: imageBoxMinY,
|
||||
width: contentWidth,
|
||||
height: headerRect.minY - Self.headerImageGap - imageBoxMinY
|
||||
)
|
||||
|
||||
let pointSize = CGSize(
|
||||
@@ -91,6 +115,22 @@ public struct PageLayout: Sendable, Equatable {
|
||||
let descent = CTFontGetDescent(metricsFont)
|
||||
let baselineY = headerRect.minY + (headerRect.height - (ascent + descent)) / 2 + descent
|
||||
|
||||
// Footer baselines, top line first, using the footer font's own descent.
|
||||
let footerMetrics = footerLabelFont as CTFont
|
||||
let footerAscent = CTFontGetAscent(footerMetrics)
|
||||
let footerDescent = CTFontGetDescent(footerMetrics)
|
||||
let footerLeading = Self.footerLineHeight
|
||||
var origins: [CGPoint] = []
|
||||
origins.reserveCapacity(footerLines.count)
|
||||
for index in footerLines.indices {
|
||||
let lineBottom = footerRect.maxY - CGFloat(index + 1) * footerLeading
|
||||
origins.append(CGPoint(
|
||||
x: footerRect.minX,
|
||||
y: lineBottom + max(0, (footerLeading - (footerAscent + footerDescent)) / 2) + footerDescent
|
||||
))
|
||||
}
|
||||
footerOrigins = origins
|
||||
|
||||
pageNumberText = "\(pageIndex) / \(pageCount)"
|
||||
pageNumberOrigin = CGPoint(x: headerRect.minX, y: baselineY)
|
||||
|
||||
@@ -135,6 +175,9 @@ public struct PageLayout: Sendable, Equatable {
|
||||
&& lhs.pageNumberOrigin == rhs.pageNumberOrigin
|
||||
&& lhs.timestampText == rhs.timestampText
|
||||
&& lhs.timestampOrigin == rhs.timestampOrigin
|
||||
&& lhs.footerRect == rhs.footerRect
|
||||
&& lhs.footerLines == rhs.footerLines
|
||||
&& lhs.footerOrigins == rhs.footerOrigins
|
||||
&& lhs.passLabelOrigin == rhs.passLabelOrigin
|
||||
&& lhs.failLabelOrigin == rhs.failLabelOrigin
|
||||
&& lhs.passTickBox == rhs.passTickBox
|
||||
|
||||
@@ -4,24 +4,26 @@ 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
|
||||
/// The user's age limit for kept sessions. `.never` (the default) means every
|
||||
/// session is kept: nothing is deleted until an age limit is chosen in Settings.
|
||||
private var retention: SessionRetention
|
||||
|
||||
public init(paths: AppSupportPaths) throws {
|
||||
public init(paths: AppSupportPaths, retention: SessionRetention = .never) throws {
|
||||
self.paths = paths
|
||||
self.retention = retention
|
||||
let fm = FileManager.default
|
||||
try Self.supersedeSpoolArchiveOverlaps(paths: paths, fileManager: fm)
|
||||
try Self.finishInterruptedArchives(paths: paths, fileManager: fm)
|
||||
let remainingIDs = try Self.listUUIDDirectories(in: paths.spool, fileManager: fm)
|
||||
if remainingIDs.isEmpty {
|
||||
self.openSession = try Self.createFreshSession(paths: paths)
|
||||
// A brand-new store: the reviewer is this Mac's user, so a session taken
|
||||
// now records who took it without the user typing anything. Lane, build
|
||||
// and commit stay empty until the user states them.
|
||||
self.openSession = try Self.createFreshSession(
|
||||
paths: paths,
|
||||
context: ReviewContext(reviewer: ReviewContext.currentUser()))
|
||||
} else {
|
||||
var candidates: [CaptureSession] = []
|
||||
for id in remainingIDs {
|
||||
@@ -34,6 +36,31 @@ public actor SpoolStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a new age limit to future archive/launch prunes. Does not delete
|
||||
/// anything itself — a caller that just changed the setting calls
|
||||
/// `pruneExpiredSessions()` when the user asked for a cleanup.
|
||||
public func setRetention(_ value: SessionRetention) {
|
||||
retention = value
|
||||
}
|
||||
|
||||
/// The age limit this store is currently enforcing.
|
||||
public func configuredRetention() -> SessionRetention {
|
||||
retention
|
||||
}
|
||||
|
||||
/// Records the review context (lane / deployed build / commit / reviewer / note)
|
||||
/// on the open session and persists it in the manifest before returning. Fails
|
||||
/// loudly if the manifest cannot be written — the in-memory session is only
|
||||
/// updated after the durable write succeeds.
|
||||
public func setContext(_ context: ReviewContext) throws -> CaptureSession {
|
||||
let open = try ensureOpenSession()
|
||||
let updated = open.withContext(context)
|
||||
try AtomicFile.writeJSON(
|
||||
updated, to: paths.sessionDirectory(open.id).appendingPathComponent("session.json"))
|
||||
openSession = updated
|
||||
return updated
|
||||
}
|
||||
|
||||
/// The session currently accepting captures. Cheap accessor — all reconciliation already
|
||||
/// 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
|
||||
@@ -54,7 +81,7 @@ public actor SpoolStore {
|
||||
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)
|
||||
let fresh = try Self.createFreshSession(paths: paths, context: openSession.context)
|
||||
openSession = fresh
|
||||
return fresh
|
||||
}
|
||||
@@ -86,10 +113,9 @@ 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 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.)
|
||||
/// (The one place that removes files is the age limit the user chose in Settings:
|
||||
/// when a session is older than that limit, its WHOLE folder — including
|
||||
/// `removed/` — is pruned. Nothing is pruned while the limit is "Never".)
|
||||
public func remove(captureID: UUID) throws -> CaptureSession {
|
||||
let open = try ensureOpenSession()
|
||||
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
|
||||
@@ -129,7 +155,7 @@ public actor SpoolStore {
|
||||
underlying: "cannot archive an empty session")
|
||||
}
|
||||
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
|
||||
openSession = try Self.createFreshSession(paths: paths)
|
||||
openSession = try Self.createFreshSession(paths: paths, context: open.context)
|
||||
applyRetention()
|
||||
return archived
|
||||
}
|
||||
@@ -141,31 +167,46 @@ public actor SpoolStore {
|
||||
/// 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.
|
||||
///
|
||||
/// The new session inherits the closed session's review context: one review run
|
||||
/// spans several sessions in the same lane and build, so retyping it each time
|
||||
/// would only add errors.
|
||||
public func closeCurrentSession() throws -> CaptureSession? {
|
||||
let open = try ensureOpenSession()
|
||||
guard !open.isEmpty else {
|
||||
openSession = try Self.createFreshSession(paths: paths)
|
||||
openSession = try Self.createFreshSession(paths: paths, context: open.context)
|
||||
return nil
|
||||
}
|
||||
let archived = try moveOpenSessionToArchive(
|
||||
open.markArchived(pdfFileName: open.pdfFileName))
|
||||
openSession = try Self.createFreshSession(paths: paths)
|
||||
openSession = try Self.createFreshSession(paths: paths, context: open.context)
|
||||
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 [] }
|
||||
/// Removes archived sessions created before the current age limit's cutoff and
|
||||
/// returns their ids. With `.never` this removes nothing and returns `[]`, so
|
||||
/// "keep everything" needs no separate code path. Only UUID session folders
|
||||
/// directly under archive/ are ever touched — never spool/, never a PDF.
|
||||
public func pruneExpiredSessions(now: Date = Date()) throws -> [UUID] {
|
||||
guard let cutoff = retention.cutoff(now: now) else { return [] }
|
||||
return try removeArchivedSessions(createdBefore: cutoff)
|
||||
}
|
||||
|
||||
/// The ids `pruneExpiredSessions()` would remove right now — what Settings shows
|
||||
/// before the user commits to a cleanup. Empty under `.never`.
|
||||
public func expiredSessionIDs(now: Date = Date()) throws -> [UUID] {
|
||||
guard let cutoff = retention.cutoff(now: now) else { return [] }
|
||||
return try archivedSessions().filter { $0.createdAt < cutoff }.map(\.id)
|
||||
}
|
||||
|
||||
/// Deletes the archived session folders created before `cutoff` and returns their
|
||||
/// ids. Only archive/ is scanned, so an open session can never match.
|
||||
private func removeArchivedSessions(createdBefore cutoff: Date) throws -> [UUID] {
|
||||
let expired = try archivedSessions().filter { $0.createdAt < cutoff }
|
||||
guard !expired.isEmpty else { return [] }
|
||||
var removed: [UUID] = []
|
||||
for session in sessions.dropFirst(limit) {
|
||||
for session in expired {
|
||||
let dir = paths.archiveDirectory(session.id)
|
||||
do {
|
||||
try FileManager.default.removeItem(at: dir)
|
||||
@@ -177,26 +218,23 @@ public actor SpoolStore {
|
||||
removed.append(session.id)
|
||||
}
|
||||
try AtomicFile.fsyncDirectory(at: paths.archive)
|
||||
Log.spool.warning(
|
||||
"Session retention (\(self.retention.displayName, privacy: .public)): removed \(removed.count, privacy: .public) archived session(s) older than \(DubaiTime.stamp(cutoff), privacy: .public).")
|
||||
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.
|
||||
/// forgotten. 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 an old session still in the Past sessions 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).")
|
||||
}
|
||||
_ = try pruneExpiredSessions()
|
||||
} catch {
|
||||
Log.spool.error(
|
||||
"Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
|
||||
"Session retention failed — expired sessions were kept: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,7 +262,7 @@ public actor SpoolStore {
|
||||
path: paths.sessionDirectory(open.id).path,
|
||||
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, context: open.context)
|
||||
openSession = fresh
|
||||
return fresh
|
||||
}
|
||||
@@ -389,7 +427,8 @@ public actor SpoolStore {
|
||||
createdAt: session.createdAt,
|
||||
state: session.state,
|
||||
captures: finalCaptures,
|
||||
pdfFileName: session.pdfFileName)
|
||||
pdfFileName: session.pdfFileName,
|
||||
context: session.context)
|
||||
try AtomicFile.writeJSON(updated, to: manifestURL)
|
||||
Log.spool.warning("Reconciled session \(id.uuidString, privacy: .public): dropped \(missingCount) missing PNG(s), recovered \(recoveredOrphans.count) orphan(s).")
|
||||
return updated
|
||||
@@ -474,7 +513,10 @@ public actor SpoolStore {
|
||||
}
|
||||
}
|
||||
|
||||
private static func createFreshSession(paths: AppSupportPaths) throws -> CaptureSession {
|
||||
private static func createFreshSession(
|
||||
paths: AppSupportPaths,
|
||||
context: ReviewContext
|
||||
) throws -> CaptureSession {
|
||||
let id = UUID()
|
||||
let createdAt = Date()
|
||||
let dir = paths.sessionDirectory(id)
|
||||
@@ -483,7 +525,9 @@ public actor SpoolStore {
|
||||
} catch {
|
||||
throw ShotdeckError.spoolWriteFailed(path: dir.path, underlying: error.localizedDescription)
|
||||
}
|
||||
let session = CaptureSession(id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil)
|
||||
let session = CaptureSession(
|
||||
id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil,
|
||||
context: context)
|
||||
try AtomicFile.writeJSON(session, to: dir.appendingPathComponent("session.json"))
|
||||
return session
|
||||
}
|
||||
|
||||
@@ -3,7 +3,11 @@ import Foundation
|
||||
public enum DubaiTime {
|
||||
private static let stampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm 'Dubai'")
|
||||
private static let fileStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmmss")
|
||||
private static let fileMinuteStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmm")
|
||||
private static let checkTimeFormatter = LockedDateFormatter(dateFormat: "HH:mm 'Dubai'")
|
||||
private static let shortStampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm")
|
||||
private static let dayStampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy")
|
||||
private static let keywordStampFormatter = LockedDateFormatter(dateFormat: "yyyy-MM-dd HH:mm 'Dubai'")
|
||||
|
||||
public static func stamp(_ date: Date) -> String {
|
||||
stampFormatter.string(from: date)
|
||||
@@ -13,6 +17,28 @@ public enum DubaiTime {
|
||||
fileStampFormatter.string(from: date)
|
||||
}
|
||||
|
||||
/// `yyyyMMdd-HHmm` — used in PDF file names where minutes are the useful detail.
|
||||
public static func fileMinuteStamp(_ date: Date) -> String {
|
||||
fileMinuteStampFormatter.string(from: date)
|
||||
}
|
||||
|
||||
/// "31 Oct 2026, 10:31" — compact session-list timestamp (the timezone is stated
|
||||
/// once in the list header, not on every row).
|
||||
public static func shortStamp(_ date: Date) -> String {
|
||||
shortStampFormatter.string(from: date)
|
||||
}
|
||||
|
||||
/// "31 Oct 2026" — for day-granular expiry notices.
|
||||
public static func dayStamp(_ date: Date) -> String {
|
||||
dayStampFormatter.string(from: date)
|
||||
}
|
||||
|
||||
/// "2026-10-31 11:00 Dubai" — for PDF keywords, where a comma would be read as a
|
||||
/// keyword separator by the PDF format itself.
|
||||
public static func keywordStamp(_ date: Date) -> String {
|
||||
keywordStampFormatter.string(from: date)
|
||||
}
|
||||
|
||||
public static func checkTime(_ date: Date) -> String {
|
||||
checkTimeFormatter.string(from: date)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import Foundation
|
||||
|
||||
/// How long Redline keeps a past session's captured screenshots.
|
||||
///
|
||||
/// The default is `.never`: every session is saved and nothing is deleted unless the
|
||||
/// user picks an age limit in Settings. Session folders are the only thing an age
|
||||
/// policy ever removes — a PDF that was already sent stays in the folder it went to.
|
||||
public enum SessionRetention: Sendable, Equatable, Hashable {
|
||||
case never
|
||||
case days(Int)
|
||||
|
||||
/// The one list Settings offers, in display order. `nil` day counts never expire.
|
||||
public static let presets: [SessionRetention] = [
|
||||
.never, .days(7), .days(14), .days(30), .days(90), .days(180), .days(365),
|
||||
]
|
||||
|
||||
public var dayCount: Int? {
|
||||
switch self {
|
||||
case .never: return nil
|
||||
case .days(let count): return count
|
||||
}
|
||||
}
|
||||
|
||||
/// "Never (default)", "7 days", "30 days", "1 year".
|
||||
public var displayName: String {
|
||||
switch self {
|
||||
case .never: return "Never (default)"
|
||||
case .days(365): return "1 year"
|
||||
case .days(let count): return "\(count) days"
|
||||
}
|
||||
}
|
||||
|
||||
/// Caption for the Settings row and the panel footer: what actually happens.
|
||||
public var policyDescription: String {
|
||||
switch self {
|
||||
case .never: return "All sessions kept."
|
||||
case .days(365): return "Sessions older than 1 year are deleted."
|
||||
case .days(let count): return "Sessions older than \(count) days are deleted."
|
||||
}
|
||||
}
|
||||
|
||||
/// Sessions created before this instant are expired; nil means nothing expires.
|
||||
public func cutoff(now: Date = Date()) -> Date? {
|
||||
guard let dayCount else { return nil }
|
||||
return Calendar(identifier: .gregorian).date(byAdding: .day, value: -dayCount, to: now)
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistence for the age limit, backed by UserDefaults.
|
||||
///
|
||||
/// Stored as a day count; 0 (or no stored value at all) means `never`. A stored value
|
||||
/// is only ever written by `save`, so an absent key is the honest "user never chose"
|
||||
/// state, not a hidden default.
|
||||
public enum RetentionSettings {
|
||||
public static let defaultsKey = "ai.flowmaster.shotdeck.sessionRetentionDays"
|
||||
|
||||
public static func load(defaults: UserDefaults = .standard) -> SessionRetention {
|
||||
guard let stored = defaults.object(forKey: defaultsKey) as? Int else { return .never }
|
||||
return stored > 0 ? .days(stored) : .never
|
||||
}
|
||||
|
||||
public static func save(_ value: SessionRetention, defaults: UserDefaults = .standard) {
|
||||
guard let dayCount = value.dayCount else {
|
||||
defaults.removeObject(forKey: defaultsKey)
|
||||
return
|
||||
}
|
||||
defaults.set(dayCount, forKey: defaultsKey)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user