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:
Claude Fable 5
2026-10-31 11:32:54 +04:00
parent 542aad296b
commit 02fa791b78
26 changed files with 2780 additions and 279 deletions
+129 -9
View File
@@ -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)"
}
}
+46 -3
View File
@@ -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