Skip to main content
coreydaley.dev

Dragging files out of a sandboxed SwiftUI app without renaming them

Purrchiver shows an archive’s contents in a table, and you can drag any row out to Finder or into the folder pane next to it. Over May 26–28 that one feature produced five separate bugs. The first two were about filenames: .gitignore landed as _gitignore, and folders landed as a file called item. The rest came from fixing them: a dispatch_assert_queue_fail crash under Swift 6, and two deadlocks.

Bug 1: folders and dotfiles became “item”

The table was a SwiftUI Table, and each row offered itself for dragging through an NSItemProvider with a file representation. You register that representation under a UTType plus a suggestedName, and the receiver builds the final filename from the two: the suggested name plus the type’s preferred extension.

I picked the type from the filename’s extension, which went wrong three ways:

  • Folders have no extension, so the lookup returned nil and the code fell back to .item, the root of the type tree.
  • Dotfiles confuse NSString.pathExtension. For .gitignore it returns gitignore. No type matches that, so .item again, and stripping the “extension” left an empty name.
  • Extensionless files like Makefile hit the same fallback.

Finder refused the drag registered as public.item and showed the ⊘ cursor. My own folder pane accepted it, but every drop landed as item.

The fix is to never fall back to .item:

func representation(for name: String, isDirectory: Bool) -> (UTType, String) {
    if isDirectory { return (.folder, name) }
    // ".gitignore": a leading dot and no other dot is the whole name, not an extension
    if name.hasPrefix("."), !name.dropFirst().contains(".") { return (.data, name) }
    let ext = (name as NSString).pathExtension
    if !ext.isEmpty, let type = UTType(filenameExtension: ext) {
        return (type, (name as NSString).deletingPathExtension)
    }
    return (.data, name)   // public.data has no preferred extension
}

public.folder and public.data are both specific enough for Finder to accept, and neither appends an extension, so the full name comes through unchanged.

Bug 2: .gitignore arrived as _gitignore

With the types right, dropping .gitignore into my own folder pane produced _gitignore. A file representation reaches the receiver as a copy the system makes in a temporary folder, and in my testing that copy renamed the leading dot to an underscore. The receiver only sees the renamed copy.

suggestedName survives that copy intact, so the first fix was to read it on the receiving side before the load finished and prefer it over the temp file’s name. That repaired my own drop target, but I can’t change how Finder or any other app receives a drop. NSItemProvider has no setting for the renaming that I could find.

The switch to NSFilePromiseProvider

The AppKit answer is a file promise. Instead of handing over a file, the source promises one, and its delegate answers two questions:

  • filePromiseProvider(_:fileNameForType:): the exact name to use, leading dot included.
  • filePromiseProvider(_:writePromiseTo:completionHandler:): here’s the final destination URL, with that name already on it; write the bytes there.

No temp copy, nothing to rename. The catch is that SwiftUI’s Table drags only through NSItemProvider, so the archive table became an NSTableView in an NSViewRepresentable, with tableView(_:pasteboardWriterForRow:) returning one promise per row. That meant rebuilding sorting, multi-select, and the context menu by hand, and giving up SwiftUI’s table styling.

Bug 3: dispatch_assert_queue_fail

The first drag with the new table hung with a beachball. sample showed the delegate’s operation queue inside writePromiseTo, then _checkExpectedExecutor, then dispatch_assert_queue_fail.

AppKit isn’t the one asking for the main actor here. Its header marks the write method NS_SWIFT_NONISOLATED and says the call arrives on the OperationQueue you return from operationQueue(for:). The isolation came from my own build settings: the app target uses Swift 6 with SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, so a class with no annotation at all is MainActor-isolated, and so is every method on it, including the protocol witnesses. When Objective-C calls a MainActor method, Swift checks that it really is on the main thread. On the promise queue it wasn’t, so the check trapped. Marking the class @unchecked Sendable didn’t help. That says the type is safe to share. It doesn’t change which actor a method runs on.

The fix is an explicit nonisolated on the write method. I put it on the other two delegate methods and the static queue as well, since none of them needs the main actor:

nonisolated func filePromiseProvider(_ provider: NSFilePromiseProvider,
                                     writePromiseTo url: URL,
                                     completionHandler: @escaping (Error?) -> Void) {
    // runs on the promise queue: write the bytes to `url`, then call completionHandler
}

That’s safe here because the delegate’s state never changes after init, and the extraction it calls into is an actor with its own isolation. The compiler accepted the original conformance without a warning; the trap only showed up at runtime.

Bug 4: a deadlock on drops inside the app

This one hit the original SwiftUI path a little earlier the same day, and the lesson applies to both. Dragging a row into the folder pane in the same window froze the app. sample showed every main-thread sample parked in semaphore_wait_trap under loadDataRepresentationSynchronously.

During a drag, AppKit holds the main thread until the mouse comes up. On drop, SwiftUI loaded the data synchronously and waited on a semaphore on the main thread. The source’s load handler started a detached task to extract the file. But the extraction function belonged to a @MainActor type, so the detached task tried to hop back to the main actor, which was busy waiting on that semaphore. Neither side could move.

The fix was nonisolated on the extraction function, which didn’t need the main actor for anything. Drags to Finder never deadlocked, because Finder is a different process with its own main thread.

Bug 5: the coordinator that deadlocked itself

Two days later, with the folder pane showing an iCloud-synced Desktop, drops from the archive table stopped landing. My first fix wrapped the source-side write in NSFileCoordinator. That deadlocked every drop inside the app. For a promise drop the receiver, NSFilePromiseReceiver, already holds coordinated access to the destination and waits for the source to write. A second coordinated write from the source waits for the receiver to let go, and it never does. Logging showed the write stopping right before the coordinator call.

So the source writes the bytes directly and leaves coordination to the receiver. AppKit’s header says as much: NSFilePromiseReceiver wraps the write in NSFileCoordinator itself. The actual problem was on the receiving side. My pane wasn’t holding the destination folder’s security scope while the drop was in progress, and it wasn’t resolving symlinks in the destination path. The drop showed the green “+” and then silently wrote nothing. The receiver now starts the scope before receiving the promises and stops it after the last completion handler fires. I could only check the iCloud case by hand, not in a unit test, so a test reads the source instead and fails if the source-side coordinator ever comes back.

What to take away

  • Never register a drag as public.item. Use .folder for directories and .data when you don’t know the type, and keep dotfiles away from pathExtension.
  • If the exact filename matters, use NSFilePromiseProvider. In SwiftUI that currently means dropping to NSTableView or NSOutlineView.
  • With SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, an AppKit delegate method that’s called off the main thread needs an explicit nonisolated. @unchecked Sendable won’t fix it.
  • Don’t hop to the main actor from anything a drag is waiting on. The main thread belongs to the drag until the mouse comes up.
  • For a promise drop, the receiver coordinates the destination and the source doesn’t.

Related posts