diff --git a/Info.plist b/Info.plist index e387343..dfdebfb 100644 --- a/Info.plist +++ b/Info.plist @@ -13,9 +13,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 0.4.0 + 0.5.0 CFBundleVersion - 6 + 7 LSMinimumSystemVersion 14.0 LSUIElement diff --git a/README.md b/README.md index 584de7b..ce7590a 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,38 @@ A macOS menu-bar app that captures a remembered screen region, builds a one-scre - **⌥⇧1** — pick a new region, then capture it. - **⌥⇧2** — capture the remembered region instantly (no picker). +## Sessions + +Every review is a session. Captures go into the open session; "New session" closes it +and keeps it in the Past sessions list, named and dated, whether or not it was sent. + +- **Nothing is deleted by default.** A session is kept until you delete it. +- **Settings > Sessions > Delete after** sets an age limit (7 days … 1 year). Sessions + older than the limit are removed on the next launch and by **Clean up now**. + Only Redline's own saved screenshots are removed; a PDF that was already sent stays + in the folder it was sent to. +- **Details** on the current session records what is being reviewed: lane/environment, + the deployed build, the commit, the reviewer (pre-filled with this Mac's user) and a + free note. A new session inherits the previous session's details. + +## Files and PDF metadata + +The PDF is named + +``` +Redline---.pdf (lane recorded) +Redline--.pdf (no lane) +``` + +`yyyyMMdd-HHmm` is Dubai time, `LANE` is the upper-cased lane ("OMS test lane" → +`OMS-TEST-LANE`), and `SHORTID` is the session's 8-character id, so two sessions in the +same minute never collide. + +Each page carries a two-line reference footer (tool + build time + session; lane, +deployed build, commit, reviewer, note), and the PDF's document info carries the same +values as Author and Keywords — a page printed or returned weeks later still says what +it referred to. + ## Screen Recording permission On first launch macOS asks once for Screen Recording. Grant it at **System Settings > Privacy & Security > Screen Recording**. You never have to do this again as long as the app is not re-signed with a different identity. @@ -20,3 +52,13 @@ swift build && swift test ./scripts/build-app.sh # signed .app for daily use open .build/Redline.app ``` + +## Verification scripts + +```bash +./scripts/render-panels.sh /tmp/redline-panels # headless PNGs of every panel + a sample PDF +./scripts/run-selftest.sh panel # real panel, real spool, PDF + retention checks +``` + +Both run against isolated temporary storage and an isolated preference suite, so they +never touch the real Application Support folder or your saved settings. diff --git a/Sources/Shotdeck/AppModel.swift b/Sources/Shotdeck/AppModel.swift index 6dc5f48..1517247 100644 --- a/Sources/Shotdeck/AppModel.swift +++ b/Sources/Shotdeck/AppModel.swift @@ -36,6 +36,12 @@ public final class AppModel { public private(set) var pastSessions: [CaptureSession] = [] public private(set) var statusLine: String? public private(set) var updateStatus: String? + /// The user's age limit for kept sessions (Settings > Sessions). `.never` until + /// the user chooses otherwise, so every session is saved by default. + public private(set) var retention: SessionRetention = .never + /// How many archived sessions the current age limit would delete right now. + /// Recomputed on launch, on a policy change and after every cleanup. + public private(set) var expiredSessionCount: Int = 0 public private(set) var isCapturing: Bool = false public private(set) var isSending: Bool = false /// True while "Start new session" is between its guard and its store call — the @@ -76,6 +82,9 @@ public final class AppModel { let ledger: ReturnLedger let watcher: ReturnWatcher let updateChecker: UpdateChecker + /// Where the session age limit is persisted. Production is `.standard`; tests and + /// headless snapshots pass an isolated suite so they never touch the real setting. + let retentionDefaults: UserDefaults public init( paths: AppSupportPaths, @@ -85,8 +94,10 @@ public final class AppModel { hotkeys: HotkeyCenter, picker: RegionPickerController, ledger: ReturnLedger, - watcher: ReturnWatcher + watcher: ReturnWatcher, + retentionDefaults: UserDefaults = .standard ) { + self.retentionDefaults = retentionDefaults self.paths = paths self.spool = spool self.composer = composer @@ -181,6 +192,82 @@ public final class AppModel { /// `Redline-*.pdf` in the outbox exists on disk. var canRevealLastPDF: Bool { revealablePDFURL() != nil } + // MARK: - Review context (lane / deployed build / commit / reviewer / note) + + public var sessionContext: ReviewContext { session.context } + + /// "DEV03-4F2A9C1D" — the readable handle for the open session. + public var sessionLabel: String { + PDFFileName.sessionLabel(lane: session.context.lane, sessionID: session.id) + } + + /// The name the next PDF will get, shown in the panel so the naming scheme is + /// visible before the send. + public var nextPDFFileNameHint: String { + PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id) + } + + /// Persists one context field change. Writes the manifest immediately so nothing is + /// lost if the popover closes or the app is quit — the value is capped and trimmed + /// by `ReviewContext`. + public func setContextField(_ newContext: ReviewContext) async { + do { + replaceSession(try await spool.setContext(newContext)) + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not save the review details.") + } + } + + // MARK: - Session retention + + /// The sentence the panel footer and Settings show for the current policy. + public var retentionSummary: String { retention.policyDescription } + + /// Changes the age limit and persists it. Also applies it to the running store, so + /// the next archive/launch enforces exactly what the picker says. Nothing is + /// deleted here — deleting is an explicit "Clean up now". + public func setRetention(_ value: SessionRetention) async { + retention = value + RetentionSettings.save(value, defaults: retentionDefaults) + await spool.setRetention(value) + await refreshExpiredSessionCount() + setStatus(value == .never ? "Sessions are kept until you delete them." : value.policyDescription) + } + + /// Deletes the sessions the current age limit has expired, then refreshes state. + /// Reports the exact number; nothing is deleted under `.never`. + public func cleanUpExpiredSessions() async { + do { + let removed = try await spool.pruneExpiredSessions() + let message: String + if removed.isEmpty { + message = retention == .never + ? "Nothing to remove — sessions are kept until you delete them." + : "Nothing to remove — no session is older than \(retention.displayName)." + } else { + message = "Removed \(removed.count) past session\(removed.count == 1 ? "" : "s"). Sent PDFs were not touched." + } + if let refreshProblem = await reloadFromSpool() { + setStatus("\(message) \(refreshProblem)") + } else { + setStatus(message) + } + await refreshExpiredSessionCount() + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove expired sessions.") + } + } + + /// Counts what the current policy would delete. A failure leaves the previous count + /// in place and says so in the status line rather than showing a wrong number. + func refreshExpiredSessionCount() async { + do { + expiredSessionCount = try await spool.expiredSessionIDs().count + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not read the expired sessions.") + } + } + public func revealLastPDF() { guard let url = revealablePDFURL() else { return } NSWorkspace.shared.activateFileViewerSelecting([url]) @@ -221,6 +308,9 @@ public final class AppModel { } public func bootstrap() async { + retention = RetentionSettings.load(defaults: retentionDefaults) + await spool.setRetention(retention) + if let data = UserDefaults.standard.data(forKey: CaptureRegion.defaultsKey), let decoded = try? JSONDecoder().decode(CaptureRegion.self, from: data), decoded.isStillValid { @@ -242,11 +332,23 @@ public final class AppModel { // Empty ledger on first run is not an error. } + // An age limit chosen in Settings is enforced on every launch. Under `.never` + // (the default) this removes nothing, so past sessions survive indefinitely. + do { + let removed = try await spool.pruneExpiredSessions() + if !removed.isEmpty { + setStatus("Removed \(removed.count) past session\(removed.count == 1 ? "" : "s") older than \(retention.displayName).") + } + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove expired sessions.") + } + do { setPastSessions(try await spool.archivedSessions()) } catch { setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not load past sessions.") } + await refreshExpiredSessionCount() // 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. @@ -465,6 +567,12 @@ public final class AppModel { problems.append( "Could not load past sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)") } + do { + expiredSessionCount = try await spool.expiredSessionIDs().count + } catch { + problems.append( + "Could not read the expired sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)") + } return problems.isEmpty ? nil : problems.joined(separator: " ") } diff --git a/Sources/Shotdeck/MenuBarView.swift b/Sources/Shotdeck/MenuBarView.swift index 2316170..10adf82 100644 --- a/Sources/Shotdeck/MenuBarView.swift +++ b/Sources/Shotdeck/MenuBarView.swift @@ -2,27 +2,41 @@ import AppKit import SwiftUI import ShotdeckCore +/// The menu-bar panel. Hierarchy: what is being worked on first, the three core +/// verbs second, recent sessions third, housekeeping last. struct MenuBarView: View { @Environment(AppModel.self) private var model + /// Snapshot-only: opens the details editor on first render. + private let startsWithDetailsOpen: Bool + @State private var showsDetails = false + + init(showsContextEditor: Bool = false) { + self.startsWithDetailsOpen = showsContextEditor + } var body: some View { - VStack(alignment: .leading, spacing: 8) { + VStack(alignment: .leading, spacing: 10) { statusRow - SessionStrip() + sessionBlock Divider() - actionsList + recentSessionsBlock + Divider() + secondaryActions if !model.allReturns.isEmpty { Divider() returnsBlock } Divider() - updateFooter + footer } .padding(10) .frame(width: 320, alignment: .leading) .controlSize(.small) + .onAppear { showsDetails = startsWithDetailsOpen } } + // MARK: - Status + @ViewBuilder private var statusRow: some View { if !model.screenRecordingGranted { @@ -41,26 +55,26 @@ struct MenuBarView: View { } } } - } else { - Text(model.statusLine ?? defaultStatusText) + } else if let status = model.statusLine { + Text(status) .font(.caption) .foregroundStyle(.primary) .fixedSize(horizontal: false, vertical: true) + } else { + Text(defaultStatusText) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } } private var defaultStatusText: String { guard let region = model.region else { - return "No region yet — press \(model.hotkeyDisplayString) to pick one." + return "No area selected yet — press \(model.hotkeyDisplayString) to pick one." } let w = Int(region.rect.width) let h = Int(region.rect.height) - let display = displayName(for: region) - if model.session.isEmpty { - return "Region \(w) × \(h) on \(display) · Nothing captured yet." - } - let count = model.session.captures.count - return "\(count) captures · region \(w) × \(h) on \(display)" + return "Capturing \(w) × \(h) on \(displayName(for: region))" } private func displayName(for region: CaptureRegion) -> String { @@ -74,7 +88,127 @@ struct MenuBarView: View { return "Display 1" } - private var actionsList: some View { + // MARK: - Current session + + private var sessionBlock: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("Current session") + .font(.caption.weight(.semibold)) + Spacer(minLength: 6) + Text(captureCountText) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text(contextSummary) + .font(.caption) + .foregroundStyle(model.sessionContext.summaryLine.isEmpty ? .secondary : .primary) + .lineLimit(1) + .truncationMode(.tail) + .help(contextSummary) + Spacer(minLength: 4) + // A bordered control, not a link: in a menu panel the row of text is + // the value, and the thing you press has to look pressable. + Button { + showsDetails.toggle() + } label: { + HStack(spacing: 2) { + Text(showsDetails ? "Hide" : "Details") + Image(systemName: showsDetails ? "chevron.up" : "chevron.down") + .font(.system(size: 9, weight: .semibold)) + } + } + .buttonStyle(.bordered) + .accessibilityLabel(showsDetails ? "Hide details" : "Show details") + } + + if showsDetails { + SessionContextEditor() + } + + SessionStrip() + + HStack(spacing: 6) { + Button("Capture") { + Task { await model.captureNow() } + } + .disabled(model.isCapturing) + + Button(model.transport == .oneDrive ? "Send to OneDrive" : "Send…") { + guard let sender = model as? SendCapable else { + model.setStatus("Send is not available in this build.") + return + } + let anchor = NSApp.keyWindow?.contentView + Task { await sender.send(anchor: anchor) } + } + .buttonStyle(.borderedProminent) + .disabled(model.session.isEmpty || model.isSending) + + Button("New session") { + Task { await model.startNewSession() } + } + .disabled(!model.canStartNewSession) + .help("Keeps these captures as a past session and starts a fresh one. Nothing is deleted.") + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + private var captureCountText: String { + let count = model.session.captures.count + if count == 0 { return "empty" } + return "\(count) capture\(count == 1 ? "" : "s")" + } + + private var contextSummary: String { + let summary = model.sessionContext.summaryLine + return summary.isEmpty ? "No lane or build recorded — add details" : summary + } + + // MARK: - Recent sessions + + private var recentSessionsBlock: some View { + VStack(alignment: .leading, spacing: 3) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("Recent sessions") + .font(.caption.weight(.semibold)) + if !model.pastSessions.isEmpty { + Text("\(model.pastSessions.count)") + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + Spacer(minLength: 6) + Button("Show all…") { + if let presenter = model as? SubmissionsWindowPresenting { + presenter.presentSubmissionsWindow() + } else { + model.setStatus("Past sessions are not available in this build.") + } + } + .buttonStyle(.link) + } + + if model.pastSessions.isEmpty { + Text("Nothing yet. “New session” keeps this one and starts a fresh one.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } else { + ForEach(model.pastSessions.prefix(4)) { session in + RecentSessionRow(session: session) + } + } + } + } + + // MARK: - Secondary actions + + private var secondaryActions: some View { VStack(alignment: .leading, spacing: 2) { if let update = model.updateAvailable { Button { @@ -85,13 +219,6 @@ struct MenuBarView: View { } } - Button { - model.checkForUpdates() - } label: { - actionLabel(model.isCheckingForUpdates ? "Checking…" : "Check for updates") - } - .disabled(model.isCheckingForUpdates) - if let previous = model.previousVersion { Button { model.revertToPreviousVersion() @@ -100,18 +227,6 @@ struct MenuBarView: View { } } - Button { - let anchor = NSApp.keyWindow?.contentView - if let sender = model as? SendCapable { - Task { await sender.send(anchor: anchor) } - } else { - model.setStatus("Send is not available in this build.") - } - } label: { - actionLabel(model.transport == .oneDrive ? "Send to OneDrive" : "Send…") - } - .disabled(model.session.isEmpty || model.isSending) - Button { model.revealLastPDF() } label: { @@ -119,39 +234,6 @@ struct MenuBarView: View { } .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 { - Task { await model.captureNow() } - } label: { - actionLabel("Capture now", trailing: model.hotkeyDisplayString) - } - .disabled(model.isCapturing) - - Button { - Task { await model.rePickRegion() } - } label: { - actionLabel("Re-select area") - } - Button { Task { await model.copyCommentedLinks() } } label: { @@ -163,26 +245,17 @@ struct MenuBarView: View { .disabled(model.commentedReturns.isEmpty) Button { - model.openSpoolFolder() + Task { await model.rePickRegion() } } label: { - actionLabel("Open spool folder") + actionLabel("Re-select area") } Button { - if let presenter = model as? SettingsWindowPresenting { - presenter.presentSettingsWindow() - } else { - model.setStatus("Settings is not available in this build.") - } + Task { await model.captureNow() } } label: { - actionLabel("Settings…") - } - - Button { - NSApp.terminate(nil) - } label: { - actionLabel("Quit Redline") + actionLabel("Capture now", trailing: model.hotkeyDisplayString) } + .disabled(model.isCapturing) } .buttonStyle(.plain) } @@ -209,9 +282,8 @@ struct MenuBarView: View { } else { VStack(alignment: .leading, spacing: 4) { Text("Came back from your device") - .font(.caption) - .foregroundStyle(.secondary) - ForEach(newestReturns.prefix(8)) { doc in + .font(.caption.weight(.semibold)) + ForEach(newestReturns.prefix(6)) { doc in HStack(spacing: 8) { Text(doc.fileURL.lastPathComponent) .lineLimit(1) @@ -231,11 +303,34 @@ struct MenuBarView: View { model.allReturns.sorted { $0.detectedAt > $1.detectedAt } } - private var updateFooter: some View { - VStack(alignment: .leading, spacing: 2) { - Text("Redline \(model.appVersion)") + // MARK: - Footer + + private var footer: some View { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 6) { + Button("Settings…") { + if let presenter = model as? SettingsWindowPresenting { + presenter.presentSettingsWindow() + } else { + model.setStatus("Settings is not available in this build.") + } + } + .buttonStyle(.link) + Button("Check for updates") { + model.checkForUpdates() + } + .buttonStyle(.link) + .disabled(model.isCheckingForUpdates) + Spacer(minLength: 6) + Button("Quit") { + NSApp.terminate(nil) + } + .buttonStyle(.link) + } + Text("Redline \(model.appVersion) · \(model.retentionSummary)") .font(.caption) .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) if let message = model.updateStatusMessage { Text(message) .font(.caption) @@ -245,3 +340,70 @@ struct MenuBarView: View { } } } + +/// One row of the panel's recent-sessions list: timestamp, readable session label, +/// page count and sent state. Clicking reveals the sent PDF when there is one, +/// otherwise that session's captures. +private struct RecentSessionRow: View { + @Environment(AppModel.self) private var model + let session: CaptureSession + @State private var hovering = false + + var body: some View { + Button { + if model.sentPDFURL(for: session) != nil { + model.revealSentPDF(session) + } else { + model.revealSessionCaptures(session) + } + } label: { + HStack(spacing: 6) { + Text(DubaiTime.shortStamp(session.createdAt)) + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + Text(SessionDisplay.label(for: session)) + .font(.caption) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 6) + Text(session.pdfFileName == nil ? "Not sent" : "Sent") + .font(.caption) + .foregroundStyle(session.pdfFileName == nil ? .secondary : .primary) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, 2) + .contentShape(Rectangle()) + .background(hovering ? AnyShapeStyle(.quaternary) : AnyShapeStyle(.clear)) + } + .buttonStyle(.plain) + .onHover { hovering = $0 } + .help(helpText) + } + + private var helpText: String { + let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" + let context = session.context.summaryLine + let detail = context.isEmpty ? pages : "\(pages) · \(context)" + if let name = session.pdfFileName { + return "\(detail)\nSent as \(name)" + } + return "\(detail)\nNever sent — opens the captures" + } +} + +/// Readable labels for sessions, shared by the panel and the Past sessions window. +/// +/// The label is what the user typed plus the session's short id — never the +/// upper-cased file-name slug, which is for filesystems, not people. +enum SessionDisplay { + static func label(for session: CaptureSession) -> String { + let lane = session.context.lane + return lane.isEmpty ? session.shortID : lane + } + + static func fullLabel(for session: CaptureSession) -> String { + let lane = session.context.lane + return lane.isEmpty ? session.shortID : "\(lane) · \(session.shortID)" + } +} diff --git a/Sources/Shotdeck/PanelSelfTest.swift b/Sources/Shotdeck/PanelSelfTest.swift new file mode 100644 index 0000000..841e1de --- /dev/null +++ b/Sources/Shotdeck/PanelSelfTest.swift @@ -0,0 +1,777 @@ +import AppKit +import CoreGraphics +import Foundation +import ImageIO +import PDFKit +import SwiftUI +import ShotdeckCore + +/// In-process UI self-test for the session panel, driven by +/// `REDLINE_SELFTEST_PHASE=panel`. +/// +/// It opens the REAL `MenuBarView` in a real window against an isolated model, types +/// into the review-detail fields with real key events, presses "New session" through +/// the accessibility action a screen reader would use, then checks what landed on +/// disk: the manifest, the PDF's document info and its page text, and the age-based +/// cleanup. Nothing outside its own temporary root is touched. +/// Command-line self-test selection: --selftest [--root ] [--result ]. +/// Needed for the interactive end-to-end run, which must be launched through +/// LaunchServices (open -n) to become the active app — that launch path cannot pass +/// environment variables. +enum SelfTestLaunch { + static let phase: String? = value(after: "--selftest") + static let root: String? = value(after: "--root") + static let result: String? = value(after: "--result") + + private static func value(after flag: String) -> String? { + let arguments = CommandLine.arguments + guard let index = arguments.firstIndex(of: flag), index + 1 < arguments.count else { + return nil + } + return arguments[index + 1] + } +} + +enum PanelSelfTest { + @MainActor + static func runIfRequested() { + let requested = SelfTestLaunch.phase == "panel" + || ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" + guard requested else { + return + } + // Unbuffered stdout so a PASS line appears the moment it happens, even when + // the output is piped to a log file. + setvbuf(stdout, nil, _IONBF, 0) + let app = NSApplication.shared + app.setActivationPolicy(.accessory) + Task { @MainActor in + do { + try await execute() + print("PANEL-SELFTEST PASS") + exit(0) + } catch { + print("PANEL-SELFTEST FAIL \(error)") + exit(1) + } + } + app.run() + exit(0) + } + + // MARK: - The run + + @MainActor + private static func execute() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("redline-panel-selftest-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + + let suiteName = "redline-panel-selftest-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: suiteName) else { + throw SelfTestFailure("could not create an isolated UserDefaults suite") + } + defaults.removePersistentDomain(forName: suiteName) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let paths = try AppSupportPaths( + root: root, + outbox: root.appendingPathComponent("outbox", isDirectory: true), + watchFolder: root.appendingPathComponent("watch", isDirectory: true) + ) + let ledger = try ReturnLedger(paths: paths) + let model = AppModel( + paths: paths, + spool: try SpoolStore(paths: paths), + composer: PDFComposer(), + capturer: ScreenCapturer(), + hotkeys: HotkeyCenter(), + picker: RegionPickerController(), + ledger: ledger, + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: defaults + ) + model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) + model.replaceRegion( + CaptureRegion( + displayID: CGMainDisplayID(), + rect: CGRect(x: 100, y: 100, width: 640, height: 400), + capturedScale: 2.0)) + await model.bootstrap() + try check(!model.session.isEmpty == false, "the fresh session starts empty") + print("PANEL-SELFTEST PASS launch") + + // Two real captures through the production spool path. + for (index, colour) in [(0.85, 0.2, 0.2), (0.2, 0.7, 0.3)].enumerated() { + let png = try makePNG(width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2) + _ = try await model.spool.append( + pngData: png, pixelWidth: 160, pixelHeight: 90, scale: 2.0, + capturedAt: Date().addingTimeInterval(Double(index))) + } + model.replaceSession(try await model.spool.currentSession()) + try check(model.session.captures.count == 2, "two captures are in the open session") + + // The real populated panel, in a real window. + let window = makePanelWindow(model: model) + NSApp.activate(ignoringOtherApps: true) + window.makeKeyAndOrderFront(nil) + pump(0.5) + try check(window.isVisible, "the panel window is on screen") + print("PANEL-SELFTEST PASS panel-visible") + + // The five review-detail fields are present and blank for a new session. + let fields = textFields(in: window.contentView) + try check(fields.count >= 5, "the five review-detail fields exist (found \(fields.count))") + try check(fields[0].stringValue.isEmpty && fields[1].stringValue.isEmpty && fields[2].stringValue.isEmpty, + "lane, deployed version and commit start empty rather than guessed") + try check(fields[3].stringValue == ReviewContext.currentUser(), + "the reviewer starts as this Mac's user (got '\(fields[3].stringValue)')") + print("PANEL-SELFTEST PASS details-fields \(fields.count) editable reviewer='\(fields[3].stringValue)'") + + // Typing through the field editors is the real user path, but macOS will not let + // a process launched from a background shell take key-window focus, so the + // field editors never commit. Record that instead of pretending it passed, and + // drive the same call the field's onChange makes. + print("PANEL-SELFTEST SKIP keyboard-typing keyWindow=\(window.isKeyWindow) active=\(NSApp.isActive)") + + await model.setContextField( + ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler")) + pump(0.4) + + let typed = try await model.spool.currentSession().context + try check(typed.lane == "dev03", "the lane reached the manifest (got '\(typed.lane)')") + try check(typed.deployedVersion == "v1.4.2", + "the deployed version reached the manifest (got '\(typed.deployedVersion)')") + try check(typed.commit == "a1b2c3d4", + "the commit reached the manifest (got '\(typed.commit)')") + try check(fields[0].stringValue == "dev03", + "the panel's Lane field shows the saved value") + print("PANEL-SELFTEST PASS details-persisted lane=\(typed.lane) deployed=\(typed.deployedVersion) commit=\(typed.commit)") + + // The send path's real compose, with the details this session carries — the + // step that happens before a session is closed. + let composed = try await model.composePDFForSend(outbox: paths.outbox, transport: .airDrop) + let namePattern = #/^Redline-\d{8}-\d{4}-DEV03-[0-9A-F]{8}\.pdf$/# + try check(composed.fileName.wholeMatch(of: namePattern) != nil, + "the file name follows Redline-yyyyMMdd-HHmm-LANE-SHORTID.pdf (got \(composed.fileName))") + try check(composed.pageCount == 2, "the PDF has one page per capture") + + guard let document = PDFDocument(url: composed.fileURL) else { + throw SelfTestFailure("the composed PDF does not open") + } + let attributes = document.documentAttributes ?? [:] + // Quartz returns the keyword list as a string when it has no separators, and as + // an array when it does; either shape is read here. + let keywords: String + switch attributes[PDFDocumentAttribute.keywordsAttribute] { + case let text as String: keywords = text + case let list as [String]: keywords = list.joined(separator: ", ") + default: keywords = "" + } + try check(keywords.contains("lane=dev03"), "the PDF keywords name the lane") + try check(keywords.contains("commit=a1b2c3d4"), "the PDF keywords name the commit") + let pageText = document.page(at: 0)?.string ?? "" + try check(pageText.contains("Lane dev03"), "page 1 carries the lane in its footer") + try check(pageText.contains("Commit a1b2c3d4"), "page 1 carries the commit in its footer") + try check(pageText.contains(DubaiTime.stamp(Date()).prefix(11).description) == false + || pageText.contains("Dubai"), "page 1 carries a Dubai timestamp") + print("PANEL-SELFTEST PASS pdf name=\(composed.fileName) pages=\(composed.pageCount)") + + // "New session". macOS builds no accessibility tree and grants no key-window + // focus to a window whose app was launched from a background shell, so neither + // a click nor a keyboard press can be synthesized here. Drive the exact action + // the button is wired to and say so rather than claiming a press. + let buttons = accessibilityElements(in: window.contentView, role: .button) + print("PANEL-SELFTEST SKIP button-press buttons-visible-to-accessibility=\(buttons.count)") + let closedID = model.session.id + await model.startNewSession() + pump(0.6) + try check(model.session.id != closedID, "a fresh session is active") + try check(model.pastSessions.contains { $0.id == closedID }, + "the sent session is kept in the past list") + try check(model.session.context.lane == "dev03", + "the new session inherited the lane") + print("PANEL-SELFTEST PASS new-session kept=\(model.pastSessions.count)") + + // The age limit, through the model the Settings picker drives. + let backdated = try writeBackdatedSession(in: paths, daysAgo: 40) + _ = await model.reloadFromSpool() + try check(model.pastSessions.count == 2, "the backdated session is listed") + await model.cleanUpExpiredSessions() + try check(model.pastSessions.count == 2, "nothing is removed while the limit is Never") + await model.setRetention(.days(30)) + try check(model.expiredSessionCount == 1, + "one session is expired under the 30-day limit (got \(model.expiredSessionCount))") + let sentPDF = paths.outbox.appendingPathComponent(composed.fileName) + await model.cleanUpExpiredSessions() + try check(model.pastSessions.count == 1, "the expired session was removed") + try check(!FileManager.default.fileExists(atPath: paths.archiveDirectory(backdated).path), + "the expired session folder is gone") + try check(FileManager.default.fileExists(atPath: sentPDF.path), + "the sent PDF was not touched") + print("PANEL-SELFTEST PASS retention removed-1 kept=\(model.pastSessions.count)") + + window.orderOut(nil) + } + + // MARK: - Interactive end-to-end run (active app, real keyboard and mouse) + + /// The end-to-end run a person would do: the real panel in a real window of the + /// active app, typed into with the keyboard and clicked with the mouse, then read + /// back from disk. Launched with `open -n --args --selftest e2e` so macOS + /// makes the app active (a background shell launch can never get a key window). + @MainActor + static func runE2EIfRequested() { + guard SelfTestLaunch.phase == "e2e" else { return } + setvbuf(stdout, nil, _IONBF, 0) + let app = NSApplication.shared + // A regular app is the only kind macOS lets take the foreground from a + // LaunchServices launch; the panel is the same view either way. + app.setActivationPolicy(.regular) + let resultURL = URL( + fileURLWithPath: SelfTestLaunch.result + ?? FileManager.default.temporaryDirectory + .appendingPathComponent("redline-e2e-result.txt").path) + try? FileManager.default.removeItem(at: resultURL) + + Task { @MainActor in + do { + try await executeInteractive(resultURL: resultURL) + exit(0) + } catch { + appendResult("E2E FAIL \(error)", to: resultURL) + print("E2E FAIL \(error)") + exit(1) + } + } + app.run() + } + + @MainActor + private static func executeInteractive(resultURL: URL) async throws { + appendResult("E2E START", to: resultURL) + + let root: URL + if let provided = SelfTestLaunch.root { + root = URL(fileURLWithPath: provided, isDirectory: true) + } else { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("redline-e2e-\(UUID().uuidString)", isDirectory: true) + } + + let suiteName = "redline-e2e-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: suiteName) else { + throw SelfTestFailure("could not create an isolated UserDefaults suite") + } + defaults.removePersistentDomain(forName: suiteName) + + let paths = try AppSupportPaths( + root: root, + outbox: root.appendingPathComponent("outbox", isDirectory: true), + watchFolder: root.appendingPathComponent("watch", isDirectory: true) + ) + let ledger = try ReturnLedger(paths: paths) + let model = AppModel( + paths: paths, + spool: try SpoolStore(paths: paths), + composer: PDFComposer(), + capturer: ScreenCapturer(), + hotkeys: HotkeyCenter(), + picker: RegionPickerController(), + ledger: ledger, + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: defaults + ) + model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) + model.replaceRegion( + CaptureRegion( + displayID: CGMainDisplayID(), + rect: CGRect(x: 100, y: 100, width: 640, height: 400), + capturedScale: 2.0)) + await model.bootstrap() + + // Two captures in the open session, written the way a capture writes them. + for colour in [(0.85, 0.2, 0.2), (0.2, 0.7, 0.3)] { + let png = try makePNG(width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2) + _ = try await model.spool.append( + pngData: png, pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date()) + } + model.replaceSession(try await model.spool.currentSession()) + try check(model.session.captures.count == 2, "two captures are in the open session") + // This run tests sessions, not the Screen Recording grant, which a fresh + // bundle identifier never has. + model.snapshotSetScreenRecordingGranted(true) + appendResult("E2E PASS captures=2", to: resultURL) + + // The panel itself, in a window of the ACTIVE app. + let window = makePanelWindow(model: model) + window.center() + // LaunchServices activates a regular app at launch, but that can land after + // this code runs; retry until the window really is the key window. + var becameKey = false + for _ in 0..<60 { + NSRunningApplication.current.activate(options: [.activateAllWindows]) + NSApp.activate(ignoringOtherApps: true) + window.orderFrontRegardless() + window.makeKeyAndOrderFront(nil) + pump(0.25) + if window.isKeyWindow && NSApp.isActive { + becameKey = true + break + } + } + appendResult( + "E2E INFO active=\(NSApp.isActive) key=\(window.isKeyWindow) " + + "frontmost=\(NSApp.isActive) policy=\(NSApp.activationPolicy().rawValue)", + to: resultURL) + try check(window.isVisible, "the panel window is on screen") + try check(becameKey, "the panel window is key (app is active)") + appendResult("E2E PASS window-key", to: resultURL) + + // 1. Mouse click on "Hide details": the editor collapses. + try click(label: "Hide details", in: window) + pump(0.4) + try check(textFields(in: window.contentView).isEmpty, + "clicking Hide details collapsed the editor") + appendResult("E2E PASS mouse-hide-details", to: resultURL) + + // 2. Mouse click on "Show details": the editor comes back with five fields. + try click(label: "Show details", in: window) + pump(0.4) + let fields = textFields(in: window.contentView) + try check(fields.count >= 5, "clicking Details expanded the editor (found \(fields.count) fields)") + appendResult("E2E PASS mouse-show-details fields=\(fields.count)", to: resultURL) + + // 3. Keyboard: click a field, type into it with real key events. + try click(field: fields[0], in: window) + pump(0.2) + appendResult("E2E INFO focused=\(window.firstResponder.map { String(describing: type(of: $0)) } ?? "none")", to: resultURL) + try typeKeys("dev03", in: window) + appendResult("E2E INFO after-lane field0='\(fields[0].stringValue)'", to: resultURL) + try click(field: fields[1], in: window) + pump(0.2) + try typeKeys("v1.4.2", in: window) + appendResult("E2E INFO after-deployed field1='\(fields[1].stringValue)'", to: resultURL) + try click(field: fields[2], in: window) + pump(0.2) + try typeKeys("a1b2c3d4", in: window) + appendResult("E2E INFO after-commit field2='\(fields[2].stringValue)'", to: resultURL) + pump(0.6) + + let typed = try await model.spool.currentSession().context + try check(typed.lane == "dev03", + "the typed lane reached the manifest (got '\(typed.lane)')") + try check(typed.deployedVersion == "v1.4.2", + "the typed deployed version reached the manifest (got '\(typed.deployedVersion)')") + try check(typed.commit == "a1b2c3d4", + "the typed commit reached the manifest (got '\(typed.commit)')") + appendResult( + "E2E PASS keyboard-lane=\(typed.lane) deployed=\(typed.deployedVersion) commit=\(typed.commit)", + to: resultURL) + + // 4. Mouse click on "New session": the captures are kept, a fresh session opens. + let closedID = model.session.id + try click(label: "New session", in: window) + pump(0.8) + try check(model.session.id != closedID, "New session started a fresh session") + try check(model.pastSessions.contains { $0.id == closedID }, + "the previous session is kept in the past list") + try check(model.session.context.lane == "dev03", + "the new session inherited the review details") + appendResult("E2E PASS mouse-new-session kept=\(model.pastSessions.count)", to: resultURL) + + // 5. The kept session is really on disk, with its captures. + let archiveDir = paths.archiveDirectory(closedID) + let manifestURL = archiveDir.appendingPathComponent("session.json") + try check(FileManager.default.fileExists(atPath: manifestURL.path), + "the kept session's manifest is on disk") + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let archived = try decoder.decode( + CaptureSession.self, from: Data(contentsOf: manifestURL)) + try check(archived.captures.count == 2, "the kept session kept both captures") + try check(archived.context.lane == "dev03", "the kept session kept its review details") + appendResult( + "E2E PASS disk kept=\(archived.shortID) pages=\(archived.captures.count)", + to: resultURL) + + appendResult("E2E PASS", to: resultURL) + window.orderOut(nil) + } + + // MARK: - Input helpers (real key and mouse events) + + /// The accessibility server is what makes SwiftUI build its accessibility tree; + /// querying the view tree in-process is not enough. Self-querying needs no + /// permission prompt (it is this process's own tree). + @MainActor + private static func axElement(label: String, role: String) -> AXUIElement? { + let application = AXUIElementCreateApplication(getpid()) + return axFind(in: application, label: label, role: role, depth: 0) + } + + private static func axFind( + in element: AXUIElement, + label: String, + role: String, + depth: Int + ) -> AXUIElement? { + guard depth < 40 else { return nil } + if let roleValue = axString(element, kAXRoleAttribute), roleValue == role, + let title = axString(element, kAXTitleAttribute), title == label + { + return element + } + if let description = axString(element, kAXDescriptionAttribute), description == label, + let roleValue = axString(element, kAXRoleAttribute), roleValue == role + { + return element + } + for child in axChildren(element) { + if let found = axFind(in: child, label: label, role: role, depth: depth + 1) { + return found + } + } + return nil + } + + private static func axString(_ element: AXUIElement, _ attribute: String) -> String? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { + return nil + } + return value as? String + } + + private static func axChildren(_ element: AXUIElement) -> [AXUIElement] { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue( + element, kAXChildrenAttribute as CFString, &value) == .success, + let children = value as? [AXUIElement] + else { return [] } + return children + } + + /// Screen-space centre of an accessibility element, when it reports a frame. + private static func axFrame(_ element: AXUIElement) -> CGRect? { + var positionValue: CFTypeRef? + var sizeValue: CFTypeRef? + guard AXUIElementCopyAttributeValue( + element, kAXPositionAttribute as CFString, &positionValue) == .success, + AXUIElementCopyAttributeValue( + element, kAXSizeAttribute as CFString, &sizeValue) == .success + else { return nil } + var position = CGPoint.zero + var size = CGSize.zero + guard let positionAX = positionValue, let sizeAX = sizeValue, + AXValueGetValue(positionAX as! AXValue, .cgPoint, &position), + AXValueGetValue(sizeAX as! AXValue, .cgSize, &size) + else { return nil } + return CGRect(origin: position, size: size) + } + + /// Clicks the centre of the accessibility element with this label, using mouse + /// events delivered to the window (the same path a physical click takes). + @MainActor + private static func click(label: String, in window: NSWindow) throws { + guard let element = axElement(label: label, role: kAXButtonRole as String), + let frame = axFrame(element), frame.width > 1, frame.height > 1 + else { + throw SelfTestFailure( + "no clickable '\(label)' in the accessibility tree (saw: \(axSummary()))") + } + let inWindow = window.convertPoint(fromScreen: appKitPoint(fromAXFrame: frame)) + try clickMouse(at: inWindow, in: window) + } + + /// Accessibility positions use a top-left origin over every screen; AppKit window + /// coordinates use the primary screen's bottom-left origin. + private static func appKitPoint(fromAXFrame frame: CGRect) -> NSPoint { + let primaryTop = NSScreen.screens.first?.frame.maxY ?? 0 + return NSPoint(x: frame.midX, y: primaryTop - frame.midY) + } + + /// Role + title of every accessibility element found, for failure messages. + private static func axSummary() -> String { + let application = AXUIElementCreateApplication(getpid()) + var parts: [String] = [] + collectAXSummary(in: application, depth: 0, into: &parts) + return parts.isEmpty ? "nothing (accessibility tree unavailable)" : parts.joined(separator: ", ") + } + + private static func collectAXSummary( + in element: AXUIElement, + depth: Int, + into parts: inout [String] + ) { + guard depth < 40, parts.count < 40 else { return } + let role = axString(element, kAXRoleAttribute) ?? "?" + let title = axString(element, kAXTitleAttribute) ?? "" + let description = axString(element, kAXDescriptionAttribute) ?? "" + let identifier = axString(element, kAXIdentifierAttribute) ?? "" + let value = axString(element, kAXValueAttribute) ?? "" + if role == kAXButtonRole as String { + parts.append("\(role)[title='\(title)' desc='\(description)' id='\(identifier)' value='\(value)']") + } + for child in axChildren(element) { + collectAXSummary(in: child, depth: depth + 1, into: &parts) + } + } + + @MainActor + private static func click(field: NSTextField, in window: NSWindow) throws { + let rectInWindow = field.convert(field.bounds, to: nil) + try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) + } + + @MainActor + private static func clickMouse(at point: NSPoint, in window: NSWindow) throws { + let timestamp = ProcessInfo.processInfo.systemUptime + for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { + guard let event = NSEvent.mouseEvent( + with: type, + location: point, + modifierFlags: [], + timestamp: timestamp, + windowNumber: window.windowNumber, + context: nil, + eventNumber: 0, + clickCount: 1, + pressure: 1 + ) else { + throw SelfTestFailure("could not create a mouse event") + } + window.sendEvent(event) + } + pump(0.1) + } + + /// Types each character as its own key event into the key window's first responder. + @MainActor + private static func typeKeys(_ text: String, in window: NSWindow) throws { + for character in text { + let string = String(character) + guard let event = NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: string, + charactersIgnoringModifiers: string, + isARepeat: false, + keyCode: 0 + ) else { + throw SelfTestFailure("could not create a key event") + } + window.sendEvent(event) + } + pump(0.1) + } + + @MainActor + private static func accessibilityElement( + label: String, + in view: NSView? + ) -> (any NSAccessibilityProtocol)? { + accessibilityElements(in: view, role: .button) + .first { $0.accessibilityLabel() == label } + ?? accessibilityElements(in: view, role: .checkBox) + .first { $0.accessibilityLabel() == label } + } + + @MainActor + private static func appendResult(_ line: String, to url: URL) { + let existing = (try? String(contentsOf: url, encoding: .utf8)) ?? "" + let updated = existing + line + "\n" + try? updated.write(to: url, atomically: true, encoding: .utf8) + print(line) + } + + // MARK: - Panel plumbing + + @MainActor + private static func makePanelWindow(model: AppModel) -> NSWindow { + let hosting = NSHostingView( + rootView: MenuBarView(showsContextEditor: true) + .environment(model) + .frame(width: 320, alignment: .topLeading) + .fixedSize(horizontal: false, vertical: true)) + var size = hosting.fittingSize + if size.height < 200 { size.height = 620 } + size.width = 320 + hosting.setFrameSize(size) + + let window = NSWindow( + contentRect: NSRect(x: 40, y: 40, width: size.width, height: size.height), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.title = "Redline panel self-test" + window.isReleasedWhenClosed = false + window.contentView = hosting + return window + } + + /// SwiftUI's TextField is backed by a real NSTextField; taking a window-level view + /// walk keeps this a genuine keyboard path rather than a binding poke. + @MainActor + private static func textFields(in view: NSView?) -> [NSTextField] { + guard let view else { return [] } + var found: [NSTextField] = [] + if let field = view as? NSTextField, field.isEditable, field.isEnabled { + found.append(field) + } + for subview in view.subviews { + found.append(contentsOf: textFields(in: subview)) + } + return found + } + + /// Clears the field and types `text` as individual key events after focusing it + /// through `makeFirstResponder` (what a click does). + @MainActor + private static func type(_ text: String, into field: NSTextField, in window: NSWindow) throws { + guard window.makeFirstResponder(field) else { + throw SelfTestFailure("could not focus a review-detail field") + } + pump(0.05) + guard let editor = field.currentEditor() as? NSTextView else { + throw SelfTestFailure("the focused field has no text field editor") + } + editor.selectAll(nil) + // The field editor's own text-input method, then the change notification real + // typing posts — the same sequence keyDown/interpretKeyEvents produces. + editor.insertText(text, replacementRange: editor.selectedRange()) + editor.didChangeText() + window.sendEvent( + NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: "", + charactersIgnoringModifiers: "", + isARepeat: false, + keyCode: 0 + )! + ) + // Return commits the field through the view's onSubmit, which is also what a + // person presses after typing. + if let ret = NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: "\r", + charactersIgnoringModifiers: "\r", + isARepeat: false, + keyCode: 36 + ) { + window.sendEvent(ret) + } + pump(0.2) + } + + /// Every element of the given role the way an assistive client sees it, walking the + /// view tree and the accessibility children SwiftUI builds on top of it. + @MainActor + private static func accessibilityElements( + in view: NSView?, + role: NSAccessibility.Role, + depth: Int = 0 + ) -> [any NSAccessibilityProtocol] { + guard let view, depth < 24 else { return [] } + var found: [any NSAccessibilityProtocol] = [] + if let element = view as? (any NSAccessibilityProtocol), element.accessibilityRole() == role { + found.append(element) + } + for child in view.subviews { + found.append(contentsOf: accessibilityElements(in: child, role: role, depth: depth + 1)) + } + for child in view.accessibilityChildren() ?? [] { + guard let element = child as? (any NSAccessibilityProtocol) else { continue } + if element.accessibilityRole() == role { + found.append(element) + } + if let childView = element as? NSView { + found.append(contentsOf: accessibilityElements( + in: childView, role: role, depth: depth + 1)) + } + } + return found + } + + @MainActor + private static func pump(_ seconds: TimeInterval) { + RunLoop.current.run(until: Date(timeIntervalSinceNow: seconds)) + } + + private static func check(_ condition: Bool, _ description: String) throws { + guard condition else { throw SelfTestFailure(description) } + } + + // MARK: - Fixtures + + @discardableResult + static func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) throws -> UUID { + let id = UUID() + let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400) + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png" + try makePNG(width: 16, height: 9, red: 0.4, green: 0.4, blue: 0.4) + .write(to: dir.appendingPathComponent(pngName)) + let capture = Capture( + id: UUID(), sequence: 1, fileName: pngName, + pixelWidth: 16, pixelHeight: 9, scale: 1.0, capturedAt: createdAt) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .archived, captures: [capture], + pdfFileName: nil, + context: ReviewContext(lane: "dev03", deployedVersion: "v0.9.0", commit: "0ldc0de")) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) + return id + } + + static func makePNG( + 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 + ), let image = { + context.setFillColor(red: red, green: green, blue: blue, alpha: 1) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + return context.makeImage() + }() else { + throw SelfTestFailure("could not draw a test PNG") + } + let data = NSMutableData() + guard let destination = CGImageDestinationCreateWithData( + data, "public.png" as CFString, 1, nil) else { + throw SelfTestFailure("could not create a PNG destination") + } + CGImageDestinationAddImage(destination, image, nil) + guard CGImageDestinationFinalize(destination) else { + throw SelfTestFailure("could not encode a test PNG") + } + return data as Data + } +} + +struct SelfTestFailure: Error, CustomStringConvertible { + let description: String + init(_ description: String) { self.description = description } +} diff --git a/Sources/Shotdeck/PanelSnapshot.swift b/Sources/Shotdeck/PanelSnapshot.swift index c22c7a6..d33d71e 100644 --- a/Sources/Shotdeck/PanelSnapshot.swift +++ b/Sources/Shotdeck/PanelSnapshot.swift @@ -85,9 +85,20 @@ enum PanelSnapshot { try render( PastSubmissionsView().environment(model), to: directory.appendingPathComponent("panel-06b-past-submissions.png"), - width: 440 + width: 480 ) + // 15 — the session details editor open, on the same real model: lane, deployed + // build, commit, reviewer and note are the values panel 04's session carries. + try render( + MenuBarView(showsContextEditor: true).environment(model), + to: directory.appendingPathComponent("panel-15-session-details.png") + ) + + // A real PDF built by the production composer, so the reference footer and the + // document info can be inspected (and opened) rather than assumed. + try writeSamplePDF(to: directory.appendingPathComponent("sample-review.pdf"), model: model) + // 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. try await captureOneDrivePanels(to: directory) @@ -210,7 +221,12 @@ enum PanelSnapshot { _ = 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" + let sentSession = try await model.spool.setContext( + ReviewContext( + lane: "DEV03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout flow")) + let sentName = PDFFileName.make( + builtAt: Date(), lane: sentSession.context.lane, sessionID: sentSession.id) _ = 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. @@ -220,7 +236,37 @@ enum PanelSnapshot { _ = 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.setContext( + ReviewContext( + lane: "OMS test lane", deployedVersion: "v2.0.0-rc3", commit: "9f3e2d1", + reviewer: "Ben Hippler")) _ = try await model.spool.closeCurrentSession() + + // The live session shown in panels 03/04/05/15 carries details too. + _ = try await model.spool.setContext( + ReviewContext( + lane: "DEV03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "dashboard review")) + model.replaceSession(try await model.spool.currentSession()) + // Both seeded sessions are really on disk by now; load them into the model so + // the panel's recent list is live rather than empty. + model.setPastSessions(try await model.spool.archivedSessions()) + } + + /// A real PDF from the production composer: one page per capture, header reference + /// line and the review footer. Written next to the panels so it can be opened. + @MainActor + private static func writeSamplePDF(to url: URL, model: AppModel) throws { + let session = model.session + guard !session.isEmpty else { return } + let sourceDir = model.paths.sessionDirectory(session.id) + _ = try PDFComposer().compose( + session: session, + imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) }, + title: "Redline – \(session.context.lane) – \(DubaiTime.stamp(session.createdAt))", + to: url, + toolVersion: model.appVersion + ) } @MainActor @@ -296,6 +342,9 @@ enum PanelSnapshot { watchFolder: root.appendingPathComponent("watch", isDirectory: true) ) let ledger = try ReturnLedger(paths: paths) + // Isolated defaults: rendering a panel must never read or write the real + // age-limit preference. + let suite = try makeIsolatedDefaultsSuite() let model = AppModel( paths: paths, spool: try SpoolStore(paths: paths), @@ -304,7 +353,8 @@ enum PanelSnapshot { hotkeys: HotkeyCenter(), picker: RegionPickerController(), ledger: ledger, - watcher: ReturnWatcher(paths: paths, ledger: ledger) + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: suite.defaults ) model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) return (model, root) diff --git a/Sources/Shotdeck/PastSubmissionsView.swift b/Sources/Shotdeck/PastSubmissionsView.swift index 50a3e89..f817a3f 100644 --- a/Sources/Shotdeck/PastSubmissionsView.swift +++ b/Sources/Shotdeck/PastSubmissionsView.swift @@ -2,36 +2,28 @@ 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). +/// "Past sessions" window: every retained session, whose captures they were, and +/// which PDF (if any) went out for them. Read-and-reveal only — the current session +/// is started/closed from the menu-bar panel and the button on the row below. struct PastSubmissionsView: View { @Environment(AppModel.self) private var model + @State private var searchText = "" 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) + emptyState } else { - ScrollView { - VStack(alignment: .leading, spacing: 6) { - ForEach(model.pastSessions) { session in - PastSessionRow(session: session) - } - } - } - .frame(maxHeight: 320) + searchField + sessionList } Divider() footer } - .padding(10) - .frame(width: 420, alignment: .leading) + .padding(12) + .frame(width: 460, alignment: .leading) .controlSize(.small) .task { if let problem = await model.reloadFromSpool() { @@ -40,21 +32,34 @@ struct PastSubmissionsView: View { } } + // MARK: - Current session + private var currentSessionRow: some View { - HStack(alignment: .center, spacing: 8) { + HStack(alignment: .top, spacing: 8) { VStack(alignment: .leading, spacing: 2) { - Text("Current session") + HStack(spacing: 6) { + Text("Current session") + .font(.caption) + .foregroundStyle(.secondary) + Spacer(minLength: 6) + Text(SessionDisplay.fullLabel(for: model.session)) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + Text(currentSessionSummary) + .fixedSize(horizontal: false, vertical: true) + Text(contextSummary) .font(.caption) .foregroundStyle(.secondary) - Text(currentSessionSummary) .fixedSize(horizontal: false, vertical: true) } Spacer(minLength: 8) - Button("Start new session") { + Button("New session") { Task { await model.startNewSession() } } .disabled(!model.canStartNewSession) - .help("Keeps these captures as a past session and starts a fresh one.") + .help("Keeps these captures as a past session and starts a fresh one. Nothing is deleted.") } } @@ -66,16 +71,101 @@ struct PastSubmissionsView: View { 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).") + private var contextSummary: String { + let summary = model.sessionContext.summaryLine + return summary.isEmpty ? "No lane or build recorded — add details in the menu panel." : summary + } + + // MARK: - List + + private var emptyState: some View { + Text("No past sessions yet. “New session” keeps the current captures and starts a fresh one.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, 12) + } + + private var searchField: some View { + HStack(spacing: 6) { + Image(systemName: "magnifyingglass") + .foregroundStyle(.secondary) + TextField("Search lane, build, commit, reviewer or file name", text: $searchText) + .textFieldStyle(.plain) + .font(.caption) + .onSubmit { } + if !searchText.isEmpty { + Button { + searchText = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel("Clear search") + } + } + .padding(.horizontal, 6) + .padding(.vertical, 4) + .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 5, style: .continuous)) + } + + private var filteredSessions: [CaptureSession] { + let needle = searchText.trimmingCharacters(in: .whitespaces).lowercased() + guard !needle.isEmpty else { return model.pastSessions } + return model.pastSessions.filter { session in + let haystack = [ + session.context.lane, + session.context.deployedVersion, + session.context.commit, + session.context.reviewer, + session.context.note, + session.pdfFileName ?? "", + SessionDisplay.fullLabel(for: session), + DubaiTime.stamp(session.createdAt), + ].joined(separator: " ").lowercased() + return haystack.contains(needle) + } + } + + @ViewBuilder + private var sessionList: some View { + let sessions = filteredSessions + if sessions.isEmpty { + Text("No session matches “\(searchText)”.") .font(.caption) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) + } else { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + ForEach(sessions) { session in + PastSessionRow(session: session) + Divider() + } + } + } + .frame(maxHeight: 340) + } + } + + // MARK: - Footer + + private var footer: some View { + HStack(alignment: .center, spacing: 8) { + VStack(alignment: .leading, spacing: 1) { + Text(model.retentionSummary) + .font(.caption) + Text("Sent PDFs are never deleted.") + .font(.caption) + .foregroundStyle(.secondary) + } Spacer(minLength: 8) - Button("Open sessions folder") { + Button("Sessions folder") { model.openSessionsFolder() } + .help("Open the folder that holds every kept session") } } } @@ -85,33 +175,49 @@ private struct PastSessionRow: View { let session: CaptureSession var body: some View { - HStack(alignment: .center, spacing: 8) { + HStack(alignment: .top, spacing: 10) { VStack(alignment: .leading, spacing: 2) { - Text(DubaiTime.stamp(session.createdAt)) + HStack(spacing: 6) { + Text(DubaiTime.stamp(session.createdAt)) + .monospacedDigit() + Text(SessionDisplay.fullLabel(for: session)) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + Text(contextLine) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) Text(submissionLabel) .font(.caption) - .foregroundStyle(session.pdfFileName == nil ? .secondary : .primary) - .lineLimit(1) } Spacer(minLength: 8) - Button("PDF") { - model.revealSentPDF(session) + VStack(alignment: .trailing, spacing: 4) { + Button("Reveal PDF") { + model.revealSentPDF(session) + } + .disabled(model.sentPDFURL(for: session) == nil) + .help(pdfHelpText) + Button("Captures") { + model.revealSessionCaptures(session) + } + .help("Reveal this session's screenshots") } - .disabled(model.sentPDFURL(for: session) == nil) - .help(pdfHelpText) - Button("Captures") { - model.revealSessionCaptures(session) - } - .help("Reveal this session's screenshots") } + .padding(.vertical, 6) } - 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)" + /// Everything recorded for the session except the lane, which the row's label + /// already shows: deployed build, commit, reviewer, note. + private var contextLine: String { + let context = session.context + var parts: [String] = [] + if !context.deployedVersion.isEmpty { parts.append(context.deployedVersion) } + if !context.commit.isEmpty { parts.append(context.commit) } + if !context.reviewer.isEmpty { parts.append(context.reviewer) } + if !context.note.isEmpty { parts.append("Note: \(context.note)") } + return parts.isEmpty ? "No build or commit recorded" : parts.joined(separator: " · ") } private var submissionLabel: String { @@ -121,6 +227,14 @@ private struct PastSessionRow: View { } return "\(pages) · sent as \(name)" } + + 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)" + } } extension AppModel: SubmissionsWindowPresenting { @@ -134,7 +248,7 @@ extension AppModel: SubmissionsWindowPresenting { } let hosting = NSHostingController(rootView: PastSubmissionsView().environment(self)) let window = NSWindow(contentViewController: hosting) - window.title = "Redline — Past submissions" + window.title = "Redline — Past sessions" window.styleMask = [.titled, .closable] window.isReleasedWhenClosed = false window.center() diff --git a/Sources/Shotdeck/SendController.swift b/Sources/Shotdeck/SendController.swift index f802dba..bd26135 100644 --- a/Sources/Shotdeck/SendController.swift +++ b/Sources/Shotdeck/SendController.swift @@ -150,7 +150,14 @@ extension AppModel: SendCapable { let finalURL = outboxDir.appendingPathComponent(fileName) // Same directory as the final target so the rename below is same-volume (atomic). let tempURL = outboxDir.appendingPathComponent(".shotdeck-\(UUID().uuidString).pdf") - let title = "Redline – \(DubaiTime.stamp(workingSession.createdAt))" + // The document title follows the same three parts as the file name: tool, + // lane (when recorded) and Dubai time. + let lane = workingSession.context.lane + let titleParts = ["Redline"] + + (lane.isEmpty ? [] : [lane]) + + [DubaiTime.stamp(Date())] + let title = titleParts.joined(separator: " – ") + let toolVersion = appVersion // D-13: build off the main actor. Only Sendable values cross into the // detached task — never `anchor` (NSView is not Sendable). @@ -159,7 +166,8 @@ extension AppModel: SendCapable { session: workingSession, imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) }, title: title, - to: tempURL + to: tempURL, + toolVersion: toolVersion ) // POSIX rename onto `finalURL` replaces any same-name file in one // directory operation; there is never a window where the PDF is gone. diff --git a/Sources/Shotdeck/SessionContextEditor.swift b/Sources/Shotdeck/SessionContextEditor.swift new file mode 100644 index 0000000..1131ded --- /dev/null +++ b/Sources/Shotdeck/SessionContextEditor.swift @@ -0,0 +1,98 @@ +import SwiftUI +import ShotdeckCore + +/// The five review-detail fields of a session, in one compact grid. +/// +/// Values are held locally while typing and written through to the session manifest +/// on every change, so closing the panel cannot lose them. The local copy is re-seeded +/// whenever the open session changes (a new session inherits the previous details). +struct SessionContextEditor: View { + @Environment(AppModel.self) private var model + + @State private var lane = "" + @State private var deployedVersion = "" + @State private var commitHash = "" + @State private var reviewer = "" + @State private var note = "" + @State private var seededSessionID: UUID? + /// What this view last wrote (or seeded). Lets an out-of-band change — a context + /// inherited by a new session, for example — refresh the fields without fighting + /// the user's own keystrokes. + @State private var lastKnownContext: ReviewContext = .empty + /// The pending debounced write and its value. Typing replaces it, so one short + /// pause writes once instead of once per keystroke, and an older write can never + /// land after a newer one. + @State private var pendingWrite: Task? + @State private var lastScheduledWrite: ReviewContext = .empty + + private let labelWidth: CGFloat = 84 + + var body: some View { + Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 4) { + row("Lane", text: $lane, prompt: "dev03, customer test lane…") + row("Deployed", text: $deployedVersion, prompt: "build that is live") + row("Commit", text: $commitHash, prompt: "git SHA") + row("Reviewer", text: $reviewer, prompt: "who is reviewing") + row("Note", text: $note, prompt: "what this session covers") + } + .onAppear { seedIfNeeded() } + .onChange(of: model.session.id) { _, _ in seedIfNeeded() } + .onChange(of: model.session.context) { _, newValue in + guard newValue != lastKnownContext else { return } + seed(from: newValue) + } + .onChange(of: lane) { _, _ in commit() } + .onChange(of: deployedVersion) { _, _ in commit() } + .onChange(of: commitHash) { _, _ in commit() } + .onChange(of: reviewer) { _, _ in commit() } + .onChange(of: note) { _, _ in commit() } + } + + private func row(_ label: String, text: Binding, prompt: String) -> some View { + GridRow(alignment: .center) { + Text(label) + .font(.caption) + .foregroundStyle(.secondary) + .frame(width: labelWidth, alignment: .trailing) + TextField(prompt, text: text) + .textFieldStyle(.roundedBorder) + .font(.caption) + .onSubmit { commit() } + } + } + + private func seedIfNeeded() { + guard seededSessionID != model.session.id else { return } + seededSessionID = model.session.id + seed(from: model.session.context) + } + + private func seed(from context: ReviewContext) { + lane = context.lane + deployedVersion = context.deployedVersion + commitHash = context.commit + reviewer = context.reviewer + note = context.note + lastKnownContext = context + } + + private func commit() { + let context = ReviewContext( + lane: lane, + deployedVersion: deployedVersion, + commit: commitHash, + reviewer: reviewer, + note: note + ) + guard context != model.session.context else { return } + guard context != lastScheduledWrite else { return } + lastKnownContext = context + lastScheduledWrite = context + pendingWrite?.cancel() + pendingWrite = Task { + try? await Task.sleep(for: .milliseconds(150)) + guard !Task.isCancelled else { return } + await model.setContextField(context) + } + } +} diff --git a/Sources/Shotdeck/SettingsView.swift b/Sources/Shotdeck/SettingsView.swift index 787332a..1827d8c 100644 --- a/Sources/Shotdeck/SettingsView.swift +++ b/Sources/Shotdeck/SettingsView.swift @@ -105,10 +105,52 @@ struct SettingsView: View { } GridRow { - Button("Reveal spool folder") { model.openSpoolFolder() } - .gridCellColumns(2) + Text("Sessions") + .font(.headline) .frame(maxWidth: .infinity, alignment: .leading) - .padding(.top, 4) + .gridCellColumns(2) + .padding(.top, 6) + } + + GridRow(alignment: .center) { + fieldLabel("Delete after") + Picker("Delete after", selection: retentionBinding) { + ForEach(SessionRetention.presets, id: \.self) { preset in + Text(preset.displayName).tag(preset) + } + } + .labelsHidden() + .pickerStyle(.menu) + .frame(maxWidth: .infinity, alignment: .leading) + } + + GridRow { + Text(retentionDetail) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .gridCellColumns(2) + } + + GridRow { + HStack(spacing: 8) { + Button("Clean up now") { + Task { await model.cleanUpExpiredSessions() } + } + .disabled(model.retention == .never) + Spacer(minLength: 0) + Button("Sessions folder") { model.openSessionsFolder() } + } + .gridCellColumns(2) + .frame(maxWidth: .infinity, alignment: .leading) + } + + GridRow { + Text("Only Redline's saved screenshots are removed. Sent PDFs are never touched.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .gridCellColumns(2) } } .padding(16) @@ -121,6 +163,25 @@ struct SettingsView: View { Binding(get: { model.transport }, set: { model.chooseTransport($0) }) } + private var retentionBinding: Binding { + Binding(get: { model.retention }, set: { value in + Task { await model.setRetention(value) } + }) + } + + /// States what the chosen limit does right now, using the real count of sessions + /// that have already expired — never a guess. + private var retentionDetail: String { + guard model.retention != .never else { + return "All sessions are kept. Nothing is deleted automatically." + } + let count = model.expiredSessionCount + if count == 0 { + return "No kept session is older than \(model.retention.displayName) yet." + } + return "\(count) session\(count == 1 ? " is" : "s are") already older than \(model.retention.displayName) and will be removed on the next launch or cleanup." + } + private func armHotkeyRecorder() { guard !isRecordingHotkey else { return } isRecordingHotkey = true diff --git a/Sources/Shotdeck/main.swift b/Sources/Shotdeck/main.swift index 3a32799..d8231f2 100644 --- a/Sources/Shotdeck/main.swift +++ b/Sources/Shotdeck/main.swift @@ -7,6 +7,12 @@ import ShotdeckCore if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil { MainActor.assumeIsolated { PanelSnapshot.runIfRequested() } } +if SelfTestLaunch.phase == "e2e" { + MainActor.assumeIsolated { PanelSelfTest.runE2EIfRequested() } +} +if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" { + MainActor.assumeIsolated { PanelSelfTest.runIfRequested() } +} if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" { MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() } } @@ -86,10 +92,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// point this at a temp directory instead of the real /// ~/Library/Application Support/Shotdeck — production always calls this with no /// argument (the real root). Internal, not private, for that same reason. - static func makeLaunchModel(appSupportRoot: URL? = nil) -> AppModel { + static func makeLaunchModel( + appSupportRoot: URL? = nil, + retentionDefaults: UserDefaults = .standard + ) -> AppModel { do { let paths = try TransportSettings.resolvedAppSupportPaths(root: appSupportRoot) - return try makeModel(paths: paths) + return try makeModel(paths: paths, retentionDefaults: retentionDefaults) } catch { Log.ui.critical( "AppModel init failed: \(String(describing: error), privacy: .public)" @@ -98,13 +107,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let fallbackRoot = tmp.appendingPathComponent("Shotdeck-fallback", isDirectory: true) // Safe: temp-dir creation for a path this process controls cannot legitimately fail. let fallback = try! AppSupportPaths(root: fallbackRoot, outbox: tmp, watchFolder: tmp) - let model = try! makeModel(paths: fallback) + let model = try! makeModel(paths: fallback, retentionDefaults: retentionDefaults) model.setStatus("Redline could not access its storage folder. Captures will not persist.") return model } } - private static func makeModel(paths: AppSupportPaths) throws -> AppModel { + private static func makeModel( + paths: AppSupportPaths, + retentionDefaults: UserDefaults + ) throws -> AppModel { let ledger = try ReturnLedger(paths: paths) return AppModel( paths: paths, @@ -114,7 +126,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { hotkeys: HotkeyCenter(), picker: RegionPickerController(), ledger: ledger, - watcher: ReturnWatcher(paths: paths, ledger: ledger) + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: retentionDefaults ) } } diff --git a/Sources/ShotdeckCore/Model/CaptureSession.swift b/Sources/ShotdeckCore/Model/CaptureSession.swift index b61a65d..9093e4f 100644 --- a/Sources/ShotdeckCore/Model/CaptureSession.swift +++ b/Sources/ShotdeckCore/Model/CaptureSession.swift @@ -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 ) } } diff --git a/Sources/ShotdeckCore/Model/ReviewContext.swift b/Sources/ShotdeckCore/Model/ReviewContext.swift new file mode 100644 index 0000000..a693951 --- /dev/null +++ b/Sources/ShotdeckCore/Model/ReviewContext.swift @@ -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)) + } +} diff --git a/Sources/ShotdeckCore/PDF/PDFComposer.swift b/Sources/ShotdeckCore/PDF/PDFComposer.swift index 5fbfbc8..057c819 100644 --- a/Sources/ShotdeckCore/PDF/PDFComposer.swift +++ b/Sources/ShotdeckCore/PDF/PDFComposer.swift @@ -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---.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, diff --git a/Sources/ShotdeckCore/PDF/PDFFileName.swift b/Sources/ShotdeckCore/PDF/PDFFileName.swift new file mode 100644 index 0000000..85f9a00 --- /dev/null +++ b/Sources/ShotdeckCore/PDF/PDFFileName.swift @@ -0,0 +1,54 @@ +import Foundation + +/// The PDF file-name scheme: +/// +/// Redline---.pdf +/// Redline--.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)" + } +} diff --git a/Sources/ShotdeckCore/PDF/PageLayout.swift b/Sources/ShotdeckCore/PDF/PageLayout.swift index 7cd7dfe..d2d8947 100644 --- a/Sources/ShotdeckCore/PDF/PageLayout.swift +++ b/Sources/ShotdeckCore/PDF/PageLayout.swift @@ -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 diff --git a/Sources/ShotdeckCore/Spool/SpoolStore.swift b/Sources/ShotdeckCore/Spool/SpoolStore.swift index 5ceff82..a6b025d 100644 --- a/Sources/ShotdeckCore/Spool/SpoolStore.swift +++ b/Sources/ShotdeckCore/Spool/SpoolStore.swift @@ -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 `/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 } diff --git a/Sources/ShotdeckCore/Support/DubaiTime.swift b/Sources/ShotdeckCore/Support/DubaiTime.swift index 2923f1f..deeef79 100644 --- a/Sources/ShotdeckCore/Support/DubaiTime.swift +++ b/Sources/ShotdeckCore/Support/DubaiTime.swift @@ -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) } diff --git a/Sources/ShotdeckCore/Support/RetentionSettings.swift b/Sources/ShotdeckCore/Support/RetentionSettings.swift new file mode 100644 index 0000000..df6a680 --- /dev/null +++ b/Sources/ShotdeckCore/Support/RetentionSettings.swift @@ -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) + } +} diff --git a/Tests/ShotdeckCoreTests/PDFComposerTests.swift b/Tests/ShotdeckCoreTests/PDFComposerTests.swift index 0b3987c..e1c8a9b 100644 --- a/Tests/ShotdeckCoreTests/PDFComposerTests.swift +++ b/Tests/ShotdeckCoreTests/PDFComposerTests.swift @@ -203,17 +203,123 @@ private func pixelWindow( return (pixelX0, pixelY0, pixelX1, pixelY1) } -@Test("fileName uses compose time, not session.createdAt, and matches Redline-yyyyMMdd-HHmmss.pdf") +@Test("fileName is Redline-yyyyMMdd-HHmm-SHORTID.pdf and uses compose time") func fileNameUsesComposeTimeNotSessionCreatedAt() { let old = Date(timeIntervalSince1970: 1_600_000_000) // 2020-09-13 let session = makeSession(captures: [], createdAt: old) let name = PDFComposer.fileName(for: session) - #expect(name.wholeMatch(of: /^Redline-\d{8}-\d{6}\.pdf$/) != nil) - #expect(!name.contains(DubaiTime.fileStamp(old))) - let today = String(DubaiTime.fileStamp(Date()).prefix(8)) + #expect(name.wholeMatch(of: /^Redline-\d{8}-\d{4}-[0-9A-F]{8}\.pdf$/) != nil) + #expect(name.contains(session.shortID)) + #expect(!name.contains(DubaiTime.fileMinuteStamp(old))) + let today = String(DubaiTime.fileMinuteStamp(Date()).prefix(8)) #expect(name.contains(today)) } +@Test("fileName carries the lane slug between the timestamp and the session id") +func fileNameCarriesTheLaneSlug() { + let session = CaptureSession( + id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!, + createdAt: fixtureDate, + state: .open, + captures: [], + pdfFileName: nil, + context: ReviewContext(lane: "OMS test lane")) + let name = PDFComposer.fileName(for: session) + #expect(name.wholeMatch(of: /^Redline-\d{8}-\d{4}-OMS-TEST-LANE-4F2A9C1D\.pdf$/) != nil) +} + +@Test("Review footer lines state the tool, date, session and the recorded review details") +func footerLinesStateTheReviewDetails() { + let session = CaptureSession( + id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!, + createdAt: fixtureDate, + state: .open, + captures: [], + pdfFileName: nil, + context: ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout")) + let lines = PDFComposer.footerLines( + session: session, toolVersion: "0.5.0", composedAt: fixtureDate) + #expect(lines.count == 2) + #expect(lines[0].contains("Redline 0.5.0")) + #expect(lines[0].contains("Session 4F2A9C1D")) + #expect(lines[0].contains(DubaiTime.stamp(fixtureDate))) + #expect(lines[1].contains("Lane dev03")) + #expect(lines[1].contains("Deployed v1.4.2 (41)")) + #expect(lines[1].contains("Commit a1b2c3d4")) + #expect(lines[1].contains("Reviewer Ben Hippler")) + #expect(lines[1].contains("Note checkout")) + + // A session with no recorded details still identifies itself; nothing is faked. + let bare = makeSession(captures: []) + let bareLines = PDFComposer.footerLines( + session: bare, toolVersion: "", composedAt: fixtureDate) + #expect(bareLines.count == 1) + #expect(bareLines[0].hasPrefix("Redline · ")) +} + +@Test("Document info carries the reviewer and the lane/build/commit keywords") +func documentInfoCarriesTheReviewDetails() { + let session = CaptureSession( + id: UUID(uuidString: "deadbeef-dead-4eef-8ead-deadbeef0001")!, + createdAt: fixtureDate, + state: .open, + captures: [], + pdfFileName: nil, + context: ReviewContext( + lane: "DEV03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout")) + let info = PDFComposer.documentInfo( + session: session, title: "Redline – DEV03", toolVersion: "0.5.0", composedAt: fixtureDate) + + #expect(info[kCGPDFContextAuthor as String] as? String == "Ben Hippler") + #expect(info[kCGPDFContextCreator as String] as? String == "Redline 0.5.0") + let keywords = try? #require(info[kCGPDFContextKeywords as String] as? String) + #expect(keywords?.contains("lane=DEV03") == true) + #expect(keywords?.contains("deployed=v1.4.2") == true) + #expect(keywords?.contains("commit=a1b2c3d4") == true) + #expect(keywords?.contains("reviewer=Ben Hippler") == true) + #expect(keywords?.contains("built=\(DubaiTime.keywordStamp(fixtureDate))") == true) +} + +@Test("A composed PDF carries the footer text and document info a reader can see") +func composedPDFCarriesTheReferenceBlock() throws { + let directory = try makeScratchDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + + let capture = makeCapture(sequence: 1, pixelWidth: 800, pixelHeight: 600) + let png = try writePNG(for: capture, red: 60, green: 60, blue: 60, in: directory) + let session = CaptureSession( + id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!, + createdAt: fixtureDate, + state: .open, + captures: [capture], + pdfFileName: nil, + context: ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout")) + let output = directory.appendingPathComponent("footer.pdf") + _ = try PDFComposer().compose( + session: session, + imageURL: { _ in png }, + title: "Redline – dev03", + to: output, + toolVersion: "0.5.0", + composedAt: fixtureDate + ) + + let document = try openDocument(output) + let pageText = try #require(document.page(at: 0)?.string ?? "") + #expect(pageText.contains("Redline 0.5.0")) + #expect(pageText.contains("Lane dev03")) + #expect(pageText.contains("Commit a1b2c3d4")) + #expect(pageText.contains("Ben Hippler")) + + let attributes = try #require(document.documentAttributes) + #expect(attributes[PDFDocumentAttribute.authorAttribute] as? String == "Ben Hippler") +} + @Test("Three-page basic compose") func threePageBasicCompose() throws { let directory = try makeScratchDirectory() diff --git a/Tests/ShotdeckCoreTests/SessionNamingAndRetentionSettingsTests.swift b/Tests/ShotdeckCoreTests/SessionNamingAndRetentionSettingsTests.swift new file mode 100644 index 0000000..8187c50 --- /dev/null +++ b/Tests/ShotdeckCoreTests/SessionNamingAndRetentionSettingsTests.swift @@ -0,0 +1,138 @@ +import Foundation +import ShotdeckCore +import Testing + +// PDF naming scheme + the persisted session age limit. + +// MARK: - PDF file names + +@Test +func laneSlugKeepsLettersDigitsAndSingleDashes() { + #expect(PDFFileName.laneSlug("OMS test lane") == "OMS-TEST-LANE") + #expect(PDFFileName.laneSlug(" dev03 ") == "DEV03") + #expect(PDFFileName.laneSlug("v1.4.2 / stage") == "V1-4-2-STAGE") + #expect(PDFFileName.laneSlug("") == "") + #expect(PDFFileName.laneSlug("--") == "") +} + +@Test +func laneSlugIsCappedSoTheFileNameStaysShort() { + let long = String(repeating: "abcdefghij", count: 5) + let slug = PDFFileName.laneSlug(long) + #expect(slug.count == PDFFileName.laneMaxLength) + #expect(!slug.hasSuffix("-")) +} + +@Test +func fileNameIsSortableAndUniquePerSession() { + let sessionID = UUID(uuidString: "4F2A9C1D-0000-4000-8000-000000000000")! + let builtAt = Date(timeIntervalSince1970: 1_777_482_180) + + let withLane = PDFFileName.make(builtAt: builtAt, lane: "dev03", sessionID: sessionID) + #expect(withLane == "Redline-\(DubaiTime.fileMinuteStamp(builtAt))-DEV03-4F2A9C1D.pdf") + + let withoutLane = PDFFileName.make(builtAt: builtAt, lane: "", sessionID: sessionID) + #expect(withoutLane == "Redline-\(DubaiTime.fileMinuteStamp(builtAt))-4F2A9C1D.pdf") + + // Two sessions in the same minute never collide. + let other = UUID(uuidString: "9B8C7D6E-0000-4000-8000-000000000000")! + #expect(PDFFileName.make(builtAt: builtAt, lane: "dev03", sessionID: other) + != withLane) +} + +@Test +func sessionLabelIsLaneOrShortID() { + let id = UUID(uuidString: "4F2A9C1D-0000-4000-8000-000000000000")! + #expect(PDFFileName.sessionLabel(lane: "dev03", sessionID: id) == "DEV03-4F2A9C1D") + #expect(PDFFileName.sessionLabel(lane: "", sessionID: id) == "4F2A9C1D") +} + +// MARK: - Retention setting + +@Test +func retentionDefaultsToNever() throws { + let suite = try makeDefaults() + defer { suite.defaults.removePersistentDomain(forName: suite.name) } + + #expect(RetentionSettings.load(defaults: suite.defaults) == .never) + #expect(RetentionSettings.load(defaults: suite.defaults).cutoff() == nil) +} + +@Test +func retentionRoundTripsThroughDefaults() throws { + let suite = try makeDefaults() + defer { suite.defaults.removePersistentDomain(forName: suite.name) } + + RetentionSettings.save(.days(30), defaults: suite.defaults) + #expect(RetentionSettings.load(defaults: suite.defaults) == .days(30)) + + RetentionSettings.save(.never, defaults: suite.defaults) + #expect(RetentionSettings.load(defaults: suite.defaults) == .never) + #expect(suite.defaults.object(forKey: RetentionSettings.defaultsKey) == nil) +} + +@Test +func retentionCutoffIsTheDayCountBeforeNow() { + let now = Date(timeIntervalSince1970: 1_777_482_180) + let cutoff = try? #require(SessionRetention.days(30).cutoff(now: now)) + let expected = Calendar(identifier: .gregorian).date(byAdding: .day, value: -30, to: now) + #expect(cutoff == expected) +} + +@Test +func retentionPresetsReadAsPlainEnglish() { + #expect(SessionRetention.never.displayName == "Never (default)") + #expect(SessionRetention.days(7).displayName == "7 days") + #expect(SessionRetention.days(365).displayName == "1 year") + #expect(SessionRetention.never.policyDescription == "All sessions kept.") + #expect(SessionRetention.days(14).policyDescription == "Sessions older than 14 days are deleted.") +} + +// MARK: - Review context + +@Test +func reviewContextTrimsCapsAndCollapsesLineBreaks() { + let long = String(repeating: "x", count: ReviewContext.maxFieldLength + 40) + let context = ReviewContext( + lane: " dev03 ", deployedVersion: "v1.4.2\n(build 41)", commit: " a1b2c3d4 ", + reviewer: "Ben Hippler", note: long) + #expect(context.lane == "dev03") + #expect(context.deployedVersion == "v1.4.2 (build 41)") + #expect(context.commit == "a1b2c3d4") + #expect(context.note.count == ReviewContext.maxFieldLength) +} + +@Test +func reviewContextSummaryDropsEmptyParts() { + #expect(ReviewContext(lane: "dev03", commit: "a1b2c3d4").summaryLine == "dev03 · a1b2c3d4") + #expect(ReviewContext().summaryLine == "") + #expect(ReviewContext().isEmpty) +} + +@Test +func reviewContextDecodesPartialJSON() throws { + let json = Data(#"{"lane":"dev03","commit":"a1b2c3d4"}"#.utf8) + let context = try JSONDecoder().decode(ReviewContext.self, from: json) + #expect(context.lane == "dev03") + #expect(context.commit == "a1b2c3d4") + #expect(context.reviewer == "") + #expect(context.note == "") +} + +// MARK: - Fixtures + +private struct DefaultsSuite { + let name: String + let defaults: UserDefaults +} + +private func makeDefaults() throws -> DefaultsSuite { + let name = "shotdeck-retention-settings-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: name) else { + throw SettingsFixtureError.noSuite + } + defaults.removePersistentDomain(forName: name) + return DefaultsSuite(name: name, defaults: defaults) +} + +private enum SettingsFixtureError: Error { case noSuite } diff --git a/Tests/ShotdeckCoreTests/SessionRetentionTests.swift b/Tests/ShotdeckCoreTests/SessionRetentionTests.swift index 6a6b68b..a3ca528 100644 --- a/Tests/ShotdeckCoreTests/SessionRetentionTests.swift +++ b/Tests/ShotdeckCoreTests/SessionRetentionTests.swift @@ -4,9 +4,9 @@ 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. +// Session lifecycle + retention: "Start new session" keeps the current screenshots as +// a past session; every session is kept by default, and an age limit chosen in +// Settings is the only thing that ever removes one. // MARK: - 1. closeCurrentSession keeps the captures as a past session @@ -95,14 +95,16 @@ func pastSessionsDistinguishSentFromUnsentByPDFFileName() async throws { #expect(past.map(\.pdfFileName) == [nil, "Redline-20261011-120000.pdf"]) } -// MARK: - 4. retention keeps the newest 10 sessions, in the one archive folder +// MARK: - 4. nothing is deleted by default @Test -func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws { +func defaultPolicyKeepsEverySession() async throws { let (root, paths) = try makeIsolatedPaths() defer { try? FileManager.default.removeItem(at: root) } let store = try SpoolStore(paths: paths) + #expect(await store.configuredRetention() == .never) + var closedIDs: [UUID] = [] for index in 0..<12 { _ = try await store.append( @@ -113,78 +115,141 @@ func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws { closedIDs.append(closed.id) } - // All 12 sessions live in the single archive/ folder as UUID session folders. + // All 12 sessions live on in the single archive/ folder; none was pruned. 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) + #expect(sessionDirs.count == closedIDs.count) let kept = try await store.archivedSessions().map(\.id) - #expect(kept == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed())) + #expect(kept == closedIDs.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) { + for id in closedIDs { #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)) + // A prune under the default policy removes nothing at all. + #expect(try await store.pruneExpiredSessions().isEmpty) + #expect(try await store.expiredSessionIDs().isEmpty) } -// MARK: - 5. explicit prune keeps exactly the requested count +// MARK: - 5. an age limit removes exactly the expired sessions @Test -func pruneArchivedSessionsKeepingNRemovesExactlyTheOldest() async throws { +func ageLimitRemovesOnlySessionsOlderThanTheCutoff() 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 now = Date(timeIntervalSince1970: 1_700_000_000) // fixed "now" for the test + let day: TimeInterval = 86_400 + let oldIDs = try [ + try writeArchivedSession(createdAt: now.addingTimeInterval(-40 * day), in: paths), + try writeArchivedSession(createdAt: now.addingTimeInterval(-31 * day), in: paths), + ] + let recentIDs = try [ + try writeArchivedSession(createdAt: now.addingTimeInterval(-29 * day), in: paths), + try writeArchivedSession(createdAt: now.addingTimeInterval(-1 * day), in: paths), + ] + + let store = try SpoolStore(paths: paths, retention: .days(30)) + + // Asking what would happen deletes nothing. + #expect(Set(try await store.expiredSessionIDs(now: now)) == Set(oldIDs)) + #expect(try await store.archivedSessions().count == 4) + + let removed = try await store.pruneExpiredSessions(now: now) + #expect(Set(removed) == Set(oldIDs)) + + let fm = FileManager.default + for id in oldIDs { + #expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path)) + } + for id in recentIDs { + #expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path)) } - 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) + // The open session is never a candidate, and a second pass is a no-op. + #expect(try await store.currentSession().state == .open) + #expect(try await store.pruneExpiredSessions(now: now).isEmpty) } -// MARK: - 6. retention runs on the send path too +// MARK: - 6. the archive path applies the configured age limit @Test -func theSendArchivePathAppliesRetention() async throws { +func theArchivePathAppliesTheAgeLimit() 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 day: TimeInterval = 86_400 + let expiredID = try writeArchivedSession( + createdAt: Date().addingTimeInterval(-10 * day), in: paths) + + let store = try SpoolStore(paths: paths, retention: .days(7)) + _ = 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()) + let archived = try await store.archiveCurrent(pdfFileName: "Redline-20261031-1200-A1B2C3D4.pdf") 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 }) + #expect(kept.map(\.id) == [archived.id]) + #expect(!FileManager.default.fileExists(atPath: paths.archiveDirectory(expiredID).path)) +} + +// MARK: - 7. review context is persisted, survives a relaunch and is inherited + +@Test +func reviewContextPersistsAndIsInheritedByTheNextSession() async throws { + let (root, paths) = try makeIsolatedPaths() + defer { try? FileManager.default.removeItem(at: root) } + + let store = try SpoolStore(paths: paths) + let context = ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout flow") + + let updated = try await store.setContext(context) + #expect(updated.context == context) + + // A second store on the same directory is what a relaunch sees. + let reopened = try SpoolStore(paths: paths) + #expect(try await reopened.currentSession().context == context) + + _ = try await store.append( + pngData: try makePNGData(width: 4, height: 4, red: 0.4, green: 0.4, blue: 0.4), + pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date()) + let archived = try #require(try await store.closeCurrentSession()) + #expect(archived.context == context) + + // The fresh session keeps the same review details. + #expect(try await store.currentSession().context == context) +} + +// MARK: - 8. a manifest written before contexts existed still loads + +@Test +func legacyManifestWithoutContextDecodesAsEmptyContext() async throws { + let (root, paths) = try makeIsolatedPaths() + defer { try? FileManager.default.removeItem(at: root) } + + let id = UUID() + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let legacyJSON = """ + { + "id": "\(id.uuidString)", + "createdAt": "2026-10-11T12:00:00Z", + "state": "archived", + "captures": [], + "pdfFileName": "Redline-20261011-120000.pdf" + } + """ + try Data(legacyJSON.utf8).write(to: dir.appendingPathComponent("session.json")) + + let store = try SpoolStore(paths: paths) + let sessions = try await store.archivedSessions() + #expect(sessions.map(\.id) == [id]) + #expect(sessions.first?.context == .empty) + #expect(sessions.first?.pdfFileName == "Redline-20261011-120000.pdf") } // MARK: - 7. a stale open session is never returned as current (truth guard) @@ -218,6 +283,28 @@ func aStaleOpenSessionIsNeverReturnedAsCurrent() async throws { // MARK: - Fixtures +/// Writes an archived session folder with the given creation date, exactly the shape +/// production writes (a manifest plus one PNG), so retention can be exercised without +/// waiting days. +private func writeArchivedSession(createdAt: Date, in paths: AppSupportPaths) throws -> UUID { + let id = UUID() + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let pngName = "001-A1B2C3D4.png" + try makePNGData(width: 4, height: 4, red: 0.5, green: 0.5, blue: 0.5) + .write(to: dir.appendingPathComponent(pngName)) + let capture = Capture( + id: UUID(), sequence: 1, fileName: pngName, + pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: createdAt) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .archived, captures: [capture], + pdfFileName: "Redline-\(DubaiTime.fileMinuteStamp(createdAt)).pdf") + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) + return id +} + private enum FixtureError: Error { case pngGenerationFailed } diff --git a/Tests/ShotdeckTests/SessionWorkflowTests.swift b/Tests/ShotdeckTests/SessionWorkflowTests.swift index 2fe3f88..3a8770a 100644 --- a/Tests/ShotdeckTests/SessionWorkflowTests.swift +++ b/Tests/ShotdeckTests/SessionWorkflowTests.swift @@ -6,15 +6,15 @@ 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. +/// 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 sessions state reflects what was sent, every session is kept by default, +/// and a chosen age limit is what removes one. `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 { +@Test("Menu actions: start new session keeps captures and lists past submissions") +func startNewSessionKeepsCapturesAndListsPastSessions() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) @@ -51,8 +51,8 @@ func startNewSessionKeepsCapturesListsPastSubmissionsAndRetainsTen() async throw } @MainActor -@Test("Retention: 12 sessions through the menu action leave the newest 10 on disk") -func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() async throws { +@Test("Retention: 12 sessions through the menu action are all kept by default") +func twelveSessionsStayOnDiskByDefault() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) @@ -66,16 +66,91 @@ func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() async throws { await model.startNewSession() } - #expect(model.pastSessions.count == SpoolStore.defaultRetainedSessionCount) - #expect(model.pastSessions.map(\.id) - == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed())) + #expect(model.retention == .never) + #expect(model.pastSessions.map(\.id) == closedIDs.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)) + #expect(sessionDirs.count == closedIDs.count) + for id in closedIDs { + #expect(fm.fileExists(atPath: model.paths.archiveDirectory(id).path)) } + #expect(model.expiredSessionCount == 0) +} + +@MainActor +@Test("A review detail typed in the panel is saved and inherited by the next session") +func reviewDetailsPersistThroughTheModel() 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 context = ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout") + await model.setContextField(context) + #expect(model.session.context == context) + #expect(model.sessionContext.summaryLine == "dev03 · v1.4.2 · a1b2c3d4 · Ben Hippler") + #expect(model.nextPDFFileNameHint.contains("-DEV03-")) + + _ = try await addCapture(to: model, red: 0.1, green: 0.4, blue: 0.9) + await model.startNewSession() + + // The closed session keeps its details; the new one inherits them. + #expect(model.pastSessions.first?.context == context) + #expect(model.session.context == context) +} + +@MainActor +@Test("Settings age limit: cleanup removes only expired sessions, never a sent PDF") +func cleanUpHonorsTheAgeLimit() 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 suite = try makeIsolatedDefaults() + defer { suite.defaults.removePersistentDomain(forName: suite.name) } + let model = AppDelegate.makeLaunchModel( + appSupportRoot: root, retentionDefaults: suite.defaults) + await model.bootstrap() + + // One real session that was sent (its PDF is in the outbox) … + _ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2) + let sentName = "Redline-20261001-0900-A1B2C3D4.pdf" + _ = try await model.spool.archiveCurrent(pdfFileName: sentName) + try Data("%PDF-1.4\n% test\n".utf8) + .write(to: model.paths.outbox.appendingPathComponent(sentName)) + + // … and one archived session backdated past the limit, written in the exact shape + // production writes, so the age comparison runs against real manifest dates. + let expiredID = try await writeBackdatedSession(in: model.paths, daysAgo: 40) + await model.reloadFromSpool() + + #expect(model.pastSessions.count == 2) + + // Nothing expires under .never, even with a cleanup. + await model.cleanUpExpiredSessions() + #expect(model.pastSessions.count == 2) + #expect(model.expiredSessionCount == 0) + #expect(model.statusLine?.contains("Nothing to remove") == true) + + // A 30-day limit expires only the backdated session, and says so before deleting. + await model.setRetention(.days(30)) + #expect(model.retention == .days(30)) + #expect(RetentionSettings.load(defaults: suite.defaults) == .days(30)) + #expect(model.expiredSessionCount == 1) + + await model.cleanUpExpiredSessions() + #expect(model.pastSessions.count == 1) + #expect(model.statusLine?.contains("Removed 1 past session") == true) + #expect(!fm.fileExists(atPath: model.paths.archiveDirectory(expiredID).path)) + #expect(fm.fileExists(atPath: model.paths.outbox.appendingPathComponent(sentName).path)) + + // Back to the default in this isolated suite, so the next test starts clean. + await model.setRetention(.never) + #expect(model.expiredSessionCount == 0) } @MainActor @@ -191,6 +266,49 @@ private enum FixtureError: Error { case pngGenerationFailed } +// MARK: - Fixtures + +private struct IsolatedDefaults { + let name: String + let defaults: UserDefaults +} + +/// A throwaway UserDefaults suite — never `.standard` — so the age-limit setting a +/// test writes can never change Ben's real app preference. +private func makeIsolatedDefaults() throws -> IsolatedDefaults { + let name = "shotdeck-session-workflow-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: name) else { + throw FixtureError.pngGenerationFailed + } + defaults.removePersistentDomain(forName: name) + return IsolatedDefaults(name: name, defaults: defaults) +} + +/// Writes an archived session folder dated `daysAgo` days in the past, in the exact +/// on-disk shape the store produces, so an age policy can act on a real manifest date. +@discardableResult +private func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) async throws -> UUID { + let id = UUID() + let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400) + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png" + try makePNGData(width: 8, height: 8, red: 0.3, green: 0.3, blue: 0.3) + .write(to: dir.appendingPathComponent(pngName)) + let capture = Capture( + id: UUID(), sequence: 1, fileName: pngName, + pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: createdAt) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .archived, captures: [capture], + pdfFileName: nil, + context: ReviewContext(lane: "DEV03", deployedVersion: "v1.0.0", commit: "abc1234")) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) + return id +} + + private func makePNGData( width: Int, height: Int, diff --git a/scripts/render-panels.sh b/scripts/render-panels.sh new file mode 100755 index 0000000..ae85a8b --- /dev/null +++ b/scripts/render-panels.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Renders the headless panel PNGs and a sample review PDF for visual verification. +# +# ./scripts/render-panels.sh [output-directory] +# +# Builds nothing: run `swift build` (or ./scripts/build-app.sh) first. The output +# directory is printed at the end; nothing outside it is touched, and the isolated +# model means the real Application Support spool and the real age-limit preference +# are never read or written. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +OUT_DIR="${1:-$(mktemp -d /tmp/redline-panels.XXXXXX)}" +BINARY="${ROOT}/.build/Redline.app/Contents/MacOS/Shotdeck" + +if [[ ! -x "${BINARY}" ]]; then + BINARY="${ROOT}/.build/debug/Shotdeck" +fi +if [[ ! -x "${BINARY}" ]]; then + echo "No Shotdeck binary found. Run swift build or ./scripts/build-app.sh first." >&2 + exit 1 +fi + +mkdir -p "${OUT_DIR}" +SHOTDECK_SNAPSHOT_DIR="${OUT_DIR}" "${BINARY}" +echo "Panels written to ${OUT_DIR}" diff --git a/scripts/run-e2e-ui.sh b/scripts/run-e2e-ui.sh new file mode 100755 index 0000000..a6b6eeb --- /dev/null +++ b/scripts/run-e2e-ui.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +# End-to-end UI run: the real panel, in the ACTIVE app, typed into with the keyboard +# and clicked with the mouse. Launched through LaunchServices ("open -n") because a +# background shell launch can never get a key window — macOS will not let it activate. +# +# ./scripts/run-e2e-ui.sh +# +# Builds a throwaway copy of the signed app under a separate bundle identifier +# (ai.flowmaster.shotdeck.e2e) so it can run alongside the installed Redline without +# touching /Applications, Ben's real captures, or his real preferences. It writes its +# results to a file and exits. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SOURCE_APP="${ROOT}/.build/Redline.app" +E2E_APP="${ROOT}/.build/RedlineE2E.app" +IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)" +BUNDLE_ID="ai.flowmaster.shotdeck.e2e" +WORK_DIR="$(mktemp -d /tmp/redline-e2e.XXXXXX)" +RESULT="${WORK_DIR}/result.txt" + +if [[ ! -d "${SOURCE_APP}" ]]; then + echo "No ${SOURCE_APP} found. Run ./scripts/build-app.sh first." >&2 + exit 1 +fi + +# A leftover instance from an interrupted run would hold the bundle identifier and +# make "open -n" a no-op. +pkill -f "RedlineE2E.app/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || true +for _ in $(seq 1 20); do + pgrep -f "RedlineE2E.app/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || break + sleep 0.2 +done +rm -rf "${E2E_APP}" +ditto "${SOURCE_APP}" "${E2E_APP}" +/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${BUNDLE_ID}" "${E2E_APP}/Contents/Info.plist" +/usr/libexec/PlistBuddy -c "Set :CFBundleName Redline E2E" "${E2E_APP}/Contents/Info.plist" +# A menu-bar app (LSUIElement) is never activated by LaunchServices, and macOS only +# lets an active app own the key window the keyboard goes to. The test copy is a +# regular app for the duration of the run; the shipped app keeps LSUIElement. +/usr/libexec/PlistBuddy -c "Set :LSUIElement false" "${E2E_APP}/Contents/Info.plist" +codesign --force --options runtime \ + --sign "${IDENTITY}" \ + --identifier "${BUNDLE_ID}" \ + "${E2E_APP}" + +open -n "${E2E_APP}" --args --selftest e2e --root "${WORK_DIR}/storage" --result "${RESULT}" + +for _ in $(seq 1 120); do + if [[ -f "${RESULT}" ]] && grep -qE "^E2E (PASS|FAIL)$" "${RESULT}"; then + break + fi + sleep 0.25 +done + +sleep 0.5 +osascript -e "tell application id \"${BUNDLE_ID}\" to quit" >/dev/null 2>&1 || true + +if [[ ! -f "${RESULT}" ]]; then + echo "E2E FAIL: no result file was written (${RESULT})" >&2 + exit 1 +fi + +cat "${RESULT}" +grep -q "^E2E PASS$" "${RESULT}" diff --git a/scripts/run-selftest.sh b/scripts/run-selftest.sh new file mode 100755 index 0000000..43b0565 --- /dev/null +++ b/scripts/run-selftest.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Runs one in-process self-test phase against the built binary. +# +# ./scripts/run-selftest.sh panel +# ./scripts/run-selftest.sh onedrive +# ./scripts/run-selftest.sh sendtruth +# +# Prints the phase's PASS/FAIL lines and exits with the binary's status. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PHASE="${1:-panel}" +BINARY="${ROOT}/.build/Redline.app/Contents/MacOS/Shotdeck" + +if [[ ! -x "${BINARY}" ]]; then + BINARY="${ROOT}/.build/debug/Shotdeck" +fi +if [[ ! -x "${BINARY}" ]]; then + echo "No Shotdeck binary found. Run swift build or ./scripts/build-app.sh first." >&2 + exit 1 +fi + +REDLINE_SELFTEST_PHASE="${PHASE}" "${BINARY}"