ReviewOS

also looking at this

craft-native/craft

Android: Bluetooth heart-rate straps, and offline media on WorkManager

#370
Merged chris wants to merge feat/android-heart-rate into main
21 files +2307 -56

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

packages/android/compile-fixtures/CraftNativeResumableDownloadTest.ktmodified+38-24
Changes to packages/android/compile-fixtures/CraftNativeResumableDownloadTest.kt
@@ -1,8 +1,8 @@
11package {{PACKAGE_NAME}}
22
3import com.sun.net.httpserver.HttpServer
43import java.io.File
5import java.net.InetSocketAddress
4import java.net.InetAddress
5import java.net.ServerSocket
66import java.nio.file.Files
77import org.junit.Assert.assertArrayEquals
88import org.junit.Assert.assertEquals
@@ -19,32 +19,46 @@ import org.junit.Test
1919class CraftNativeResumableDownloadTest {
2020 private val body = "0123456789abcdefghij".toByteArray()
2121
22 /** Serves `body`, honouring `Range: bytes=N-` when `ranges` is on; records each request's Range. */
22 /**
23 * Serves `body`, honouring `Range: bytes=N-` when `ranges` is on; records
24 * each request's Range. A plain socket: Android's unit-test classpath has
25 * no com.sun.net.httpserver.
26 */
2327 private fun serve(ranges: Boolean = true, status: Int = 200, check: (String, MutableList<String?>) -> Unit) {
24 val seen = mutableListOf<String?>()
25 val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
26 server.createContext("/") { exchange ->
27 val range = exchange.requestHeaders.getFirst("Range")
28 seen.add(range)
29 val start = Regex("^bytes=(\\d+)-$").find(range.orEmpty())?.groupValues?.get(1)?.toInt()
30 when {
31 status != 200 -> exchange.sendResponseHeaders(status, -1)
32 ranges && start != null && start >= body.size -> exchange.sendResponseHeaders(416, -1)
33 ranges && start != null -> {
34 exchange.responseHeaders.add("Content-Range", "bytes $start-${body.size - 1}/${body.size}")
35 exchange.sendResponseHeaders(206, (body.size - start).toLong())
36 exchange.responseBody.use { it.write(body, start, body.size - start) }
37 }
38 else -> {
39 exchange.sendResponseHeaders(200, body.size.toLong())
40 exchange.responseBody.use { it.write(body) }
28 val seen = java.util.Collections.synchronizedList(mutableListOf<String?>())
29 val server = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
30 val thread = Thread {
31 while (!server.isClosed) {
32 val socket = runCatching { server.accept() }.getOrNull() ?: break
33 socket.use { client ->
34 val reader = client.getInputStream().bufferedReader(Charsets.ISO_8859_1)
35 val lines = generateSequence { reader.readLine() }.takeWhile { it.isNotEmpty() }.toList()
36 val range = lines.drop(1).firstOrNull { it.startsWith("Range:", ignoreCase = true) }?.substringAfter(':')?.trim()
37 seen.add(range)
38 val start = Regex("^bytes=(\\d+)-$").find(range.orEmpty())?.groupValues?.get(1)?.toInt()
39 val out = client.getOutputStream()
40 fun head(code: Int, length: Int, extra: String = "") =
41 out.write("HTTP/1.1 $code X\r\nContent-Length: $length\r\n${extra}Connection: close\r\n\r\n".toByteArray(Charsets.ISO_8859_1))
42 when {
43 status != 200 -> head(status, 0)
44 ranges && start != null && start >= body.size -> head(416, 0)
45 ranges && start != null -> {
46 head(206, body.size - start, "Content-Range: bytes $start-${body.size - 1}/${body.size}\r\n")
47 out.write(body, start, body.size - start)
48 }
49 else -> {
50 head(200, body.size)
51 out.write(body)
52 }
53 }
54 out.flush()
4155 }
4256 }
43 exchange.close()
4457 }
45 server.start()
46 try { check("http://127.0.0.1:${server.address.port}/clip.mp4", seen) }
47 finally { server.stop(0) }
58 thread.isDaemon = true
59 thread.start()
60 try { check("http://127.0.0.1:${server.localPort}/clip.mp4", seen) }
61 finally { server.close(); thread.join(2000) }
4862 }
4963
5064 private fun part(check: (File) -> Unit) {
packages/typescript/src/mobile-media-testing.tsmodified+1-1
Changes to packages/typescript/src/mobile-media-testing.ts
@@ -158,7 +158,7 @@ export async function verifyMobileMediaCache(options: MobileMediaCacheTestOption
158158 await Bun.write(join(android, 'settings.gradle.kts'), 'pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }\ndependencyResolutionManagement { repositories { google(); mavenCentral() } }\nrootProject.name = "HQDownloadProbe"\ninclude(":app")')
159159 await Bun.write(join(android, 'build.gradle.kts'), 'plugins { id("com.android.application") version "8.9.1" apply false; id("org.jetbrains.kotlin.android") version "2.0.21" apply false }')
160160 await Bun.write(join(android, 'local.properties'), `sdk.dir=${sdk}\n`)
161 await Bun.write(join(android, 'gradle.properties'), 'org.gradle.jvmargs=-Xmx768m\norg.gradle.workers.max=2\n')
161 await Bun.write(join(android, 'gradle.properties'), 'org.gradle.jvmargs=-Xmx768m\norg.gradle.workers.max=2\nandroid.useAndroidX=true\n')
162162 await Bun.write(join(app, 'build.gradle.kts'), `plugins { id("com.android.application");
163163 id("org.jetbrains.kotlin.android") }\nandroid { namespace = "${packageName}";
164164 compileSdk = 36;
packages/zig/test/android_conformance_test.zigmodified+13-2
Changes to packages/zig/test/android_conformance_test.zig
@@ -140,8 +140,11 @@ const zig_sources = [_][]const u8{
140140/// that dims the screen while it shows little (a workout's big timer);
141141/// 41 when the five crashReporter* methods arrived in the Kotlin first, as
142142/// iOS's did: they queue the page's error events in CraftCrashReporter.kt's
143/// on-disk outbox, which the uncaught-exception handler also writes to.
144const max_not_yet_migrated: usize = 41;
143/// on-disk outbox, which the uncaught-exception handler also writes to;
144/// 42 when heartRate did, as iOS's did (CraftHeartRate.swift): one GATT
145/// session, its reconnects and a recording kept on disk, owned by
146/// CraftHeartRate.kt and the foreground service that keeps it reading.
147const max_not_yet_migrated: usize = 42;
145148
146149/// Every `@JavascriptInterface fun <name>(` in the Kotlin bridge.
147150///
@@ -431,6 +434,14 @@ const deliberate_deferrals = [_]Deferral{
431434 .{ .action = "crashReporterFlush", .reason = "drives the reporter's own delivery thread and backoff" },
432435 .{ .action = "crashReporterContext", .reason = "answers the reporter's session and release, which only it holds" },
433436
437 // ---- Heart rate, which arrived in the Kotlin first ---------------
438 //
439 // One Bluetooth GATT session for the whole app, its reconnects, and a
440 // recording kept on disk while a foreground service keeps the strap
441 // reading with the screen locked. The native screens reach the same
442 // object through CraftNativeServices, so the page's door stays with it.
443 .{ .action = "heartRate", .reason = "drives the app-wide GATT session and recording CraftHeartRate.kt and its service own" },
444
434445 // The auth-persistence trio shares one timestamp in Kotlin-configured
435446 // EncryptedSharedPreferences. It now survives process death, but migrating
436447 // any one action would split ownership of the same key; the trio must move