Compare commits
5
Commits
70231574c9
...
3abb8dc6ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3abb8dc6ca | ||
|
|
8d68c836cd | ||
|
|
04d1e73532 | ||
|
|
d7984add2d | ||
|
|
723cd7dcea |
@@ -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)]
|
||||||
|
),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -139,6 +139,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
|
||||||
@@ -241,19 +249,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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
@@ -543,6 +543,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 +680,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)
|
||||||
|
|||||||
@@ -16,28 +16,44 @@ extension AppModel: SendCapable {
|
|||||||
guard !session.isEmpty, !isSending else { return }
|
guard !session.isEmpty, !isSending else { return }
|
||||||
setSending(true)
|
setSending(true)
|
||||||
|
|
||||||
|
// Wait for any IN-FLIGHT transport/folder reconcile (chooseTransport/
|
||||||
|
// chooseOneDriveFolder in SettingsView.swift) to fully settle BEFORE
|
||||||
|
// snapshotting transport/folder below. Without this, a toggle immediately
|
||||||
|
// followed by Send could let send() read a state that is still mid-transition
|
||||||
|
// — e.g. the watcher's recordUncommented flag briefly lagging the just-chosen
|
||||||
|
// transport, so a freshly-sent unmarked OneDrive PDF gets misreported as an
|
||||||
|
// already-returned document. `Task<Void, Never>.value` never throws, and
|
||||||
|
// awaiting nil is an immediate no-op (AirDrop mode, or no toggle in flight).
|
||||||
|
await pendingReconcileTask?.value
|
||||||
|
|
||||||
// Snapshot BOTH the transport AND the destination folder into local `let`s
|
// 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 +75,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.
|
||||||
@@ -109,10 +125,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 +156,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)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -176,4 +176,29 @@ 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)")
|
||||||
|
do {
|
||||||
|
try AtomicFile.write(Data(), to: probeURL)
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
try fileManager.removeItem(at: probeURL)
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -122,6 +122,44 @@ 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))
|
||||||
|
}
|
||||||
|
|
||||||
struct TransportDefaultsSuite {
|
struct TransportDefaultsSuite {
|
||||||
let name: String
|
let name: String
|
||||||
let defaults: UserDefaults
|
let defaults: UserDefaults
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import AppKit
|
||||||
|
import Foundation
|
||||||
|
import PDFKit
|
||||||
|
import Testing
|
||||||
|
import ShotdeckCore
|
||||||
|
@testable import Shotdeck
|
||||||
|
|
||||||
|
/// Coverage gap closed (adversarial review, round 3): 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.
|
||||||
|
@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() }
|
||||||
|
|
||||||
|
#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()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user