Merge pull request 'Redline: OneDrive folder transport as alternative to AirDrop (MMDB-2631)' (#23) from feat/redline-onedrive-transport-20260905 into main
Merge pull request #23: Redline: OneDrive folder transport as alternative to AirDrop (MMDB-2631)
This commit was merged in pull request #23.
This commit is contained in:
@@ -3,6 +3,7 @@ import CoreGraphics
|
||||
import Darwin
|
||||
import Foundation
|
||||
import ImageIO
|
||||
import PDFKit
|
||||
import ShotdeckCore
|
||||
|
||||
/// In-process self-test for the region picker, driven by `SHOTDECK_PICKER_SELFTEST`.
|
||||
@@ -173,7 +174,7 @@ enum PickerSelfTest {
|
||||
try await executeSendTruth()
|
||||
print("SEND-TRUTH PASS")
|
||||
fflush(stdout)
|
||||
if !startUpdateSelfTestIfRequested() {
|
||||
if !startUpdateSelfTestIfRequested(), !startOneDriveSelfTestIfRequested() {
|
||||
exit(0)
|
||||
}
|
||||
} catch {
|
||||
@@ -222,7 +223,7 @@ enum PickerSelfTest {
|
||||
sendTruthFail("seeded session was empty")
|
||||
}
|
||||
|
||||
let pending = try await model.composePDFForSend()
|
||||
let pending = try await model.composePDFForSend(outbox: model.outboxURL, transport: .airDrop)
|
||||
guard fm.fileExists(atPath: pending.fileURL.path) else {
|
||||
sendTruthFail("PDF was not written")
|
||||
}
|
||||
@@ -315,7 +316,9 @@ enum PickerSelfTest {
|
||||
try await runUpdateSelfTest(outputDirectory: output)
|
||||
print("UPDATE-SELFTEST PASS version=99.0.0")
|
||||
fflush(stdout)
|
||||
exit(0)
|
||||
if !startOneDriveSelfTestIfRequested() {
|
||||
exit(0)
|
||||
}
|
||||
} catch let error as UpdateSelfTestError {
|
||||
updateFail(error.description)
|
||||
} catch {
|
||||
@@ -573,6 +576,335 @@ enum PickerSelfTest {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
/// Phase 5: proves the OneDrive transport end to end against a REAL sync root —
|
||||
/// resolved at runtime via `OneDriveLocator.syncRoots()`, never a hardcoded path, so
|
||||
/// this runs correctly on any Mac/account that has OneDrive signed in (MMD-named
|
||||
/// root preferred, same as production). Triggered by `SHOTDECK_ONEDRIVE_SELFTEST`
|
||||
/// when chained after PICKER/SEND-TRUTH/UPDATE-SELFTEST — the exact pattern
|
||||
/// `startUpdateSelfTestIfRequested` uses for its own env var. Returns true when the
|
||||
/// async phase was scheduled (it calls `exit` itself).
|
||||
@discardableResult
|
||||
private static func startOneDriveSelfTestIfRequested() -> Bool {
|
||||
guard ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil else {
|
||||
return false
|
||||
}
|
||||
runOneDriveSelfTestAndExit()
|
||||
return true
|
||||
}
|
||||
|
||||
/// Entry point for running ONLY this phase, bypassing the on-screen picker chain
|
||||
/// entirely. The harness has no other per-phase selector, so this is the escape
|
||||
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
|
||||
static func runOneDriveOnlyIfRequested() {
|
||||
guard ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" else {
|
||||
return
|
||||
}
|
||||
// Same hop as runIfRequested(): a plain main-queue turn after NSApp starts, so
|
||||
// AppKit/PDFKit calls inside the phase are not racing app launch.
|
||||
DispatchQueue.main.async {
|
||||
MainActor.assumeIsolated {
|
||||
runOneDriveSelfTestAndExit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func runOneDriveSelfTestAndExit() {
|
||||
// Never a false PASS: no real OneDrive sync root on this machine/account is a
|
||||
// SKIP (still non-zero exit), not silently treated as passing.
|
||||
guard let syncRoot = OneDriveLocator.syncRoots().first else {
|
||||
print("ONEDRIVE-SELFTEST SKIP no OneDrive sync root")
|
||||
fflush(stdout)
|
||||
exit(1)
|
||||
}
|
||||
Task { @MainActor in
|
||||
do {
|
||||
let folder = try await executeOneDriveSelfTest(syncRoot: syncRoot)
|
||||
print("ONEDRIVE-SELFTEST PASS path=\(folder.path)")
|
||||
fflush(stdout)
|
||||
exit(0)
|
||||
} catch let error as OneDriveSelfTestError {
|
||||
oneDriveFail(error.description)
|
||||
} catch {
|
||||
oneDriveFail(String(describing: error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sub-step 1: builds a session, sends it through the OneDrive branch of
|
||||
/// `send(anchor: nil)` against a NEW folder under `syncRoot`, confirms the watcher
|
||||
/// does NOT report the freshly-written unmarked PDF as a return, then adds a real
|
||||
/// PDFKit ink annotation in place (what the iPad does) and confirms the watcher now
|
||||
/// reports it as commented.
|
||||
///
|
||||
/// Sub-step 1b: rapid transport toggling (chooseTransport(.airDrop) immediately
|
||||
/// followed by chooseTransport(.oneDrive), no await between them) must still end
|
||||
/// with the watcher pointed at the OneDrive folder — proves the generation-guarded
|
||||
/// reconcile in chooseTransport/chooseOneDriveFolder (SettingsView.swift) really
|
||||
/// does let the last choice win instead of an earlier, superseded call applying its
|
||||
/// stale folder after a later one already won.
|
||||
///
|
||||
/// Sub-step 1c: the OTHER race — a toggle immediately followed by Send, with no
|
||||
/// sleep at all before send() runs. Proves send() awaits `pendingReconcileTask`
|
||||
/// before snapshotting transport/folder: a freshly-sent, still-unmarked PDF must
|
||||
/// never be reported as an already-returned document (which is exactly what would
|
||||
/// happen if send() raced ahead while recordUncommented was still `true`, stale
|
||||
/// from the .airDrop leg of the toggle).
|
||||
///
|
||||
/// Sub-step 2: relaunch simulation — the exact BLOCKER scenario this phase exists to
|
||||
/// catch. OneDrive is still persisted in defaults from sub-step 1; builds a FRESH
|
||||
/// model the same way the real app launches (`AppDelegate.makeLaunchModel()` itself,
|
||||
/// not a reimplementation), bootstraps it, then marks a PDF in the folder in place —
|
||||
/// the relaunched watcher must report it. A temp app-support root keeps this off the
|
||||
/// real ~/Library/Application Support/Shotdeck.
|
||||
///
|
||||
/// Never deletes anything under OneDrive — the created folder and PDFs are left in
|
||||
/// place for Ben to inspect / for the real iPad round trip.
|
||||
private static func executeOneDriveSelfTest(syncRoot: URL) async throws -> URL {
|
||||
let fm = FileManager.default
|
||||
|
||||
// UserDefaults.standard is the ONLY defaults instance send()/TransportSettings
|
||||
// actually read at runtime (there is no defaults-threading through AppModel), so
|
||||
// "isolated" here means snapshot-and-restore around the real keys — the same
|
||||
// pattern runRegionPersistPhase already uses for CaptureRegion.defaultsKey.
|
||||
let defaults = UserDefaults.standard
|
||||
let previousTransport = defaults.string(forKey: TransportSettings.transportDefaultsKey)
|
||||
let previousFolder = defaults.string(forKey: TransportSettings.oneDriveFolderDefaultsKey)
|
||||
defer {
|
||||
if let previousTransport {
|
||||
defaults.set(previousTransport, forKey: TransportSettings.transportDefaultsKey)
|
||||
} else {
|
||||
defaults.removeObject(forKey: TransportSettings.transportDefaultsKey)
|
||||
}
|
||||
if let previousFolder {
|
||||
defaults.set(previousFolder, forKey: TransportSettings.oneDriveFolderDefaultsKey)
|
||||
} else {
|
||||
defaults.removeObject(forKey: TransportSettings.oneDriveFolderDefaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
let stamp = DubaiTime.fileStamp(Date())
|
||||
let selftestFolder = syncRoot.appendingPathComponent("Redline-selftest-\(stamp)", isDirectory: true)
|
||||
try fm.createDirectory(at: selftestFolder, withIntermediateDirectories: true)
|
||||
|
||||
TransportSettings.setTransport(.oneDrive, defaults: defaults)
|
||||
TransportSettings.setOneDriveFolder(selftestFolder, defaults: defaults)
|
||||
|
||||
// Local spool root only — the outbox/watch folder is the real OneDrive folder.
|
||||
let spoolRoot = fm.temporaryDirectory
|
||||
.appendingPathComponent("shotdeck-onedrive-selftest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? fm.removeItem(at: spoolRoot) }
|
||||
|
||||
let paths = try AppSupportPaths(root: spoolRoot, outbox: selftestFolder, watchFolder: selftestFolder)
|
||||
let ledger = try ReturnLedger(paths: paths)
|
||||
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
|
||||
await watcher.setRecordUncommented(false) // OneDrive mode: today's default is AirDrop's `true`.
|
||||
|
||||
let model = AppModel(
|
||||
paths: paths,
|
||||
spool: try SpoolStore(paths: paths),
|
||||
composer: PDFComposer(),
|
||||
capturer: ScreenCapturer(),
|
||||
hotkeys: HotkeyCenter(),
|
||||
picker: RegionPickerController(),
|
||||
ledger: ledger,
|
||||
watcher: watcher
|
||||
)
|
||||
model.setFolderURLs(outbox: selftestFolder, watch: selftestFolder)
|
||||
model.setTransport(.oneDrive)
|
||||
|
||||
let png = try makeTinyPNGData()
|
||||
_ = try await model.spool.append(
|
||||
pngData: png, pixelWidth: 64, pixelHeight: 48, scale: 1, capturedAt: Date()
|
||||
)
|
||||
model.replaceSession(try await model.spool.currentSession())
|
||||
guard !model.session.isEmpty else {
|
||||
throw OneDriveSelfTestError.detail("seeded session was empty")
|
||||
}
|
||||
|
||||
await model.send(anchor: nil)
|
||||
|
||||
guard let status = model.statusLine, status.hasPrefix("Saved to OneDrive") else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"status did not start with 'Saved to OneDrive': \(model.statusLine ?? "nil")"
|
||||
)
|
||||
}
|
||||
guard model.session.isEmpty else {
|
||||
throw OneDriveSelfTestError.detail("session was not archived after the OneDrive send")
|
||||
}
|
||||
|
||||
let written = (try? fm.contentsOfDirectory(at: selftestFolder, includingPropertiesForKeys: nil)) ?? []
|
||||
guard let pdfURL = written.first(where: { $0.pathExtension.lowercased() == "pdf" }) else {
|
||||
throw OneDriveSelfTestError.detail("no PDF found in \(selftestFolder.path)")
|
||||
}
|
||||
|
||||
// Unmarked so far: the watcher must not treat it as a return.
|
||||
let beforeMarkup = try await watcher.scanNow()
|
||||
guard !beforeMarkup.contains(where: { $0.fileURL == pdfURL }) else {
|
||||
throw OneDriveSelfTestError.detail("unmarked PDF was reported as returned by scanNow")
|
||||
}
|
||||
let commentedBefore = try await ledger.commented()
|
||||
guard !commentedBefore.contains(where: { $0.fileURL == pdfURL }) else {
|
||||
throw OneDriveSelfTestError.detail("unmarked PDF was recorded as commented in the ledger")
|
||||
}
|
||||
|
||||
// What the iPad does: mark it up in place with a real ink annotation, then save.
|
||||
try addInkMark(to: pdfURL)
|
||||
|
||||
let afterMarkup = try await watcher.scanNow()
|
||||
guard let recorded = afterMarkup.first(where: { $0.fileURL == pdfURL }), recorded.isCommented else {
|
||||
throw OneDriveSelfTestError.detail("annotated PDF was not reported as commented by scanNow")
|
||||
}
|
||||
let commentedAfter = try await ledger.commented()
|
||||
guard commentedAfter.contains(where: { $0.fileURL == pdfURL }) else {
|
||||
throw OneDriveSelfTestError.detail("annotated PDF was not recorded in the ledger as commented")
|
||||
}
|
||||
|
||||
// Sub-step 1b: rapid toggle race — see the doc comment above this function.
|
||||
model.chooseTransport(.airDrop)
|
||||
model.chooseTransport(.oneDrive) // immediately superseding the call above
|
||||
// The generation guard itself is what's under test, not this wait — it just
|
||||
// gives the (already-guarded) reconcile Task a moment to settle either way.
|
||||
try await Task.sleep(for: .milliseconds(500))
|
||||
guard model.transport == .oneDrive else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"rapid toggle: model.transport ended as \(model.transport), expected .oneDrive"
|
||||
)
|
||||
}
|
||||
let racePDFURL = selftestFolder.appendingPathComponent("Redline-race-\(stamp).pdf")
|
||||
try writeUnmarkedRedlinePDF(to: racePDFURL)
|
||||
try addInkMark(to: racePDFURL)
|
||||
let raceFound = try await model.watcher.scanNow()
|
||||
guard raceFound.first(where: { $0.fileURL == racePDFURL })?.isCommented == true else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"rapid toggle: watcher did not end up watching \(selftestFolder.path) — an earlier, superseded chooseTransport call won"
|
||||
)
|
||||
}
|
||||
|
||||
// Sub-step 1c: toggle-then-immediate-send race — see the doc comment above
|
||||
// this function. No sleep here: this IS the exact race window finding #3
|
||||
// exists to close, so send() itself must wait out the pending reconcile.
|
||||
let racePNG = try makeTinyPNGData()
|
||||
_ = try await model.spool.append(
|
||||
pngData: racePNG, pixelWidth: 64, pixelHeight: 48, scale: 1, capturedAt: Date()
|
||||
)
|
||||
model.replaceSession(try await model.spool.currentSession())
|
||||
guard !model.session.isEmpty else {
|
||||
throw OneDriveSelfTestError.detail("toggle-then-send: re-seeded session was empty")
|
||||
}
|
||||
|
||||
let knownBeforeToggleSend = Set(
|
||||
((try? fm.contentsOfDirectory(at: selftestFolder, includingPropertiesForKeys: nil)) ?? [])
|
||||
.map(\.lastPathComponent)
|
||||
)
|
||||
model.chooseTransport(.airDrop)
|
||||
model.chooseTransport(.oneDrive) // immediately superseding, no sleep before send()
|
||||
await model.send(anchor: nil)
|
||||
|
||||
guard let toggleSendStatus = model.statusLine, toggleSendStatus.hasPrefix("Saved to OneDrive") else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"toggle-then-send: status was \(model.statusLine ?? "nil"), expected 'Saved to OneDrive'"
|
||||
)
|
||||
}
|
||||
guard model.session.isEmpty else {
|
||||
throw OneDriveSelfTestError.detail("toggle-then-send: session was not archived")
|
||||
}
|
||||
let filesAfterToggleSend = (try? fm.contentsOfDirectory(
|
||||
at: selftestFolder, includingPropertiesForKeys: nil
|
||||
)) ?? []
|
||||
guard let toggleSendPDFURL = filesAfterToggleSend.first(where: {
|
||||
$0.pathExtension.lowercased() == "pdf" && !knownBeforeToggleSend.contains($0.lastPathComponent)
|
||||
}) else {
|
||||
throw OneDriveSelfTestError.detail("toggle-then-send: no new PDF found in \(selftestFolder.path)")
|
||||
}
|
||||
// The freshly-sent PDF is UNMARKED. If send() had raced ahead of the pending
|
||||
// reconcile, recordUncommented could still have been (stale) true, and this
|
||||
// scan would wrongly report it as already returned.
|
||||
let scanAfterToggleSend = try await model.watcher.scanNow()
|
||||
guard !scanAfterToggleSend.contains(where: { $0.fileURL == toggleSendPDFURL }) else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"toggle-then-send: freshly-sent unmarked PDF at \(toggleSendPDFURL.path) was reported as returned — send() raced ahead of the pending reconcile"
|
||||
)
|
||||
}
|
||||
|
||||
// Sub-step 2: relaunch simulation — see the doc comment above this function.
|
||||
let relaunchAppSupportRoot = fm.temporaryDirectory
|
||||
.appendingPathComponent("shotdeck-onedrive-relaunch-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? fm.removeItem(at: relaunchAppSupportRoot) }
|
||||
|
||||
let relaunchModel = AppDelegate.makeLaunchModel(appSupportRoot: relaunchAppSupportRoot)
|
||||
guard relaunchModel.transport == .oneDrive else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"relaunch: model transport was \(relaunchModel.transport), expected .oneDrive"
|
||||
)
|
||||
}
|
||||
guard relaunchModel.watchFolderURL.path == selftestFolder.path else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"relaunch: model watchFolderURL was \(relaunchModel.watchFolderURL.path), expected \(selftestFolder.path) — this is the exact BLOCKER this phase guards against"
|
||||
)
|
||||
}
|
||||
|
||||
await relaunchModel.bootstrap()
|
||||
|
||||
let relaunchPDFURL = selftestFolder.appendingPathComponent("Redline-relaunch-\(stamp).pdf")
|
||||
try writeUnmarkedRedlinePDF(to: relaunchPDFURL)
|
||||
try addInkMark(to: relaunchPDFURL)
|
||||
|
||||
let relaunchFound = try await relaunchModel.watcher.scanNow()
|
||||
guard relaunchFound.first(where: { $0.fileURL == relaunchPDFURL })?.isCommented == true else {
|
||||
throw OneDriveSelfTestError.detail(
|
||||
"relaunch: watcher did not report the marked PDF at \(relaunchPDFURL.path) as returned — it was watching the wrong folder after relaunch"
|
||||
)
|
||||
}
|
||||
await relaunchModel.watcher.stop()
|
||||
|
||||
return selftestFolder
|
||||
}
|
||||
|
||||
/// Adds a real PDFKit ink annotation to the PDF at `url` in place and saves it —
|
||||
/// exactly what the iPad does when marking up a page.
|
||||
private static func addInkMark(to url: URL) throws {
|
||||
guard let document = PDFDocument(url: url), let page = document.page(at: 0) else {
|
||||
throw OneDriveSelfTestError.detail("could not reopen \(url.path) to annotate it")
|
||||
}
|
||||
let ink = PDFAnnotation(
|
||||
bounds: CGRect(x: 20, y: 20, width: 60, height: 60),
|
||||
forType: .ink,
|
||||
withProperties: nil
|
||||
)
|
||||
let stroke = NSBezierPath()
|
||||
stroke.move(to: NSPoint(x: 20, y: 20))
|
||||
stroke.line(to: NSPoint(x: 80, y: 80))
|
||||
ink.add(stroke)
|
||||
page.addAnnotation(ink)
|
||||
guard document.write(to: url) else {
|
||||
throw OneDriveSelfTestError.detail("could not save the annotated PDF back to \(url.path)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a fresh, unmarked, single-page "Redline"-creator PDF straight to `url` —
|
||||
/// standing in for a PDF that has just landed in the watch folder, before any
|
||||
/// human mark. Used by the rapid-toggle and relaunch sub-steps, which don't need to
|
||||
/// exercise send()/composePDFForSend() again (sub-step 1 already does).
|
||||
private static func writeUnmarkedRedlinePDF(to url: URL) throws {
|
||||
let document = PDFDocument()
|
||||
let page = PDFPage()
|
||||
page.setBounds(CGRect(x: 0, y: 0, width: 612, height: 792), for: .mediaBox)
|
||||
document.insert(page, at: 0)
|
||||
document.documentAttributes = [
|
||||
PDFDocumentAttribute.creatorAttribute: "Redline",
|
||||
PDFDocumentAttribute.subjectAttribute: UUID().uuidString,
|
||||
]
|
||||
guard document.write(to: url) else {
|
||||
throw OneDriveSelfTestError.detail("could not write \(url.path)")
|
||||
}
|
||||
}
|
||||
|
||||
private static func oneDriveFail(_ detail: String) -> Never {
|
||||
print("ONEDRIVE-SELFTEST FAIL \(detail)")
|
||||
fflush(stdout)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
private static func interpolate(_ step: Int) -> NSPoint {
|
||||
let t = CGFloat(step) / CGFloat(dragSteps)
|
||||
return NSPoint(
|
||||
@@ -638,3 +970,12 @@ private enum UpdateSelfTestError: Error, CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum OneDriveSelfTestError: Error, CustomStringConvertible {
|
||||
case detail(String)
|
||||
var description: String {
|
||||
switch self {
|
||||
case .detail(let s): return s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user