From a80ccb9560451a29571cdbac6d48c50ea54fb2e9 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Sun, 22 Nov 2026 07:45:59 +0530 Subject: [PATCH 1/3] Keep page translation tied to the current document and text Bind each system session to the request, page instance, document and navigation that created it. Scope DOM updates and restoration to the owning run and preserve text the page has edited or replaced. Walk the rendered page and open shadow roots within node and character budgets. Cover late delivery, cancellation, site mutations, hidden content and the native translation UI. --- Sources/Early/BrowserWindowModel.swift | 2 +- Sources/Early/PageTranslationSupport.swift | 64 ++++---- Sources/EarlyWeb/BrowserPage.swift | 7 +- Sources/EarlyWeb/PageTranslation.swift | 145 ++++++++++++------ .../PageToolsActionTests.swift | 70 +++++++++ .../EarlyWebTests/PageTranslationTests.swift | 139 +++++++++++++++++ UITests/EarlyUITests.swift | 48 ++++++ 7 files changed, 397 insertions(+), 78 deletions(-) diff --git a/Sources/Early/BrowserWindowModel.swift b/Sources/Early/BrowserWindowModel.swift index ff59b15..3280562 100644 --- a/Sources/Early/BrowserWindowModel.swift +++ b/Sources/Early/BrowserWindowModel.swift @@ -114,7 +114,7 @@ final class BrowserWindowModel { /// Tabs whose language Apple's Translation can turn into the user's. var translationOffers: [UUID: TranslationOffer] = [:] /// The translation waiting for (or running in) the window's session. - var translationRequest: TranslationRequest? + var pendingTranslation: TranslationRequest? /// Command-F focuses the focused pane's find field, even if already open. var findFocusRequest = 0 /// Early's download icon flying from the clicked page point to the button. diff --git a/Sources/Early/PageTranslationSupport.swift b/Sources/Early/PageTranslationSupport.swift index bbe21e3..1db93da 100644 --- a/Sources/Early/PageTranslationSupport.swift +++ b/Sources/Early/PageTranslationSupport.swift @@ -25,6 +25,7 @@ struct TranslationOffer: Equatable { struct TranslationRequest: Equatable, Identifiable { let id = UUID() let offer: TranslationOffer + let target: PageTranslationTarget } @MainActor @@ -42,6 +43,7 @@ extension BrowserWindowModel { func updateTranslationOffer(_ id: UUID, language: String?) { translationOffers[id] = nil + if pendingTranslation?.offer.tabID == id, translationRequest == nil { pendingTranslation = nil } let target = Self.translationTarget guard let language, Self.needsTranslation(from: language, to: target) else { return } guard #available(macOS 15.0, *) else { return } @@ -53,6 +55,14 @@ extension BrowserWindowModel { } } + /// The host and its menus observe the same request. Closing the tab or + /// starting a navigation withdraws it even before the system replies. + var translationRequest: TranslationRequest? { + guard let request = pendingTranslation, + webViews.translationTarget(for: request.offer.tabID) == request.target else { return nil } + return request + } + /// The menu title for this tab, or nil when Translate would not work. func translationTitle(for id: UUID) -> String? { guard let page = webViews.pages[id] else { return nil } @@ -64,20 +74,25 @@ extension BrowserWindowModel { func toggleTranslation(_ id: UUID) { guard let page = webViews.pages[id] else { return } if page.translation.isActive || translationRequest?.offer.tabID == id { - if translationRequest?.offer.tabID == id { translationRequest = nil } + if pendingTranslation?.offer.tabID == id { pendingTranslation = nil } webViews.showOriginal(id) return } - guard let offer = translationOffers[id], webViews.canTranslate(id) else { return } + guard let offer = translationOffers[id], let target = webViews.translationTarget(for: id) else { return } + if let previous = translationRequest { webViews.showOriginal(previous.offer.tabID) } webViews.showOriginal(id) // Clears an earlier failure. - translationRequest = TranslationRequest(offer: offer) + pendingTranslation = TranslationRequest(offer: offer, target: target) + } + + func runTranslation(_ request: TranslationRequest, using translate: PageTextTranslator) async { + guard pendingTranslation?.id == request.id, webViews.pages[request.offer.tabID]?.translation.isActive != true else { return } + defer { finishTranslationRequest(request) } + guard translationRequest == request, !Task.isCancelled else { return } + await webViews.translatePage(request.offer.tabID, using: translate) } - @available(macOS 15.0, *) - func runTranslation(_ request: TranslationRequest, session: TranslationSession) async { - defer { if translationRequest?.id == request.id { translationRequest = nil } } - let translator = SessionTranslator(session: session) - await webViews.translatePage(request.offer.tabID) { texts in try await translator.translate(texts) } + fileprivate func finishTranslationRequest(_ request: TranslationRequest) { + if pendingTranslation?.id == request.id { pendingTranslation = nil } } } @@ -105,29 +120,20 @@ private struct SessionTranslator: @unchecked Sendable { @available(macOS 15.0, *) struct PageTranslationHost: View { @Bindable var model: BrowserWindowModel - @State private var configuration: TranslationSession.Configuration? - @State private var running: TranslationRequest? var body: some View { - Color.clear - .frame(width: 0, height: 0) - .accessibilityHidden(true) - .onChange(of: model.translationRequest) { _, request in start(request) } - .translationTask(configuration) { session in - guard let running else { return } - await model.runTranslation(running, session: session) - } - } - - private func start(_ request: TranslationRequest?) { - guard let request else { return } - running = request - let source = Locale.Language(identifier: request.offer.source) - let target = Locale.Language(identifier: request.offer.target) - if configuration?.source == source && configuration?.target == target { - configuration?.invalidate() - } else { - configuration = TranslationSession.Configuration(source: source, target: target) + if let request = model.translationRequest { + Color.clear + .frame(width: 0, height: 0) + .accessibilityHidden(true) + .translationTask(source: Locale.Language(identifier: request.offer.source), + target: Locale.Language(identifier: request.offer.target)) { session in + let translator = SessionTranslator(session: session) + await model.runTranslation(request) { try await translator.translate($0) } + } + // Even two requests for the same language pair own separate system tasks. + .onDisappear { model.finishTranslationRequest(request) } + .id(request.id) } } } diff --git a/Sources/EarlyWeb/BrowserPage.swift b/Sources/EarlyWeb/BrowserPage.swift index 7d8e0b1..dc8315a 100644 --- a/Sources/EarlyWeb/BrowserPage.swift +++ b/Sources/EarlyWeb/BrowserPage.swift @@ -65,7 +65,7 @@ public final class BrowserPage { /// The page's language (BCP 47), detected from its text after loading. public internal(set) var language: String? public internal(set) var translation = PageTranslationPhase.original - /// The running translation; an older one, or its error, changes nothing. + /// The run that owns the collected text, including while showing its translation. var translationRun: UUID? /// The connection's trust, from WebKit's public secure-content state. public internal(set) var security = PageSecurity.none @@ -100,10 +100,11 @@ public final class BrowserPage { var reportedURL: URL? var reportedTitle: String? var reportedDocumentID: UUID? - /// The committed document eligible to contribute a history visit or title. - public var historyDocumentID: UUID? { + /// The current committed document, while its metadata and text can be used. + var currentDocumentID: UUID? { !awaitsNavigationCommit && failure == nil && !processTerminated ? documentID : nil } + public var historyDocumentID: UUID? { currentDocumentID } var navigationGeneration = UUID() var faviconRefresh: UUID? var activeNavigation: ObjectIdentifier? diff --git a/Sources/EarlyWeb/PageTranslation.swift b/Sources/EarlyWeb/PageTranslation.swift index c56e114..c98ec8c 100644 --- a/Sources/EarlyWeb/PageTranslation.swift +++ b/Sources/EarlyWeb/PageTranslation.swift @@ -21,17 +21,29 @@ public enum PageTranslationPhase: Equatable, Sendable { /// Translation; tests supply a stand-in. Page text goes nowhere else. public typealias PageTextTranslator = @MainActor ([String]) async throws -> [String] +/// The live page and navigation that requested an on-device translation session. +public struct PageTranslationTarget: Equatable, Sendable { + fileprivate let page: UUID + fileprivate let document: UUID + fileprivate let navigation: UUID +} + /// Translation replaces the text of the page's own text nodes from an isolated /// world, keeping each node's surrounding whitespace, and can restore it. @MainActor extension WebViewManager { static let translationWorld = WKContentWorld.world(name: "Early.Translate") static let translationBatchSize = 40 - static let translationLimits = (nodes: 3000, characters: 100_000) + static let translationLimits = (nodes: 3000, characters: 100_000, visited: 30_000) public func canTranslate(_ id: UUID) -> Bool { - guard let page = pages[id], page.view.url != nil, !page.isReaderShown else { return false } - return page.language != nil + translationTarget(for: id) != nil + } + + public func translationTarget(for id: UUID) -> PageTranslationTarget? { + guard let page = pages[id], let document = page.currentDocumentID, page.view.url != nil, + page.language != nil, !page.isReaderShown else { return nil } + return PageTranslationTarget(page: page.instanceID, document: document, navigation: page.navigationGeneration) } /// The page's language from its own visible text, with its `lang` @@ -67,7 +79,7 @@ extension WebViewManager { /// leaving the page stops it; a failure restores the original text. @discardableResult public func translatePage(_ id: UUID, using translate: PageTextTranslator) async -> Bool { - guard canTranslate(id), let page = pages[id], !page.translation.isActive else { return false } + guard !Task.isCancelled, canTranslate(id), let page = pages[id], !page.translation.isActive else { return false } let generation = page.navigationGeneration // Translate, Show Original, Translate again: the first run's batches // and errors must never reach the second's text. @@ -75,13 +87,19 @@ extension WebViewManager { page.translationRun = run page.translation = .translating(completed: 0, total: 0) func current() -> Bool { - pages[id] === page && page.navigationGeneration == generation && page.translationRun == run && page.translation.isActive + !Task.isCancelled && pages[id] === page && page.navigationGeneration == generation + && page.translationRun == run && page.translation.isActive + } + defer { + if pages[id] === page, page.translationRun == run, case .translating = page.translation { showOriginal(id) } } let collected = try? await page.view.callAsyncJavaScript(Self.translationCollect, - arguments: ["maxNodes": Self.translationLimits.nodes, "maxCharacters": Self.translationLimits.characters], + arguments: ["runID": run.uuidString, "maxNodes": Self.translationLimits.nodes, "maxCharacters": Self.translationLimits.characters, + "maxVisited": Self.translationLimits.visited], in: nil, contentWorld: Self.translationWorld) guard current() else { return false } guard let texts = collected as? [String], !texts.isEmpty else { + page.translationRun = nil page.translation = .failed("This page has no text to translate.") return false } @@ -94,7 +112,7 @@ extension WebViewManager { guard current() else { return false } guard translated.count == batch.count else { throw TranslationMismatch() } _ = try await page.view.callAsyncJavaScript(Self.translationApply, - arguments: ["start": start, "texts": translated], in: nil, contentWorld: Self.translationWorld) + arguments: ["runID": run.uuidString, "start": start, "texts": translated], in: nil, contentWorld: Self.translationWorld) guard current() else { return false } start += batch.count page.translation = .translating(completed: start, total: texts.count) @@ -102,10 +120,10 @@ extension WebViewManager { } catch { guard current() else { return false } restoreOriginalText(page) + page.translationRun = nil page.translation = .failed(error is TranslationMismatch ? "The translation was incomplete." : error.localizedDescription) return false } - page.translationRun = nil page.translation = .translated return true } @@ -119,7 +137,8 @@ extension WebViewManager { } private func restoreOriginalText(_ page: BrowserPage) { - page.view.callAsyncJavaScript(Self.translationRestore, arguments: [:], in: nil, in: Self.translationWorld) { _ in } + guard let run = page.translationRun else { return } + page.view.callAsyncJavaScript(Self.translationRestore, arguments: ["runID": run.uuidString], in: nil, in: Self.translationWorld) { _ in } } /// A new document starts untranslated, with its language detected again. @@ -136,55 +155,91 @@ extension WebViewManager { private struct TranslationMismatch: Error {} static let translationCollect = #""" - const skipped = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'TEXTAREA', 'INPUT', 'SELECT', 'OPTION', - 'CODE', 'PRE', 'KBD', 'SAMP', 'VAR', 'SVG', 'MATH', 'IFRAME', 'OBJECT', 'EMBED', 'CANVAS', 'AUDIO', 'VIDEO']); - const state = window.__earlyTranslation || (window.__earlyTranslation = { nodes: [], originals: [] }); - // Always start from the original text. - state.nodes.forEach((node, index) => { if (node.isConnected) node.data = state.originals[index]; }); - state.nodes = []; - state.originals = []; - let characters = 0, full = false; - const visit = root => { - const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, { - acceptNode(node) { - if (node.nodeType !== Node.ELEMENT_NODE) return NodeFilter.FILTER_ACCEPT; - if (skipped.has(node.tagName) || node.getAttribute('translate') === 'no' - || node.classList.contains('notranslate') || node.isContentEditable) return NodeFilter.FILTER_REJECT; - return node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; + window.__earlyTranslation?.restore(); + const entries = [], texts = []; + window.__earlyTranslation = { runID, entries, restore() { + for (const entry of entries) { + if (entry && entry.written !== null && entry.node.isConnected && entry.node.parentNode === entry.parent + && entry.node.ownerDocument === document + && entry.node.data === entry.written) entry.node.data = entry.original; + } + entries.length = 0; + }}; + const skipped = new Set(['head', 'script', 'style', 'noscript', 'template', 'textarea', 'input', 'select', 'option', + 'code', 'pre', 'kbd', 'samp', 'var', 'svg', 'math', 'iframe', 'object', 'embed', 'canvas', 'audio', 'video']); + let visited = 0, characters = 0; + function* slotChildren(slot) { + const host = slot.getRootNode().host; + if (!host || host.childNodes.length <= maxVisited - visited) { + const assigned = slot.assignedNodes(); + yield* (assigned.length ? assigned : slot.childNodes); + return; + } + // Avoid materializing an oversized assignment list. Charge the light + // children we inspect to the same traversal budget. + let found = false; + for (const child of host.childNodes) { + if (++visited >= maxVisited) return; + if (child.assignedSlot === slot) { found = true; yield child; } + } + if (!found) yield* slot.childNodes; + } + const stack = [{ children: document.childNodes.values(), visible: true }]; + while (stack.length && visited < maxVisited && entries.length < maxNodes && characters < maxCharacters) { + const level = stack[stack.length - 1], next = level.children.next(); + if (next.done) { stack.pop(); continue; } + const node = next.value; + visited++; + if (level.summaryOnly) { + if (node.localName !== 'summary') continue; + stack.pop(); // Only the first direct summary is rendered in closed details. + } + if (node.nodeType === Node.TEXT_NODE) { + if (!level.visible || node.length > maxCharacters) continue; + const original = node.data, text = original.trim(); + if (text.length <= maxCharacters - characters && /\p{L}/u.test(text)) { + entries.push({ node, parent: node.parentNode, original, written: null }); + texts.push(text); + characters += text.length; } - }); - for (let node = walker.nextNode(); node && !full; node = walker.nextNode()) { - if (node.nodeType === Node.ELEMENT_NODE) { visit(node.shadowRoot); continue; } - const text = node.data.trim(); - if (!text || !/\p{L}/u.test(text)) continue; - if (state.nodes.length >= maxNodes || characters + text.length > maxCharacters) { full = true; break; } - state.nodes.push(node); - state.originals.push(node.data); - characters += text.length; + continue; } - }; - if (document.body) visit(document.body); - return state.nodes.map(node => node.data.trim()); + if (node.nodeType !== Node.ELEMENT_NODE || skipped.has(node.localName) || node.hasAttribute('hidden') + || node.getAttribute('translate')?.toLowerCase() === 'no' || node.classList.contains('notranslate') + || node.isContentEditable) continue; + const style = getComputedStyle(node); + if (style.display === 'none' || style.contentVisibility === 'hidden' || style.opacity === '0') continue; + // Descendants can override inherited visibility. Their own styles decide. + const visible = style.visibility !== 'hidden' && style.visibility !== 'collapse'; + const root = node.shadowRoot || node; + const children = node.localName === 'slot' ? slotChildren(node) + : (visible ? root.childNodes : root.children)[Symbol.iterator](); + stack.push({ children, visible, summaryOnly: node.localName === 'details' && !node.open }); + } + return texts; """# static let translationApply = #""" const state = window.__earlyTranslation; - if (!state) return 0; + if (state?.runID !== runID) return 0; + const entries = state.entries; texts.forEach((text, offset) => { - const node = state.nodes[start + offset], original = state.originals[start + offset]; - if (!node || !node.isConnected || typeof text !== 'string') return; - node.data = original.match(/^\s*/)[0] + text + original.match(/\s*$/)[0]; + const index = start + offset, entry = entries[index]; + if (!entry || typeof text !== 'string') return; + const { node, original } = entry; + if (!node.isConnected || node.parentNode !== entry.parent || node.ownerDocument !== document || node.data !== original) { + entries[index] = null; + return; + } + entry.written = original.match(/^\s*/)[0] + text + original.match(/\s*$/)[0]; + node.data = entry.written; }); return texts.length; """# static let translationRestore = #""" const state = window.__earlyTranslation; - if (state) { - state.nodes.forEach((node, index) => { if (node.isConnected) node.data = state.originals[index]; }); - state.nodes = []; - state.originals = []; - } + if (state?.runID === runID) state.restore(); return true; """# } diff --git a/Tests/EarlyBrowserTests/PageToolsActionTests.swift b/Tests/EarlyBrowserTests/PageToolsActionTests.swift index dd7c41d..b327ee9 100644 --- a/Tests/EarlyBrowserTests/PageToolsActionTests.swift +++ b/Tests/EarlyBrowserTests/PageToolsActionTests.swift @@ -210,6 +210,76 @@ struct PageToolsActionTests { #expect(model.translationTitle(for: id) == nil && !model.canPerform(.toggleTranslation)) } + enum BeforeSession: CaseIterable { case unchanged, cancelledTask, showOriginal, replaceRequest, anotherTab, navigation, provisional, route, reopen } + + @Test(arguments: BeforeSession.allCases) + func delayedTranslationSessionBelongsToItsOriginalRequest(change: BeforeSession) async throws { + let fixture = Fixture(), model = fixture.model + defer { fixture.cleanup() } + let address = URL(string: "early-test://fixture/article?lang=fr")! + model.webViews.onPageLanguage = nil // Supply the language-pair availability locally. + try #require(model.openLocations([address])) + let id = try #require(model.coordinator.focusedTabID) + try await fixture.waitForLoad(id) + let page = try #require(model.webViews.pages[id]) + try await fixture.waitUntil("French article") { page.language == "fr" } + let document = try #require(page.historyDocumentID) + model.translationOffers[id] = TranslationOffer(tabID: id, source: "fr", target: "en") + model.toggleTranslation(id) + let request = try #require(model.translationRequest) + var replacement: TranslationRequest? + switch change { + case .unchanged, .cancelledTask: break + case .showOriginal: model.toggleTranslation(id) + case .replaceRequest: + model.toggleTranslation(id) + model.toggleTranslation(id) + replacement = try #require(model.translationRequest) + #expect(replacement?.id != request.id) + case .anotherTab: + try #require(model.openLocations([address])) + let other = try #require(model.coordinator.focusedTabID) + try #require(other != id) + try await fixture.waitUntil("other French article") { model.webViews.pages[other]?.language == "fr" } + model.translationOffers[other] = TranslationOffer(tabID: other, source: "fr", target: "en") + model.toggleTranslation(other) + replacement = try #require(model.translationRequest) + case .navigation, .provisional: + model.webViews.reload(id) + if change == .navigation { + try await fixture.waitUntil("reloaded French article") { + page.historyDocumentID != nil && page.historyDocumentID != document && page.language == "fr" + } + } + case .route: + let generation = page.navigationGeneration + _ = try await page.view.evaluateJavaScript("history.pushState({}, '', '#part')") + try await fixture.waitUntil("new route") { page.navigationGeneration != generation } + #expect(page.historyDocumentID == document) + case .reopen: + model.closeTab(id) + model.reopenClosedTab(id) + try await fixture.waitForLoad(id) + try await fixture.waitUntil("reopened French article") { model.webViews.pages[id]?.language == "fr" } + #expect(model.webViews.pages[id]?.instanceID != page.instanceID) + } + if change != .unchanged && change != .cancelledTask { #expect(model.translationRequest == replacement) } + var calls = 0 + let delivery = Task { + if change == .cancelledTask { withUnsafeCurrentTask { $0?.cancel() } } + await model.runTranslation(request) { texts in calls += 1; return texts.map { "[old] " + $0 } } + } + await delivery.value + #expect((calls > 0) == (change == .unchanged)) + #expect(model.translationRequest == replacement) + if let replacement { + await model.runTranslation(replacement) { texts in texts.map { "[current] " + $0 } } + let current = try #require(model.webViews.pages[replacement.offer.tabID]) + #expect(current.translation == .translated) + #expect(try await current.view.evaluateJavaScript("document.body.innerText.includes('[current]')") as? Bool == true) + } + } + @Test func backAndForwardListsJumpWithinTheFocusedTabAndAClickStillNavigates() async throws { let fixture = Fixture() defer { fixture.cleanup() } diff --git a/Tests/EarlyWebTests/PageTranslationTests.swift b/Tests/EarlyWebTests/PageTranslationTests.swift index 30df534..c75b2d9 100644 --- a/Tests/EarlyWebTests/PageTranslationTests.swift +++ b/Tests/EarlyWebTests/PageTranslationTests.swift @@ -116,11 +116,19 @@ struct PageTranslationTests { } } try await fixture.waitUntil("first run waiting") { releaseFirst != nil } + let page = try fixture.page(tab) + let oldRun = try #require(page.translationRun) manager.showOriginal(tab.id) let second = await manager.translatePage(tab.id) { texts in texts.map { "[new] " + $0 } } #expect(second && manager.pages[tab.id]?.translation == .translated) releaseFirst?.resume() #expect(await first.value == false, "The earlier run stops") + // WebKit commands already issued for the old run can also arrive late. + _ = try await page.view.callAsyncJavaScript(WebViewManager.translationRestore, + arguments: ["runID": oldRun.uuidString], in: nil, contentWorld: WebViewManager.translationWorld) + _ = try await page.view.callAsyncJavaScript(WebViewManager.translationApply, + arguments: ["runID": oldRun.uuidString, "start": 0, "texts": ["[old]"]], + in: nil, contentWorld: WebViewManager.translationWorld) let text = try await fixture.evaluate("document.getElementById('one').textContent", in: tab) as? String ?? "" #expect(text.contains("[new]") && !text.contains("[old]"), "\(text)") #expect(manager.pages[tab.id]?.translation == .translated) @@ -144,6 +152,137 @@ struct PageTranslationTests { #expect(after.contains("[new]"), "\(after)") } + @Test func cancellingTheSystemTaskRestoresAPartialTranslationAndKeepsSiteEdits() async throws { + let paragraphs = (0...WebViewManager.translationBatchSize).map { "

Article \($0)

" }.joined() + let fixture = PageToolFixture(pages: ["article": "\(paragraphs)"]) + defer { fixture.cleanup() } + let tab = try await fixture.open("article"), page = try fixture.page(tab) + try await fixture.waitUntil("language detected") { page.language != nil } + var lastBatch: CheckedContinuation? + defer { lastBatch?.resume() } + let task = Task { + await fixture.manager.translatePage(tab.id) { texts in + if texts.count == 1 { await withCheckedContinuation { lastBatch = $0 } } + return texts.map { "[en] " + $0 } + } + } + try await fixture.waitUntil("last batch suspended") { lastBatch != nil } + #expect(try await fixture.evaluate("document.querySelector('p').textContent", in: tab) as? String == "[en] Article 0") + _ = try await fixture.evaluate("document.querySelector('p').firstChild.data = 'Updated'", in: tab) + task.cancel() + lastBatch?.resume() + lastBatch = nil + #expect(await task.value == false && page.translation == .original) + #expect(try await fixture.evaluate("document.querySelector('p').textContent", in: tab) as? String == "Updated") + #expect(try await fixture.evaluate("document.body.textContent.includes('[en]')", in: tab) as? Bool == false) + } + + @Test(arguments: [false, true]) + func siteEditsSurviveApplyingRestoringAndCollectingAgain(recollect: Bool) async throws { + let html = """ +

Avant

Après

+

Remplacé

Détaché

Stable

+
Déplacé
+ """ + let fixture = PageToolFixture(pages: ["page": html]) + defer { fixture.cleanup() } + let tab = try await fixture.open("page"), page = try fixture.page(tab) + try await fixture.waitUntil("language detected") { page.language != nil } + let result = await fixture.manager.translatePage(tab.id) { texts in + _ = try await fixture.evaluate(""" + before.firstChild.data = 'Édition avant'; + replaced.replaceChildren(document.createTextNode('Nouveau')); + window.removedText = detached.firstChild; + detached.replaceChildren(); + destination.append(moved.firstChild); + """, in: tab) + return texts.map { "[en] " + $0 } + } + #expect(result) + let read = "[before.textContent, after.textContent, replaced.textContent, removedText.data, stable.textContent]" + #expect(try await fixture.evaluate(read, in: tab) as? [String] == + ["Édition avant", "[en] Après", "Nouveau", "Détaché", " [en] Stable "]) + #expect(try await fixture.evaluate("destination.textContent", in: tab) as? String == "Déplacé") + _ = try await fixture.evaluate("after.firstChild.data = 'Site updated'; detached.append(removedText);", in: tab) + if recollect { + let texts = try await page.view.callAsyncJavaScript(WebViewManager.translationCollect, + arguments: ["runID": "recollection", "maxNodes": 100, "maxCharacters": 1_000, "maxVisited": 500], + in: nil, contentWorld: WebViewManager.translationWorld) + #expect(texts as? [String] == ["Édition avant", "Site updated", "Nouveau", "Détaché", "Stable", "Déplacé"]) + } else { fixture.manager.showOriginal(tab.id) } + #expect(try await fixture.evaluate(read, in: tab) as? [String] == + ["Édition avant", "Site updated", "Nouveau", "Détaché", " Stable "]) + } + + @Test(arguments: [false, true]) + func hiddenContentLeavesTheNodeAndCharacterQuotasForRenderedText(manyNodes: Bool) async throws { + let pageHTML = """ + +
+

CSS hidden

Transparent

+

Skipped content

+
InvisibleVisible override
+
SummaryClosed details
+
Editable
Code
Keep
+
SlottedHidden slotUnassigned
+
Visible article
+ + """ + let fixture = PageToolFixture(pages: ["page": pageHTML]) + defer { fixture.cleanup() } + let tab = try await fixture.open("page"), page = try fixture.page(tab) + try await fixture.waitUntil("language detected") { page.language != nil } + var sent: [String] = [] + #expect(await fixture.manager.translatePage(tab.id) { texts in sent += texts; return texts.map { "[en] " + $0 } }) + #expect(sent == ["Visible override", "Summary", "Shadow text", "Slotted", "Shown fallback", "Visible article"]) + #expect(try await fixture.evaluate("document.querySelector('main').textContent", in: tab) as? String == "[en] Visible article") + } + + @Test func translationTraversalStopsAtItsWorkLimitAndSkipsHiddenSubtrees() async throws { + let pageHTML = """ +
Visible article
+ + """ + let fixture = PageToolFixture(pages: ["page": pageHTML]) + defer { fixture.cleanup() } + let tab = try await fixture.open("page"), page = try fixture.page(tab) + func collect(budget: Int) async throws -> [String]? { + try await page.view.callAsyncJavaScript(WebViewManager.translationCollect, + arguments: ["runID": "quota", "maxNodes": 10, "maxCharacters": 100, "maxVisited": budget], + in: nil, contentWorld: WebViewManager.translationWorld) as? [String] + } + #expect(try await collect(budget: 40) == []) + #expect(try await collect(budget: 110) == ["Visible article"]) + + _ = try await fixture.evaluate(""" + for (let i = 0; i < 40; i++) document.querySelector('main').append(document.createTextNode('More text')); + """, in: tab) + let counts = try await page.view.callAsyncJavaScript(""" + const original = window.getComputedStyle, article = document.querySelector('main'); + let articleReads = 0, hiddenChildReads = 0; + window.getComputedStyle = function(element) { + if (element === article) articleReads++; + if (element.parentElement?.id === 'hiddenTree') hiddenChildReads++; + return original.call(window, element); + }; + try { + const texts = (() => { \(WebViewManager.translationCollect) })(); + return [texts.length, articleReads, hiddenChildReads]; + } finally { window.getComputedStyle = original; } + """, arguments: ["runID": "style-count", "maxNodes": 100, "maxCharacters": 1_000, "maxVisited": 200], + in: nil, contentWorld: WebViewManager.translationWorld) + #expect(counts as? [Int] == [41, 1, 0]) + } + @Test func thePageMenuOffersTranslateOnlyWithATitleFromTheWindow() async throws { let fixture = PageToolFixture(pages: ["french": Self.french]) defer { fixture.cleanup() } diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index a7f8cde..cee8826 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 import AppKit +import Translation import XCTest @MainActor @@ -2717,6 +2718,53 @@ final class EarlyUITests: XCTestCase { expectRuntime(app, tabs: 1, views: 1, created: 1) } + func testSystemTranslationRestoresTheArticleOrDismissesTheLanguageDownload() async throws { + guard #available(macOS 15.0, *) else { throw XCTSkip("System translation requires macOS 15.") } + let preferred = Locale.Language(identifier: Locale.preferredLanguages.first ?? "en") + let target = Locale.Language(identifier: preferred.languageCode?.identifier ?? "en") + let source = Locale.Language(identifier: "fr") + let availability = await LanguageAvailability().status(from: source, to: target) + guard source.languageCode != target.languageCode, availability != .unsupported else { + throw XCTSkip("This Mac does not offer translation for the French fixture into its preferred language.") + } + let app = launchFreshApp() + defer { app.terminate() } + navigate(app, to: "early-test://fixture/article?lang=fr") + expectPage(app, "Article") + let french = app.webViews.staticTexts.matching(NSPredicate( + format: "label CONTAINS %@ OR value CONTAINS %@", "Le navigateur reste calme", "Le navigateur reste calme")).firstMatch + XCTAssertTrue(french.waitForExistence(timeout: 5)) + app.buttons["address.siteControls"].click() + let translate = app.buttons["siteControls.translate"] + XCTAssertTrue(translate.waitForExistence(timeout: 15)) + translate.click() + + let translated = app.descendants(matching: .any).matching(NSPredicate( + format: "identifier == %@ AND label BEGINSWITH %@", "translation.badge", "Translated")).firstMatch + let modals = [app.sheets.firstMatch, app.alerts.firstMatch, app.dialogs.firstMatch] + let reply = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + translated.exists || modals.contains { $0.exists } + }, object: nil) + await fulfillment(of: [reply], timeout: 30) + if translated.exists { + XCTAssertFalse(french.exists) + let original = app.buttons["translation.original"] + XCTAssertTrue(original.waitForExistence(timeout: 5)) + original.click() + XCTAssertTrue(original.waitForNonExistence(timeout: 5)) + } else if let prompt = modals.first(where: { $0.exists }) { + // A runner without both models can exercise the real cancellation + // path without accepting a download. + let cancel = prompt.buttons["Cancel"] + if cancel.exists { cancel.click() } else { app.typeKey(.escape, modifierFlags: []) } + XCTAssertTrue(prompt.waitForNonExistence(timeout: 10)) + } else { XCTFail("The system translation ended without a result or a language prompt."); return } + XCTAssertTrue(french.waitForExistence(timeout: 10)) + navigate(app, to: "early-test://fixture/two") + expectPage(app, "Two") + XCTAssertFalse(app.descendants(matching: .any)["translation.badge"].exists) + } + func testBackListJumpsToAnEarlierPageAndClearRemovesTodayTabs() { let app = launchFreshApp() navigate(app, to: "early-test://fixture/one") From 30b99ee454c83890170a8cd6c8e8060bcb8b2f23 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Sun, 22 Nov 2026 12:45:01 +0530 Subject: [PATCH 2/3] Fix the translation UI test hang and split-menu selection --- .github/WORKFLOWS.md | 3 ++ .github/workflows/tests.yml | 9 +++++- UITests/EarlyUITests.swift | 58 ++++++++++++++++++------------------- 3 files changed, 40 insertions(+), 30 deletions(-) diff --git a/.github/WORKFLOWS.md b/.github/WORKFLOWS.md index 726371c..f7f652d 100644 --- a/.github/WORKFLOWS.md +++ b/.github/WORKFLOWS.md @@ -11,6 +11,9 @@ It uses macOS 26 runners and Xcode 26.6. One job runs `swift test --no-parallel`; four separate jobs run native UI tests. Xcode discovers the enabled UI tests, and the sorted identifiers are interleaved across the four shards. Each shard executes serially to avoid competing mouse/keyboard input. +The Actions log shows each test starting and finishing. XCTest gives each test +five minutes before recording a timeout. The `ui-results-N` artifact for shard +`N` contains the full `ui.log` trace and the Xcode result bundle. The workflow has read-only repository permissions and disables persisted checkout credentials. New commits cancel obsolete test runs for the same ref. Logs, diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 35a2ff8..c37ead6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -82,12 +82,14 @@ jobs: ) # Build and discover the complete suite without executing test methods. + echo "::group::Build and discover UI tests" xcodebuild "${xcode_args[@]}" \ -enumerate-tests \ -test-enumeration-style flat \ -test-enumeration-format json \ -test-enumeration-output-path build/TestResults/discovered-tests.json \ test 2>&1 | tee build/TestResults/discovery.log + echo "::endgroup::" # Interleave the sorted test IDs so every enabled test runs exactly once. jq -er --argjson shard "$UI_SHARD" --argjson count "$UI_SHARD_COUNT" ' @@ -109,9 +111,14 @@ jobs: printf '%s\n' "${test_args[@]}" # UI automation stays serial on each Mac to avoid input/focus conflicts. + # Let XCTest record a hung case and continue before the job times out. + # Stream case results to Actions and retain the full trace in ui.log. xcodebuild "${xcode_args[@]}" "${test_args[@]}" \ + -test-timeouts-enabled YES -default-test-execution-time-allowance 300 \ -resultBundlePath "build/TestResults/UI-$UI_SHARD.xcresult" \ - test-without-building 2>&1 | tee build/TestResults/ui.log + test-without-building 2>&1 | tee build/TestResults/ui.log | awk ' + /^Test (Case|Suite) |^[[:space:]]*Executed |^Testing |^Failing tests:|: error: |^error:|^xcodebuild:|^\*\* TEST/ { print; fflush() } + ' - name: Upload UI results if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index cee8826..0462651 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -1,7 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 import AppKit -import Translation import XCTest @MainActor @@ -11,11 +10,11 @@ final class EarlyUITests: XCTestCase { continueAfterFailure = false } - private func launchFreshApp(appearance: String = "dark") -> XCUIApplication { + private func launchFreshApp(appearance: String = "dark", arguments: [String] = []) -> XCUIApplication { let app = XCUIApplication() app.launchEnvironment["EARLY_TEST_DEFAULTS_SUITE"] = "local.early.tests.\(UUID().uuidString)" app.launchEnvironment["EARLY_TEST_APPEARANCE"] = appearance - app.launchArguments = ["-ApplePersistenceIgnoreState", "YES"] + app.launchArguments = ["-ApplePersistenceIgnoreState", "YES"] + arguments // Typed text stays as typed whatever the Mac's keyboard settings: CI's // automatic capitalization once turned "keep" into "Keep" mid-test. for setting in ["NSAutomaticCapitalizationEnabled", "NSAutomaticSpellingCorrectionEnabled", "NSAutomaticTextReplacementEnabled", @@ -334,7 +333,7 @@ final class EarlyUITests: XCTestCase { app.buttons[firstID].rightClick() // The Tab menu has a Split View submenu too; use the open context menu's. visibleMenuItem("Split View")?.hover() - visibleMenuAction("Place on Left") + activateFirstSubmenuItem("Place on Left", in: app) let divider = app.descendants(matching: .any).matching(identifier: "split.divider").firstMatch XCTAssertTrue(divider.waitForExistence(timeout: 5)) let left = app.descendants(matching: .any).matching(identifier: "browser.pane.\(firstID.dropFirst(4))").firstMatch @@ -355,7 +354,7 @@ final class EarlyUITests: XCTestCase { XCTAssertTrue(app.menuItems["Swap Sides"].waitForExistence(timeout: 3)) XCTAssertTrue(app.menuItems["Exit Split View"].exists) XCTAssertFalse(app.menuItems["Place on Left"].exists || app.menuItems["Place on Right"].exists) - visibleMenuAction("Swap Sides") + activateFirstSubmenuItem("Swap Sides", in: app) let swapped = NSPredicate { _, _ in reversed ? left.frame.midX > right.frame.midX : left.frame.midX < right.frame.midX } XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: swapped, object: nil)], timeout: 5), .completed) XCTAssertEqual(left.textFields["Saved text"].value as? String, "keep left") @@ -725,6 +724,23 @@ final class EarlyUITests: XCTestCase { visibleMenuTarget(title)?.item } + /// Right Arrow selects the first enabled item of the highlighted submenu. + /// A mouse click can dismiss a nested AppKit menu while crossing to its child. + private func activateFirstSubmenuItem(_ title: String, in app: XCUIApplication, + file: StaticString = #filePath, line: UInt = #line) { + app.typeKey(.rightArrow, modifierFlags: []) + let selected = app.menuItems.matching(identifier: title) + .matching(NSPredicate(format: "selected == true AND enabled == true")) + let ready = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + selected.allElementsBoundByIndex.filter { self.usableMenuFrame($0.frame) }.count == 1 + }, object: nil) + guard XCTWaiter.wait(for: [ready], timeout: 5) == .completed else { + XCTFail("Expected the open submenu to select \(title) before Return", file: file, line: line) + return + } + app.typeKey(.return, modifierFlags: []) + } + private func usableMenuFrame(_ frame: CGRect) -> Bool { !frame.isNull && !frame.isInfinite && frame.width > 0 && frame.height > 0 && [frame.minX, frame.minY, frame.maxX, frame.maxY, frame.midX, frame.midY].allSatisfy(\.isFinite) @@ -1161,19 +1177,7 @@ final class EarlyUITests: XCTestCase { let submenu = app.menuItems[menu] XCTAssertTrue(submenu.waitForExistence(timeout: 3)) submenu.hover() - // Each destination submenu in this fixture has one enabled item. - // Enter it through AppKit's keyboard navigation: XCTest can fail - // to compute a mouse hit point even when the child has valid bounds. - app.typeKey(.rightArrow, modifierFlags: []) - let selected = app.menuItems.matching(identifier: name) - .matching(NSPredicate(format: "selected == true AND enabled == true")) - let destinationReady = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in - let items = selected.allElementsBoundByIndex.filter { self.usableMenuFrame($0.frame) } - return items.count == 1 - }, object: nil) - XCTAssertEqual(XCTWaiter.wait(for: [destinationReady], timeout: 5), .completed, - "The \(menu) submenu must select \(name) before Return") - app.typeKey(.return, modifierFlags: []) + activateFirstSubmenuItem(name, in: app) } func move(_ row: XCUIElement, to name: String) { let contextAction = row.identifier.hasPrefix("folder.") ? "Rename Folder…" : "Rename Tab…" @@ -2718,16 +2722,11 @@ final class EarlyUITests: XCTestCase { expectRuntime(app, tabs: 1, views: 1, created: 1) } - func testSystemTranslationRestoresTheArticleOrDismissesTheLanguageDownload() async throws { + func testSystemTranslationRestoresTheArticleOrDismissesTheLanguageDownload() throws { guard #available(macOS 15.0, *) else { throw XCTSkip("System translation requires macOS 15.") } - let preferred = Locale.Language(identifier: Locale.preferredLanguages.first ?? "en") - let target = Locale.Language(identifier: preferred.languageCode?.identifier ?? "en") - let source = Locale.Language(identifier: "fr") - let availability = await LanguageAvailability().status(from: source, to: target) - guard source.languageCode != target.languageCode, availability != .unsupported else { - throw XCTSkip("This Mac does not offer translation for the French fixture into its preferred language.") - } - let app = launchFreshApp() + // Early checks availability when it inspects the French page. The UI + // runner has a separate sandbox and cannot query the translation service. + let app = launchFreshApp(arguments: ["-AppleLanguages", "(en)"]) defer { app.terminate() } navigate(app, to: "early-test://fixture/article?lang=fr") expectPage(app, "Article") @@ -2736,7 +2735,7 @@ final class EarlyUITests: XCTestCase { XCTAssertTrue(french.waitForExistence(timeout: 5)) app.buttons["address.siteControls"].click() let translate = app.buttons["siteControls.translate"] - XCTAssertTrue(translate.waitForExistence(timeout: 15)) + XCTAssertTrue(translate.waitForExistence(timeout: 15), "Expected Early to offer French-to-English translation.\n\(app.debugDescription)") translate.click() let translated = app.descendants(matching: .any).matching(NSPredicate( @@ -2745,7 +2744,8 @@ final class EarlyUITests: XCTestCase { let reply = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in translated.exists || modals.contains { $0.exists } }, object: nil) - await fulfillment(of: [reply], timeout: 30) + XCTAssertEqual(XCTWaiter.wait(for: [reply], timeout: 30), .completed, + "Expected translated text or the system language-download prompt.\n\(app.debugDescription)") if translated.exists { XCTAssertFalse(french.exists) let original = app.buttons["translation.original"] From 882d09c3cef646bf2b51fe52058feb0faa916854 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Sun, 22 Nov 2026 13:11:03 +0530 Subject: [PATCH 3/3] Match the full French paragraph in the translation UI test --- UITests/EarlyUITests.swift | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index 0462651..aa86f26 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -2730,9 +2730,14 @@ final class EarlyUITests: XCTestCase { defer { app.terminate() } navigate(app, to: "early-test://fixture/article?lang=fr") expectPage(app, "Article") + // WebKit also exposes heading levels as numeric static-text values. + // Equality can check the complete original paragraph against either AX attribute. + let paragraph = "Le navigateur reste calme pour que la page puisse parler. Les espaces rassemblent les onglets " + + "d'un projet, les pages épinglées restent à leur place et la barre latérale se replie quand " + + "on veut toute la fenêtre. La lecture devrait être pareille : un texte simple et des marges stables." let french = app.webViews.staticTexts.matching(NSPredicate( - format: "label CONTAINS %@ OR value CONTAINS %@", "Le navigateur reste calme", "Le navigateur reste calme")).firstMatch - XCTAssertTrue(french.waitForExistence(timeout: 5)) + format: "label == %@ OR value == %@", paragraph, paragraph)).firstMatch + XCTAssertTrue(french.waitForExistence(timeout: 5), "Expected the original French paragraph in the article.") app.buttons["address.siteControls"].click() let translate = app.buttons["siteControls.translate"] XCTAssertTrue(translate.waitForExistence(timeout: 15), "Expected Early to offer French-to-English translation.\n\(app.debugDescription)") @@ -2747,7 +2752,7 @@ final class EarlyUITests: XCTestCase { XCTAssertEqual(XCTWaiter.wait(for: [reply], timeout: 30), .completed, "Expected translated text or the system language-download prompt.\n\(app.debugDescription)") if translated.exists { - XCTAssertFalse(french.exists) + XCTAssertTrue(french.waitForNonExistence(timeout: 5), "The translated article still contains the original paragraph.") let original = app.buttons["translation.original"] XCTAssertTrue(original.waitForExistence(timeout: 5)) original.click()