feat(sessions): keep every session, record review details, name and stamp the PDF

Sessions are now the unit of the product instead of an implicit capture run.

- Nothing is deleted by default: the fixed 10-session cap is gone. An age limit
  (Never / 7 / 14 / 30 / 90 / 180 / 365 days) is chosen in Settings > Sessions and
  applied on launch, after archiving, and by "Clean up now". Sent PDFs are never
  touched.
- Each session carries review details: lane, deployed version, commit, reviewer
  (pre-filled with the Mac user) and a free note. They persist in session.json and
  are inherited by the next session, so a review run is typed once.
- PDF file names are Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf, and every page
  carries a two-line reference footer (tool, build time, session / lane, deployed
  build, commit, reviewer, note). The PDF document info carries the same values in
  Author and Keywords.
- Verification: 159 tests, a headless panel self-test, and a LaunchServices-driven
  end-to-end run that types and clicks the real panel.
This commit is contained in:
Claude Fable 5
2026-10-31 11:32:54 +04:00
parent 542aad296b
commit 02fa791b78
26 changed files with 2780 additions and 279 deletions
+109 -1
View File
@@ -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: " ")
}
+248 -86
View File
@@ -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)"
}
}
+777
View File
@@ -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 <phase> [--root <dir>] [--result <file>].
/// 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 <app> --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 }
}
+53 -3
View File
@@ -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)
+159 -45
View File
@@ -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()
+10 -2
View File
@@ -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.
@@ -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<Void, Never>?
@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<String>, 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)
}
}
}
+64 -3
View File
@@ -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<SessionRetention> {
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
+18 -5
View File
@@ -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
)
}
}