Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0506ce04e9 | ||
|
|
eaa5bd5884 | ||
|
|
6ab398c3f2 | ||
|
|
eb1af5bf18 | ||
|
|
49c6a41033 | ||
|
|
706726a3d4 | ||
|
|
e1f569cc3e | ||
|
|
4da02e243f | ||
|
|
8b53a727e3 | ||
|
|
fdec105174 | ||
|
|
12128b016d | ||
|
|
a32cd03581 | ||
|
|
8a12ed0a54 | ||
|
|
bfdc6fde9d | ||
|
|
9884c844d4 | ||
|
|
365220ade8 | ||
|
|
064e410e30 | ||
|
|
a79a569a7d | ||
|
|
3abb8dc6ca | ||
|
|
8d68c836cd | ||
|
|
04d1e73532 | ||
|
|
d7984add2d | ||
|
|
723cd7dcea |
+2
-2
@@ -13,9 +13,9 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>0.2.0</string>
|
<string>0.3.0</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>2</string>
|
<string>3</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>14.0</string>
|
<string>14.0</string>
|
||||||
<key>LSUIElement</key>
|
<key>LSUIElement</key>
|
||||||
|
|||||||
@@ -27,5 +27,14 @@ 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)]
|
||||||
|
),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -14,6 +14,11 @@ public protocol SettingsWindowPresenting: AnyObject {
|
|||||||
func presentSettingsWindow()
|
func presentSettingsWindow()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
public protocol SubmissionsWindowPresenting: AnyObject {
|
||||||
|
func presentSubmissionsWindow()
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
public protocol ReturnsSectionProviding: AnyObject {
|
public protocol ReturnsSectionProviding: AnyObject {
|
||||||
@ViewBuilder func returnsSection() -> AnyView
|
@ViewBuilder func returnsSection() -> AnyView
|
||||||
@@ -27,9 +32,16 @@ public final class AppModel {
|
|||||||
public private(set) var screenRecordingGranted: Bool
|
public private(set) var screenRecordingGranted: Bool
|
||||||
public private(set) var allReturns: [ReturnedDocument] = []
|
public private(set) var allReturns: [ReturnedDocument] = []
|
||||||
public private(set) var commentedReturns: [ReturnedDocument] = []
|
public private(set) var commentedReturns: [ReturnedDocument] = []
|
||||||
|
/// Retained past sessions (newest first) — what the Past submissions window lists.
|
||||||
|
public private(set) var pastSessions: [CaptureSession] = []
|
||||||
public private(set) var statusLine: String?
|
public private(set) var statusLine: 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
|
||||||
|
/// True while "Start new session" is between its guard and its store call — the
|
||||||
|
/// synchronous flag both this action and send() check BEFORE their first await, so
|
||||||
|
/// the two can never interleave a session close with an in-flight compose (a
|
||||||
|
/// SwiftUI `.disabled` render-time guard alone does not stop a queued Task).
|
||||||
|
public private(set) var isStartingNewSession: 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
|
/// Live transport choice; WP-onedrive reads this to pick the send path and to drive
|
||||||
@@ -51,6 +63,8 @@ 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
|
||||||
@@ -108,12 +122,26 @@ public final class AppModel {
|
|||||||
self.setStatus(message)
|
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() }
|
||||||
|
/// Most recent status text — shared with the general status line by design
|
||||||
|
/// (Redline has one status channel, not a separate update-only one).
|
||||||
|
public var updateStatusMessage: String? { statusLine }
|
||||||
|
|
||||||
// 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 setSending(_ value: Bool) { isSending = value }
|
func setSending(_ value: Bool) { isSending = value }
|
||||||
|
/// Fixture seam (same family as setSending): lets tests/PanelSnapshot stage the
|
||||||
|
/// in-flight-start state that production only ever reaches inside startNewSession().
|
||||||
|
func setStartingNewSession(_ value: Bool) { isStartingNewSession = 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 }
|
||||||
func replaceRegion(_ new: CaptureRegion?) { region = new }
|
func replaceRegion(_ new: CaptureRegion?) { region = new }
|
||||||
@@ -121,6 +149,7 @@ public final class AppModel {
|
|||||||
allReturns = all
|
allReturns = all
|
||||||
commentedReturns = commented
|
commentedReturns = commented
|
||||||
}
|
}
|
||||||
|
func setPastSessions(_ value: [CaptureSession]) { pastSessions = value }
|
||||||
func setFolderDisplayNames(outbox: String, watch: String) {
|
func setFolderDisplayNames(outbox: String, watch: String) {
|
||||||
outboxDisplayName = outbox
|
outboxDisplayName = outbox
|
||||||
watchFolderDisplayName = watch
|
watchFolderDisplayName = watch
|
||||||
@@ -139,6 +168,14 @@ public final class AppModel {
|
|||||||
/// lets the LAST choice win instead of applying stale, superseded work. Not
|
/// lets the LAST choice win instead of applying stale, superseded work. Not
|
||||||
/// `@Observable`-relevant state — pure internal bookkeeping, never read by a View.
|
/// `@Observable`-relevant state — pure internal bookkeeping, never read by a View.
|
||||||
var reconcileGeneration = 0
|
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
|
||||||
@@ -206,6 +243,12 @@ public final class AppModel {
|
|||||||
// Empty ledger on first run is not an error.
|
// Empty ledger on first run is not an error.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
setPastSessions(try await spool.archivedSessions())
|
||||||
|
} catch {
|
||||||
|
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not load past sessions.")
|
||||||
|
}
|
||||||
|
|
||||||
// OneDrive mode: outbox == watch folder, so a freshly written, unmarked PDF must
|
// 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.
|
// 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
|
// Also make sure the resolved OneDrive folder actually exists before the
|
||||||
@@ -241,19 +284,29 @@ 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.")
|
||||||
}
|
}
|
||||||
|
|
||||||
let pref = HotkeyPreference.load()
|
// Env-var-flagged self-test/headless runs (PickerSelfTest's phases, PanelSnapshot,
|
||||||
captureHotkey = pref
|
// and the new ShotdeckTests launch-wiring regression test) skip two real-world
|
||||||
if !bindCaptureHotkey(pref) {
|
// side effects that are unsafe or meaningless in that context: the update-check
|
||||||
setStatus("\(pref.displayString) is already used by another app — capture only works from the menu.")
|
// 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
|
||||||
let skipSchedule =
|
// 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_PICKER_SELFTEST"] != nil
|
||||||
|| ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil
|
|| ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil
|
||||||
|| ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|
|| ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|
||||||
|| ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil
|
|| ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil
|
||||||
|| ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] != nil
|
|| ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] != nil
|
||||||
if !skipSchedule {
|
|
||||||
|
let pref = HotkeyPreference.load()
|
||||||
|
captureHotkey = pref
|
||||||
|
if !isSelfTestRun, !bindCaptureHotkey(pref) {
|
||||||
|
setStatus("\(pref.displayString) is already used by another app — capture only works from the menu.")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isSelfTestRun {
|
||||||
updateChecker.startSchedule()
|
updateChecker.startSchedule()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -264,6 +317,19 @@ 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() {
|
||||||
@@ -345,6 +411,100 @@ public final class AppModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// True when "Start new session" applies: there is something to keep and neither a
|
||||||
|
/// send nor another session start is in flight.
|
||||||
|
public var canStartNewSession: Bool {
|
||||||
|
!session.isEmpty && !isSending && !isStartingNewSession
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Menu "Start new session": keeps the current screenshots as a past session
|
||||||
|
/// (moved into the single archive folder — never deleted) and opens a fresh empty
|
||||||
|
/// session. Session retention (newest 10 kept) is applied inside the store, on
|
||||||
|
/// this path and on the send path alike.
|
||||||
|
public func startNewSession() async {
|
||||||
|
// Re-checked here on the main actor, synchronously, before the first await:
|
||||||
|
// the menu's `.disabled` state cannot stop a Task that was queued just before
|
||||||
|
// a send started.
|
||||||
|
guard !isSending, !isStartingNewSession else {
|
||||||
|
setStatus(isSending ? "Finish the current send first." : "A new session is already being started.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isStartingNewSession = true
|
||||||
|
defer { isStartingNewSession = false }
|
||||||
|
|
||||||
|
var message: String
|
||||||
|
do {
|
||||||
|
if let archived = try await spool.closeCurrentSession() {
|
||||||
|
let count = archived.captures.count
|
||||||
|
message = "New session — \(count) capture\(count == 1 ? "" : "s") kept as a past session."
|
||||||
|
} else {
|
||||||
|
message = "New session started."
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
message = (error as? ShotdeckError)?.errorDescription ?? "Could not start a new session."
|
||||||
|
}
|
||||||
|
if let refreshProblem = await reloadFromSpool() {
|
||||||
|
message += " \(refreshProblem)"
|
||||||
|
}
|
||||||
|
setStatus(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-reads the open session and the past-session list from the store. Returns a
|
||||||
|
/// problem description when either read failed (the caller decides how to surface
|
||||||
|
/// it), nil when everything was refreshed — never silently substitutes stale state.
|
||||||
|
func reloadFromSpool() async -> String? {
|
||||||
|
var problems: [String] = []
|
||||||
|
do {
|
||||||
|
replaceSession(try await spool.currentSession())
|
||||||
|
} catch {
|
||||||
|
problems.append(
|
||||||
|
"Could not reload the current session: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
setPastSessions(try await spool.archivedSessions())
|
||||||
|
} catch {
|
||||||
|
problems.append(
|
||||||
|
"Could not load past sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
|
||||||
|
}
|
||||||
|
return problems.isEmpty ? nil : problems.joined(separator: " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a past session's sent PDF lives now (the outbox in AirDrop mode, the
|
||||||
|
/// OneDrive folder in OneDrive mode), or nil when it was never sent / is gone.
|
||||||
|
public func sentPDFURL(for session: CaptureSession) -> URL? {
|
||||||
|
guard let name = session.pdfFileName else { return nil }
|
||||||
|
let url = outboxURL.appendingPathComponent(name)
|
||||||
|
return FileManager.default.fileExists(atPath: url.path) ? url : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "PDF" action on a past-submission row: reveals the exact PDF that was sent.
|
||||||
|
public func revealSentPDF(_ session: CaptureSession) {
|
||||||
|
guard session.pdfFileName != nil else {
|
||||||
|
setStatus("That session was never sent.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let url = sentPDFURL(for: session) else {
|
||||||
|
setStatus("The PDF is no longer in \(outboxDisplayName).")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([url])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Captures" action on a past-submission row: reveals that session's folder.
|
||||||
|
public func revealSessionCaptures(_ session: CaptureSession) {
|
||||||
|
let dir = paths.archiveDirectory(session.id)
|
||||||
|
guard FileManager.default.fileExists(atPath: dir.path) else {
|
||||||
|
setStatus("That past session is no longer on disk.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([dir])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The single folder every retained session lives in.
|
||||||
|
public func openSessionsFolder() {
|
||||||
|
NSWorkspace.shared.open(paths.archive)
|
||||||
|
}
|
||||||
|
|
||||||
public func copyCommentedLinks() async {
|
public func copyCommentedLinks() async {
|
||||||
do {
|
do {
|
||||||
let text = try await ledger.clipboardText()
|
let text = try await ledger.clipboardText()
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ struct MenuBarView: View {
|
|||||||
Divider()
|
Divider()
|
||||||
returnsBlock
|
returnsBlock
|
||||||
}
|
}
|
||||||
|
Divider()
|
||||||
|
updateFooter
|
||||||
}
|
}
|
||||||
.padding(10)
|
.padding(10)
|
||||||
.frame(width: 320, alignment: .leading)
|
.frame(width: 320, alignment: .leading)
|
||||||
@@ -83,6 +85,21 @@ 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 {
|
||||||
@@ -102,6 +119,26 @@ struct MenuBarView: View {
|
|||||||
}
|
}
|
||||||
.disabled(!model.canRevealLastPDF)
|
.disabled(!model.canRevealLastPDF)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
Task { await model.startNewSession() }
|
||||||
|
} label: {
|
||||||
|
actionLabel("Start new session")
|
||||||
|
}
|
||||||
|
.disabled(!model.canStartNewSession)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
if let presenter = model as? SubmissionsWindowPresenting {
|
||||||
|
presenter.presentSubmissionsWindow()
|
||||||
|
} else {
|
||||||
|
model.setStatus("Past submissions are not available in this build.")
|
||||||
|
}
|
||||||
|
} label: {
|
||||||
|
actionLabel(
|
||||||
|
"Past submissions…",
|
||||||
|
trailing: model.pastSessions.isEmpty ? nil : "\(model.pastSessions.count)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Button {
|
Button {
|
||||||
Task { await model.captureNow() }
|
Task { await model.captureNow() }
|
||||||
} label: {
|
} label: {
|
||||||
@@ -193,4 +230,18 @@ 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,11 @@ enum PanelSnapshot {
|
|||||||
|
|
||||||
let region = sampleRegion()
|
let region = sampleRegion()
|
||||||
|
|
||||||
|
// Two real past sessions through the REAL store paths (one sent with a PDF in
|
||||||
|
// the outbox, one closed without ever sending) so panel-06b has the exact two
|
||||||
|
// states the Past submissions window must distinguish.
|
||||||
|
try await seedPastSessions(to: model)
|
||||||
|
|
||||||
// 01 — Screen Recording missing (no public mutator; snapshot-only seam).
|
// 01 — Screen Recording missing (no public mutator; snapshot-only seam).
|
||||||
model.snapshotSetScreenRecordingGranted(false)
|
model.snapshotSetScreenRecordingGranted(false)
|
||||||
model.replaceRegion(nil)
|
model.replaceRegion(nil)
|
||||||
@@ -74,6 +79,15 @@ enum PanelSnapshot {
|
|||||||
to: directory.appendingPathComponent("panel-06-settings.png")
|
to: directory.appendingPathComponent("panel-06-settings.png")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 06b — Past submissions window against the same isolated model: the two
|
||||||
|
// seeded past sessions plus the live session's three captures from panel 04.
|
||||||
|
model.setPastSessions(try await model.spool.archivedSessions())
|
||||||
|
try render(
|
||||||
|
PastSubmissionsView().environment(model),
|
||||||
|
to: directory.appendingPathComponent("panel-06b-past-submissions.png"),
|
||||||
|
width: 440
|
||||||
|
)
|
||||||
|
|
||||||
// 07/08/09 — OneDrive-mode Settings + menu bar, on a SEPARATE isolated model so
|
// 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.
|
// this transport switch never bleeds into the AirDrop-mode panels above.
|
||||||
try await captureOneDrivePanels(to: directory)
|
try await captureOneDrivePanels(to: directory)
|
||||||
@@ -157,6 +171,27 @@ enum PanelSnapshot {
|
|||||||
try renderMenuBar(model: model, to: directory, name: "09-captures-present-onedrive")
|
try renderMenuBar(model: model, to: directory, name: "09-captures-present-onedrive")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private static func seedPastSessions(to model: AppModel) async throws {
|
||||||
|
_ = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 192, height: 108, red: 0.55, green: 0.35, blue: 0.85),
|
||||||
|
pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date())
|
||||||
|
_ = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 192, height: 108, red: 0.25, green: 0.7, blue: 0.6),
|
||||||
|
pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date())
|
||||||
|
let sentName = "Redline-\(DubaiTime.fileStamp(Date())).pdf"
|
||||||
|
_ = try await model.spool.archiveCurrent(pdfFileName: sentName)
|
||||||
|
// The real send writes the PDF to the outbox; the fixture does the same so the
|
||||||
|
// row's PDF action is genuinely live in the snapshot.
|
||||||
|
try Data("%PDF-1.4\n% snapshot fixture\n".utf8).write(
|
||||||
|
to: model.paths.outbox.appendingPathComponent(sentName))
|
||||||
|
|
||||||
|
_ = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 160, height: 90, red: 0.9, green: 0.55, blue: 0.2),
|
||||||
|
pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date())
|
||||||
|
_ = try await model.spool.closeCurrentSession()
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private static func renderMenuBar(model: AppModel, to directory: URL, name: String) throws {
|
private static func renderMenuBar(model: AppModel, to directory: URL, name: String) throws {
|
||||||
try render(
|
try render(
|
||||||
@@ -166,9 +201,9 @@ enum PanelSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private static func render(_ view: some View, to url: URL) throws {
|
private static func render(_ view: some View, to url: URL, width: CGFloat = panelWidth) throws {
|
||||||
let wrapped = view
|
let wrapped = view
|
||||||
.frame(width: panelWidth, alignment: .topLeading)
|
.frame(width: width, alignment: .topLeading)
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
.background(Color(nsColor: .windowBackgroundColor))
|
.background(Color(nsColor: .windowBackgroundColor))
|
||||||
|
|
||||||
@@ -196,7 +231,7 @@ enum PanelSnapshot {
|
|||||||
size.height = hosting.intrinsicContentSize.height
|
size.height = hosting.intrinsicContentSize.height
|
||||||
}
|
}
|
||||||
if size.height < 1 { size.height = 240 }
|
if size.height < 1 { size.height = 240 }
|
||||||
size.width = panelWidth
|
size.width = width
|
||||||
size.height = ceil(size.height)
|
size.height = ceil(size.height)
|
||||||
|
|
||||||
hosting.setFrameSize(size)
|
hosting.setFrameSize(size)
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
import ShotdeckCore
|
||||||
|
|
||||||
|
/// "Past submissions…" window: every retained session and what was sent for it.
|
||||||
|
/// Read-and-reveal only — keeping/starting sessions is driven from the menu rows
|
||||||
|
/// (and the button on the current-session row below).
|
||||||
|
struct PastSubmissionsView: View {
|
||||||
|
@Environment(AppModel.self) private var model
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
currentSessionRow
|
||||||
|
Divider()
|
||||||
|
if model.pastSessions.isEmpty {
|
||||||
|
Text("No past sessions yet. Use “Start new session” to keep the current captures.")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
} else {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
ForEach(model.pastSessions) { session in
|
||||||
|
PastSessionRow(session: session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxHeight: 320)
|
||||||
|
}
|
||||||
|
Divider()
|
||||||
|
footer
|
||||||
|
}
|
||||||
|
.padding(10)
|
||||||
|
.frame(width: 420, alignment: .leading)
|
||||||
|
.controlSize(.small)
|
||||||
|
.task {
|
||||||
|
if let problem = await model.reloadFromSpool() {
|
||||||
|
model.setStatus(problem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentSessionRow: some View {
|
||||||
|
HStack(alignment: .center, spacing: 8) {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text("Current session")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text(currentSessionSummary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
Spacer(minLength: 8)
|
||||||
|
Button("Start new session") {
|
||||||
|
Task { await model.startNewSession() }
|
||||||
|
}
|
||||||
|
.disabled(!model.canStartNewSession)
|
||||||
|
.help("Keeps these captures as a past session and starts a fresh one.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentSessionSummary: String {
|
||||||
|
let count = model.session.captures.count
|
||||||
|
if count == 0 {
|
||||||
|
return "Nothing captured yet."
|
||||||
|
}
|
||||||
|
return "\(count) capture\(count == 1 ? "" : "s") · started \(DubaiTime.stamp(model.session.createdAt))"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var footer: some View {
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
Text("Sessions are kept in one folder — the newest \(SpoolStore.defaultRetainedSessionCount).")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
Spacer(minLength: 8)
|
||||||
|
Button("Open sessions folder") {
|
||||||
|
model.openSessionsFolder()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct PastSessionRow: View {
|
||||||
|
@Environment(AppModel.self) private var model
|
||||||
|
let session: CaptureSession
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(alignment: .center, spacing: 8) {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(DubaiTime.stamp(session.createdAt))
|
||||||
|
Text(submissionLabel)
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(session.pdfFileName == nil ? .secondary : .primary)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
Spacer(minLength: 8)
|
||||||
|
Button("PDF") {
|
||||||
|
model.revealSentPDF(session)
|
||||||
|
}
|
||||||
|
.disabled(model.sentPDFURL(for: session) == nil)
|
||||||
|
.help(pdfHelpText)
|
||||||
|
Button("Captures") {
|
||||||
|
model.revealSessionCaptures(session)
|
||||||
|
}
|
||||||
|
.help("Reveal this session's screenshots")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var pdfHelpText: String {
|
||||||
|
guard let name = session.pdfFileName else { return "This session was never sent." }
|
||||||
|
guard model.sentPDFURL(for: session) != nil else {
|
||||||
|
return "The PDF \(name) is no longer in the output folder."
|
||||||
|
}
|
||||||
|
return "Reveal \(name)"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var submissionLabel: String {
|
||||||
|
let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")"
|
||||||
|
guard let name = session.pdfFileName else {
|
||||||
|
return "\(pages) · not sent"
|
||||||
|
}
|
||||||
|
return "\(pages) · sent as \(name)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension AppModel: SubmissionsWindowPresenting {
|
||||||
|
private static var submissionsWindowController: NSWindowController?
|
||||||
|
|
||||||
|
public func presentSubmissionsWindow() {
|
||||||
|
if let existing = Self.submissionsWindowController {
|
||||||
|
existing.window?.makeKeyAndOrderFront(nil)
|
||||||
|
NSApp.activate()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let hosting = NSHostingController(rootView: PastSubmissionsView().environment(self))
|
||||||
|
let window = NSWindow(contentViewController: hosting)
|
||||||
|
window.title = "Redline — Past submissions"
|
||||||
|
window.styleMask = [.titled, .closable]
|
||||||
|
window.isReleasedWhenClosed = false
|
||||||
|
window.center()
|
||||||
|
let controller = NSWindowController(window: window)
|
||||||
|
Self.submissionsWindowController = controller
|
||||||
|
controller.showWindow(nil)
|
||||||
|
NSApp.activate()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -223,7 +223,7 @@ enum PickerSelfTest {
|
|||||||
sendTruthFail("seeded session was empty")
|
sendTruthFail("seeded session was empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
let pending = try await model.composePDFForSend(outbox: model.outboxURL)
|
let pending = try await model.composePDFForSend(outbox: model.outboxURL, transport: .airDrop)
|
||||||
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")
|
||||||
}
|
}
|
||||||
@@ -241,7 +241,10 @@ enum PickerSelfTest {
|
|||||||
sendTruthFail("fail path status missing 'nothing was sent': \(model.statusLine ?? "nil")")
|
sendTruthFail("fail path status missing 'nothing was sent': \(model.statusLine ?? "nil")")
|
||||||
}
|
}
|
||||||
|
|
||||||
await model.handleDidShareItems(fileName: pending.fileName, pageCount: pending.pageCount)
|
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||||||
|
await model.handleDidShareItems(
|
||||||
|
fileName: pending.fileName,
|
||||||
|
sentSummary: "Sent — \(pending.pageCount) \(pageWord).")
|
||||||
let fresh = try await model.spool.currentSession()
|
let fresh = try await model.spool.currentSession()
|
||||||
guard fresh.isEmpty, fresh.id != openID, fresh.state == .open else {
|
guard fresh.isEmpty, fresh.id != openID, fresh.state == .open else {
|
||||||
sendTruthFail("success path did not mint a fresh empty session")
|
sendTruthFail("success path did not mint a fresh empty session")
|
||||||
@@ -328,6 +331,9 @@ 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)
|
||||||
@@ -335,6 +341,9 @@ 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) {
|
||||||
@@ -352,17 +361,20 @@ 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")
|
||||||
|
|
||||||
|
func writeZipAndAppcast() throws {
|
||||||
if fm.fileExists(atPath: zipURL.path) {
|
if fm.fileExists(atPath: zipURL.path) {
|
||||||
try fm.removeItem(at: zipURL)
|
try fm.removeItem(at: zipURL)
|
||||||
}
|
}
|
||||||
try runDitto(arguments: ["-c", "-k", payload.path, zipURL.path])
|
try runDitto(arguments: ["-c", "-k", payload.path, zipURL.path])
|
||||||
|
|
||||||
let zipData = try Data(contentsOf: zipURL)
|
let zipData = try Data(contentsOf: zipURL)
|
||||||
let hex = UpdateChecker.sha256Hex(zipData)
|
let hex = UpdateChecker.sha256Hex(zipData)
|
||||||
|
|
||||||
let appcastURL = outputDirectory.appendingPathComponent("appcast.json")
|
|
||||||
let appcast: [String: String] = [
|
let appcast: [String: String] = [
|
||||||
"version": "99.0.0",
|
"version": "99.0.0",
|
||||||
"zipURL": zipURL.absoluteString,
|
"zipURL": zipURL.absoluteString,
|
||||||
@@ -371,13 +383,15 @@ enum PickerSelfTest {
|
|||||||
]
|
]
|
||||||
let appcastData = try JSONSerialization.data(withJSONObject: appcast, options: [.sortedKeys])
|
let appcastData = try JSONSerialization.data(withJSONObject: appcast, options: [.sortedKeys])
|
||||||
try appcastData.write(to: appcastURL)
|
try appcastData.write(to: appcastURL)
|
||||||
|
}
|
||||||
|
try writeZipAndAppcast()
|
||||||
|
|
||||||
let defaults = UserDefaults.standard
|
let defaults = UserDefaults.standard
|
||||||
let previous = defaults.string(forKey: UpdateChecker.appcastURLDefaultsKey)
|
let previousAppcastPref = defaults.string(forKey: UpdateChecker.appcastURLDefaultsKey)
|
||||||
defaults.set(appcastURL.absoluteString, forKey: UpdateChecker.appcastURLDefaultsKey)
|
defaults.set(appcastURL.absoluteString, forKey: UpdateChecker.appcastURLDefaultsKey)
|
||||||
defer {
|
defer {
|
||||||
if let previous {
|
if let previousAppcastPref {
|
||||||
defaults.set(previous, forKey: UpdateChecker.appcastURLDefaultsKey)
|
defaults.set(previousAppcastPref, forKey: UpdateChecker.appcastURLDefaultsKey)
|
||||||
} else {
|
} else {
|
||||||
defaults.removeObject(forKey: UpdateChecker.appcastURLDefaultsKey)
|
defaults.removeObject(forKey: UpdateChecker.appcastURLDefaultsKey)
|
||||||
}
|
}
|
||||||
@@ -386,39 +400,128 @@ 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(
|
||||||
"updateAvailable=\(model.updateAvailable?.version ?? "nil")"
|
"staged-signed: updateAvailable=\(model.updateAvailable?.version ?? "nil")"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
guard let staged = model.updateChecker.stagedAppURL else {
|
guard let staged = model.updateChecker.stagedAppURL else {
|
||||||
throw UpdateSelfTestError.detail("staged payload missing")
|
throw UpdateSelfTestError.detail("staged-signed: staged payload missing")
|
||||||
}
|
}
|
||||||
guard staged.lastPathComponent == "Redline.app" else {
|
guard staged.lastPathComponent == "Redline.app" else {
|
||||||
throw UpdateSelfTestError.detail("staged name \(staged.lastPathComponent)")
|
throw UpdateSelfTestError.detail("staged-signed: 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 Contents/MacOS/Shotdeck missing")
|
throw UpdateSelfTestError.detail("staged-signed: staged Contents/MacOS/Shotdeck missing")
|
||||||
}
|
}
|
||||||
|
print("UPDATE-SELFTEST staged-signed PASS")
|
||||||
|
fflush(stdout)
|
||||||
|
|
||||||
let targetRoot = outputDirectory.appendingPathComponent("target", isDirectory: true)
|
// (c) ATOMIC INSTALL — a throwaway target pre-populated with the real
|
||||||
if fm.fileExists(atPath: targetRoot.path) {
|
// running version; never `/Applications`.
|
||||||
try fm.removeItem(at: targetRoot)
|
let tempAppsRoot = outputDirectory.appendingPathComponent("Applications", isDirectory: true)
|
||||||
|
if fm.fileExists(atPath: tempAppsRoot.path) {
|
||||||
|
try fm.removeItem(at: tempAppsRoot)
|
||||||
}
|
}
|
||||||
let target = targetRoot.appendingPathComponent("Redline.app")
|
try fm.createDirectory(at: tempAppsRoot, withIntermediateDirectories: true)
|
||||||
model.updateChecker.installStaged(to: target)
|
let tempTarget = tempAppsRoot.appendingPathComponent("Redline.app")
|
||||||
|
try fm.copyItem(at: sourceApp, to: tempTarget)
|
||||||
|
|
||||||
let installedPlist = target.appendingPathComponent("Contents/Info.plist")
|
model.updateChecker.installStaged(to: tempTarget)
|
||||||
guard let installed = NSDictionary(contentsOf: installedPlist) as? [String: Any],
|
|
||||||
let installedVersion = installed["CFBundleShortVersionString"] as? String
|
guard let installedVersion = readShortVersion(atAppURL: tempTarget) else {
|
||||||
else {
|
throw UpdateSelfTestError.detail("atomic-install: installed Info.plist unreadable")
|
||||||
throw UpdateSelfTestError.detail("installed Info.plist unreadable")
|
|
||||||
}
|
}
|
||||||
guard installedVersion == "99.0.0" else {
|
guard installedVersion == "99.0.0" else {
|
||||||
throw UpdateSelfTestError.detail("installed version \(installedVersion)")
|
throw UpdateSelfTestError.detail("atomic-install: 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: ", "))"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -492,6 +595,38 @@ enum PickerSelfTest {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Entry point for running ONLY the SEND-TRUTH phase, bypassing the on-screen picker
|
||||||
|
/// chain entirely — the chain's REGION-PERSIST phase needs an active display
|
||||||
|
/// (CGDisplayIsActive) and exits before SEND-TRUTH in headless/remote sessions.
|
||||||
|
/// Escape hatch: `REDLINE_SELFTEST_PHASE=sendtruth`.
|
||||||
|
static func runSendTruthOnlyIfRequested() {
|
||||||
|
guard ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Same hop as runOneDriveOnlyIfRequested(): 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 {
|
||||||
|
runSendTruthAndExit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func runSendTruthAndExit() {
|
||||||
|
Task { @MainActor in
|
||||||
|
do {
|
||||||
|
try await executeSendTruth()
|
||||||
|
print("SEND-TRUTH PASS")
|
||||||
|
fflush(stdout)
|
||||||
|
exit(0)
|
||||||
|
} catch {
|
||||||
|
print("SEND-TRUTH FAIL \(error)")
|
||||||
|
fflush(stdout)
|
||||||
|
exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Entry point for running ONLY this phase, bypassing the on-screen picker chain
|
/// 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
|
/// entirely. The harness has no other per-phase selector, so this is the escape
|
||||||
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
|
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
|
||||||
@@ -543,6 +678,13 @@ enum PickerSelfTest {
|
|||||||
/// does let the last choice win instead of an earlier, superseded call applying its
|
/// does let the last choice win instead of an earlier, superseded call applying its
|
||||||
/// stale folder after a later one already won.
|
/// 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
|
/// 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
|
/// 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,
|
/// model the same way the real app launches (`AppDelegate.makeLaunchModel()` itself,
|
||||||
@@ -673,6 +815,52 @@ enum PickerSelfTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.
|
// Sub-step 2: relaunch simulation — see the doc comment above this function.
|
||||||
let relaunchAppSupportRoot = fm.temporaryDirectory
|
let relaunchAppSupportRoot = fm.temporaryDirectory
|
||||||
.appendingPathComponent("shotdeck-onedrive-relaunch-\(UUID().uuidString)", isDirectory: true)
|
.appendingPathComponent("shotdeck-onedrive-relaunch-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
|||||||
@@ -14,30 +14,53 @@ struct ComposedSend: Sendable {
|
|||||||
extension AppModel: SendCapable {
|
extension AppModel: SendCapable {
|
||||||
public func send(anchor: NSView?) async {
|
public func send(anchor: NSView?) async {
|
||||||
guard !session.isEmpty, !isSending else { return }
|
guard !session.isEmpty, !isSending else { return }
|
||||||
|
// Same synchronous guard as AppModel.startNewSession(): refuse while a session
|
||||||
|
// start is mid-flight, instead of composing from a session directory that is
|
||||||
|
// being renamed into the archive.
|
||||||
|
guard !isStartingNewSession else {
|
||||||
|
setStatus("Finish starting the new session first.")
|
||||||
|
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
|
// Snapshot BOTH the transport AND the destination folder into local `let`s
|
||||||
// ONCE, before any `await` in this function. chooseTransport/chooseOneDriveFolder
|
// ONCE, before any further `await` in this function. chooseTransport/
|
||||||
// now refuse (status "Finish the current send first.") while isSending is true,
|
// chooseOneDriveFolder also refuse outright (status "Finish the current send
|
||||||
// but this snapshot is the actual fix for the race: even without that guard,
|
// first.") while isSending is true, but this snapshot is the actual fix for the
|
||||||
// everything below operates on these frozen values — composePDFForSend(outbox:)
|
// send-vs-switch race: even without that guard, everything below operates on
|
||||||
// takes the folder as a parameter and never re-reads `self.outboxURL` after a
|
// these frozen values — composePDFForSend(outbox:transport:) takes both as
|
||||||
// suspension point, so a concurrent transport switch mid-send can no longer land
|
// parameters and never re-reads `self.outboxURL`/`self.transport` after a
|
||||||
// the PDF under one transport's folder while the archive/status branch (which
|
// suspension point, so a concurrent transport switch mid-send can no longer
|
||||||
// switches on the same frozen `transport` local) runs the other's.
|
// land the PDF under one transport's folder while the archive/status branch
|
||||||
|
// runs the other's.
|
||||||
let transport = TransportSettings.transport()
|
let transport = TransportSettings.transport()
|
||||||
let destinationFolder: URL
|
let destinationFolder: URL
|
||||||
|
|
||||||
// OneDrive mode: verify the real destination exists AND is writable RIGHT NOW,
|
// OneDrive mode: verify the real destination exists, is writable, AND actually
|
||||||
// before composing anything. `outboxURL` is kept in sync with the resolved
|
// accepts a real write RIGHT NOW, before composing anything. `isWritableDirectory`
|
||||||
// OneDrive folder by bootstrap/chooseTransport/chooseOneDriveFolder, but this is
|
// 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
|
// re-resolved fresh here (never trusted stale) so a folder that vanished or lost
|
||||||
// its permissions since then (OneDrive signed out, external volume unmounted,
|
// its permissions since then (OneDrive signed out, external volume unmounted,
|
||||||
// folder deleted, chmod'd unwritable) is caught instead of silently attempted
|
// folder deleted, chmod'd unwritable) is caught instead of silently attempted
|
||||||
// and surfacing as a generic PDF-composition failure.
|
// and surfacing as a generic PDF-composition failure.
|
||||||
if transport == .oneDrive {
|
if transport == .oneDrive {
|
||||||
guard let folder = OneDriveLocator.resolveOneDriveFolder(),
|
guard let folder = OneDriveLocator.resolveOneDriveFolder(),
|
||||||
OneDriveLocator.isWritableDirectory(at: folder)
|
OneDriveLocator.isWritableDirectory(at: folder),
|
||||||
|
OneDriveLocator.probeWritable(at: folder)
|
||||||
else {
|
else {
|
||||||
let path = OneDriveLocator.resolveOneDriveFolder()?.path
|
let path = OneDriveLocator.resolveOneDriveFolder()?.path
|
||||||
?? TransportSettings.storedOneDriveFolderPath()
|
?? TransportSettings.storedOneDriveFolderPath()
|
||||||
@@ -59,7 +82,7 @@ extension AppModel: SendCapable {
|
|||||||
|
|
||||||
let pending: ComposedSend
|
let pending: ComposedSend
|
||||||
do {
|
do {
|
||||||
pending = try await composePDFForSend(outbox: destinationFolder)
|
pending = try await composePDFForSend(outbox: destinationFolder, transport: transport)
|
||||||
} 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.
|
||||||
@@ -72,10 +95,10 @@ extension AppModel: SendCapable {
|
|||||||
case .oneDrive:
|
case .oneDrive:
|
||||||
// No AirDrop, no anchor needed — the PDF is already in the watched
|
// No AirDrop, no anchor needed — the PDF is already in the watched
|
||||||
// OneDrive folder. Archive immediately; the iPad marks it up in place.
|
// 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"
|
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||||||
setStatus(
|
await handleDidShareItems(
|
||||||
"Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
|
fileName: pending.fileName,
|
||||||
|
sentSummary: "Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
|
||||||
)
|
)
|
||||||
setSending(false)
|
setSending(false)
|
||||||
|
|
||||||
@@ -90,9 +113,10 @@ extension AppModel: SendCapable {
|
|||||||
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
|
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
if success {
|
if success {
|
||||||
|
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||||||
await self.handleDidShareItems(
|
await self.handleDidShareItems(
|
||||||
fileName: pending.fileName,
|
fileName: pending.fileName,
|
||||||
pageCount: pending.pageCount
|
sentSummary: "Sent — \(pending.pageCount) \(pageWord)."
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
self.handleDidFailToShareItems(fileName: pending.fileName)
|
self.handleDidFailToShareItems(fileName: pending.fileName)
|
||||||
@@ -109,10 +133,16 @@ extension AppModel: SendCapable {
|
|||||||
|
|
||||||
/// Writes the PDF to `outboxDir` and records its path. Does not archive the session
|
/// Writes the PDF to `outboxDir` 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` is passed in (a value `send(anchor:)` snapshotted before any await)
|
/// `outboxDir`/`transport` are passed in (values `send(anchor:)` snapshotted before
|
||||||
/// rather than read from `self.outboxURL` here, so a concurrent transport switch
|
/// any await) rather than read from `self.outboxURL`/`self.transport` here, so a
|
||||||
/// mid-send can never redirect an in-flight compose to a different folder.
|
/// concurrent transport switch mid-send can never redirect an in-flight compose to
|
||||||
func composePDFForSend(outbox outboxDir: URL) async throws -> ComposedSend {
|
/// 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
|
||||||
let sourceDir = paths.sessionDirectory(workingSession.id)
|
let sourceDir = paths.sessionDirectory(workingSession.id)
|
||||||
@@ -134,14 +164,27 @@ 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)
|
||||||
@@ -152,17 +195,26 @@ extension AppModel: SendCapable {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam.
|
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam — also the
|
||||||
func handleDidShareItems(fileName: String, pageCount: Int) async {
|
/// OneDrive completion path. Composes ONE truthful status from the caller's success
|
||||||
|
/// summary (the share itself DID complete) plus, when they happened, the archive
|
||||||
|
/// error and any state-refresh problem — nothing is overwritten or hidden.
|
||||||
|
func handleDidShareItems(fileName: String, sentSummary: String) async {
|
||||||
guard !session.isEmpty else { return }
|
guard !session.isEmpty else { return }
|
||||||
|
var message = sentSummary
|
||||||
do {
|
do {
|
||||||
_ = try await spool.archiveCurrent(pdfFileName: fileName)
|
_ = try await spool.archiveCurrent(pdfFileName: fileName)
|
||||||
replaceSession(try await spool.currentSession())
|
|
||||||
let pageWord = pageCount == 1 ? "page" : "pages"
|
|
||||||
setStatus("Sent — \(pageCount) \(pageWord).")
|
|
||||||
} catch {
|
} catch {
|
||||||
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")
|
message += " \((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")"
|
||||||
}
|
}
|
||||||
|
// Refresh model state from the store on BOTH paths: after a successful archive
|
||||||
|
// the current session and the past-submissions list are stale until reloaded,
|
||||||
|
// and after a failure the store (not this model) knows whether the session
|
||||||
|
// actually moved. Any refresh problem is appended to the status, never hidden.
|
||||||
|
if let refreshProblem = await reloadFromSpool() {
|
||||||
|
message += " \(refreshProblem)"
|
||||||
|
}
|
||||||
|
setStatus(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `NSSharingServiceDelegate.sharingService(_:didFailToShareItems:error:)` seam,
|
/// `NSSharingServiceDelegate.sharingService(_:didFailToShareItems:error:)` seam,
|
||||||
|
|||||||
@@ -255,6 +255,9 @@ extension AppModel: SettingsWindowPresenting {
|
|||||||
/// the live value before every mutating step, so rapid toggling (this function or
|
/// 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
|
/// 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.
|
/// 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) {
|
func chooseTransport(_ value: SendTransport) {
|
||||||
guard !isSending else {
|
guard !isSending else {
|
||||||
setStatus("Finish the current send first.")
|
setStatus("Finish the current send first.")
|
||||||
@@ -274,7 +277,7 @@ extension AppModel: SettingsWindowPresenting {
|
|||||||
|
|
||||||
reconcileGeneration += 1
|
reconcileGeneration += 1
|
||||||
let generation = reconcileGeneration
|
let generation = reconcileGeneration
|
||||||
Task {
|
pendingReconcileTask = Task {
|
||||||
guard generation == self.reconcileGeneration else { return }
|
guard generation == self.reconcileGeneration else { return }
|
||||||
await watcher.setRecordUncommented(value == .airDrop)
|
await watcher.setRecordUncommented(value == .airDrop)
|
||||||
guard generation == self.reconcileGeneration else { return }
|
guard generation == self.reconcileGeneration else { return }
|
||||||
@@ -306,7 +309,7 @@ extension AppModel: SettingsWindowPresenting {
|
|||||||
|
|
||||||
reconcileGeneration += 1
|
reconcileGeneration += 1
|
||||||
let generation = reconcileGeneration
|
let generation = reconcileGeneration
|
||||||
Task {
|
pendingReconcileTask = Task {
|
||||||
guard generation == self.reconcileGeneration else { return }
|
guard generation == self.reconcileGeneration else { return }
|
||||||
do {
|
do {
|
||||||
try await watcher.updateWatchFolder(url)
|
try await watcher.updateWatchFolder(url)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import AppKit
|
import AppKit
|
||||||
import CryptoKit
|
import CryptoKit
|
||||||
import Foundation
|
import Foundation
|
||||||
|
import Security
|
||||||
|
|
||||||
/// 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.
|
||||||
@@ -10,22 +11,31 @@ 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?
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
let config = URLSessionConfiguration.ephemeral
|
let config = URLSessionConfiguration.ephemeral
|
||||||
config.timeoutIntervalForRequest = 15
|
config.timeoutIntervalForRequest = 30
|
||||||
config.timeoutIntervalForResource = 15
|
config.timeoutIntervalForResource = 600
|
||||||
config.httpCookieAcceptPolicy = .never
|
config.httpCookieAcceptPolicy = .never
|
||||||
config.httpShouldSetCookies = false
|
config.httpShouldSetCookies = false
|
||||||
config.httpCookieStorage = nil
|
config.httpCookieStorage = nil
|
||||||
@@ -51,10 +61,18 @@ final class UpdateChecker {
|
|||||||
repeatingTimer = timer
|
repeatingTimer = timer
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkNow() async {
|
/// Checks the appcast and stages a newer, signature-verified payload.
|
||||||
guard !isChecking else { return }
|
/// `manual` only affects the status message shown when already up to date —
|
||||||
isChecking = true
|
/// a user-initiated check says so; the silent background check stays quiet.
|
||||||
defer { isChecking = false }
|
func checkNow(manual: Bool = false) async {
|
||||||
|
guard !isCheckingNow else { return }
|
||||||
|
isCheckingNow = true
|
||||||
|
onCheckingChanged?(true)
|
||||||
|
defer {
|
||||||
|
isCheckingNow = false
|
||||||
|
onCheckingChanged?(false)
|
||||||
|
}
|
||||||
|
lastCheckedAt = Date()
|
||||||
|
|
||||||
let appcast: Appcast
|
let appcast: Appcast
|
||||||
do {
|
do {
|
||||||
@@ -67,7 +85,7 @@ final class UpdateChecker {
|
|||||||
|
|
||||||
guard Self.isNewer(appcast.version, than: Self.currentVersion()) else {
|
guard Self.isNewer(appcast.version, than: Self.currentVersion()) else {
|
||||||
clearOffer()
|
clearOffer()
|
||||||
statusMessage = nil
|
statusMessage = manual ? "Redline \(Self.currentVersion()) is up to date." : nil
|
||||||
onChecked?()
|
onChecked?()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -80,6 +98,10 @@ final class UpdateChecker {
|
|||||||
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
|
||||||
@@ -88,9 +110,9 @@ final class UpdateChecker {
|
|||||||
onChecked?()
|
onChecked?()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Copies the staged app onto `target` with ditto (in place; never deletes the old app).
|
/// Installs the staged app onto `target` atomically, keeping exactly one rollback
|
||||||
/// Relaunches unless `SHOTDECK_UPDATE_SELFTEST` is set, so the in-process self-test
|
/// copy (`Redline.app.previous`), then hands off to a relaunch and quits.
|
||||||
/// can assert the installed Info.plist without killing the process.
|
/// Never deletes the old app before the new one is verified in place.
|
||||||
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."
|
||||||
@@ -98,29 +120,118 @@ final class UpdateChecker {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let targetDir = target.deletingLastPathComponent()
|
||||||
|
let previousURL = targetDir.appendingPathComponent("Redline.app.previous")
|
||||||
|
|
||||||
do {
|
do {
|
||||||
try FileManager.default.createDirectory(
|
try FileManager.default.createDirectory(at: targetDir, withIntermediateDirectories: true)
|
||||||
at: target.deletingLastPathComponent(),
|
|
||||||
withIntermediateDirectories: true
|
let replacementDir = try FileManager.default.url(
|
||||||
|
for: .itemReplacementDirectory,
|
||||||
|
in: .userDomainMask,
|
||||||
|
appropriateFor: target,
|
||||||
|
create: true
|
||||||
)
|
)
|
||||||
try Self.runProcess(executable: "/usr/bin/ditto", arguments: [staged.path, target.path])
|
defer { try? FileManager.default.removeItem(at: replacementDir) }
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
let isSelfTest = ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|
// Defense in depth: re-verify what actually landed on disk, not just the staged copy.
|
||||||
if isSelfTest { return }
|
|
||||||
|
|
||||||
do {
|
do {
|
||||||
try Self.runProcess(executable: "/usr/bin/open", arguments: ["-n", target.path])
|
try Self.verifySignature(of: target)
|
||||||
} catch {
|
} catch {
|
||||||
statusMessage = "The update was installed but Redline could not relaunch. Open it from Applications."
|
statusMessage = "The update was installed but failed verification."
|
||||||
onChecked?()
|
onChecked?()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
NSApp.terminate(nil)
|
|
||||||
|
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 {
|
||||||
|
try Self.verifySignature(of: previousURL)
|
||||||
|
} catch {
|
||||||
|
statusMessage = "The previous version failed verification and was not restored."
|
||||||
|
onChecked?()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
|
func previousVersion(target: URL = UpdateChecker.defaultInstallTarget) -> String? {
|
||||||
|
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 {
|
||||||
@@ -156,6 +267,67 @@ 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 {
|
||||||
@@ -170,6 +342,7 @@ 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 {
|
||||||
@@ -219,6 +392,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +409,35 @@ 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")
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil {
|
|||||||
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" {
|
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" {
|
||||||
MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() }
|
MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() }
|
||||||
}
|
}
|
||||||
|
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" {
|
||||||
|
MainActor.assumeIsolated { PickerSelfTest.runSendTruthOnlyIfRequested() }
|
||||||
|
}
|
||||||
if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil {
|
if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil {
|
||||||
MainActor.assumeIsolated { PickerSelfTest.runIfRequested() }
|
MainActor.assumeIsolated { PickerSelfTest.runIfRequested() }
|
||||||
}
|
}
|
||||||
@@ -24,8 +27,9 @@ 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) {
|
||||||
Image(systemName: state.symbolName)
|
menuBarIcon(for: state, hasUpdate: hasUpdate)
|
||||||
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))
|
||||||
}
|
}
|
||||||
@@ -36,6 +40,29 @@ 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
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import Foundation
|
|||||||
|
|
||||||
public enum SessionState: String, Codable, Sendable {
|
public enum SessionState: String, Codable, Sendable {
|
||||||
case open // accepting captures
|
case open // accepting captures
|
||||||
case archived // its PDF has been built and sent; kept forever, never deleted
|
case archived // closed and kept as a past session (sent or not); pruned by retention
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The manifest persisted as session.json alongside the PNGs.
|
/// The manifest persisted as session.json alongside the PNGs.
|
||||||
@@ -11,7 +11,9 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
|||||||
public let createdAt: Date
|
public let createdAt: Date
|
||||||
public private(set) var state: SessionState
|
public private(set) var state: SessionState
|
||||||
public private(set) var captures: [Capture]
|
public private(set) var captures: [Capture]
|
||||||
/// Set when the PDF is built, so a re-send reuses the same file.
|
/// Set when the PDF is built, so a re-send reuses the same file. nil on a
|
||||||
|
/// session that was closed without ever sending — the Past submissions list
|
||||||
|
/// shows that as "Not sent".
|
||||||
public private(set) var pdfFileName: String?
|
public private(set) var pdfFileName: String?
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
@@ -61,7 +63,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Value-semantic: returns a new session; does not mutate `self`.
|
/// Value-semantic: returns a new session; does not mutate `self`.
|
||||||
public func markArchived(pdfFileName: String) -> CaptureSession {
|
/// `pdfFileName` is nil when the session is closed without ever sending.
|
||||||
|
public func markArchived(pdfFileName: String?) -> CaptureSession {
|
||||||
CaptureSession(
|
CaptureSession(
|
||||||
id: id,
|
id: id,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
|
|||||||
@@ -17,6 +17,15 @@ public actor ReturnWatcher {
|
|||||||
/// A document that IS commented is always recorded, regardless of this flag.
|
/// A document that IS commented is always recorded, regardless of this flag.
|
||||||
public var recordUncommented: Bool = true
|
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;
|
||||||
/// `updateWatchFolder` is invoked by the UI layer only.
|
/// `updateWatchFolder` is invoked by the UI layer only.
|
||||||
|
|||||||
@@ -4,6 +4,13 @@ import CoreGraphics
|
|||||||
import Darwin
|
import Darwin
|
||||||
|
|
||||||
public actor SpoolStore {
|
public actor SpoolStore {
|
||||||
|
/// How many archived sessions (past submissions) are kept on disk. Ben's
|
||||||
|
/// retention rule (2026-10-11): "by default, retain the past 10 sessions" —
|
||||||
|
/// older session folders are removed from `archive/` once this is exceeded.
|
||||||
|
/// Any PDF a pruned session produced is not touched: it lives in the outbox
|
||||||
|
/// (or the OneDrive folder) it was sent to.
|
||||||
|
public static let defaultRetainedSessionCount = 10
|
||||||
|
|
||||||
private let paths: AppSupportPaths
|
private let paths: AppSupportPaths
|
||||||
private var openSession: CaptureSession
|
private var openSession: CaptureSession
|
||||||
|
|
||||||
@@ -28,9 +35,28 @@ public actor SpoolStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The session currently accepting captures. Cheap accessor — all reconciliation already
|
/// The session currently accepting captures. Cheap accessor — all reconciliation already
|
||||||
/// happened once, inside init.
|
/// happened once, inside init. A truth guard: if the stored session is no longer really
|
||||||
|
/// open on disk (its directory was archived away and the replacement session could not
|
||||||
|
/// be created — e.g. disk full), a fresh session is minted, or the call fails loudly.
|
||||||
|
/// It never returns an already-archived session as the open one.
|
||||||
public func currentSession() throws -> CaptureSession {
|
public func currentSession() throws -> CaptureSession {
|
||||||
openSession
|
try ensureOpenSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mint-or-verify the open session: returns the session that is REALLY open on disk,
|
||||||
|
/// creating a fresh one when the stored one is stale (archived away mid-run). Throws
|
||||||
|
/// loudly when no new session can be created either — never substitutes a lie.
|
||||||
|
private func ensureOpenSession() throws -> CaptureSession {
|
||||||
|
let dir = paths.sessionDirectory(openSession.id)
|
||||||
|
if openSession.state == .open && FileManager.default.fileExists(atPath: dir.path) {
|
||||||
|
return openSession
|
||||||
|
}
|
||||||
|
let staleID = openSession.id.uuidString
|
||||||
|
Log.spool.error(
|
||||||
|
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
|
||||||
|
let fresh = try Self.createFreshSession(paths: paths)
|
||||||
|
openSession = fresh
|
||||||
|
return fresh
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
|
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
|
||||||
@@ -40,32 +66,38 @@ public actor SpoolStore {
|
|||||||
pngData: Data, pixelWidth: Int, pixelHeight: Int,
|
pngData: Data, pixelWidth: Int, pixelHeight: Int,
|
||||||
scale: CGFloat, capturedAt: Date
|
scale: CGFloat, capturedAt: Date
|
||||||
) throws -> Capture {
|
) throws -> Capture {
|
||||||
|
let open = try ensureOpenSession()
|
||||||
let captureID = UUID()
|
let captureID = UUID()
|
||||||
let sequence = openSession.nextSequence
|
let sequence = open.nextSequence
|
||||||
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
|
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
|
||||||
let sessionDir = paths.sessionDirectory(openSession.id)
|
let sessionDir = paths.sessionDirectory(open.id)
|
||||||
let fileURL = sessionDir.appendingPathComponent(fileName)
|
let fileURL = sessionDir.appendingPathComponent(fileName)
|
||||||
try AtomicFile.write(pngData, to: fileURL)
|
try AtomicFile.write(pngData, to: fileURL)
|
||||||
let capture = Capture(
|
let capture = Capture(
|
||||||
id: captureID, sequence: sequence, fileName: fileName,
|
id: captureID, sequence: sequence, fileName: fileName,
|
||||||
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
|
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
|
||||||
scale: scale, capturedAt: capturedAt)
|
scale: scale, capturedAt: capturedAt)
|
||||||
let updated = openSession.appending(capture)
|
let updated = open.appending(capture)
|
||||||
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
|
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
|
||||||
openSession = updated
|
openSession = updated
|
||||||
return capture
|
return capture
|
||||||
}
|
}
|
||||||
|
|
||||||
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
|
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
|
||||||
/// its manifest entry. NEVER unlinks/deletes a user PNG. Throws (no filesystem change) if
|
/// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
|
||||||
/// `captureID` is not present in the open session.
|
/// filesystem change) if `captureID` is not present in the open session.
|
||||||
|
/// (Session retention is the one place that removes files: when a session falls
|
||||||
|
/// outside the newest `defaultRetainedSessionCount`, its WHOLE folder — including
|
||||||
|
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
|
||||||
|
/// not this remove path.)
|
||||||
public func remove(captureID: UUID) throws -> CaptureSession {
|
public func remove(captureID: UUID) throws -> CaptureSession {
|
||||||
guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
|
let open = try ensureOpenSession()
|
||||||
|
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
|
||||||
throw ShotdeckError.spoolWriteFailed(
|
throw ShotdeckError.spoolWriteFailed(
|
||||||
path: paths.sessionDirectory(openSession.id).path,
|
path: paths.sessionDirectory(open.id).path,
|
||||||
underlying: "capture \(captureID) is not in the open session")
|
underlying: "capture \(captureID) is not in the open session")
|
||||||
}
|
}
|
||||||
let sessionDir = paths.sessionDirectory(openSession.id)
|
let sessionDir = paths.sessionDirectory(open.id)
|
||||||
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
|
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
|
||||||
do {
|
do {
|
||||||
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
|
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
|
||||||
@@ -87,35 +119,110 @@ public actor SpoolStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Closes the open session (must be non-empty), moves its directory under archive/, records
|
/// Closes the open session (must be non-empty), moves its directory under archive/, records
|
||||||
/// pdfFileName, and starts a fresh empty open session. Returns the archived one.
|
/// pdfFileName, starts a fresh empty open session, and applies session retention.
|
||||||
|
/// Returns the archived one.
|
||||||
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
|
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
|
||||||
guard !openSession.isEmpty else {
|
let open = try ensureOpenSession()
|
||||||
|
guard !open.isEmpty else {
|
||||||
throw ShotdeckError.spoolWriteFailed(
|
throw ShotdeckError.spoolWriteFailed(
|
||||||
path: paths.sessionDirectory(openSession.id).path,
|
path: paths.sessionDirectory(open.id).path,
|
||||||
underlying: "cannot archive an empty session")
|
underlying: "cannot archive an empty session")
|
||||||
}
|
}
|
||||||
let archived = openSession.markArchived(pdfFileName: pdfFileName)
|
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
|
||||||
let sessionDir = paths.sessionDirectory(openSession.id)
|
openSession = try Self.createFreshSession(paths: paths)
|
||||||
|
applyRetention()
|
||||||
|
return archived
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes the open session — sent or not — and keeps its captures as a past
|
||||||
|
/// session under archive/, then starts a fresh empty open session. Unlike
|
||||||
|
/// `archiveCurrent(pdfFileName:)` this never requires a PDF: the archived session
|
||||||
|
/// keeps whatever pdfFileName it already has (nil when it was never sent, which
|
||||||
|
/// the Past submissions list shows as "Not sent"). An empty open session is
|
||||||
|
/// simply replaced — there is nothing to keep. Returns the archived session, or
|
||||||
|
/// nil when the open session was empty.
|
||||||
|
public func closeCurrentSession() throws -> CaptureSession? {
|
||||||
|
let open = try ensureOpenSession()
|
||||||
|
guard !open.isEmpty else {
|
||||||
|
openSession = try Self.createFreshSession(paths: paths)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
let archived = try moveOpenSessionToArchive(
|
||||||
|
open.markArchived(pdfFileName: open.pdfFileName))
|
||||||
|
openSession = try Self.createFreshSession(paths: paths)
|
||||||
|
applyRetention()
|
||||||
|
return archived
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the newest `limit` archived sessions and removes the rest of the session
|
||||||
|
/// folders from archive/ (the single folder all sessions live in). Returns the
|
||||||
|
/// removed ids. Only UUID session folders directly under archive/ are ever
|
||||||
|
/// touched — never spool/, never anything else. This is the requested retention
|
||||||
|
/// policy (Ben, 2026-10-11: "retain the past 10 sessions"): a session folder
|
||||||
|
/// dropped here is gone for good, while any PDF it produced stays in the
|
||||||
|
/// outbox/OneDrive folder it was sent to.
|
||||||
|
public func pruneArchivedSessions(keeping limit: Int) throws -> [UUID] {
|
||||||
|
let sessions = try archivedSessions()
|
||||||
|
guard sessions.count > limit else { return [] }
|
||||||
|
var removed: [UUID] = []
|
||||||
|
for session in sessions.dropFirst(limit) {
|
||||||
|
let dir = paths.archiveDirectory(session.id)
|
||||||
|
do {
|
||||||
|
try FileManager.default.removeItem(at: dir)
|
||||||
|
} catch {
|
||||||
|
throw ShotdeckError.spoolWriteFailed(
|
||||||
|
path: dir.path,
|
||||||
|
underlying: "could not remove an expired session: \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
removed.append(session.id)
|
||||||
|
}
|
||||||
|
try AtomicFile.fsyncDirectory(at: paths.archive)
|
||||||
|
return removed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The retention policy every archive path funnels through, so it can never be
|
||||||
|
/// forgotten: sessions over the default count are pruned. A retention failure is
|
||||||
|
/// logged loudly (with the exact path) and never thrown — the archive it follows
|
||||||
|
/// already succeeded, and converting a completed send into a reported failure
|
||||||
|
/// would be a lie (the safe direction of a failed prune is keeping too much, never
|
||||||
|
/// losing data). The visible symptom of a failed prune is simply more than 10
|
||||||
|
/// sessions in the Past submissions list.
|
||||||
|
private func applyRetention() {
|
||||||
|
do {
|
||||||
|
let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount)
|
||||||
|
if !removed.isEmpty {
|
||||||
|
Log.spool.warning(
|
||||||
|
"Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
Log.spool.error(
|
||||||
|
"Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the archived manifest, then renames the whole session directory from
|
||||||
|
/// spool/ into archive/ in one atomic operation.
|
||||||
|
private func moveOpenSessionToArchive(_ archived: CaptureSession) throws -> CaptureSession {
|
||||||
|
let sessionDir = paths.sessionDirectory(archived.id)
|
||||||
try AtomicFile.writeJSON(archived, to: sessionDir.appendingPathComponent("session.json"))
|
try AtomicFile.writeJSON(archived, to: sessionDir.appendingPathComponent("session.json"))
|
||||||
let archiveDir = paths.archiveDirectory(openSession.id)
|
let archiveDir = paths.archiveDirectory(archived.id)
|
||||||
guard rename(sessionDir.path, archiveDir.path) == 0 else {
|
guard rename(sessionDir.path, archiveDir.path) == 0 else {
|
||||||
throw ShotdeckError.spoolWriteFailed(
|
throw ShotdeckError.spoolWriteFailed(
|
||||||
path: sessionDir.path,
|
path: sessionDir.path,
|
||||||
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
|
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
|
||||||
}
|
}
|
||||||
try AtomicFile.fsyncDirectory(at: paths.archive)
|
try AtomicFile.fsyncDirectory(at: paths.archive)
|
||||||
let fresh = try Self.createFreshSession(paths: paths)
|
|
||||||
openSession = fresh
|
|
||||||
return archived
|
return archived
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
|
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
|
||||||
/// with no filesystem change, if the open session has captures.
|
/// with no filesystem change, if the open session has captures.
|
||||||
public func startNewSession() throws -> CaptureSession {
|
public func startNewSession() throws -> CaptureSession {
|
||||||
guard openSession.isEmpty else {
|
let open = try ensureOpenSession()
|
||||||
|
guard open.isEmpty else {
|
||||||
throw ShotdeckError.spoolWriteFailed(
|
throw ShotdeckError.spoolWriteFailed(
|
||||||
path: paths.sessionDirectory(openSession.id).path,
|
path: paths.sessionDirectory(open.id).path,
|
||||||
underlying: "cannot start a new session: \(openSession.captures.count) capture(s) present in the open session")
|
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
|
||||||
}
|
}
|
||||||
let fresh = try Self.createFreshSession(paths: paths)
|
let fresh = try Self.createFreshSession(paths: paths)
|
||||||
openSession = fresh
|
openSession = fresh
|
||||||
@@ -129,19 +236,44 @@ public actor SpoolStore {
|
|||||||
return dir.appendingPathComponent(capture.fileName)
|
return dir.appendingPathComponent(capture.fileName)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Archived sessions, newest createdAt first. Lazily reconciles each archive/ directory
|
/// Archived sessions, newest first. Lazily reconciles each archive/ directory
|
||||||
/// the same way init reconciles spool/ candidates (orphan recovery, missing-drop, corrupt
|
/// the same way init reconciles spool/ candidates (orphan recovery, missing-drop, corrupt
|
||||||
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
|
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
|
||||||
/// ever losing a PNG.
|
/// ever losing a PNG.
|
||||||
|
///
|
||||||
|
/// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is
|
||||||
|
/// pinned in AtomicFileTests), then the session folder's creation date and content
|
||||||
|
/// modification date to break ties at real resolution (two sessions closed in the
|
||||||
|
/// same second would otherwise order, and therefore prune, arbitrarily by UUID —
|
||||||
|
/// and on a volume that reports no creation date the modification date still keeps
|
||||||
|
/// retention on real order), then the id as the final deterministic tie-break.
|
||||||
|
/// The folder dates are tie-break refinements only — the manifest `createdAt` stays
|
||||||
|
/// the authoritative timestamp; if a volume reports neither date the tie-break
|
||||||
|
/// degrades to the id.
|
||||||
public func archivedSessions() throws -> [CaptureSession] {
|
public func archivedSessions() throws -> [CaptureSession] {
|
||||||
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
|
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
|
||||||
var sessions: [CaptureSession] = []
|
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
|
||||||
for id in ids {
|
for id in ids {
|
||||||
sessions.append(
|
let dir = paths.archiveDirectory(id)
|
||||||
try Self.reconcileSessionDirectory(
|
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
|
||||||
at: paths.archiveDirectory(id), id: id, assumedStateIfRebuilt: .archived, fileManager: .default))
|
// session.json and bump the folder's modification date to "now", which
|
||||||
|
// would let a healed older session outrank a genuinely newer same-second
|
||||||
|
// peer in the tie-break below.
|
||||||
|
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
|
||||||
|
let session = try Self.reconcileSessionDirectory(
|
||||||
|
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
|
||||||
|
// The manifest `createdAt` is the authoritative timestamp; the folder dates
|
||||||
|
// only refine ties between same-second sessions.
|
||||||
|
let folderCreatedAt = values?.creationDate ?? session.createdAt
|
||||||
|
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
|
||||||
|
keyed.append((session, folderCreatedAt, folderModifiedAt))
|
||||||
}
|
}
|
||||||
return sessions.sorted { ($0.createdAt, $0.id.uuidString) > ($1.createdAt, $1.id.uuidString) }
|
return keyed
|
||||||
|
.sorted { lhs, rhs in
|
||||||
|
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.folderModifiedAt, lhs.session.id.uuidString)
|
||||||
|
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
|
||||||
|
}
|
||||||
|
.map(\.session)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Reconciliation (static so they can run inside init)
|
// MARK: - Reconciliation (static so they can run inside init)
|
||||||
|
|||||||
@@ -176,4 +176,46 @@ public enum OneDriveLocator {
|
|||||||
guard exists, isDirectory.boolValue else { return false }
|
guard exists, isDirectory.boolValue else { return false }
|
||||||
return fileManager.isWritableFile(atPath: url.path)
|
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,271 @@
|
|||||||
|
import CoreGraphics
|
||||||
|
import Foundation
|
||||||
|
import ImageIO
|
||||||
|
import Testing
|
||||||
|
import ShotdeckCore
|
||||||
|
|
||||||
|
// Session lifecycle + retention (MMDB-2925): "Start new session" keeps the current
|
||||||
|
// screenshots as a past session, and the newest 10 sessions are retained in the one
|
||||||
|
// archive folder.
|
||||||
|
|
||||||
|
// MARK: - 1. closeCurrentSession keeps the captures as a past session
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func closeCurrentSessionKeepsCapturesAsAPastSessionAndStartsFresh() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
let c1 = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 8, height: 8, red: 1, green: 0, blue: 0),
|
||||||
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
||||||
|
let c2 = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 8, height: 8, red: 0, green: 1, blue: 0),
|
||||||
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
||||||
|
|
||||||
|
let closedID = try await store.currentSession().id
|
||||||
|
let archived = try #require(try await store.closeCurrentSession())
|
||||||
|
|
||||||
|
#expect(archived.id == closedID)
|
||||||
|
#expect(archived.state == .archived)
|
||||||
|
#expect(archived.pdfFileName == nil) // never sent — shown as "Not sent"
|
||||||
|
#expect(archived.captures.map(\.id) == [c1.id, c2.id])
|
||||||
|
|
||||||
|
// Nothing is deleted: both PNGs live on under archive/<id>/.
|
||||||
|
let archiveDir = paths.archiveDirectory(closedID)
|
||||||
|
for capture in archived.captures {
|
||||||
|
#expect(FileManager.default.fileExists(
|
||||||
|
atPath: archiveDir.appendingPathComponent(capture.fileName).path))
|
||||||
|
}
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: paths.sessionDirectory(closedID).path))
|
||||||
|
|
||||||
|
let fresh = try await store.currentSession()
|
||||||
|
#expect(fresh.id != closedID)
|
||||||
|
#expect(fresh.state == .open)
|
||||||
|
#expect(fresh.isEmpty)
|
||||||
|
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.map(\.id) == [closedID])
|
||||||
|
#expect(past.first?.captures.count == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 2. closeCurrentSession on an empty open session just starts fresh
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func closeCurrentSessionOnAnEmptyOpenSessionStartsFreshWithoutArchiving() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
let before = try await store.currentSession().id
|
||||||
|
|
||||||
|
let archived = try await store.closeCurrentSession()
|
||||||
|
#expect(archived == nil)
|
||||||
|
|
||||||
|
let after = try await store.currentSession()
|
||||||
|
#expect(after.id != before)
|
||||||
|
#expect(after.isEmpty)
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 3. sent and unsent sessions are distinguishable in the past list
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func pastSessionsDistinguishSentFromUnsentByPDFFileName() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 6, height: 6, red: 1, green: 0, blue: 0),
|
||||||
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
||||||
|
let sent = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120000.pdf")
|
||||||
|
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 6, height: 6, red: 0, green: 0, blue: 1),
|
||||||
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
||||||
|
let closed = try #require(try await store.closeCurrentSession())
|
||||||
|
|
||||||
|
#expect(sent.pdfFileName == "Redline-20261011-120000.pdf")
|
||||||
|
#expect(closed.pdfFileName == nil)
|
||||||
|
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.map(\.id) == [closed.id, sent.id]) // newest first
|
||||||
|
#expect(past.map(\.pdfFileName) == [nil, "Redline-20261011-120000.pdf"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 4. retention keeps the newest 10 sessions, in the one archive folder
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
var closedIDs: [UUID] = []
|
||||||
|
for index in 0..<12 {
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 4, height: 4, red: 0.1, green: 0.1, blue: 0.1),
|
||||||
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
|
||||||
|
capturedAt: Date(timeIntervalSince1970: 1_700_000_000 + Double(index)))
|
||||||
|
let closed = try #require(try await store.closeCurrentSession())
|
||||||
|
closedIDs.append(closed.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// All 12 sessions live in the single archive/ folder as UUID session folders.
|
||||||
|
let fm = FileManager.default
|
||||||
|
let entries = try fm.contentsOfDirectory(at: paths.archive, includingPropertiesForKeys: nil)
|
||||||
|
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
|
||||||
|
#expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
|
||||||
|
let kept = try await store.archivedSessions().map(\.id)
|
||||||
|
#expect(kept == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
||||||
|
|
||||||
|
// The two oldest sessions are gone; the newest ten are fully on disk.
|
||||||
|
for id in closedIDs.prefix(2) {
|
||||||
|
#expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path))
|
||||||
|
}
|
||||||
|
for id in closedIDs.suffix(SpoolStore.defaultRetainedSessionCount) {
|
||||||
|
#expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The open session is never touched by retention.
|
||||||
|
let open = try await store.currentSession()
|
||||||
|
#expect(open.state == .open)
|
||||||
|
#expect(open.isEmpty)
|
||||||
|
#expect(fm.fileExists(atPath: paths.sessionDirectory(open.id).path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 5. explicit prune keeps exactly the requested count
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func pruneArchivedSessionsKeepingNRemovesExactlyTheOldest() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
var closedIDs: [UUID] = []
|
||||||
|
for _ in 0..<4 {
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 4, height: 4, red: 0.2, green: 0.2, blue: 0.2),
|
||||||
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date())
|
||||||
|
closedIDs.append(try #require(try await store.closeCurrentSession()).id)
|
||||||
|
}
|
||||||
|
|
||||||
|
let removed = try await store.pruneArchivedSessions(keeping: 2)
|
||||||
|
#expect(removed == Array(closedIDs.prefix(2).reversed())) // newest-first walk order
|
||||||
|
let kept = try await store.archivedSessions().map(\.id)
|
||||||
|
#expect(kept == Array(closedIDs.suffix(2).reversed()))
|
||||||
|
|
||||||
|
// Idempotent: nothing left to prune at that limit.
|
||||||
|
let removedAgain = try await store.pruneArchivedSessions(keeping: 2)
|
||||||
|
#expect(removedAgain.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 6. retention runs on the send path too
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func theSendArchivePathAppliesRetention() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
var sentIDs: [UUID] = []
|
||||||
|
for index in 0..<(SpoolStore.defaultRetainedSessionCount + 3) {
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 4, height: 4, red: 0.3, green: 0.3, blue: 0.3),
|
||||||
|
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
|
||||||
|
capturedAt: Date(timeIntervalSince1970: 1_700_100_000 + Double(index)))
|
||||||
|
let archived = try await store.archiveCurrent(pdfFileName: "Redline-\(index).pdf")
|
||||||
|
sentIDs.append(archived.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
let kept = try await store.archivedSessions()
|
||||||
|
#expect(kept.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
#expect(kept.map(\.id) == Array(sentIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
||||||
|
#expect(kept.allSatisfy { $0.pdfFileName != nil })
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - 7. a stale open session is never returned as current (truth guard)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func aStaleOpenSessionIsNeverReturnedAsCurrent() async throws {
|
||||||
|
let (root, paths) = try makeIsolatedPaths()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
|
||||||
|
let store = try SpoolStore(paths: paths)
|
||||||
|
_ = try await store.append(
|
||||||
|
pngData: try makePNGData(width: 6, height: 6, red: 0.7, green: 0.7, blue: 0.1),
|
||||||
|
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
|
||||||
|
let archived = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120200.pdf")
|
||||||
|
|
||||||
|
// Simulate the mid-run failure the truth guard exists for: the archived session
|
||||||
|
// moved away and the replacement open session's folder is gone (e.g. the fresh
|
||||||
|
// session could not be created / survive). The store must mint a real fresh
|
||||||
|
// session — never report the already-archived one as open.
|
||||||
|
let fresh = try await store.currentSession()
|
||||||
|
try FileManager.default.removeItem(at: paths.sessionDirectory(fresh.id))
|
||||||
|
|
||||||
|
let recovered = try await store.currentSession()
|
||||||
|
#expect(recovered.id != fresh.id)
|
||||||
|
#expect(recovered.id != archived.id)
|
||||||
|
#expect(recovered.state == .open)
|
||||||
|
#expect(recovered.isEmpty)
|
||||||
|
let past = try await store.archivedSessions()
|
||||||
|
#expect(past.map(\.id) == [archived.id])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Fixtures
|
||||||
|
|
||||||
|
private enum FixtureError: Error {
|
||||||
|
case pngGenerationFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeIsolatedPaths() throws -> (root: URL, paths: AppSupportPaths) {
|
||||||
|
let root = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-retention-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
let paths = try AppSupportPaths(
|
||||||
|
root: root,
|
||||||
|
outbox: root.appendingPathComponent("outbox", isDirectory: true),
|
||||||
|
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
|
||||||
|
)
|
||||||
|
return (root, paths)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makePNGData(
|
||||||
|
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 FixtureError.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 FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
let data = NSMutableData()
|
||||||
|
guard let destination = CGImageDestinationCreateWithData(
|
||||||
|
data, "public.png" as CFString, 1, nil
|
||||||
|
) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
CGImageDestinationAddImage(destination, image, nil)
|
||||||
|
guard CGImageDestinationFinalize(destination) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
return data as Data
|
||||||
|
}
|
||||||
@@ -122,6 +122,87 @@ func isWritableDirectoryFalseForAPlainFileAndForANonexistentPath() throws {
|
|||||||
#expect(!OneDriveLocator.isWritableDirectory(at: dir.appendingPathComponent("does-not-exist")))
|
#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 {
|
struct TransportDefaultsSuite {
|
||||||
let name: String
|
let name: String
|
||||||
let defaults: UserDefaults
|
let defaults: UserDefaults
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
import AppKit
|
||||||
|
import CoreGraphics
|
||||||
|
import Foundation
|
||||||
|
import ImageIO
|
||||||
|
import Testing
|
||||||
|
import ShotdeckCore
|
||||||
|
@testable import Shotdeck
|
||||||
|
|
||||||
|
/// MMDB-2925, through the REAL app-target seams the menu rows invoke (`AppModel`
|
||||||
|
/// actions + `SpoolStore`): "Start new session" keeps the current screenshots as a
|
||||||
|
/// past session, the Past submissions state reflects what was sent, and session
|
||||||
|
/// retention keeps the newest 10 sessions in the one archive folder. `bootstrap()`
|
||||||
|
/// itself is covered by LaunchWiringTests; here `addCapture` refreshes the session
|
||||||
|
/// from the store exactly the way `AppModel.captureNow()` does after a real capture.
|
||||||
|
@MainActor
|
||||||
|
@Test("Menu actions: start new session keeps captures, lists past submissions, retains 10")
|
||||||
|
func startNewSessionKeepsCapturesListsPastSubmissionsAndRetainsTen() async throws {
|
||||||
|
let fm = FileManager.default
|
||||||
|
let root = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
|
||||||
|
|
||||||
|
// Two captures in the open session, then the menu's "Start new session".
|
||||||
|
let c1 = try await addCapture(to: model, red: 1, green: 0, blue: 0)
|
||||||
|
let c2 = try await addCapture(to: model, red: 0, green: 1, blue: 0)
|
||||||
|
let closedID = model.session.id
|
||||||
|
#expect(model.canStartNewSession)
|
||||||
|
|
||||||
|
await model.startNewSession()
|
||||||
|
|
||||||
|
// The fresh session is active and the captures are kept as a past session.
|
||||||
|
#expect(model.session.id != closedID)
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
#expect(!model.canStartNewSession)
|
||||||
|
#expect(model.pastSessions.map(\.id) == [closedID])
|
||||||
|
#expect(model.pastSessions.first?.captures.map(\.id) == [c1.id, c2.id])
|
||||||
|
#expect(model.pastSessions.first?.pdfFileName == nil) // never sent
|
||||||
|
#expect(model.statusLine?.contains("kept as a past session") == true)
|
||||||
|
|
||||||
|
// Nothing was deleted on close: both PNGs live in the single archive folder.
|
||||||
|
let archiveDir = model.paths.archiveDirectory(closedID)
|
||||||
|
for capture in [c1, c2] {
|
||||||
|
#expect(fm.fileExists(atPath: archiveDir.appendingPathComponent(capture.fileName).path))
|
||||||
|
}
|
||||||
|
|
||||||
|
// "PDF" on a never-sent row: visible missing state, no silent substitute.
|
||||||
|
#expect(model.sentPDFURL(for: model.pastSessions[0]) == nil)
|
||||||
|
model.revealSentPDF(model.pastSessions[0])
|
||||||
|
#expect(model.statusLine == "That session was never sent.")
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("Retention: 12 sessions through the menu action leave the newest 10 on disk")
|
||||||
|
func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() async throws {
|
||||||
|
let fm = FileManager.default
|
||||||
|
let root = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
|
||||||
|
|
||||||
|
var closedIDs: [UUID] = []
|
||||||
|
for _ in 0..<12 {
|
||||||
|
_ = try await addCapture(to: model, red: 0.2, green: 0.2, blue: 0.2)
|
||||||
|
closedIDs.append(model.session.id)
|
||||||
|
await model.startNewSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
#expect(model.pastSessions.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
#expect(model.pastSessions.map(\.id)
|
||||||
|
== Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed()))
|
||||||
|
|
||||||
|
let entries = try fm.contentsOfDirectory(at: model.paths.archive, includingPropertiesForKeys: nil)
|
||||||
|
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
|
||||||
|
#expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount)
|
||||||
|
for id in closedIDs.prefix(2) {
|
||||||
|
#expect(!fm.fileExists(atPath: model.paths.archiveDirectory(id).path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("Menu action on an empty session reports it started without inventing a past session")
|
||||||
|
func startNewSessionOnEmptySessionCreatesNoPastSession() async throws {
|
||||||
|
let fm = FileManager.default
|
||||||
|
let root = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
|
||||||
|
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
await model.startNewSession()
|
||||||
|
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
#expect(model.pastSessions.isEmpty)
|
||||||
|
#expect(model.statusLine == "New session started.")
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("Send seam refreshes past submissions after archiving (menu count stays true)")
|
||||||
|
func successfulSendRefreshesPastSubmissions() async throws {
|
||||||
|
let fm = FileManager.default
|
||||||
|
let root = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
|
||||||
|
|
||||||
|
_ = try await addCapture(to: model, red: 0.4, green: 0.4, blue: 0.4)
|
||||||
|
await model.handleDidShareItems(
|
||||||
|
fileName: "Redline-20261011-120000.pdf", sentSummary: "Sent — 1 page.")
|
||||||
|
|
||||||
|
#expect(model.statusLine == "Sent — 1 page.")
|
||||||
|
#expect(model.session.isEmpty)
|
||||||
|
#expect(model.pastSessions.count == 1)
|
||||||
|
#expect(model.pastSessions.first?.pdfFileName == "Redline-20261011-120000.pdf")
|
||||||
|
#expect(model.pastSessions.first?.captures.count == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("Start new session and send refuse to overlap (no mid-flight session close)")
|
||||||
|
func sessionStartAndSendRefuseToOverlap() async throws {
|
||||||
|
let fm = FileManager.default
|
||||||
|
let root = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
|
||||||
|
|
||||||
|
let capture = try await addCapture(to: model, red: 0.1, green: 0.1, blue: 0.1)
|
||||||
|
let before = model.session.id
|
||||||
|
|
||||||
|
// A send in flight: "Start new session" must refuse instead of renaming the
|
||||||
|
// session directory out from under the compose.
|
||||||
|
model.setSending(true)
|
||||||
|
await model.startNewSession()
|
||||||
|
#expect(model.session.id == before)
|
||||||
|
#expect(model.session.captures.map(\.id) == [capture.id])
|
||||||
|
#expect(model.statusLine == "Finish the current send first.")
|
||||||
|
model.setSending(false)
|
||||||
|
|
||||||
|
// A session start in flight: send must refuse before composing anything.
|
||||||
|
model.setStartingNewSession(true)
|
||||||
|
await model.send(anchor: nil)
|
||||||
|
#expect(model.statusLine == "Finish starting the new session first.")
|
||||||
|
#expect(model.session.id == before)
|
||||||
|
#expect(model.session.captures.map(\.id) == [capture.id])
|
||||||
|
model.setStartingNewSession(false)
|
||||||
|
|
||||||
|
// Both settled: the normal path still works.
|
||||||
|
await model.startNewSession()
|
||||||
|
#expect(model.session.id != before)
|
||||||
|
#expect(model.pastSessions.count == 1)
|
||||||
|
#expect(model.pastSessions.first?.captures.map(\.id) == [capture.id])
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("The OneDrive send summary survives archiving (never overwritten by the archive path)")
|
||||||
|
func oneDriveSendSummarySurvivesArchiving() async throws {
|
||||||
|
let fm = FileManager.default
|
||||||
|
let root = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
|
||||||
|
|
||||||
|
_ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2)
|
||||||
|
let summary = "Saved to OneDrive — 1 page. Open it in Files on your iPad."
|
||||||
|
await model.handleDidShareItems(fileName: "Redline-20261011-120100.pdf", sentSummary: summary)
|
||||||
|
|
||||||
|
#expect(model.statusLine == summary)
|
||||||
|
#expect(model.pastSessions.count == 1)
|
||||||
|
#expect(model.pastSessions.first?.pdfFileName == "Redline-20261011-120100.pdf")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Fixtures
|
||||||
|
|
||||||
|
/// Appends one generated PNG through the store and refreshes `model.session` from
|
||||||
|
/// it — the same refresh `AppModel.captureNow()` performs after a real capture.
|
||||||
|
@MainActor
|
||||||
|
private func addCapture(
|
||||||
|
to model: AppModel,
|
||||||
|
red: CGFloat,
|
||||||
|
green: CGFloat,
|
||||||
|
blue: CGFloat
|
||||||
|
) async throws -> Capture {
|
||||||
|
let capture = try await model.spool.append(
|
||||||
|
pngData: try makePNGData(width: 8, height: 8, red: red, green: green, blue: blue),
|
||||||
|
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
|
||||||
|
model.replaceSession(try await model.spool.currentSession())
|
||||||
|
return capture
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum FixtureError: Error {
|
||||||
|
case pngGenerationFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makePNGData(
|
||||||
|
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 FixtureError.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 FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
let buffer = NSMutableData()
|
||||||
|
guard let destination = CGImageDestinationCreateWithData(buffer, "public.png" as CFString, 1, nil) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
CGImageDestinationAddImage(destination, image, nil)
|
||||||
|
guard CGImageDestinationFinalize(destination) else {
|
||||||
|
throw FixtureError.pngGenerationFailed
|
||||||
|
}
|
||||||
|
return buffer as Data
|
||||||
|
}
|
||||||
+198
-16
@@ -13,7 +13,10 @@ 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"
|
||||||
SIGN_IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
|
BUNDLE_ID="ai.flowmaster.shotdeck"
|
||||||
|
# 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
|
||||||
@@ -72,6 +75,7 @@ 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}"
|
||||||
@@ -139,6 +143,38 @@ 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() {
|
||||||
@@ -167,31 +203,85 @@ 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 "${ROOT}/.build/Redline.app" ]]; then
|
if [[ ! -d "${APP_BUNDLE}" ]]; then
|
||||||
echo "Signed app missing at ${ROOT}/.build/Redline.app" >&2
|
echo "Signed app missing at ${APP_BUNDLE}" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "==> Zipping Redline.app -> ${ZIP_PATH}"
|
# build-app.sh always signs with its own hardcoded Apple Development identity
|
||||||
mkdir -p "${ROOT}/.build"
|
# 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"
|
cd "${ROOT}/.build"
|
||||||
rm -f "${ZIP_NAME}"
|
rm -f "${ZIP_NAME}"
|
||||||
ditto -c -k --keepParent Redline.app "${ZIP_NAME}"
|
ditto -c -k --keepParent Redline.app "${ZIP_NAME}"
|
||||||
)
|
)
|
||||||
|
if [[ ! -s "${ZIP_PATH}" ]]; then
|
||||||
if [[ ! -s "${ZIP_PATH}" ]]; then
|
|
||||||
echo "Zip was not created at ${ZIP_PATH}" >&2
|
echo "Zip was not created at ${ZIP_PATH}" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
echo "==> Building manual installer DMG"
|
# Rebuilds the manual-installer DMG from whatever is currently at
|
||||||
run_signed ./scripts/make-dmg.sh
|
# ${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"
|
||||||
|
|
||||||
if [[ ! -s "${DMG_PATH}" ]]; then
|
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
|
echo "DMG was not created at ${DMG_PATH}" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==> Zipping Redline.app -> ${ZIP_PATH}"
|
||||||
|
build_zip
|
||||||
|
|
||||||
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}")"
|
||||||
@@ -200,18 +290,102 @@ 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}" <<'PY'
|
python3 - "${VERSION}" "${ZIP_URL}" "${SHA256}" "${NOTES}" "${PUBDATE}" "${APPCAST_PATH}" "${NOTARIZED}" "${TEAM_IDENTIFIER}" <<'PY'
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
version, zip_url, sha256, notes, pub_date, out_path = sys.argv[1:]
|
version, zip_url, sha256, notes, pub_date, out_path, notarized, team_identifier = 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)
|
||||||
@@ -280,6 +454,14 @@ fi
|
|||||||
|
|
||||||
echo
|
echo
|
||||||
echo "Published v${VERSION}"
|
echo "Published v${VERSION}"
|
||||||
|
echo " identity: ${SIGN_IDENTITY}"
|
||||||
|
if [[ "${NOTARIZED}" -eq 1 ]]; then
|
||||||
|
echo " notarized: yes"
|
||||||
|
else
|
||||||
|
echo " notarized: no"
|
||||||
|
fi
|
||||||
|
echo " spctl: ${SPCTL_OUTPUT}"
|
||||||
|
echo " team: ${TEAM_IDENTIFIER}"
|
||||||
echo " appcast: ${APPCAST_URL}"
|
echo " appcast: ${APPCAST_URL}"
|
||||||
echo " zip: ${ZIP_URL}"
|
echo " zip: ${ZIP_URL}"
|
||||||
echo " sha256: ${SHA256}"
|
echo " sha256: ${SHA256}"
|
||||||
|
|||||||
Reference in New Issue
Block a user