# TestFly Part 17: Cross-browser reliability with BiDi console capture, Edge/Safari on Grid and guaranteed driver cleanup

URL: https://hakangul.lovable.app/blog/testfly-part-17-cross-browser-reliability-bidi-grid-safari-edge-2
Author: Hakan Gül — Team Lead Senior Test Automation Engineer
Published: 2026-10-12
Updated: 2026-10-18
Category: test-automation
Tags: TestFly, Selenium, Cross-Browser, Java, SDET

> TestFly 1.1.0 opens a real WebDriver BiDi connection to catch console errors that Firefox used to miss, runs Edge and Safari on Selenium Grid under browser.matrix, and quits every tracked browser when the JVM shuts down abnormally.

## English

TestFly 1.0.6 and 1.1.0 close three cross-browser reliability gaps.

First, `browser.bidi` opens a real WebDriver BiDi connection to a locally launched Chrome, Edge or Firefox. `ConsoleErrorCollector` then reads `console.error` calls and uncaught exceptions from BiDi log events instead of a JS shim, which catches errors Firefox used to hide. `ConsoleErrorCollector.isBiDiActive()` tells you which capture path ran.

Second, `RemoteDriverProvider` now resolves Edge and Safari on Selenium Grid and honors `browser.matrix`. Before, it only knew chrome/firefox and always read `browser.name`.

Third, JVM shutdown hooks and `DriverManager.quitAllTrackedDrivers()` quit every tracked browser exactly once when a run is aborted with Ctrl+C or `System.exit`. That covers browsers on every thread, including threads other than the one running the hook.

## How BiDi catches console errors that Firefox used to miss

TestFly's `captureConsoleErrors` has always read browser console errors. Firefox exposes no browser logs over classic WebDriver, so on Firefox this meant injecting a JavaScript shim that only sees errors after it runs on the current page. The shim could not see an error thrown while the page was still loading, or one on a page reached by following a link.

`browser.bidi` (default `false`) solves this at the protocol level. When a Chrome, Edge or Firefox session is launched locally, TestFly requests a real WebDriver BiDi connection and subscribes to BiDi log events from the moment the test gets its browser:

```yaml
# testfly.yml
browser:
  name: firefox
  bidi: true
  captureConsoleErrors: true
```

The capability request is one line and is added only when BiDi is turned on:

```java
// BiDiCapability.java
static void applyIfConfigured(MutableCapabilities options, TestFlyConfig config) {
    if (config != null && config.getBrowser() != null && config.getBrowser().isBidi()) {
        options.setCapability("webSocketUrl", true);
    }
}
```

`ConsoleErrorCollector` then opens one `LogInspector` per session over that connection. The inspectors are kept in a `WeakHashMap<WebDriver, BiDiCapture>`, so a session is not held in memory after its driver is gone:

```java
private static final Map<WebDriver, BiDiCapture> BIDI =
        Collections.synchronizedMap(new WeakHashMap<>());
```

The subscription starts at `beginTest(driver)`, so errors from a previous test are dropped even when a per-suite browser is reused. There is no JS shim and no race with page load.

Safari and remote drivers (Selenium Grid, BrowserStack, Sauce Labs) don't get a BiDi connection in TestFly today. For those, TestFly logs one warning per session and falls back to the usual capture path without throwing.

To check which path ran without reading logs:

```java
if (ConsoleErrorCollector.isBiDiActive()) {
    // BiDi log events are driving capture for this session
}
```

```java
// ConsoleErrorCollector.java
@TestFlyApi(since = "1.1.0")
public static boolean isBiDiActive() {
    try {
        return BIDI.containsKey(DriverManager.getDriver());
    } catch (RuntimeException e) {
        return false;
    }
}
```

## Knowing which browser features you lose

A locally started Chrome or Edge gives TestFly the Chrome DevTools Protocol (CDP). CDP powers network mocking, device emulation, geolocation overrides and the screencast-based video recorder. Firefox, Safari, Selenium Grid and cloud sessions don't expose CDP, and neither does a remote Chrome, so these features would degrade silently unless something reported it.

`BrowserFeatures`, new in 1.1.0, names the four CDP-dependent features and describes the fallback for each:

```java
public enum Feature {
    NETWORK_MOCK("Network interception requires a local Chrome/Edge session... "
            + "routes are ignored and requests reach the real network."),
    CDP_RECORDING("Video recording uses periodic screenshots instead of the "
            + "DevTools screencast, so frames are less frequent."),
    DEVICE_EMULATION("Device emulation only resizes the window and overrides "
            + "navigator.userAgent in the current page..."),
    GEOLOCATION("The location is overridden through JavaScript in the current "
            + "page only and is lost on navigation.");
}
```

`BrowserFeatures.supports(driver, feature)` answers the question directly (`driver instanceof ChromiumDriver` for three of the four features, `HasDevTools` for recording). `warnOnce(driver, feature)` logs the fallback exactly once per browser session and feature, and names the browser:

```java
BrowserFeatures.warnOnce(driver, BrowserFeatures.Feature.GEOLOCATION);
```

`GeoLocation` already calls this before it falls back to its JS override on Firefox. The video recording fallback used to be silent. Now every degraded feature logs a warning.

## Running Edge and Safari on Selenium Grid

Before this release, `RemoteDriverProvider` only built `ChromeOptions` or `FirefoxOptions` and always read `browser.name` directly. A `browser.matrix` run on a Grid therefore used whatever `browser.name` said and ignored the matrix browser, and Edge and Safari on Grid were not supported at all.

Browser resolution now goes through one shared method that both the local and remote paths call. `BrowserContext` (the matrix override) takes precedence over YAML:

```java
// DriverProviderFactory.java
public static String resolveBrowserName(TestFlyConfig config) {
    String contextBrowser = BrowserContext.get();
    if (contextBrowser != null && !contextBrowser.isBlank()) {
        return contextBrowser;
    }
    String name = config.getBrowser().getName();
    if (name == null || name.isBlank()) {
        throw new IllegalStateException(
                "No browser selected: set browser.name, or run through browser.matrix.");
    }
    return name;
}
```

`RemoteDriverProvider.buildOptions(config, browser)` is a public method you can test on its own. It now covers all four browsers that Grid supports:

```java
// RemoteDriverProvider.java
switch (browser.toLowerCase(Locale.ROOT)) {
    case "chrome" -> options = chromium(new ChromeOptions(), browserConfig.isHeadless(), arguments);
    case "edge" -> options = chromium(new EdgeOptions(), browserConfig.isHeadless(), arguments);
    case "firefox" -> { /* FirefoxOptions, -headless */ }
    case "safari" -> {
        if (browserConfig.isHeadless()) {
            System.err.println("[TestFly] Safari does not support headless mode via Selenium; ignoring headless=true.");
        }
        options = new SafariOptions();
    }
    default -> throw new IllegalStateException(
            "Unsupported browser for remote execution: " + browser + ". Supported: chrome, edge, firefox, safari.");
}
options.setCapability("unhandledPromptBehavior", "ignore");
```

A matrix config that runs the same suite on Chrome, Edge and Safari on a Grid now works without changes:

```yaml
# testfly.yml
execution:
  mode: remote
  gridUrl: http://grid.local:4444/wd/hub
browser:
  matrix: [chrome, edge, safari]
```

Two related fixes shipped alongside. The first (`do not reuse a per-suite driver for another matrix browser`) stops `DriverManager` from handing a Chrome `per-suite` driver to a thread that should be testing Edge; `DRIVER_BROWSER_CONTEXT` is now tracked per thread and checked before reuse. The second (`quit the browser when post-launch session setup fails`) makes every built-in provider quit the session before rethrowing when timeout configuration fails right after launch, so a setup failure no longer leaves a browser process behind.

## Making sure no browser is left running

`DriverManager` has registered a JVM shutdown hook from early on. Until this release, though, the hook only quit per-suite drivers and whatever driver was bound to the hook's own thread, and that is never the thread that ran a per-test driver. If you aborted a parallel `per-test` run with Ctrl+C or `System.exit`, the worker-thread browsers kept running after the JVM exited.

The hook now calls `quitAllTrackedDrivers()`. It takes every driver that still holds a session permit plus every registered per-suite driver, across all threads, and quits each one exactly once:

```java
static void quitAllTrackedDrivers() {
    java.util.Set<WebDriver> drivers =
            java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
    drivers.addAll(PERMIT_HOLDERS);
    drivers.addAll(SUITE_DRIVERS);
    for (WebDriver driver : drivers) {
        try {
            driver.quit();
        } catch (Throwable ignored) {
        } finally {
            SUITE_DRIVERS.remove(driver);
            releasePermitOf(driver);
        }
    }
}
```

`PERMIT_HOLDERS` is the set of drivers that currently hold a session-slot permit. Exactly one code path per driver adds and removes entries, which is also why `execution.maxActiveSessions` can't leak slots. Normal suite teardown still calls `DriverManager.quitAllSuiteDrivers()` and then `quitDriver()` from `SuiteExecutionListener`, `TestFlyExtension` (JUnit 5) and `CucumberHooks`. The shutdown hook is the safety net for abnormal exits and runs the same cleanup logic no matter which thread owned the browser.

This builds on the original "Guaranteed Driver Cleanup" item from 1.0.6 (shutdown hooks plus `@AfterAll` listener execution). The hook has existed since 1.0.6; this release makes it reach every thread's browser and not only the suite-level ones.

## FAQ

### Does `browser.bidi` work with Selenium Grid or BrowserStack/Sauce Labs?

No. BiDi only applies to a locally launched Chrome, Edge or Firefox. On Safari or any remote driver, TestFly logs one warning and falls back to the previous capture path (CDP logs on Chrome, the JS shim elsewhere). Nothing fails.

### How do I check which console-error capture path is active for the current test?

Call `ConsoleErrorCollector.isBiDiActive()`. It returns `true` only when the current thread's driver has an open BiDi log subscription. It never throws; it returns `false` if there is no driver or the check fails.

### Can I run the same suite on Chrome, Edge and Safari against one Selenium Grid?

Yes, with `execution.mode: remote`, `execution.gridUrl` and `browser.matrix: [chrome, edge, safari]`. `RemoteDriverProvider` resolves the matrix browser before `browser.name` and builds Grid options for all four supported browsers, including Safari's headless restriction.

### If I kill a parallel run with Ctrl+C, are all browser processes gone?

Yes. The JVM shutdown hook now collects every driver that holds a session permit and every per-suite driver, on every thread, and quits each one exactly once, regardless of which thread the hook runs on.

## Türkçe

TestFly 1.0.6 ve 1.1.0, tarayıcılar arası güvenilirlikte üç açığı kapatıyor.

Birincisi, `browser.bidi` yerelde başlatılan Chrome, Edge ya da Firefox'a gerçek bir WebDriver BiDi bağlantısı açıyor. `ConsoleErrorCollector` artık `console.error` çağrılarını ve yakalanmamış exception'ları bir JS shim yerine BiDi log olaylarından okuyor, böylece Firefox'ta daha önce görünmeyen hatalar da yakalanıyor. Hangi yakalama yolunun çalıştığını `ConsoleErrorCollector.isBiDiActive()` söylüyor.

İkincisi, `RemoteDriverProvider` artık Selenium Grid'de Edge ve Safari'yi tanıyor ve `browser.matrix` ayarını dikkate alıyor. Eskiden yalnızca chrome/firefox biliyordu ve her zaman `browser.name`'i okuyordu.

Üçüncüsü, JVM shutdown hook'ları ve `DriverManager.quitAllTrackedDrivers()`, koşu Ctrl+C ya da `System.exit` ile kesildiğinde takip edilen her tarayıcıyı bir kez kapatıyor. Bu, hook'un çalıştığı thread'deki tarayıcılarla sınırlı değil, bütün thread'lerdeki tarayıcıları kapsıyor.

## BiDi, Firefox'ta kaçan konsol hatalarını nasıl yakalıyor

TestFly'ın `captureConsoleErrors` özelliği tarayıcı konsol hatalarını hep okuyordu. Ancak Firefox klasik WebDriver üzerinden tarayıcı loglarını vermediği için, Firefox'ta bu iş mevcut sayfaya bir JavaScript shim enjekte etmek demekti. Shim yalnızca çalışmaya başladıktan sonraki hataları görebiliyordu. Sayfa daha yüklenirken atılan bir hatayı ya da bir link'e tıklanarak gidilen sayfadaki hatayı göremiyordu.

`browser.bidi` (varsayılanı `false`) sorunu protokol seviyesinde çözüyor. Yerelde bir Chrome, Edge ya da Firefox oturumu açıldığında TestFly gerçek bir WebDriver BiDi bağlantısı istiyor ve test tarayıcıyı aldığı andan itibaren BiDi log olaylarını dinliyor:

```yaml
# testfly.yml
browser:
  name: firefox
  bidi: true
  captureConsoleErrors: true
```

Capability isteği tek satır ve yalnızca BiDi açıksa ekleniyor:

```java
// BiDiCapability.java
static void applyIfConfigured(MutableCapabilities options, TestFlyConfig config) {
    if (config != null && config.getBrowser() != null && config.getBrowser().isBidi()) {
        options.setCapability("webSocketUrl", true);
    }
}
```

Ardından `ConsoleErrorCollector` bu bağlantı üzerinden her oturum için bir `LogInspector` açıyor. Bunlar bir `WeakHashMap<WebDriver, BiDiCapture>` içinde tutuluyor, dolayısıyla driver ortadan kalktıktan sonra oturum bellekte asılı kalmıyor:

```java
private static final Map<WebDriver, BiDiCapture> BIDI =
        Collections.synchronizedMap(new WeakHashMap<>());
```

Dinleme `beginTest(driver)` ile başladığı için, per-suite modda aynı tarayıcı tekrar kullanılsa bile önceki testin hataları sonraki teste taşınmıyor. JS shim'e de, sayfa yüklemesiyle yarışa da gerek kalmıyor.

Safari ve uzak driver'lar (Selenium Grid, BrowserStack, Sauce Labs) için TestFly şu an BiDi bağlantısı açmıyor. Bu durumda oturum başına bir uyarı loglanıyor ve framework hata fırlatmadan normal yakalama yoluna dönüyor.

Log okumadan hangi yolun çalıştığını görmek için:

```java
if (ConsoleErrorCollector.isBiDiActive()) {
    // Bu oturum için yakalamayı BiDi log olayları yürütüyor
}
```

```java
// ConsoleErrorCollector.java
@TestFlyApi(since = "1.1.0")
public static boolean isBiDiActive() {
    try {
        return BIDI.containsKey(DriverManager.getDriver());
    } catch (RuntimeException e) {
        return false;
    }
}
```

## Hangi tarayıcı özelliklerini kaybettiğinizi bilmek

Yerelde açılan bir Chrome ya da Edge, TestFly'a Chrome DevTools Protocol (CDP) erişimi veriyor. Network mock'lama, cihaz emülasyonu, geolocation override ve screencast tabanlı video kaydı CDP ile çalışıyor. Firefox, Safari, Selenium Grid ve bulut oturumları CDP sunmuyor, uzaktaki bir Chrome bile sunmuyor. Bu yüzden biri haber vermezse bu özellikler sessizce zayıflıyordu.

1.1.0 ile gelen `BrowserFeatures`, CDP'ye bağlı dört özelliği ve her birinde yerine ne olacağını tanımlıyor:

```java
public enum Feature {
    NETWORK_MOCK("Network interception requires a local Chrome/Edge session... "
            + "routes are ignored and requests reach the real network."),
    CDP_RECORDING("Video recording uses periodic screenshots instead of the "
            + "DevTools screencast, so frames are less frequent."),
    DEVICE_EMULATION("Device emulation only resizes the window and overrides "
            + "navigator.userAgent in the current page..."),
    GEOLOCATION("The location is overridden through JavaScript in the current "
            + "page only and is lost on navigation.");
}
```

`BrowserFeatures.supports(driver, feature)` soruyu doğrudan cevaplıyor (dört özelliğin üçünde `driver instanceof ChromiumDriver`, kayıtta `HasDevTools`). `warnOnce(driver, feature)` ise yedek davranışı her tarayıcı oturumu ve özellik için yalnızca bir kez, tarayıcının adını da vererek logluyor:

```java
BrowserFeatures.warnOnce(driver, BrowserFeatures.Feature.GEOLOCATION);
```

`GeoLocation` Firefox'ta JS override'a geçmeden önce bunu zaten çağırıyor. Video kaydındaki yedek davranış eskiden hiçbir şey söylemiyordu. Artık zayıflayan her özellik için uyarı düşülüyor.

## Selenium Grid'de Edge ve Safari koşturmak

Bu sürümden önce `RemoteDriverProvider` yalnızca `ChromeOptions` ya da `FirefoxOptions` oluşturuyor ve her zaman doğrudan `browser.name`'i okuyordu. Grid üzerinde `browser.matrix` ile yapılan bir koşu, matrix'teki tarayıcıyı yok sayıp `browser.name`'de ne yazıyorsa onu kullanıyordu. Grid'de Edge ve Safari ise hiç desteklenmiyordu.

Tarayıcı seçimi artık yerel ve uzak yolun ortak kullandığı tek bir metottan geçiyor. `BrowserContext` (matrix override'ı) YAML'daki değerden önce geliyor:

```java
// DriverProviderFactory.java
public static String resolveBrowserName(TestFlyConfig config) {
    String contextBrowser = BrowserContext.get();
    if (contextBrowser != null && !contextBrowser.isBlank()) {
        return contextBrowser;
    }
    String name = config.getBrowser().getName();
    if (name == null || name.isBlank()) {
        throw new IllegalStateException(
                "No browser selected: set browser.name, or run through browser.matrix.");
    }
    return name;
}
```

`RemoteDriverProvider.buildOptions(config, browser)`, tek başına test edilebilen public bir metot ve artık Grid'in desteklediği dört tarayıcının hepsini kapsıyor:

```java
// RemoteDriverProvider.java
switch (browser.toLowerCase(Locale.ROOT)) {
    case "chrome" -> options = chromium(new ChromeOptions(), browserConfig.isHeadless(), arguments);
    case "edge" -> options = chromium(new EdgeOptions(), browserConfig.isHeadless(), arguments);
    case "firefox" -> { /* FirefoxOptions, -headless */ }
    case "safari" -> {
        if (browserConfig.isHeadless()) {
            System.err.println("[TestFly] Safari does not support headless mode via Selenium; ignoring headless=true.");
        }
        options = new SafariOptions();
    }
    default -> throw new IllegalStateException(
            "Unsupported browser for remote execution: " + browser + ". Supported: chrome, edge, firefox, safari.");
}
options.setCapability("unhandledPromptBehavior", "ignore");
```

Aynı suite'i Grid üzerinde Chrome, Edge ve Safari'de koşturan bir matrix config artık hiçbir değişiklik yapmadan çalışıyor:

```yaml
# testfly.yml
execution:
  mode: remote
  gridUrl: http://grid.local:4444/wd/hub
browser:
  matrix: [chrome, edge, safari]
```

Bununla birlikte iki düzeltme daha geldi. İlki (`do not reuse a per-suite driver for another matrix browser`), `DriverManager`'ın Edge test etmesi gereken bir thread'e Chrome `per-suite` driver'ını vermesini engelliyor. `DRIVER_BROWSER_CONTEXT` artık thread bazında tutuluyor ve driver tekrar kullanılmadan önce kontrol ediliyor. İkincisi (`quit the browser when post-launch session setup fails`), tarayıcı açıldıktan hemen sonra timeout ayarı hata verirse bütün yerleşik provider'ların hatayı tekrar fırlatmadan önce oturumu kapatmasını sağlıyor. Böylece kurulum sırasında çıkan bir hata arkada açık tarayıcı süreci bırakmıyor.

## Hiçbir tarayıcının açık kalmaması

`DriverManager` ilk sürümlerden beri bir JVM shutdown hook'u kaydediyor. Ama bu sürüme kadar hook yalnızca per-suite driver'ları ve hook'un kendi thread'ine bağlı driver'ı kapatıyordu. Per-test driver'ı çalıştıran thread ise hiçbir zaman hook'un thread'i olmuyor. Paralel bir `per-test` koşusunu Ctrl+C ya da `System.exit` ile durdurduğunuzda worker thread'lerdeki tarayıcılar JVM kapandıktan sonra da açık kalıyordu.

Hook artık `quitAllTrackedDrivers()`'ı çağırıyor. Bu metot, bütün thread'lerde hâlâ oturum izni (permit) tutan driver'ları ve kayıtlı bütün per-suite driver'ları bir araya topluyor ve her birini tam olarak bir kez kapatıyor:

```java
static void quitAllTrackedDrivers() {
    java.util.Set<WebDriver> drivers =
            java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
    drivers.addAll(PERMIT_HOLDERS);
    drivers.addAll(SUITE_DRIVERS);
    for (WebDriver driver : drivers) {
        try {
            driver.quit();
        } catch (Throwable ignored) {
        } finally {
            SUITE_DRIVERS.remove(driver);
            releasePermitOf(driver);
        }
    }
}
```

`PERMIT_HOLDERS`, o anda oturum slotu izni tutan driver'ların kümesi. Her driver için bu kümeye ekleme ve çıkarma tek bir kod yolundan yapılıyor. `execution.maxActiveSessions`'ın slot sızdırmamasının sebebi de bu. Normal suite kapanışında `SuiteExecutionListener`, `TestFlyExtension` (JUnit 5) ve `CucumberHooks` yine önce `DriverManager.quitAllSuiteDrivers()`, sonra `quitDriver()` çağırıyor. Shutdown hook, beklenmedik çıkışlar için bir güvenlik ağı. Tarayıcı hangi thread'e ait olursa olsun aynı temizlik mantığını çalıştırıyor.

Bu değişiklik, 1.0.6'daki "Guaranteed Driver Cleanup" maddesinin (shutdown hook'ları ve `@AfterAll` listener çalıştırması) devamı. Hook 1.0.6'dan beri vardı. Bu sürümle yalnızca suite seviyesindeki tarayıcılara değil, her thread'in tarayıcısına ulaşıyor.

## SSS

### `browser.bidi`, Selenium Grid ya da BrowserStack/Sauce Labs ile çalışıyor mu?

Hayır. BiDi yalnızca yerelde açılan Chrome, Edge ya da Firefox için geçerli. Safari'de ya da herhangi bir uzak driver'da TestFly bir uyarı logluyor ve önceki yakalama yoluna dönüyor (Chrome'da CDP logları, diğerlerinde JS shim). Test düşmüyor.

### Mevcut testte hangi konsol hatası yakalama yolunun aktif olduğunu nasıl görürüm?

`ConsoleErrorCollector.isBiDiActive()`'i çağırın. Yalnızca mevcut thread'in driver'ının açık bir BiDi log aboneliği varsa `true` dönüyor. Hiçbir zaman hata fırlatmıyor; driver yoksa ya da kontrol başarısız olursa `false` dönüyor.

### Aynı suite'i tek bir Selenium Grid üzerinde Chrome, Edge ve Safari'de koşturabilir miyim?

Evet. `execution.mode: remote`, `execution.gridUrl` ve `browser.matrix: [chrome, edge, safari]` ayarlarıyla. `RemoteDriverProvider` matrix'teki tarayıcıyı `browser.name`'den önce dikkate alıyor ve desteklenen dört tarayıcının hepsi için Grid'e uygun option'ları, Safari'nin headless kısıtı dahil, oluşturuyor.

### Paralel bir koşuyu Ctrl+C ile durdurursam bütün tarayıcı süreçleri kapanıyor mu?

Evet. JVM shutdown hook'u artık bütün thread'lerde oturum izni tutan driver'ları ve per-suite driver'ları topluyor, hook'un kendisi hangi thread'de çalışırsa çalışsın her birini tam olarak bir kez kapatıyor.
