Two issues: (1) directoryExists(at:) only checked existence + isDirectory, so an existing-but-unwritable OneDrive folder skipped the oneDriveFolderUnavailable branch and surfaced as a generic pdfCompositionFailed message instead — now uses OneDriveLocator.isWritableDirectory(at:). (2) send() read `self.outboxURL` again inside composePDFForSend() after at least one await had already run, so a concurrent chooseTransport() call (SettingsView.swift) could flip transport/outboxURL/recordUncommented mid-send, landing the PDF under one transport's folder while the archive/status branch ran the other's. Fix: send() now snapshots BOTH transport and the destination folder into local `let`s once, before any await, and passes the folder explicitly into the renamed composePDFForSend(outbox:) — which no longer reads self.outboxURL at all. The archive/status switch already used the frozen `transport` local. (chooseTransport/chooseOneDriveFolder additionally refuse outright while isSending is true — see the SettingsView.swift commit — so in practice this race can no longer even be triggered, but the snapshot is the actual structural fix regardless.) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
176 lines
8.1 KiB
Swift
176 lines
8.1 KiB
Swift
import AppKit
|
||
import Darwin
|
||
import Foundation
|
||
import ShotdeckCore
|
||
|
||
/// Result of composing a send PDF. Kept so the self-test can drive the share
|
||
/// outcome without presenting a real AirDrop sheet.
|
||
struct ComposedSend: Sendable {
|
||
let fileName: String
|
||
let fileURL: URL
|
||
let pageCount: Int
|
||
}
|
||
|
||
extension AppModel: SendCapable {
|
||
public func send(anchor: NSView?) async {
|
||
guard !session.isEmpty, !isSending else { return }
|
||
setSending(true)
|
||
|
||
// Snapshot BOTH the transport AND the destination folder into local `let`s
|
||
// ONCE, before any `await` in this function. chooseTransport/chooseOneDriveFolder
|
||
// now refuse (status "Finish the current send first.") while isSending is true,
|
||
// but this snapshot is the actual fix for the race: even without that guard,
|
||
// everything below operates on these frozen values — composePDFForSend(outbox:)
|
||
// takes the folder as a parameter and never re-reads `self.outboxURL` after a
|
||
// suspension point, so a concurrent transport switch mid-send can no longer land
|
||
// the PDF under one transport's folder while the archive/status branch (which
|
||
// switches on the same frozen `transport` local) runs the other's.
|
||
let transport = TransportSettings.transport()
|
||
let destinationFolder: URL
|
||
|
||
// OneDrive mode: verify the real destination exists AND is writable RIGHT NOW,
|
||
// before composing anything. `outboxURL` is kept in sync with the resolved
|
||
// OneDrive folder by bootstrap/chooseTransport/chooseOneDriveFolder, but this is
|
||
// re-resolved fresh here (never trusted stale) so a folder that vanished or lost
|
||
// its permissions since then (OneDrive signed out, external volume unmounted,
|
||
// folder deleted, chmod'd unwritable) is caught instead of silently attempted
|
||
// and surfacing as a generic PDF-composition failure.
|
||
if transport == .oneDrive {
|
||
guard let folder = OneDriveLocator.resolveOneDriveFolder(),
|
||
OneDriveLocator.isWritableDirectory(at: folder)
|
||
else {
|
||
let path = OneDriveLocator.resolveOneDriveFolder()?.path
|
||
?? TransportSettings.storedOneDriveFolderPath()
|
||
?? "no OneDrive folder found"
|
||
setResolvedOneDriveFolder(nil)
|
||
setStatus(ShotdeckError.oneDriveFolderUnavailable(path: path).errorDescription)
|
||
setSending(false)
|
||
return
|
||
}
|
||
destinationFolder = folder
|
||
setResolvedOneDriveFolder(folder)
|
||
if outboxURL != folder || watchFolderURL != folder {
|
||
setFolderURLs(outbox: folder, watch: folder)
|
||
try? await watcher.updateWatchFolder(folder)
|
||
}
|
||
} else {
|
||
destinationFolder = outboxURL
|
||
}
|
||
|
||
let pending: ComposedSend
|
||
do {
|
||
pending = try await composePDFForSend(outbox: destinationFolder)
|
||
} catch {
|
||
// Never unlink the published PDF, and never unlink the temp file either:
|
||
// a rename failure would leave the complete document at the temp name.
|
||
setStatus((error as? ShotdeckError)?.errorDescription ?? "The PDF could not be built.")
|
||
setSending(false)
|
||
return
|
||
}
|
||
|
||
switch transport {
|
||
case .oneDrive:
|
||
// No AirDrop, no anchor needed — the PDF is already in the watched
|
||
// OneDrive folder. Archive immediately; the iPad marks it up in place.
|
||
await handleDidShareItems(fileName: pending.fileName, pageCount: pending.pageCount)
|
||
let pageWord = pending.pageCount == 1 ? "page" : "pages"
|
||
setStatus(
|
||
"Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
|
||
)
|
||
setSending(false)
|
||
|
||
case .airDrop:
|
||
guard let anchor else {
|
||
handleDidFailToShareItems(fileName: pending.fileName)
|
||
setSending(false)
|
||
return
|
||
}
|
||
|
||
do {
|
||
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
|
||
guard let self else { return }
|
||
if success {
|
||
await self.handleDidShareItems(
|
||
fileName: pending.fileName,
|
||
pageCount: pending.pageCount
|
||
)
|
||
} else {
|
||
self.handleDidFailToShareItems(fileName: pending.fileName)
|
||
}
|
||
self.setSending(false)
|
||
}
|
||
} catch {
|
||
// canPerform false, no service, or no visible window: same as cancel.
|
||
handleDidFailToShareItems(fileName: pending.fileName)
|
||
setSending(false)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Writes the PDF to `outboxDir` and records its path. Does not archive the session
|
||
/// and does not present AirDrop — that happens only after the share completes.
|
||
/// `outboxDir` is passed in (a value `send(anchor:)` snapshotted before any await)
|
||
/// rather than read from `self.outboxURL` here, so a concurrent transport switch
|
||
/// mid-send can never redirect an in-flight compose to a different folder.
|
||
func composePDFForSend(outbox outboxDir: URL) async throws -> ComposedSend {
|
||
let workingSession = session
|
||
let composer = self.composer
|
||
let sourceDir = paths.sessionDirectory(workingSession.id)
|
||
let fileName = PDFComposer.fileName(for: workingSession)
|
||
let finalURL = outboxDir.appendingPathComponent(fileName)
|
||
// Same directory as the final target so the rename below is same-volume (atomic).
|
||
let tempURL = outboxDir.appendingPathComponent(".shotdeck-\(UUID().uuidString).pdf")
|
||
let title = "Redline – \(DubaiTime.stamp(workingSession.createdAt))"
|
||
|
||
// D-13: build off the main actor. Only Sendable values cross into the
|
||
// detached task — never `anchor` (NSView is not Sendable).
|
||
try await Task.detached(priority: .userInitiated) {
|
||
_ = try composer.compose(
|
||
session: workingSession,
|
||
imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) },
|
||
title: title,
|
||
to: tempURL
|
||
)
|
||
// POSIX rename onto `finalURL` replaces any same-name file in one
|
||
// directory operation; there is never a window where the PDF is gone.
|
||
if Darwin.rename(tempURL.path, finalURL.path) != 0 {
|
||
throw ShotdeckError.pdfCompositionFailed(
|
||
reason: "could not publish the PDF: \(String(cString: strerror(errno)))"
|
||
)
|
||
}
|
||
try AtomicFile.fsyncDirectory(at: outboxDir)
|
||
}.value
|
||
|
||
guard FileManager.default.fileExists(atPath: finalURL.path) else {
|
||
throw ShotdeckError.pdfCompositionFailed(reason: "the PDF was not written to disk")
|
||
}
|
||
rememberLastComposedPDF(finalURL)
|
||
return ComposedSend(
|
||
fileName: fileName,
|
||
fileURL: finalURL,
|
||
pageCount: workingSession.captures.count
|
||
)
|
||
}
|
||
|
||
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam.
|
||
func handleDidShareItems(fileName: String, pageCount: Int) async {
|
||
guard !session.isEmpty else { return }
|
||
do {
|
||
_ = try await spool.archiveCurrent(pdfFileName: fileName)
|
||
replaceSession(try await spool.currentSession())
|
||
let pageWord = pageCount == 1 ? "page" : "pages"
|
||
setStatus("Sent — \(pageCount) \(pageWord).")
|
||
} catch {
|
||
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")
|
||
}
|
||
}
|
||
|
||
/// `NSSharingServiceDelegate.sharingService(_:didFailToShareItems:error:)` seam,
|
||
/// also used when `canPerform` is false or the user cancels. Does not archive.
|
||
func handleDidFailToShareItems(fileName: String) {
|
||
setStatus(
|
||
"AirDrop didn't complete — nothing was sent. Your captures are still here; the PDF is on your \(outboxDisplayName) as \(fileName)."
|
||
)
|
||
}
|
||
}
|