From 8b8d7d9a6aad0c7fe15590804bd2600f100d28f8 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Wed, 18 Nov 2026 19:57:43 +0100 Subject: [PATCH 01/26] fix: delete the temporary profile when the browser stops When no userDataDir is given, kdriver creates a kdriver_* profile in the temp directory, and cleanupTemporaryProfile() was a TODO: every browser left its profile on disk (thousands of directories, tens of GB on a busy host). - cleanupTemporaryProfile() deletes the profile this browser created, never a custom userDataDir nor a temporary one inherited through Config.copy(). It waits (bounded) for the browser process to exit first, and retries briefly when a file is still locked. - stop() calls it after the process is gone, non-cancellably and before cancelling the browser scope; a second stop() or cleanup does nothing. - One process-wide shutdown hook (LaunchedBrowsers) stops the browsers still running when the JVM exits, which deletes their profiles. It replaces the per-browser hook in create(), which kept every browser reachable forever and missed browsers started with DefaultBrowser(...).start(). - Recursive deletion per platform, never following symbolic links or junctions: kotlin.io.path on the JVM, lstat/readdir on POSIX, FindFirstFileW on Windows. - Process liveness fixes the wait depends on: reap the child on Linux native (a zombie looked alive forever), use NSTask.isRunning on macOS, and keep the Windows process handle open after destroy() so isAlive() stays accurate. Co-Authored-By: Claude Opus 5.5 --- .../dev/kdriver/core/browser/Browser.kt | 10 ++ .../kotlin/dev/kdriver/core/browser/Config.kt | 11 ++ .../kdriver/core/browser/DefaultBrowser.kt | 98 +++++++++++-- .../kdriver/core/browser/LaunchedBrowsers.kt | 60 ++++++++ .../dev/kdriver/core/browser/ProcessExit.kt | 7 +- .../kdriver/core/browser/TemporaryProfile.kt | 39 +++++ .../dev/kdriver/core/browser/Process.js.kt | 4 + .../core/browser/TemporaryProfile.jvm.kt | 23 +++ .../core/browser/TemporaryProfileTest.kt | 134 ++++++++++++++++++ .../dev/kdriver/core/browser/Process.linux.kt | 12 ++ .../core/browser/TemporaryProfileTest.kt | 26 ++++ .../dev/kdriver/core/browser/Process.macos.kt | 3 + .../core/browser/TemporaryProfileTest.kt | 26 ++++ .../dev/kdriver/core/browser/Process.mingw.kt | 7 +- .../core/browser/TemporaryProfile.mingw.kt | 55 +++++++ .../core/browser/TemporaryProfileTest.kt | 26 ++++ .../dev/kdriver/core/browser/Process.posix.kt | 7 + .../core/browser/TemporaryProfile.posix.kt | 55 +++++++ 18 files changed, 591 insertions(+), 12 deletions(-) create mode 100644 core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt create mode 100644 core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt create mode 100644 core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt create mode 100644 core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt create mode 100644 core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt create mode 100644 core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt create mode 100644 core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt create mode 100644 core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt create mode 100644 core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt index c97eae16c..f901dd8f3 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt @@ -138,6 +138,16 @@ interface Browser { */ suspend fun detach() + /** + * Deletes the temporary profile this browser created, when no [Config.userDataDir] was given. + * + * A profile passed as [Config.userDataDir] is never deleted. Nor is the temporary one while the + * browser process still runs: this waits a few seconds for it to exit, then gives up and leaves + * the profile in place. Calling it again, or after the profile is gone, does nothing. + * + * [stop] already calls it, and so does the shutdown hook that stops the browsers still running + * when the host process exits (on the JVM). There is usually no need to call it yourself. + */ suspend fun cleanupTemporaryProfile() /** diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index a0eed7272..d6f2833c5 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -55,6 +55,15 @@ class Config( private var _userDataDir: Path? = null private var _customDataDir: Boolean = false + /** + * True only when *this* instance created the temporary profile in [userDataDir]. + * + * Deliberately not carried over by [copy]: a copy that inherits an already created temporary + * profile shares it with the original, so it must not delete it. + */ + internal var createdTemporaryProfile: Boolean = false + private set + private val _browserArgs: MutableList = browserArgs?.toMutableList() ?: mutableListOf() internal val _extensions: MutableList = mutableListOf() @@ -81,12 +90,14 @@ class Config( if (_userDataDir == null) { _userDataDir = tempProfileDir() _customDataDir = false + createdTemporaryProfile = true } return _userDataDir!! } set(value) { _userDataDir = value _customDataDir = true + createdTemporaryProfile = false } val usesCustomDataDir: Boolean diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 87b506102..4cd8e676e 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -15,6 +15,7 @@ import io.ktor.util.logging.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.io.files.Path import kotlin.concurrent.Volatile import kotlin.time.Duration.Companion.seconds @@ -41,6 +42,19 @@ open class DefaultBrowser( private val updateTargetInfoMutex = Mutex() private var process: Process? = null + + /** + * The temporary profile this browser created and must delete, or null if it uses a custom + * [Config.userDataDir], has not launched a process, or already deleted it. + */ + private var temporaryProfile: Path? = null + + /** + * The process that runs on [temporaryProfile]. Unlike [process], it is kept after [stop] and + * [detach]: the profile may only be deleted once this process has exited. + */ + private var temporaryProfileUser: Process? = null + private val temporaryProfileMutex = Mutex() private var http: HTTPApi? = null private var _cookies: CookieJar? = null @@ -93,6 +107,13 @@ open class DefaultBrowser( private const val TARGET_WAIT_TIMEOUT_MS = 10_000L private const val TARGET_POLL_INTERVAL_MS = 50L + /** + * How long [cleanupTemporaryProfile] waits for the browser process to exit before giving up on + * deleting its profile. [stop] has already waited for it by then; this bounds the wait when + * [cleanupTemporaryProfile] is called on its own. + */ + private const val PROFILE_RELEASE_TIMEOUT_MS = 5_000L + /** * The entry point for creating a new Browser instance. * @@ -108,11 +129,9 @@ open class DefaultBrowser( suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser { val browserScope = CoroutineScope(coroutineScope.coroutineContext + SupervisorJob()) val instance = DefaultBrowser(browserScope, config) + // start() registers the launched browser with LaunchedBrowsers, whose shutdown hook stops + // it and deletes its temporary profile if the host process exits without calling stop(). instance.start() - addShutdownHook { - if (!instance.stopped) instance.stop() - instance.cleanupTemporaryProfile() - } return instance } @@ -232,7 +251,7 @@ open class DefaultBrowser( override suspend fun start(): Browser { process?.let { - if (process?.isAlive() == false) return create(coroutineScope, config) + if (process?.isAlive() == false) return restart() logger.warn("Ignored! Browser is already running.") return this } @@ -264,7 +283,19 @@ open class DefaultBrowser( logger.info("starting\n\texecutable :$exe\n\narguments:\n${params.joinToString("\n\t")}") - process = startProcess(exe, params) + // config() above created the temporary profile, if any: from here on it is ours to delete. + if (!config.usesCustomDataDir && config.createdTemporaryProfile) { + temporaryProfile = config.userDataDir + } + val launched = try { + startProcess(exe, params) + } catch (e: Throwable) { + withContext(NonCancellable) { cleanupTemporaryProfile() } + throw e + } + process = launched + temporaryProfileUser = launched + LaunchedBrowsers.register(this) } logger.info("Browser process started with PID: ${process?.pid()}") @@ -331,6 +362,32 @@ open class DefaultBrowser( return this } + /** + * Starts a new browser on the same configuration, because this one's process has died. + * + * The new browser runs on the same profile, so it takes over deleting it: this one must no longer + * delete it, nor be stopped on exit. + */ + private suspend fun restart(): Browser { + val inherited = temporaryProfile + temporaryProfile = null + temporaryProfileUser = null + LaunchedBrowsers.unregister(this) + val restarted = try { + create(coroutineScope, config) + } catch (e: Throwable) { + // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. + temporaryProfile = inherited + withContext(NonCancellable) { cleanupTemporaryProfile() } + throw e + } + if (inherited != null) { + if (restarted is DefaultBrowser) restarted.temporaryProfile = inherited + else logger.warn("Temporary profile $inherited will not be deleted") + } + return restarted + } + private suspend fun handleTargetUpdate(event: Any) = updateTargetInfoMutex.withLock { when (event) { // Both create and info-changed go through the same dedupe-by-targetId upsert, so an @@ -391,6 +448,13 @@ open class DefaultBrowser( logger.debug("Closing HTTP API client...") http?.close() http = null + // Before cancelling the scope, which may be the caller's own; and non-cancellable, so a stop() + // called from a `finally` of a cancelled coroutine still deletes the profile. + withContext(NonCancellable) { + cleanupTemporaryProfile() + // Still registered if the profile could not be deleted, so the exit hook tries again. + if (temporaryProfile == null) LaunchedBrowsers.unregister(this@DefaultBrowser) + } logger.debug("Canceling coroutine scope...") coroutineScope.cancel() logger.info("Browser process stopped") @@ -399,8 +463,10 @@ open class DefaultBrowser( override suspend fun detach() { logger.info("Detaching from browser at ${info?.webSocketDebuggerUrl}") // Only client-side teardown: no Browser.close, no process kill. Forgetting the process also - // keeps the shutdown hook from stopping a browser we chose to leave running. + // keeps the shutdown hook from stopping a browser we chose to leave running. Its temporary + // profile is kept too, since the browser still runs on it. process = null + LaunchedBrowsers.unregister(this) val targets = updateTargetInfoMutex.withLock { detached = true mutableTargets.toList().also { @@ -417,8 +483,22 @@ open class DefaultBrowser( logger.info("Detached from browser") } - override suspend fun cleanupTemporaryProfile() { - // TODO: Implement cleanup of temporary profile files (nothing on JVM but maybe for other platforms) + override suspend fun cleanupTemporaryProfile() = temporaryProfileMutex.withLock { + val profile = temporaryProfile ?: return@withLock + // The browser keeps writing to its profile while it shuts down: deleting it earlier would race + // those writes, and leave files (or recreated directories) behind. + val user = temporaryProfileUser + if (user != null && !user.awaitExit(PROFILE_RELEASE_TIMEOUT_MS)) { + logger.warn("Not deleting temporary profile $profile: browser process ${user.pid()} is still running") + return@withLock + } + if (deleteTemporaryProfile(profile)) { + logger.debug("Deleted temporary profile $profile") + temporaryProfile = null + temporaryProfileUser = null + } else { + logger.warn("Could not delete temporary profile $profile") + } } private suspend fun getTargets(): List { diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt new file mode 100644 index 000000000..77e58f12b --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt @@ -0,0 +1,60 @@ +package dev.kdriver.core.browser + +import io.ktor.util.logging.* +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * The browsers this process launched and has not stopped yet. + * + * When the host process exits without calling [Browser.stop], they are stopped from a single + * shutdown hook (see [addShutdownHook]), which also deletes their temporary profiles. Without it, a + * program that simply returns from `main` leaves a `kdriver_*` profile behind on every run. + * + * One hook for the whole process rather than one per browser: a hook cannot be removed once added, + * so a hook per browser would keep every browser ever created reachable until the process exits. + * A browser leaves this registry as soon as it is stopped or detached. + */ +internal object LaunchedBrowsers { + + private val logger = KtorSimpleLogger("LaunchedBrowsers") + private val mutex = Mutex() + private val browsers = LinkedHashSet() + private var hookInstalled = false + + suspend fun register(browser: Browser) = mutex.withLock { + if (!hookInstalled) { + addShutdownHook { stopAll() } + hookInstalled = true + } + browsers += browser + } + + suspend fun unregister(browser: Browser) = mutex.withLock { + browsers -= browser + } + + suspend operator fun contains(browser: Browser): Boolean = mutex.withLock { browser in browsers } + + /** Stops every browser still registered, concurrently, so their grace periods overlap. */ + internal suspend fun stopAll() { + val remaining = mutex.withLock { browsers.toList() } + coroutineScope { + remaining.forEach { browser -> + launch { + try { + browser.stop() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.warn("Could not stop browser ${browser.pid} on exit: ${e.message}") + } + } + } + } + } + +} diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt index 8101d3dce..28139a1d4 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ProcessExit.kt @@ -37,7 +37,12 @@ suspend fun Process.destroyAndAwaitExit( } } -private suspend fun Process.awaitExit(timeoutMillis: Long): Boolean { +/** + * Waits up to [timeoutMillis] for the process to exit, without asking it to. + * + * @return true if the process has exited. + */ +internal suspend fun Process.awaitExit(timeoutMillis: Long): Boolean { var waited = 0L while (waited < timeoutMillis) { if (!isAlive()) return true diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt new file mode 100644 index 000000000..9478aca91 --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt @@ -0,0 +1,39 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.delay +import kotlinx.io.files.Path + +/** + * Deletes [path] and everything below it, without following symbolic links (or, on Windows, + * junctions): a link inside the profile is removed, never what it points to. + * + * Best effort: keeps going past an entry it cannot delete, so one locked file does not keep the + * rest of the profile on disk. + * + * @return true if [path] no longer exists afterwards (including when it never existed). + */ +internal expect fun deleteRecursively(path: Path): Boolean + +/** + * Deletes a temporary profile, retrying for a short while if it cannot be removed at once. + * + * Even after the browser process has exited, a file of the profile can stay locked for a moment + * (on Windows by a child process that is still winding down, or by an antivirus scanning it), so a + * single attempt is not enough. + * + * @return true if the profile is gone. + */ +internal suspend fun deleteTemporaryProfile( + path: Path, + attempts: Int = PROFILE_DELETE_ATTEMPTS, + retryDelayMillis: Long = PROFILE_DELETE_RETRY_DELAY_MILLIS, +): Boolean { + repeat(attempts) { attempt -> + if (deleteRecursively(path)) return true + if (attempt < attempts - 1) delay(retryDelayMillis) + } + return false +} + +private const val PROFILE_DELETE_ATTEMPTS = 10 +private const val PROFILE_DELETE_RETRY_DELAY_MILLIS = 200L diff --git a/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt b/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt index 3c9c224d2..4bf8caa8c 100644 --- a/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt +++ b/core/src/jsMain/kotlin/dev/kdriver/core/browser/Process.js.kt @@ -64,3 +64,7 @@ actual fun freePort(): Int? { actual fun defaultBrowserSearchConfig(): BrowserSearchConfig { throw UnsupportedOperationException() } + +internal actual fun deleteRecursively(path: Path): Boolean { + throw UnsupportedOperationException() +} diff --git a/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt new file mode 100644 index 000000000..299273a6e --- /dev/null +++ b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt @@ -0,0 +1,23 @@ +package dev.kdriver.core.browser + +import kotlinx.io.files.Path +import java.nio.file.LinkOption +import java.nio.file.Paths +import kotlin.io.path.ExperimentalPathApi +import kotlin.io.path.deleteRecursively +import kotlin.io.path.exists + +/** + * `Path.deleteRecursively` does not follow symbolic links, and keeps going past an entry it cannot + * delete before throwing: the end state is what tells whether the profile is gone. + */ +@OptIn(ExperimentalPathApi::class) +internal actual fun deleteRecursively(path: Path): Boolean { + val target = Paths.get(path.toString()) + try { + target.deleteRecursively() + } catch (_: Exception) { + // Reported below, through whether the directory is still there. + } + return !target.exists(LinkOption.NOFOLLOW_LINKS) +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..3f82d828f --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,134 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.Path +import java.io.File +import java.nio.file.Files +import kotlin.io.path.createTempDirectory +import kotlin.io.path.deleteRecursively +import kotlin.io.path.ExperimentalPathApi +import kotlin.io.path.exists +import kotlin.io.path.writeText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The temporary profile kdriver creates when no `userDataDir` is given must be deleted once the + * browser is stopped; a profile the caller supplied must never be. + */ +@OptIn(ExperimentalPathApi::class) +class TemporaryProfileTest { + + @Test + fun stop_deletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + assertFalse(browser.config.usesCustomDataDir) + assertTrue(profile.isDirectory, "the browser runs on a temporary profile") + assertTrue(profile.name.startsWith("kdriver_")) + + browser.stop() + + assertFalse(profile.exists(), "the temporary profile must be deleted by stop()") + assertFalse(browser in LaunchedBrowsers, "a stopped browser is no longer stopped on exit") + } + + @Test + fun stop_keepsACustomUserDataDir() = runBlocking { + val custom = createTempDirectory(prefix = "kdriver_custom_test_") + try { + val browser = createBrowser(this, userDataDir = Path(custom.toString()), headless = true, sandbox = false) + assertTrue(browser.config.usesCustomDataDir) + + browser.stop() + browser.cleanupTemporaryProfile() + + assertTrue(custom.exists(), "a userDataDir given by the caller must never be deleted") + assertTrue(custom.toFile().list().orEmpty().isNotEmpty(), "the browser's files in it are kept too") + } finally { + custom.deleteRecursively() + } + } + + @Test + fun secondStopAndCleanupAreHarmless() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + + browser.stop() + browser.stop() + browser.cleanupTemporaryProfile() + browser.cleanupTemporaryProfile() + + assertFalse(profile.exists()) + assertTrue(browser.stopped) + } + + @Test + fun exitHook_stopsRunningBrowsersAndDeletesTheirProfiles() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + assertTrue(browser in LaunchedBrowsers, "a launched browser is stopped on exit") + + // What the shutdown hook runs when the host process exits without calling stop(). + LaunchedBrowsers.stopAll() + + assertTrue(browser.stopped) + assertFalse(profile.exists(), "the temporary profile must be deleted on exit") + } + + @Test + fun copyOfAConfigDoesNotOwnItsTemporaryProfile() { + val original = Config(browserExecutablePath = Path("/usr/bin/chromium")) + val profile = original.userDataDir + try { + assertTrue(original.createdTemporaryProfile) + val copy = original.copy() + assertEquals(profile, copy.userDataDir, "the copy shares the profile…") + assertFalse(copy.createdTemporaryProfile, "…so it must not delete it") + } finally { + deleteRecursively(profile) + } + } + + @Test + fun deleteRecursively_removesNestedContent() { + val root = createTempDirectory(prefix = "kdriver_delete_test_") + Files.createDirectories(root.resolve("Default/Cache")) + root.resolve("Default/Cache/data").writeText("x") + root.resolve("Local State").writeText("{}") + + assertTrue(deleteRecursively(Path(root.toString()))) + assertFalse(root.exists()) + } + + @Test + fun deleteRecursively_doesNotFollowSymbolicLinks() { + val outside = createTempDirectory(prefix = "kdriver_outside_test_") + val kept = outside.resolve("kept").also { it.writeText("keep me") } + val root = createTempDirectory(prefix = "kdriver_delete_test_") + try { + val linked = runCatching { Files.createSymbolicLink(root.resolve("link"), outside) } + // Creating a symbolic link needs a privilege Windows does not grant by default. + if (linked.isFailure) return + + assertTrue(deleteRecursively(Path(root.toString()))) + + assertFalse(root.exists()) + assertTrue(kept.exists(), "what a link points to must never be deleted") + } finally { + root.deleteRecursively() + outside.deleteRecursively() + } + } + + @Test + fun deleteRecursively_isTrueForAMissingDirectory() { + val missing = createTempDirectory(prefix = "kdriver_missing_test_").also { Files.delete(it) } + + assertTrue(deleteRecursively(Path(missing.toString()))) + } + +} diff --git a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt index 077cd35b9..e0af86306 100644 --- a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt +++ b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt @@ -8,6 +8,18 @@ import kotlinx.io.files.Path import platform.posix.* private class PosixProcess(override val processIdentifier: Int) : Process() { + private var reaped = false + + /** + * Reaps the child once it has exited. Nothing else waits for it here, so without this it stays a + * zombie and [isAlive] never turns false. Remembered, because the pid may be reused afterwards. + */ + @OptIn(ExperimentalForeignApi::class) + override fun hasExited(): Boolean { + if (!reaped) reaped = waitpid(processIdentifier, null, WNOHANG) == processIdentifier + return reaped + } + override fun destroy() { if (isAlive()) { kill(processIdentifier, SIGTERM) diff --git a/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..2fb78c39e --- /dev/null +++ b/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,26 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.SystemFileSystem +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TemporaryProfileTest { + + @Test + fun stop_deletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = browser.config.userDataDir + assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") + + browser.stop() + assertFalse(SystemFileSystem.exists(profile), "the temporary profile must be deleted by stop()") + + // Stopping or cleaning up again is harmless. + browser.stop() + browser.cleanupTemporaryProfile() + assertFalse(SystemFileSystem.exists(profile)) + } + +} diff --git a/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt b/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt index 9421248ba..ffda98045 100644 --- a/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt +++ b/core/src/macosMain/kotlin/dev/kdriver/core/browser/Process.macos.kt @@ -13,6 +13,9 @@ private class NSTaskProcess(private val task: NSTask) : Process() { override val processIdentifier: Int get() = task.processIdentifier + /** NSTask reaps its own child, and knows when it has exited. */ + override fun hasExited(): Boolean = !task.isRunning() + override fun destroy() { if (task.isRunning()) { task.terminate() diff --git a/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..2fb78c39e --- /dev/null +++ b/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,26 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.SystemFileSystem +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TemporaryProfileTest { + + @Test + fun stop_deletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = browser.config.userDataDir + assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") + + browser.stop() + assertFalse(SystemFileSystem.exists(profile), "the temporary profile must be deleted by stop()") + + // Stopping or cleaning up again is harmless. + browser.stop() + browser.cleanupTemporaryProfile() + assertFalse(SystemFileSystem.exists(profile)) + } + +} diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt index c62e3b8f8..e748eba4f 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt @@ -19,7 +19,7 @@ actual abstract class Process { val handle = processHandle ?: return false val exitCode = memScoped { val code = alloc() - GetExitCodeProcess(handle, code.ptr) + if (GetExitCodeProcess(handle, code.ptr) == 0) return false code.value } return exitCode == STILL_ACTIVE @@ -37,12 +37,15 @@ private class WindowsProcess( override val processHandle: HANDLE?, override val processId: DWORD, ) : Process() { + /** + * Keeps the handle open: [isAlive] reads the exit code through it after `destroy`, to know when the + * process is really gone (and its profile can be deleted). A closed handle would make it guess. + */ override fun destroy() { processHandle?.let { if (isAlive()) { TerminateProcess(it, 1u) } - CloseHandle(it) } } } diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt new file mode 100644 index 000000000..431944be3 --- /dev/null +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt @@ -0,0 +1,55 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.* +import kotlinx.io.files.Path +import platform.windows.* + +@OptIn(ExperimentalForeignApi::class) +internal actual fun deleteRecursively(path: Path): Boolean { + val target = path.toString() + deleteEntry(target) + return GetFileAttributesW(target) == INVALID_FILE_ATTRIBUTES +} + +/** + * Deletes [path], and its content first if it is a directory. A junction or symbolic link (a reparse + * point) is removed itself, never followed. + */ +@OptIn(ExperimentalForeignApi::class) +private fun deleteEntry(path: String) { + val attributes = GetFileAttributesW(path) + if (attributes == INVALID_FILE_ATTRIBUTES) return + // DeleteFileW and RemoveDirectoryW both refuse a read-only entry. + val readOnly = FILE_ATTRIBUTE_READONLY.toUInt() + if (attributes and readOnly != 0u) SetFileAttributesW(path, attributes and readOnly.inv()) + + val isDirectory = attributes and FILE_ATTRIBUTE_DIRECTORY.toUInt() != 0u + val isLink = attributes and FILE_ATTRIBUTE_REPARSE_POINT.toUInt() != 0u + when { + isDirectory && !isLink -> { + children(path).forEach { deleteEntry("$path\\$it") } + RemoveDirectoryW(path) + } + + isDirectory -> RemoveDirectoryW(path) + else -> DeleteFileW(path) + } +} + +/** Lists the names in [path], read in full before anything is deleted from it. */ +@OptIn(ExperimentalForeignApi::class) +private fun children(path: String): List = memScoped { + val data = alloc() + val handle = FindFirstFileW("$path\\*", data.ptr) + if (handle == null || handle == INVALID_HANDLE_VALUE) return@memScoped emptyList() + val names = mutableListOf() + try { + do { + val name = data.cFileName.toKStringFromUtf16() + if (name != "." && name != "..") names += name + } while (FindNextFileW(handle, data.ptr) != 0) + } finally { + FindClose(handle) + } + names +} diff --git a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt new file mode 100644 index 000000000..2fb78c39e --- /dev/null +++ b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -0,0 +1,26 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.runBlocking +import kotlinx.io.files.SystemFileSystem +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TemporaryProfileTest { + + @Test + fun stop_deletesTheTemporaryProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = browser.config.userDataDir + assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") + + browser.stop() + assertFalse(SystemFileSystem.exists(profile), "the temporary profile must be deleted by stop()") + + // Stopping or cleaning up again is harmless. + browser.stop() + browser.cleanupTemporaryProfile() + assertFalse(SystemFileSystem.exists(profile)) + } + +} diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt index 61b2f1e21..06f31729a 100644 --- a/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt @@ -9,10 +9,17 @@ actual abstract class Process { abstract val processIdentifier: Int actual fun isAlive(): Boolean { + if (hasExited()) return false // Check if process exists by sending signal 0 return kill(processIdentifier, 0) == 0 } + /** + * Whether the process is known to have exited. Signal 0 alone cannot tell: a child that exited + * but was not reaped yet (a zombie) still has its pid, so it would look alive forever. + */ + protected open fun hasExited(): Boolean = false + actual fun pid(): Long { return processIdentifier.toLong() } diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt new file mode 100644 index 000000000..b91af97a1 --- /dev/null +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt @@ -0,0 +1,55 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.* +import kotlinx.io.files.Path +import platform.posix.* + +@OptIn(ExperimentalForeignApi::class) +internal actual fun deleteRecursively(path: Path): Boolean { + val target = path.toString() + deleteEntry(target) + return !entryExists(target) +} + +/** + * Deletes [path], and its content first if it is a directory. A symbolic link is unlinked, never + * followed: `lstat` describes the link itself. + */ +@OptIn(ExperimentalForeignApi::class) +private fun deleteEntry(path: String) { + if (isRealDirectory(path)) { + children(path).forEach { deleteEntry("$path/$it") } + rmdir(path) + } else { + unlink(path) + } +} + +/** Lists the names in [path], read in full before anything is deleted from it. */ +@OptIn(ExperimentalForeignApi::class) +private fun children(path: String): List { + val dir = opendir(path) ?: return emptyList() + val names = mutableListOf() + try { + while (true) { + val entry = readdir(dir) ?: break + val name = entry.pointed.d_name.toKString() + if (name != "." && name != "..") names += name + } + } finally { + closedir(dir) + } + return names +} + +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +private fun isRealDirectory(path: String): Boolean = memScoped { + val info = alloc() + lstat(path, info.ptr) == 0 && (info.st_mode.convert() and S_IFMT.convert()) == S_IFDIR.convert() +} + +@OptIn(ExperimentalForeignApi::class) +private fun entryExists(path: String): Boolean = memScoped { + val info = alloc() + lstat(path, info.ptr) == 0 +} From 37d11fea97c6a44d01206b2bb0771a90125699eb Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Wed, 18 Nov 2026 20:06:14 +0100 Subject: [PATCH 02/26] fix: address review of the temporary profile cleanup - Stop on JVM exit every started browser, connect-existing ones included, as the per-browser hook of create() did (registry renamed StartedBrowsers). - create() stops the browser when start() fails after launching it: the caller never gets the instance, so it could not. - stop() does not wait another 5 s for a process it has just waited for. - Windows: close the process handle once the process is seen to exit (atomically), instead of leaking it; exit code cached for exitCodeOrNull. - Linux: never reset the reaped flag; ECHILD from a racing waitpid means exited too. - POSIX delete: chmod a profile subdirectory before listing it, so one without read/search permission can still be emptied. - Restart hands the profile over under the new browser's mutex; kdoc says the exit hook is JVM only. Co-Authored-By: Claude Opus 5.5 --- .../kdriver/core/browser/DefaultBrowser.kt | 35 +++++++---- ...LaunchedBrowsers.kt => StartedBrowsers.kt} | 9 ++- .../core/browser/TemporaryProfileTest.kt | 6 +- .../dev/kdriver/core/browser/Process.linux.kt | 9 ++- .../dev/kdriver/core/browser/Process.mingw.kt | 58 ++++++++++++------- .../core/browser/TemporaryProfile.posix.kt | 5 +- 6 files changed, 82 insertions(+), 40 deletions(-) rename core/src/commonMain/kotlin/dev/kdriver/core/browser/{LaunchedBrowsers.kt => StartedBrowsers.kt} (85%) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 4cd8e676e..d59c0f0e5 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -129,9 +129,15 @@ open class DefaultBrowser( suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser { val browserScope = CoroutineScope(coroutineScope.coroutineContext + SupervisorJob()) val instance = DefaultBrowser(browserScope, config) - // start() registers the launched browser with LaunchedBrowsers, whose shutdown hook stops - // it and deletes its temporary profile if the host process exits without calling stop(). - instance.start() + // start() registers the browser with StartedBrowsers, whose shutdown hook stops it and + // deletes its temporary profile if the host process exits without calling stop(). + try { + instance.start() + } catch (e: Throwable) { + // The caller never gets this instance, so it could never stop the browser it launched. + withContext(NonCancellable) { instance.stop() } + throw e + } return instance } @@ -295,8 +301,8 @@ open class DefaultBrowser( } process = launched temporaryProfileUser = launched - LaunchedBrowsers.register(this) } + StartedBrowsers.register(this) logger.info("Browser process started with PID: ${process?.pid()}") if (config.browserUrl == null && config.port == null) error("Port not set") @@ -372,7 +378,7 @@ open class DefaultBrowser( val inherited = temporaryProfile temporaryProfile = null temporaryProfileUser = null - LaunchedBrowsers.unregister(this) + StartedBrowsers.unregister(this) val restarted = try { create(coroutineScope, config) } catch (e: Throwable) { @@ -382,12 +388,16 @@ open class DefaultBrowser( throw e } if (inherited != null) { - if (restarted is DefaultBrowser) restarted.temporaryProfile = inherited + if (restarted is DefaultBrowser) restarted.adoptTemporaryProfile(inherited) else logger.warn("Temporary profile $inherited will not be deleted") } return restarted } + private suspend fun adoptTemporaryProfile(profile: Path) = temporaryProfileMutex.withLock { + temporaryProfile = profile + } + private suspend fun handleTargetUpdate(event: Any) = updateTargetInfoMutex.withLock { when (event) { // Both create and info-changed go through the same dedupe-by-targetId upsert, so an @@ -451,9 +461,10 @@ open class DefaultBrowser( // Before cancelling the scope, which may be the caller's own; and non-cancellable, so a stop() // called from a `finally` of a cancelled coroutine still deletes the profile. withContext(NonCancellable) { - cleanupTemporaryProfile() + // No further wait: the process has just been waited for, and killed if it lingered. + cleanupTemporaryProfile(releaseTimeoutMillis = 0) // Still registered if the profile could not be deleted, so the exit hook tries again. - if (temporaryProfile == null) LaunchedBrowsers.unregister(this@DefaultBrowser) + if (temporaryProfile == null) StartedBrowsers.unregister(this@DefaultBrowser) } logger.debug("Canceling coroutine scope...") coroutineScope.cancel() @@ -466,7 +477,7 @@ open class DefaultBrowser( // keeps the shutdown hook from stopping a browser we chose to leave running. Its temporary // profile is kept too, since the browser still runs on it. process = null - LaunchedBrowsers.unregister(this) + StartedBrowsers.unregister(this) val targets = updateTargetInfoMutex.withLock { detached = true mutableTargets.toList().also { @@ -483,12 +494,14 @@ open class DefaultBrowser( logger.info("Detached from browser") } - override suspend fun cleanupTemporaryProfile() = temporaryProfileMutex.withLock { + override suspend fun cleanupTemporaryProfile() = cleanupTemporaryProfile(PROFILE_RELEASE_TIMEOUT_MS) + + private suspend fun cleanupTemporaryProfile(releaseTimeoutMillis: Long) = temporaryProfileMutex.withLock { val profile = temporaryProfile ?: return@withLock // The browser keeps writing to its profile while it shuts down: deleting it earlier would race // those writes, and leave files (or recreated directories) behind. val user = temporaryProfileUser - if (user != null && !user.awaitExit(PROFILE_RELEASE_TIMEOUT_MS)) { + if (user != null && !user.awaitExit(releaseTimeoutMillis)) { logger.warn("Not deleting temporary profile $profile: browser process ${user.pid()} is still running") return@withLock } diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt similarity index 85% rename from core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt rename to core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt index 77e58f12b..d434ec8d6 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/LaunchedBrowsers.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt @@ -8,19 +8,22 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** - * The browsers this process launched and has not stopped yet. + * The browsers this process started and has not stopped (nor detached) yet. * * When the host process exits without calling [Browser.stop], they are stopped from a single * shutdown hook (see [addShutdownHook]), which also deletes their temporary profiles. Without it, a * program that simply returns from `main` leaves a `kdriver_*` profile behind on every run. * + * Only the JVM has such a hook: [addShutdownHook] does nothing on the native and JS targets, where + * a browser that is never stopped keeps its profile on disk. + * * One hook for the whole process rather than one per browser: a hook cannot be removed once added, * so a hook per browser would keep every browser ever created reachable until the process exits. * A browser leaves this registry as soon as it is stopped or detached. */ -internal object LaunchedBrowsers { +internal object StartedBrowsers { - private val logger = KtorSimpleLogger("LaunchedBrowsers") + private val logger = KtorSimpleLogger("StartedBrowsers") private val mutex = Mutex() private val browsers = LinkedHashSet() private var hookInstalled = false diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 3f82d828f..f0f5d2da5 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -32,7 +32,7 @@ class TemporaryProfileTest { browser.stop() assertFalse(profile.exists(), "the temporary profile must be deleted by stop()") - assertFalse(browser in LaunchedBrowsers, "a stopped browser is no longer stopped on exit") + assertFalse(browser in StartedBrowsers, "a stopped browser is no longer stopped on exit") } @Test @@ -70,10 +70,10 @@ class TemporaryProfileTest { fun exitHook_stopsRunningBrowsersAndDeletesTheirProfiles() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val profile = File(browser.config.userDataDir.toString()) - assertTrue(browser in LaunchedBrowsers, "a launched browser is stopped on exit") + assertTrue(browser in StartedBrowsers, "a launched browser is stopped on exit") // What the shutdown hook runs when the host process exits without calling stop(). - LaunchedBrowsers.stopAll() + StartedBrowsers.stopAll() assertTrue(browser.stopped) assertFalse(profile.exists(), "the temporary profile must be deleted on exit") diff --git a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt index e0af86306..bee364153 100644 --- a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt +++ b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/Process.linux.kt @@ -6,17 +6,24 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.withContext import kotlinx.io.files.Path import platform.posix.* +import kotlin.concurrent.Volatile private class PosixProcess(override val processIdentifier: Int) : Process() { + @Volatile private var reaped = false /** * Reaps the child once it has exited. Nothing else waits for it here, so without this it stays a * zombie and [isAlive] never turns false. Remembered, because the pid may be reused afterwards. + * + * Only ever set to true: when two threads race, the loser gets `ECHILD` (already reaped), which + * means exited too. */ @OptIn(ExperimentalForeignApi::class) override fun hasExited(): Boolean { - if (!reaped) reaped = waitpid(processIdentifier, null, WNOHANG) == processIdentifier + if (reaped) return true + val result = waitpid(processIdentifier, null, WNOHANG) + if (result == processIdentifier || (result == -1 && errno == ECHILD)) reaped = true return reaped } diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt index e748eba4f..11a900729 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt @@ -8,6 +8,8 @@ import kotlinx.io.files.Path import platform.posix.getenv import platform.posix.memset import platform.windows.* +import kotlin.concurrent.AtomicReference +import kotlin.concurrent.Volatile import kotlin.random.Random @OptIn(ExperimentalForeignApi::class) @@ -15,16 +17,32 @@ actual abstract class Process { abstract val processHandle: HANDLE? abstract val processId: DWORD + /** The exit code, once the process has been seen to exit; its handle is closed from then on. */ + @Volatile + internal var exitCode: DWORD? = null + private set + actual fun isAlive(): Boolean { + if (exitCode != null) return false val handle = processHandle ?: return false - val exitCode = memScoped { - val code = alloc() - if (GetExitCodeProcess(handle, code.ptr) == 0) return false - code.value + val code = memScoped { + val c = alloc() + if (GetExitCodeProcess(handle, c.ptr) == 0) return false + c.value } - return exitCode == STILL_ACTIVE + if (code == STILL_ACTIVE) return true + exitCode = code + releaseHandle() + return false } + /** + * Closes the process handle, once the process has exited and nothing needs it anymore. Kept open + * until then, `destroy` included: [isAlive] reads the exit code through it, to know when the + * process is really gone (and its profile can be deleted). + */ + protected abstract fun releaseHandle() + actual fun pid(): Long { return processId.toLong() } @@ -34,13 +52,19 @@ actual abstract class Process { @OptIn(ExperimentalForeignApi::class) private class WindowsProcess( - override val processHandle: HANDLE?, + processHandle: HANDLE?, override val processId: DWORD, ) : Process() { - /** - * Keeps the handle open: [isAlive] reads the exit code through it after `destroy`, to know when the - * process is really gone (and its profile can be deleted). A closed handle would make it guess. - */ + private val handle = AtomicReference(processHandle) + + override val processHandle: HANDLE? + get() = handle.value + + /** Atomic, so two threads seeing the exit at once do not close the same handle twice. */ + override fun releaseHandle() { + handle.getAndSet(null)?.let { CloseHandle(it) } + } + override fun destroy() { processHandle?.let { if (isAlive()) { @@ -65,19 +89,11 @@ actual suspend fun Process.readStderrSnapshot(maxBytes: Int, timeoutMillis: Long * the one running browsers in production, uses `ProcessHandle.descendants()` for that. */ /** - * Reads the exit status via `GetExitCodeProcess`, the same call [Process.isAlive] uses — null while - * it still reports `STILL_ACTIVE`. + * Reads the exit status recorded by [Process.isAlive] through `GetExitCodeProcess` — null while the + * process still runs. */ @OptIn(ExperimentalForeignApi::class) -actual fun Process.exitCodeOrNull(): Int? { - val handle = processHandle ?: return null - val code = memScoped { - val c = alloc() - GetExitCodeProcess(handle, c.ptr) - c.value - } - return if (code == STILL_ACTIVE) null else code.toInt() -} +actual fun Process.exitCodeOrNull(): Int? = if (isAlive()) null else exitCode?.toInt() @OptIn(ExperimentalForeignApi::class) actual fun Process.killTree() { diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt index b91af97a1..3ffd9f315 100644 --- a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt @@ -15,9 +15,12 @@ internal actual fun deleteRecursively(path: Path): Boolean { * Deletes [path], and its content first if it is a directory. A symbolic link is unlinked, never * followed: `lstat` describes the link itself. */ -@OptIn(ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) private fun deleteEntry(path: String) { if (isRealDirectory(path)) { + // A directory without read or search permission cannot be listed nor emptied. It is ours (it + // is inside the profile we created), and lstat said it is not a link, so chmod is safe here. + chmod(path, S_IRWXU.convert()) children(path).forEach { deleteEntry("$path/$it") } rmdir(path) } else { From 333127efcd28a533c2ca9f12b0816b4e2b11b141 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Wed, 18 Nov 2026 20:11:27 +0100 Subject: [PATCH 03/26] refactor: try/finally instead of catching Throwable in the profile cleanup paths Co-Authored-By: Claude Opus 5.5 --- .../kdriver/core/browser/DefaultBrowser.kt | 36 ++++++++++--------- .../core/browser/TemporaryProfile.jvm.kt | 3 +- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index d59c0f0e5..17c951ca6 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -131,12 +131,14 @@ open class DefaultBrowser( val instance = DefaultBrowser(browserScope, config) // start() registers the browser with StartedBrowsers, whose shutdown hook stops it and // deletes its temporary profile if the host process exits without calling stop(). + var started = false try { instance.start() - } catch (e: Throwable) { - // The caller never gets this instance, so it could never stop the browser it launched. - withContext(NonCancellable) { instance.stop() } - throw e + started = true + } finally { + // On failure the caller never gets this instance, so it could never stop the browser + // it launched. + if (!started) withContext(NonCancellable) { instance.stop() } } return instance } @@ -293,11 +295,11 @@ open class DefaultBrowser( if (!config.usesCustomDataDir && config.createdTemporaryProfile) { temporaryProfile = config.userDataDir } - val launched = try { - startProcess(exe, params) - } catch (e: Throwable) { - withContext(NonCancellable) { cleanupTemporaryProfile() } - throw e + var launched: Process? = null + try { + launched = startProcess(exe, params) + } finally { + if (launched == null) withContext(NonCancellable) { cleanupTemporaryProfile() } } process = launched temporaryProfileUser = launched @@ -379,13 +381,15 @@ open class DefaultBrowser( temporaryProfile = null temporaryProfileUser = null StartedBrowsers.unregister(this) - val restarted = try { - create(coroutineScope, config) - } catch (e: Throwable) { - // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. - temporaryProfile = inherited - withContext(NonCancellable) { cleanupTemporaryProfile() } - throw e + var restarted: Browser? = null + try { + restarted = create(coroutineScope, config) + } finally { + if (restarted == null) { + // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. + temporaryProfile = inherited + withContext(NonCancellable) { cleanupTemporaryProfile() } + } } if (inherited != null) { if (restarted is DefaultBrowser) restarted.adoptTemporaryProfile(inherited) diff --git a/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt index 299273a6e..45326b6a2 100644 --- a/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt +++ b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.jvm.kt @@ -1,6 +1,7 @@ package dev.kdriver.core.browser import kotlinx.io.files.Path +import java.io.IOException import java.nio.file.LinkOption import java.nio.file.Paths import kotlin.io.path.ExperimentalPathApi @@ -16,7 +17,7 @@ internal actual fun deleteRecursively(path: Path): Boolean { val target = Paths.get(path.toString()) try { target.deleteRecursively() - } catch (_: Exception) { + } catch (_: IOException) { // Reported below, through whether the directory is still there. } return !target.exists(LinkOption.NOFOLLOW_LINKS) From c16d59387f4a0d0ab76628a3b6b06d1e72b6cd87 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Wed, 18 Nov 2026 20:24:55 +0100 Subject: [PATCH 04/26] test: delete the custom profile with retries, Windows keeps it locked a moment Co-Authored-By: Claude Opus 5.5 --- .../kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index f0f5d2da5..528fa083b 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -48,7 +48,8 @@ class TemporaryProfileTest { assertTrue(custom.exists(), "a userDataDir given by the caller must never be deleted") assertTrue(custom.toFile().list().orEmpty().isNotEmpty(), "the browser's files in it are kept too") } finally { - custom.deleteRecursively() + // With retries: on Windows the browser's children may hold its files for a moment more. + deleteTemporaryProfile(Path(custom.toString())) } } From 17d33d97908f82dffdbbea18a68939e4b6960c48 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Wed, 18 Nov 2026 20:45:44 +0100 Subject: [PATCH 05/26] test: profile kept while the browser runs, retries give up on a locked entry Co-Authored-By: Claude Opus 5.5 --- .../core/browser/TemporaryProfileTest.kt | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 528fa083b..f97323747 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -67,6 +67,20 @@ class TemporaryProfileTest { assertTrue(browser.stopped) } + @Test + fun cleanup_keepsTheProfileWhileTheBrowserStillRuns() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + try { + // Not stopped: the browser keeps writing to its profile, which must not be deleted under it. + browser.cleanupTemporaryProfile() + assertTrue(profile.isDirectory, "a running browser's profile must be kept") + } finally { + browser.stop() + } + assertFalse(profile.exists(), "stop() deletes it once the browser is gone") + } + @Test fun exitHook_stopsRunningBrowsersAndDeletesTheirProfiles() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) @@ -125,6 +139,23 @@ class TemporaryProfileTest { } } + @Test + fun deleteTemporaryProfile_givesUpOnAnEntryItCannotDelete() = runBlocking { + // A read-only directory protects its entries on POSIX only, and never from root. + if (!isPosix() || isRoot()) return@runBlocking + val root = createTempDirectory(prefix = "kdriver_delete_test_") + val locked = Files.createDirectories(root.resolve("locked")) + locked.resolve("file").writeText("x") + locked.toFile().setWritable(false) + try { + assertFalse(deleteTemporaryProfile(Path(root.toString()), attempts = 2, retryDelayMillis = 10)) + assertTrue(locked.resolve("file").exists()) + } finally { + locked.toFile().setWritable(true) + root.deleteRecursively() + } + } + @Test fun deleteRecursively_isTrueForAMissingDirectory() { val missing = createTempDirectory(prefix = "kdriver_missing_test_").also { Files.delete(it) } From 4249cf2d7c2293f716716153c6b403249afdf1dd Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 14:54:06 +0100 Subject: [PATCH 06/26] refactor: address static analysis findings on the profile cleanup - StartedBrowsers.stopAll runs each stop in a supervisor scope with an exception handler, instead of catching Exception: a browser that fails to stop still does not keep the others running, and cancellation still propagates. - Windows Process.isAlive reads the exit code through a helper and returns once. - Native TemporaryProfileTest: camelCase test name and KDoc, as detekt requires outside the excluded test source sets. --- .../kdriver/core/browser/StartedBrowsers.kt | 24 +++++++++---------- .../core/browser/TemporaryProfileTest.kt | 6 ++++- .../core/browser/TemporaryProfileTest.kt | 6 ++++- .../dev/kdriver/core/browser/Process.mingw.kt | 21 ++++++++-------- .../core/browser/TemporaryProfileTest.kt | 6 ++++- 5 files changed, 38 insertions(+), 25 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt index d434ec8d6..1f3b178dd 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt @@ -1,9 +1,9 @@ package dev.kdriver.core.browser import io.ktor.util.logging.* -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.launch +import kotlinx.coroutines.supervisorScope import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -42,20 +42,20 @@ internal object StartedBrowsers { suspend operator fun contains(browser: Browser): Boolean = mutex.withLock { browser in browsers } - /** Stops every browser still registered, concurrently, so their grace periods overlap. */ + /** + * Stops every browser still registered, concurrently, so their grace periods overlap. + * + * A browser that fails to stop is logged and does not keep the others from stopping: each runs in + * its own child of a supervisor scope, whose failure goes to a handler rather than to its siblings. + */ internal suspend fun stopAll() { val remaining = mutex.withLock { browsers.toList() } - coroutineScope { + supervisorScope { remaining.forEach { browser -> - launch { - try { - browser.stop() - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - logger.warn("Could not stop browser ${browser.pid} on exit: ${e.message}") - } + val onFailure = CoroutineExceptionHandler { _, e -> + logger.warn("Could not stop browser ${browser.pid} on exit: ${e.message}") } + launch(onFailure) { browser.stop() } } } } diff --git a/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 2fb78c39e..400105b68 100644 --- a/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/linuxTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -6,10 +6,14 @@ import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue +/** + * The temporary profile is deleted by this platform's own recursive delete once the browser stops. + */ class TemporaryProfileTest { + /** The profile is gone after `stop()`; stopping or cleaning up again is harmless. */ @Test - fun stop_deletesTheTemporaryProfile() = runBlocking { + fun stopDeletesTheTemporaryProfile() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val profile = browser.config.userDataDir assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") diff --git a/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 2fb78c39e..400105b68 100644 --- a/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/macosTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -6,10 +6,14 @@ import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue +/** + * The temporary profile is deleted by this platform's own recursive delete once the browser stops. + */ class TemporaryProfileTest { + /** The profile is gone after `stop()`; stopping or cleaning up again is harmless. */ @Test - fun stop_deletesTheTemporaryProfile() = runBlocking { + fun stopDeletesTheTemporaryProfile() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val profile = browser.config.userDataDir assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt index 11a900729..b0cfef87d 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt @@ -23,17 +23,18 @@ actual abstract class Process { private set actual fun isAlive(): Boolean { - if (exitCode != null) return false - val handle = processHandle ?: return false - val code = memScoped { - val c = alloc() - if (GetExitCodeProcess(handle, c.ptr) == 0) return false - c.value + // Null once the exit was seen (the handle is closed then), without a handle, or if unreadable. + val code = if (exitCode == null) processHandle?.let { readExitCode(it) } else null + if (code != null && code != STILL_ACTIVE) { + exitCode = code + releaseHandle() } - if (code == STILL_ACTIVE) return true - exitCode = code - releaseHandle() - return false + return code == STILL_ACTIVE + } + + private fun readExitCode(handle: HANDLE): DWORD? = memScoped { + val c = alloc() + if (GetExitCodeProcess(handle, c.ptr) == 0) null else c.value } /** diff --git a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 2fb78c39e..400105b68 100644 --- a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -6,10 +6,14 @@ import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue +/** + * The temporary profile is deleted by this platform's own recursive delete once the browser stops. + */ class TemporaryProfileTest { + /** The profile is gone after `stop()`; stopping or cleaning up again is harmless. */ @Test - fun stop_deletesTheTemporaryProfile() = runBlocking { + fun stopDeletesTheTemporaryProfile() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val profile = browser.config.userDataDir assertTrue(SystemFileSystem.exists(profile), "the browser runs on a temporary profile") From f1767f6577fcd8ae65dad09244065445d1638b1f Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:05:38 +0100 Subject: [PATCH 07/26] test: cover every temporary profile cleanup path New JVM tests, with internal seams only (no public API change): the logger, the release timeout and the profile deletion of DefaultBrowser, a factory for DefaultBrowser.create, the relaunch of a dead browser, and one delete attempt of deleteTemporaryProfile. - a profile inherited through Config.copy() is never deleted; - a process still running after the bounded wait keeps its profile and logs a warning; - a profile is deleted when the process cannot be launched, and when create() fails after the launch (the browser is stopped too); - a failed delete in stop() logs a warning and keeps the browser registered, so the exit hook deletes the profile later; - deleteTemporaryProfile retries with a delay between attempts, stops at the first success, and gives up after the last attempt; - the exit hook stops the other browsers when one fails to stop; - stop() on a browser that died still deletes its profile; - restart on a dead process: the profile is handed over to the new browser, or deleted when the relaunch fails. The restart test found that a restarted browser never launched a process: it inherited the host and port assigned to the dead one, took the connect-existing branch, and timed out on the dead port. The relaunch now clears them so the new browser gets a port of its own. It also found that stop() on a browser that had died threw from the graceful Browser.close (nothing answers anymore), before reaching the kill and the profile deletion: a crashed browser kept its profile. An I/O failure of that close is now logged and stop() goes on. --- .../kdriver/core/browser/DefaultBrowser.kt | 51 +++- .../kdriver/core/browser/TemporaryProfile.kt | 4 +- .../core/browser/TemporaryProfileTest.kt | 251 +++++++++++++++++- 3 files changed, 291 insertions(+), 15 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 17c951ca6..9584f66c4 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -15,6 +15,7 @@ import io.ktor.util.logging.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.io.IOException import kotlinx.io.files.Path import kotlin.concurrent.Volatile import kotlin.time.Duration.Companion.seconds @@ -38,7 +39,8 @@ open class DefaultBrowser( */ override val config: Config = config.copy() - private val logger = KtorSimpleLogger("Browser") + /** Internal so tests can observe what is logged, such as a profile left on disk. */ + internal var logger: Logger = KtorSimpleLogger("Browser") private val updateTargetInfoMutex = Mutex() private var process: Process? = null @@ -55,6 +57,12 @@ open class DefaultBrowser( */ private var temporaryProfileUser: Process? = null private val temporaryProfileMutex = Mutex() + + /** How long [cleanupTemporaryProfile] waits for the browser process to exit; shortened by tests. */ + internal var profileReleaseTimeoutMillis: Long = PROFILE_RELEASE_TIMEOUT_MS + + /** Deletes the temporary profile, with retries; replaced by tests to simulate a locked profile. */ + internal var deleteProfile: suspend (Path) -> Boolean = { deleteTemporaryProfile(it) } private var http: HTTPApi? = null private var _cookies: CookieJar? = null @@ -126,9 +134,17 @@ open class DefaultBrowser( * * @return A new instance of the Browser class. */ - suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser { + suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser = + create(coroutineScope, config, ::DefaultBrowser) + + /** [create], with the instance built by [factory]: tests use it to make the start fail. */ + internal suspend fun create( + coroutineScope: CoroutineScope, + config: Config, + factory: (CoroutineScope, Config) -> DefaultBrowser, + ): DefaultBrowser { val browserScope = CoroutineScope(coroutineScope.coroutineContext + SupervisorJob()) - val instance = DefaultBrowser(browserScope, config) + val instance = factory(browserScope, config) // start() registers the browser with StartedBrowsers, whose shutdown hook stops it and // deletes its temporary profile if the host process exits without calling stop(). var started = false @@ -381,9 +397,14 @@ open class DefaultBrowser( temporaryProfile = null temporaryProfileUser = null StartedBrowsers.unregister(this) - var restarted: Browser? = null + var restarted: DefaultBrowser? = null try { - restarted = create(coroutineScope, config) + restarted = relaunch(config.copy().apply { + // The host and port start() assigned to the dead process: the new browser gets its own. + // Kept, they would make it connect to that dead port instead of launching a browser. + host = null + port = null + }) } finally { if (restarted == null) { // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. @@ -391,13 +412,13 @@ open class DefaultBrowser( withContext(NonCancellable) { cleanupTemporaryProfile() } } } - if (inherited != null) { - if (restarted is DefaultBrowser) restarted.adoptTemporaryProfile(inherited) - else logger.warn("Temporary profile $inherited will not be deleted") - } + if (inherited != null) restarted.adoptTemporaryProfile(inherited) return restarted } + /** Launches the browser that replaces this one in [restart]; overridden by tests to make it fail. */ + internal open suspend fun relaunch(config: Config): DefaultBrowser = create(coroutineScope, config, ::DefaultBrowser) + private suspend fun adoptTemporaryProfile(profile: Path) = temporaryProfileMutex.withLock { temporaryProfile = profile } @@ -446,7 +467,13 @@ open class DefaultBrowser( override suspend fun stop() { logger.info("Stopping browser process with PID: ${process?.pid()}") logger.debug("Closing browser gracefully...") - withTimeoutOrNull(5.seconds) { connection?.browser?.close() } + try { + withTimeoutOrNull(5.seconds) { connection?.browser?.close() } + } catch (e: IOException) { + // Nothing answers: the browser already died (crashed, or killed from outside). Its process + // and its profile are still dealt with below. + logger.debug("Could not close the browser gracefully: ${e.message}") + } logger.debug("Killing browser process...") // Wait for it to actually be gone, don't just ask. destroy() returns immediately and does not // reach the browser's child processes, which keep open handles on the profile directory — @@ -498,7 +525,7 @@ open class DefaultBrowser( logger.info("Detached from browser") } - override suspend fun cleanupTemporaryProfile() = cleanupTemporaryProfile(PROFILE_RELEASE_TIMEOUT_MS) + override suspend fun cleanupTemporaryProfile() = cleanupTemporaryProfile(profileReleaseTimeoutMillis) private suspend fun cleanupTemporaryProfile(releaseTimeoutMillis: Long) = temporaryProfileMutex.withLock { val profile = temporaryProfile ?: return@withLock @@ -509,7 +536,7 @@ open class DefaultBrowser( logger.warn("Not deleting temporary profile $profile: browser process ${user.pid()} is still running") return@withLock } - if (deleteTemporaryProfile(profile)) { + if (deleteProfile(profile)) { logger.debug("Deleted temporary profile $profile") temporaryProfile = null temporaryProfileUser = null diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt index 9478aca91..af9191b84 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt @@ -21,15 +21,17 @@ internal expect fun deleteRecursively(path: Path): Boolean * (on Windows by a child process that is still winding down, or by an antivirus scanning it), so a * single attempt is not enough. * + * @param delete one attempt, [deleteRecursively] outside of tests. * @return true if the profile is gone. */ internal suspend fun deleteTemporaryProfile( path: Path, attempts: Int = PROFILE_DELETE_ATTEMPTS, retryDelayMillis: Long = PROFILE_DELETE_RETRY_DELAY_MILLIS, + delete: (Path) -> Boolean = ::deleteRecursively, ): Boolean { repeat(attempts) { attempt -> - if (deleteRecursively(path)) return true + if (delete(path)) return true if (attempt < attempts - 1) delay(retryDelayMillis) } return false diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index f97323747..9fc0e487f 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -1,18 +1,35 @@ package dev.kdriver.core.browser +import dev.kdriver.cdp.domain.browser +import io.ktor.util.logging.Logger +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.io.files.Path import java.io.File +import java.io.IOException import java.nio.file.Files import kotlin.io.path.createTempDirectory +import kotlin.io.path.createTempFile import kotlin.io.path.deleteRecursively import kotlin.io.path.ExperimentalPathApi import kotlin.io.path.exists import kotlin.io.path.writeText import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.measureTime /** * The temporary profile kdriver creates when no `userDataDir` is given must be deleted once the @@ -69,18 +86,169 @@ class TemporaryProfileTest { @Test fun cleanup_keepsTheProfileWhileTheBrowserStillRuns() = runBlocking { - val browser = createBrowser(this, headless = true, sandbox = false) + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser val profile = File(browser.config.userDataDir.toString()) + val logger = mockk(relaxed = true) + browser.logger = logger + browser.profileReleaseTimeoutMillis = 300 try { // Not stopped: the browser keeps writing to its profile, which must not be deleted under it. - browser.cleanupTemporaryProfile() + val waited = measureTime { browser.cleanupTemporaryProfile() } + assertTrue(profile.isDirectory, "a running browser's profile must be kept") + assertTrue(waited >= 300.milliseconds, "it waits for the process to exit first, waited $waited") + verify { logger.warn(match { "is still running" in it && profile.path in it }) } } finally { browser.stop() } assertFalse(profile.exists(), "stop() deletes it once the browser is gone") } + @Test + fun stop_keepsATemporaryProfileInheritedThroughCopy() = runBlocking { + val config = Config(headless = true, sandbox = false) + // Reading it creates the temporary profile on this config: the browser's own copy inherits it. + val profile = File(config.userDataDir.toString()) + try { + val browser = createBrowser(this, config) + assertEquals(config.userDataDir, browser.config.userDataDir, "the browser runs on the inherited profile") + assertFalse(browser.config.createdTemporaryProfile) + + browser.stop() + + assertTrue(profile.isDirectory, "a profile the browser did not create must not be deleted") + assertFalse(browser in StartedBrowsers) + } finally { + deleteTemporaryProfile(Path(profile.path)) + } + } + + @Test + fun start_deletesTheProfileWhenTheProcessCannotBeLaunched() = runBlocking { + // An existing file that is not an executable: launching it fails on every platform. + val notABrowser = createTempFile(prefix = "kdriver_not_a_browser_", suffix = ".txt") + notABrowser.writeText("not a browser") + try { + val browser = DefaultBrowser(this, Config(browserExecutablePath = Path(notABrowser.toString()))) + + assertFailsWith { browser.start() } + + val profile = File(browser.config.userDataDir.toString()) + assertTrue(profile.name.startsWith("kdriver_"), "the start created a temporary profile") + assertFalse(profile.exists(), "a profile no browser ever ran on is deleted at once") + assertFalse(browser in StartedBrowsers) + } finally { + Files.deleteIfExists(notABrowser) + } + } + + @Test + fun create_stopsTheBrowserItLaunchedWhenTheStartFailsAfterTheLaunch() = runBlocking { + var launched: DefaultBrowser? = null + val failure = assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + override suspend fun start(): Browser { + super.start() + error("target discovery failed") + } + }.also { launched = it } + } + } + assertEquals("target discovery failed", failure.message) + + // The caller never got this instance, so create() had to stop it. + val browser = assertNotNull(launched) + assertTrue(browser.stopped, "the browser process must be stopped") + assertFalse(File(browser.config.userDataDir.toString()).exists(), "and its profile deleted") + assertFalse(browser in StartedBrowsers) + } + + @Test + fun start_afterTheProcessDied_relaunchesOnTheSameProfileAndHandsItsDeletionOver() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + killFromOutside(browser) + + val restarted = browser.start() + try { + assertNotSame(browser, restarted) + assertFalse(restarted.stopped, "a new browser process runs") + assertEquals(browser.config.userDataDir, restarted.config.userDataDir, "on the same profile") + assertNotNull(restarted.pid, "it launched a process, rather than connecting to the dead one's port") + assertFalse(browser in StartedBrowsers, "the dead browser is no longer stopped on exit") + assertTrue(restarted in StartedBrowsers) + + browser.cleanupTemporaryProfile() + assertTrue(profile.isDirectory, "the dead browser no longer deletes the profile the new one runs on") + } finally { + restarted.stop() + browser.stop() + } + assertFalse(profile.exists(), "the new browser deletes it when it stops") + } + + @Test + fun stop_afterTheProcessDied_stillDeletesTheProfile() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + killFromOutside(browser) + + // Nothing answers the graceful close anymore: that must not keep stop() from cleaning up. + browser.stop() + + assertFalse(profile.exists(), "a crashed browser's profile is deleted by stop() too") + assertFalse(browser in StartedBrowsers) + } + + @Test + fun start_afterTheProcessDied_deletesTheProfileWhenTheRelaunchFails() = runBlocking { + val browser = DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + override suspend fun relaunch(config: Config): DefaultBrowser = throw IOException("no browser") + } + } + val profile = File(browser.config.userDataDir.toString()) + try { + killFromOutside(browser) + + assertFailsWith { browser.start() } + + assertFalse(profile.exists(), "nothing runs on the profile anymore: it is deleted") + assertFalse(browser in StartedBrowsers) + } finally { + browser.stop() + } + } + + @Test + fun stop_whenTheProfileCannotBeDeleted_keepsTheBrowserForTheExitHook() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val logger = mockk(relaxed = true) + browser.logger = logger + var attempts = 0 + browser.deleteProfile = { + attempts++ + false + } + + browser.stop() + + assertTrue(browser.stopped) + assertEquals(1, attempts) + assertTrue(profile.isDirectory, "a profile that could not be deleted stays on disk") + verify { logger.warn(match { "Could not delete temporary profile" in it && profile.path in it }) } + assertTrue(browser in StartedBrowsers, "the exit hook must try again") + + // The lock is gone by the time the host process exits. + browser.deleteProfile = { deleteTemporaryProfile(it) } + StartedBrowsers.stopAll() + + assertFalse(profile.exists(), "the exit hook deletes it") + assertFalse(browser in StartedBrowsers) + } + @Test fun exitHook_stopsRunningBrowsersAndDeletesTheirProfiles() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) @@ -163,4 +331,83 @@ class TemporaryProfileTest { assertTrue(deleteRecursively(Path(missing.toString()))) } + @Test + fun deleteTemporaryProfile_retriesUntilTheProfileIsGone() = runTest { + val profile = Path("kdriver_profile") + val seen = mutableListOf() + + val gone = deleteTemporaryProfile(profile, attempts = 5, retryDelayMillis = 200) { + seen += it + seen.size == 3 + } + + assertTrue(gone) + assertEquals(listOf(profile, profile, profile), seen, "stops at the first attempt that succeeds") + assertEquals(400, currentTime, "waits between two attempts") + } + + @Test + fun deleteTemporaryProfile_givesUpAfterItsLastAttempt() = runTest { + var attempts = 0 + + val gone = deleteTemporaryProfile(Path("kdriver_profile"), attempts = 4, retryDelayMillis = 200) { + attempts++ + false + } + + assertFalse(gone) + assertEquals(4, attempts) + assertEquals(600, currentTime, "no wait after the last attempt") + } + + @Test + fun deleteTemporaryProfile_triesTenTimesOverAboutTwoSecondsByDefault() = runTest { + var attempts = 0 + + assertFalse(deleteTemporaryProfile(Path("kdriver_profile")) { attempts++; false }) + + assertEquals(10, attempts) + assertEquals(1_800, currentTime) + } + + @Test + fun exitHook_stopsTheOtherBrowsersWhenOneFailsToStop() = runBlocking { + val scope = this + val unused = Config(browserExecutablePath = Path("unused")) + val failing = object : DefaultBrowser(scope, unused) { + override suspend fun stop() { + throw IllegalStateException("cannot stop") + } + } + val stopped = mutableListOf() + val others = List(2) { + object : DefaultBrowser(scope, unused) { + override suspend fun stop() { + stopped += this + } + } + } + val all = listOf(failing) + others + all.forEach { StartedBrowsers.register(it) } + try { + StartedBrowsers.stopAll() + + assertEquals(others.toSet(), stopped.toSet(), "a failure must not keep the other browsers running") + } finally { + all.forEach { StartedBrowsers.unregister(it) } + } + } + + /** Ends the browser process behind kdriver's back, as a crash would, and waits until it is gone. */ + private suspend fun killFromOutside(browser: Browser) { + try { + withTimeoutOrNull(5.seconds) { browser.connection?.browser?.close() } + } catch (_: IOException) { + // The browser may drop the connection before it answers: its exit is what is awaited below. + } + withTimeout(10.seconds) { + while (!browser.stopped) delay(50) + } + } + } From 9db02747d69829863b34c11a7a55d970ad2a6eb1 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:11:18 +0100 Subject: [PATCH 08/26] fix: let stop() go on when the graceful close finds the connection closed The connection layer reports a browser that no longer answers as ConnectionClosedException (a RuntimeException) once every send attempt has failed, not only as an IOException: stop() must go on to the kill and the profile deletion in both cases. Both are now covered by tests on a connection whose Browser.close fails. --- .../kdriver/core/browser/DefaultBrowser.kt | 4 +++ .../core/browser/TemporaryProfileTest.kt | 31 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 9584f66c4..67578a21d 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -8,6 +8,7 @@ import dev.kdriver.core.connection.Connection import dev.kdriver.core.connection.DefaultConnection import dev.kdriver.core.connection.OwnedConnection import dev.kdriver.core.exceptions.BrowserExecutableNotFoundException +import dev.kdriver.core.exceptions.ConnectionClosedException import dev.kdriver.core.exceptions.FailedToConnectToBrowserException import dev.kdriver.core.tab.DefaultTab import dev.kdriver.core.tab.Tab @@ -473,6 +474,9 @@ open class DefaultBrowser( // Nothing answers: the browser already died (crashed, or killed from outside). Its process // and its profile are still dealt with below. logger.debug("Could not close the browser gracefully: ${e.message}") + } catch (e: ConnectionClosedException) { + // The same, once the connection has given up on every send attempt. + logger.debug("Could not close the browser gracefully: ${e.message}") } logger.debug("Killing browser process...") // Wait for it to actually be gone, don't just ask. destroy() returns immediately and does not diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 9fc0e487f..e56c2ee68 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -1,9 +1,16 @@ package dev.kdriver.core.browser import dev.kdriver.cdp.domain.browser +import dev.kdriver.core.connection.Connection +import dev.kdriver.core.exceptions.ConnectionClosedException import io.ktor.util.logging.Logger +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every import io.mockk.mockk import io.mockk.verify +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.currentTime @@ -201,6 +208,30 @@ class TemporaryProfileTest { assertFalse(browser in StartedBrowsers) } + @Test + fun stop_goesOnWhenTheGracefulCloseFindsTheConnectionClosed() = runBlocking { + assertStopGoesOnAfterAFailedClose(ConnectionClosedException()) + } + + @Test + fun stop_goesOnWhenTheGracefulCloseCannotReachTheBrowser() = runBlocking { + assertStopGoesOnAfterAFailedClose(IOException("Connection refused")) + } + + private suspend fun assertStopGoesOnAfterAFailedClose(failure: Exception) { + val connection = mockk(relaxed = true) + every { connection.generatedDomains } returns mutableMapOf() + coEvery { connection.callCommand("Browser.close", any(), any()) } throws failure + // A scope of its own: stop() cancels it. + val browser = DefaultBrowser(CoroutineScope(Job()), Config(browserExecutablePath = Path("unused"))) + browser.connection = connection + + browser.stop() + + coVerify { connection.close() } + assertEquals(null, browser.connection, "stop() went on past the failed close") + } + @Test fun start_afterTheProcessDied_deletesTheProfileWhenTheRelaunchFails() = runBlocking { val browser = DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> From 2a5442aebea86c06c8e7615588186000cc8c3f0c Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:25:17 +0100 Subject: [PATCH 09/26] style: address the remaining static analysis findings Full parameter documentation for deleteTemporaryProfile, error() in a test double, and a line wrapped under the length limit. --- .../kotlin/dev/kdriver/core/browser/DefaultBrowser.kt | 3 ++- .../kotlin/dev/kdriver/core/browser/TemporaryProfile.kt | 3 +++ .../kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 67578a21d..b631aacc3 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -418,7 +418,8 @@ open class DefaultBrowser( } /** Launches the browser that replaces this one in [restart]; overridden by tests to make it fail. */ - internal open suspend fun relaunch(config: Config): DefaultBrowser = create(coroutineScope, config, ::DefaultBrowser) + internal open suspend fun relaunch(config: Config): DefaultBrowser = + create(coroutineScope, config, ::DefaultBrowser) private suspend fun adoptTemporaryProfile(profile: Path) = temporaryProfileMutex.withLock { temporaryProfile = profile diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt index af9191b84..799488998 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt @@ -21,6 +21,9 @@ internal expect fun deleteRecursively(path: Path): Boolean * (on Windows by a child process that is still winding down, or by an antivirus scanning it), so a * single attempt is not enough. * + * @param path the profile directory. + * @param attempts how many times to try at most. + * @param retryDelayMillis how long to wait between two attempts. * @param delete one attempt, [deleteRecursively] outside of tests. * @return true if the profile is gone. */ diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index e56c2ee68..e40308a30 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -407,7 +407,7 @@ class TemporaryProfileTest { val unused = Config(browserExecutablePath = Path("unused")) val failing = object : DefaultBrowser(scope, unused) { override suspend fun stop() { - throw IllegalStateException("cannot stop") + error("cannot stop") } } val stopped = mutableListOf() From d3e6a4c9b70ea7dd7e672e95d150f71fdeab3863 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:43:54 +0100 Subject: [PATCH 10/26] fix: retry deleting the temporary profile for about 5 seconds On the Windows CI a browser stopped right after its start left its profile locked for more than the 2 seconds of retries, so stop() kept the profile until the exit hook. Retries cost nothing when the first attempt succeeds. The test that caught it now lists what is left of the profile when it fails. --- .../dev/kdriver/core/browser/TemporaryProfile.kt | 4 +++- .../dev/kdriver/core/browser/TemporaryProfileTest.kt | 12 +++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt index 799488998..276295e01 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt @@ -40,5 +40,7 @@ internal suspend fun deleteTemporaryProfile( return false } -private const val PROFILE_DELETE_ATTEMPTS = 10 +// About 5 seconds in all: a profile Chrome has only just written (a browser stopped right after its +// start) can stay locked on Windows for more than 2 seconds. +private const val PROFILE_DELETE_ATTEMPTS = 26 private const val PROFILE_DELETE_RETRY_DELAY_MILLIS = 200L diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index e40308a30..42fa020c5 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -10,6 +10,7 @@ import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking @@ -42,7 +43,7 @@ import kotlin.time.measureTime * The temporary profile kdriver creates when no `userDataDir` is given must be deleted once the * browser is stopped; a profile the caller supplied must never be. */ -@OptIn(ExperimentalPathApi::class) +@OptIn(ExperimentalPathApi::class, ExperimentalCoroutinesApi::class) class TemporaryProfileTest { @Test @@ -167,7 +168,8 @@ class TemporaryProfileTest { // The caller never got this instance, so create() had to stop it. val browser = assertNotNull(launched) assertTrue(browser.stopped, "the browser process must be stopped") - assertFalse(File(browser.config.userDataDir.toString()).exists(), "and its profile deleted") + val profile = File(browser.config.userDataDir.toString()) + assertFalse(profile.exists(), "and its profile deleted, left: ${profile.walk().take(20).toList()}") assertFalse(browser in StartedBrowsers) } @@ -392,13 +394,13 @@ class TemporaryProfileTest { } @Test - fun deleteTemporaryProfile_triesTenTimesOverAboutTwoSecondsByDefault() = runTest { + fun deleteTemporaryProfile_triesForAboutFiveSecondsByDefault() = runTest { var attempts = 0 assertFalse(deleteTemporaryProfile(Path("kdriver_profile")) { attempts++; false }) - assertEquals(10, attempts) - assertEquals(1_800, currentTime) + assertEquals(26, attempts) + assertEquals(5_000, currentTime) } @Test From 0cf43a99de6ac5c2a57a2f9af286c6efc8a0c14c Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 19:22:45 +0100 Subject: [PATCH 11/26] refactor: avoid duplicated finally branches in browser start, and cover custom dir restart and never-started stop --- .../kdriver/core/browser/DefaultBrowser.kt | 33 ++++++++---------- .../core/browser/TemporaryProfileTest.kt | 34 +++++++++++++++++++ 2 files changed, 49 insertions(+), 18 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index b631aacc3..4eb2c1c26 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -148,14 +148,13 @@ open class DefaultBrowser( val instance = factory(browserScope, config) // start() registers the browser with StartedBrowsers, whose shutdown hook stops it and // deletes its temporary profile if the host process exits without calling stop(). - var started = false try { instance.start() - started = true - } finally { + } catch (e: Throwable) { // On failure the caller never gets this instance, so it could never stop the browser // it launched. - if (!started) withContext(NonCancellable) { instance.stop() } + withContext(NonCancellable) { instance.stop() } + throw e } return instance } @@ -312,11 +311,11 @@ open class DefaultBrowser( if (!config.usesCustomDataDir && config.createdTemporaryProfile) { temporaryProfile = config.userDataDir } - var launched: Process? = null - try { - launched = startProcess(exe, params) - } finally { - if (launched == null) withContext(NonCancellable) { cleanupTemporaryProfile() } + val launched = try { + startProcess(exe, params) + } catch (e: Throwable) { + withContext(NonCancellable) { cleanupTemporaryProfile() } + throw e } process = launched temporaryProfileUser = launched @@ -398,20 +397,18 @@ open class DefaultBrowser( temporaryProfile = null temporaryProfileUser = null StartedBrowsers.unregister(this) - var restarted: DefaultBrowser? = null - try { - restarted = relaunch(config.copy().apply { + val restarted = try { + relaunch(config.copy().apply { // The host and port start() assigned to the dead process: the new browser gets its own. // Kept, they would make it connect to that dead port instead of launching a browser. host = null port = null }) - } finally { - if (restarted == null) { - // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. - temporaryProfile = inherited - withContext(NonCancellable) { cleanupTemporaryProfile() } - } + } catch (e: Throwable) { + // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. + temporaryProfile = inherited + withContext(NonCancellable) { cleanupTemporaryProfile() } + throw e } if (inherited != null) restarted.adoptTemporaryProfile(inherited) return restarted diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 42fa020c5..647d7c9a4 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -12,6 +12,7 @@ import io.mockk.verify import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.currentTime @@ -197,6 +198,39 @@ class TemporaryProfileTest { assertFalse(profile.exists(), "the new browser deletes it when it stops") } + @Test + fun start_afterTheProcessDied_keepsACustomUserDataDirOnRelaunch() = runBlocking { + val custom = createTempDirectory(prefix = "kdriver_custom_test_") + try { + val browser = createBrowser(this, userDataDir = Path(custom.toString()), headless = true, sandbox = false) + killFromOutside(browser) + + val restarted = browser.start() + try { + assertNotSame(browser, restarted) + assertEquals(browser.config.userDataDir, restarted.config.userDataDir) + } finally { + restarted.stop() + browser.stop() + } + assertTrue(custom.exists(), "a userDataDir given by the caller must never be deleted") + } finally { + deleteTemporaryProfile(Path(custom.toString())) + } + } + + @Test + fun stop_onABrowserThatNeverStartedDoesNothing() = runBlocking { + val scope = CoroutineScope(coroutineContext + SupervisorJob()) + val browser = DefaultBrowser(scope, Config(headless = true, sandbox = false)) + + browser.stop() + browser.cleanupTemporaryProfile() + + assertTrue(browser.stopped) + assertFalse(browser in StartedBrowsers) + } + @Test fun stop_afterTheProcessDied_stillDeletesTheProfile() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) From f6a45cd6f536df4f4c5d541a1c4ec4ae5eba4943 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 19:33:38 +0100 Subject: [PATCH 12/26] style: suppress the generic catch that cleans up and rethrows --- .../kotlin/dev/kdriver/core/browser/DefaultBrowser.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 4eb2c1c26..6e0a53959 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -139,6 +139,7 @@ open class DefaultBrowser( create(coroutineScope, config, ::DefaultBrowser) /** [create], with the instance built by [factory]: tests use it to make the start fail. */ + @Suppress("TooGenericExceptionCaught") // cleans up whatever made the start fail, then rethrows it internal suspend fun create( coroutineScope: CoroutineScope, config: Config, @@ -311,6 +312,7 @@ open class DefaultBrowser( if (!config.usesCustomDataDir && config.createdTemporaryProfile) { temporaryProfile = config.userDataDir } + @Suppress("TooGenericExceptionCaught") // cleans up whatever made the launch fail, then rethrows it val launched = try { startProcess(exe, params) } catch (e: Throwable) { @@ -392,6 +394,7 @@ open class DefaultBrowser( * The new browser runs on the same profile, so it takes over deleting it: this one must no longer * delete it, nor be stopped on exit. */ + @Suppress("TooGenericExceptionCaught") // cleans up whatever made the relaunch fail, then rethrows it private suspend fun restart(): Browser { val inherited = temporaryProfile temporaryProfile = null From d3800f4bd13b46de5ee75791f353800574874e7e Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 20:11:30 +0100 Subject: [PATCH 13/26] fix: do not close a browser create() only connected to, and keep the original failure when cleanup fails --- .../kdriver/core/browser/DefaultBrowser.kt | 22 +++++++-- .../core/browser/TemporaryProfileTest.kt | 49 +++++++++++++++++++ 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 6e0a53959..7805c889b 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -138,6 +138,19 @@ open class DefaultBrowser( suspend fun create(coroutineScope: CoroutineScope, config: Config): Browser = create(coroutineScope, config, ::DefaultBrowser) + /** + * Runs [cleanup] after [cause] made an operation fail, without being cancelled. A failure of + * the cleanup itself is attached to [cause] as suppressed, so it never replaces the root cause. + */ + @Suppress("TooGenericExceptionCaught") + private suspend fun cleanUpAfter(cause: Throwable, cleanup: suspend () -> Unit) { + try { + withContext(NonCancellable) { cleanup() } + } catch (e: Throwable) { + cause.addSuppressed(e) + } + } + /** [create], with the instance built by [factory]: tests use it to make the start fail. */ @Suppress("TooGenericExceptionCaught") // cleans up whatever made the start fail, then rethrows it internal suspend fun create( @@ -153,8 +166,9 @@ open class DefaultBrowser( instance.start() } catch (e: Throwable) { // On failure the caller never gets this instance, so it could never stop the browser - // it launched. - withContext(NonCancellable) { instance.stop() } + // it launched. A browser it only connected to (connect-existing) is not ours to close: + // it may be shared, so only the client side is torn down. + cleanUpAfter(e) { if (instance.pid != null) instance.stop() else instance.detach() } throw e } return instance @@ -316,7 +330,7 @@ open class DefaultBrowser( val launched = try { startProcess(exe, params) } catch (e: Throwable) { - withContext(NonCancellable) { cleanupTemporaryProfile() } + cleanUpAfter(e) { cleanupTemporaryProfile() } throw e } process = launched @@ -410,7 +424,7 @@ open class DefaultBrowser( } catch (e: Throwable) { // Nothing runs on the profile anymore: this browser's process is dead and the new one failed. temporaryProfile = inherited - withContext(NonCancellable) { cleanupTemporaryProfile() } + cleanUpAfter(e) { cleanupTemporaryProfile() } throw e } if (inherited != null) restarted.adoptTemporaryProfile(inherited) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 647d7c9a4..e443837cc 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -174,6 +174,55 @@ class TemporaryProfileTest { assertFalse(browser in StartedBrowsers) } + @Test + fun create_keepsTheOriginalFailureWhenTheCleanupFailsToo() = runBlocking { + val failure = assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + override suspend fun start(): Browser { + super.start() + error("target discovery failed") + } + + override suspend fun stop() { + try { + error("stop failed") + } finally { + super.stop() + } + } + } + } + } + assertEquals("target discovery failed", failure.message) + assertEquals(listOf("stop failed"), failure.suppressed.map { it.message }) + } + + @Test + fun create_doesNotStopABrowserItOnlyConnectedTo() = runBlocking { + var stopped = false + var detached = false + val failure = assertFailsWith { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + // Fails without having launched a process, as a connect-existing start would. + override suspend fun start(): Browser = error("no such browser") + + override suspend fun stop() { + stopped = true + } + + override suspend fun detach() { + detached = true + } + } + } + } + assertEquals("no such browser", failure.message) + assertFalse(stopped, "Browser.close must not reach a browser kdriver did not launch") + assertTrue(detached) + } + @Test fun start_afterTheProcessDied_relaunchesOnTheSameProfileAndHandsItsDeletionOver() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) From 2c31c8e8bd84e23e75ae817af58a5e337fa4c168 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Sat, 21 Nov 2026 12:56:17 +0100 Subject: [PATCH 14/26] test: wait for the page before reading its title or content, and print kdriver's warnings in JVM tests get() returns once the navigation has started, while the target's title is still its URL and the document may still be loading. testMultipleBrowsersDiffUserData read the title after an idle wait, which a slow runner could pass before the page parsed its ; it now waits for the target to report the expected title (subscribed to targetInfoChanged before reading the current one, with a timeout, no fixed sleep). testGetContentGetsHtmlContent (JVM, macOS, Linux) now reads the document once its ready state is complete. slf4j-simple at the warn level in jvmTest: a browser that fails to start logs its fate, the last connection error and its stderr, which SLF4J's no-op default dropped, leaving only "Failed to connect to browser". --- core/build.gradle.kts | 3 ++ .../kotlin/dev/kdriver/core/Extensions.kt | 37 +++++++++++++++++++ .../dev/kdriver/core/browser/BrowserTest.kt | 12 ++++-- .../jvmTest/resources/simplelogger.properties | 3 ++ .../kotlin/dev/kdriver/core/tab/TabTest.kt | 2 + .../kotlin/dev/kdriver/core/tab/TabTest.kt | 2 + gradle/libs.versions.toml | 2 + 7 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 core/src/jvmTest/resources/simplelogger.properties diff --git a/core/build.gradle.kts b/core/build.gradle.kts index b6c1792ce..0b42a9aa3 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -121,6 +121,9 @@ kotlin { implementation(kotlin("test")) implementation(libs.tests.mockk) implementation(libs.tests.coroutines) + // Prints what kdriver logs (warnings and errors only, see simplelogger.properties), + // such as why a browser failed to start, instead of dropping it. + runtimeOnly(libs.tests.slf4jSimple) } } val macosTest by getting { diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt index 746ab25d9..2d5caa495 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt @@ -1,8 +1,45 @@ package dev.kdriver.core +import dev.kdriver.cdp.domain.target +import dev.kdriver.core.browser.Browser +import dev.kdriver.core.tab.Tab +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withTimeoutOrNull + fun sampleFile(name: String): String { val resource = checkNotNull(Thread.currentThread().contextClassLoader.getResource(name)) { "Resource '$name' not found" } return resource.toURI().toString() } + +/** + * Waits until the browser reports [title] for this tab's target, then refreshes [Tab.targetInfo]. + * + * `Browser.get` returns once the navigation has started, while the target's title is still its URL: + * Chrome only reports the page's title once the page has parsed it. This waits for that event, with + * no fixed sleep, and fails after [timeoutMillis]: generous, since the first page load of a run, on a + * cold runner, has been seen to take more than ten seconds. + */ +suspend fun Tab.awaitTitle(browser: Browser, title: String, timeoutMillis: Long = 30_000) { + val targetId = checkNotNull(targetInfo?.targetId) { "the tab has no target" } + val events = checkNotNull(browser.connection) { "the browser is not started" }.target.targetInfoChanged + val loaded = withTimeoutOrNull(timeoutMillis) { + coroutineScope { + // Subscribed before the current title is read, so the event cannot slip in between. + val titled = async(start = CoroutineStart.UNDISPATCHED) { + events.first { it.targetInfo.targetId == targetId && it.targetInfo.title == title } + } + updateTarget() + if (targetInfo?.title != title) { + titled.await() + updateTarget() + } + titled.cancel() + } + } + checkNotNull(loaded) { "the target still reports the title '${targetInfo?.title}' after $timeoutMillis ms, not '$title'" } +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt index c92296ed1..22e419bed 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt @@ -1,6 +1,7 @@ package dev.kdriver.core.browser import dev.kdriver.cdp.domain.Network +import dev.kdriver.core.awaitTitle import dev.kdriver.core.sampleFile import dev.kdriver.core.tab.ReadyState import kotlinx.coroutines.runBlocking @@ -143,6 +144,8 @@ class BrowserTest { fun testGetContentGetsHtmlContent() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val tab = browser.get("https://example.com") + // get() returns once the navigation has started: read the document once it has loaded. + tab.waitForReadyState(ReadyState.COMPLETE) val content = tab.getContent() assertTrue(content.lowercase().startsWith("<!doctype html>")) browser.stop() @@ -186,17 +189,20 @@ class BrowserTest { assertEquals(3, userDataDirs.size) val page1 = browser1.get("https://example.com/one") - page1.wait() + // Not a fixed wait: get() returns before the page has loaded, while the title is still its URL. + page1.awaitTitle(browser1, "Example Domain") assertNotNull(page1.targetInfo) assertEquals("Example Domain", page1.targetInfo?.title) val page2 = browser2.get("https://example.com/two") - page2.wait() + // Not a fixed wait: get() returns before the page has loaded, while the title is still its URL. + page2.awaitTitle(browser2, "Example Domain") assertNotNull(page2.targetInfo) assertEquals("Example Domain", page2.targetInfo?.title) val page3 = browser3.get("https://example.com/three") - page3.wait() + // Not a fixed wait: get() returns before the page has loaded, while the title is still its URL. + page3.awaitTitle(browser3, "Example Domain") assertNotNull(page3.targetInfo) assertEquals("Example Domain", page3.targetInfo?.title) diff --git a/core/src/jvmTest/resources/simplelogger.properties b/core/src/jvmTest/resources/simplelogger.properties new file mode 100644 index 000000000..f0acbc7e9 --- /dev/null +++ b/core/src/jvmTest/resources/simplelogger.properties @@ -0,0 +1,3 @@ +org.slf4j.simpleLogger.defaultLogLevel=warn +org.slf4j.simpleLogger.showDateTime=true +org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss.SSS diff --git a/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt index da534b4a9..042b91c42 100644 --- a/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt +++ b/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt @@ -11,6 +11,8 @@ class TabTest { fun testGetContentGetsHtmlContent() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val tab = browser.get("https://example.com") + // get() returns once the navigation has started: read the document once it has loaded. + tab.waitForReadyState(ReadyState.COMPLETE) val content = tab.getContent() assertTrue(content.lowercase().startsWith("<!doctype html>")) browser.stop() diff --git a/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt index da534b4a9..042b91c42 100644 --- a/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt +++ b/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt @@ -11,6 +11,8 @@ class TabTest { fun testGetContentGetsHtmlContent() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) val tab = browser.get("https://example.com") + // get() returns once the navigation has started: read the document once it has loaded. + tab.waitForReadyState(ReadyState.COMPLETE) val content = tab.getContent() assertTrue(content.lowercase().startsWith("<!doctype html>")) browser.stop() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4a12042ba..85d40bfd3 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -7,6 +7,7 @@ ksp = "2.3.12" maven = "0.37.0" ktor = "3.4.0" mockk = "1.13.12" +slf4j = "2.0.17" jsoup = "1.16.2" kotlinx-coroutines = "1.10.2" kotlinx-serialization = "1.8.1" @@ -34,6 +35,7 @@ ktor-clientDarwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor ktor-clientCurl = { module = "io.ktor:ktor-client-curl", version.ref = "ktor" } ktor-clientWinhttp = { module = "io.ktor:ktor-client-winhttp", version.ref = "ktor" } tests-mockk = { module = "io.mockk:mockk", version.ref = "mockk" } +tests-slf4jSimple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } tests-jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" } tests-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" } From c76056a10adb773f1002443de6d3cf52e2e19c13 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 12:56:17 +0100 Subject: [PATCH 15/26] fix: delete the profile when a step of stop() fails, and let a config copy keep its temporary profile a temporary one stop() ran its steps one after the other: a graceful close that threw (with anything but the I/O errors it already tolerated), a failed kill or a failed connection close skipped the rest, leaving the process running and the profile on disk. Every step now runs even if an earlier one failed or was cancelled; the kill, client closes and profile deletion run non-cancellable, the scope is cancelled last, and the first failure is rethrown with the others suppressed. Config.copy() did not carry whether the profile is a temporary one kdriver created, so a profile created before the browser copied its config (for instance by reading userDataDir first) was never deleted. It is now derived from the profile itself (set, and not given by the caller), so every copy agrees, and the browser running on it deletes it. The restart path no longer needs to hand the profile over explicitly. detach() keeps the temporary profile, since the browser still runs on it: said in its KDoc, with how to delete it once that browser has exited, and tested. --- .../dev/kdriver/core/browser/Browser.kt | 15 ++- .../kotlin/dev/kdriver/core/browser/Config.kt | 24 +++-- .../kdriver/core/browser/DefaultBrowser.kt | 99 +++++++++++------ .../core/browser/TemporaryProfileTest.kt | 100 +++++++++++++++--- 4 files changed, 181 insertions(+), 57 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt index f901dd8f3..f07b1275e 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Browser.kt @@ -103,6 +103,10 @@ interface Browser { /** * Launches the actual browser + * + * If the browser process this instance launched has died, a new browser is started on the same + * configuration and profile and returned: use that instance from then on. It owns the process and + * the temporary profile, so [stop] it rather than this one. */ suspend fun start(): Browser @@ -134,7 +138,13 @@ interface Browser { * through [Config.browserUrl]; use [stop] to shut the browser down. * * A browser process launched by this instance is left running too; [stop] will no longer reach - * it. This instance cannot be used anymore afterwards. + * it, and the shutdown hook will not stop it either. This instance cannot be used anymore + * afterwards. + * + * Its temporary profile (when no [Config.userDataDir] was given) is kept on disk, since the + * browser still runs on it. It is deleted only if [cleanupTemporaryProfile] is called once that + * browser has exited; otherwise whoever shuts the browser down owns the directory, found in + * [Config.userDataDir]. */ suspend fun detach() @@ -146,7 +156,8 @@ interface Browser { * the profile in place. Calling it again, or after the profile is gone, does nothing. * * [stop] already calls it, and so does the shutdown hook that stops the browsers still running - * when the host process exits (on the JVM). There is usually no need to call it yourself. + * when the host process exits (on the JVM). There is usually no need to call it yourself, except + * after [detach], which keeps the profile. */ suspend fun cleanupTemporaryProfile() diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index d6f2833c5..52423c79c 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -56,13 +56,16 @@ class Config( private var _customDataDir: Boolean = false /** - * True only when *this* instance created the temporary profile in [userDataDir]. + * True when [userDataDir] is a temporary profile kdriver created (no directory was given), and it + * has been created already. * - * Deliberately not carried over by [copy]: a copy that inherits an already created temporary - * profile shares it with the original, so it must not delete it. + * Carried over by [copy], like [userDataDir] itself: the browser that runs on such a profile + * deletes it when it stops, whichever copy of the configuration created it. Otherwise a profile + * created before the browser copied its configuration (for instance by reading [userDataDir] + * first) would never be deleted. */ - internal var createdTemporaryProfile: Boolean = false - private set + internal val createdTemporaryProfile: Boolean + get() = _userDataDir != null && !_customDataDir private val _browserArgs: MutableList<String> = browserArgs?.toMutableList() ?: mutableListOf() internal val _extensions: MutableList<Path> = mutableListOf() @@ -85,19 +88,23 @@ class Config( } } + /** + * The browser profile directory. + * + * When none is given, the first read creates a temporary `kdriver_*` directory, which the browser + * running on it deletes when it stops. A directory given here is never deleted. + */ var userDataDir: Path get() { if (_userDataDir == null) { _userDataDir = tempProfileDir() _customDataDir = false - createdTemporaryProfile = true } return _userDataDir!! } set(value) { _userDataDir = value _customDataDir = true - createdTemporaryProfile = false } val usesCustomDataDir: Boolean @@ -157,6 +164,9 @@ class Config( * * The copy is deep where it matters: the argument and extension lists are duplicated, so * mutating one config never affects the other. + * + * A temporary profile this config already created is shared with the copy, not duplicated: the + * browser that runs on it deletes it when it stops (see [Browser.cleanupTemporaryProfile]). */ fun copy(): Config = Config( // Pass the already-resolved executable so the copy does not re-run the disk search. diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 7805c889b..541f8f05a 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -151,6 +151,24 @@ open class DefaultBrowser( } } + /** + * Runs every one of [steps], even after one of them fails. The first failure is rethrown once + * they have all run, with the later ones attached to it as suppressed. + */ + @Suppress("TooGenericExceptionCaught") // collects every failure, then rethrows the first one + private suspend fun runEach(vararg steps: suspend () -> Unit) { + var failure: Throwable? = null + for (step in steps) { + try { + step() + } catch (e: Throwable) { + val first = failure + if (first == null) failure = e else first.addSuppressed(e) + } + } + failure?.let { throw it } + } + /** [create], with the instance built by [factory]: tests use it to make the start fail. */ @Suppress("TooGenericExceptionCaught") // cleans up whatever made the start fail, then rethrows it internal suspend fun create( @@ -323,9 +341,7 @@ open class DefaultBrowser( logger.info("starting\n\texecutable :$exe\n\narguments:\n${params.joinToString("\n\t")}") // config() above created the temporary profile, if any: from here on it is ours to delete. - if (!config.usesCustomDataDir && config.createdTemporaryProfile) { - temporaryProfile = config.userDataDir - } + if (config.createdTemporaryProfile) temporaryProfile = config.userDataDir @Suppress("TooGenericExceptionCaught") // cleans up whatever made the launch fail, then rethrows it val launched = try { startProcess(exe, params) @@ -405,7 +421,8 @@ open class DefaultBrowser( /** * Starts a new browser on the same configuration, because this one's process has died. * - * The new browser runs on the same profile, so it takes over deleting it: this one must no longer + * The new browser runs on the same profile, so it takes over deleting it (its configuration, a + * copy of this one, says the profile is a temporary one kdriver created): this one must no longer * delete it, nor be stopped on exit. */ @Suppress("TooGenericExceptionCaught") // cleans up whatever made the relaunch fail, then rethrows it @@ -427,7 +444,6 @@ open class DefaultBrowser( cleanUpAfter(e) { cleanupTemporaryProfile() } throw e } - if (inherited != null) restarted.adoptTemporaryProfile(inherited) return restarted } @@ -435,10 +451,6 @@ open class DefaultBrowser( internal open suspend fun relaunch(config: Config): DefaultBrowser = create(coroutineScope, config, ::DefaultBrowser) - private suspend fun adoptTemporaryProfile(profile: Path) = temporaryProfileMutex.withLock { - temporaryProfile = profile - } - private suspend fun handleTargetUpdate(event: Any) = updateTargetInfoMutex.withLock { when (event) { // Both create and info-changed go through the same dedupe-by-targetId upsert, so an @@ -482,43 +494,62 @@ open class DefaultBrowser( override suspend fun stop() { logger.info("Stopping browser process with PID: ${process?.pid()}") + // Each step runs even if an earlier one failed or was cancelled: a graceful close that throws + // must not leave the process running nor its profile on disk. The first failure is rethrown. + runEach( + { closeGracefully() }, + { + // Not cancellable, so a stop() called from the `finally` of a cancelled coroutine still + // kills the process and deletes the profile. + withContext(NonCancellable) { + runEach( + { killProcess() }, + { connection?.also { connection = null }?.close() }, + { http?.also { http = null }?.close() }, + { deleteProfileOnStop() }, + ) + } + }, + { + // Last, since it may be the caller's own scope. + logger.debug("Canceling coroutine scope...") + coroutineScope.cancel() + }, + ) + logger.info("Browser process stopped") + } + + private suspend fun closeGracefully() { logger.debug("Closing browser gracefully...") try { withTimeoutOrNull(5.seconds) { connection?.browser?.close() } } catch (e: IOException) { // Nothing answers: the browser already died (crashed, or killed from outside). Its process - // and its profile are still dealt with below. + // and its profile are still dealt with afterwards. logger.debug("Could not close the browser gracefully: ${e.message}") } catch (e: ConnectionClosedException) { // The same, once the connection has given up on every send attempt. logger.debug("Could not close the browser gracefully: ${e.message}") } + } + + private suspend fun killProcess() { logger.debug("Killing browser process...") // Wait for it to actually be gone, don't just ask. destroy() returns immediately and does not - // reach the browser's child processes, which keep open handles on the profile directory — - // a browser started on the same --user-data-dir right after would hang before opening its - // debug port, and the start would time out for no visible reason. - process?.let { - if (!it.destroyAndAwaitExit()) logger.warn("Browser process ${it.pid()} still alive after kill") - } - process = null - logger.debug("Closing connection...") - connection?.close() - connection = null - logger.debug("Closing HTTP API client...") - http?.close() - http = null - // Before cancelling the scope, which may be the caller's own; and non-cancellable, so a stop() - // called from a `finally` of a cancelled coroutine still deletes the profile. - withContext(NonCancellable) { - // No further wait: the process has just been waited for, and killed if it lingered. - cleanupTemporaryProfile(releaseTimeoutMillis = 0) - // Still registered if the profile could not be deleted, so the exit hook tries again. - if (temporaryProfile == null) StartedBrowsers.unregister(this@DefaultBrowser) - } - logger.debug("Canceling coroutine scope...") - coroutineScope.cancel() - logger.info("Browser process stopped") + // reach the browser's child processes, which keep open handles on the profile directory — a + // browser started on the same --user-data-dir right after would hang before opening its debug + // port, and the start would time out for no visible reason. + val process = process ?: return + if (!process.destroyAndAwaitExit()) logger.warn("Browser process ${process.pid()} still alive after kill") + this.process = null + } + + private suspend fun deleteProfileOnStop() { + // No further wait: the process has just been waited for, and killed if it lingered. If the + // kill failed, the profile is kept, since the process may still be writing to it. + cleanupTemporaryProfile(releaseTimeoutMillis = 0) + // Still registered if the profile could not be deleted, so the exit hook tries again. + if (temporaryProfile == null) StartedBrowsers.unregister(this) } override suspend fun detach() { diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index e443837cc..630f18f28 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -114,22 +114,18 @@ class TemporaryProfileTest { } @Test - fun stop_keepsATemporaryProfileInheritedThroughCopy() = runBlocking { + fun stop_deletesATemporaryProfileCreatedBeforeTheBrowserCopiedItsConfig() = runBlocking { val config = Config(headless = true, sandbox = false) - // Reading it creates the temporary profile on this config: the browser's own copy inherits it. + // Reading it creates the temporary profile on this config, before the browser copies it. val profile = File(config.userDataDir.toString()) - try { - val browser = createBrowser(this, config) - assertEquals(config.userDataDir, browser.config.userDataDir, "the browser runs on the inherited profile") - assertFalse(browser.config.createdTemporaryProfile) + val browser = createBrowser(this, config) + assertEquals(config.userDataDir, browser.config.userDataDir, "the browser runs on that profile") + assertTrue(browser.config.createdTemporaryProfile) - browser.stop() + browser.stop() - assertTrue(profile.isDirectory, "a profile the browser did not create must not be deleted") - assertFalse(browser in StartedBrowsers) - } finally { - deleteTemporaryProfile(Path(profile.path)) - } + assertFalse(profile.exists(), "a temporary profile kdriver created must not leak, whichever copy created it") + assertFalse(browser in StartedBrowsers) } @Test @@ -379,19 +375,95 @@ class TemporaryProfileTest { } @Test - fun copyOfAConfigDoesNotOwnItsTemporaryProfile() { + fun copyOfAConfigKeepsItsTemporaryProfileATemporaryOne() { val original = Config(browserExecutablePath = Path("/usr/bin/chromium")) + assertFalse(original.createdTemporaryProfile, "nothing is created before the profile is read") + assertFalse(original.copy().createdTemporaryProfile) val profile = original.userDataDir try { assertTrue(original.createdTemporaryProfile) val copy = original.copy() assertEquals(profile, copy.userDataDir, "the copy shares the profile…") - assertFalse(copy.createdTemporaryProfile, "…so it must not delete it") + assertTrue(copy.createdTemporaryProfile, "…and the browser that runs on it deletes it") + assertFalse(copy.usesCustomDataDir) } finally { deleteRecursively(profile) } } + @Test + fun copyOfAConfigWithACustomUserDataDirNeverOwnsIt() { + val custom = Config(browserExecutablePath = Path("/usr/bin/chromium"), userDataDir = Path("/tmp/mine")) + + assertFalse(custom.createdTemporaryProfile) + assertFalse(custom.copy().createdTemporaryProfile) + assertTrue(custom.copy().usesCustomDataDir) + } + + @Test + fun stop_deletesTheProfileEvenWhenTheGracefulCloseFails() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val real = assertNotNull(browser.connection) + val failing = mockk<Connection>(relaxed = true) + every { failing.generatedDomains } returns mutableMapOf() + coEvery { failing.callCommand("Browser.close", any(), any()) } throws IllegalStateException("close failed") + browser.connection = failing + try { + val failure = assertFailsWith<IllegalStateException> { browser.stop() } + + assertEquals("close failed", failure.message, "the failure is still reported") + assertTrue(browser.stopped, "the process is killed all the same") + assertFalse(profile.exists(), "and its profile deleted") + assertFalse(browser in StartedBrowsers) + coVerify { failing.close() } + } finally { + real.close() + } + } + + @Test + fun stop_deletesTheProfileEvenWhenClosingTheConnectionFails() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) as DefaultBrowser + val profile = File(browser.config.userDataDir.toString()) + val real = assertNotNull(browser.connection) + val failing = mockk<Connection>(relaxed = true) + every { failing.generatedDomains } returns mutableMapOf() + coEvery { failing.close() } throws IllegalStateException("connection close failed") + browser.connection = failing + try { + val failure = assertFailsWith<IllegalStateException> { browser.stop() } + + assertEquals("connection close failed", failure.message) + assertTrue(browser.stopped) + assertFalse(profile.exists(), "the profile is deleted after a failed step") + assertEquals(null, browser.connection) + } finally { + real.close() + } + } + + @Test + fun detach_keepsTheProfileTheBrowserStillRunsOn() = runBlocking { + val browser = createBrowser(this, headless = true, sandbox = false) + val profile = File(browser.config.userDataDir.toString()) + val pid = assertNotNull(browser.pid) + val process = assertNotNull(ProcessHandle.of(pid).orElse(null)) + try { + browser.detach() + + assertTrue(process.isAlive, "detach leaves the browser running…") + assertTrue(profile.isDirectory, "…so its profile is kept") + assertFalse(browser in StartedBrowsers, "and the exit hook leaves both alone") + } finally { + // What the owner of a detached browser does: shut it down, then delete its profile. + (process.descendants().toList() + process).forEach { it.destroyForcibly() } + process.onExit().get() + browser.cleanupTemporaryProfile() + } + assertFalse(profile.exists(), "cleanupTemporaryProfile deletes it once the browser has exited") + } + @Test fun deleteRecursively_removesNestedContent() { val root = createTempDirectory(prefix = "kdriver_delete_test_") From 3cb11c19007105e221841e879de84af145fe47f6 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 12:56:17 +0100 Subject: [PATCH 16/26] fix: delete profile entries beyond MAX_PATH on Windows A profile nests deep enough (extensions, caches) to pass 260 characters, which the plain-path wide functions refuse, so those entries were left. The walk now uses the \\?\ extended-length form (UNC paths as \\?\UNC\...), which needs no system setting; relative and device paths are left as is. --- .../core/browser/TemporaryProfile.mingw.kt | 44 +++++++++- .../browser/WindowsDeleteRecursivelyTest.kt | 88 +++++++++++++++++++ 2 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt index 431944be3..375e0cfcc 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt @@ -4,11 +4,51 @@ import kotlinx.cinterop.* import kotlinx.io.files.Path import platform.windows.* +/** + * Every path goes through [extendedLengthPath]: a profile nests deep enough (extension and cache + * directories) to pass the 260 characters a plain path is limited to, and such entries would be left. + */ @OptIn(ExperimentalForeignApi::class) internal actual fun deleteRecursively(path: Path): Boolean { - val target = path.toString() + val target = extendedLengthPath(path.toString()) deleteEntry(target) - return GetFileAttributesW(target) == INVALID_FILE_ATTRIBUTES + return isGone(target) +} + +/** Only when the system says the entry does not exist: an invalid path or a denied access is not gone. */ +@OptIn(ExperimentalForeignApi::class) +private fun isGone(path: String): Boolean { + if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return false + val error = GetLastError() + return error == ERROR_FILE_NOT_FOUND.toUInt() || error == ERROR_PATH_NOT_FOUND.toUInt() +} + +/** + * [path] in the `\\?\` form, which the wide Windows file functions accept beyond `MAX_PATH` (260 + * characters) without any system setting. That form is taken literally, with no normalisation, so + * separators are made single backslashes first. A relative path cannot take it and is returned as is + * (a temporary profile is always absolute). + */ +internal fun extendedLengthPath(path: String): String { + val slashes = path.replace('/', '\\') + // A leading pair is the start of a UNC, extended or device path: kept, the rest collapsed. + val lead = if (slashes.startsWith("\\\\")) "\\\\" else "" + val windowsPath = lead + collapseSeparators(slashes.substring(lead.length)) + return when { + windowsPath.startsWith(EXTENDED_PREFIX) || windowsPath.startsWith(DEVICE_PREFIX) -> windowsPath + // \\server\share\... becomes \\?\UNC\server\share\... + windowsPath.startsWith("\\\\") -> EXTENDED_PREFIX + "UNC\\" + windowsPath.removePrefix("\\\\") + windowsPath.length >= 3 && windowsPath[0].isLetter() && windowsPath[1] == ':' && windowsPath[2] == '\\' -> + EXTENDED_PREFIX + windowsPath + else -> windowsPath + } +} + +private const val EXTENDED_PREFIX = "\\\\?\\" +private const val DEVICE_PREFIX = "\\\\.\\" + +private fun collapseSeparators(path: String): String = buildString(path.length) { + path.forEach { c -> if (c != '\\' || lastOrNull() != '\\') append(c) } } /** diff --git a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt new file mode 100644 index 000000000..769f91825 --- /dev/null +++ b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt @@ -0,0 +1,88 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.toKString +import kotlinx.io.files.Path +import platform.posix.getenv +import platform.windows.* +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** The Windows recursive delete of a temporary profile. */ +@OptIn(ExperimentalForeignApi::class) +class WindowsDeleteRecursivelyTest { + + @Test + fun removesEntriesBeyondTheMaxPathLimit() { + val root = "${tempBase()}\\kdriver_long_path_test_${Random.nextLong().toString(16)}" + // Nested well past 260 characters, as a profile's extension or cache directories can be. + var deepest = root + createDirectory(root) + repeat(8) { level -> + deepest = "$deepest\\${"d$level".padEnd(40, 'x')}" + createDirectory(deepest) + } + assertTrue(deepest.length > 300, "the test path must pass MAX_PATH, is ${deepest.length}") + val file = "$deepest\\Cookies" + val handle: HANDLE? = CreateFileW( + extendedLengthPath(file), + GENERIC_WRITE.toUInt(), + 0u, + null, + CREATE_NEW.toUInt(), + FILE_ATTRIBUTE_NORMAL.toUInt(), + null, + ) + assertTrue(handle != null && handle != INVALID_HANDLE_VALUE, "create $file, error ${GetLastError()}") + CloseHandle(handle) + + assertTrue(deleteRecursively(Path(root)), "every entry is deleted, however deep") + assertEquals(INVALID_FILE_ATTRIBUTES, GetFileAttributesW(extendedLengthPath(root))) + } + + @Test + fun extendedLengthPathPrefixesAbsolutePathsOnly() { + assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:\\Temp\\kdriver_1")) + assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:/Temp/kdriver_1")) + assertEquals("\\\\?\\UNC\\server\\share\\kdriver_1", extendedLengthPath("\\\\server\\share\\kdriver_1")) + assertEquals("\\\\?\\C:\\already", extendedLengthPath("\\\\?\\C:\\already")) + assertEquals("\\\\.\\device", extendedLengthPath("\\\\.\\device")) + assertEquals("relative\\kdriver_1", extendedLengthPath("relative/kdriver_1")) + // The extended form is taken literally: a doubled separator (TEMP ending with one) would break it. + assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:\\Temp\\\\kdriver_1")) + assertEquals("\\\\?\\UNC\\server\\share\\kdriver_1", extendedLengthPath("\\\\server\\share\\\\kdriver_1")) + } + + @Test + fun removesAProfileWhosePathHasADoubledSeparator() { + val name = "kdriver_double_separator_test_${Random.nextLong().toString(16)}" + createDirectory("${tempBase()}\\$name") + createDirectory("${tempBase()}\\$name\\Default") + + assertTrue(deleteRecursively(Path("${tempBase()}\\\\$name"))) + assertEquals(INVALID_FILE_ATTRIBUTES, GetFileAttributesW(extendedLengthPath("${tempBase()}\\$name"))) + } + + @Test + fun aProfileThatCannotBeReachedIsNotReportedGone() { + // An invalid name, not a missing one: deleting it fails, and must not count as done. + assertFalse(deleteRecursively(Path("C:\\kdriver_invalid_<name>"))) + } + + @Test + fun tempProfileDirHasNoDoubledSeparator() { + assertFalse("\\\\" in tempProfileDir().toString().removePrefix("\\\\")) + } + + private fun tempBase(): String = + (getenv("TEMP") ?: getenv("TMP"))?.toKString()?.trimEnd('\\', '/') ?: "C:\\Temp" + + private fun createDirectory(path: String) { + assertNotEquals(0, CreateDirectoryW(extendedLengthPath(path), null), "create $path, error ${GetLastError()}") + } + +} From 992d18c844c3dcd2a7b22e98864439c04dbdb14c Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 12:56:17 +0100 Subject: [PATCH 17/26] fix: never follow a link swapped in while deleting a profile on POSIX The walk checked an entry with lstat, then chmod-ed, listed and removed it by path: an entry replaced by a symbolic link in between had its target's mode changed, and could be listed and emptied. Each directory is now opened without following links and its children are reached from that descriptor only: the *at functions on macOS (with O_NOFOLLOW_ANY, since openat is not exposed there), /proc/self/fd on Linux, where Kotlin/Native exposes none of them (falling back to the path without /proc). A directory is made accessible through its descriptor, or through fchmodat / an O_PATH descriptor when it cannot be read, so a link is never chmod-ed through. The temporary profile is now created owner-only (0700, like Chrome's own), not 0777 minus the umask, so no other user can add entries to it. posixTest covers the native walk on macOS and Linux: nested content, unreadable directories, links (never followed, target mode unchanged), a root that is itself a link, a missing root. --- core/build.gradle.kts | 5 + .../core/browser/TemporaryProfile.linux.kt | 52 ++++++++ .../core/browser/TemporaryProfile.macos.kt | 32 +++++ .../kotlin/dev/kdriver/core/tab/TabTest.kt | 21 --- .../dev/kdriver/core/browser/Process.posix.kt | 8 +- .../core/browser/TemporaryProfile.posix.kt | 126 ++++++++++++++---- .../browser/PosixDeleteRecursivelyTest.kt | 118 ++++++++++++++++ .../kotlin/dev/kdriver/core/tab/TabTest.kt | 0 8 files changed, 314 insertions(+), 48 deletions(-) create mode 100644 core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt create mode 100644 core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt delete mode 100644 core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt create mode 100644 core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt rename core/src/{linuxTest => posixTest}/kotlin/dev/kdriver/core/tab/TabTest.kt (100%) diff --git a/core/build.gradle.kts b/core/build.gradle.kts index 0b42a9aa3..70449efa3 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -126,13 +126,18 @@ kotlin { runtimeOnly(libs.tests.slf4jSimple) } } + val posixTest by creating { + dependsOn(commonTest.get()) + } val macosTest by getting { + dependsOn(posixTest) dependencies { implementation(kotlin("test")) implementation(libs.tests.coroutines) } } val linuxTest by getting { + dependsOn(posixTest) dependencies { implementation(kotlin("test")) implementation(libs.tests.coroutines) diff --git a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt new file mode 100644 index 000000000..b89c7cb37 --- /dev/null +++ b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt @@ -0,0 +1,52 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.UnsafeNumber +import kotlinx.cinterop.convert +import platform.posix.* + +/** + * Kotlin/Native exposes none of the `*at` functions on Linux, so they go through `/proc/self/fd`: + * `/proc/self/fd/<parent>/<name>` resolves `<parent>` to exactly the directory that descriptor is + * open on, then looks `<name>` up in it, which is what `openat`, `unlinkat` and `fchmodat` do (glibc + * implements `fchmodat` this way too). + * + * Without `/proc` (some minimal containers), the entry's full path is used instead. A path is only + * as safe as its parents then; the profile directory is created with owner-only permissions, so + * only its owner could change them during the walk. + */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +internal actual object DirectoryAccess { + + actual fun openDirectory(entry: Entry): Int = + open(entry.resolved(), O_RDONLY or O_DIRECTORY or O_NOFOLLOW or O_CLOEXEC) + + actual fun grantOwnerAccess(entry: Entry): Boolean { + // A descriptor that only designates the directory (O_PATH needs no permission on it); with + // O_NOFOLLOW and O_DIRECTORY, a link that replaced it is refused. Its /proc link then names + // exactly that directory, whatever happens to the path. + val fd = open(entry.resolved(), O_PATH or O_DIRECTORY or O_NOFOLLOW or O_CLOEXEC) + if (fd < 0) return false + return try { + chmod("$PROC_FDS/$fd", S_IRWXU.convert()) == 0 + } finally { + close(fd) + } + } + + actual fun remove(entry: Entry, directory: Boolean) { + // unlink and rmdir never follow a link in place of the last component. + if (directory) rmdir(entry.resolved()) else unlink(entry.resolved()) + } + + private fun Entry.resolved(): String = + if (parentFd == NO_PARENT || !procAvailable) path else "$PROC_FDS/$parentFd/$name" + + private val procAvailable: Boolean by lazy { access("$PROC_FDS/", F_OK) == 0 } + + private const val PROC_FDS = "/proc/self/fd" + + /** From the kernel's `fcntl.h`, the same on x86-64 and arm64; glibc's headers hide it here. */ + private const val O_PATH = 0x200000 + +} diff --git a/core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt b/core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt new file mode 100644 index 000000000..871f945a5 --- /dev/null +++ b/core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt @@ -0,0 +1,32 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.UnsafeNumber +import kotlinx.cinterop.convert +import platform.posix.* + +/** + * The `*at` functions, except `openat`, which Kotlin/Native does not expose on macOS: a directory is + * opened through its whole path instead, with `O_NOFOLLOW_ANY`, which refuses a symbolic link in any + * component of the path and so keeps the walk inside the profile just as well. The walk starts from a + * path whose parent is canonical, free of links (`$TMPDIR` itself is under `/var`, a link). + * + * `O_NOFOLLOW_ANY` alone: it already covers the last component, and macOS refuses it combined with + * `O_NOFOLLOW` (`EINVAL`). + */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +internal actual object DirectoryAccess { + + actual fun openDirectory(entry: Entry): Int = + open(entry.path, O_RDONLY or O_DIRECTORY or O_NOFOLLOW_ANY or O_CLOEXEC) + + actual fun grantOwnerAccess(entry: Entry): Boolean = + fchmodat(entry.dirFd(), entry.name, S_IRWXU.convert(), AT_SYMLINK_NOFOLLOW) == 0 + + actual fun remove(entry: Entry, directory: Boolean) { + unlinkat(entry.dirFd(), entry.name, if (directory) AT_REMOVEDIR else 0) + } + + private fun Entry.dirFd(): Int = if (parentFd == NO_PARENT) AT_FDCWD else parentFd + +} diff --git a/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt deleted file mode 100644 index 042b91c42..000000000 --- a/core/src/macosTest/kotlin/dev/kdriver/core/tab/TabTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package dev.kdriver.core.tab - -import dev.kdriver.core.browser.createBrowser -import kotlinx.coroutines.runBlocking -import kotlin.test.Test -import kotlin.test.assertTrue - -class TabTest { - - @Test - fun testGetContentGetsHtmlContent() = runBlocking { - val browser = createBrowser(this, headless = true, sandbox = false) - val tab = browser.get("https://example.com") - // get() returns once the navigation has started: read the document once it has loaded. - tab.waitForReadyState(ReadyState.COMPLETE) - val content = tab.getContent() - assertTrue(content.lowercase().startsWith("<!doctype html>")) - browser.stop() - } - -} diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt index 06f31729a..75ece61bb 100644 --- a/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/Process.posix.kt @@ -100,11 +100,15 @@ actual fun exists(path: Path): Boolean { @OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) actual fun tempProfileDir(): Path { - val tempDir = getenv("TMPDIR")?.toKString() ?: "/tmp" + // Without a trailing separator ($TMPDIR has one on macOS), which would double the one added below + // ("/" becomes "", so the profile is created right under it). + val tempDir = (getenv("TMPDIR")?.toKString() ?: "/tmp").trimEnd('/') val uniqueName = "kdriver_${Random.nextLong().toString(16)}" val profilePath = "$tempDir/$uniqueName" - mkdir(profilePath, 0x1FFu) // 0777 permissions + // Owner only, like the profiles Chrome creates: nobody else may list it, nor add entries (such as + // a symbolic link) that its deletion would then have to deal with. + mkdir(profilePath, S_IRWXU.convert()) return Path(profilePath) } diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt index 3ffd9f315..7370fef82 100644 --- a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt @@ -4,51 +4,127 @@ import kotlinx.cinterop.* import kotlinx.io.files.Path import platform.posix.* +/** + * Every entry is reached from its parent's open descriptor, never through a path that could be + * changed during the walk (see [DirectoryAccess]): an entry replaced by a symbolic link between two + * steps is unlinked, never followed, so nothing outside the profile is ever deleted, listed, or has + * its mode changed. + */ @OptIn(ExperimentalForeignApi::class) internal actual fun deleteRecursively(path: Path): Boolean { - val target = path.toString() - deleteEntry(target) + val target = path.toString().trimEnd('/').ifEmpty { "/" } + val root = withCanonicalParent(target) + deleteEntry(Entry(NO_PARENT, root, root)) return !entryExists(target) } /** - * Deletes [path], and its content first if it is a directory. A symbolic link is unlinked, never - * followed: `lstat` describes the link itself. + * [path] with its parent directory in canonical form, free of symbolic links (on macOS `$TMPDIR` is + * under `/var`, itself a link), so that a link met during the walk can only be one that appeared + * inside the profile. The last component is kept as is: a profile that is itself a link is unlinked, + * not followed. */ -@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) -private fun deleteEntry(path: String) { - if (isRealDirectory(path)) { - // A directory without read or search permission cannot be listed nor emptied. It is ours (it - // is inside the profile we created), and lstat said it is not a link, so chmod is safe here. - chmod(path, S_IRWXU.convert()) - children(path).forEach { deleteEntry("$path/$it") } - rmdir(path) - } else { - unlink(path) +@OptIn(ExperimentalForeignApi::class) +private fun withCanonicalParent(path: String): String { + val slash = path.lastIndexOf('/') + if (slash < 0) return path + val parent = if (slash == 0) "/" else path.substring(0, slash) + // A buffer of our own: the realpath Kotlin/Native binds on macOS is the legacy one, which refuses + // a null buffer. + val canonical = memScoped { + val buffer = allocArray<ByteVar>(PATH_MAX + 1) + realpath(parent, buffer)?.toKString() + } ?: return path + return "${canonical.trimEnd('/')}/${path.substring(slash + 1)}" +} + +/** + * An entry of the walk: [name] in the directory open as [parentFd], or the root [path] itself when + * [parentFd] is [NO_PARENT]. [path] is the same entry from the root, for messages and for the + * platforms without `*at` functions. + */ +internal class Entry(val parentFd: Int, val name: String, val path: String) + +/** [Entry.parentFd] of the root of the walk, which is reached through its path. */ +internal const val NO_PARENT = -1 + +/** + * The `*at` operations the walk needs, which each POSIX target provides its own way: none of them + * follows a symbolic link in place of [Entry.name], nor resolves [Entry.name] anywhere but in the + * directory open as [Entry.parentFd]. + */ +internal expect object DirectoryAccess { + /** Opens [entry] if it is a real directory, or returns -1 with `errno` set. */ + fun openDirectory(entry: Entry): Int + + /** Gives the owner read, write and search permission on the directory [entry]. */ + fun grantOwnerAccess(entry: Entry): Boolean + + /** Removes [entry]: an empty directory if [directory], else a file or a link. */ + fun remove(entry: Entry, directory: Boolean) +} + +/** + * Deletes [entry], and its content first if it is a directory. Best effort: an entry that cannot be + * deleted is left, and the walk goes on. + */ +@OptIn(ExperimentalForeignApi::class) +private fun deleteEntry(entry: Entry) { + val dirFd = openDirectory(entry) + if (dirFd < 0) { + // Not a directory, a symbolic link (refused), or already gone: unlink it as it is. + DirectoryAccess.remove(entry, directory = false) + return } + deleteChildren(dirFd, entry.path) + DirectoryAccess.remove(entry, directory = true) } -/** Lists the names in [path], read in full before anything is deleted from it. */ +/** + * Opens [entry] if it is a real directory (not a link to one), or returns -1. + * + * A directory without read permission cannot be opened: it is ours (inside the profile we created), + * so we give ourselves access first, without following a link that may have replaced it since. + */ @OptIn(ExperimentalForeignApi::class) -private fun children(path: String): List<String> { - val dir = opendir(path) ?: return emptyList() - val names = mutableListOf<String>() +private fun openDirectory(entry: Entry): Int { + val fd = DirectoryAccess.openDirectory(entry) + if (fd >= 0 || errno != EACCES) return fd + if (!DirectoryAccess.grantOwnerAccess(entry)) return -1 + return DirectoryAccess.openDirectory(entry) +} + +/** + * Deletes everything in the directory open as [dirFd], then closes it. The names are read in full + * before anything is deleted. + */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +private fun deleteChildren(dirFd: Int, path: String) { + // Emptying a directory needs write and search permission on it, on top of read to list it. The + // mode is changed through the descriptor, so on the very directory that was opened. + memScoped { + val info = alloc<stat>() + val ownerAccess = S_IRWXU.convert<Int>() + if (fstat(dirFd, info.ptr) == 0 && (info.st_mode.convert<Int>() and ownerAccess) != ownerAccess) { + fchmod(dirFd, (info.st_mode.convert<Int>() or ownerAccess).convert()) + } + } + // fdopendir takes over the descriptor: closedir closes it. + val dir = fdopendir(dirFd) ?: run { + close(dirFd) + return + } try { + val names = mutableListOf<String>() while (true) { val entry = readdir(dir) ?: break val name = entry.pointed.d_name.toKString() if (name != "." && name != "..") names += name } + names.forEach { deleteEntry(Entry(dirFd, it, "$path/$it")) } } finally { closedir(dir) } - return names -} - -@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) -private fun isRealDirectory(path: String): Boolean = memScoped { - val info = alloc<stat>() - lstat(path, info.ptr) == 0 && (info.st_mode.convert<Int>() and S_IFMT.convert<Int>()) == S_IFDIR.convert<Int>() } @OptIn(ExperimentalForeignApi::class) diff --git a/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt b/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt new file mode 100644 index 000000000..d4b983634 --- /dev/null +++ b/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt @@ -0,0 +1,118 @@ +package dev.kdriver.core.browser + +import kotlinx.cinterop.* +import kotlinx.io.files.Path +import platform.posix.* +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** The POSIX recursive delete of a temporary profile, on the native targets. */ +@OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) +class PosixDeleteRecursivelyTest { + + @Test + fun removesNestedContent() { + val root = tempDir("kdriver_delete_test_") + makeDir("$root/Default") + makeDir("$root/Default/Cache") + writeFile("$root/Default/Cache/data") + writeFile("$root/Local State") + + assertTrue(deleteRecursively(Path(root))) + assertFalse(exists(root)) + } + + @Test + fun removesADirectoryItCannotListAtFirst() { + // A permission check that root bypasses: nothing to prove there. + if (getuid() == 0u) return + val root = tempDir("kdriver_delete_test_") + makeDir("$root/locked") + writeFile("$root/locked/file") + chmod("$root/locked", 0.convert()) + makeDir("$root/searchOnly") + writeFile("$root/searchOnly/file") + chmod("$root/searchOnly", S_IRUSR.convert()) + + assertTrue(deleteRecursively(Path(root)), "an entry of our own profile is made deletable first") + assertFalse(exists(root)) + } + + @Test + fun neverFollowsNorChangesWhatALinkPointsTo() { + val outside = tempDir("kdriver_outside_test_") + writeFile("$outside/kept") + // Read-only, so a delete that followed the link would have to chmod it first. + chmod(outside, (S_IRUSR or S_IXUSR).convert()) + val root = tempDir("kdriver_delete_test_") + try { + assertEquals(0, symlink(outside, "$root/link")) + + assertTrue(deleteRecursively(Path(root))) + + assertFalse(exists(root)) + assertTrue(exists("$outside/kept"), "what a link points to must never be deleted") + assertEquals(S_IRUSR or S_IXUSR, modeOf(outside) and S_IRWXU, "nor have its mode changed") + } finally { + chmod(outside, S_IRWXU.convert()) + deleteRecursively(Path(outside)) + } + } + + @Test + fun removesARootThatIsALinkWithoutFollowingIt() { + val outside = tempDir("kdriver_outside_test_") + writeFile("$outside/kept") + val link = "${tempDir("kdriver_link_parent_")}/profile" + try { + assertEquals(0, symlink(outside, link)) + + assertTrue(deleteRecursively(Path(link))) + + assertFalse(exists(link)) + assertTrue(exists("$outside/kept")) + } finally { + deleteRecursively(Path(outside)) + deleteRecursively(Path(link.substringBeforeLast('/'))) + } + } + + @Test + fun isTrueForAMissingDirectory() { + val missing = tempDir("kdriver_missing_test_").also { rmdir(it) } + + assertTrue(deleteRecursively(Path(missing))) + } + + private fun tempDir(prefix: String): String { + val base = getenv("TMPDIR")?.toKString()?.trimEnd('/')?.takeIf { it.isNotEmpty() } ?: "/tmp" + val template = "$base/${prefix}XXXXXX".cstr + return memScoped { + val buffer = template.getPointer(this) + mkdtemp(buffer)?.toKString() ?: error("mkdtemp failed: errno $errno") + } + } + + private fun makeDir(path: String) { + assertEquals(0, mkdir(path, S_IRWXU.convert()), "mkdir $path") + } + + private fun writeFile(path: String) { + val file = fopen(path, "w") ?: error("fopen $path failed: errno $errno") + fputs("x", file) + fclose(file) + } + + private fun exists(path: String): Boolean = memScoped { + lstat(path, alloc<stat>().ptr) == 0 + } + + private fun modeOf(path: String): Int = memScoped { + val info = alloc<stat>() + check(lstat(path, info.ptr) == 0) + info.st_mode.convert() + } + +} diff --git a/core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt similarity index 100% rename from core/src/linuxTest/kotlin/dev/kdriver/core/tab/TabTest.kt rename to core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt From ab0f0c83e60b3f62cc210629a570962186a24ab7 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 13:03:25 +0100 Subject: [PATCH 18/26] fix: do not close a browser kdriver only connected to when the host exits start() registered every browser with the exit hook, including one reached through browserUrl or a host and port, so the hook sent Browser.close to a browser that may be shared or owned by something else. The old per-browser hook skipped it (stopped is true without a process). Only a browser kdriver launched is registered now. --- .../dev/kdriver/core/browser/DefaultBrowser.kt | 4 +++- .../dev/kdriver/core/browser/StartedBrowsers.kt | 4 +++- .../kdriver/core/browser/TemporaryProfileTest.kt | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 541f8f05a..6257a66a5 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -351,8 +351,10 @@ open class DefaultBrowser( } process = launched temporaryProfileUser = launched + // Only a browser kdriver launched: one it merely connected to (browserUrl, or host and + // port) may be shared or owned by something else, so the exit hook must not close it. + StartedBrowsers.register(this) } - StartedBrowsers.register(this) logger.info("Browser process started with PID: ${process?.pid()}") if (config.browserUrl == null && config.port == null) error("Port not set") diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt index 1f3b178dd..50f36436a 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/StartedBrowsers.kt @@ -8,7 +8,9 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** - * The browsers this process started and has not stopped (nor detached) yet. + * The browsers this process launched and has not stopped (nor detached) yet. A browser it only + * connected to (through [Config.browserUrl], or a host and port) is never in it: it may be shared, or + * owned by something else, so it is not closed on exit. * * When the host process exits without calling [Browser.stop], they are stopped from a single * shutdown hook (see [addShutdownHook]), which also deletes their temporary profiles. Without it, a diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 630f18f28..6d9d75175 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -443,6 +443,20 @@ class TemporaryProfileTest { } } + @Test + fun exitHook_leavesABrowserItOnlyConnectedTo() = runBlocking { + val owner = createBrowser(this, headless = true, sandbox = false) + val connected = createBrowser(this, Config(host = owner.config.host, port = owner.config.port)) + try { + assertEquals(null, connected.pid, "it connected to the running browser, launched nothing") + assertFalse(connected in StartedBrowsers, "a browser kdriver did not launch is not closed on exit") + assertTrue(owner in StartedBrowsers) + } finally { + connected.detach() + owner.stop() + } + } + @Test fun detach_keepsTheProfileTheBrowserStillRunsOn() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false) From e491c9a23d8dc286811b0890ff981928e1300ff4 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 13:03:25 +0100 Subject: [PATCH 19/26] fix: run the blocking profile deletion on the I/O dispatcher Each delete attempt walks the whole profile with blocking file system calls, up to 26 times when a file stays locked; it ran on the caller's dispatcher, blocking a small one (a UI thread, a single-threaded loop) for the walk. --- .../dev/kdriver/core/browser/TemporaryProfile.kt | 10 +++++++++- .../kdriver/core/browser/FileSystemDispatcher.js.kt | 7 +++++++ .../kdriver/core/browser/FileSystemDispatcher.jvm.kt | 6 ++++++ .../core/browser/FileSystemDispatcher.native.kt | 7 +++++++ 4 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt create mode 100644 core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt create mode 100644 core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt index 276295e01..f95bf2fbb 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.kt @@ -1,6 +1,8 @@ package dev.kdriver.core.browser +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext import kotlinx.io.files.Path /** @@ -14,6 +16,12 @@ import kotlinx.io.files.Path */ internal expect fun deleteRecursively(path: Path): Boolean +/** + * Where the blocking file system calls of a profile deletion run, so that a [Browser.stop] called + * from a small dispatcher (a UI thread, a single-threaded loop) does not block it during the walk. + */ +internal expect val fileSystemDispatcher: CoroutineDispatcher + /** * Deletes a temporary profile, retrying for a short while if it cannot be removed at once. * @@ -34,7 +42,7 @@ internal suspend fun deleteTemporaryProfile( delete: (Path) -> Boolean = ::deleteRecursively, ): Boolean { repeat(attempts) { attempt -> - if (delete(path)) return true + if (withContext(fileSystemDispatcher) { delete(path) }) return true if (attempt < attempts - 1) delay(retryDelayMillis) } return false diff --git a/core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt b/core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt new file mode 100644 index 000000000..5f4011e2f --- /dev/null +++ b/core/src/jsMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.js.kt @@ -0,0 +1,7 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers + +/** JS cannot launch a browser, so it never deletes a profile: there is no I/O dispatcher there anyway. */ +internal actual val fileSystemDispatcher: CoroutineDispatcher = Dispatchers.Default diff --git a/core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt new file mode 100644 index 000000000..db7d9be61 --- /dev/null +++ b/core/src/jvmMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.jvm.kt @@ -0,0 +1,6 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers + +internal actual val fileSystemDispatcher: CoroutineDispatcher = Dispatchers.IO diff --git a/core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt b/core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt new file mode 100644 index 000000000..0c6be109d --- /dev/null +++ b/core/src/nativeMain/kotlin/dev/kdriver/core/browser/FileSystemDispatcher.native.kt @@ -0,0 +1,7 @@ +package dev.kdriver.core.browser + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO + +internal actual val fileSystemDispatcher: CoroutineDispatcher = Dispatchers.IO From 6f64f452fd40ccad3e46fe03982ad4254eb19522 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 13:03:25 +0100 Subject: [PATCH 20/26] fix: keep the Windows process handle open for as long as the process object is used The handle was closed by whichever thread first saw the exit in isAlive(), while destroy() or another isAlive() could still be about to use it: a TerminateProcess or GetExitCodeProcess on a closed, possibly reused, handle. It is now closed by a cleaner once the object is unreachable, which also releases it after detach(), where nothing ever saw the exit. The temporary profile directory no longer doubles the separator when TEMP ends with one. --- .../dev/kdriver/core/browser/Process.mingw.kt | 56 ++++++++----------- 1 file changed, 23 insertions(+), 33 deletions(-) diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt index b0cfef87d..154160e6b 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt @@ -8,8 +8,9 @@ import kotlinx.io.files.Path import platform.posix.getenv import platform.posix.memset import platform.windows.* -import kotlin.concurrent.AtomicReference import kotlin.concurrent.Volatile +import kotlin.experimental.ExperimentalNativeApi +import kotlin.native.ref.createCleaner import kotlin.random.Random @OptIn(ExperimentalForeignApi::class) @@ -17,19 +18,18 @@ actual abstract class Process { abstract val processHandle: HANDLE? abstract val processId: DWORD - /** The exit code, once the process has been seen to exit; its handle is closed from then on. */ + /** The exit code, once the process has been seen to exit. */ @Volatile internal var exitCode: DWORD? = null private set actual fun isAlive(): Boolean { - // Null once the exit was seen (the handle is closed then), without a handle, or if unreadable. - val code = if (exitCode == null) processHandle?.let { readExitCode(it) } else null - if (code != null && code != STILL_ACTIVE) { - exitCode = code - releaseHandle() - } - return code == STILL_ACTIVE + if (exitCode != null) return false + val handle = processHandle ?: return false + val code = readExitCode(handle) ?: return false + if (code == STILL_ACTIVE) return true + exitCode = code + return false } private fun readExitCode(handle: HANDLE): DWORD? = memScoped { @@ -37,13 +37,6 @@ actual abstract class Process { if (GetExitCodeProcess(handle, c.ptr) == 0) null else c.value } - /** - * Closes the process handle, once the process has exited and nothing needs it anymore. Kept open - * until then, `destroy` included: [isAlive] reads the exit code through it, to know when the - * process is really gone (and its profile can be deleted). - */ - protected abstract fun releaseHandle() - actual fun pid(): Long { return processId.toLong() } @@ -51,27 +44,23 @@ actual abstract class Process { actual abstract fun destroy() } -@OptIn(ExperimentalForeignApi::class) +@OptIn(ExperimentalForeignApi::class, ExperimentalNativeApi::class) private class WindowsProcess( - processHandle: HANDLE?, + override val processHandle: HANDLE?, override val processId: DWORD, ) : Process() { - private val handle = AtomicReference(processHandle) - - override val processHandle: HANDLE? - get() = handle.value - - /** Atomic, so two threads seeing the exit at once do not close the same handle twice. */ - override fun releaseHandle() { - handle.getAndSet(null)?.let { CloseHandle(it) } - } + /** + * Closes the process handle once this object is unreachable, and never before: [isAlive] reads + * the exit code through it (to know when the process is really gone, and its profile can be + * deleted) and [destroy] terminates through it, from any thread, for as long as the object is + * used. Closing it any earlier would race them onto a closed, or reused, handle. + */ + @Suppress("unused") + private val handleCleaner = processHandle?.let { handle -> createCleaner(handle) { CloseHandle(it) } } override fun destroy() { - processHandle?.let { - if (isAlive()) { - TerminateProcess(it, 1u) - } - } + val handle = processHandle ?: return + if (isAlive()) TerminateProcess(handle, 1u) } } @@ -167,7 +156,8 @@ actual fun isRoot(): Boolean { @OptIn(ExperimentalForeignApi::class) actual fun tempProfileDir(): Path { - val tempDir = getEnv("TEMP") ?: getEnv("TMP") ?: "C:\\Temp" + // Without a trailing separator, which would double the one added below. + val tempDir = (getEnv("TEMP") ?: getEnv("TMP") ?: "C:\\Temp").trimEnd('\\', '/') val uniqueName = "kdriver_${Random.nextLong().toString(16)}" val profilePath = "$tempDir\\$uniqueName" From 7fbe24cf6b42df75c8443366f81c620af39ca3d1 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 13:44:06 +0100 Subject: [PATCH 21/26] fix(deps): update Ktor to 3.4.3 for Curl WebSocket fixes on Linux native On Linux native (Curl engine) a CDP command could get no answer (a 30 s command timeout in TabTest.testGetContentGetsHtmlContent, on DOM.getDocument or DOM.getOuterHTML) once another browser had run and stopped in the same process. Ktor 3.4.1 to 3.4.3 fix several Curl WebSocket bugs, among them a WebSocket cancellation that could cancel a new request reusing the same easy handle (KTOR-9540) and a freeze on large responses (KTOR-9527). With 3.4.0 the Linux native tests failed on every run of this branch since the ready state wait was added; with 3.4.3 they pass. --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 85d40bfd3..250b5fbf4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,7 +5,7 @@ detekt = "1.23.8" dokka = "2.2.0" ksp = "2.3.12" maven = "0.37.0" -ktor = "3.4.0" +ktor = "3.4.3" mockk = "1.13.12" slf4j = "2.0.17" jsoup = "1.16.2" From d14312baa13d935d8b6dc100698e7062d97f41c1 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 13:48:26 +0100 Subject: [PATCH 22/26] fix: keep a browser whose failed start already stopped it for the exit hook, and retry a failed kill create() chose between stop() and detach() on the pid, which stop() clears: a start that stopped the browser itself (no answer on the debug port) and then threw got detached, which took it off the exit hook even when its profile could not be deleted or its process could not be killed. It now asks whether the instance launched a process. A kill that fails no longer forgets the process either, so the exit hook's stop() tries again. The KDoc now says the profile is deleted by the browser kdriver launches on it: a browser it only connects to never owns a profile. --- .../kotlin/dev/kdriver/core/browser/Config.kt | 8 ++--- .../kdriver/core/browser/DefaultBrowser.kt | 18 ++++++++++-- .../core/browser/TemporaryProfileTest.kt | 29 +++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index 52423c79c..347723990 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -59,8 +59,8 @@ class Config( * True when [userDataDir] is a temporary profile kdriver created (no directory was given), and it * has been created already. * - * Carried over by [copy], like [userDataDir] itself: the browser that runs on such a profile - * deletes it when it stops, whichever copy of the configuration created it. Otherwise a profile + * Carried over by [copy], like [userDataDir] itself: the browser kdriver launches on such a + * profile deletes it when it stops, whichever copy of the configuration created it. Otherwise a profile * created before the browser copied its configuration (for instance by reading [userDataDir] * first) would never be deleted. */ @@ -92,7 +92,7 @@ class Config( * The browser profile directory. * * When none is given, the first read creates a temporary `kdriver_*` directory, which the browser - * running on it deletes when it stops. A directory given here is never deleted. + * kdriver launches on it deletes when it stops. A directory given here is never deleted. */ var userDataDir: Path get() { @@ -166,7 +166,7 @@ class Config( * mutating one config never affects the other. * * A temporary profile this config already created is shared with the copy, not duplicated: the - * browser that runs on it deletes it when it stops (see [Browser.cleanupTemporaryProfile]). + * browser kdriver launches on it deletes it when it stops (see [Browser.cleanupTemporaryProfile]). */ fun copy(): Config = Config( // Pass the already-resolved executable so the copy does not re-run the disk search. diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt index 6257a66a5..3dff70381 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/DefaultBrowser.kt @@ -57,6 +57,14 @@ open class DefaultBrowser( * [detach]: the profile may only be deleted once this process has exited. */ private var temporaryProfileUser: Process? = null + + /** + * Whether this instance launched a browser process (rather than connecting to one), even if it + * has been stopped since: a failed start may have stopped it already, and must not then be + * treated as a browser it only connected to. + */ + internal var launchedProcess: Boolean = false + private set private val temporaryProfileMutex = Mutex() /** How long [cleanupTemporaryProfile] waits for the browser process to exit; shortened by tests. */ @@ -186,7 +194,7 @@ open class DefaultBrowser( // On failure the caller never gets this instance, so it could never stop the browser // it launched. A browser it only connected to (connect-existing) is not ours to close: // it may be shared, so only the client side is torn down. - cleanUpAfter(e) { if (instance.pid != null) instance.stop() else instance.detach() } + cleanUpAfter(e) { if (instance.launchedProcess) instance.stop() else instance.detach() } throw e } return instance @@ -351,6 +359,7 @@ open class DefaultBrowser( } process = launched temporaryProfileUser = launched + launchedProcess = true // Only a browser kdriver launched: one it merely connected to (browserUrl, or host and // port) may be shared or owned by something else, so the exit hook must not close it. StartedBrowsers.register(this) @@ -542,7 +551,12 @@ open class DefaultBrowser( // browser started on the same --user-data-dir right after would hang before opening its debug // port, and the start would time out for no visible reason. val process = process ?: return - if (!process.destroyAndAwaitExit()) logger.warn("Browser process ${process.pid()} still alive after kill") + if (!process.destroyAndAwaitExit()) { + // Kept, so that a later stop() (the exit hook's, since the browser stays registered with + // its profile) tries to kill it again. + logger.warn("Browser process ${process.pid()} still alive after kill") + return + } this.process = null } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt index 6d9d75175..11d4051b7 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/TemporaryProfileTest.kt @@ -170,6 +170,35 @@ class TemporaryProfileTest { assertFalse(browser in StartedBrowsers) } + @Test + fun create_keepsForTheExitHookABrowserItsFailedStartAlreadyStopped() = runBlocking { + var launched: DefaultBrowser? = null + assertFailsWith<IllegalStateException> { + DefaultBrowser.create(this, Config(headless = true, sandbox = false)) { scope, config -> + object : DefaultBrowser(scope, config) { + // As start() does when the browser never answers: it stops the browser, then throws. + override suspend fun start(): Browser { + super.start() + deleteProfile = { false } + stop() + error("failed to connect") + } + }.also { launched = it } + } + } + + val browser = assertNotNull(launched) + val profile = File(browser.config.userDataDir.toString()) + try { + assertTrue(profile.isDirectory, "the profile could not be deleted…") + assertTrue(browser in StartedBrowsers, "…so the browser stays for the exit hook, not detached") + } finally { + browser.deleteProfile = { deleteTemporaryProfile(it) } + browser.stop() + } + assertFalse(profile.exists()) + } + @Test fun create_keepsTheOriginalFailureWhenTheCleanupFailsToo() = runBlocking { val failure = assertFailsWith<IllegalStateException> { From c084b26fab62db17325cf26527e425849b91e36b Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 13:48:26 +0100 Subject: [PATCH 23/26] test: share the native TabTest between macOS and Linux in posixTest --- core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt index 22e419bed..3c0df8eff 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt @@ -195,13 +195,11 @@ class BrowserTest { assertEquals("Example Domain", page1.targetInfo?.title) val page2 = browser2.get("https://example.com/two") - // Not a fixed wait: get() returns before the page has loaded, while the title is still its URL. page2.awaitTitle(browser2, "Example Domain") assertNotNull(page2.targetInfo) assertEquals("Example Domain", page2.targetInfo?.title) val page3 = browser3.get("https://example.com/three") - // Not a fixed wait: get() returns before the page has loaded, while the title is still its URL. page3.awaitTitle(browser3, "Example Domain") assertNotNull(page3.targetInfo) assertEquals("Example Domain", page3.targetInfo?.title) From da5de067dde96c03b245e891a35213d776c3fab7 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 14:02:29 +0100 Subject: [PATCH 24/26] test: load local pages in testMultipleBrowsersDiffUserData, and wait for the page in lookup tests testMultipleBrowsersDiffUserData loaded example.com/one, /two and /three: on a CI run one of them was still loading after 30 s, so the test measured the runner's network, not the browsers. It now loads three local pages and waits for their titles. The lookup tests ran their lookups right after get(), which returns once the navigation has started: select("li[", timeout = 0) could find no document yet and time out instead of getting the browser's error. They now wait for the page's ready state first. --- .../dev/kdriver/core/browser/BrowserTest.kt | 21 ++++++++++--------- .../kdriver/core/tab/LookupBehaviourTest.kt | 6 +++++- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt index 3c0df8eff..603a90bf5 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt @@ -188,21 +188,22 @@ class BrowserTest { ) assertEquals(3, userDataDirs.size) - val page1 = browser1.get("https://example.com/one") - // Not a fixed wait: get() returns before the page has loaded, while the title is still its URL. - page1.awaitTitle(browser1, "Example Domain") + val page1 = browser1.get(sampleFile("groceries.html")) + // Local pages: the test is about the browsers, not about how fast a remote site answers. And not a + // fixed wait: get() returns before the page has loaded, while the title is still its URL. + page1.awaitTitle(browser1, "Grocery List") assertNotNull(page1.targetInfo) - assertEquals("Example Domain", page1.targetInfo?.title) + assertEquals("Grocery List", page1.targetInfo?.title) - val page2 = browser2.get("https://example.com/two") - page2.awaitTitle(browser2, "Example Domain") + val page2 = browser2.get(sampleFile("lookup-test.html")) + page2.awaitTitle(browser2, "Lookup") assertNotNull(page2.targetInfo) - assertEquals("Example Domain", page2.targetInfo?.title) + assertEquals("Lookup", page2.targetInfo?.title) - val page3 = browser3.get("https://example.com/three") - page3.awaitTitle(browser3, "Example Domain") + val page3 = browser3.get(sampleFile("profile.html")) + page3.awaitTitle(browser3, "Fetch Example") assertNotNull(page3.targetInfo) - assertEquals("Example Domain", page3.targetInfo?.title) + assertEquals("Fetch Example", page3.targetInfo?.title) browser1.stop() browser2.stop() diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt index 23d7a4d26..02e686f82 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt @@ -26,7 +26,11 @@ class LookupBehaviourTest { private fun withPage(block: suspend Tab.() -> Unit) = runBlocking { val browser: Browser = createBrowser(this as CoroutineScope, headless = true, sandbox = false) try { - browser.get(sampleFile("lookup-test.html")).block() + // get() returns once the navigation has started: a lookup before the page has loaded would + // find nothing (and time out) rather than reach the document. + val tab = browser.get(sampleFile("lookup-test.html")) + tab.waitForReadyState(ReadyState.COMPLETE) + tab.block() } finally { browser.stop() } From 769f970be8808f85b7c49466b82f0f798c44f5bd Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 14:18:24 +0100 Subject: [PATCH 25/26] test: read the page title from the loaded document in testMultipleBrowsersDiffUserData Waiting for the target to report the title still failed on CI (on Ubuntu and Windows): the page had its URL as target title 30 s after get(), on a local file. The test now waits for the document's ready state, as the other page tests do, and reads document.title; the propagation of the title into the target info is covered by testUpdateTargetSetsTargetTitle. --- .../kotlin/dev/kdriver/core/Extensions.kt | 37 ------------------- .../dev/kdriver/core/browser/BrowserTest.kt | 19 +++++----- 2 files changed, 10 insertions(+), 46 deletions(-) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt index 2d5caa495..746ab25d9 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/Extensions.kt @@ -1,45 +1,8 @@ package dev.kdriver.core -import dev.kdriver.cdp.domain.target -import dev.kdriver.core.browser.Browser -import dev.kdriver.core.tab.Tab -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.async -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.withTimeoutOrNull - fun sampleFile(name: String): String { val resource = checkNotNull(Thread.currentThread().contextClassLoader.getResource(name)) { "Resource '$name' not found" } return resource.toURI().toString() } - -/** - * Waits until the browser reports [title] for this tab's target, then refreshes [Tab.targetInfo]. - * - * `Browser.get` returns once the navigation has started, while the target's title is still its URL: - * Chrome only reports the page's title once the page has parsed it. This waits for that event, with - * no fixed sleep, and fails after [timeoutMillis]: generous, since the first page load of a run, on a - * cold runner, has been seen to take more than ten seconds. - */ -suspend fun Tab.awaitTitle(browser: Browser, title: String, timeoutMillis: Long = 30_000) { - val targetId = checkNotNull(targetInfo?.targetId) { "the tab has no target" } - val events = checkNotNull(browser.connection) { "the browser is not started" }.target.targetInfoChanged - val loaded = withTimeoutOrNull(timeoutMillis) { - coroutineScope { - // Subscribed before the current title is read, so the event cannot slip in between. - val titled = async(start = CoroutineStart.UNDISPATCHED) { - events.first { it.targetInfo.targetId == targetId && it.targetInfo.title == title } - } - updateTarget() - if (targetInfo?.title != title) { - titled.await() - updateTarget() - } - titled.cancel() - } - } - checkNotNull(loaded) { "the target still reports the title '${targetInfo?.title}' after $timeoutMillis ms, not '$title'" } -} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt index 603a90bf5..7c99c7422 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/BrowserTest.kt @@ -1,9 +1,9 @@ package dev.kdriver.core.browser import dev.kdriver.cdp.domain.Network -import dev.kdriver.core.awaitTitle import dev.kdriver.core.sampleFile import dev.kdriver.core.tab.ReadyState +import dev.kdriver.core.tab.evaluate import kotlinx.coroutines.runBlocking import kotlinx.io.files.Path import kotlin.io.path.deleteIfExists @@ -189,21 +189,22 @@ class BrowserTest { assertEquals(3, userDataDirs.size) val page1 = browser1.get(sampleFile("groceries.html")) - // Local pages: the test is about the browsers, not about how fast a remote site answers. And not a - // fixed wait: get() returns before the page has loaded, while the title is still its URL. - page1.awaitTitle(browser1, "Grocery List") + // Local pages: the test is about the browsers, not about how fast a remote site answers. Read once + // loaded, from the document: get() returns once the navigation has started, and the target's title + // can still be its URL for a while after the load. + page1.waitForReadyState(ReadyState.COMPLETE) assertNotNull(page1.targetInfo) - assertEquals("Grocery List", page1.targetInfo?.title) + assertEquals("Grocery List", page1.evaluate<String>("document.title")) val page2 = browser2.get(sampleFile("lookup-test.html")) - page2.awaitTitle(browser2, "Lookup") + page2.waitForReadyState(ReadyState.COMPLETE) assertNotNull(page2.targetInfo) - assertEquals("Lookup", page2.targetInfo?.title) + assertEquals("Lookup", page2.evaluate<String>("document.title")) val page3 = browser3.get(sampleFile("profile.html")) - page3.awaitTitle(browser3, "Fetch Example") + page3.waitForReadyState(ReadyState.COMPLETE) assertNotNull(page3.targetInfo) - assertEquals("Fetch Example", page3.targetInfo?.title) + assertEquals("Fetch Example", page3.evaluate<String>("document.title")) browser1.stop() browser2.stop() From 733fe7437711e5bc491261f56a813416bb4f72d6 Mon Sep 17 00:00:00 2001 From: NathanFallet <contact@nathanfallet.me> Date: Sat, 21 Nov 2026 14:36:58 +0100 Subject: [PATCH 26/26] style: address static analysis findings on the native profile deletion Fewer returns in isAlive (Windows), openDirectory and withCanonicalParent (POSIX), a named check instead of indexes for drive paths, the DirectoryAccess actuals named after it, and KDoc and named constants in the native tests. --- ...file.linux.kt => DirectoryAccess.linux.kt} | 3 +++ ...file.macos.kt => DirectoryAccess.macos.kt} | 3 +++ .../dev/kdriver/core/browser/Process.mingw.kt | 10 +++----- .../core/browser/TemporaryProfile.mingw.kt | 7 ++++-- .../browser/WindowsDeleteRecursivelyTest.kt | 25 +++++++++++++++---- .../core/browser/TemporaryProfile.posix.kt | 17 +++++++------ .../browser/PosixDeleteRecursivelyTest.kt | 5 ++++ .../kotlin/dev/kdriver/core/tab/TabTest.kt | 2 ++ 8 files changed, 51 insertions(+), 21 deletions(-) rename core/src/linuxMain/kotlin/dev/kdriver/core/browser/{TemporaryProfile.linux.kt => DirectoryAccess.linux.kt} (94%) rename core/src/macosMain/kotlin/dev/kdriver/core/browser/{TemporaryProfile.macos.kt => DirectoryAccess.macos.kt} (91%) diff --git a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.linux.kt similarity index 94% rename from core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt rename to core/src/linuxMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.linux.kt index b89c7cb37..cccfaf7fc 100644 --- a/core/src/linuxMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.linux.kt +++ b/core/src/linuxMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.linux.kt @@ -1,3 +1,6 @@ +// One actual per POSIX target, named after the expect object it implements. +@file:Suppress("MatchingDeclarationName") + package dev.kdriver.core.browser import kotlinx.cinterop.ExperimentalForeignApi diff --git a/core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt b/core/src/macosMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.macos.kt similarity index 91% rename from core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt rename to core/src/macosMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.macos.kt index 871f945a5..98075e1b4 100644 --- a/core/src/macosMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.macos.kt +++ b/core/src/macosMain/kotlin/dev/kdriver/core/browser/DirectoryAccess.macos.kt @@ -1,3 +1,6 @@ +// One actual per POSIX target, named after the expect object it implements. +@file:Suppress("MatchingDeclarationName") + package dev.kdriver.core.browser import kotlinx.cinterop.ExperimentalForeignApi diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt index 154160e6b..6eef34ada 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/Process.mingw.kt @@ -24,12 +24,10 @@ actual abstract class Process { private set actual fun isAlive(): Boolean { - if (exitCode != null) return false - val handle = processHandle ?: return false - val code = readExitCode(handle) ?: return false - if (code == STILL_ACTIVE) return true - exitCode = code - return false + // Null once the exit was seen, without a handle, or if unreadable: not alive in all three cases. + val code = if (exitCode == null) processHandle?.let { readExitCode(it) } else null + if (code != null && code != STILL_ACTIVE) exitCode = code + return code == STILL_ACTIVE } private fun readExitCode(handle: HANDLE): DWORD? = memScoped { diff --git a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt index 375e0cfcc..2367449b7 100644 --- a/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt +++ b/core/src/mingwMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.mingw.kt @@ -38,8 +38,7 @@ internal fun extendedLengthPath(path: String): String { windowsPath.startsWith(EXTENDED_PREFIX) || windowsPath.startsWith(DEVICE_PREFIX) -> windowsPath // \\server\share\... becomes \\?\UNC\server\share\... windowsPath.startsWith("\\\\") -> EXTENDED_PREFIX + "UNC\\" + windowsPath.removePrefix("\\\\") - windowsPath.length >= 3 && windowsPath[0].isLetter() && windowsPath[1] == ':' && windowsPath[2] == '\\' -> - EXTENDED_PREFIX + windowsPath + isDriveAbsolute(windowsPath) -> EXTENDED_PREFIX + windowsPath else -> windowsPath } } @@ -47,6 +46,10 @@ internal fun extendedLengthPath(path: String): String { private const val EXTENDED_PREFIX = "\\\\?\\" private const val DEVICE_PREFIX = "\\\\.\\" +/** `C:\\...`: a drive letter, a colon and a separator. */ +private fun isDriveAbsolute(path: String): Boolean = + path.getOrNull(0)?.isLetter() == true && path.getOrNull(1) == ':' && path.getOrNull(2) == '\\' + private fun collapseSeparators(path: String): String = buildString(path.length) { path.forEach { c -> if (c != '\\' || lastOrNull() != '\\') append(c) } } diff --git a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt index 769f91825..20f1b42ed 100644 --- a/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt +++ b/core/src/mingwTest/kotlin/dev/kdriver/core/browser/WindowsDeleteRecursivelyTest.kt @@ -16,17 +16,18 @@ import kotlin.test.assertTrue @OptIn(ExperimentalForeignApi::class) class WindowsDeleteRecursivelyTest { + /** Entries nested past `MAX_PATH` are deleted, through the extended-length form. */ @Test fun removesEntriesBeyondTheMaxPathLimit() { - val root = "${tempBase()}\\kdriver_long_path_test_${Random.nextLong().toString(16)}" + val root = "${tempBase()}\\kdriver_long_path_test_${randomSuffix()}" // Nested well past 260 characters, as a profile's extension or cache directories can be. var deepest = root createDirectory(root) - repeat(8) { level -> - deepest = "$deepest\\${"d$level".padEnd(40, 'x')}" + repeat(LEVELS) { level -> + deepest = "$deepest\\${"d$level".padEnd(LEVEL_NAME_LENGTH, 'x')}" createDirectory(deepest) } - assertTrue(deepest.length > 300, "the test path must pass MAX_PATH, is ${deepest.length}") + assertTrue(deepest.length > MAX_PATH, "the test path must pass MAX_PATH, is ${deepest.length}") val file = "$deepest\\Cookies" val handle: HANDLE? = CreateFileW( extendedLengthPath(file), @@ -44,6 +45,7 @@ class WindowsDeleteRecursivelyTest { assertEquals(INVALID_FILE_ATTRIBUTES, GetFileAttributesW(extendedLengthPath(root))) } + /** The extended-length form of drive, UNC, already extended, device and relative paths. */ @Test fun extendedLengthPathPrefixesAbsolutePathsOnly() { assertEquals("\\\\?\\C:\\Temp\\kdriver_1", extendedLengthPath("C:\\Temp\\kdriver_1")) @@ -57,9 +59,10 @@ class WindowsDeleteRecursivelyTest { assertEquals("\\\\?\\UNC\\server\\share\\kdriver_1", extendedLengthPath("\\\\server\\share\\\\kdriver_1")) } + /** A doubled separator, which the extended-length form would take literally, is collapsed. */ @Test fun removesAProfileWhosePathHasADoubledSeparator() { - val name = "kdriver_double_separator_test_${Random.nextLong().toString(16)}" + val name = "kdriver_double_separator_test_${randomSuffix()}" createDirectory("${tempBase()}\\$name") createDirectory("${tempBase()}\\$name\\Default") @@ -67,17 +70,21 @@ class WindowsDeleteRecursivelyTest { assertEquals(INVALID_FILE_ATTRIBUTES, GetFileAttributesW(extendedLengthPath("${tempBase()}\\$name"))) } + /** Only a missing entry counts as deleted, not one the system refuses to reach. */ @Test fun aProfileThatCannotBeReachedIsNotReportedGone() { // An invalid name, not a missing one: deleting it fails, and must not count as done. assertFalse(deleteRecursively(Path("C:\\kdriver_invalid_<name>"))) } + /** `TEMP` ending with a separator does not double it in the profile path. */ @Test fun tempProfileDirHasNoDoubledSeparator() { assertFalse("\\\\" in tempProfileDir().toString().removePrefix("\\\\")) } + private fun randomSuffix(): String = Random.nextLong().toString(HEX) + private fun tempBase(): String = (getenv("TEMP") ?: getenv("TMP"))?.toKString()?.trimEnd('\\', '/') ?: "C:\\Temp" @@ -85,4 +92,12 @@ class WindowsDeleteRecursivelyTest { assertNotEquals(0, CreateDirectoryW(extendedLengthPath(path), null), "create $path, error ${GetLastError()}") } + private companion object { + /** Eight levels of 40 characters: well past the 260 of `MAX_PATH`. */ + const val LEVELS = 8 + const val LEVEL_NAME_LENGTH = 40 + const val MAX_PATH = 260 + const val HEX = 16 + } + } diff --git a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt index 7370fef82..52b608c1f 100644 --- a/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt +++ b/core/src/posixMain/kotlin/dev/kdriver/core/browser/TemporaryProfile.posix.kt @@ -27,15 +27,14 @@ internal actual fun deleteRecursively(path: Path): Boolean { @OptIn(ExperimentalForeignApi::class) private fun withCanonicalParent(path: String): String { val slash = path.lastIndexOf('/') - if (slash < 0) return path - val parent = if (slash == 0) "/" else path.substring(0, slash) + val parent = if (slash == 0) "/" else path.substring(0, slash.coerceAtLeast(0)) // A buffer of our own: the realpath Kotlin/Native binds on macOS is the legacy one, which refuses // a null buffer. - val canonical = memScoped { + val canonical = if (slash < 0) null else memScoped { val buffer = allocArray<ByteVar>(PATH_MAX + 1) realpath(parent, buffer)?.toKString() - } ?: return path - return "${canonical.trimEnd('/')}/${path.substring(slash + 1)}" + } + return canonical?.let { "${it.trimEnd('/')}/${path.substring(slash + 1)}" } ?: path } /** @@ -89,9 +88,11 @@ private fun deleteEntry(entry: Entry) { @OptIn(ExperimentalForeignApi::class) private fun openDirectory(entry: Entry): Int { val fd = DirectoryAccess.openDirectory(entry) - if (fd >= 0 || errno != EACCES) return fd - if (!DirectoryAccess.grantOwnerAccess(entry)) return -1 - return DirectoryAccess.openDirectory(entry) + return when { + fd >= 0 || errno != EACCES -> fd + DirectoryAccess.grantOwnerAccess(entry) -> DirectoryAccess.openDirectory(entry) + else -> -1 + } } /** diff --git a/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt b/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt index d4b983634..82eae1059 100644 --- a/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt +++ b/core/src/posixTest/kotlin/dev/kdriver/core/browser/PosixDeleteRecursivelyTest.kt @@ -12,6 +12,7 @@ import kotlin.test.assertTrue @OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) class PosixDeleteRecursivelyTest { + /** Directories and files at several levels are all deleted. */ @Test fun removesNestedContent() { val root = tempDir("kdriver_delete_test_") @@ -24,6 +25,7 @@ class PosixDeleteRecursivelyTest { assertFalse(exists(root)) } + /** A directory of the profile without read, or without write and search permission, is made deletable. */ @Test fun removesADirectoryItCannotListAtFirst() { // A permission check that root bypasses: nothing to prove there. @@ -40,6 +42,7 @@ class PosixDeleteRecursivelyTest { assertFalse(exists(root)) } + /** A link inside the profile is unlinked: its target is neither deleted nor has its mode changed. */ @Test fun neverFollowsNorChangesWhatALinkPointsTo() { val outside = tempDir("kdriver_outside_test_") @@ -61,6 +64,7 @@ class PosixDeleteRecursivelyTest { } } + /** A profile path that is itself a link is unlinked, not followed. */ @Test fun removesARootThatIsALinkWithoutFollowingIt() { val outside = tempDir("kdriver_outside_test_") @@ -79,6 +83,7 @@ class PosixDeleteRecursivelyTest { } } + /** Nothing to delete counts as deleted. */ @Test fun isTrueForAMissingDirectory() { val missing = tempDir("kdriver_missing_test_").also { rmdir(it) } diff --git a/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt b/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt index 042b91c42..9b4d18706 100644 --- a/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt +++ b/core/src/posixTest/kotlin/dev/kdriver/core/tab/TabTest.kt @@ -5,8 +5,10 @@ import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertTrue +/** Tab tests on the native POSIX targets (macOS, Linux). */ class TabTest { + /** The page's HTML, once it has loaded. */ @Test fun testGetContentGetsHtmlContent() = runBlocking { val browser = createBrowser(this, headless = true, sandbox = false)