Compare commits

..
24 changed files with 1118 additions and 2571 deletions
+2 -2
View File
@@ -13,9 +13,9 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>0.3.1</string> <string>0.2.0</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>4</string> <string>2</string>
<key>LSMinimumSystemVersion</key> <key>LSMinimumSystemVersion</key>
<string>14.0</string> <string>14.0</string>
<key>LSUIElement</key> <key>LSUIElement</key>
-9
View File
@@ -27,14 +27,5 @@ let package = Package(
dependencies: ["ShotdeckCore"], dependencies: ["ShotdeckCore"],
swiftSettings: [.swiftLanguageMode(.v6)] swiftSettings: [.swiftLanguageMode(.v6)]
), ),
// Exercises the real Shotdeck-app-target wiring (AppDelegate.makeLaunchModel(),
// AppModel.bootstrap()) via @testable import logic ShotdeckCoreTests cannot
// reach because it only depends on ShotdeckCore, not the Shotdeck executable
// target itself. See ReturnWatcherLaunchWiringTests.swift.
.testTarget(
name: "ShotdeckTests",
dependencies: ["Shotdeck", "ShotdeckCore"],
swiftSettings: [.swiftLanguageMode(.v6)]
),
] ]
) )
+15 -100
View File
@@ -28,19 +28,10 @@ public final class AppModel {
public private(set) var allReturns: [ReturnedDocument] = [] public private(set) var allReturns: [ReturnedDocument] = []
public private(set) var commentedReturns: [ReturnedDocument] = [] public private(set) var commentedReturns: [ReturnedDocument] = []
public private(set) var statusLine: String? public private(set) var statusLine: String?
public private(set) var updateStatus: String?
public private(set) var isCapturing: Bool = false public private(set) var isCapturing: Bool = false
public private(set) var isSending: Bool = false public private(set) var isSending: Bool = false
public private(set) var outboxDisplayName: String public private(set) var outboxDisplayName: String
public private(set) var watchFolderDisplayName: String public private(set) var watchFolderDisplayName: String
/// Live transport choice; WP-onedrive reads this to pick the send path and to drive
/// the Settings "Send via" picker and the menu's "Send" label.
public private(set) var transport: SendTransport
/// Ground truth for the Settings OneDrive row: nil means "no OneDrive folder found".
/// Views read this instead of calling `OneDriveLocator.resolveOneDriveFolder()`
/// directly, so state (and testing with a fake home) flows through the model like
/// everything else never a View reaching past the model for real UserDefaults/home.
public private(set) var resolvedOneDriveFolder: URL?
/// Live outbox; WP-4b reads this (not `paths.outbox`) so Settings folder changes take effect. /// Live outbox; WP-4b reads this (not `paths.outbox`) so Settings folder changes take effect.
public private(set) var outboxURL: URL public private(set) var outboxURL: URL
/// Live watch folder; WP-4c updates this alongside `ReturnWatcher.updateWatchFolder`. /// Live watch folder; WP-4c updates this alongside `ReturnWatcher.updateWatchFolder`.
@@ -52,8 +43,6 @@ public final class AppModel {
var hotkeyDisplayString: String { captureHotkey.displayString } var hotkeyDisplayString: String { captureHotkey.displayString }
/// Staged update offered in the menu. Set only after checksum + payload validation. /// Staged update offered in the menu. Set only after checksum + payload validation.
public private(set) var updateAvailable: (version: String, notes: String)? public private(set) var updateAvailable: (version: String, notes: String)?
/// True for the duration of any appcast check (manual or scheduled).
public private(set) var isCheckingForUpdates: Bool = false
let paths: AppSupportPaths let paths: AppSupportPaths
let spool: SpoolStore let spool: SpoolStore
@@ -63,6 +52,7 @@ public final class AppModel {
let picker: RegionPickerController let picker: RegionPickerController
let ledger: ReturnLedger let ledger: ReturnLedger
let watcher: ReturnWatcher let watcher: ReturnWatcher
let historyStore: HistoryStore
let updateChecker: UpdateChecker let updateChecker: UpdateChecker
public init( public init(
@@ -74,7 +64,7 @@ public final class AppModel {
picker: RegionPickerController, picker: RegionPickerController,
ledger: ReturnLedger, ledger: ReturnLedger,
watcher: ReturnWatcher watcher: ReturnWatcher
) { ) throws {
self.paths = paths self.paths = paths
self.spool = spool self.spool = spool
self.composer = composer self.composer = composer
@@ -83,6 +73,7 @@ public final class AppModel {
self.picker = picker self.picker = picker
self.ledger = ledger self.ledger = ledger
self.watcher = watcher self.watcher = watcher
self.historyStore = try HistoryStore(paths: paths)
self.session = CaptureSession( self.session = CaptureSession(
id: UUID(), id: UUID(),
createdAt: Date(), createdAt: Date(),
@@ -92,39 +83,26 @@ public final class AppModel {
) )
self.region = Self.loadPersistedRegion() self.region = Self.loadPersistedRegion()
self.screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted self.screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted
// Seeded from TransportSettings.effectiveFolders() the one place that combines // Seeded from FolderSettings.resolve() via resolvedAppSupportPaths never .standard().
// the transport choice with FolderSettings/OneDriveLocator. Never call let folders = FolderSettings.resolve()
// FolderSettings.resolve() directly outside that function.
let folders = TransportSettings.effectiveFolders()
self.outboxURL = folders.outbox self.outboxURL = folders.outbox
self.watchFolderURL = folders.watch self.watchFolderURL = folders.watch
self.outboxDisplayName = folders.outbox.lastPathComponent self.outboxDisplayName = folders.outbox.lastPathComponent
self.watchFolderDisplayName = folders.watch.lastPathComponent self.watchFolderDisplayName = folders.watch.lastPathComponent
self.transport = folders.transport
self.resolvedOneDriveFolder = OneDriveLocator.resolveOneDriveFolder()
self.captureHotkey = HotkeyPreference.load() self.captureHotkey = HotkeyPreference.load()
self.updateChecker = UpdateChecker() self.updateChecker = UpdateChecker()
self.updateChecker.onChecked = { [weak self] in self.updateChecker.onChecked = { [weak self] in
guard let self else { return } guard let self else { return }
self.updateAvailable = self.updateChecker.availableUpdate self.updateAvailable = self.updateChecker.availableUpdate
self.setUpdateStatus(self.updateChecker.statusMessage) if let message = self.updateChecker.statusMessage {
} self.setStatus(message)
self.updateChecker.onCheckingChanged = { [weak self] checking in }
self?.isCheckingForUpdates = checking
} }
} }
/// CFBundleShortVersionString of the running app.
public var appVersion: String { UpdateChecker.currentVersion() }
/// Version recorded in the app-managed rollback copy, when one exists.
public var previousVersion: String? { updateChecker.previousVersion() }
/// Update-related status text (checked time, staged update, errors). Displayed only in the footer.
public var updateStatusMessage: String? { updateStatus }
// MARK: Seam mutators the only way a WP-4b/4c extension changes state. // MARK: Seam mutators the only way a WP-4b/4c extension changes state.
func setStatus(_ text: String?) { statusLine = text } func setStatus(_ text: String?) { statusLine = text }
func setUpdateStatus(_ text: String?) { updateStatus = text }
func setSending(_ value: Bool) { isSending = value } func setSending(_ value: Bool) { isSending = value }
func setCapturing(_ value: Bool) { isCapturing = value } func setCapturing(_ value: Bool) { isCapturing = value }
func replaceSession(_ new: CaptureSession) { session = new } func replaceSession(_ new: CaptureSession) { session = new }
@@ -142,23 +120,6 @@ public final class AppModel {
watchFolderURL = watch watchFolderURL = watch
setFolderDisplayNames(outbox: outbox.lastPathComponent, watch: watch.lastPathComponent) setFolderDisplayNames(outbox: outbox.lastPathComponent, watch: watch.lastPathComponent)
} }
func setTransport(_ value: SendTransport) { transport = value }
func setResolvedOneDriveFolder(_ value: URL?) { resolvedOneDriveFolder = value }
/// Bumped by chooseTransport/chooseOneDriveFolder (SettingsView.swift) before each
/// spawns its async watcher-reconcile Task; that Task checks its own snapshot
/// against the live value before every mutating step, so rapid toggling always
/// lets the LAST choice win instead of applying stale, superseded work. Not
/// `@Observable`-relevant state pure internal bookkeeping, never read by a View.
var reconcileGeneration = 0
/// The MOST RECENT watcher-reconcile Task spawned by chooseTransport/
/// chooseOneDriveFolder, if one is still (or was just) in flight. send() awaits
/// this BEFORE snapshotting transport/folder, so a toggle immediately followed by
/// Send can never race ahead of the reconcile it depends on (the watcher's
/// recordUncommented flag briefly lagging the just-chosen transport, for example).
/// `Task<Void, Never>` never throws; awaiting an already-completed task's `.value`
/// returns immediately. Not `@Observable`-relevant pure internal bookkeeping.
var pendingReconcileTask: Task<Void, Never>?
func rememberLastComposedPDF(_ url: URL) { lastComposedPDFURL = url } func rememberLastComposedPDF(_ url: URL) { lastComposedPDFURL = url }
/// True when a last-composed PDF path is known this run, or the newest /// True when a last-composed PDF path is known this run, or the newest
@@ -226,29 +187,7 @@ public final class AppModel {
// Empty ledger on first run is not an error. // Empty ledger on first run is not an error.
} }
// 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.
// Also make sure the resolved OneDrive folder actually exists before the
// watcher starts watching it (bootstrap is the other creation trigger besides
// chooseTransport/chooseOneDriveFolder see TransportSettings.effectiveFolders).
if transport == .oneDrive {
try? FileManager.default.createDirectory(at: outboxURL, withIntermediateDirectories: true)
}
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
await watcher.setRecordUncommented(transport == .airDrop)
do { do {
// BLOCKER fix: reconcile the watcher's internal watchFolder with the live
// watchFolderURL UNCONDITIONALLY, before it ever starts. `paths` (and so the
// watcher's initial folder, set in its own init) now comes from the same
// transport-aware TransportSettings.effectiveFolders() as watchFolderURL, so
// in the normal case this is a no-op but it is the only thing that would
// have caught the old bug (launch paths built AirDrop-only while OneDrive was
// the persisted transport, leaving the watcher's FSEvents stream pointed at a
// stale folder for the whole session) and it stays cheap insurance against
// that class of drift ever recurring. Calling it before start() only updates
// the stored folder no FSEvents stream exists yet to restart.
try await watcher.updateWatchFolder(watchFolderURL)
try await watcher.start { [weak self] _ in try await watcher.start { [weak self] _ in
Task { @MainActor in Task { @MainActor in
guard let self else { return } guard let self else { return }
@@ -261,29 +200,18 @@ public final class AppModel {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not watch the return folder.") setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not watch the return folder.")
} }
// Env-var-flagged self-test/headless runs (PickerSelfTest's phases, PanelSnapshot,
// and the new ShotdeckTests launch-wiring regression test) skip two real-world
// side effects that are unsafe or meaningless in that context: the update-check
// schedule (a real network call), and binding the REAL, process-wide Carbon
// global hotkey which is not safe to exercise in an automated/parallel test
// process (it can collide with ShotdeckCoreTests' own HotkeyCenterCarbonTests
// running in the same test binary) and was never meaningfully exercised by any
// self-test anyway. A real user launch never sets these env vars, so production
// behavior is unchanged.
let isSelfTestRun =
ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] != nil
let pref = HotkeyPreference.load() let pref = HotkeyPreference.load()
captureHotkey = pref captureHotkey = pref
if !isSelfTestRun, !bindCaptureHotkey(pref) { if !bindCaptureHotkey(pref) {
setStatus("\(pref.displayString) is already used by another app — capture only works from the menu.") setStatus("\(pref.displayString) is already used by another app — capture only works from the menu.")
} }
if !isSelfTestRun { let skipSchedule =
ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_HISTORY_SELFTEST"] != nil
if !skipSchedule {
updateChecker.startSchedule() updateChecker.startSchedule()
} }
} }
@@ -294,19 +222,6 @@ public final class AppModel {
updateChecker.installStaged() updateChecker.installStaged()
} }
/// User-initiated appcast check ("Check for updates" menu row).
public func checkForUpdates() {
Task { @MainActor in
await updateChecker.checkNow(manual: true)
}
}
/// Reverts `/Applications/Redline.app` to the app-managed rollback copy and relaunches.
/// Does nothing unless a `Redline.app.previous` exists and the user clicked the row.
public func revertToPreviousVersion() {
updateChecker.revertToPrevious()
}
/// Unregisters `capture` and binds `HotkeyPreference.load()`. If Carbon rejects the new /// Unregisters `capture` and binds `HotkeyPreference.load()`. If Carbon rejects the new
/// combo, restores the previous preference (UserDefaults + Carbon) so the old one keeps working. /// combo, restores the previous preference (UserDefaults + Carbon) so the old one keeps working.
func reRegisterHotkey() { func reRegisterHotkey() {
+1 -32
View File
@@ -15,8 +15,6 @@ struct MenuBarView: View {
Divider() Divider()
returnsBlock returnsBlock
} }
Divider()
updateFooter
} }
.padding(10) .padding(10)
.frame(width: 320, alignment: .leading) .frame(width: 320, alignment: .leading)
@@ -85,21 +83,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()
} label: {
actionLabel("Revert to \(previous)")
}
}
Button { Button {
let anchor = NSApp.keyWindow?.contentView let anchor = NSApp.keyWindow?.contentView
if let sender = model as? SendCapable { if let sender = model as? SendCapable {
@@ -108,7 +91,7 @@ struct MenuBarView: View {
model.setStatus("Send is not available in this build.") model.setStatus("Send is not available in this build.")
} }
} label: { } label: {
actionLabel(model.transport == .oneDrive ? "Send to OneDrive" : "Send…") actionLabel("Send…")
} }
.disabled(model.session.isEmpty || model.isSending) .disabled(model.session.isEmpty || model.isSending)
@@ -210,18 +193,4 @@ struct MenuBarView: View {
private var newestReturns: [ReturnedDocument] { private var newestReturns: [ReturnedDocument] {
model.allReturns.sorted { $0.detectedAt > $1.detectedAt } model.allReturns.sorted { $0.detectedAt > $1.detectedAt }
} }
private var updateFooter: some View {
VStack(alignment: .leading, spacing: 2) {
Text("Redline \(model.appVersion)")
.font(.caption)
.foregroundStyle(.secondary)
if let message = model.updateStatusMessage {
Text(message)
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
}
} }
+7 -158
View File
@@ -61,28 +61,6 @@ enum PanelSnapshot {
try renderMenuBar(model: model, to: directory, name: "03-empty-session") try renderMenuBar(model: model, to: directory, name: "03-empty-session")
// 04 three real PNGs in the temp spool so SessionStrip thumbnails decode. // 04 three real PNGs in the temp spool so SessionStrip thumbnails decode.
try await addSampleCaptures(to: model)
try renderMenuBar(model: model, to: directory, name: "04-captures-present")
// 05 two inspected PDFs in the temp ledger, one marked / one not.
try await seedReturns(model: model)
try renderMenuBar(model: model, to: directory, name: "05-returns-present")
// 06 SettingsView against the same isolated model.
try render(
SettingsView().environment(model),
to: directory.appendingPathComponent("panel-06-settings.png")
)
// 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)
}
/// Three real PNGs appended to the given model's temp spool so SessionStrip
/// thumbnails decode. Shared by panel 04 (AirDrop) and panel 09 (OneDrive).
@MainActor
private static func addSampleCaptures(to model: AppModel) async throws {
let swatches: [(CGFloat, CGFloat, CGFloat)] = [ let swatches: [(CGFloat, CGFloat, CGFloat)] = [
(0.85, 0.22, 0.18), (0.85, 0.22, 0.18),
(0.18, 0.62, 0.32), (0.18, 0.62, 0.32),
@@ -99,93 +77,17 @@ enum PanelSnapshot {
) )
} }
model.replaceSession(try await model.spool.currentSession()) model.replaceSession(try await model.spool.currentSession())
} try renderMenuBar(model: model, to: directory, name: "04-captures-present")
/// Panels 07-09: OneDrive transport, on its own isolated model/temp root so // 05 two inspected PDFs in the temp ledger, one marked / one not.
/// switching transport here never touches the AirDrop-mode model above, the real try await seedReturns(model: model)
/// home directory, or UserDefaults.standard. The "resolved" and "not found" states try renderMenuBar(model: model, to: directory, name: "05-returns-present")
/// are produced by calling the real OneDriveLocator functions against fake home
/// trees built under this snapshot's own temp root never a hand-typed path.
@MainActor
private static func captureOneDrivePanels(to directory: URL) async throws {
let (model, root) = try makeIsolatedModel()
defer { try? FileManager.default.removeItem(at: root) }
model.setTransport(.oneDrive)
// 07 a resolved OneDrive folder, shaped like the real default // 06 SettingsView against the same isolated model.
// (/Library/CloudStorage/OneDrive-MMDGROUP/Redline): a fake home tree with a
// real OneDrive-MMDGROUP directory under it, resolved via the same pure
// OneDriveLocator function production code uses never a hand-typed path.
let fakeHomeWithOneDrive = root.appendingPathComponent("fake-home-with-onedrive", isDirectory: true)
let syncRoot = fakeHomeWithOneDrive
.appendingPathComponent("Library/CloudStorage/OneDrive-MMDGROUP", isDirectory: true)
try FileManager.default.createDirectory(at: syncRoot, withIntermediateDirectories: true)
guard let resolvedFolder = OneDriveLocator.defaultRedlineFolder(
home: fakeHomeWithOneDrive, fileManager: .default
) else {
throw SnapshotError.oneDriveFixtureFailed("fake OneDrive-MMDGROUP root did not resolve")
}
model.setResolvedOneDriveFolder(resolvedFolder)
try render( try render(
SettingsView().environment(model), SettingsView().environment(model),
to: directory.appendingPathComponent("panel-07-settings-onedrive.png") to: directory.appendingPathComponent("panel-06-settings.png")
) )
// 08 no OneDrive folder found: a fake home with NO Library/CloudStorage at
// all, and a throwaway UserDefaults suite (never .standard, never touched
// before) so the stored-override check also legitimately finds nothing.
let fakeHomeWithoutOneDrive = root.appendingPathComponent("fake-home-without-onedrive", isDirectory: true)
try FileManager.default.createDirectory(at: fakeHomeWithoutOneDrive, withIntermediateDirectories: true)
let isolatedDefaults = try makeIsolatedDefaultsSuite()
defer { isolatedDefaults.defaults.removePersistentDomain(forName: isolatedDefaults.suiteName) }
let missingFolder = OneDriveLocator.resolveOneDriveFolder(
defaults: isolatedDefaults.defaults, home: fakeHomeWithoutOneDrive, fileManager: .default
)
guard missingFolder == nil else {
throw SnapshotError.oneDriveFixtureFailed("fake home without OneDrive unexpectedly resolved")
}
model.setResolvedOneDriveFolder(nil)
try render(
SettingsView().environment(model),
to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png")
)
// 09 menu bar panel, 3 captures present, OneDrive mode ("Send to OneDrive").
model.snapshotSetScreenRecordingGranted(true)
model.replaceRegion(sampleRegion())
try await addSampleCaptures(to: model)
try renderMenuBar(model: model, to: directory, name: "09-captures-present-onedrive")
// 10 update idle: 3 captures, no update available, footer "Redline <ver>", row "Check for updates".
let (updateModel, updateRoot) = try makeIsolatedModel()
defer { try? FileManager.default.removeItem(at: updateRoot) }
updateModel.snapshotSetScreenRecordingGranted(true)
updateModel.replaceRegion(sampleRegion())
try await addSampleCaptures(to: updateModel)
// No update set, updateChecker in idle state, no previous version
updateModel.snapshotSetPreviousVersion(nil)
try renderMenuBar(model: updateModel, to: directory, name: "10-update-idle")
// 11 update checking: same as 10 but isCheckingForUpdates = true.
updateModel.snapshotSetIsCheckingForUpdates(true)
try renderMenuBar(model: updateModel, to: directory, name: "11-update-checking")
updateModel.snapshotSetIsCheckingForUpdates(false)
// 12 update up-to-date: footer status line reads "Redline <ver> is up to date, checked 10:42 Dubai".
let upToDateMessage = "Redline \(updateModel.appVersion) is up to date, checked 10:42 Dubai"
updateModel.snapshotSetUpdateStatusMessage(upToDateMessage)
try renderMenuBar(model: updateModel, to: directory, name: "12-update-uptodate")
// 13 update staged: row "Update to 9.9.9" present, footer status "Update to 9.9.9 is ready".
updateModel.snapshotSetUpdateAvailable(version: "9.9.9", notes: "Test release")
updateModel.snapshotSetUpdateStatusMessage("Update to 9.9.9 is ready")
try renderMenuBar(model: updateModel, to: directory, name: "13-update-staged")
// 14 update revert: row "Revert to 0.2.0" present.
updateModel.snapshotSetUpdateAvailable(version: nil, notes: nil) // Clear the staged update
updateModel.snapshotSetUpdateStatusMessage(nil)
updateModel.snapshotSetPreviousVersion("0.2.0")
try renderMenuBar(model: updateModel, to: directory, name: "14-update-revert")
} }
@MainActor @MainActor
@@ -261,7 +163,7 @@ enum PanelSnapshot {
watchFolder: root.appendingPathComponent("watch", isDirectory: true) watchFolder: root.appendingPathComponent("watch", isDirectory: true)
) )
let ledger = try ReturnLedger(paths: paths) let ledger = try ReturnLedger(paths: paths)
let model = AppModel( let model = try AppModel(
paths: paths, paths: paths,
spool: try SpoolStore(paths: paths), spool: try SpoolStore(paths: paths),
composer: PDFComposer(), composer: PDFComposer(),
@@ -275,23 +177,6 @@ enum PanelSnapshot {
return (model, root) return (model, root)
} }
/// A throwaway UserDefaults suite never `.standard` for the panel-08 fixture,
/// the same isolation pattern ShotdeckCoreTests uses for TransportSettings/
/// OneDriveLocator tests.
private struct IsolatedDefaultsSuite {
let suiteName: String
let defaults: UserDefaults
}
private static func makeIsolatedDefaultsSuite() throws -> IsolatedDefaultsSuite {
let suiteName = "shotdeck-panel-snapshot-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: suiteName) else {
throw SnapshotError.oneDriveFixtureFailed("could not create isolated UserDefaults suite")
}
defaults.removePersistentDomain(forName: suiteName)
return IsolatedDefaultsSuite(suiteName: suiteName, defaults: defaults)
}
@MainActor @MainActor
private static func seedReturns(model: AppModel) async throws { private static func seedReturns(model: AppModel) async throws {
let watch = model.paths.watchFolder let watch = model.paths.watchFolder
@@ -391,40 +276,6 @@ extension AppModel {
) )
self[keyPath: writable] = granted self[keyPath: writable] = granted
} }
/// Snapshot-only: set isCheckingForUpdates without triggering a real check.
func snapshotSetIsCheckingForUpdates(_ checking: Bool) {
let writable: ReferenceWritableKeyPath<AppModel, Bool> = unsafeBitCast(
\AppModel.isCheckingForUpdates, to: ReferenceWritableKeyPath<AppModel, Bool>.self
)
self[keyPath: writable] = checking
}
/// Snapshot-only: set updateStatusMessage for panel display.
func snapshotSetUpdateStatusMessage(_ message: String?) {
setUpdateStatus(message)
}
/// Snapshot-only: set updateAvailable without triggering a real download.
func snapshotSetUpdateAvailable(version: String?, notes: String?) {
if let version = version, let notes = notes {
let writable: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?> = unsafeBitCast(
\AppModel.updateAvailable, to: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?>.self
)
self[keyPath: writable] = (version: version, notes: notes)
} else {
let writable: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?> = unsafeBitCast(
\AppModel.updateAvailable, to: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?>.self
)
self[keyPath: writable] = nil
}
}
/// Snapshot-only: set a fake previousVersion for the revert panel.
func snapshotSetPreviousVersion(_ version: String?) {
updateChecker.snapshotPreviousVersionOverride = version
updateChecker.snapshotUsesPreviousVersionOverride = true
}
} }
private enum SnapshotError: Error, CustomStringConvertible { private enum SnapshotError: Error, CustomStringConvertible {
@@ -432,7 +283,6 @@ private enum SnapshotError: Error, CustomStringConvertible {
case encodeFailed(String) case encodeFailed(String)
case pngGenerationFailed case pngGenerationFailed
case pdfWriteFailed(String) case pdfWriteFailed(String)
case oneDriveFixtureFailed(String)
var description: String { var description: String {
switch self { switch self {
@@ -440,7 +290,6 @@ private enum SnapshotError: Error, CustomStringConvertible {
case .encodeFailed(let name): return "PNG encode failed for \(name)" case .encodeFailed(let name): return "PNG encode failed for \(name)"
case .pngGenerationFailed: return "CoreGraphics PNG generation failed" case .pngGenerationFailed: return "CoreGraphics PNG generation failed"
case .pdfWriteFailed(let name): return "could not write \(name)" case .pdfWriteFailed(let name): return "could not write \(name)"
case .oneDriveFixtureFailed(let detail): return "OneDrive snapshot fixture failed: \(detail)"
} }
} }
} }
+205 -477
View File
@@ -3,7 +3,6 @@ import CoreGraphics
import Darwin import Darwin
import Foundation import Foundation
import ImageIO import ImageIO
import PDFKit
import ShotdeckCore import ShotdeckCore
/// In-process self-test for the region picker, driven by `SHOTDECK_PICKER_SELFTEST`. /// In-process self-test for the region picker, driven by `SHOTDECK_PICKER_SELFTEST`.
@@ -31,6 +30,20 @@ enum PickerSelfTest {
} }
} }
/// Standalone HISTORY phase when `SHOTDECK_HISTORY_SELFTEST` is set without
/// the picker chain. Waits for NSApp like the other phases, then exits.
static func runHistoryIfRequested() {
guard let raw = ProcessInfo.processInfo.environment["SHOTDECK_HISTORY_SELFTEST"],
!raw.isEmpty
else { return }
_ = raw
DispatchQueue.main.async {
MainActor.assumeIsolated {
runHistoryPhase()
}
}
}
private static func execute(outputDirectory: URL) { private static func execute(outputDirectory: URL) {
do { do {
try FileManager.default.createDirectory( try FileManager.default.createDirectory(
@@ -118,7 +131,8 @@ enum PickerSelfTest {
runRegionPersistPhase() runRegionPersistPhase()
// Hop off this MainActor job so the SEND-TRUTH Task can run; do not // Hop off this MainActor job so the SEND-TRUTH Task can run; do not
// exit(0) here runSendTruthPhase prints its own PASS/FAIL, then // exit(0) here runSendTruthPhase prints its own PASS/FAIL, then
// chains to UPDATE-SELFTEST (or exits if that phase is not requested). // chains to HISTORY, then UPDATE-SELFTEST (or exits if that phase is
// not requested).
runSendTruthPhase() runSendTruthPhase()
} }
@@ -167,21 +181,166 @@ enum PickerSelfTest {
/// Fail path must leave the session open in the temp spool; success path archives /// Fail path must leave the session open in the temp spool; success path archives
/// and mints a fresh empty session. Scheduled as a new MainActor job because this /// and mints a fresh empty session. Scheduled as a new MainActor job because this
/// function is called from inside `execute()` a nested run-loop wait would never /// function is called from inside `execute()` a nested run-loop wait would never
/// let the Task start. On success, chains to UPDATE-SELFTEST instead of exiting. /// let the Task start. On success, chains to HISTORY instead of exiting.
private static func runSendTruthPhase() { private static func runSendTruthPhase() {
Task { @MainActor in Task { @MainActor in
do { do {
try await executeSendTruth() try await executeSendTruth()
print("SEND-TRUTH PASS") print("SEND-TRUTH PASS")
fflush(stdout) fflush(stdout)
if !startUpdateSelfTestIfRequested(), !startOneDriveSelfTestIfRequested() {
exit(0)
}
} catch { } catch {
print("SEND-TRUTH FAIL \(error)") print("SEND-TRUTH FAIL \(error)")
fflush(stdout) fflush(stdout)
exit(1) exit(1)
} }
runHistoryPhase()
}
}
/// Phase 4: drive HistoryStore record/prune in a temp root. Env-gated by
/// `SHOTDECK_HISTORY_SELFTEST` the same way UPDATE is gated, and also runs
/// whenever the picker self-test chain is already in flight so a full
/// self-test prints HISTORY PASS|FAIL. Chains to UPDATE-SELFTEST (or exits).
private static func runHistoryPhase() {
let historyRequested = ProcessInfo.processInfo.environment["SHOTDECK_HISTORY_SELFTEST"]
let pickerRequested = ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"]
let shouldRun = (historyRequested.map { !$0.isEmpty } ?? false)
|| (pickerRequested.map { !$0.isEmpty } ?? false)
guard shouldRun else {
if !startUpdateSelfTestIfRequested() {
exit(0)
}
return
}
Task { @MainActor in
do {
try await executeHistorySelfTest()
print("HISTORY PASS")
fflush(stdout)
if !startUpdateSelfTestIfRequested() {
exit(0)
}
} catch {
print("HISTORY FAIL \(error)")
fflush(stdout)
exit(1)
}
}
}
private static func executeHistorySelfTest() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-history-selftest-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let paths = try AppSupportPaths(
root: root.appendingPathComponent("root", isDirectory: true),
outbox: root.appendingPathComponent("outbox", isDirectory: true),
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
let store = try HistoryStore(paths: paths)
let sources = root.appendingPathComponent("user-sources", isDirectory: true)
try fm.createDirectory(at: sources, withIntermediateDirectories: true)
var recorded: [HistoryEntry] = []
for i in 0..<12 {
let source = sources.appendingPathComponent("source-\(i).pdf")
try Data("%PDF-1.4\n%hist-\(i)\n%%EOF\n".utf8).write(to: source)
let entry = try await store.recordSentPDF(
sourceURL: source,
sessionID: UUID(),
pageCount: 1,
sentAt: Date(timeIntervalSince1970: 1_800_000_000 + TimeInterval(i))
)
recorded.append(entry)
let onDisk = try Data(contentsOf: source)
guard onDisk == Data("%PDF-1.4\n%hist-\(i)\n%%EOF\n".utf8) else {
throw HistorySelfTestError.detail("user source PDF was modified: \(source.path)")
}
}
let listed = await store.listPDFs()
guard listed.count == 10 else {
throw HistorySelfTestError.detail("listPDFs count \(listed.count) want 10")
}
let wantNewest = Array(recorded.suffix(10).reversed())
guard listed.map(\.id) == wantNewest.map(\.id) else {
throw HistorySelfTestError.detail("listPDFs did not return the 10 newest")
}
let pdfsDir = paths.root.appendingPathComponent("history/pdfs", isDirectory: true)
for entry in recorded.prefix(2) {
let gone = pdfsDir.appendingPathComponent(entry.fileName)
guard !fm.fileExists(atPath: gone.path) else {
throw HistorySelfTestError.detail("oldest PDF still on disk: \(gone.path)")
}
}
let same = sources.appendingPathComponent("same.pdf")
try Data("%PDF-1.4\n%same\n%%EOF\n".utf8).write(to: same)
let first = try await store.recordSentPDF(
sourceURL: same, sessionID: nil, pageCount: 1,
sentAt: Date(timeIntervalSince1970: 1_800_000_100)
)
let second = try await store.recordSentPDF(
sourceURL: same, sessionID: nil, pageCount: 1,
sentAt: Date(timeIntervalSince1970: 1_800_000_101)
)
guard first.id != second.id, first.fileURL.path != second.fileURL.path,
fm.fileExists(atPath: first.fileURL.path),
fm.fileExists(atPath: second.fileURL.path),
fm.fileExists(atPath: same.path)
else {
throw HistorySelfTestError.detail("re-record same source did not produce two distinct copies")
}
let spool = try SpoolStore(paths: paths)
let png = try makeTinyPNGData()
let base = Date(timeIntervalSince1970: 1_800_100_000)
var n = 0
var oldestSessionID: UUID?
for count in [5, 15, 15] {
if n == 0 {
oldestSessionID = try await spool.currentSession().id
}
for _ in 0..<count {
_ = try await spool.append(
pngData: png, pixelWidth: 64, pixelHeight: 48, scale: 1,
capturedAt: base.addingTimeInterval(TimeInterval(n))
)
n += 1
}
_ = try await spool.archiveCurrent(pdfFileName: "Redline-hist-\(n).pdf")
}
let openCapture = try await spool.append(
pngData: png, pixelWidth: 64, pixelHeight: 48, scale: 1,
capturedAt: Date(timeIntervalSince1970: 1_900_000_000)
)
let openSession = try await spool.currentSession()
let openPNG = paths.sessionDirectory(openSession.id).appendingPathComponent(openCapture.fileName)
let openBytes = try Data(contentsOf: openPNG)
try await store.pruneImages()
let images = try await store.listImages(limit: 50)
guard images.count == 30 else {
throw HistorySelfTestError.detail("listImages count \(images.count) want 30")
}
if let oldestSessionID {
let oldDir = paths.archiveDirectory(oldestSessionID)
guard !fm.fileExists(atPath: oldDir.path) else {
throw HistorySelfTestError.detail("emptied archive session still on disk")
}
}
guard fm.fileExists(atPath: openPNG.path), try Data(contentsOf: openPNG) == openBytes else {
throw HistorySelfTestError.detail("open session PNG was touched")
}
let remainingOpen = try await spool.currentSession()
guard remainingOpen.id == openSession.id,
remainingOpen.captures.map(\.id) == [openCapture.id]
else {
throw HistorySelfTestError.detail("open session manifest was touched")
} }
} }
@@ -197,7 +356,7 @@ enum PickerSelfTest {
watchFolder: root.appendingPathComponent("watch", isDirectory: true) watchFolder: root.appendingPathComponent("watch", isDirectory: true)
) )
let ledger = try ReturnLedger(paths: paths) let ledger = try ReturnLedger(paths: paths)
let model = AppModel( let model = try AppModel(
paths: paths, paths: paths,
spool: try SpoolStore(paths: paths), spool: try SpoolStore(paths: paths),
composer: PDFComposer(), composer: PDFComposer(),
@@ -223,7 +382,7 @@ enum PickerSelfTest {
sendTruthFail("seeded session was empty") sendTruthFail("seeded session was empty")
} }
let pending = try await model.composePDFForSend(outbox: model.outboxURL, transport: .airDrop) let pending = try await model.composePDFForSend()
guard fm.fileExists(atPath: pending.fileURL.path) else { guard fm.fileExists(atPath: pending.fileURL.path) else {
sendTruthFail("PDF was not written") sendTruthFail("PDF was not written")
} }
@@ -301,7 +460,7 @@ enum PickerSelfTest {
exit(1) exit(1)
} }
/// Phase 4: builds a fake 99.0.0 bundle, serves a local appcast, stages via /// Phase 5: builds a fake 99.0.0 bundle, serves a local appcast, stages via
/// `checkNow`, then `installStaged` into the env dir never `/Applications`. /// `checkNow`, then `installStaged` into the env dir never `/Applications`.
/// Returns true when the async phase was scheduled (it calls `exit` itself). /// Returns true when the async phase was scheduled (it calls `exit` itself).
@discardableResult @discardableResult
@@ -316,9 +475,7 @@ enum PickerSelfTest {
try await runUpdateSelfTest(outputDirectory: output) try await runUpdateSelfTest(outputDirectory: output)
print("UPDATE-SELFTEST PASS version=99.0.0") print("UPDATE-SELFTEST PASS version=99.0.0")
fflush(stdout) fflush(stdout)
if !startOneDriveSelfTestIfRequested() { exit(0)
exit(0)
}
} catch let error as UpdateSelfTestError { } catch let error as UpdateSelfTestError {
updateFail(error.description) updateFail(error.description)
} catch { } catch {
@@ -328,9 +485,6 @@ enum PickerSelfTest {
return true return true
} }
/// (a) rejects an invalidly-signed payload, (b) stages the same payload once
/// properly signed, (c) installs it atomically into a throwaway target with
/// exactly one rollback copy, (d) reverts back. Never touches `/Applications`.
private static func runUpdateSelfTest(outputDirectory: URL) async throws { private static func runUpdateSelfTest(outputDirectory: URL) async throws {
let fm = FileManager.default let fm = FileManager.default
try fm.createDirectory(at: outputDirectory, withIntermediateDirectories: true) try fm.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
@@ -338,9 +492,6 @@ enum PickerSelfTest {
guard let sourceApp = ownAppBundleURL() else { guard let sourceApp = ownAppBundleURL() else {
throw UpdateSelfTestError.detail("own bundle is not a .app (\(Bundle.main.bundleURL.path))") throw UpdateSelfTestError.detail("own bundle is not a .app (\(Bundle.main.bundleURL.path))")
} }
guard let originalVersion = readShortVersion(atAppURL: sourceApp) else {
throw UpdateSelfTestError.detail("own Info.plist has no CFBundleShortVersionString")
}
let payload = outputDirectory.appendingPathComponent("payload", isDirectory: true) let payload = outputDirectory.appendingPathComponent("payload", isDirectory: true)
if fm.fileExists(atPath: payload.path) { if fm.fileExists(atPath: payload.path) {
@@ -358,37 +509,32 @@ enum PickerSelfTest {
plist["CFBundleShortVersionString"] = "99.0.0" plist["CFBundleShortVersionString"] = "99.0.0"
let rewritten = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) let rewritten = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
try rewritten.write(to: plistURL) try rewritten.write(to: plistURL)
// Editing Info.plist after copying it invalidates the inherited signature
// Info.plist is a sealed special slot in the CodeDirectory so this fake
// bundle is genuinely unsigned-in-effect without us stripping anything.
let zipURL = outputDirectory.appendingPathComponent("Redline-99.0.0.zip") let zipURL = outputDirectory.appendingPathComponent("Redline-99.0.0.zip")
let appcastURL = outputDirectory.appendingPathComponent("appcast.json") if fm.fileExists(atPath: zipURL.path) {
try fm.removeItem(at: zipURL)
func writeZipAndAppcast() throws {
if fm.fileExists(atPath: zipURL.path) {
try fm.removeItem(at: zipURL)
}
try runDitto(arguments: ["-c", "-k", payload.path, zipURL.path])
let zipData = try Data(contentsOf: zipURL)
let hex = UpdateChecker.sha256Hex(zipData)
let appcast: [String: String] = [
"version": "99.0.0",
"zipURL": zipURL.absoluteString,
"sha256": hex,
"notes": "UPDATE-SELFTEST",
]
let appcastData = try JSONSerialization.data(withJSONObject: appcast, options: [.sortedKeys])
try appcastData.write(to: appcastURL)
} }
try writeZipAndAppcast() try runDitto(arguments: ["-c", "-k", payload.path, zipURL.path])
let zipData = try Data(contentsOf: zipURL)
let hex = UpdateChecker.sha256Hex(zipData)
let appcastURL = outputDirectory.appendingPathComponent("appcast.json")
let appcast: [String: String] = [
"version": "99.0.0",
"zipURL": zipURL.absoluteString,
"sha256": hex,
"notes": "UPDATE-SELFTEST",
]
let appcastData = try JSONSerialization.data(withJSONObject: appcast, options: [.sortedKeys])
try appcastData.write(to: appcastURL)
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
let previousAppcastPref = defaults.string(forKey: UpdateChecker.appcastURLDefaultsKey) let previous = defaults.string(forKey: UpdateChecker.appcastURLDefaultsKey)
defaults.set(appcastURL.absoluteString, forKey: UpdateChecker.appcastURLDefaultsKey) defaults.set(appcastURL.absoluteString, forKey: UpdateChecker.appcastURLDefaultsKey)
defer { defer {
if let previousAppcastPref { if let previous {
defaults.set(previousAppcastPref, forKey: UpdateChecker.appcastURLDefaultsKey) defaults.set(previous, forKey: UpdateChecker.appcastURLDefaultsKey)
} else { } else {
defaults.removeObject(forKey: UpdateChecker.appcastURLDefaultsKey) defaults.removeObject(forKey: UpdateChecker.appcastURLDefaultsKey)
} }
@@ -397,128 +543,39 @@ enum PickerSelfTest {
let (model, isolatedRoot) = try makeIsolatedUpdateModel() let (model, isolatedRoot) = try makeIsolatedUpdateModel()
defer { try? fm.removeItem(at: isolatedRoot) } defer { try? fm.removeItem(at: isolatedRoot) }
// (a) NEGATIVE invalidly-signed payload must never be offered or staged.
await model.updateChecker.checkNow() await model.updateChecker.checkNow()
guard model.updateAvailable == nil else {
throw UpdateSelfTestError.detail(
"reject-unsigned: updateAvailable=\(model.updateAvailable?.version ?? "nil") (expected nil)"
)
}
guard model.updateChecker.statusMessage == "Update is not signed by MMD — not installed." else {
throw UpdateSelfTestError.detail(
"reject-unsigned: statusMessage=\(model.updateChecker.statusMessage ?? "nil")"
)
}
print("UPDATE-SELFTEST reject-unsigned PASS")
fflush(stdout)
// (b) POSITIVE re-sign the same bundle, re-zip, re-serve; must now stage.
let signIdentity = ProcessInfo.processInfo.environment["SHOTDECK_SELFTEST_SIGN_IDENTITY"]
?? "Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
try runCodesign(identity: signIdentity, path: fakeApp.path)
try writeZipAndAppcast()
await model.updateChecker.checkNow()
guard model.updateAvailable?.version == "99.0.0" else { guard model.updateAvailable?.version == "99.0.0" else {
throw UpdateSelfTestError.detail( throw UpdateSelfTestError.detail(
"staged-signed: updateAvailable=\(model.updateAvailable?.version ?? "nil")" "updateAvailable=\(model.updateAvailable?.version ?? "nil")"
) )
} }
guard let staged = model.updateChecker.stagedAppURL else { guard let staged = model.updateChecker.stagedAppURL else {
throw UpdateSelfTestError.detail("staged-signed: staged payload missing") throw UpdateSelfTestError.detail("staged payload missing")
} }
guard staged.lastPathComponent == "Redline.app" else { guard staged.lastPathComponent == "Redline.app" else {
throw UpdateSelfTestError.detail("staged-signed: staged name \(staged.lastPathComponent)") throw UpdateSelfTestError.detail("staged name \(staged.lastPathComponent)")
} }
let stagedExe = staged.appendingPathComponent("Contents/MacOS/Shotdeck") let stagedExe = staged.appendingPathComponent("Contents/MacOS/Shotdeck")
guard fm.fileExists(atPath: stagedExe.path) else { guard fm.fileExists(atPath: stagedExe.path) else {
throw UpdateSelfTestError.detail("staged-signed: staged Contents/MacOS/Shotdeck missing") throw UpdateSelfTestError.detail("staged Contents/MacOS/Shotdeck missing")
} }
print("UPDATE-SELFTEST staged-signed PASS")
fflush(stdout)
// (c) ATOMIC INSTALL a throwaway target pre-populated with the real let targetRoot = outputDirectory.appendingPathComponent("target", isDirectory: true)
// running version; never `/Applications`. if fm.fileExists(atPath: targetRoot.path) {
let tempAppsRoot = outputDirectory.appendingPathComponent("Applications", isDirectory: true) try fm.removeItem(at: targetRoot)
if fm.fileExists(atPath: tempAppsRoot.path) {
try fm.removeItem(at: tempAppsRoot)
} }
try fm.createDirectory(at: tempAppsRoot, withIntermediateDirectories: true) let target = targetRoot.appendingPathComponent("Redline.app")
let tempTarget = tempAppsRoot.appendingPathComponent("Redline.app") model.updateChecker.installStaged(to: target)
try fm.copyItem(at: sourceApp, to: tempTarget)
model.updateChecker.installStaged(to: tempTarget) let installedPlist = target.appendingPathComponent("Contents/Info.plist")
guard let installed = NSDictionary(contentsOf: installedPlist) as? [String: Any],
guard let installedVersion = readShortVersion(atAppURL: tempTarget) else { let installedVersion = installed["CFBundleShortVersionString"] as? String
throw UpdateSelfTestError.detail("atomic-install: installed Info.plist unreadable") else {
throw UpdateSelfTestError.detail("installed Info.plist unreadable")
} }
guard installedVersion == "99.0.0" else { guard installedVersion == "99.0.0" else {
throw UpdateSelfTestError.detail("atomic-install: installed version \(installedVersion)") throw UpdateSelfTestError.detail("installed version \(installedVersion)")
}
let previousCopy = tempAppsRoot.appendingPathComponent("Redline.app.previous")
guard let previousVersionAfterInstall = readShortVersion(atAppURL: previousCopy) else {
throw UpdateSelfTestError.detail("atomic-install: Redline.app.previous missing or unreadable")
}
guard previousVersionAfterInstall == originalVersion else {
throw UpdateSelfTestError.detail(
"atomic-install: previous version=\(previousVersionAfterInstall) expected=\(originalVersion)"
)
}
try assertNoLeftoverEntries(in: tempAppsRoot, expecting: ["Redline.app", "Redline.app.previous"])
print("UPDATE-SELFTEST atomic-install PASS")
fflush(stdout)
// (d) REVERT the rollback copy swaps back in; the just-replaced version
// becomes the new rollback copy, so a revert is itself reversible.
model.updateChecker.revertToPrevious(target: tempTarget)
guard let revertedVersion = readShortVersion(atAppURL: tempTarget) else {
throw UpdateSelfTestError.detail("revert: reverted Info.plist unreadable")
}
guard revertedVersion == originalVersion else {
throw UpdateSelfTestError.detail("revert: target version=\(revertedVersion) expected=\(originalVersion)")
}
guard let previousVersionAfterRevert = readShortVersion(atAppURL: previousCopy) else {
throw UpdateSelfTestError.detail("revert: Redline.app.previous missing or unreadable")
}
guard previousVersionAfterRevert == "99.0.0" else {
throw UpdateSelfTestError.detail(
"revert: previous version=\(previousVersionAfterRevert) expected=99.0.0"
)
}
try assertNoLeftoverEntries(in: tempAppsRoot, expecting: ["Redline.app", "Redline.app.previous"])
print("UPDATE-SELFTEST revert PASS")
fflush(stdout)
}
private static func readShortVersion(atAppURL url: URL) -> String? {
let plistURL = url.appendingPathComponent("Contents/Info.plist")
guard let dict = NSDictionary(contentsOf: plistURL) as? [String: Any] else { return nil }
return dict["CFBundleShortVersionString"] as? String
}
private static func runCodesign(identity: String, path: String) throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")
process.arguments = ["--force", "--deep", "--sign", identity, path]
let err = Pipe()
process.standardError = err
process.standardOutput = Pipe()
try process.run()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
let message = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
throw UpdateSelfTestError.detail("codesign failed: \(message)")
}
}
private static func assertNoLeftoverEntries(in directory: URL, expecting expected: Set<String>) throws {
let entries = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
let unexpected = entries.filter { !expected.contains($0) }
guard unexpected.isEmpty else {
throw UpdateSelfTestError.detail(
"unexpected entries in \(directory.path): \(unexpected.joined(separator: ", "))"
)
} }
} }
@@ -542,7 +599,7 @@ enum PickerSelfTest {
watchFolder: root.appendingPathComponent("watch", isDirectory: true) watchFolder: root.appendingPathComponent("watch", isDirectory: true)
) )
let ledger = try ReturnLedger(paths: paths) let ledger = try ReturnLedger(paths: paths)
let model = AppModel( let model = try AppModel(
paths: paths, paths: paths,
spool: try SpoolStore(paths: paths), spool: try SpoolStore(paths: paths),
composer: PDFComposer(), composer: PDFComposer(),
@@ -576,335 +633,6 @@ enum PickerSelfTest {
exit(1) exit(1)
} }
/// Phase 5: proves the OneDrive transport end to end against a REAL sync root
/// resolved at runtime via `OneDriveLocator.syncRoots()`, never a hardcoded path, so
/// this runs correctly on any Mac/account that has OneDrive signed in (MMD-named
/// root preferred, same as production). Triggered by `SHOTDECK_ONEDRIVE_SELFTEST`
/// when chained after PICKER/SEND-TRUTH/UPDATE-SELFTEST the exact pattern
/// `startUpdateSelfTestIfRequested` uses for its own env var. Returns true when the
/// async phase was scheduled (it calls `exit` itself).
@discardableResult
private static func startOneDriveSelfTestIfRequested() -> Bool {
guard ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil else {
return false
}
runOneDriveSelfTestAndExit()
return true
}
/// Entry point for running ONLY this phase, bypassing the on-screen picker chain
/// entirely. The harness has no other per-phase selector, so this is the escape
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
static func runOneDriveOnlyIfRequested() {
guard ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" else {
return
}
// Same hop as runIfRequested(): a plain main-queue turn after NSApp starts, so
// AppKit/PDFKit calls inside the phase are not racing app launch.
DispatchQueue.main.async {
MainActor.assumeIsolated {
runOneDriveSelfTestAndExit()
}
}
}
private static func runOneDriveSelfTestAndExit() {
// Never a false PASS: no real OneDrive sync root on this machine/account is a
// SKIP (still non-zero exit), not silently treated as passing.
guard let syncRoot = OneDriveLocator.syncRoots().first else {
print("ONEDRIVE-SELFTEST SKIP no OneDrive sync root")
fflush(stdout)
exit(1)
}
Task { @MainActor in
do {
let folder = try await executeOneDriveSelfTest(syncRoot: syncRoot)
print("ONEDRIVE-SELFTEST PASS path=\(folder.path)")
fflush(stdout)
exit(0)
} catch let error as OneDriveSelfTestError {
oneDriveFail(error.description)
} catch {
oneDriveFail(String(describing: error))
}
}
}
/// Sub-step 1: builds a session, sends it through the OneDrive branch of
/// `send(anchor: nil)` against a NEW folder under `syncRoot`, confirms the watcher
/// does NOT report the freshly-written unmarked PDF as a return, then adds a real
/// PDFKit ink annotation in place (what the iPad does) and confirms the watcher now
/// reports it as commented.
///
/// Sub-step 1b: rapid transport toggling (chooseTransport(.airDrop) immediately
/// followed by chooseTransport(.oneDrive), no await between them) must still end
/// with the watcher pointed at the OneDrive folder proves the generation-guarded
/// reconcile in chooseTransport/chooseOneDriveFolder (SettingsView.swift) really
/// does let the last choice win instead of an earlier, superseded call applying its
/// stale folder after a later one already won.
///
/// Sub-step 1c: the OTHER race a toggle immediately followed by Send, with no
/// sleep at all before send() runs. Proves send() awaits `pendingReconcileTask`
/// before snapshotting transport/folder: a freshly-sent, still-unmarked PDF must
/// never be reported as an already-returned document (which is exactly what would
/// happen if send() raced ahead while recordUncommented was still `true`, stale
/// from the .airDrop leg of the toggle).
///
/// Sub-step 2: relaunch simulation the exact BLOCKER scenario this phase exists to
/// catch. OneDrive is still persisted in defaults from sub-step 1; builds a FRESH
/// model the same way the real app launches (`AppDelegate.makeLaunchModel()` itself,
/// not a reimplementation), bootstraps it, then marks a PDF in the folder in place
/// the relaunched watcher must report it. A temp app-support root keeps this off the
/// real ~/Library/Application Support/Shotdeck.
///
/// Never deletes anything under OneDrive the created folder and PDFs are left in
/// place for Ben to inspect / for the real iPad round trip.
private static func executeOneDriveSelfTest(syncRoot: URL) async throws -> URL {
let fm = FileManager.default
// UserDefaults.standard is the ONLY defaults instance send()/TransportSettings
// actually read at runtime (there is no defaults-threading through AppModel), so
// "isolated" here means snapshot-and-restore around the real keys the same
// pattern runRegionPersistPhase already uses for CaptureRegion.defaultsKey.
let defaults = UserDefaults.standard
let previousTransport = defaults.string(forKey: TransportSettings.transportDefaultsKey)
let previousFolder = defaults.string(forKey: TransportSettings.oneDriveFolderDefaultsKey)
defer {
if let previousTransport {
defaults.set(previousTransport, forKey: TransportSettings.transportDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.transportDefaultsKey)
}
if let previousFolder {
defaults.set(previousFolder, forKey: TransportSettings.oneDriveFolderDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.oneDriveFolderDefaultsKey)
}
}
let stamp = DubaiTime.fileStamp(Date())
let selftestFolder = syncRoot.appendingPathComponent("Redline-selftest-\(stamp)", isDirectory: true)
try fm.createDirectory(at: selftestFolder, withIntermediateDirectories: true)
TransportSettings.setTransport(.oneDrive, defaults: defaults)
TransportSettings.setOneDriveFolder(selftestFolder, defaults: defaults)
// Local spool root only the outbox/watch folder is the real OneDrive folder.
let spoolRoot = fm.temporaryDirectory
.appendingPathComponent("shotdeck-onedrive-selftest-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: spoolRoot) }
let paths = try AppSupportPaths(root: spoolRoot, outbox: selftestFolder, watchFolder: selftestFolder)
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
await watcher.setRecordUncommented(false) // OneDrive mode: today's default is AirDrop's `true`.
let model = AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
composer: PDFComposer(),
capturer: ScreenCapturer(),
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: watcher
)
model.setFolderURLs(outbox: selftestFolder, watch: selftestFolder)
model.setTransport(.oneDrive)
let png = try makeTinyPNGData()
_ = try await model.spool.append(
pngData: png, pixelWidth: 64, pixelHeight: 48, scale: 1, capturedAt: Date()
)
model.replaceSession(try await model.spool.currentSession())
guard !model.session.isEmpty else {
throw OneDriveSelfTestError.detail("seeded session was empty")
}
await model.send(anchor: nil)
guard let status = model.statusLine, status.hasPrefix("Saved to OneDrive") else {
throw OneDriveSelfTestError.detail(
"status did not start with 'Saved to OneDrive': \(model.statusLine ?? "nil")"
)
}
guard model.session.isEmpty else {
throw OneDriveSelfTestError.detail("session was not archived after the OneDrive send")
}
let written = (try? fm.contentsOfDirectory(at: selftestFolder, includingPropertiesForKeys: nil)) ?? []
guard let pdfURL = written.first(where: { $0.pathExtension.lowercased() == "pdf" }) else {
throw OneDriveSelfTestError.detail("no PDF found in \(selftestFolder.path)")
}
// Unmarked so far: the watcher must not treat it as a return.
let beforeMarkup = try await watcher.scanNow()
guard !beforeMarkup.contains(where: { $0.fileURL == pdfURL }) else {
throw OneDriveSelfTestError.detail("unmarked PDF was reported as returned by scanNow")
}
let commentedBefore = try await ledger.commented()
guard !commentedBefore.contains(where: { $0.fileURL == pdfURL }) else {
throw OneDriveSelfTestError.detail("unmarked PDF was recorded as commented in the ledger")
}
// What the iPad does: mark it up in place with a real ink annotation, then save.
try addInkMark(to: pdfURL)
let afterMarkup = try await watcher.scanNow()
guard let recorded = afterMarkup.first(where: { $0.fileURL == pdfURL }), recorded.isCommented else {
throw OneDriveSelfTestError.detail("annotated PDF was not reported as commented by scanNow")
}
let commentedAfter = try await ledger.commented()
guard commentedAfter.contains(where: { $0.fileURL == pdfURL }) else {
throw OneDriveSelfTestError.detail("annotated PDF was not recorded in the ledger as commented")
}
// Sub-step 1b: rapid toggle race see the doc comment above this function.
model.chooseTransport(.airDrop)
model.chooseTransport(.oneDrive) // immediately superseding the call above
// The generation guard itself is what's under test, not this wait it just
// gives the (already-guarded) reconcile Task a moment to settle either way.
try await Task.sleep(for: .milliseconds(500))
guard model.transport == .oneDrive else {
throw OneDriveSelfTestError.detail(
"rapid toggle: model.transport ended as \(model.transport), expected .oneDrive"
)
}
let racePDFURL = selftestFolder.appendingPathComponent("Redline-race-\(stamp).pdf")
try writeUnmarkedRedlinePDF(to: racePDFURL)
try addInkMark(to: racePDFURL)
let raceFound = try await model.watcher.scanNow()
guard raceFound.first(where: { $0.fileURL == racePDFURL })?.isCommented == true else {
throw OneDriveSelfTestError.detail(
"rapid toggle: watcher did not end up watching \(selftestFolder.path) — an earlier, superseded chooseTransport call won"
)
}
// Sub-step 1c: toggle-then-immediate-send race see the doc comment above
// this function. No sleep here: this IS the exact race window finding #3
// exists to close, so send() itself must wait out the pending reconcile.
let racePNG = try makeTinyPNGData()
_ = try await model.spool.append(
pngData: racePNG, pixelWidth: 64, pixelHeight: 48, scale: 1, capturedAt: Date()
)
model.replaceSession(try await model.spool.currentSession())
guard !model.session.isEmpty else {
throw OneDriveSelfTestError.detail("toggle-then-send: re-seeded session was empty")
}
let knownBeforeToggleSend = Set(
((try? fm.contentsOfDirectory(at: selftestFolder, includingPropertiesForKeys: nil)) ?? [])
.map(\.lastPathComponent)
)
model.chooseTransport(.airDrop)
model.chooseTransport(.oneDrive) // immediately superseding, no sleep before send()
await model.send(anchor: nil)
guard let toggleSendStatus = model.statusLine, toggleSendStatus.hasPrefix("Saved to OneDrive") else {
throw OneDriveSelfTestError.detail(
"toggle-then-send: status was \(model.statusLine ?? "nil"), expected 'Saved to OneDrive'"
)
}
guard model.session.isEmpty else {
throw OneDriveSelfTestError.detail("toggle-then-send: session was not archived")
}
let filesAfterToggleSend = (try? fm.contentsOfDirectory(
at: selftestFolder, includingPropertiesForKeys: nil
)) ?? []
guard let toggleSendPDFURL = filesAfterToggleSend.first(where: {
$0.pathExtension.lowercased() == "pdf" && !knownBeforeToggleSend.contains($0.lastPathComponent)
}) else {
throw OneDriveSelfTestError.detail("toggle-then-send: no new PDF found in \(selftestFolder.path)")
}
// The freshly-sent PDF is UNMARKED. If send() had raced ahead of the pending
// reconcile, recordUncommented could still have been (stale) true, and this
// scan would wrongly report it as already returned.
let scanAfterToggleSend = try await model.watcher.scanNow()
guard !scanAfterToggleSend.contains(where: { $0.fileURL == toggleSendPDFURL }) else {
throw OneDriveSelfTestError.detail(
"toggle-then-send: freshly-sent unmarked PDF at \(toggleSendPDFURL.path) was reported as returned — send() raced ahead of the pending reconcile"
)
}
// Sub-step 2: relaunch simulation see the doc comment above this function.
let relaunchAppSupportRoot = fm.temporaryDirectory
.appendingPathComponent("shotdeck-onedrive-relaunch-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: relaunchAppSupportRoot) }
let relaunchModel = AppDelegate.makeLaunchModel(appSupportRoot: relaunchAppSupportRoot)
guard relaunchModel.transport == .oneDrive else {
throw OneDriveSelfTestError.detail(
"relaunch: model transport was \(relaunchModel.transport), expected .oneDrive"
)
}
guard relaunchModel.watchFolderURL.path == selftestFolder.path else {
throw OneDriveSelfTestError.detail(
"relaunch: model watchFolderURL was \(relaunchModel.watchFolderURL.path), expected \(selftestFolder.path) — this is the exact BLOCKER this phase guards against"
)
}
await relaunchModel.bootstrap()
let relaunchPDFURL = selftestFolder.appendingPathComponent("Redline-relaunch-\(stamp).pdf")
try writeUnmarkedRedlinePDF(to: relaunchPDFURL)
try addInkMark(to: relaunchPDFURL)
let relaunchFound = try await relaunchModel.watcher.scanNow()
guard relaunchFound.first(where: { $0.fileURL == relaunchPDFURL })?.isCommented == true else {
throw OneDriveSelfTestError.detail(
"relaunch: watcher did not report the marked PDF at \(relaunchPDFURL.path) as returned — it was watching the wrong folder after relaunch"
)
}
await relaunchModel.watcher.stop()
return selftestFolder
}
/// Adds a real PDFKit ink annotation to the PDF at `url` in place and saves it
/// exactly what the iPad does when marking up a page.
private static func addInkMark(to url: URL) throws {
guard let document = PDFDocument(url: url), let page = document.page(at: 0) else {
throw OneDriveSelfTestError.detail("could not reopen \(url.path) to annotate it")
}
let ink = PDFAnnotation(
bounds: CGRect(x: 20, y: 20, width: 60, height: 60),
forType: .ink,
withProperties: nil
)
let stroke = NSBezierPath()
stroke.move(to: NSPoint(x: 20, y: 20))
stroke.line(to: NSPoint(x: 80, y: 80))
ink.add(stroke)
page.addAnnotation(ink)
guard document.write(to: url) else {
throw OneDriveSelfTestError.detail("could not save the annotated PDF back to \(url.path)")
}
}
/// Writes a fresh, unmarked, single-page "Redline"-creator PDF straight to `url`
/// standing in for a PDF that has just landed in the watch folder, before any
/// human mark. Used by the rapid-toggle and relaunch sub-steps, which don't need to
/// exercise send()/composePDFForSend() again (sub-step 1 already does).
private static func writeUnmarkedRedlinePDF(to url: URL) throws {
let document = PDFDocument()
let page = PDFPage()
page.setBounds(CGRect(x: 0, y: 0, width: 612, height: 792), for: .mediaBox)
document.insert(page, at: 0)
document.documentAttributes = [
PDFDocumentAttribute.creatorAttribute: "Redline",
PDFDocumentAttribute.subjectAttribute: UUID().uuidString,
]
guard document.write(to: url) else {
throw OneDriveSelfTestError.detail("could not write \(url.path)")
}
}
private static func oneDriveFail(_ detail: String) -> Never {
print("ONEDRIVE-SELFTEST FAIL \(detail)")
fflush(stdout)
exit(1)
}
private static func interpolate(_ step: Int) -> NSPoint { private static func interpolate(_ step: Int) -> NSPoint {
let t = CGFloat(step) / CGFloat(dragSteps) let t = CGFloat(step) / CGFloat(dragSteps)
return NSPoint( return NSPoint(
@@ -971,7 +699,7 @@ private enum UpdateSelfTestError: Error, CustomStringConvertible {
} }
} }
private enum OneDriveSelfTestError: Error, CustomStringConvertible { private enum HistorySelfTestError: Error, CustomStringConvertible {
case detail(String) case detail(String)
var description: String { var description: String {
switch self { switch self {
+41 -115
View File
@@ -16,66 +16,9 @@ extension AppModel: SendCapable {
guard !session.isEmpty, !isSending else { return } guard !session.isEmpty, !isSending else { return }
setSending(true) setSending(true)
// Wait for any IN-FLIGHT transport/folder reconcile (chooseTransport/
// chooseOneDriveFolder in SettingsView.swift) to fully settle BEFORE
// snapshotting transport/folder below. Without this, a toggle immediately
// followed by Send could let send() read a state that is still mid-transition
// e.g. the watcher's recordUncommented flag briefly lagging the just-chosen
// transport, so a freshly-sent unmarked OneDrive PDF gets misreported as an
// already-returned document. `Task<Void, Never>.value` never throws, and
// awaiting nil is an immediate no-op (AirDrop mode, or no toggle in flight).
await pendingReconcileTask?.value
// Snapshot BOTH the transport AND the destination folder into local `let`s
// ONCE, before any further `await` in this function. chooseTransport/
// chooseOneDriveFolder also refuse outright (status "Finish the current send
// first.") while isSending is true, but this snapshot is the actual fix for the
// send-vs-switch race: even without that guard, everything below operates on
// these frozen values composePDFForSend(outbox:transport:) takes both as
// parameters and never re-reads `self.outboxURL`/`self.transport` after a
// suspension point, so a concurrent transport switch mid-send can no longer
// land the PDF under one transport's folder while the archive/status branch
// runs the other's.
let transport = TransportSettings.transport()
let destinationFolder: URL
// OneDrive mode: verify the real destination exists, is writable, AND actually
// accepts a real write RIGHT NOW, before composing anything. `isWritableDirectory`
// alone is not enough a OneDrive Files-On-Demand directory whose provider
// domain is signed out can report as existing and POSIX-writable while an
// actual write fails, so `probeWritable` writes-fsyncs-removes a tiny real probe
// file to catch that. `outboxURL` is kept in sync with the resolved OneDrive
// folder by bootstrap/chooseTransport/chooseOneDriveFolder, but this is
// re-resolved fresh here (never trusted stale) so a folder that vanished or lost
// its permissions since then (OneDrive signed out, external volume unmounted,
// folder deleted, chmod'd unwritable) is caught instead of silently attempted
// and surfacing as a generic PDF-composition failure.
if transport == .oneDrive {
guard let folder = OneDriveLocator.resolveOneDriveFolder(),
OneDriveLocator.isWritableDirectory(at: folder),
OneDriveLocator.probeWritable(at: folder)
else {
let path = OneDriveLocator.resolveOneDriveFolder()?.path
?? TransportSettings.storedOneDriveFolderPath()
?? "no OneDrive folder found"
setResolvedOneDriveFolder(nil)
setStatus(ShotdeckError.oneDriveFolderUnavailable(path: path).errorDescription)
setSending(false)
return
}
destinationFolder = folder
setResolvedOneDriveFolder(folder)
if outboxURL != folder || watchFolderURL != folder {
setFolderURLs(outbox: folder, watch: folder)
try? await watcher.updateWatchFolder(folder)
}
} else {
destinationFolder = outboxURL
}
let pending: ComposedSend let pending: ComposedSend
do { do {
pending = try await composePDFForSend(outbox: destinationFolder, transport: transport) pending = try await composePDFForSend()
} catch { } catch {
// Never unlink the published PDF, and never unlink the temp file either: // Never unlink the published PDF, and never unlink the temp file either:
// a rename failure would leave the complete document at the temp name. // a rename failure would leave the complete document at the temp name.
@@ -84,59 +27,39 @@ extension AppModel: SendCapable {
return return
} }
switch transport { guard let anchor else {
case .oneDrive: handleDidFailToShareItems(fileName: pending.fileName)
// No AirDrop, no anchor needed the PDF is already in the watched
// OneDrive folder. Archive immediately; the iPad marks it up in place.
await handleDidShareItems(fileName: pending.fileName, pageCount: pending.pageCount)
let pageWord = pending.pageCount == 1 ? "page" : "pages"
setStatus(
"Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
)
setSending(false) setSending(false)
return
}
case .airDrop: do {
guard let anchor else { try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
handleDidFailToShareItems(fileName: pending.fileName) guard let self else { return }
setSending(false) if success {
return await self.handleDidShareItems(
} fileName: pending.fileName,
pageCount: pending.pageCount
do { )
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in } else {
guard let self else { return } self.handleDidFailToShareItems(fileName: pending.fileName)
if success {
await self.handleDidShareItems(
fileName: pending.fileName,
pageCount: pending.pageCount
)
} else {
self.handleDidFailToShareItems(fileName: pending.fileName)
}
self.setSending(false)
} }
} catch { self.setSending(false)
// canPerform false, no service, or no visible window: same as cancel.
handleDidFailToShareItems(fileName: pending.fileName)
setSending(false)
} }
} catch {
// canPerform false, no service, or no visible window: same as cancel.
handleDidFailToShareItems(fileName: pending.fileName)
setSending(false)
} }
} }
/// Writes the PDF to `outboxDir` and records its path. Does not archive the session /// Writes the PDF to the outbox and records its path. Does not archive the session
/// and does not present AirDrop that happens only after the share completes. /// and does not present AirDrop that happens only after the share completes.
/// `outboxDir`/`transport` are passed in (values `send(anchor:)` snapshotted before func composePDFForSend() async throws -> ComposedSend {
/// any await) rather than read from `self.outboxURL`/`self.transport` here, so a
/// concurrent transport switch mid-send can never redirect an in-flight compose to
/// a different folder. A write/rename failure specifically at the destination
/// folder (as opposed to composer.compose()'s own session/image-content failures)
/// is reported as `oneDriveFolderUnavailable` rather than the generic
/// `pdfCompositionFailed` when `transport == .oneDrive` the File Provider edge
/// case where the folder looked writable moments ago in `send(anchor:)` but the
/// actual write still failed (e.g. OneDrive signed out mid-write).
func composePDFForSend(outbox outboxDir: URL, transport: SendTransport) async throws -> ComposedSend {
let workingSession = session let workingSession = session
let composer = self.composer let composer = self.composer
// Live outbox (FolderSettings), not `paths.outbox` Settings changes take effect.
let outboxDir = outboxURL
let sourceDir = paths.sessionDirectory(workingSession.id) let sourceDir = paths.sessionDirectory(workingSession.id)
let fileName = PDFComposer.fileName(for: workingSession) let fileName = PDFComposer.fileName(for: workingSession)
let finalURL = outboxDir.appendingPathComponent(fileName) let finalURL = outboxDir.appendingPathComponent(fileName)
@@ -156,27 +79,14 @@ extension AppModel: SendCapable {
// POSIX rename onto `finalURL` replaces any same-name file in one // POSIX rename onto `finalURL` replaces any same-name file in one
// directory operation; there is never a window where the PDF is gone. // directory operation; there is never a window where the PDF is gone.
if Darwin.rename(tempURL.path, finalURL.path) != 0 { if Darwin.rename(tempURL.path, finalURL.path) != 0 {
if transport == .oneDrive {
throw ShotdeckError.oneDriveFolderUnavailable(path: outboxDir.path)
}
throw ShotdeckError.pdfCompositionFailed( throw ShotdeckError.pdfCompositionFailed(
reason: "could not publish the PDF: \(String(cString: strerror(errno)))" reason: "could not publish the PDF: \(String(cString: strerror(errno)))"
) )
} }
do { try AtomicFile.fsyncDirectory(at: outboxDir)
try AtomicFile.fsyncDirectory(at: outboxDir)
} catch {
if transport == .oneDrive {
throw ShotdeckError.oneDriveFolderUnavailable(path: outboxDir.path)
}
throw error
}
}.value }.value
guard FileManager.default.fileExists(atPath: finalURL.path) else { guard FileManager.default.fileExists(atPath: finalURL.path) else {
if transport == .oneDrive {
throw ShotdeckError.oneDriveFolderUnavailable(path: outboxDir.path)
}
throw ShotdeckError.pdfCompositionFailed(reason: "the PDF was not written to disk") throw ShotdeckError.pdfCompositionFailed(reason: "the PDF was not written to disk")
} }
rememberLastComposedPDF(finalURL) rememberLastComposedPDF(finalURL)
@@ -190,6 +100,8 @@ extension AppModel: SendCapable {
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam. /// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam.
func handleDidShareItems(fileName: String, pageCount: Int) async { func handleDidShareItems(fileName: String, pageCount: Int) async {
guard !session.isEmpty else { return } guard !session.isEmpty else { return }
let sentSessionID = session.id
let sourceURL = lastComposedPDFURL ?? outboxURL.appendingPathComponent(fileName)
do { do {
_ = try await spool.archiveCurrent(pdfFileName: fileName) _ = try await spool.archiveCurrent(pdfFileName: fileName)
replaceSession(try await spool.currentSession()) replaceSession(try await spool.currentSession())
@@ -197,6 +109,20 @@ extension AppModel: SendCapable {
setStatus("Sent — \(pageCount) \(pageWord).") setStatus("Sent — \(pageCount) \(pageWord).")
} catch { } catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.") setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")
return
}
do {
_ = try await historyStore.recordSentPDF(
sourceURL: sourceURL,
sessionID: sentSessionID,
pageCount: pageCount,
sentAt: Date()
)
try await historyStore.pruneImages()
} catch {
Log.spool.error(
"Could not record sent PDF into history at \(sourceURL.path, privacy: .public): \(error.localizedDescription, privacy: .public)"
)
} }
} }
+9 -143
View File
@@ -33,25 +33,6 @@ struct SettingsView: View {
.frame(minHeight: 22) .frame(minHeight: 22)
} }
GridRow {
Text("Send via")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.gridCellColumns(2)
.padding(.top, 6)
}
GridRow {
Picker("Send via", selection: transportBinding) {
ForEach(SendTransport.allCases, id: \.self) { transport in
Text(transport.displayName).tag(transport)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.gridCellColumns(2)
}
GridRow { GridRow {
Text("Folders") Text("Folders")
.font(.headline) .font(.headline)
@@ -60,47 +41,17 @@ struct SettingsView: View {
.padding(.top, 6) .padding(.top, 6)
} }
if model.transport == .airDrop { GridRow(alignment: .center) {
GridRow(alignment: .center) { fieldLabel("Watch folder")
fieldLabel("Watch folder") folderValue(path: model.watchFolderURL.path) {
folderValue(path: model.watchFolderURL.path) { model.chooseWatchFolder()
model.chooseWatchFolder()
}
} }
}
GridRow(alignment: .center) { GridRow(alignment: .center) {
fieldLabel("Output folder") fieldLabel("Output folder")
folderValue(path: model.outboxURL.path) { folderValue(path: model.outboxURL.path) {
model.chooseOutboxFolder() model.chooseOutboxFolder()
}
}
} else {
GridRow(alignment: .center) {
fieldLabel("OneDrive folder")
if let folder = model.resolvedOneDriveFolder {
folderValue(path: folder.path) {
model.chooseOneDriveFolder()
}
} else {
// One-line row, same shape as the normal path row: "Not found"
// where the path would be, Choose stays live. The explanation
// moves to the caption below instead of wrapping this row.
folderValue(path: "Not found") {
model.chooseOneDriveFolder()
}
}
}
GridRow {
Text(
model.resolvedOneDriveFolder != nil
? "The PDF is saved here and this same folder is watched for the marked-up copy. On the iPad open it from Files > OneDrive."
: "No OneDrive folder found. Sign in to OneDrive, or choose a folder."
)
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
.gridCellColumns(2)
} }
} }
@@ -117,10 +68,6 @@ struct SettingsView: View {
.onDisappear { disarmHotkeyRecorder() } .onDisappear { disarmHotkeyRecorder() }
} }
private var transportBinding: Binding<SendTransport> {
Binding(get: { model.transport }, set: { model.chooseTransport($0) })
}
private func armHotkeyRecorder() { private func armHotkeyRecorder() {
guard !isRecordingHotkey else { return } guard !isRecordingHotkey else { return }
isRecordingHotkey = true isRecordingHotkey = true
@@ -243,87 +190,6 @@ extension AppModel: SettingsWindowPresenting {
} }
} }
/// Settings "Send via" picker action. Persists the choice, recomputes the effective
/// outbox/watch folder for the new transport, creates the OneDrive folder if it
/// doesn't exist yet, and re-points the running watcher (folder + recordUncommented)
/// at the new state. Switching back to AirDrop restores its own stored overrides
/// untouched, since AirDrop and OneDrive folder settings are stored under separate keys.
/// Refuses while a send is in flight (send() snapshots its own folder/transport, but
/// switching mid-send is still confusing UX nothing to gain by allowing it).
/// The async reconcile below is generation-guarded: `reconcileGeneration` is bumped
/// synchronously before the Task starts, and the Task checks its own snapshot against
/// the live value before every mutating step, so rapid toggling (this function or
/// chooseOneDriveFolder, in any order) always lets the LAST choice win instead of an
/// earlier, superseded call applying its stale folder/flag after a later one already won.
/// The Task's handle is stored in `pendingReconcileTask` so send() can await its
/// completion before snapshotting transport/folder closing the OTHER race, where a
/// toggle is immediately followed by Send before this reconcile has settled.
func chooseTransport(_ value: SendTransport) {
guard !isSending else {
setStatus("Finish the current send first.")
return
}
guard value != transport else { return }
TransportSettings.setTransport(value)
setTransport(value)
let folders = TransportSettings.effectiveFolders()
if value == .oneDrive {
try? FileManager.default.createDirectory(
at: folders.outbox, withIntermediateDirectories: true
)
}
setFolderURLs(outbox: folders.outbox, watch: folders.watch)
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
reconcileGeneration += 1
let generation = reconcileGeneration
pendingReconcileTask = Task {
guard generation == self.reconcileGeneration else { return }
await watcher.setRecordUncommented(value == .airDrop)
guard generation == self.reconcileGeneration else { return }
do {
try await watcher.updateWatchFolder(folders.watch)
} catch {
guard generation == self.reconcileGeneration else { return }
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
/// Refuses while a send is in flight, same reasoning as chooseTransport. See
/// chooseTransport's doc comment for the generation-guard mechanism shared here.
func chooseOneDriveFolder() {
guard !isSending else {
setStatus("Finish the current send first.")
return
}
let start = resolvedOneDriveFolder ?? FileManager.default.homeDirectoryForCurrentUser
guard let url = chooseDirectory(startingAt: start) else { return }
TransportSettings.setOneDriveFolder(url)
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
guard transport == .oneDrive else { return }
setFolderURLs(outbox: url, watch: url)
reconcileGeneration += 1
let generation = reconcileGeneration
pendingReconcileTask = Task {
guard generation == self.reconcileGeneration else { return }
do {
try await watcher.updateWatchFolder(url)
guard generation == self.reconcileGeneration else { return }
setStatus("OneDrive folder set to \(url.lastPathComponent).")
} catch {
guard generation == self.reconcileGeneration else { return }
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
private func chooseDirectory(startingAt directory: URL) -> URL? { private func chooseDirectory(startingAt directory: URL) -> URL? {
let panel = NSOpenPanel() let panel = NSOpenPanel()
panel.canChooseDirectories = true panel.canChooseDirectories = true
+22 -245
View File
@@ -1,8 +1,6 @@
import AppKit import AppKit
import CryptoKit import CryptoKit
import Foundation import Foundation
import Security
import ShotdeckCore
/// Built-in updater. Checks an appcast, stages a verified payload, and installs /// Built-in updater. Checks an appcast, stages a verified payload, and installs
/// only when the user clicks the menu row never automatically. /// only when the user clicks the menu row never automatically.
@@ -12,37 +10,22 @@ final class UpdateChecker {
static let defaultAppcastURL = URL(string: "https://get.baobab-ts.com/cowork/redline/appcast.json")! static let defaultAppcastURL = URL(string: "https://get.baobab-ts.com/cowork/redline/appcast.json")!
static let defaultInstallTarget = URL(fileURLWithPath: "/Applications/Redline.app") static let defaultInstallTarget = URL(fileURLWithPath: "/Applications/Redline.app")
/// Required bundle identifier for any staged or installed payload.
static let expectedBundleIdentifier = "ai.flowmaster.shotdeck"
/// Developer team identifiers MMD ships Redline under. Overridable only for the self-test.
static let allowedTeamIdentifiers: Set<String> = ["PWMCBMX5M8", "L3N9S54CN3"]
private(set) var availableUpdate: (version: String, notes: String)? private(set) var availableUpdate: (version: String, notes: String)?
private(set) var stagedAppURL: URL? private(set) var stagedAppURL: URL?
private(set) var statusMessage: String? private(set) var statusMessage: String?
private(set) var lastCheckedAt: Date?
private(set) var isCheckingNow: Bool = false
var onChecked: (() -> Void)? var onChecked: (() -> Void)?
/// Fired whenever `isCheckingNow` flips, so a UI can show "Checking" for the
/// whole duration of a check rather than only after it lands.
var onCheckingChanged: ((Bool) -> Void)?
private let urlSession: URLSession private let urlSession: URLSession
private var repeatingTimer: Timer? private var repeatingTimer: Timer?
private var firstCheckTask: Task<Void, Never>? private var firstCheckTask: Task<Void, Never>?
private var isChecking = false
private var stagingDirectory: URL? private var stagingDirectory: URL?
/// Snapshot-only override for previousVersion; when snapshotUsesPreviousVersionOverride is true,
/// this value (including nil) is returned instead of checking the file system.
var snapshotPreviousVersionOverride: String?
var snapshotUsesPreviousVersionOverride: Bool = false
/// Test seam: override appcast JSON. When set, returns this instead of fetching from URL.
var testAppcastJSON: String?
init() { init() {
let config = URLSessionConfiguration.ephemeral let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 30 config.timeoutIntervalForRequest = 15
config.timeoutIntervalForResource = 600 config.timeoutIntervalForResource = 15
config.httpCookieAcceptPolicy = .never config.httpCookieAcceptPolicy = .never
config.httpShouldSetCookies = false config.httpShouldSetCookies = false
config.httpCookieStorage = nil config.httpCookieStorage = nil
@@ -68,18 +51,10 @@ final class UpdateChecker {
repeatingTimer = timer repeatingTimer = timer
} }
/// Checks the appcast and stages a newer, signature-verified payload. func checkNow() async {
/// `manual` only affects the status message shown when already up to date guard !isChecking else { return }
/// a user-initiated check says so; the silent background check stays quiet. isChecking = true
func checkNow(manual: Bool = false) async { defer { isChecking = false }
guard !isCheckingNow else { return }
isCheckingNow = true
onCheckingChanged?(true)
defer {
isCheckingNow = false
onCheckingChanged?(false)
}
lastCheckedAt = Date()
let appcast: Appcast let appcast: Appcast
do { do {
@@ -92,12 +67,7 @@ final class UpdateChecker {
guard Self.isNewer(appcast.version, than: Self.currentVersion()) else { guard Self.isNewer(appcast.version, than: Self.currentVersion()) else {
clearOffer() clearOffer()
if manual { statusMessage = nil
let timestamp = DubaiTime.checkTime(lastCheckedAt ?? Date())
statusMessage = "Redline \(Self.currentVersion()) is up to date, checked \(timestamp)"
} else {
statusMessage = nil
}
onChecked?() onChecked?()
return return
} }
@@ -105,15 +75,11 @@ final class UpdateChecker {
do { do {
try await downloadAndStage(appcast) try await downloadAndStage(appcast)
availableUpdate = (version: appcast.version, notes: appcast.notes ?? "") availableUpdate = (version: appcast.version, notes: appcast.notes ?? "")
statusMessage = manual ? "Update to \(appcast.version) is ready" : nil statusMessage = nil
} catch UpdateCheckError.checksumMismatch { } catch UpdateCheckError.checksumMismatch {
discardStaging() discardStaging()
availableUpdate = nil availableUpdate = nil
statusMessage = "Update file failed the checksum — not installed." statusMessage = "Update file failed the checksum — not installed."
} catch UpdateCheckError.signatureInvalid {
discardStaging()
availableUpdate = nil
statusMessage = "Update is not signed by MMD — not installed."
} catch { } catch {
discardStaging() discardStaging()
availableUpdate = nil availableUpdate = nil
@@ -122,9 +88,9 @@ final class UpdateChecker {
onChecked?() onChecked?()
} }
/// Installs the staged app onto `target` atomically, keeping exactly one rollback /// Copies the staged app onto `target` with ditto (in place; never deletes the old app).
/// copy (`Redline.app.previous`), then hands off to a relaunch and quits. /// Relaunches unless `SHOTDECK_UPDATE_SELFTEST` is set, so the in-process self-test
/// Never deletes the old app before the new one is verified in place. /// can assert the installed Info.plist without killing the process.
func installStaged(to target: URL = UpdateChecker.defaultInstallTarget) { func installStaged(to target: URL = UpdateChecker.defaultInstallTarget) {
guard let staged = stagedAppURL else { guard let staged = stagedAppURL else {
statusMessage = "No update is staged." statusMessage = "No update is staged."
@@ -132,121 +98,29 @@ final class UpdateChecker {
return return
} }
let targetDir = target.deletingLastPathComponent()
let previousURL = targetDir.appendingPathComponent("Redline.app.previous")
do { do {
try FileManager.default.createDirectory(at: targetDir, withIntermediateDirectories: true) try FileManager.default.createDirectory(
at: target.deletingLastPathComponent(),
let replacementDir = try FileManager.default.url( withIntermediateDirectories: true
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: target,
create: true
) )
defer { try? FileManager.default.removeItem(at: replacementDir) } try Self.runProcess(executable: "/usr/bin/ditto", arguments: [staged.path, target.path])
let newCopy = replacementDir.appendingPathComponent(target.lastPathComponent)
try Self.runProcess(executable: "/usr/bin/ditto", arguments: [staged.path, newCopy.path])
// Exactly one rollback copy is kept drop any older one before this install.
if FileManager.default.fileExists(atPath: previousURL.path) {
try FileManager.default.removeItem(at: previousURL)
}
if FileManager.default.fileExists(atPath: target.path) {
_ = try FileManager.default.replaceItemAt(
target,
withItemAt: newCopy,
backupItemName: previousURL.lastPathComponent,
options: [.withoutDeletingBackupItem]
)
} else {
try FileManager.default.moveItem(at: newCopy, to: target)
}
} catch { } catch {
statusMessage = "The update could not be installed." statusMessage = "The update could not be installed."
onChecked?() onChecked?()
return return
} }
// Defense in depth: re-verify what actually landed on disk, not just the staged copy. let isSelfTest = ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
do { if isSelfTest { return }
try Self.verifySignature(of: target)
} catch {
statusMessage = "The update was installed but failed verification."
onChecked?()
return
}
discardStaging()
availableUpdate = nil
relaunch(target: target)
}
/// Swaps `Redline.app.previous` back into place, verifying its signature first.
/// The just-replaced (newer) app becomes the new `.previous` a revert is
/// itself reversible.
func revertToPrevious(target: URL = UpdateChecker.defaultInstallTarget) {
let targetDir = target.deletingLastPathComponent()
let previousURL = targetDir.appendingPathComponent("Redline.app.previous")
guard FileManager.default.fileExists(atPath: previousURL.path) else {
statusMessage = "No previous version to revert to."
onChecked?()
return
}
do { do {
try Self.verifySignature(of: previousURL) try Self.runProcess(executable: "/usr/bin/open", arguments: ["-n", target.path])
} catch { } catch {
statusMessage = "The previous version failed verification and was not restored." statusMessage = "The update was installed but Redline could not relaunch. Open it from Applications."
onChecked?() onChecked?()
return return
} }
NSApp.terminate(nil)
do {
// `previousURL` cannot be handed to replaceItemAt directly: its own path
// IS the requested backup name, so the backup step would clobber it
// before the swap ever reads it. Stage a throwaway copy first, exactly
// like installStaged does for the forward direction.
let replacementDir = try FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: target,
create: true
)
defer { try? FileManager.default.removeItem(at: replacementDir) }
let newCopy = replacementDir.appendingPathComponent(target.lastPathComponent)
try Self.runProcess(executable: "/usr/bin/ditto", arguments: [previousURL.path, newCopy.path])
try FileManager.default.removeItem(at: previousURL)
_ = try FileManager.default.replaceItemAt(
target,
withItemAt: newCopy,
backupItemName: previousURL.lastPathComponent,
options: [.withoutDeletingBackupItem]
)
} catch {
statusMessage = "Could not revert to the previous version."
onChecked?()
return
}
relaunch(target: target)
}
/// The version recorded in `Redline.app.previous`'s Info.plist, or nil when no
/// rollback copy exists. Respects the snapshot-only override for panel rendering.
func previousVersion(target: URL = UpdateChecker.defaultInstallTarget) -> String? {
if snapshotUsesPreviousVersionOverride {
return snapshotPreviousVersionOverride
}
let previousURL = target.deletingLastPathComponent().appendingPathComponent("Redline.app.previous")
let plistURL = previousURL.appendingPathComponent("Contents/Info.plist")
guard let plist = NSDictionary(contentsOf: plistURL) as? [String: Any] else { return nil }
return plist["CFBundleShortVersionString"] as? String
} }
static func resolvedAppcastURL() -> URL { static func resolvedAppcastURL() -> URL {
@@ -282,67 +156,6 @@ final class UpdateChecker {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
} }
/// Validates the code signature of the app at `appURL`: strictly, across all
/// architectures and nested code, then checks its bundle identifier and team
/// identifier against `expectedBundleIdentifier` / the allowed-teams set.
/// `REDLINE_ALLOWED_TEAMS` (comma separated) overrides the allowed set for
/// the self-test only, so it can accept a locally re-signed fake bundle.
static func verifySignature(of appURL: URL) throws {
var staticCode: SecStaticCode?
let createStatus = SecStaticCodeCreateWithPath(appURL as CFURL, [], &staticCode)
guard createStatus == errSecSuccess, let code = staticCode else {
throw UpdateCheckError.signatureInvalid(
"could not read a code signature (status \(createStatus))"
)
}
let validityFlags = SecCSFlags(
rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode
)
var validityError: Unmanaged<CFError>?
let validityStatus = SecStaticCodeCheckValidityWithErrors(code, validityFlags, nil, &validityError)
guard validityStatus == errSecSuccess else {
let detail = (validityError?.takeRetainedValue()).map { String(describing: $0) } ?? "status \(validityStatus)"
throw UpdateCheckError.signatureInvalid("signature is not valid: \(detail)")
}
var signingInfo: CFDictionary?
let infoStatus = SecCodeCopySigningInformation(
code,
SecCSFlags(rawValue: kSecCSSigningInformation),
&signingInfo
)
guard infoStatus == errSecSuccess, let info = signingInfo as? [String: Any] else {
throw UpdateCheckError.signatureInvalid("could not read signing information (status \(infoStatus))")
}
let identifier = info[kSecCodeInfoIdentifier as String] as? String
guard identifier == expectedBundleIdentifier else {
throw UpdateCheckError.signatureInvalid(
"unexpected bundle identifier: \(identifier ?? "nil")"
)
}
let teamIdentifier = info[kSecCodeInfoTeamIdentifier as String] as? String
guard let teamIdentifier, resolvedAllowedTeamIdentifiers().contains(teamIdentifier) else {
throw UpdateCheckError.signatureInvalid(
"unexpected team identifier: \(teamIdentifier ?? "nil")"
)
}
}
private static func resolvedAllowedTeamIdentifiers() -> Set<String> {
if let env = ProcessInfo.processInfo.environment["REDLINE_ALLOWED_TEAMS"], !env.isEmpty {
let parts = env.split(separator: ",")
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if !parts.isEmpty {
return Set(parts)
}
}
return allowedTeamIdentifiers
}
// MARK: - Private // MARK: - Private
private struct Appcast: Decodable { private struct Appcast: Decodable {
@@ -357,16 +170,10 @@ final class UpdateChecker {
case invalidPayload case invalidPayload
case httpStatus(Int) case httpStatus(Int)
case processFailed(String) case processFailed(String)
case signatureInvalid(String)
} }
private func fetchAppcast() async throws -> Appcast { private func fetchAppcast() async throws -> Appcast {
let data: Data let data = try await fetchData(from: Self.resolvedAppcastURL())
if let testJSON = testAppcastJSON {
data = testJSON.data(using: .utf8) ?? Data()
} else {
data = try await fetchData(from: Self.resolvedAppcastURL())
}
return try JSONDecoder().decode(Appcast.self, from: data) return try JSONDecoder().decode(Appcast.self, from: data)
} }
@@ -412,7 +219,6 @@ final class UpdateChecker {
guard FileManager.default.fileExists(atPath: executable.path) else { guard FileManager.default.fileExists(atPath: executable.path) else {
throw UpdateCheckError.invalidPayload throw UpdateCheckError.invalidPayload
} }
try Self.verifySignature(of: appURL)
stagedAppURL = appURL stagedAppURL = appURL
} }
@@ -429,35 +235,6 @@ final class UpdateChecker {
stagedAppURL = nil stagedAppURL = nil
} }
/// Spawns a detached watcher that waits for this process to exit, then reopens
/// `target`, and quits. Never called during the self-test, so the in-process
/// assertions after `installStaged`/`revertToPrevious` can still run.
private func relaunch(target: URL) {
guard ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] == nil else { return }
let ownPID = ProcessInfo.processInfo.processIdentifier
let script = "while kill -0 \(ownPID) 2>/dev/null; do sleep 0.2; done; " +
"/usr/bin/open -n \(Self.shellQuoted(target.path))"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/sh")
process.arguments = ["-c", script]
process.standardInput = FileHandle.nullDevice
process.standardOutput = FileHandle.nullDevice
process.standardError = FileHandle.nullDevice
do {
try process.run()
} catch {
statusMessage = "The update was installed but Redline could not relaunch. Open it from Applications."
onChecked?()
return
}
NSApp.terminate(nil)
}
private static func shellQuoted(_ path: String) -> String {
"'" + path.replacingOccurrences(of: "'", with: "'\\''") + "'"
}
private static func findRedlineApp(in directory: URL) -> URL? { private static func findRedlineApp(in directory: URL) -> URL? {
let fm = FileManager.default let fm = FileManager.default
let direct = directory.appendingPathComponent("Redline.app") let direct = directory.appendingPathComponent("Redline.app")
+6 -40
View File
@@ -7,11 +7,10 @@ import ShotdeckCore
if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil { if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil {
MainActor.assumeIsolated { PanelSnapshot.runIfRequested() } MainActor.assumeIsolated { PanelSnapshot.runIfRequested() }
} }
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" {
MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() }
}
if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil { if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil {
MainActor.assumeIsolated { PickerSelfTest.runIfRequested() } MainActor.assumeIsolated { PickerSelfTest.runIfRequested() }
} else if ProcessInfo.processInfo.environment["SHOTDECK_HISTORY_SELFTEST"] != nil {
MainActor.assumeIsolated { PickerSelfTest.runHistoryIfRequested() }
} }
ShotdeckApp.main() ShotdeckApp.main()
@@ -24,9 +23,8 @@ struct ShotdeckApp: App {
.environment(appDelegate.model) .environment(appDelegate.model)
} label: { } label: {
let state = appDelegate.model.iconState let state = appDelegate.model.iconState
let hasUpdate = appDelegate.model.updateAvailable != nil
HStack(spacing: 4) { HStack(spacing: 4) {
menuBarIcon(for: state, hasUpdate: hasUpdate) Image(systemName: state.symbolName)
if let count = state.countText { if let count = state.countText {
Text(count).font(.system(size: 11, weight: .semibold)) Text(count).font(.system(size: 11, weight: .semibold))
} }
@@ -37,29 +35,6 @@ struct ShotdeckApp: App {
} }
} }
/// The menu-bar symbol for `state`, badged while an update is staged. Uses the
/// SF Symbol's own `.badge` variant when one exists; falls back to a small
/// overlaid dot on the plain symbol otherwise. The badge disappears on its own
/// once `updateAvailable` clears, since this reads live model state.
@ViewBuilder
private func menuBarIcon(for state: MenuIconState, hasUpdate: Bool) -> some View {
if hasUpdate {
let badgeName = "\(state.symbolName).badge"
if NSImage(systemSymbolName: badgeName, accessibilityDescription: nil) != nil {
Image(systemName: badgeName)
} else {
ZStack(alignment: .topTrailing) {
Image(systemName: state.symbolName)
Circle()
.frame(width: 6, height: 6)
.offset(x: 3, y: -3)
}
}
} else {
Image(systemName: state.symbolName)
}
}
@MainActor @MainActor
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
let model: AppModel let model: AppModel
@@ -74,18 +49,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
Task { await model.bootstrap() } Task { await model.bootstrap() }
} }
/// Builds the model exactly the way the real app launches: paths come from private static func makeLaunchModel() -> AppModel {
/// `TransportSettings.resolvedAppSupportPaths()` transport-aware, so the watcher
/// this feeds is never seeded with a stale AirDrop folder while OneDrive is the
/// persisted transport (that was the BLOCKER this function used to have, when it
/// called the AirDrop-only `FolderSettings.resolvedAppSupportPaths()` instead).
/// `appSupportRoot` exists only so PickerSelfTest's relaunch-simulation sub-step can
/// 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 {
do { do {
let paths = try TransportSettings.resolvedAppSupportPaths(root: appSupportRoot) let paths = try FolderSettings.resolvedAppSupportPaths()
return try makeModel(paths: paths) return try makeModel(paths: paths)
} catch { } catch {
Log.ui.critical( Log.ui.critical(
@@ -103,7 +69,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private static func makeModel(paths: AppSupportPaths) throws -> AppModel { private static func makeModel(paths: AppSupportPaths) throws -> AppModel {
let ledger = try ReturnLedger(paths: paths) let ledger = try ReturnLedger(paths: paths)
return AppModel( return try AppModel(
paths: paths, paths: paths,
spool: try SpoolStore(paths: paths), spool: try SpoolStore(paths: paths),
composer: PDFComposer(), composer: PDFComposer(),
@@ -0,0 +1,446 @@
import Foundation
/// Retention ruling (2026-09-02). Ben's instruction is the authority that
/// supersedes the earlier D-11 never-delete rule FOR THIS STORE only:
///
/// "the last 10 files are saved, and the past 30 images, and cleared up
/// afterwards. user should be able to select from those and send again."
///
/// App-managed copies live under `AppSupportPaths.root/history/`. Pruning
/// unlinks files under `history/pdfs/` and archived capture PNGs beyond the
/// newest 30. It never deletes a user file, never touches the outbox PDF, and
/// never touches the open spool session (D-11 still applies there).
/// One sent-PDF copy retained for re-send. The file at `fileURL` is the
/// app-managed copy under `history/pdfs/`, not the user's original.
public struct HistoryEntry: Codable, Sendable, Equatable, Identifiable {
public let id: UUID
public let fileName: String
public let fileURL: URL
public let originalFileName: String
public let sessionID: UUID?
public let pageCount: Int
public let sentAt: Date
public init(
id: UUID,
fileName: String,
fileURL: URL,
originalFileName: String,
sessionID: UUID?,
pageCount: Int,
sentAt: Date
) {
self.id = id
self.fileName = fileName
self.fileURL = fileURL
self.originalFileName = originalFileName
self.sessionID = sessionID
self.pageCount = pageCount
self.sentAt = sentAt
}
}
/// A capture PNG on disk under an archived session, listed for re-send.
/// `path` is the real file; HistoryStore never copies images.
public struct ImageRef: Sendable, Equatable {
public let path: URL
public let capturedAt: Date
public let sessionID: UUID
public init(path: URL, capturedAt: Date, sessionID: UUID) {
self.path = path
self.capturedAt = capturedAt
self.sessionID = sessionID
}
}
public actor HistoryStore {
public static let pdfRetentionCount = 10
public static let imageRetentionCount = 30
private let paths: AppSupportPaths
private let historyRoot: URL
private let pdfsDirectory: URL
private let manifestURL: URL
private var entries: [HistoryEntry]
public init(paths: AppSupportPaths) throws {
self.paths = paths
self.historyRoot = paths.root.appendingPathComponent("history", isDirectory: true)
self.pdfsDirectory = historyRoot.appendingPathComponent("pdfs", isDirectory: true)
self.manifestURL = historyRoot.appendingPathComponent("history.json")
do {
try FileManager.default.createDirectory(at: historyRoot, withIntermediateDirectories: true)
try FileManager.default.createDirectory(at: pdfsDirectory, withIntermediateDirectories: true)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: historyRoot.path,
underlying: error.localizedDescription
)
}
self.entries = try Self.loadEntries(from: manifestURL, pdfsDirectory: pdfsDirectory)
}
/// Copies `sourceURL` into `history/pdfs/` (never moves or writes the
/// user's file), appends an entry, then keeps the 10 newest PDF copies.
public func recordSentPDF(
sourceURL: URL,
sessionID: UUID?,
pageCount: Int,
sentAt: Date
) throws -> HistoryEntry {
let fm = FileManager.default
guard fm.fileExists(atPath: sourceURL.path) else {
throw ShotdeckError.spoolWriteFailed(
path: sourceURL.path,
underlying: "source PDF does not exist"
)
}
let data: Data
do {
data = try Data(contentsOf: sourceURL)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: sourceURL.path,
underlying: error.localizedDescription
)
}
let id = UUID()
let fileName = "\(DubaiTime.fileStamp(sentAt))-\(id.uuidString.lowercased()).pdf"
let destURL = pdfsDirectory.appendingPathComponent(fileName)
try AtomicFile.write(data, to: destURL)
let entry = HistoryEntry(
id: id,
fileName: fileName,
fileURL: destURL,
originalFileName: sourceURL.lastPathComponent,
sessionID: sessionID,
pageCount: pageCount,
sentAt: sentAt
)
entries.append(entry)
try prunePDFEntries()
return entry
}
/// Newest first, at most `pdfRetentionCount`.
public func listPDFs() -> [HistoryEntry] {
Array(sortedPDFs().prefix(Self.pdfRetentionCount))
}
/// The newest capture PNGs across `archive/` sessions (including
/// `removed/`). Does not copy files and does not look at the open spool.
public func listImages(limit: Int = 30) throws -> [ImageRef] {
let images = try collectArchivedImages()
return images.prefix(max(limit, 0)).map(\.ref)
}
/// Across archived sessions only: keep the 30 newest PNGs total (including
/// `removed/`); delete older PNGs, drop them from `session.json`, and
/// remove a session directory left with zero PNGs. Never touches spool/.
public func pruneImages() throws {
let fm = FileManager.default
let images = try collectArchivedImages()
let keepCount = Self.imageRetentionCount
let doomed = Array(images.dropFirst(keepCount))
guard !doomed.isEmpty else { return }
var remainingBySession: [UUID: CaptureSession] = [:]
var dirBySession: [UUID: URL] = [:]
for item in images {
remainingBySession[item.session.id] = item.session
dirBySession[item.session.id] = item.sessionDir
}
var droppedIDs: [UUID: Set<UUID>] = [:]
for item in doomed {
try deleteIfPrunableImage(item.ref.path)
if let captureID = item.captureID {
droppedIDs[item.session.id, default: []].insert(captureID)
}
}
for (sessionID, ids) in droppedIDs {
guard var session = remainingBySession[sessionID] else { continue }
for id in ids {
session = session.removing(captureID: id)
}
remainingBySession[sessionID] = session
}
let touchedIDs = Set(doomed.map(\.session.id))
for sessionID in touchedIDs {
guard let sessionDir = dirBySession[sessionID] else { continue }
guard isUnderArchive(sessionDir), !isUnderSpool(sessionDir) else { continue }
if pngsRemaining(in: sessionDir).isEmpty {
if fm.fileExists(atPath: sessionDir.path) {
try fm.removeItem(at: sessionDir)
Log.spool.warning("Pruned \(sessionDir.path, privacy: .public)")
}
try AtomicFile.fsyncDirectory(at: paths.archive)
continue
}
if let session = remainingBySession[sessionID], droppedIDs[sessionID] != nil {
try AtomicFile.writeJSON(
session,
to: sessionDir.appendingPathComponent("session.json")
)
}
}
}
// MARK: - PDF retention
private func prunePDFEntries() throws {
let sorted = sortedPDFs()
let kept = Array(sorted.prefix(Self.pdfRetentionCount))
let discarded = sorted.dropFirst(Self.pdfRetentionCount)
for entry in discarded {
let url = pdfsDirectory.appendingPathComponent(entry.fileName)
try deleteIfAppManagedPDF(url)
}
entries = kept
try persistEntries()
}
private func sortedPDFs() -> [HistoryEntry] {
entries.sorted { lhs, rhs in
if lhs.sentAt != rhs.sentAt { return lhs.sentAt > rhs.sentAt }
return lhs.id.uuidString > rhs.id.uuidString
}
}
private func persistEntries() throws {
try AtomicFile.writeJSON(entries, to: manifestURL)
}
private func deleteIfAppManagedPDF(_ url: URL) throws {
guard isUnderPDFs(url) else { return }
let fm = FileManager.default
guard fm.fileExists(atPath: url.path) else { return }
do {
try fm.removeItem(at: url)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: url.path,
underlying: error.localizedDescription
)
}
Log.spool.warning("Pruned \(url.path, privacy: .public)")
try AtomicFile.fsyncDirectory(at: pdfsDirectory)
}
// MARK: - Archived images
private struct ArchivedImage {
let ref: ImageRef
let session: CaptureSession
let sessionDir: URL
let captureID: UUID?
}
private func collectArchivedImages() throws -> [ArchivedImage] {
let dirs = try archivedSessionDirectories()
var collected: [ArchivedImage] = []
for dir in dirs {
let sessionID = UUID(uuidString: dir.lastPathComponent) ?? UUID()
let session = (try? loadSession(at: dir, id: sessionID))
?? CaptureSession(
id: sessionID,
createdAt: fileDate(dir) ?? Date(),
state: .archived,
captures: [],
pdfFileName: nil
)
var referenced = Set<String>()
for capture in session.captures {
let url = dir.appendingPathComponent(capture.fileName)
guard FileManager.default.fileExists(atPath: url.path) else { continue }
referenced.insert(capture.fileName)
collected.append(
ArchivedImage(
ref: ImageRef(path: url, capturedAt: capture.capturedAt, sessionID: session.id),
session: session,
sessionDir: dir,
captureID: capture.id
)
)
}
let removedDir = dir.appendingPathComponent("removed", isDirectory: true)
for url in pngFiles(in: dir) where !referenced.contains(url.lastPathComponent) {
collected.append(
ArchivedImage(
ref: ImageRef(
path: url,
capturedAt: fileDate(url) ?? .distantPast,
sessionID: session.id
),
session: session,
sessionDir: dir,
captureID: nil
)
)
}
for url in pngFiles(in: removedDir) {
collected.append(
ArchivedImage(
ref: ImageRef(
path: url,
capturedAt: fileDate(url) ?? .distantPast,
sessionID: session.id
),
session: session,
sessionDir: dir,
captureID: nil
)
)
}
}
return collected.sorted { lhs, rhs in
if lhs.ref.capturedAt != rhs.ref.capturedAt {
return lhs.ref.capturedAt > rhs.ref.capturedAt
}
return lhs.ref.path.path > rhs.ref.path.path
}
}
private func archivedSessionDirectories() throws -> [URL] {
let fm = FileManager.default
let entries: [URL]
do {
entries = try fm.contentsOfDirectory(
at: paths.archive,
includingPropertiesForKeys: [.isDirectoryKey],
options: []
)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: paths.archive.path,
underlying: error.localizedDescription
)
}
return entries.filter { url in
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
return isDirectory && UUID(uuidString: url.lastPathComponent) != nil
}
}
private func loadSession(at dir: URL, id: UUID) throws -> CaptureSession {
let url = dir.appendingPathComponent("session.json")
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let session = try decoder.decode(CaptureSession.self, from: data)
guard session.id == id else {
throw ShotdeckError.manifestCorrupt(path: url.path)
}
return session
}
private func pngFiles(in dir: URL) -> [URL] {
let fm = FileManager.default
guard fm.fileExists(atPath: dir.path) else { return [] }
let entries = (try? fm.contentsOfDirectory(
at: dir,
includingPropertiesForKeys: [.isDirectoryKey],
options: []
)) ?? []
return entries.filter { url in
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
return !isDirectory && url.pathExtension.lowercased() == "png"
}
}
private func pngsRemaining(in sessionDir: URL) -> [URL] {
pngFiles(in: sessionDir)
+ pngFiles(in: sessionDir.appendingPathComponent("removed", isDirectory: true))
}
private func deleteIfPrunableImage(_ url: URL) throws {
guard isUnderArchive(url), !isUnderSpool(url) else { return }
let fm = FileManager.default
guard fm.fileExists(atPath: url.path) else { return }
do {
try fm.removeItem(at: url)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: url.path,
underlying: error.localizedDescription
)
}
Log.spool.warning("Pruned \(url.path, privacy: .public)")
try AtomicFile.fsyncDirectory(at: url.deletingLastPathComponent())
}
private func fileDate(_ url: URL) -> Date? {
let values = try? url.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
return values?.creationDate ?? values?.contentModificationDate
}
// MARK: - Path guards
private func isUnderPDFs(_ url: URL) -> Bool {
isUnderDirectory(url, parent: pdfsDirectory)
}
private func isUnderArchive(_ url: URL) -> Bool {
isUnderDirectory(url, parent: paths.archive)
}
private func isUnderSpool(_ url: URL) -> Bool {
isUnderDirectory(url, parent: paths.spool)
}
private func isUnderDirectory(_ url: URL, parent: URL) -> Bool {
let parentPath = parent.standardizedFileURL.path
let path = url.standardizedFileURL.path
if path == parentPath { return true }
let prefix = parentPath.hasSuffix("/") ? parentPath : parentPath + "/"
return path.hasPrefix(prefix)
}
// MARK: - Manifest load
private static func loadEntries(from url: URL, pdfsDirectory: URL) throws -> [HistoryEntry] {
let fm = FileManager.default
guard fm.fileExists(atPath: url.path) else { return [] }
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: url.path,
underlying: error.localizedDescription
)
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let decoded = try decoder.decode([HistoryEntry].self, from: data)
return decoded.map { entry in
HistoryEntry(
id: entry.id,
fileName: entry.fileName,
fileURL: pdfsDirectory.appendingPathComponent(entry.fileName),
originalFileName: entry.originalFileName,
sessionID: entry.sessionID,
pageCount: entry.pageCount,
sentAt: entry.sentAt
)
}
} catch {
let corruptURL = url.deletingLastPathComponent()
.appendingPathComponent("history.json.corrupt-\(DubaiTime.fileStamp(Date()))")
try? fm.moveItem(at: url, to: corruptURL)
Log.spool.error(
"history.json could not be decoded; moved to \(corruptURL.path, privacy: .public): \(error.localizedDescription, privacy: .public)"
)
return []
}
}
}
@@ -10,7 +10,6 @@ public enum ShotdeckError: Error, LocalizedError, Sendable {
case pdfCompositionFailed(reason: String) case pdfCompositionFailed(reason: String)
case airDropUnavailable case airDropUnavailable
case noCommentedReturns case noCommentedReturns
case oneDriveFolderUnavailable(path: String)
public var errorDescription: String? { public var errorDescription: String? {
switch self { switch self {
@@ -32,8 +31,6 @@ public enum ShotdeckError: Error, LocalizedError, Sendable {
return "AirDrop is not available right now." return "AirDrop is not available right now."
case .noCommentedReturns: case .noCommentedReturns:
return "None of the returned PDFs have comments on them." return "None of the returned PDFs have comments on them."
case .oneDriveFolderUnavailable(let path):
return "Your OneDrive folder is not available: \(path). Check that OneDrive is signed in, or choose another folder in Settings."
} }
} }
} }
@@ -10,21 +10,6 @@ public actor ReturnWatcher {
private var bridge: FSEventBridge? private var bridge: FSEventBridge?
private var pendingScanTask: Task<Void, Never>? private var pendingScanTask: Task<Void, Never>?
private let eventQueue = DispatchQueue(label: "ai.flowmaster.shotdeck.returns.fsevents") private let eventQueue = DispatchQueue(label: "ai.flowmaster.shotdeck.returns.fsevents")
/// When false, a document with zero human marks is neither recorded into the ledger
/// nor included in scanNow's/onChange's results needed for OneDrive mode, where the
/// outbox and watch folder are the same folder and a freshly written, unmarked PDF
/// must not be treated as a return. Defaults to true (today's AirDrop behaviour).
/// A document that IS commented is always recorded, regardless of this flag.
public var recordUncommented: Bool = true
/// The folder this watcher is CURRENTLY seeded to scan/watch whatever `init`
/// last set it to, or `updateWatchFolder` since. Exposed so tests can observe the
/// watcher's seeded folder directly (e.g. right after construction, before
/// `start()`/`updateWatchFolder()` ever run) rather than only inferring it
/// indirectly through `scanNow()`'s behavior.
public var currentWatchFolder: URL {
watchFolder
}
/// Watch folder is `paths.watchFolder`, which production constructs from /// Watch folder is `paths.watchFolder`, which production constructs from
/// `FolderSettings.resolve().watch`. This type never calls FolderSettings; /// `FolderSettings.resolve().watch`. This type never calls FolderSettings;
@@ -44,12 +29,6 @@ public actor ReturnWatcher {
onChange(found) onChange(found)
} }
/// Sets `recordUncommented`. A `func` (not a plain property set) only because
/// callers outside this actor must `await` it like any other actor mutation.
public func setRecordUncommented(_ value: Bool) {
recordUncommented = value
}
/// Idempotent. Stops and releases the FSEventStream if one is running; safe to call /// Idempotent. Stops and releases the FSEventStream if one is running; safe to call
/// when never started or already stopped. Cancels any pending debounced scan. /// when never started or already stopped. Cancels any pending debounced scan.
public func stop() { public func stop() {
@@ -98,7 +77,6 @@ public actor ReturnWatcher {
guard let document = PDFDocument(url: url), guard let document = PDFDocument(url: url),
AnnotationInspector.isShotdeckDocument(document) else { continue } AnnotationInspector.isShotdeckDocument(document) else { continue }
guard let inspected = try? AnnotationInspector.inspect(fileURL: url) else { continue } guard let inspected = try? AnnotationInspector.inspect(fileURL: url) else { continue }
if !recordUncommented, !inspected.isCommented { continue }
try await ledger.record(inspected) try await ledger.record(inspected)
results.append(inspected) results.append(inspected)
} }
@@ -11,6 +11,12 @@ public struct AppSupportPaths: Sendable {
/// Production paths. /// Production paths.
public static func standard() throws -> AppSupportPaths { public static func standard() throws -> AppSupportPaths {
let fileManager = FileManager.default let fileManager = FileManager.default
let appSupportParent = try fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
let desktop = try fileManager.url( let desktop = try fileManager.url(
for: .desktopDirectory, for: .desktopDirectory,
in: .userDomainMask, in: .userDomainMask,
@@ -23,25 +29,10 @@ public struct AppSupportPaths: Sendable {
appropriateFor: nil, appropriateFor: nil,
create: true create: true
) )
let root = try standardRoot(fileManager: fileManager) let root = appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
return try AppSupportPaths(root: root, outbox: desktop, watchFolder: downloads) return try AppSupportPaths(root: root, outbox: desktop, watchFolder: downloads)
} }
/// The standard `~/Library/Application Support/Shotdeck` root. Shared by
/// `standard()`, `FolderSettings.resolvedAppSupportPaths()`, and
/// `TransportSettings.resolvedAppSupportPaths()` so all three agree on where the
/// root lives the folder-resolution logic (AirDrop-only vs transport-aware)
/// differs between those, the root computation never should.
public static func standardRoot(fileManager: FileManager = .default) throws -> URL {
let appSupportParent = try fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
return appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
}
/// Test paths rooted anywhere. Every directory is created if missing. /// Test paths rooted anywhere. Every directory is created if missing.
public init(root: URL, outbox: URL, watchFolder: URL) throws { public init(root: URL, outbox: URL, watchFolder: URL) throws {
self.root = root self.root = root
@@ -3,7 +3,6 @@ import Foundation
public enum DubaiTime { public enum DubaiTime {
private static let stampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm 'Dubai'") private static let stampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm 'Dubai'")
private static let fileStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmmss") private static let fileStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmmss")
private static let checkTimeFormatter = LockedDateFormatter(dateFormat: "HH:mm 'Dubai'")
public static func stamp(_ date: Date) -> String { public static func stamp(_ date: Date) -> String {
stampFormatter.string(from: date) stampFormatter.string(from: date)
@@ -12,10 +11,6 @@ public enum DubaiTime {
public static func fileStamp(_ date: Date) -> String { public static func fileStamp(_ date: Date) -> String {
fileStampFormatter.string(from: date) fileStampFormatter.string(from: date)
} }
public static func checkTime(_ date: Date) -> String {
checkTimeFormatter.string(from: date)
}
} }
/// DateFormatter is not Sendable. This holder is the only shared mutable state /// DateFormatter is not Sendable. This holder is the only shared mutable state
@@ -70,7 +70,15 @@ public enum FolderSettings {
defaults: UserDefaults = .standard, defaults: UserDefaults = .standard,
fileManager: FileManager = .default fileManager: FileManager = .default
) throws -> AppSupportPaths { ) throws -> AppSupportPaths {
let resolvedRoot = try root ?? AppSupportPaths.standardRoot(fileManager: fileManager) let resolvedRoot: URL
if let root {
resolvedRoot = root
} else {
let appSupportParent = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
resolvedRoot = appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
}
let folders = resolve(defaults: defaults, fileManager: fileManager) let folders = resolve(defaults: defaults, fileManager: fileManager)
return try AppSupportPaths(root: resolvedRoot, outbox: folders.outbox, watchFolder: folders.watch) return try AppSupportPaths(root: resolvedRoot, outbox: folders.outbox, watchFolder: folders.watch)
} }
@@ -1,221 +0,0 @@
import Foundation
/// The two ways a composed PDF can reach the iPad and come back marked up.
public enum SendTransport: String, Codable, Sendable, CaseIterable {
case airDrop
case oneDrive
public var displayName: String {
switch self {
case .airDrop: return "AirDrop"
case .oneDrive: return "OneDrive folder"
}
}
}
/// User-configurable transport choice plus the OneDrive folder override, backed by
/// UserDefaults the same way `FolderSettings` is. See `FolderSettings` for why a plain
/// path (not a security-scoped bookmark) is correct for this unsandboxed app.
public enum TransportSettings {
public static let transportDefaultsKey = "ai.flowmaster.shotdeck.transport"
public static let oneDriveFolderDefaultsKey = "ai.flowmaster.shotdeck.oneDriveFolder"
/// Defaults to `.airDrop` when unset or when the stored value cannot be parsed.
public static func transport(defaults: UserDefaults = .standard) -> SendTransport {
guard let raw = defaults.string(forKey: transportDefaultsKey),
let value = SendTransport(rawValue: raw)
else { return .airDrop }
return value
}
public static func setTransport(_ value: SendTransport, defaults: UserDefaults = .standard) {
defaults.set(value.rawValue, forKey: transportDefaultsKey)
}
/// Raw stored path (or nil if never set / cleared). Does NOT validate that the
/// directory still exists.
public static func storedOneDriveFolderPath(defaults: UserDefaults = .standard) -> String? {
defaults.string(forKey: oneDriveFolderDefaultsKey)
}
public static func setOneDriveFolder(_ url: URL, defaults: UserDefaults = .standard) {
defaults.set(url.path, forKey: oneDriveFolderDefaultsKey)
}
public static func resetOneDriveFolder(defaults: UserDefaults = .standard) {
defaults.removeObject(forKey: oneDriveFolderDefaultsKey)
}
/// The outbox/watch folders Redline should actually use right now, for the current
/// transport. AirDrop mode delegates to `FolderSettings.resolve()` unchanged.
/// OneDrive mode uses the SAME folder for both outbox and watch see
/// `OneDriveLocator.resolveOneDriveFolder`. When no OneDrive folder can be resolved
/// at all (no sync root, no override), this falls back to the AirDrop folders so the
/// app always has somewhere to write; `send(anchor:)` performs its own live
/// existence check before ever composing into a OneDrive send, so that fallback is
/// never mistaken for a valid OneDrive destination.
public static func effectiveFolders(
defaults: UserDefaults = .standard,
fileManager: FileManager = .default
) -> (outbox: URL, watch: URL, transport: SendTransport) {
let transport = transport(defaults: defaults)
switch transport {
case .airDrop:
let folders = FolderSettings.resolve(defaults: defaults, fileManager: fileManager)
return (folders.outbox, folders.watch, transport)
case .oneDrive:
if let folder = OneDriveLocator.resolveOneDriveFolder(
defaults: defaults,
home: fileManager.homeDirectoryForCurrentUser,
fileManager: fileManager
) {
return (folder, folder, transport)
}
let folders = FolderSettings.resolve(defaults: defaults, fileManager: fileManager)
return (folders.outbox, folders.watch, transport)
}
}
/// Builds an `AppSupportPaths` using `root` (defaults to the standard
/// `~/Library/Application Support/Shotdeck` when nil) plus whatever
/// `effectiveFolders()` returns for outbox/watch. Unlike
/// `FolderSettings.resolvedAppSupportPaths()` (AirDrop-only), this is
/// transport-aware it is the ONLY function launch code should use to build its
/// paths, so the watcher it feeds is never seeded with a stale AirDrop folder while
/// OneDrive is the persisted transport. `root` is exposed purely so tests (and the
/// ONEDRIVE-SELFTEST relaunch simulation) can point it at a temporary directory
/// instead of the user's real Application Support folder.
public static func resolvedAppSupportPaths(
root: URL? = nil,
defaults: UserDefaults = .standard,
fileManager: FileManager = .default
) throws -> AppSupportPaths {
let resolvedRoot = try root ?? AppSupportPaths.standardRoot(fileManager: fileManager)
let folders = effectiveFolders(defaults: defaults, fileManager: fileManager)
return try AppSupportPaths(root: resolvedRoot, outbox: folders.outbox, watchFolder: folders.watch)
}
}
/// Pure path logic for locating a OneDrive sync root under
/// `~/Library/CloudStorage` and the Redline folder inside it. No side effects never
/// creates a directory. Fully unit-testable with a fake home tree.
public enum OneDriveLocator {
/// Every directory directly under `<home>/Library/CloudStorage` whose name starts
/// with "OneDrive-", sorted so a name containing "MMD" (case-insensitive) sorts
/// first, then alphabetically. Empty when CloudStorage does not exist.
public static func syncRoots(
home: URL = FileManager.default.homeDirectoryForCurrentUser,
fileManager: FileManager = .default
) -> [URL] {
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
var isDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: cloudStorage.path, isDirectory: &isDirectory),
isDirectory.boolValue
else { return [] }
let items = (try? fileManager.contentsOfDirectory(
at: cloudStorage,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
)) ?? []
let roots = items.filter { url in
guard url.lastPathComponent.hasPrefix("OneDrive-") else { return false }
var itemIsDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: url.path, isDirectory: &itemIsDirectory)
return exists && itemIsDirectory.boolValue
}
return roots.sorted { a, b in
let aName = a.lastPathComponent
let bName = b.lastPathComponent
let aIsMMD = aName.localizedCaseInsensitiveContains("MMD")
let bIsMMD = bName.localizedCaseInsensitiveContains("MMD")
if aIsMMD != bIsMMD { return aIsMMD }
return aName.localizedStandardCompare(bName) == .orderedAscending
}
}
/// First sync root's "Redline" subfolder, or nil when there is no sync root at all.
public static func defaultRedlineFolder(
home: URL = FileManager.default.homeDirectoryForCurrentUser,
fileManager: FileManager = .default
) -> URL? {
guard let first = syncRoots(home: home, fileManager: fileManager).first else { return nil }
return first.appendingPathComponent("Redline", isDirectory: true)
}
/// The stored override when it is set AND still exists as a directory; otherwise
/// `defaultRedlineFolder`. Never creates anything.
public static func resolveOneDriveFolder(
defaults: UserDefaults = .standard,
home: URL = FileManager.default.homeDirectoryForCurrentUser,
fileManager: FileManager = .default
) -> URL? {
if let storedPath = TransportSettings.storedOneDriveFolderPath(defaults: defaults) {
var isDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: storedPath, isDirectory: &isDirectory)
if exists, isDirectory.boolValue {
return URL(fileURLWithPath: storedPath, isDirectory: true)
}
}
return defaultRedlineFolder(home: home, fileManager: fileManager)
}
/// True when `url` exists as a directory AND is writable by the current process.
/// The live check `send(anchor:)` performs before ever composing into a OneDrive
/// destination a directory that exists but has had its permissions revoked (e.g.
/// `chmod 500`) must be treated as unavailable, not silently attempted and
/// surfaced as a generic PDF-composition failure.
public static func isWritableDirectory(
at url: URL,
fileManager: FileManager = .default
) -> Bool {
var isDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
guard exists, isDirectory.boolValue else { return false }
return fileManager.isWritableFile(atPath: url.path)
}
/// Writes a tiny probe file into `folder`, fsyncs it, then removes it the only
/// reliable way to catch a OneDrive Files-On-Demand directory whose provider domain
/// is signed out: such a directory can report as existing and POSIX-writable
/// (`isWritableDirectory` returns true) while an actual write fails. True only when
/// the write, fsync, AND removal of the probe file all succeed; any failure at any
/// of those steps means false, so the caller treats the folder as unavailable
/// rather than proceeding to compose a real PDF into it.
public static func probeWritable(
at folder: URL,
fileManager: FileManager = .default
) -> Bool {
let probeURL = folder.appendingPathComponent(".redline-probe-\(UUID().uuidString)")
// Belt-and-suspenders cleanup, unconditional: AtomicFile.write renames the temp
// file onto probeURL and THEN fsyncs the containing directory if that last
// fsync throws, the probe file already exists on disk but the catch below
// returns false before ever reaching the explicit removeItem call. And if the
// explicit removeItem itself throws, this is the only retry it gets. Either
// way, never leave the probe file behind just because we're about to return.
defer {
if fileManager.fileExists(atPath: probeURL.path) {
try? fileManager.removeItem(at: probeURL)
}
}
do {
try AtomicFile.write(Data(), to: probeURL)
} catch {
return false
}
do {
try fileManager.removeItem(at: probeURL)
} catch {
return false
}
// Only true when the explicit removal above actually succeeded AND the file is
// confirmed gone never trust a removeItem call that returned without throwing
// as proof of anything on a File Provider domain.
return !fileManager.fileExists(atPath: probeURL.path)
}
}
@@ -0,0 +1,319 @@
import CoreGraphics
import Foundation
import ImageIO
import Testing
import ShotdeckCore
@Test
func recordTwelvePDFsKeepsTenNewestAndDeletesOldestCopies() async throws {
let (root, paths) = try makeHistoryPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try HistoryStore(paths: paths)
let sources = root.appendingPathComponent("user-sources", isDirectory: true)
try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true)
var recorded: [HistoryEntry] = []
for i in 0..<12 {
let source = sources.appendingPathComponent("source-\(i).pdf")
try writeDummyPDF(to: source, marker: "pdf-\(i)")
let sentAt = Date(timeIntervalSince1970: 1_800_000_000 + TimeInterval(i))
let entry = try await store.recordSentPDF(
sourceURL: source,
sessionID: UUID(),
pageCount: i + 1,
sentAt: sentAt
)
recorded.append(entry)
}
let listed = await store.listPDFs()
#expect(listed.count == 10)
#expect(listed.map(\.id) == recorded.suffix(10).reversed().map(\.id))
#expect(listed.map(\.sentAt) == recorded.suffix(10).reversed().map(\.sentAt))
let pdfsDir = paths.root.appendingPathComponent("history/pdfs", isDirectory: true)
for entry in recorded.prefix(2) {
#expect(!FileManager.default.fileExists(atPath: pdfsDir.appendingPathComponent(entry.fileName).path))
}
for entry in recorded.suffix(10) {
#expect(FileManager.default.fileExists(atPath: pdfsDir.appendingPathComponent(entry.fileName).path))
}
}
@Test
func pruneImagesKeepsThirtyNewestAcrossThreeArchivedSessionsAndLeavesOpenSessionAlone() async throws {
let (root, paths) = try makeHistoryPaths()
defer { try? FileManager.default.removeItem(at: root) }
let spool = try SpoolStore(paths: paths)
let base = Date(timeIntervalSince1970: 1_800_100_000)
var captures: [(id: UUID, capturedAt: Date, sessionID: UUID)] = []
// 5 oldest + 15 + 15 = 35 archived PNGs. The oldest session is emptied by prune.
let perSession = [5, 15, 15]
var index = 0
for count in perSession {
let sessionID = try await spool.currentSession().id
for _ in 0..<count {
let capturedAt = base.addingTimeInterval(TimeInterval(index))
let capture = try await spool.append(
pngData: try makeHistoryPNGData(width: 6, height: 4, red: 0.2, green: 0.3, blue: 0.4),
pixelWidth: 6,
pixelHeight: 4,
scale: 1.0,
capturedAt: capturedAt
)
captures.append((capture.id, capturedAt, sessionID))
index += 1
}
_ = try await spool.archiveCurrent(pdfFileName: "Redline-hist-\(sessionID.uuidString).pdf")
}
let openBefore = try await spool.currentSession()
let openCapture = try await spool.append(
pngData: try makeHistoryPNGData(width: 8, height: 6, red: 0.9, green: 0.1, blue: 0.1),
pixelWidth: 8,
pixelHeight: 6,
scale: 1.0,
capturedAt: Date(timeIntervalSince1970: 1_900_000_000)
)
let openSession = try await spool.currentSession()
#expect(openSession.id == openBefore.id)
let openDir = paths.sessionDirectory(openSession.id)
let openPNG = openDir.appendingPathComponent(openCapture.fileName)
let openPNGBytes = try Data(contentsOf: openPNG)
let openManifest = try Data(contentsOf: openDir.appendingPathComponent("session.json"))
let store = try HistoryStore(paths: paths)
try await store.pruneImages()
let remaining = try await store.listImages(limit: 50)
#expect(remaining.count == 30)
let newestThirty = Array(captures.suffix(30))
let remainingDates = Set(remaining.map(\.capturedAt))
#expect(remainingDates == Set(newestThirty.map(\.capturedAt)))
#expect(remaining.map(\.sessionID).allSatisfy { $0 != openSession.id })
let oldestFive = Array(captures.prefix(5))
for old in oldestFive {
let archiveDir = paths.archiveDirectory(old.sessionID)
#expect(!FileManager.default.fileExists(atPath: archiveDir.path))
}
#expect(pngFiles(under: paths.archive).count == 30)
try assertManifestsMatchDisk(archiveRoot: paths.archive)
#expect(FileManager.default.fileExists(atPath: openPNG.path))
#expect(try Data(contentsOf: openPNG) == openPNGBytes)
#expect(try Data(contentsOf: openDir.appendingPathComponent("session.json")) == openManifest)
#expect(try await spool.currentSession().captures.map(\.id) == [openCapture.id])
}
@Test
func recordSentPDFLeavesTheUserSourceUntouched() async throws {
let (root, paths) = try makeHistoryPaths()
defer { try? FileManager.default.removeItem(at: root) }
let source = root.appendingPathComponent("outside-appsupport.pdf")
let payload = Data("%PDF-1.4\n%user-original\n%%EOF\n".utf8)
try payload.write(to: source)
let store = try HistoryStore(paths: paths)
let entry = try await store.recordSentPDF(
sourceURL: source,
sessionID: UUID(),
pageCount: 2,
sentAt: Date(timeIntervalSince1970: 1_800_200_000)
)
#expect(FileManager.default.fileExists(atPath: source.path))
#expect(try Data(contentsOf: source) == payload)
#expect(entry.fileURL.path != source.path)
#expect(try Data(contentsOf: entry.fileURL) == payload)
#expect(entry.fileURL.path.hasPrefix(
paths.root.appendingPathComponent("history/pdfs", isDirectory: true).path
))
}
@Test
func recordingTheSameSourceTwiceMakesTwoDistinctCopies() async throws {
let (root, paths) = try makeHistoryPaths()
defer { try? FileManager.default.removeItem(at: root) }
let source = root.appendingPathComponent("resend.pdf")
try writeDummyPDF(to: source, marker: "same-source")
let store = try HistoryStore(paths: paths)
let first = try await store.recordSentPDF(
sourceURL: source,
sessionID: nil,
pageCount: 1,
sentAt: Date(timeIntervalSince1970: 1_800_300_000)
)
let second = try await store.recordSentPDF(
sourceURL: source,
sessionID: nil,
pageCount: 1,
sentAt: Date(timeIntervalSince1970: 1_800_300_001)
)
#expect(first.id != second.id)
#expect(first.fileName != second.fileName)
#expect(first.fileURL.path != second.fileURL.path)
#expect(FileManager.default.fileExists(atPath: first.fileURL.path))
#expect(FileManager.default.fileExists(atPath: second.fileURL.path))
let firstBytes = try Data(contentsOf: first.fileURL)
let secondBytes = try Data(contentsOf: second.fileURL)
#expect(firstBytes == secondBytes)
#expect(FileManager.default.fileExists(atPath: source.path))
let listed = await store.listPDFs()
#expect(listed.count == 2)
#expect(Set(listed.map(\.id)) == [first.id, second.id])
}
@Test
func pruneImagesDeletesOlderPNGsInRemovedFolders() async throws {
let (root, paths) = try makeHistoryPaths()
defer { try? FileManager.default.removeItem(at: root) }
let spool = try SpoolStore(paths: paths)
let base = Date(timeIntervalSince1970: 1_800_400_000)
for i in 0..<30 {
_ = try await spool.append(
pngData: try makeHistoryPNGData(width: 4, height: 4, red: 0.1, green: 0.2, blue: 0.3),
pixelWidth: 4,
pixelHeight: 4,
scale: 1.0,
capturedAt: base.addingTimeInterval(TimeInterval(10 + i))
)
}
_ = try await spool.archiveCurrent(pdfFileName: "Redline-keep.pdf")
let oldSessionID = UUID()
let oldDir = paths.archiveDirectory(oldSessionID)
let removedDir = oldDir.appendingPathComponent("removed", isDirectory: true)
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
let oldPNG = removedDir.appendingPathComponent("001-DEADBEEF.png")
try makeHistoryPNGData(width: 4, height: 4, red: 0.5, green: 0.5, blue: 0.5).write(to: oldPNG)
try FileManager.default.setAttributes(
[.creationDate: base],
ofItemAtPath: oldPNG.path
)
let oldSession = CaptureSession(
id: oldSessionID,
createdAt: base,
state: .archived,
captures: [],
pdfFileName: "Redline-old.pdf"
)
try AtomicFile.writeJSON(oldSession, to: oldDir.appendingPathComponent("session.json"))
let store = try HistoryStore(paths: paths)
try await store.pruneImages()
#expect(!FileManager.default.fileExists(atPath: oldPNG.path))
#expect(pngFiles(under: paths.archive).count == 30)
}
// MARK: - Fixtures
private func makeHistoryPaths() throws -> (root: URL, paths: AppSupportPaths) {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-history-\(UUID().uuidString)", isDirectory: true)
let paths = try AppSupportPaths(
root: root.appendingPathComponent("root", isDirectory: true),
outbox: root.appendingPathComponent("outbox", isDirectory: true),
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
return (root, paths)
}
private func writeDummyPDF(to url: URL, marker: String) throws {
try Data("%PDF-1.4\n%\(marker)\n%%EOF\n".utf8).write(to: url)
}
private func makeHistoryPNGData(
width: Int,
height: Int,
red: CGFloat,
green: CGFloat,
blue: CGFloat
) throws -> Data {
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
throw HistoryFixtureError.pngGenerationFailed
}
context.setFillColor(red: red, green: green, blue: blue, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let image = context.makeImage() else {
throw HistoryFixtureError.pngGenerationFailed
}
let buffer = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(buffer, "public.png" as CFString, 1, nil) else {
throw HistoryFixtureError.pngGenerationFailed
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
throw HistoryFixtureError.pngGenerationFailed
}
return buffer as Data
}
private func pngFiles(under root: URL) -> [URL] {
let fm = FileManager.default
guard let enumerator = fm.enumerator(
at: root,
includingPropertiesForKeys: [.isRegularFileKey],
options: []
) else { return [] }
var urls: [URL] = []
for case let url as URL in enumerator {
let isFile = (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) ?? false
if isFile, url.pathExtension.lowercased() == "png" {
urls.append(url)
}
}
return urls
}
private func assertManifestsMatchDisk(archiveRoot: URL) throws {
let fm = FileManager.default
let sessions = (try fm.contentsOfDirectory(
at: archiveRoot,
includingPropertiesForKeys: [.isDirectoryKey],
options: []
)).filter {
((try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false)
&& UUID(uuidString: $0.lastPathComponent) != nil
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
for dir in sessions {
let manifestURL = dir.appendingPathComponent("session.json")
#expect(fm.fileExists(atPath: manifestURL.path))
let session = try decoder.decode(CaptureSession.self, from: Data(contentsOf: manifestURL))
for capture in session.captures {
let url = dir.appendingPathComponent(capture.fileName)
#expect(fm.fileExists(atPath: url.path))
}
let topLevelPNGs = (try fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil, options: []))
.filter { $0.pathExtension.lowercased() == "png" }
let manifestNames = Set(session.captures.map(\.fileName))
#expect(Set(topLevelPNGs.map(\.lastPathComponent)) == manifestNames)
}
}
private enum HistoryFixtureError: Error {
case pngGenerationFailed
}
@@ -1,125 +0,0 @@
import Foundation
import Testing
import ShotdeckCore
@Test
func syncRootsFindsOneDriveDirsMMDFirstIgnoresNonDirsAndOtherProviders() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(at: cloudStorage, withIntermediateDirectories: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-Flowmaster", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("GoogleDrive-x", isDirectory: true),
withIntermediateDirectories: true
)
// A plain FILE (not a directory) named like a OneDrive root must be ignored.
FileManager.default.createFile(
atPath: cloudStorage.appendingPathComponent("OneDrive-notadir").path,
contents: Data("not a directory".utf8)
)
let roots = OneDriveLocator.syncRoots(home: home, fileManager: .default)
#expect(roots.map(\.lastPathComponent) == ["OneDrive-MMDGROUP", "OneDrive-Flowmaster"])
}
@Test
func syncRootsEmptyAndDefaultFolderNilWithNoCloudStorageDirectory() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
// No Library/CloudStorage created at all.
let roots = OneDriveLocator.syncRoots(home: home, fileManager: .default)
#expect(roots.isEmpty)
let defaultFolder = OneDriveLocator.defaultRedlineFolder(home: home, fileManager: .default)
#expect(defaultFolder == nil)
}
@Test
func defaultRedlineFolderIsFirstSyncRootPlusRedline() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-Flowmaster", isDirectory: true),
withIntermediateDirectories: true
)
let defaultFolder = try #require(
OneDriveLocator.defaultRedlineFolder(home: home, fileManager: .default)
)
// Derive "expected" from syncRoots() itself (already covered by its own dedicated
// test) rather than hand-building the path string FileManager's directory
// enumeration can canonicalize /var -> /private/var and the two constructions
// otherwise disagree on that even for a URL that already exists.
let expectedRoot = try #require(OneDriveLocator.syncRoots(home: home, fileManager: .default).first)
let expected = expectedRoot.appendingPathComponent("Redline", isDirectory: true)
#expect(defaultFolder.path == expected.path)
}
@Test
func resolveOneDriveFolderPrefersAnExistingStoredOverride() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let override = try makeTransportTemporaryDirectory(prefix: "shotdeck-onedrive-override")
defer { try? FileManager.default.removeItem(at: override) }
TransportSettings.setOneDriveFolder(override, defaults: suite.defaults)
let resolved = OneDriveLocator.resolveOneDriveFolder(
defaults: suite.defaults, home: home, fileManager: .default
)
#expect(resolved?.path == override.path)
}
@Test
func resolveOneDriveFolderIgnoresAStoredPathThatNoLongerExists() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let goneOverride = try makeTransportTemporaryDirectory(prefix: "shotdeck-onedrive-gone")
TransportSettings.setOneDriveFolder(goneOverride, defaults: suite.defaults)
try FileManager.default.removeItem(at: goneOverride)
let resolved = OneDriveLocator.resolveOneDriveFolder(
defaults: suite.defaults, home: home, fileManager: .default
)
let expectedRoot = try #require(OneDriveLocator.syncRoots(home: home, fileManager: .default).first)
let expected = expectedRoot.appendingPathComponent("Redline", isDirectory: true)
#expect(resolved?.path == expected.path)
}
private func makeFakeHome() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-fake-home-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
return home
}
@@ -230,162 +230,3 @@ func w27_fsEventsCallbackFiresOnRealArrival() async throws {
await watcher.stop() await watcher.stop()
} }
} }
@Test("recordUncommented defaults to true: an unmarked PDF is still recorded (AirDrop behaviour unchanged)")
func recordUncommentedDefaultTrueRecordsAnUnmarkedPDF() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260905-090000.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: "Redline", annotations: [])
let found = try await watcher.scanNow()
#expect(found.count == 1)
#expect(found.first?.isCommented == false)
let all = try await ledger.all()
#expect(all.count == 1)
}
@Test("recordUncommented=false: an unmarked PDF is not recorded or returned; marking it up in place gets it recorded")
func recordUncommentedFalseSkipsUnmarkedThenRecordsAfterInPlaceMarkup() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
await watcher.setRecordUncommented(false)
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260905-091500.pdf")
// OneDrive mode: the PDF is freshly written here (by "send"), unmarked so far.
try makePDF(at: pdfURL, pageCount: 1, creator: "Redline", annotations: [])
let beforeMarkup = try await watcher.scanNow()
#expect(beforeMarkup.isEmpty)
let allBefore = try await ledger.all()
#expect(allBefore.isEmpty)
// What the iPad does: mark it up in place, in the SAME folder, then save.
let document = try #require(PDFDocument(url: pdfURL))
let page = try #require(document.page(at: 0))
page.addAnnotation(makeAnnotation(.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)))
#expect(document.write(to: pdfURL))
let afterMarkup = try await watcher.scanNow()
#expect(afterMarkup.count == 1)
#expect(afterMarkup.first?.isCommented == true)
let commented = try await ledger.commented()
#expect(commented.count == 1)
#expect(commented.first?.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
}
// MARK: - Launch-paths BLOCKER regression (adversarial review, 20260905)
//
// The bug: AppDelegate.makeLaunchModel() built `paths` via the AirDrop-only
// FolderSettings.resolvedAppSupportPaths(), so ReturnWatcher's internal watchFolder
// (seeded from paths.watchFolder in its own init) was the AirDrop folder even when
// OneDrive was the persisted transport, and bootstrap() never reconciled it before
// starting. Net effect: PDFs went to OneDrive but FSEvents kept watching the stale
// AirDrop folder for the whole session marked-up returns were never detected.
// The fix: launch paths now come from TransportSettings.resolvedAppSupportPaths()
// (transport-aware), and AppModel.bootstrap() unconditionally reconciles the watcher's
// folder via updateWatchFolder() before it starts. These two tests characterize the
// bug (still reproducible via the old AirDrop-only construction) and prove the fix
// (the real launch-construction path, end to end).
@Test("Launch regression (fix): OneDrive persisted -> transport-aware launch paths -> bootstrap-style reconcile -> a marked PDF is detected")
func launchStyleConstructionWithOneDriveTransportDetectsAMarkedReturn() async throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let oneDriveFolder = try makeTransportTemporaryDirectory(prefix: "shotdeck-launch-onedrive")
defer { try? FileManager.default.removeItem(at: oneDriveFolder) }
let appSupportRoot = try makeTransportTemporaryDirectory(prefix: "shotdeck-launch-approot")
defer { try? FileManager.default.removeItem(at: appSupportRoot) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
TransportSettings.setOneDriveFolder(oneDriveFolder, defaults: suite.defaults)
// Exactly what AppDelegate.makeLaunchModel() now does: build launch paths from the
// transport-aware resolver the fix, NOT FolderSettings.resolvedAppSupportPaths(),
// which is AirDrop-only and is the root cause the next test characterizes.
let paths = try TransportSettings.resolvedAppSupportPaths(
root: appSupportRoot, defaults: suite.defaults, fileManager: .default
)
#expect(paths.outbox.path == oneDriveFolder.path)
#expect(paths.watchFolder.path == oneDriveFolder.path)
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
// What AppModel.bootstrap() now does, unconditionally, before watcher.start():
await watcher.setRecordUncommented(false) // transport == .oneDrive
try await watcher.updateWatchFolder(paths.watchFolder)
let pdfURL = oneDriveFolder.appendingPathComponent("Redline-20260905-100000.pdf")
try makePDF(
at: pdfURL, pageCount: 1, creator: "Redline",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
let found = try await watcher.scanNow()
#expect(found.contains(where: {
$0.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path && $0.isCommented
}))
let commented = try await ledger.commented()
#expect(commented.contains(where: {
$0.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path
}))
}
@Test("Launch regression (characterizes the bug): AirDrop-only launch paths with no reconcile miss an OneDrive-mode return")
func airDropOnlyLaunchPathsWithoutReconcileMissesAMarkedOneDriveReturn() async throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let oneDriveFolder = try makeTransportTemporaryDirectory(prefix: "shotdeck-buggy-onedrive")
defer { try? FileManager.default.removeItem(at: oneDriveFolder) }
// A configured AirDrop watch-folder override, isolated to a temp dir NOT the real
// ~/Downloads, which may already hold real marked-up Redline PDFs from actual use
// and would make this test's "found.isEmpty" assertion depend on the state of
// Ben's real Downloads folder instead of the isolated fixture under test.
let staleAirDropFolder = try makeTransportTemporaryDirectory(prefix: "shotdeck-buggy-airdrop-stale")
defer { try? FileManager.default.removeItem(at: staleAirDropFolder) }
let appSupportRoot = try makeTransportTemporaryDirectory(prefix: "shotdeck-buggy-approot")
defer { try? FileManager.default.removeItem(at: appSupportRoot) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
TransportSettings.setOneDriveFolder(oneDriveFolder, defaults: suite.defaults)
FolderSettings.setWatchFolder(staleAirDropFolder, defaults: suite.defaults)
// The BUG's exact construction: FolderSettings.resolvedAppSupportPaths() ignores
// the persisted transport entirely and always resolves the AirDrop folders.
let buggyPaths = try FolderSettings.resolvedAppSupportPaths(root: appSupportRoot, defaults: suite.defaults)
#expect(buggyPaths.watchFolder.path == staleAirDropFolder.path)
#expect(buggyPaths.watchFolder.path != oneDriveFolder.path)
let ledger = try ReturnLedger(paths: buggyPaths)
let watcher = ReturnWatcher(paths: buggyPaths, ledger: ledger)
// The old bootstrap(): recordUncommented was set, but there was NO
// updateWatchFolder() call before start() to reconcile the folder.
await watcher.setRecordUncommented(false)
let pdfURL = oneDriveFolder.appendingPathComponent("Redline-20260905-100100.pdf")
try makePDF(
at: pdfURL, pageCount: 1, creator: "Redline",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
// The watcher is still pointed at the stale (configured-AirDrop) watch folder, so
// scanning it NOT the OneDrive folder the PDF actually landed in finds nothing.
// This is the exact BLOCKER the fix above closes.
let found = try await watcher.scanNow()
#expect(found.isEmpty)
}
@@ -1,227 +0,0 @@
import Foundation
import Testing
import ShotdeckCore
@Test
func transportDefaultsToAirDropWhenUnset() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
#expect(TransportSettings.transport(defaults: suite.defaults) == .airDrop)
}
@Test
func setTransportRoundTrips() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
#expect(TransportSettings.transport(defaults: suite.defaults) == .oneDrive)
TransportSettings.setTransport(.airDrop, defaults: suite.defaults)
#expect(TransportSettings.transport(defaults: suite.defaults) == .airDrop)
}
@Test
func garbageStoredTransportFallsBackToAirDrop() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
suite.defaults.set("not-a-real-transport", forKey: TransportSettings.transportDefaultsKey)
#expect(TransportSettings.transport(defaults: suite.defaults) == .airDrop)
}
@Test
func oneDriveFolderStoreAndReset() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let folder = try makeTransportTemporaryDirectory(prefix: "shotdeck-onedrive-folder")
defer { try? FileManager.default.removeItem(at: folder) }
#expect(TransportSettings.storedOneDriveFolderPath(defaults: suite.defaults) == nil)
TransportSettings.setOneDriveFolder(folder, defaults: suite.defaults)
#expect(TransportSettings.storedOneDriveFolderPath(defaults: suite.defaults) == folder.path)
TransportSettings.resetOneDriveFolder(defaults: suite.defaults)
#expect(TransportSettings.storedOneDriveFolderPath(defaults: suite.defaults) == nil)
}
@Test
func effectiveFoldersForAirDropMatchesFolderSettings() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let outbox = try makeTransportTemporaryDirectory(prefix: "shotdeck-effective-outbox")
defer { try? FileManager.default.removeItem(at: outbox) }
FolderSettings.setOutbox(outbox, defaults: suite.defaults)
let effective = TransportSettings.effectiveFolders(defaults: suite.defaults)
let expected = FolderSettings.resolve(defaults: suite.defaults)
#expect(effective.transport == .airDrop)
#expect(effective.outbox.path == expected.outbox.path)
#expect(effective.watch.path == expected.watch.path)
}
@Test
func effectiveFoldersForOneDriveWithAResolvableFolderUsesItForBoth() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let folder = try makeTransportTemporaryDirectory(prefix: "shotdeck-effective-onedrive")
defer { try? FileManager.default.removeItem(at: folder) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
TransportSettings.setOneDriveFolder(folder, defaults: suite.defaults)
let effective = TransportSettings.effectiveFolders(defaults: suite.defaults)
#expect(effective.transport == .oneDrive)
#expect(effective.outbox.path == folder.path)
#expect(effective.watch.path == folder.path)
#expect(effective.outbox.path == effective.watch.path)
}
@Test
func oneDriveFolderUnavailableErrorDescriptionContainsThePath() throws {
let path = "/Users/example/Library/CloudStorage/OneDrive-Example/Redline"
let error = ShotdeckError.oneDriveFolderUnavailable(path: path)
let description = try #require(error.errorDescription)
#expect(!description.isEmpty)
#expect(description.contains(path))
}
@Test
func isWritableDirectoryTrueForAnOrdinaryWritableDirectory() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-writable")
defer { try? FileManager.default.removeItem(at: dir) }
#expect(OneDriveLocator.isWritableDirectory(at: dir))
}
@Test
func isWritableDirectoryFalseForAnExistingButUnwritableDirectory() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-unwritable")
defer {
// Restore perms BEFORE removal an unwritable dir can't otherwise be cleaned up.
try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
try? FileManager.default.removeItem(at: dir)
}
#expect(OneDriveLocator.isWritableDirectory(at: dir)) // sanity check before chmod
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
#expect(!OneDriveLocator.isWritableDirectory(at: dir))
}
@Test
func isWritableDirectoryFalseForAPlainFileAndForANonexistentPath() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-writable-check-parent")
defer { try? FileManager.default.removeItem(at: dir) }
let filePath = dir.appendingPathComponent("plain-file.txt")
FileManager.default.createFile(atPath: filePath.path, contents: Data("x".utf8))
#expect(!OneDriveLocator.isWritableDirectory(at: filePath))
#expect(!OneDriveLocator.isWritableDirectory(at: dir.appendingPathComponent("does-not-exist")))
}
@Test
func probeWritableTrueForAnOrdinaryWritableDirectoryAndLeavesNoProbeFileBehind() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-writable")
defer { try? FileManager.default.removeItem(at: dir) }
#expect(OneDriveLocator.probeWritable(at: dir))
let leftovers = try FileManager.default.contentsOfDirectory(atPath: dir.path)
#expect(leftovers.isEmpty)
}
@Test
func probeWritableFalseForAChmod500Directory() throws {
// The File Provider edge case this probe exists for: isWritableDirectory can be
// true (as verified by the isWritableDirectory tests above) while an actual write
// still fails. A chmod 500 directory reproduces that "looks writable, isn't"
// shape closely enough to prove the probe itself does a real write, not just
// another permissions-bit check.
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-unwritable")
defer {
try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
try? FileManager.default.removeItem(at: dir)
}
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
#expect(!OneDriveLocator.probeWritable(at: dir))
}
@Test
func probeWritableFalseForAPlainFilePath() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-file-parent")
defer { try? FileManager.default.removeItem(at: dir) }
let filePath = dir.appendingPathComponent("plain-file.txt")
FileManager.default.createFile(atPath: filePath.path, contents: Data("x".utf8))
#expect(!OneDriveLocator.probeWritable(at: filePath))
}
/// The write itself succeeds (a real probe file lands on disk via AtomicFile.write,
/// which never touches this injected FileManager it uses raw POSIX calls), but the
/// FIRST call to `removeItem(at:)` throws, simulating a transient File Provider
/// removal failure. probeWritable's own defer-based cleanup must retry and succeed
/// (the second call through this same override falls through to `super`), so no
/// probe file is left behind even though the function correctly still reports false
/// (the removal it explicitly attempted did fail).
private final class ThrowOnceOnRemoveFileManager: FileManager, @unchecked Sendable {
private let lock = NSLock()
private var hasThrown = false
override func removeItem(at URL: URL) throws {
lock.lock()
let shouldThrow = !hasThrown
hasThrown = true
lock.unlock()
if shouldThrow {
throw NSError(domain: "ShotdeckCoreTests.ThrowOnceOnRemove", code: 1)
}
try super.removeItem(at: URL)
}
}
@Test
func probeWritableFalseAndLeavesNoProbeFileWhenRemoveItemThrowsOnce() throws {
// Directory fsync failure (the OTHER way probeWritable's cleanup can be needed) has
// no injectable seam: AtomicFile.write's directory fsync is a raw Darwin fsync(2)
// call on an already-open file descriptor, not parameterized by any FileManager or
// other dependency this test can substitute, and there is no portable way to make
// fsync(2) itself fail via chmod or other standard test techniques (fsync failures
// are OS/filesystem/hardware-level events). Covering the removeItem-throws path
// (below) is what this test does; the fsync-throws path is covered by code
// inspection only the same `defer` block guards both.
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-remove-throws")
defer { try? FileManager.default.removeItem(at: dir) }
let injectedFileManager = ThrowOnceOnRemoveFileManager()
#expect(!OneDriveLocator.probeWritable(at: dir, fileManager: injectedFileManager))
let leftovers = try FileManager.default.contentsOfDirectory(atPath: dir.path)
#expect(leftovers.isEmpty)
}
struct TransportDefaultsSuite {
let name: String
let defaults: UserDefaults
}
func makeTransportDefaultsSuite() throws -> TransportDefaultsSuite {
let name = "shotdeck-transport-test-\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defaults.removePersistentDomain(forName: name)
return TransportDefaultsSuite(name: name, defaults: defaults)
}
func tearDownTransportSuite(_ suite: TransportDefaultsSuite) {
suite.defaults.removePersistentDomain(forName: suite.name)
}
func makeTransportTemporaryDirectory(prefix: String) throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("\(prefix)-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
-142
View File
@@ -1,142 +0,0 @@
import AppKit
import Foundation
import PDFKit
import Testing
import ShotdeckCore
@testable import Shotdeck
/// Coverage gap closed (adversarial review, rounds 3 and 4): the Core-level regression
/// tests in ShotdeckCoreTests hand-replicate what `AppDelegate.makeLaunchModel()` and
/// `AppModel.bootstrap()` do, rather than calling them so a future revert of
/// `makeLaunchModel()` back to the AirDrop-only resolver, or a dropped
/// `updateWatchFolder` call inside `bootstrap()`, would NOT fail `swift test`. This
/// test goes through the real, unmodified call sites in the `Shotdeck` executable
/// target via `@testable import`, which `ShotdeckCoreTests` cannot reach (it only
/// depends on `ShotdeckCore`) hence this separate `ShotdeckTests` target.
///
/// Round 4 correction: the first version of this test asserted only
/// `model.watchFolderURL`, which `AppModel.init` computes independently via
/// `TransportSettings.effectiveFolders()` so it stayed correct (and the test kept
/// passing) even when `makeLaunchModel()` was reverted to the AirDrop-only resolver,
/// because `bootstrap()`'s own unconditional `updateWatchFolder` reconcile papered
/// over the reverted resolver. That made the "verified this catches the blocker"
/// claim in the previous round's commit message empirically false. This version
/// asserts `model.paths`/the watcher's `currentWatchFolder` BEFORE `bootstrap()` runs,
/// which actually depends on what `makeLaunchModel()` built see this file's git
/// history (or the round-4 commit message) for the verbatim before/after
/// `swift test --filter` output proving it now discriminates correctly.
@MainActor
@Test("Real wiring: AppDelegate.makeLaunchModel() + AppModel.bootstrap() detect a marked OneDrive return")
func realLaunchModelAndBootstrapDetectAMarkedOneDriveReturn() async throws {
let fm = FileManager.default
// UserDefaults.standard is the ONLY defaults instance makeLaunchModel()/bootstrap()
// actually read there is no defaults-threading through AppModel/AppDelegate (the
// same reasoning documented in PickerSelfTest.swift's ONEDRIVE-SELFTEST phase).
// "Isolated" here means snapshot-and-restore around the real keys, not a separate
// UserDefaults(suiteName:) instance that these real, unmodified call sites would
// never actually consult.
let defaults = UserDefaults.standard
let previousTransport = defaults.string(forKey: TransportSettings.transportDefaultsKey)
let previousFolder = defaults.string(forKey: TransportSettings.oneDriveFolderDefaultsKey)
defer {
if let previousTransport {
defaults.set(previousTransport, forKey: TransportSettings.transportDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.transportDefaultsKey)
}
if let previousFolder {
defaults.set(previousFolder, forKey: TransportSettings.oneDriveFolderDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.oneDriveFolderDefaultsKey)
}
}
let oneDriveFolderRaw = fm.temporaryDirectory
.appendingPathComponent("shotdeck-real-wiring-onedrive-\(UUID().uuidString)", isDirectory: true)
try fm.createDirectory(at: oneDriveFolderRaw, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: oneDriveFolderRaw) }
// FileManager's directory enumeration (inside the real ReturnWatcher/AppSupportPaths
// call sites this test exercises) can canonicalize /var -> /private/var for a path
// that actually exists; resolve here so every comparison below agrees.
let oneDriveFolder = oneDriveFolderRaw.resolvingSymlinksInPath()
let appSupportRoot = fm.temporaryDirectory
.appendingPathComponent("shotdeck-real-wiring-approot-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: appSupportRoot) }
TransportSettings.setTransport(.oneDrive, defaults: defaults)
TransportSettings.setOneDriveFolder(oneDriveFolder, defaults: defaults)
// Best-effort: keeps AppModel.bootstrap()'s real update-check schedule (a real
// HTTP GET after 10s, plus a RunLoop timer) from starting during this test.
// ProcessInfo.processInfo.environment on Darwin reads `environ` fresh each call,
// so a setenv() here is visible to bootstrap()'s own check immediately.
setenv("SHOTDECK_ONEDRIVE_SELFTEST", "1", 1)
defer { unsetenv("SHOTDECK_ONEDRIVE_SELFTEST") }
// The REAL, unmodified call sites not a reimplementation. This is exactly what
// launching Redline with OneDrive as the persisted transport does.
let model = AppDelegate.makeLaunchModel(appSupportRoot: appSupportRoot)
// bootstrap() registers a REAL, process-wide Carbon global hotkey (capture combo,
// e.g. Option-Shift-2). Carbon registrations are not scoped to this test/model
// they must be released before this test ends, or ShotdeckCoreTests'
// HotkeyCenterCarbonTests (a separate test target, same test process) can find the
// combo already taken / the global hotkey table in an unexpected state.
defer { model.hotkeys.unregisterAll() }
// PRE-bootstrap assertions this is the actual proof of the launch RESOLVER
// (AppDelegate.makeLaunchModel() -> TransportSettings.resolvedAppSupportPaths()),
// independent of bootstrap()'s own reconcile. `model.watchFolderURL` alone does
// NOT prove this: AppModel.init computes it separately via
// TransportSettings.effectiveFolders(), so it would read as correct even if
// makeLaunchModel's `paths` were built by the AirDrop-only resolver which is
// exactly how the first version of this test was empirically shown to be vacuous
// for the launch-resolver path (see this commit's message). `model.paths` is
// `internal` on AppModel, so @testable import already exposes it without any
// production API change; `currentWatchFolder` is the one new (internal-facing,
// `public` on the actor) seam added to ReturnWatcher for this purpose.
#expect(model.paths.watchFolder.path == oneDriveFolder.path)
#expect(model.paths.outbox.path == oneDriveFolder.path)
let seededWatchFolder = await model.watcher.currentWatchFolder
#expect(seededWatchFolder.path == oneDriveFolder.path)
#expect(model.transport == .oneDrive)
#expect(model.watchFolderURL.path == oneDriveFolder.path)
await model.bootstrap()
// Drop a marked-up Redline PDF into the folder in place what OneDrive syncing
// down an already-marked copy after a relaunch looks like.
let pdfURL = oneDriveFolder.appendingPathComponent("Redline-realwiring-\(UUID().uuidString).pdf")
let document = PDFDocument()
let page = PDFPage()
page.setBounds(CGRect(x: 0, y: 0, width: 612, height: 792), for: .mediaBox)
document.insert(page, at: 0)
document.documentAttributes = [
PDFDocumentAttribute.creatorAttribute: "Redline",
PDFDocumentAttribute.subjectAttribute: UUID().uuidString,
]
let ink = PDFAnnotation(
bounds: CGRect(x: 20, y: 20, width: 60, height: 60), forType: .ink, withProperties: nil
)
let stroke = NSBezierPath()
stroke.move(to: NSPoint(x: 20, y: 20))
stroke.line(to: NSPoint(x: 80, y: 80))
ink.add(stroke)
page.addAnnotation(ink)
let written = document.write(to: pdfURL)
#expect(written)
guard written else { return }
// .resolvingSymlinksInPath().path not plain URL equality matching how the rest
// of the suite compares a temp-dir-derived expected URL against a returned one.
let expectedPath = pdfURL.resolvingSymlinksInPath().path
let found = try await model.watcher.scanNow()
#expect(found.first(where: { $0.fileURL.resolvingSymlinksInPath().path == expectedPath })?.isCommented == true)
let commented = try await model.ledger.commented()
#expect(commented.contains(where: { $0.fileURL.resolvingSymlinksInPath().path == expectedPath }))
await model.watcher.stop()
}
@@ -1,118 +0,0 @@
import Foundation
import Testing
@testable import Shotdeck
@testable import ShotdeckCore
@Test("DubaiTime.checkTime formats as HH:MM Dubai")
func dubaiTimeCheckTimeFormat() {
let now = Date()
let result = DubaiTime.checkTime(now)
// Dubai timezone format: HH:MM Dubai
let pattern = "^[0-9]{2}:[0-9]{2} Dubai$"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(result.startIndex..<result.endIndex, in: result)
let matches = regex?.matches(in: result, options: [], range: range) ?? []
#expect(!matches.isEmpty, "checkTime should format as HH:MM Dubai, got: \(result)")
}
@Test("Status message: up-to-date manual check includes Dubai timestamp")
@MainActor
func manualCheckUpToDateIncludesTimestamp() async {
let checker = UpdateChecker()
// Inject a stub appcast showing the current version (no update available)
let currentVersion = UpdateChecker.currentVersion()
let stubAppcast = """
{
"version": "\(currentVersion)",
"zipURL": "https://example.com/dummy.zip",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000"
}
"""
checker.testAppcastJSON = stubAppcast
// Capture the status message
var capturedStatus: String?
checker.onChecked = {
capturedStatus = checker.statusMessage
}
// Run the manual check
await checker.checkNow(manual: true)
// Verify the message matches the expected format and includes a timestamp
guard let status = capturedStatus else {
#expect(false, "statusMessage should not be nil for manual check finding no update")
return
}
// Message should be "Redline X.Y.Z is up to date, checked HH:MM Dubai"
let pattern = "^Redline [0-9]+\\.[0-9]+\\.[0-9]+ is up to date, checked [0-9]{2}:[0-9]{2} Dubai$"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(status.startIndex..<status.endIndex, in: status)
let matches = regex?.matches(in: status, options: [], range: range) ?? []
#expect(!matches.isEmpty, "Manual check up-to-date message should match format, got: \(status)")
}
@Test("Status message: automatic check doesn't set message when up-to-date")
@MainActor
func automaticCheckUpToDateLeavesMessageNil() async {
let checker = UpdateChecker()
// Inject a stub appcast showing the current version (no update available)
let currentVersion = UpdateChecker.currentVersion()
let stubAppcast = """
{
"version": "\(currentVersion)",
"zipURL": "https://example.com/dummy.zip",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000"
}
"""
checker.testAppcastJSON = stubAppcast
// Capture the status message
var capturedStatus: String?
checker.onChecked = {
capturedStatus = checker.statusMessage
}
// Run an AUTOMATIC check (manual: false)
await checker.checkNow(manual: false)
// For automatic checks finding no update, statusMessage should be nil
#expect(capturedStatus == nil,
"Automatic check finding no update should leave statusMessage nil, got: \(capturedStatus ?? "(nil)")")
}
@Test("Update status and general status are independent channels")
@MainActor
func statusChannelsAreIndependent() async throws {
let fm = FileManager.default
let appSupportRoot = fm.temporaryDirectory
.appendingPathComponent("update-checker-channel-test-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: appSupportRoot) }
// Create a real AppModel using the standard launch pattern
let model = AppDelegate.makeLaunchModel(appSupportRoot: appSupportRoot)
defer { model.hotkeys.unregisterAll() }
// Test 1: Setting statusLine should NOT affect updateStatusMessage
model.setStatus("General status: captured 3")
#expect(model.statusLine == "General status: captured 3", "statusLine should be set")
#expect(model.updateStatusMessage == nil, "updateStatusMessage should remain nil")
// Test 2: Setting updateStatus should NOT affect statusLine
model.setUpdateStatus("Update to 9.9.9 is ready")
#expect(model.statusLine == "General status: captured 3", "statusLine should remain unchanged")
#expect(model.updateStatusMessage == "Update to 9.9.9 is ready", "updateStatusMessage should be set")
// Test 3: Clearing statusLine leaves updateStatus intact
model.setStatus(nil)
#expect(model.statusLine == nil, "statusLine should be cleared")
#expect(model.updateStatusMessage == "Update to 9.9.9 is ready", "updateStatusMessage should persist")
// Test 4: Clearing updateStatus leaves other state unaffected
model.setUpdateStatus(nil)
#expect(model.updateStatusMessage == nil, "updateStatusMessage should be cleared")
}
+29 -211
View File
@@ -13,10 +13,7 @@ PLISTBUDDY="/usr/libexec/PlistBuddy"
REMOTE_HOST="mmd01" REMOTE_HOST="mmd01"
REMOTE_BASE="/opt/mmd-installer-content/cowork/redline" REMOTE_BASE="/opt/mmd-installer-content/cowork/redline"
PUBLIC_BASE="https://get.baobab-ts.com/cowork/redline" PUBLIC_BASE="https://get.baobab-ts.com/cowork/redline"
BUNDLE_ID="ai.flowmaster.shotdeck" SIGN_IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
# Used both as the fallback signing identity and as what build-app.sh itself
# still hardcodes for its own (pre-final) signing pass.
FALLBACK_SIGN_IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
usage() { usage() {
echo "Usage: $0 <version> [\"notes\"]" >&2 echo "Usage: $0 <version> [\"notes\"]" >&2
@@ -75,7 +72,6 @@ else
PUBLIC_DIR="${PUBLIC_BASE}" PUBLIC_DIR="${PUBLIC_BASE}"
fi fi
APP_BUNDLE="${ROOT}/.build/Redline.app"
ZIP_NAME="Redline-${VERSION}.zip" ZIP_NAME="Redline-${VERSION}.zip"
DMG_NAME="Redline-${VERSION}.dmg" DMG_NAME="Redline-${VERSION}.dmg"
ZIP_PATH="${ROOT}/.build/${ZIP_NAME}" ZIP_PATH="${ROOT}/.build/${ZIP_NAME}"
@@ -143,38 +139,6 @@ else
echo "==> --test: skipping git commit of version bump" echo "==> --test: skipping git commit of version bump"
fi fi
# --- Resolve the signing identity for the shipped artifacts -----------------
# REDLINE_KEYCHAIN (optional): a specific keychain to search/sign against,
# for hosts where the Developer ID identity does not live in the login
# keychain that codesign searches by default.
FIND_IDENTITY_ARGS=(-v -p codesigning)
CODESIGN_KEYCHAIN_ARGS=()
if [[ -n "${REDLINE_KEYCHAIN:-}" ]]; then
FIND_IDENTITY_ARGS+=("${REDLINE_KEYCHAIN}")
CODESIGN_KEYCHAIN_ARGS=(--keychain "${REDLINE_KEYCHAIN}")
fi
if [[ -n "${REDLINE_SIGN_IDENTITY:-}" ]]; then
SIGN_IDENTITY="${REDLINE_SIGN_IDENTITY}"
echo "==> Signing identity: ${SIGN_IDENTITY} (REDLINE_SIGN_IDENTITY)"
else
DEVELOPER_ID_LINE="$(security find-identity "${FIND_IDENTITY_ARGS[@]}" 2>/dev/null \
| grep -o '"Developer ID Application:[^"]*"' | head -n1 || true)"
DEVELOPER_ID="${DEVELOPER_ID_LINE//\"/}"
if [[ -n "${DEVELOPER_ID}" ]]; then
SIGN_IDENTITY="${DEVELOPER_ID}"
echo "==> Signing identity: ${SIGN_IDENTITY} (auto-detected Developer ID Application)"
else
SIGN_IDENTITY="${FALLBACK_SIGN_IDENTITY}"
echo
echo "************************************************************************"
echo "WARNING: signing with Apple Development identity — not Developer ID;"
echo "Gatekeeper will block first install on other Macs."
echo "************************************************************************"
echo
fi
fi
# Restricted HOMEs (agent sandboxes) hide the login keychain from codesign. # Restricted HOMEs (agent sandboxes) hide the login keychain from codesign.
# Re-run signed steps with the account's real home when the identity is missing. # Re-run signed steps with the account's real home when the identity is missing.
signing_home() { signing_home() {
@@ -203,85 +167,31 @@ run_signed() {
echo "==> Building signed Redline.app" echo "==> Building signed Redline.app"
run_signed ./scripts/build-app.sh run_signed ./scripts/build-app.sh
if [[ ! -d "${APP_BUNDLE}" ]]; then if [[ ! -d "${ROOT}/.build/Redline.app" ]]; then
echo "Signed app missing at ${APP_BUNDLE}" >&2 echo "Signed app missing at ${ROOT}/.build/Redline.app" >&2
exit 1 exit 1
fi fi
# build-app.sh always signs with its own hardcoded Apple Development identity
# first (it has to — that identifier+identity pair is what keeps the Screen
# Recording grant alive). Re-sign here with the identity actually resolved
# above, which is what ships. A no-op when the two happen to be the same.
echo "==> Signing ${APP_BUNDLE} with resolved identity"
run_signed codesign --force --options runtime --timestamp \
${CODESIGN_KEYCHAIN_ARGS[@]+"${CODESIGN_KEYCHAIN_ARGS[@]}"} \
--sign "${SIGN_IDENTITY}" \
--identifier "${BUNDLE_ID}" \
"${APP_BUNDLE}"
build_zip() {
mkdir -p "${ROOT}/.build"
(
cd "${ROOT}/.build"
rm -f "${ZIP_NAME}"
ditto -c -k --keepParent Redline.app "${ZIP_NAME}"
)
if [[ ! -s "${ZIP_PATH}" ]]; then
echo "Zip was not created at ${ZIP_PATH}" >&2
exit 1
fi
}
# Rebuilds the manual-installer DMG from whatever is currently at
# ${APP_BUNDLE} — never re-invokes build-app.sh, so a prior custom signature
# or notarization staple on ${APP_BUNDLE} survives into the DMG untouched.
build_dmg() {
local staging="${ROOT}/.build/dmg-staging"
local mount_point="${ROOT}/.build/dmg-mnt"
rm -rf "${staging}"
mkdir -p "${staging}"
ditto "${APP_BUNDLE}" "${staging}/Redline.app"
ln -s /Applications "${staging}/Applications"
mkdir -p "$(dirname "${DMG_PATH}")"
rm -f "${DMG_PATH}"
hdiutil create -volname "Redline" -srcfolder "${staging}" -ov -format UDZO "${DMG_PATH}"
if [[ -d "${mount_point}" ]] && /sbin/mount | grep -F -q "${mount_point}"; then
hdiutil detach "${mount_point}" || hdiutil detach "${mount_point}" -force
fi
rm -rf "${mount_point}"
mkdir -p "${mount_point}"
hdiutil attach "${DMG_PATH}" -nobrowse -readonly -mountpoint "${mount_point}"
local ok=1
if [[ ! -d "${mount_point}/Redline.app" ]]; then
echo "Verification failed: Redline.app missing from mounted DMG" >&2
ok=0
fi
if [[ "${ok}" -eq 1 && "$(readlink "${mount_point}/Applications" 2>/dev/null || true)" != "/Applications" ]]; then
echo "Verification failed: Applications does not point at /Applications" >&2
ok=0
fi
if [[ "${ok}" -eq 1 ]] && ! codesign --verify --deep --verbose=2 "${mount_point}/Redline.app"; then
ok=0
fi
hdiutil detach "${mount_point}" || hdiutil detach "${mount_point}" -force || true
if [[ "${ok}" -ne 1 ]]; then
exit 1
fi
if [[ ! -s "${DMG_PATH}" ]]; then
echo "DMG was not created at ${DMG_PATH}" >&2
exit 1
fi
}
echo "==> Zipping Redline.app -> ${ZIP_PATH}" echo "==> Zipping Redline.app -> ${ZIP_PATH}"
build_zip mkdir -p "${ROOT}/.build"
(
cd "${ROOT}/.build"
rm -f "${ZIP_NAME}"
ditto -c -k --keepParent Redline.app "${ZIP_NAME}"
)
if [[ ! -s "${ZIP_PATH}" ]]; then
echo "Zip was not created at ${ZIP_PATH}" >&2
exit 1
fi
echo "==> Building manual installer DMG"
run_signed ./scripts/make-dmg.sh
if [[ ! -s "${DMG_PATH}" ]]; then
echo "DMG was not created at ${DMG_PATH}" >&2
exit 1
fi
SHA256="$(shasum -a 256 "${ZIP_PATH}" | awk '{print $1}')" SHA256="$(shasum -a 256 "${ZIP_PATH}" | awk '{print $1}')"
ZIP_BYTES="$(stat -f%z "${ZIP_PATH}")" ZIP_BYTES="$(stat -f%z "${ZIP_PATH}")"
@@ -290,102 +200,18 @@ PUBDATE="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
echo "==> Zip SHA256: ${SHA256}" echo "==> Zip SHA256: ${SHA256}"
echo " Zip bytes: ${ZIP_BYTES}" echo " Zip bytes: ${ZIP_BYTES}"
# --- Notarization (optional) -------------------------------------------------
# Either REDLINE_NOTARY_PROFILE (a `notarytool store-credentials` keychain
# profile) or all three of REDLINE_NOTARY_KEY_ID / REDLINE_NOTARY_ISSUER /
# REDLINE_NOTARY_KEY_PATH (App Store Connect API key). Absent both: skip.
NOTARIZED=0
NOTARY_CONFIGURED=0
if [[ -n "${REDLINE_NOTARY_PROFILE:-}" ]]; then
NOTARY_CONFIGURED=1
elif [[ -n "${REDLINE_NOTARY_KEY_ID:-}" && -n "${REDLINE_NOTARY_ISSUER:-}" && -n "${REDLINE_NOTARY_KEY_PATH:-}" ]]; then
NOTARY_CONFIGURED=1
fi
if [[ "${NOTARY_CONFIGURED}" -eq 1 ]]; then
echo "==> Submitting ${ZIP_PATH} to notarytool"
NOTARY_ARGS=(xcrun notarytool submit "${ZIP_PATH}" --wait --timeout 30m)
if [[ -n "${REDLINE_NOTARY_PROFILE:-}" ]]; then
NOTARY_ARGS+=(--keychain-profile "${REDLINE_NOTARY_PROFILE}")
else
NOTARY_ARGS+=(
--key "${REDLINE_NOTARY_KEY_PATH}"
--key-id "${REDLINE_NOTARY_KEY_ID}"
--issuer "${REDLINE_NOTARY_ISSUER}"
)
fi
set +e
NOTARY_OUTPUT="$("${NOTARY_ARGS[@]}" 2>&1)"
NOTARY_STATUS=$?
set -e
echo "${NOTARY_OUTPUT}"
if [[ "${NOTARY_STATUS}" -ne 0 ]]; then
echo "notarytool submit failed (exit ${NOTARY_STATUS})." >&2
exit 1
fi
if ! grep -qi 'status: *Accepted' <<<"${NOTARY_OUTPUT}"; then
echo "notarytool did not report Accepted." >&2
exit 1
fi
NOTARIZED=1
echo "==> Stapling ${APP_BUNDLE}"
xcrun stapler staple "${APP_BUNDLE}"
echo "==> Rebuilding zip from the stapled app"
build_zip
SHA256="$(shasum -a 256 "${ZIP_PATH}" | awk '{print $1}')"
ZIP_BYTES="$(stat -f%z "${ZIP_PATH}")"
echo " Zip SHA256: ${SHA256}"
echo " Zip bytes: ${ZIP_BYTES}"
echo "==> Rebuilding DMG from the stapled app"
build_dmg
echo "==> Stapling ${DMG_PATH}"
xcrun stapler staple "${DMG_PATH}"
else
echo "==> REDLINE_NOTARY_KEY_ID/ISSUER/KEY_PATH (or REDLINE_NOTARY_PROFILE) not set"
echo "NOT NOTARIZED"
echo "==> Building manual installer DMG"
build_dmg
fi
echo "==> Gatekeeper check: spctl -a -vv -t exec ${APP_BUNDLE}"
set +e
SPCTL_OUTPUT="$(spctl -a -vv -t exec "${APP_BUNDLE}" 2>&1)"
SPCTL_STATUS=$?
set -e
echo "${SPCTL_OUTPUT}"
if [[ "${SPCTL_STATUS}" -ne 0 ]] || ! grep -qi 'accepted' <<<"${SPCTL_OUTPUT}"; then
if [[ "${NOTARIZED}" -eq 1 ]]; then
echo "spctl did not report accepted for ${APP_BUNDLE} although it was notarized." >&2
exit 1
fi
echo "WARNING: Gatekeeper does not accept this build (not notarized). First install on other Macs needs right-click > Open." >&2
fi
TEAM_IDENTIFIER="$(codesign -dv "${APP_BUNDLE}" 2>&1 | awk -F= '/^TeamIdentifier=/{print $2}')"
if [[ -z "${TEAM_IDENTIFIER}" ]]; then
echo "No TeamIdentifier on ${APP_BUNDLE} — the build is not signed with a team identity; refusing to publish." >&2
exit 1
fi
echo "==> Writing ${APPCAST_PATH}" echo "==> Writing ${APPCAST_PATH}"
python3 - "${VERSION}" "${ZIP_URL}" "${SHA256}" "${NOTES}" "${PUBDATE}" "${APPCAST_PATH}" "${NOTARIZED}" "${TEAM_IDENTIFIER}" <<'PY' python3 - "${VERSION}" "${ZIP_URL}" "${SHA256}" "${NOTES}" "${PUBDATE}" "${APPCAST_PATH}" <<'PY'
import json import json
import sys import sys
version, zip_url, sha256, notes, pub_date, out_path, notarized, team_identifier = sys.argv[1:] version, zip_url, sha256, notes, pub_date, out_path = sys.argv[1:]
payload = { payload = {
"version": version, "version": version,
"zipURL": zip_url, "zipURL": zip_url,
"sha256": sha256, "sha256": sha256,
"notes": notes, "notes": notes,
"pubDate": pub_date, "pubDate": pub_date,
"notarized": notarized == "1",
"teamIdentifier": team_identifier,
} }
with open(out_path, "w", encoding="utf-8") as fh: with open(out_path, "w", encoding="utf-8") as fh:
json.dump(payload, fh, indent=2) json.dump(payload, fh, indent=2)
@@ -454,16 +280,8 @@ fi
echo echo
echo "Published v${VERSION}" echo "Published v${VERSION}"
echo " identity: ${SIGN_IDENTITY}" echo " appcast: ${APPCAST_URL}"
if [[ "${NOTARIZED}" -eq 1 ]]; then echo " zip: ${ZIP_URL}"
echo " notarized: yes" echo " sha256: ${SHA256}"
else echo " dmg: ${PUBLIC_DIR}/${DMG_NAME}"
echo " notarized: no" echo " dmg: ${PUBLIC_DIR}/Redline.dmg"
fi
echo " spctl: ${SPCTL_OUTPUT}"
echo " team: ${TEAM_IDENTIFIER}"
echo " appcast: ${APPCAST_URL}"
echo " zip: ${ZIP_URL}"
echo " sha256: ${SHA256}"
echo " dmg: ${PUBLIC_DIR}/${DMG_NAME}"
echo " dmg: ${PUBLIC_DIR}/Redline.dmg"