diff --git a/Sources/Early/BrowserApplication.swift b/Sources/Early/BrowserApplication.swift index 1a39234..73a0196 100644 --- a/Sources/Early/BrowserApplication.swift +++ b/Sources/Early/BrowserApplication.swift @@ -265,7 +265,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { /// A fresh window shares saved organization/store identity, never another /// window's Today tabs, split membership, live views, or command-bar state. @discardableResult - func openNewWindow(from source: BrowserWindowModel? = nil) -> UUID? { + func openNewWindow(from source: BrowserWindowModel? = nil, opening urls: [URL] = []) -> UUID? { guard canOpenWindow, let workspace else { return nil } let template: BrowserSession // New Window from a private window opens an ordinary one. @@ -276,7 +276,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { guard let session = workspace.session(for: workspace.activeProfileID) else { return nil } template = session } - let id = addWindow(session: template.savedItemsOnly) + let id = addWindow(session: template.openingWindow(at: urls)) self.workspace?.activeProfileID = template.profileID saveAll() presentWindow?(id) @@ -287,12 +287,13 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { /// no history, and nothing in it is saved, restored or kept on disk. /// It fills passwords saved in the profile it was opened from. @discardableResult - func openPrivateWindow(from source: BrowserWindowModel? = nil) -> UUID? { + func openPrivateWindow(from source: BrowserWindowModel? = nil, opening urls: [URL] = []) -> UUID? { guard canOpenWindow else { return nil } let profile = privateProfileID ?? UUID() privateProfileID = profile let passwordsFrom = source?.passwordsProfileID ?? workspace?.activeProfileID - let id = addWindow(session: .privateWindow(profileID: profile), passwordsFrom: passwordsFrom) + let session = BrowserSession.privateWindow(profileID: profile).openingWindow(at: urls) + let id = addWindow(session: session, passwordsFrom: passwordsFrom) presentWindow?(id) return id } @@ -343,7 +344,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { privateExtensionHosts.removeAll() sitePermissionStores.removeValue(forKey: profile) localFileStores.removeValue(forKey: profile) - downloadStores.removeValue(forKey: profile)?.cancelAll() + downloadStores.removeValue(forKey: profile)?.retire() } private func websiteDataStore(for id: UUID) -> WKWebsiteDataStore { @@ -532,11 +533,11 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { if let owner = (window?.owner as? BrowserWindowModel) ?? self.extensionModels(of: host).first { return owner.openExtensionTab(url, active: active) } - return self.openExtensionWindow(for: host, url: url)?.activeTab + return (try? self.openExtensionWindow(for: host, urls: [url]))?.activeTab } - host.openWindow = { [weak self, weak host] url in + host.openWindow = { [weak self, weak host] urls in guard let self, let host else { return nil } - return self.openExtensionWindow(for: host, url: url) + return try self.openExtensionWindow(for: host, urls: urls) } host.presentPopup = { [weak self, weak host] action in guard let self, let host, @@ -557,23 +558,27 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { /// A window an extension asked for, in the host's profile (or private session). @available(macOS 15.4, *) - private func openExtensionWindow(for host: ExtensionHost, url: URL?) -> ExtensionWindow? { + private func openExtensionWindow(for host: ExtensionHost, urls: [URL]) throws -> ExtensionWindow? { + // Validate the entire request before publishing a window or any tabs. + guard let urls = try? urls.map({ try input.validate($0) }) else { throw ExtensionHost.ExtensionError.invalidWindowURL } let source = extensionModels(of: host).first var id: UUID? if host.isPrivate { guard let source else { return nil } - id = openPrivateWindow(from: source) + id = openPrivateWindow(from: source, opening: urls) } else if let source { - id = openNewWindow(from: source) + id = openNewWindow(from: source, opening: urls) } else if canOpenWindow, let profile = extensionHosts.first(where: { $0.value === host })?.key, let session = workspace?.session(for: profile) { - let window = addWindow(session: session.savedItemsOnly) + let window = addWindow(session: session.openingWindow(at: urls)) saveAll() presentWindow?(window) id = window } guard let id, let model = windowModel(id) else { return nil } - if let url { _ = model.openExtensionTab(url, active: true) } + for tab in model.coordinator.tabStore.tabs where tab.isOpen && tab.id != model.coordinator.activeTabID { + model.webViews.load(tab.currentURL, in: tab) + } return model.extensionWindow as? ExtensionWindow } @@ -585,7 +590,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { owner.openExtensionTab(url, active: true) owner.extensionFocusWindow() } else { - _ = openExtensionWindow(for: host, url: url) + _ = try? openExtensionWindow(for: host, urls: [url]) } } @@ -1292,6 +1297,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { // its windows, credentials, extension data and permissions be removed. workspace = draft profileError = nil + downloadStores.removeValue(forKey: id)?.retire() let closing = windows.filter { $0.model.coordinator.profileID == id }.map(\.id) for windowID in closing { nativeWindow(id: windowID)?.close() @@ -1302,7 +1308,6 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { closeWindow(nil) } dataStores.removeValue(forKey: id) - downloadStores.removeValue(forKey: id)?.cancelAll() pullRequestFeeds.removeValue(forKey: id)?.stop() if extensionsProfileID == id { extensionsProfileID = nil } if passwordsProfileID == id { passwordsProfileID = nil } diff --git a/Sources/EarlyCore/BackgroundFileIO.swift b/Sources/EarlyCore/BackgroundFileIO.swift index 7a83679..d8c2886 100644 --- a/Sources/EarlyCore/BackgroundFileIO.swift +++ b/Sources/EarlyCore/BackgroundFileIO.swift @@ -104,10 +104,10 @@ public enum BackgroundFileIO { defer { try? output.close() } try write(output) try output.synchronize() - try Task.checkCancellation() if let mode = try? files.attributesOfItem(atPath: destination.path)[.posixPermissions] { try files.setAttributes([.posixPermissions: mode], ofItemAtPath: staged.path) } + try Task.checkCancellation() guard Darwin.rename(staged.path, destination.path) == 0 else { throw fileError() } } } diff --git a/Sources/EarlyCore/BrowserSession.swift b/Sources/EarlyCore/BrowserSession.swift index 237fe12..aeea0f2 100644 --- a/Sources/EarlyCore/BrowserSession.swift +++ b/Sources/EarlyCore/BrowserSession.swift @@ -131,16 +131,17 @@ public struct BrowserSession: Codable, Equatable, Sendable { /// A copied page is a new Today tab, even when opened from a saved pin. /// Saved tabs start unloaded; no other window's live navigation is copied. public func openingWindow(at url: URL, title: String? = nil) -> BrowserSession { - let saved = tabs.filter { $0.pinnedURL != nil }.map { tab in - var copy = tab - copy.currentURL = tab.pinnedURL! - copy.title = tab.pinnedTitle ?? tab.title - copy.isOpen = false - return copy + openingWindow(at: [url], firstTitle: title) + } + + public func openingWindow(at urls: [URL], firstTitle: String? = nil) -> BrowserSession { + var window = savedItemsOnly + let pages = urls.enumerated().map { index, url in + BrowserTab(spaceID: activeSpaceID, profileID: profileID, + title: (index == 0 ? firstTitle : nil) ?? url.host ?? url.absoluteString, currentURL: url) } - let page = BrowserTab(spaceID: activeSpaceID, profileID: profileID, - title: title ?? url.host ?? url.absoluteString, currentURL: url) - return BrowserSession(profileID: profileID, activeSpaceID: activeSpaceID, - tabs: saved + [page], selectionBySpace: [activeSpaceID: page.id], folders: folders, spaces: spaces) + window.tabs.append(contentsOf: pages) + window.selectionBySpace[activeSpaceID] = pages.first?.id + return window } } diff --git a/Sources/EarlyWeb/BrowserExtensions.swift b/Sources/EarlyWeb/BrowserExtensions.swift index 43ef213..3ad63ad 100644 --- a/Sources/EarlyWeb/BrowserExtensions.swift +++ b/Sources/EarlyWeb/BrowserExtensions.swift @@ -121,7 +121,7 @@ public final class ExtensionHost: NSObject, WKWebExtensionControllerDelegate { @ObservationIgnored public private(set) weak var focusedWindow: ExtensionWindow? /// Opens a tab for an extension; the app decides where. @ObservationIgnored public var openTab: ((URL, ExtensionWindow?, _ active: Bool) -> ExtensionTab?)? - @ObservationIgnored public var openWindow: ((URL?) -> ExtensionWindow?)? + @ObservationIgnored public var openWindow: (([URL]) throws -> ExtensionWindow?)? /// Shows an extension's popup; false when it can't be shown now. @ObservationIgnored public var presentPopup: ((WKWebExtension.Action) -> Bool)? /// An extension loaded (or loaded again): tabs showing its pages reload. @@ -245,13 +245,16 @@ public final class ExtensionHost: NSObject, WKWebExtensionControllerDelegate { } public enum ExtensionError: LocalizedError { - case missing, alreadyAdded, windowPrivacyMismatch, localFiles + case missing, alreadyAdded, windowPrivacyMismatch, localFiles, existingWindowTabs, invalidWindowURL, windowUnavailable public var errorDescription: String? { switch self { case .missing: "Its files are missing. If it came with an app, the app may have moved or been deleted." case .alreadyAdded: "This extension is already added." case .windowPrivacyMismatch: "Extensions cannot create a window in a different privacy mode. Open the appropriate window in Early first." case .localFiles: "This extension isn’t allowed to open files on this Mac. You can allow it in Settings › Extensions." + case .existingWindowTabs: "Extensions cannot move existing tabs into a new window." + case .invalidWindowURL: "A tab address requested for this window is unsupported or invalid." + case .windowUnavailable: "Early couldn’t open a window for this extension." } } } @@ -538,10 +541,12 @@ public final class ExtensionHost: NSObject, WKWebExtensionControllerDelegate { // Each host owns one regular or private session. Never silently replace // the requested mode with the host's mode, or cross their data stores. guard configuration.shouldBePrivate == isPrivate else { throw ExtensionError.windowPrivacyMismatch } + guard configuration.tabs.isEmpty else { throw ExtensionError.existingWindowTabs } guard !configuration.tabURLs.contains(where: \.isFileURL) || allowsLocalFiles(extensionContext) else { throw ExtensionError.localFiles } - return openWindow?(configuration.tabURLs.first) + guard let window = try openWindow?(configuration.tabURLs) else { throw ExtensionError.windowUnavailable } + return window } public func webExtensionController(_ controller: WKWebExtensionController, diff --git a/Sources/EarlyWeb/BrowserWebView.swift b/Sources/EarlyWeb/BrowserWebView.swift index e1b346f..2f9953c 100644 --- a/Sources/EarlyWeb/BrowserWebView.swift +++ b/Sources/EarlyWeb/BrowserWebView.swift @@ -25,12 +25,40 @@ enum UnhandledPageKey { @MainActor final class BrowserWebView: WKWebView, @preconcurrency NSSharingServicePickerDelegate { let initialPresentation = InitialPagePresentation() + private var fileDrop: (urls: [URL], expires: ContinuousClock.Instant)? override func stopLoading() { + clearFileDrop() initialPresentation.reveal() super.stopLoading() } + override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool { + noteFileDrop(from: sender.draggingPasteboard) + // Let WebKit deliver the drop to the document first, including uploads. + let accepted = super.performDragOperation(sender) + if !accepted { clearFileDrop() } + return accepted + } + + func noteFileDrop(from pasteboard: NSPasteboard, now: ContinuousClock.Instant = .now) { + let files = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? [] + fileDrop = files.isEmpty ? nil : (files, now.advanced(by: .seconds(5))) + } + + func clearFileDrop() { fileDrop = nil } + + /// WebKit reports unhandled file drops as ordinary navigation actions. + /// Take the actual native file URL once, only on the view that received it. + func takeDroppedFile(matching url: URL, now: ContinuousClock.Instant = .now) -> URL? { + guard let fileDrop else { return nil } + guard now < fileDrop.expires else { clearFileDrop(); return nil } + let path = url.standardizedFileURL.path + guard let file = fileDrop.urls.first(where: { $0.standardizedFileURL.path == path }) else { return nil } + clearFileDrop() + return file + } + /// What a trusted right-click landed on, already validated by the manager. struct ContextTarget: Equatable { var link: URL? diff --git a/Sources/EarlyWeb/DownloadStore.swift b/Sources/EarlyWeb/DownloadStore.swift index 20ba089..abec69e 100644 --- a/Sources/EarlyWeb/DownloadStore.swift +++ b/Sources/EarlyWeb/DownloadStore.swift @@ -87,6 +87,7 @@ public final class DownloadStore: NSObject, WKDownloadDelegate { @ObservationIgnored private var tracked: [ObjectIdentifier: DownloadItem] = [:] @ObservationIgnored private var reserved: Set = [] @ObservationIgnored private var automaticReservations: Set = [] + @ObservationIgnored private(set) var isRetired = false /// Private windows' files keep their quarantine, which Gatekeeper needs, /// but their addresses never reach LaunchServices' quarantine-event log. @@ -117,7 +118,7 @@ public final class DownloadStore: NSObject, WKDownloadDelegate { /// Shared by every window in the profile. Authorization and WebKit's /// adoption callback are separate turns, so both need to hold a slot. var canReserveAutomaticDownload: Bool { - activeTransferCount + automaticReservations.count < WebViewManager.automaticDownloadLimit + !isRetired && activeTransferCount + automaticReservations.count < WebViewManager.automaticDownloadLimit } func reserveAutomaticDownload() -> UUID? { @@ -153,6 +154,11 @@ public final class DownloadStore: NSObject, WKDownloadDelegate { @discardableResult func adopt(_ download: WKDownload, source: URL?, origin: URL?, destination: URL? = nil, listed: Bool = true) -> DownloadItem { let item = DownloadItem(source: source, origin: origin, requestedDestination: destination, listed: listed) + guard !isRetired else { + item.state = .cancelled + download.cancel { _ in } + return item + } attach(download, to: item) if listed { items.insert(item, at: 0) @@ -224,7 +230,7 @@ public final class DownloadStore: NSObject, WKDownloadDelegate { /// Continues a stopped or interrupted transfer into its original file. @discardableResult public func resume(_ item: DownloadItem) -> Bool { - guard item.canResume, let resumeData = item.resumeData else { return false } + guard !isRetired, item.canResume, let resumeData = item.resumeData else { return false } let configuration = WKWebViewConfiguration() if let store = dataStoreProvider?() { configuration.websiteDataStore = store } let host = WKWebView(frame: .zero, configuration: configuration) @@ -284,6 +290,14 @@ public final class DownloadStore: NSObject, WKDownloadDelegate { } } + /// The owning profile was removed or its last private window closed. + public func retire() { + isRetired = true + dataStoreProvider = nil + automaticReservations.removeAll() + cancelAll() + } + /// Removes finished, failed and cancelled rows. Files are never deleted; /// stopped transfers stay so they can resume. public func clearInactive() { @@ -419,21 +433,21 @@ public final class DownloadStore: NSObject, WKDownloadDelegate { guard let item = tracked.removeValue(forKey: ObjectIdentifier(download)) else { return } let nsError = error as NSError synchronizeProgress(item) - releaseTransfer(item) if nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled && resumeData == nil { item.state = .cancelled } else { - item.state = .failed item.failureReason = nsError.localizedDescription - if let resumeData { - // An interrupted transfer keeps its partial file for Resume. - item.resumeData = resumeData - return - } + item.resumeData = resumeData + item.state = .failed + } + if resumeData == nil || !item.listed { + // Remove our partial file, but never a destination WebKit refused + // because another process had already created it. Unlisted + // transfers have no Resume action and don't keep partial files. + discardPartialFile(of: item) + item.resumeData = nil } - // Remove our partial file, but never a destination WebKit refused - // because another process had already created it. - discardPartialFile(of: item) + releaseTransfer(item) } // MARK: Helpers diff --git a/Sources/EarlyWeb/PageDocuments.swift b/Sources/EarlyWeb/PageDocuments.swift index be00bc3..95e1758 100644 --- a/Sources/EarlyWeb/PageDocuments.swift +++ b/Sources/EarlyWeb/PageDocuments.swift @@ -177,19 +177,21 @@ extension WebViewManager { private func performDocumentSave(pageID: UUID?, to destination: URL, source: URL?, failure: String, operation: @escaping @Sendable () async throws -> Void) { + let downloads = downloads + guard !downloads.isRetired else { return } let token = UUID() let task = Task { @MainActor [weak self] in + defer { self?.documentWrites[token] = nil } + guard !downloads.isRetired else { return } do { try Task.checkCancellation() try await operation() - guard let self else { return } - self.documentWrites[token] = nil - guard !Task.isCancelled else { return } - self.downloads.recordSavedFile(at: destination, source: source) + // A successful write already renamed the file. Its profile + // owns the result even if the page or window closed meanwhile. + guard !downloads.isRetired else { return } + downloads.recordSavedFile(at: destination, source: source) } catch { - guard let self else { return } - self.documentWrites[token] = nil - if !(error is CancellationError) { self.onNotice?(failure) } + if !downloads.isRetired && !Task.isCancelled && !(error is CancellationError) { self?.onNotice?(failure) } } } documentWrites[token] = PendingDocumentWrite(pageID: pageID, task: task) @@ -363,7 +365,7 @@ extension WebViewManager { let started = startDownload(url, from: id, to: destination, listed: false) { [weak self] item in defer { try? FileManager.default.removeItem(at: folder) } guard item.state == .finished, let image = NSImage(contentsOf: destination) else { - if item.state == .failed { self?.onNotice?("The image could not be copied.") } + if item.state == .failed || item.state == .finished { self?.onNotice?("The image could not be copied.") } return } NSPasteboard.general.clearContents() diff --git a/Sources/EarlyWeb/PageNavigation.swift b/Sources/EarlyWeb/PageNavigation.swift index 1c20c02..1a659b8 100644 --- a/Sources/EarlyWeb/PageNavigation.swift +++ b/Sources/EarlyWeb/PageNavigation.swift @@ -26,7 +26,8 @@ extension WebViewManager { return } if url.isFileURL { - decideLocalNavigation(to: url, action: action, in: webView, mainFrame: mainFrame, decisionHandler: decisionHandler) + decideLocalNavigation(to: url, type: action.navigationType, in: webView, + targetIsMainFrame: action.targetFrame?.isMainFrame, decisionHandler: decisionHandler) return } if (try? input.validate(url)) != nil { @@ -99,23 +100,26 @@ extension WebViewManager { /// Local documents load only from Early's own requests (Open File, drops, /// restoration, reload), from another local page, or through history. A /// web page can never open a local file. - func decideLocalNavigation(to url: URL, action: WKNavigationAction, in webView: WKWebView, mainFrame: Bool, - decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) { + func decideLocalNavigation(to url: URL, type: WKNavigationType, in webView: WKWebView, targetIsMainFrame: Bool?, + decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) { guard (try? input.validate(url)) != nil, let id = identities[ObjectIdentifier(webView)], let page = pages[id] else { decisionHandler(.cancel) return } + let mainFrame = targetIsMainFrame ?? true let fromLocalPage = webView.url?.isFileURL == true - if page.requestedURL == url || fromLocalPage || action.navigationType == .backForward || action.navigationType == .reload { + if page.requestedURL == url || fromLocalPage || type == .backForward || type == .reload { if mainFrame { page.requestedURL = url } decisionHandler(.allow) return } decisionHandler(.cancel) cancelForPolicy(id, url: url, mainFrame: mainFrame, notice: nil) - // A file dropped on a page that does not accept it opens as a new tab, - // leaving a pinned or saved page in place. - if mainFrame, action.navigationType == .other { onOpenFiles?([url]) } + // Open an unhandled native drop in a new tab, leaving the page in place. + if targetIsMainFrame == true, type == .other, + let file = (webView as? BrowserWebView)?.takeDroppedFile(matching: url) { + onOpenFiles?([file]) + } } public func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse, @@ -197,6 +201,10 @@ extension WebViewManager { let origin = id.flatMap { pages[$0]?.view.url } let item = downloads.adopt(download, source: download.originalRequest?.url, origin: origin, destination: destination, listed: listed) + guard item.state.isActive else { + settled?(item) + return item + } if let id, let token = protect(tabID: id, reason: .download) { item.onSettled.append { [weak self] _ in self?.releaseProtection(tabID: id, token: token) } } @@ -209,7 +217,7 @@ extension WebViewManager { @discardableResult public func startDownload(_ url: URL, from tabID: UUID, to destination: URL? = nil, listed: Bool = true, settled: ((DownloadItem) -> Void)? = nil) -> Bool { - guard let page = pages[tabID], isDownloadable(url) else { return false } + guard !downloads.isRetired, let page = pages[tabID], isDownloadable(url) else { return false } // Adopt inside WebKit's callback. WebKit can ask for a destination right // after it, and a delegate set from an awaited continuation may be too // late: the download would then be dropped while it shows "Starting…". diff --git a/Sources/EarlyWeb/WebViewManager.swift b/Sources/EarlyWeb/WebViewManager.swift index 5e71d48..5f91574 100644 --- a/Sources/EarlyWeb/WebViewManager.swift +++ b/Sources/EarlyWeb/WebViewManager.swift @@ -527,6 +527,7 @@ public final class WebViewManager: NSObject, WKNavigationDelegate, WKUIDelegate func beginLoading(_ id: UUID, start: LoadStart = .request) { guard let page = pages[id] else { return } + (page.view as? BrowserWebView)?.clearFileDrop() cancelAutomaticDownloadAuthorizations(for: id) switch start { case .request: diff --git a/Tests/EarlyBrowserTests/ExtensionApplicationTests.swift b/Tests/EarlyBrowserTests/ExtensionApplicationTests.swift index a77269e..b1ec611 100644 --- a/Tests/EarlyBrowserTests/ExtensionApplicationTests.swift +++ b/Tests/EarlyBrowserTests/ExtensionApplicationTests.swift @@ -218,7 +218,7 @@ struct ExtensionApplicationTests { } @Test(arguments: [false, true]) - func extensionWindowRequestsNeverChangePrivacyMode(isPrivate: Bool) async throws { + func extensionWindowRequestsPreserveTabOrderAndProfileBoundaries(isPrivate: Bool) async throws { guard #available(macOS 15.4, *) else { return } let fixture = Fixture() await fixture.start() @@ -248,33 +248,52 @@ struct ExtensionApplicationTests { try await Task.sleep(for: .milliseconds(50)) } - func request(private requested: Bool) async throws -> [String: Any] { + func request(_ properties: [String: Any]) async throws -> [String: Any] { let result = try await view.callAsyncJavaScript(""" try { - const created = await browser.windows.create({incognito: requested, url: 'early-test://fixture/window'}); - return {incognito: created.incognito}; + const created = await browser.windows.create(properties); + const tabs = await browser.tabs.query({windowId: created.id}); + return {incognito: created.incognito, tabIds: tabs.map(tab => tab.id)}; } catch (error) { return {error: error.message}; } - """, arguments: ["requested": requested], contentWorld: .page) + """, arguments: ["properties": properties], contentWorld: .page) return try #require(result as? [String: Any]) } // A regular extension must not open an ordinary window for a private // request, nor may a private extension silently change a regular request. let count = fixture.opened.count - let denied = try await request(private: !isPrivate) + let urls = ["first", "second", "third"].map { "early-test://fixture/\($0)" } + let denied = try await request(["incognito": !isPrivate, "url": urls]) #expect((denied["error"] as? String)?.contains("privacy mode") == true) #expect(fixture.opened.count == count, "Rejected requests must not create any window") - let allowed = try await request(private: isPrivate) + let localDenied = try await request(["incognito": isPrivate, "url": urls + ["file:///unused/local.html"]]) + #expect((localDenied["error"] as? String)?.contains("allowed to open files") == true) + #expect(fixture.opened.count == count) + + let invalid = try await request(["incognito": isPrivate, "url": urls + ["ftp://fixture/unsupported"]]) + #expect(invalid["error"] != nil) + #expect(fixture.opened.count == count) + + let allowed = try await request(["incognito": isPrivate, "url": urls]) #expect(allowed["incognito"] as? Bool == isPrivate) #expect(fixture.opened.count == count + 1) let created = try #require(app.windowModel(fixture.opened.last)) + let createdTabs = created.coordinator.tabStore.tabs.filter(\.isOpen) + #expect(createdTabs.map { $0.currentURL.absoluteString } == urls) + #expect(created.coordinator.activeTabID == createdTabs.first?.id) #expect(created.isPrivate == isPrivate) #expect(created.webViews.websiteDataStore === source.webViews.websiteDataStore) if isPrivate { #expect(!created.webViews.websiteDataStore.isPersistent) #expect(created.webViews.websiteDataStore !== regular.webViews.websiteDataStore) } + let tabIDs = try #require(allowed["tabIds"] as? [Int]) + #expect(tabIDs.count == urls.count) + let move = try await request(["incognito": isPrivate, "tabId": try #require(tabIDs.first)]) + #expect((move["error"] as? String)?.contains("cannot move existing tabs") == true) + #expect(fixture.opened.count == count + 1) + #expect(created.coordinator.tabStore.tabs.filter(\.isOpen).map(\.id) == createdTabs.map(\.id)) await fixture.cleanup() } diff --git a/Tests/EarlyWebTests/BackgroundDocumentTests.swift b/Tests/EarlyWebTests/BackgroundDocumentTests.swift index 8d3112d..9d7bc0c 100644 --- a/Tests/EarlyWebTests/BackgroundDocumentTests.swift +++ b/Tests/EarlyWebTests/BackgroundDocumentTests.swift @@ -70,6 +70,47 @@ struct BackgroundDocumentTests { #expect(notice == "Could not save" && manager.downloads.items.isEmpty) #expect(try String(contentsOf: file, encoding: .utf8) == "kept") } + + @Test(arguments: [false, true]) + func aCommittedSaveBelongsToItsProfileAfterTheSourceCloses(retiringProfile: Bool) async throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent("EarlyCommittedDocument-\(UUID()).html") + defer { try? FileManager.default.removeItem(at: file) } + try Data("original".utf8).write(to: file) + let gate = Gate(), downloads = DownloadStore(), profile = UUID() + defer { Task { await gate.releaseAll() } } + let source = URL(string: "https://example.com/saved-page")! + let tab = BrowserTab(spaceID: UUID(), profileID: profile, title: "Saved page", currentURL: source) + var manager: WebViewManager? = WebViewManager(profileID: profile, ephemeral: true, + websiteDataStore: .nonPersistent(), downloads: downloads, observesMemoryPressure: false) + manager?.documentWriter = { data, destination in + try await BackgroundFileIO.write(data, to: destination) + await gate.wait() + } + _ = manager?.prepare(tab) + manager?.write(.success(Data("replacement".utf8)), to: file, source: source, failure: "Could not save", pageID: tab.id) + let write = try #require(manager?.documentWrites.values.first?.task) + try await waitUntil { await gate.started == 1 } + #expect(try String(contentsOf: file, encoding: .utf8) == "replacement") + #expect(downloads.items.isEmpty) + + manager?.discard(tabID: tab.id) + #expect(write.isCancelled) + weak let formerManager = manager + manager = nil + #expect(formerManager == nil) + if retiringProfile { downloads.retire() } + await gate.releaseAll() + await write.value + + #expect(try String(contentsOf: file, encoding: .utf8) == "replacement") + if retiringProfile { + #expect(downloads.items.isEmpty && downloads.finishedRevision == 0) + } else { + #expect(downloads.items.count == 1 && downloads.finishedRevision == 1) + let saved = try #require(downloads.items.first) + #expect(saved.state == .finished && saved.wasSaved && saved.destination == file && saved.sourceURL == source) + } + } } @Suite(.serialized) @MainActor diff --git a/Tests/EarlyWebTests/DownloadStoreTests.swift b/Tests/EarlyWebTests/DownloadStoreTests.swift index 01f267f..f9167a3 100644 --- a/Tests/EarlyWebTests/DownloadStoreTests.swift +++ b/Tests/EarlyWebTests/DownloadStoreTests.swift @@ -694,7 +694,10 @@ struct DownloadStoreTests { let server = try LocalHTTPServer(body: Data(repeating: 19, count: 400_000), initialChunk: 80_000) let fixture = Fixture() defer { server.stop(); fixture.cleanup() } - #expect(fixture.manager.startDownload(server.url, from: fixture.tab.id)) + var results: [(DownloadItem.State, String?, Data?)] = [] + #expect(fixture.manager.startDownload(server.url, from: fixture.tab.id) { + results.append(($0.state, $0.failureReason, $0.resumeData)) + }) try await waitUntil("transfer started") { fixture.store.items.first.map { $0.state == .downloading && $0.completedBytes >= 80_000 } == true } @@ -702,10 +705,41 @@ struct DownloadStoreTests { server.finishTransfers(sendingRemaining: false) try await waitUntil("network failure") { item.state == .failed } #expect(item.failureReason != nil && !fixture.store.hasActiveDownloads) + #expect(results.count == 1) + let result = try #require(results.first) + #expect(result.0 == .failed && result.1 == item.failureReason && result.2 == item.resumeData) + #expect(item.canResume) #expect(!fixture.manager.hasProtection(tabID: fixture.tab.id, reason: .download)) #expect(fixture.manager.pages[fixture.tab.id] === fixture.page, "A failed transfer must keep its source page") } + @Test(arguments: [false, true]) + func failingToCopyAnImageReportsTheFailureAndCleansUp(interruptTransfer: Bool) async throws { + let server = try LocalHTTPServer(body: Data(repeating: 1, count: 400_000), initialChunk: 80_000) + let fixture = Fixture() + defer { server.stop(); fixture.cleanup() } + let view = try #require(fixture.page.view as? BrowserWebView) + let temporary = FileManager.default.temporaryDirectory + func imageFolders() throws -> Set { + Set(try FileManager.default.contentsOfDirectory(atPath: temporary.path).filter { $0.hasPrefix("Early-Image-") }) + } + let existing = try imageFolders() + var notices: [String] = [] + fixture.manager.onNotice = { notices.append($0) } + fixture.manager.performContextAction(.copyImage(server.url), in: view) + let folder = try #require(try imageFolders().subtracting(existing).first) + let destination = temporary.appending(path: folder).appending(path: WebViewManager.imageName(for: server.url)) + try await waitUntil("copy transfer wrote a partial file") { + fixture.manager.hasProtection(tabID: fixture.tab.id, reason: .download) + && FileManager.default.fileExists(atPath: destination.path) + } + server.finishTransfers(sendingRemaining: !interruptTransfer) + try await waitUntil("copy transfer settled") { !fixture.manager.hasProtection(tabID: fixture.tab.id, reason: .download) } + #expect(notices == ["The image could not be copied."]) + #expect(fixture.store.items.isEmpty) + #expect(!FileManager.default.fileExists(atPath: destination.deletingLastPathComponent().path)) + } + @Test func cancellingAStoppedTransferDeletesOnlyItsPartialFile() async throws { let server = try LocalHTTPServer(body: Data(repeating: 7, count: 400_000), initialChunk: 80_000) let fixture = Fixture() @@ -819,8 +853,9 @@ struct DownloadStoreTests { @Test func cancellingBeforeADestinationCreatesNoFileAndClearingKeepsFinishedFiles() async throws { let fixture = Fixture() defer { fixture.cleanup() } + var states: [DownloadItem.State] = [] fixture.manager.onDownloadStarted = { [store = fixture.store] item in store.cancel(item) } - #expect(fixture.manager.startDownload(hello, from: fixture.tab.id)) + #expect(fixture.manager.startDownload(hello, from: fixture.tab.id) { states.append($0.state) }) try await waitUntil("cancelled") { fixture.store.items.first?.state == .cancelled } try await Task.sleep(for: .milliseconds(100)) let cancelled = try #require(fixture.store.items.first) @@ -829,12 +864,13 @@ struct DownloadStoreTests { #expect(((try? FileManager.default.contentsOfDirectory(atPath: fixture.directory.path)) ?? []).isEmpty) fixture.manager.onDownloadStarted = nil - #expect(fixture.manager.startDownload(hello, from: fixture.tab.id)) + #expect(fixture.manager.startDownload(hello, from: fixture.tab.id) { states.append($0.state) }) try await waitUntil("finished") { fixture.store.items.first?.state == .finished } let finished = try #require(fixture.store.items.first) #expect(fixture.store.fileExists(finished)) fixture.store.clearInactive() #expect(fixture.store.items.isEmpty) + #expect(states == [.cancelled, .finished]) #expect(FileManager.default.fileExists(atPath: try #require(finished.destination).path), "Clearing never deletes files") } diff --git a/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift b/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift index e1dccac..0802ed7 100644 --- a/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift +++ b/Tests/EarlyWebTests/LocalDocumentPolicyTests.swift @@ -45,6 +45,13 @@ struct LocalDocumentPolicyTests { return result } + private func fileDecision(_ manager: WebViewManager, _ page: BrowserPage, _ file: URL, + type: WKNavigationType = .other, mainFrame: Bool? = true) -> WKNavigationActionPolicy? { + var result: WKNavigationActionPolicy? + manager.decideLocalNavigation(to: file, type: type, in: page.view, targetIsMainFrame: mainFrame) { result = $0 } + return result + } + @Test func localFileAddressesAreValidOnlyWhenAllowedAndHostless() throws { let file = URL(filePath: "/Users/example/Documents/page.html") #expect(try input.validate(file) == file) @@ -54,21 +61,49 @@ struct LocalDocumentPolicyTests { #expect(throws: NavigationInputError.invalidAddress) { try input.validate(URL(string: "file:///")!) } } - @Test func webContentCannotOpenLocalFilesButDropsOpenANewTab() { + @Test func unprovenNavigationDoesNotOpenLocalFiles() { let (manager, _, page) = fixture() defer { manager.discardAll() } let file = URL(filePath: "/Users/example/Documents/notes.pdf") var opened: [[URL]] = [] manager.onOpenFiles = { opened.append($0) } - #expect(decision(manager, page, Action(file, type: .linkActivated)) == .cancel) - #expect(decision(manager, page, Action(file, type: .formSubmitted)) == .cancel) - #expect(opened.isEmpty, "A web page's link or form never opens a local file") - #expect(decision(manager, page, Action(file, type: .other)) == .cancel) - #expect(opened == [[file]], "An unhandled drop opens the file as a new tab instead of replacing the page") + for type: WKNavigationType in [.linkActivated, .formSubmitted, .other] { + #expect(fileDecision(manager, page, file, type: type) == .cancel) + } + #expect(opened.isEmpty) #expect(page.navigationNotice == nil && page.failure == nil) #expect(manager.contextLinkURL(href: file.absoluteString, in: page.view) == nil) } + @Test func anUnhandledDropOpensOnlyTheMatchingFileOnce() throws { + let (manager, _, page) = fixture() + defer { manager.discardAll() } + let view = try #require(page.view as? BrowserWebView) + let file = URL(filePath: "/Users/example/Documents/notes.pdf") + let other = URL(filePath: "/Users/example/Documents/other.pdf") + let pasteboard = NSPasteboard(name: .init("EarlyFileDrop-\(UUID())")) + defer { pasteboard.releaseGlobally() } + try #require(pasteboard.writeObjects([file as NSURL])) + var opened: [[URL]] = [] + manager.onOpenFiles = { opened.append($0) } + + view.noteFileDrop(from: pasteboard, now: .now.advanced(by: .seconds(-10))) + #expect(fileDecision(manager, page, file) == .cancel) + #expect(opened.isEmpty, "An expired drop can no longer open a file") + + view.noteFileDrop(from: pasteboard) + #expect(fileDecision(manager, page, other) == .cancel) + #expect(decision(manager, page, Action(file)) == .cancel) + #expect(fileDecision(manager, page, file, mainFrame: false) == .cancel) + #expect(fileDecision(manager, page, file, type: .linkActivated) == .cancel) + #expect(opened.isEmpty) + + #expect(fileDecision(manager, page, file) == .cancel) + #expect(opened == [[file]], "The file opens in a different tab") + #expect(fileDecision(manager, page, file) == .cancel) + #expect(opened == [[file]]) + } + @Test func earlysOwnLocalLoadAndHistoryAreAllowed() { let (manager, _, page) = fixture() defer { manager.discardAll() } diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index b5f09bc..97d1bb8 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -54,8 +54,9 @@ final class EarlyUITests: XCTestCase { "The import preview must publish its current selection before continuing") } - private func previewImportFile(_ file: URL, selectingAllFiles: Bool = false, in app: XCUIApplication) { - let panel = app.windows["open-panel"] + private func chooseFile(_ file: URL, selectingAllFiles: Bool = false, in app: XCUIApplication) { + // Open File uses a sheet and Import uses a window. Both share this identifier. + let panel = app.descendants(matching: .any).matching(identifier: "open-panel").firstMatch XCTAssertTrue(panel.waitForExistence(timeout: 5), app.debugDescription) app.typeKey("g", modifierFlags: [.command, .shift]) // A complete file path selects it regardless of the panel's view mode @@ -72,6 +73,19 @@ final class EarlyUITests: XCTestCase { XCTAssertTrue(panel.waitForNonExistence(timeout: 5), app.debugDescription) } + func testOpenFileLoadsTheSelectedLocalDocument() throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent("EarlyOpenFile-\(UUID()).html") + try Data("Local document

Selected local document

".utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let app = launchFreshApp() + app.typeKey(.escape, modifierFlags: []) + app.menuBars.menuBarItems["File"].click() + app.menuItems["Open File…"].click() + chooseFile(file, in: app) + XCTAssertTrue(app.webViews.staticTexts["Selected local document"].firstMatch.waitForExistence(timeout: 10)) + expectRuntime(app, tabs: 1, views: 1, created: 1) + } + func testKeyboardCommandsLeaveEmptyWindowUsable() { let app = launchFreshApp() let query = app.textFields["commandBar.query"] @@ -120,7 +134,7 @@ final class EarlyUITests: XCTestCase { let choose = app.buttons["browserImport.chooseFile"] XCTAssertTrue(choose.waitForExistence(timeout: 5)) choose.click() - previewImportFile(file, in: app) + chooseFile(file, in: app) let search = app.textFields["browserImport.search"] XCTAssertTrue(search.waitForExistence(timeout: 5)) app.buttons["Select None"].click() @@ -167,7 +181,7 @@ final class EarlyUITests: XCTestCase { let source = openBrowserImport(in: app) source.click(); app.menuItems["Safari"].click() app.buttons["browserImport.chooseFile"].click() - previewImportFile(directory.appendingPathComponent("Bookmarks.html"), selectingAllFiles: true, in: app) + chooseFile(directory.appendingPathComponent("Bookmarks.html"), selectingAllFiles: true, in: app) XCTAssertTrue(app.buttons["Select All"].waitForExistence(timeout: 5)); app.buttons["Select All"].click() waitForBrowserImportSelection(3, in: app) app.buttons["browserImport.continue"].click(); app.buttons["browserImport.continue"].click()