diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 00000000..e2bda802 --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,51 @@ +name: Android + +on: + pull_request: + paths: + - 'android/**' + - 'docs/hermes/**' + - '.github/workflows/android.yml' + push: + branches: [main] + paths: + - 'android/**' + - 'docs/hermes/**' + - '.github/workflows/android.yml' + +permissions: + contents: read + +concurrency: + group: android-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: android + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + cache: gradle + cache-dependency-path: | + android/**/*.gradle.kts + android/gradle/wrapper/gradle-wrapper.properties + - name: Validate Gradle wrapper + run: echo '81a82aaea5abcc8ff68b3dfcb58b3c3c429378efd98e7433460610fecd7ae45f gradle/wrapper/gradle-wrapper.jar' | sha256sum --check --strict + # The pinned GitHub runner includes these SDK packages; use no unapproved setup actions. + - name: Verify Android SDK + run: | + test -d "$ANDROID_HOME/platforms/android-36" + test -d "$ANDROID_HOME/build-tools/35.0.0" + - name: Test, lint and build + run: ./gradlew :hermes:test :app:testDebugUnitTest :app:lintDebug :app:assembleDebug + - uses: actions/upload-artifact@v4 + with: + name: bighelp-android-debug + path: android/app/build/outputs/apk/debug/*.apk diff --git a/README.md b/README.md index 8b35d365..6e01b079 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ xcodebuild test -project Bighelp.xcodeproj -scheme Bighelp \ | `BighelpMacUpdater/` | The Mac app's updates (Sparkle) | | `BighelpTests/`, `BighelpUITests/`, `BighelpVisionUITests/`, `BighelpWatchUITests/` | Tests | | `BighelpMac/`, `BighelpMacTests/` | An early desktop prototype on sample data. It is not the Mac app. | +| `android/` | Native Kotlin/Compose Android foundation; see its README for build instructions and current limits | | `services/` | Cloudflare Workers: the notification service, the template and avatar catalogs, and the provider logos | | `Scripts/` | Tests against real Hermes hosts, the Mac release, and other tools | | `Design/AvatarKit/` | Avatar artwork and the tools that export it | @@ -119,6 +120,7 @@ that work on the code. For an Android or other client port, start with the platform-neutral [Hermes transport contract](docs/NATIVE_TRANSPORT.md), including API references, recovery rules and portable conformance vectors. +The native Kotlin/Compose build-out is in [`android/`](android/README.md). ## Contributing diff --git a/android/.gitattributes b/android/.gitattributes new file mode 100644 index 00000000..43a6f0c7 --- /dev/null +++ b/android/.gitattributes @@ -0,0 +1,2 @@ +gradlew text eol=lf +gradlew.bat text eol=crlf diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 00000000..b2689040 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,7 @@ +.gradle/ +.kotlin/ +.idea/ +local.properties +captures/ +*.jks +*.keystore diff --git a/android/README.md b/android/README.md new file mode 100644 index 00000000..6798e861 --- /dev/null +++ b/android/README.md @@ -0,0 +1,58 @@ +# bighelp for Android + +Native Kotlin and Jetpack Compose build-out, tracked in [#644](https://github.com/promptclickrun/bighelp/issues/644). + +The integration authority is [the Hermes transport contract](../docs/NATIVE_TRANSPORT.md). The first milestone is described in [the design](../docs/superpowers/specs/2026-10-27-android-foundation-design.md) and [implementation plan](../docs/superpowers/plans/2026-10-27-android-foundation.md). + +## Build + +Install JDK 17 and an Android SDK with platform 36 and build tools 35.0.0. Set `ANDROID_HOME` or create a local, ignored `local.properties` with `sdk.dir=/absolute/path/to/sdk`. Open this directory in Android Studio, or run from the repository root: + +```sh +cd android +./gradlew :hermes:test :app:testDebugUnitTest :app:lintDebug :app:assembleDebug +``` + +The debug APK is `app/build/outputs/apk/debug/app-debug.apk`, with application ID `app.bighelp.android.debug`. Release signing, Play upload and the permanent release ID are not configured. + +The wrapper pins Gradle 8.13 and its distribution checksum. AGP 8.13.2 supports API 36 with JDK 17 and Gradle 8.13 ([Android compatibility table](https://developer.android.com/build/releases/agp-8-13-0-release-notes)). Kotlin and Compose dependencies are pinned; this foundation uses the stable Compose BOM 2025.10.01. Android's [Compose BOM guide](https://developer.android.com/develop/ui/compose/bom) explains dependency alignment. + +## Structure + +- `hermes/`: pure JVM endpoint and wire policy; tests read `../docs/hermes/vectors/wire.json` directly. +- `app/`: Android lifecycle, platform storage, Compose screens and explicit demo fixtures. In `app/src/main/kotlin/app/bighelp/android/`: + - State, no Android types: `AppState.kt` (routes, setup, demo data), `BighelpAppModel.kt` (every action and rule), `DemoContent.kt` (invented sample chats and the fixed example reply). + - Network: `HostDiscovery.kt` (`HostDiscovery.check(endpoint, consentGranted)`) and `HostStatus.kt` (strict `/api/status` decoding). This is the only code that opens a connection. + - Platform: `MainActivity.kt` (Activity, `ViewModel`, privacy-policy link), `PreviewPreferences.kt` (consent and appearance in app-private preferences). + - Screens and theme: `BighelpApp.kt` (routing and Back), `WelcomeScreens.kt`, `SetupScreen.kt`, `SessionsScreen.kt`, `ChatScreen.kt`, `AgentsScreen.kt`, `SettingsScreen.kt`, `PlacesMenu.kt` (the one menu), `Components.kt`, `BighelpTheme.kt`, `NoodleMark.kt`. +- `../.github/workflows/android.yml`: JVM tests, Android unit checks, lint and APK build on Android/contract changes. + +## Evidence and release gates + +The foundation is not an Android feature-parity or release-readiness claim. Record executed verification in the PR. Shared framing fixtures and scripted tests do not establish real-host compatibility, physical-device lifecycle, browser callbacks, credential rotation, or notification delivery. + +### What the first app milestone does + +- **Try the demo** opens sample chats, agents and Settings. Everything is invented and stays on the phone; every demo screen says so, and every reply is the same fixed, labeled example. It needs no agreement because nothing is sent. Controls that work: New chat, Send, search, agent choice, Light/Dark/Same as phone, drafts kept while you look elsewhere, Latest button and Android Back. +- **Connect your computer** asks for the one-time AI data agreement first (stored as `bighelp.privacy.ai-data-agreed` in app-private preferences, excluded from backup and device transfer), then checks one typed address with `GET /api/status`. A host that answers is reported as *found*, never *connected*. It collects no token or password, stores no address or sign-in, opens no gateway and sends no chat. +- Discovery sends no cookies, tokens or custom headers, follows no redirect, reads at most 16,384 decoded bytes, and keeps no response text. Each status request sends `Connection: close` to avoid reusing a closed HTTP/1.x connection; automatic retries remain disabled. HTTPS uses the platform's certificate checks, and `network_security_config.xml` trusts only the phone's built-in (system) certificate authorities. A certificate signed by a private authority that you installed on the phone is not trusted, so a host that uses one looks like "No Hermes computer answered". Use a certificate from a public authority, or plain HTTP on a private network. This preview offers no way to trust a private authority. + +### Plain HTTP on a private network + +`HermesEndpoint.parse` allows `http://` only with the explicit private-network switch **and** a host that is private by its syntax (see [the connection contract](../docs/hermes/CONNECTION.md)). Android's network security config cannot list those ranges, so `res/xml/network_security_config.xml` permits cleartext at the platform level, and the typed client is the gate: `HostDiscovery` requests only a validated `HermesEndpoint`, and nothing else in the app opens a connection (no WebView, no other HTTP client). Anyone adding network code must go through `HermesEndpoint`, or tighten that file first. + +### Tests in this milestone + +`app/src/test` holds JVM tests only: `AppModelTest` (consent gating, address refusal, one check at a time, stale and cancelled results, demo send, drafts, search, Back), `HostStatusTest` (strict status shape and bounds) and `HostDiscoveryTest` (real requests to a local scripted server: the GET and its headers, no credentials, no redirect, only HTTP 200, malformed bodies, the 16,384-byte limit with and without a declared length, a cancelled check cancelling the real call, and repeated checks of closing and keep-alive HTTP/1.x hosts). Emulator verification is recorded separately; there are no automated UI tests yet. Demo drafts and chats survive navigation and rotation, but reset after process death or leaving the demo. UI localization is not implemented yet. + +### Verified preview snapshot: 2026-10-27 + +At source commit `591c44d`, all 57 core and 41 app JVM tests pass, debug assemble succeeds, and lint reports 0 errors and 9 dependency-version notices. [Android CI passed on that commit](https://github.com/promptclickrun/bighelp/actions/runs/40552550144). The core suite includes all 55 shared wire vectors; changing the shared vector file invalidates Gradle's test result. + +Manual checks on an Android 16 / API 36 emulator exercised demo controls, drafts, keyboard/Back, history/Latest, rotation, light/dark appearance, consent and setup. After the HTTP/1.x connection fix, the initial status check and eight consecutive Check again taps each showed Found with exactly one matching local-fixture receipt and response. A separate two-second delayed check passed. The installed APK's on-device SHA-256 matched the built file. + +These are demo and synthetic HTTP/1.0 fixture results. No real Hermes host, HTTPS/HTTP/2 discovery, physical device, lower API level or TalkBack behavior was verified. The rotation checks did not reproduce the suspected jump; they do not rule out a timing race. + +Before a working live-chat milestone, implement and test authenticated ordered WebSocket readiness, prompt handlers, the exclusive-submit gate, distinct runtime/stored IDs, a durable uncertainty journal, streaming/history reconciliation and reconnect/replay. Do not expose live Send before those acceptance cases pass. Follow [PORTING.md](../docs/hermes/PORTING.md) in order. + +Before Play release, settle the permanent application ID and signing ownership, complete personal developer registration and verification, verify on a physical Android device, add the Android delivery adapter if push is offered, and complete Google's current test/release requirements. No production service is deployed by the Android foundation. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 00000000..29b88468 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,59 @@ +plugins { + id("com.android.application") + kotlin("android") + id("org.jetbrains.kotlin.plugin.compose") +} + +android { + namespace = "app.bighelp.android" + compileSdk = 36 + + defaultConfig { + applicationId = "app.bighelp.android" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "0.1.0" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + debug { + applicationIdSuffix = ".debug" + versionNameSuffix = "-dev" + } + release { + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) + } + } + buildFeatures { compose = true } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" } +} + +kotlin { + compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } +} + +dependencies { + implementation(project(":hermes")) + implementation(platform("androidx.compose:compose-bom:2025.10.01")) + implementation("androidx.activity:activity-compose:1.11.0") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.4") + implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.4") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.material:material-icons-extended") + implementation("androidx.compose.ui:ui-tooling-preview") + debugImplementation("androidx.compose.ui:ui-tooling") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + testImplementation("junit:junit:4.13.2") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2") + testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test.ext:junit:1.3.0") +} diff --git a/android/app/src/androidTest/kotlin/app/bighelp/android/live/AndroidCredentialAdapterTest.kt b/android/app/src/androidTest/kotlin/app/bighelp/android/live/AndroidCredentialAdapterTest.kt new file mode 100644 index 00000000..700fc75d --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/bighelp/android/live/AndroidCredentialAdapterTest.kt @@ -0,0 +1,45 @@ +package app.bighelp.android.live + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.StaleCredentialException +import app.bighelp.hermes.StoredAuth +import java.util.UUID +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class AndroidCredentialAdapterTest { + @Test fun credentialCodecRotationAndComputerIsolationUseTheRealAndroidStore() = runBlocking { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val firstID = UUID.randomUUID() + val secondID = UUID.randomUUID() + val endpoint = HermesEndpoint.parse("https://storage-probe.example.test/hermes") + val first = SavedConnection(endpoint, StoredAuth.Bearer("synthetic-access-one", "synthetic-refresh-one", 1_950_000_000), "basic", "fixture") + val next = SavedConnection(endpoint, StoredAuth.Bearer("synthetic-access-two", "synthetic-refresh-two", 1_950_000_001), "basic", "fixture") + val other = SavedConnection(endpoint, StoredAuth.Bearer("synthetic-independent", null, null), "basic", "fixture") + fun firstVault() = AndroidCredentialStore.create(context, firstID) + fun secondVault() = AndroidCredentialStore.create(context, secondID) + try { + firstVault().replace(null, first) + secondVault().replace(null, other) + assertEquals(first, firstVault().load(first.authority)) + assertEquals(other, secondVault().load(other.authority)) + firstVault().replace(first, next) + try { + firstVault().delete(first) + fail("A stale sign-out must not delete the new token") + } catch (_: StaleCredentialException) { + } + assertEquals(next, firstVault().load(next.authority)) + assertEquals(other, secondVault().load(other.authority)) + } finally { + firstVault().load(first.authority)?.let { firstVault().delete(it) } + secondVault().load(other.authority)?.let { secondVault().delete(it) } + } + } +} diff --git a/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidChatStoreDeviceTest.kt b/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidChatStoreDeviceTest.kt new file mode 100644 index 00000000..3db8ac6a --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidChatStoreDeviceTest.kt @@ -0,0 +1,66 @@ +package app.bighelp.android.storage + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import app.bighelp.hermes.chat.ChatStoreException +import app.bighelp.hermes.chat.ConversationScope +import app.bighelp.hermes.chat.DraftRecord +import app.bighelp.hermes.chat.HostScope +import app.bighelp.hermes.chat.RecordKey +import app.bighelp.hermes.chat.RecordKind +import app.bighelp.hermes.chat.StoreOp +import java.io.File +import java.util.UUID +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * The chat store on the phone's own filesystem: flushing, the atomic rename that compaction relies on, the + * directory sync and a restart (a second store over the same folder). Synthetic data, in a folder of its own. + */ +@RunWith(AndroidJUnit4::class) +class AndroidChatStoreDeviceTest { + private val context = InstrumentationRegistry.getInstrumentation().targetContext + private val directory = File(context.noBackupFilesDir, "chat-store-device-test-${UUID.randomUUID()}") + private val host = HostScope(UUID.randomUUID().toString(), "https://device-probe.example.test", "dashboard-session") + private val scope = ConversationScope(host, "default", "anchor-1") + + @After fun clean() { directory.deleteRecursively() } + + private fun draft(text: String) = StoreOp.Put(RecordKey.draft(scope), DraftRecord(scope, text, updatedAtMillis = 1).encode()) + + @Test fun aCommitAndACacheSurviveANewStoreOverTheSameFolderOnTheRealFilesystem() = runBlocking { + val first = AndroidChatStore(directory, Dispatchers.IO) + first.commit(listOf(draft("typed on the device"))) + first.putCache(RecordKey.history(scope), ByteArray(2_000) { 5 }) + first.close() + + val second = AndroidChatStore(directory, Dispatchers.IO) + assertEquals("typed on the device", DraftRecord.decode(scope, second.read(RecordKey.draft(scope))!!).text) + assertEquals(2_000, second.read(RecordKey.history(scope))!!.size) + assertEquals(listOf("anchor-1"), second.keys(host, RecordKind.Draft).map { it.anchor }) + } + + @Test fun compactionRenamesTheNewLogOverTheOldOneAndTheRecordsAreStillThere() = runBlocking { + val store = AndroidChatStore(directory, Dispatchers.IO, SystemChatStoreFiles, ChatStoreTuning(compactionMinimumGarbage = 20_000)) + repeat(120) { store.commit(listOf(draft("edit $it " + "x".repeat(500)))) } + assertTrue("The log stayed small: ${File(directory, AndroidChatStore.LOG_NAME).length()}", File(directory, AndroidChatStore.LOG_NAME).length() < 120_000) + store.close() + val reopened = AndroidChatStore(directory, Dispatchers.IO) + assertEquals("edit 119 " + "x".repeat(500), DraftRecord.decode(scope, reopened.read(RecordKey.draft(scope))!!).text) + assertNull(File(directory, AndroidChatStore.COMPACT_NAME).takeIf { it.exists() }) + } + + @Test fun anOversizeDraftIsRefusedOnTheDeviceToo() = runBlocking { + val store = AndroidChatStore(directory, Dispatchers.IO) + val failure = runCatching { store.commit(listOf(StoreOp.Put(RecordKey.draft(scope), ByteArray(RecordKind.Draft.maximumBytes + 1)))) }.exceptionOrNull() + assertEquals(ChatStoreException.Kind.TooLarge, (failure as ChatStoreException).kind) + assertTrue(store.keys(host, RecordKind.Draft).isEmpty()) + } +} diff --git a/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt b/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt new file mode 100644 index 00000000..f5a128b8 --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt @@ -0,0 +1,93 @@ +package app.bighelp.android.storage + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import java.io.File +import java.util.UUID +import java.security.KeyStore +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +/** Exercises the real Android Keystore and app filesystem rather than the JVM crypto provider. */ +@RunWith(AndroidJUnit4::class) +class AndroidCredentialStorageTest { + @Test fun deviceKeyIsNonExportable() { + val key = AndroidCredentialKey.getOrCreate() + assertEquals("AES", key.algorithm) + assertNull(key.encoded) + } + + @Test fun protectedRecordReopensAndAStaleAuthenticatorCannotReplaceOrDeleteIt() = withStore { root -> + val binding = "storage-probe:https://example.test/hermes|basic|synthetic-person" + val original = "synthetic-refresh-one".toByteArray() + val replacement = "synthetic-refresh-two".toByteArray() + fun vault() = ProtectedRecordStore(root, RecordCipher(AndroidCredentialKey)) + assertTrue(vault().compareAndSet(binding, null, original)) + assertArrayEquals(original, vault().read(binding)) + assertTrue(vault().compareAndSet(binding, original, replacement)) + assertFalse(vault().compareAndSet(binding, original, "stale".toByteArray())) + assertFalse(vault().compareAndSet(binding, original, null)) + assertArrayEquals(replacement, vault().read(binding)) + assertTrue(vault().compareAndSet(binding, replacement, null)) + assertNull(vault().read(binding)) + } + + @Test fun aModifiedCiphertextIsRefusedOnAndroid() = withStore { root -> + val vault = ProtectedRecordStore(root, RecordCipher(AndroidCredentialKey)) + val binding = "storage-probe:synthetic-authority" + assertTrue(vault.compareAndSet(binding, null, "synthetic-token".toByteArray())) + val file = root.listFiles()!!.single { it.extension == "sealed" } + val bytes = file.readBytes() + assertFalse(bytes.toString(Charsets.ISO_8859_1).contains("synthetic-token")) + file.writeBytes(bytes.also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() }) + try { + vault.read(binding) + fail("Modified ciphertext must not be adopted") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.CorruptRecord, failure.problem) + } + } + + @Test fun maximumRecordRoundTripsWithTheAndroidKey() = withStore { root -> + val vault = ProtectedRecordStore(root, RecordCipher(AndroidCredentialKey)) + val value = ByteArray(65_536) { (it % 127).toByte() } + assertTrue(vault.compareAndSet("storage-probe:maximum", null, value)) + assertArrayEquals(value, vault.read("storage-probe:maximum")) + } + + @Test fun missingKeyIsNotRecreatedByReadingAndAllowsExplicitLocalRecovery() = withStore { root -> + val alias = "bighelp.storage-probe.${UUID.randomUUID()}" + val keys = AndroidKeyStoreRecordKeys(alias) + val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + val vault = ProtectedRecordStore(root, RecordCipher(keys)) + val binding = "storage-probe:missing-key" + try { + assertTrue(vault.compareAndSet(binding, null, "synthetic-first".toByteArray())) + keyStore.deleteEntry(alias) + try { + vault.read(binding) + fail("Reading must not create a replacement key") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.KeyMissing, failure.problem) + } + assertFalse(keyStore.containsAlias(alias)) + assertTrue(vault.discardUnreadable(binding)) + val next = "synthetic-new-sign-in".toByteArray() + assertTrue(vault.compareAndSet(binding, null, next)) + assertArrayEquals(next, vault.read(binding)) + } finally { + keyStore.deleteEntry(alias) + } + } + + private fun withStore(block: (File) -> Unit) { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val root = File(context.noBackupFilesDir, "storage-probe-${UUID.randomUUID()}") + try { + block(root) + } finally { + root.deleteRecursively() + } + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..5646f123 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/app/bighelp/android/AccessInput.kt b/android/app/src/main/kotlin/app/bighelp/android/AccessInput.kt new file mode 100644 index 00000000..27d033da --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/AccessInput.kt @@ -0,0 +1,60 @@ +package app.bighelp.android + +import app.bighelp.android.live.AccessSetup +import app.bighelp.hermes.AccessCredential +import app.bighelp.hermes.CustomHeader +import app.bighelp.hermes.CustomHeaderException +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException + +enum class AccessKind { None, Cloudflare, ProxyLogin } + +enum class AccessProblem { Credential, HeaderName, HeaderReserved, HeaderValue, HeaderDuplicate, TooManyHeaders } + +/** + * What the person typed under "Extra access details": the gate in front of their computer's address. It stays + * plain strings until [build] checks them, so the form can keep half-typed text. + */ +data class AccessInput( + val kind: AccessKind = AccessKind.None, + val id: String = "", + val secret: String = "", + val headers: List> = emptyList(), +) { + internal fun build(): AccessBuild = try { + val credential = when (kind) { + AccessKind.None -> null + AccessKind.Cloudflare -> AccessCredential.cloudflareAccess(id, secret) + AccessKind.ProxyLogin -> AccessCredential.proxyBasic(id, secret) + } + AccessBuild.Ok(AccessSetup(credential, CustomHeader.list(headers))) + } catch (_: HermesException) { + AccessBuild.Invalid(AccessProblem.Credential) + } catch (failure: CustomHeaderException) { + AccessBuild.Invalid( + when (failure.problem) { + CustomHeaderException.Problem.InvalidName -> AccessProblem.HeaderName + CustomHeaderException.Problem.Reserved -> AccessProblem.HeaderReserved + CustomHeaderException.Problem.InvalidValue -> AccessProblem.HeaderValue + CustomHeaderException.Problem.Duplicate -> AccessProblem.HeaderDuplicate + CustomHeaderException.Problem.TooMany -> AccessProblem.TooManyHeaders + }, + ) + } +} + +internal sealed interface AccessBuild { + data class Ok(val setup: AccessSetup) : AccessBuild + data class Invalid(val problem: AccessProblem) : AccessBuild +} + +internal fun defaultComputerName(endpoint: HermesEndpoint): String = endpoint.host + +internal fun describe(problem: AccessProblem): String = when (problem) { + AccessProblem.Credential -> "Those access details can't be used. Check for spaces or a colon in the username." + AccessProblem.HeaderName -> "A header name can only use letters, numbers and dashes." + AccessProblem.HeaderReserved -> "That header name is used by the app itself. Pick another." + AccessProblem.HeaderValue -> "Every header needs a value." + AccessProblem.HeaderDuplicate -> "Each header name can be used once." + AccessProblem.TooManyHeaders -> "You can add up to 16 headers." +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/AgentsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/AgentsScreen.kt new file mode 100644 index 00000000..816ff3b2 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/AgentsScreen.kt @@ -0,0 +1,75 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.selection.selectable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +/** Pick which sample agent new chats start with. */ +@Composable +fun AgentsScreen( + demo: DemoState, + onSelect: (String) -> Unit, + onNewChat: () -> Unit, + onOpenPlace: (Route) -> Unit, +) { + val selected = demo.agent(demo.selectedAgentId) + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.agents")) { + ScreenHeader("Agents", leading = { PlacesMenu(current = Route.Agents, onOpen = onOpenPlace) }) + DemoBanner(Modifier.padding(horizontal = 16.dp)) + Text( + "New chats start with the agent you pick.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp), + ) + LazyColumn(Modifier.weight(1f).testTag("agents.list")) { + items(demo.agents, key = { it.id }) { agent -> + val isSelected = agent.id == demo.selectedAgentId + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 72.dp) + .selectable(selected = isSelected, role = Role.RadioButton, onClick = { onSelect(agent.id) }) + .padding(horizontal = 16.dp, vertical = 10.dp) + .testTag("agents.row.${agent.id}"), + verticalAlignment = Alignment.CenterVertically, + ) { + AgentAvatar(agent) + Spacer(Modifier.width(14.dp)) + Column(Modifier.weight(1f)) { + Text(agent.name, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(agent.role, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (isSelected) Icon(Icons.Default.Check, contentDescription = "Selected") + } + } + } + InkButton( + "New chat with ${selected.name}", + onNewChat, + tag = "agents.new-chat", + modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), + ) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/AppState.kt b/android/app/src/main/kotlin/app/bighelp/android/AppState.kt new file mode 100644 index 00000000..566e1d87 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/AppState.kt @@ -0,0 +1,101 @@ +package app.bighelp.android + +import app.bighelp.hermes.HermesEndpointException + +/** Light, Dark, or follow the phone. Saved on the device. */ +enum class Appearance { Automatic, Light, Dark } + +/** Where the person is. The back stack is plain data so navigation can be tested without a device. */ +sealed interface Route { + data object Welcome : Route + data object Consent : Route + data object Setup : Route + data object Sessions : Route + data object Agents : Route + data object Settings : Route + + /** Choosing how to sign in to the computer that was just checked. */ + data object SignIn : Route + data object Archived : Route + data class Chat(val sessionId: String) : Route + + /** A real chat; [refId] is `ConversationRef.id`, never an ID from the host's own wire. */ + data class LiveChat(val refId: String) : Route +} + +/** What the setup screen shows for the host check. Found is never a connection. */ +sealed interface DiscoveryState { + data object Idle : DiscoveryState + data object Checking : DiscoveryState + + /** The typed address was refused before any request; only the category is kept, never the input. */ + data class AddressProblem(val reason: HermesEndpointException.Reason) : DiscoveryState + + data class Unavailable(val address: String) : DiscoveryState + + /** The live check was refused, with the reason in plain words (a gate, a web page, a certificate...). */ + data class Refused(val message: String) : DiscoveryState + data class Found(val address: String, val authRequired: Boolean, val browserSignIn: Boolean) : DiscoveryState +} + +data class SetupState( + val address: String = "", + val allowPrivateHttp: Boolean = false, + val discovery: DiscoveryState = DiscoveryState.Idle, + /** The gate in front of the address, typed under "Extra access details". Cleared once a computer is added. */ + val access: AccessInput = AccessInput(), +) + +data class DemoAgent(val id: String, val name: String, val role: String, val colorArgb: Long) + +/** [isExample] marks a reply the demo wrote itself; no agent produced it. */ +data class DemoMessage(val id: String, val fromUser: Boolean, val text: String, val isExample: Boolean = false) + +data class DemoSession(val id: String, val agentId: String, val title: String, val messages: List) + +/** Everything the sample data owns. It lives only in memory and ends with the demo. */ +data class DemoState( + val agents: List, + val selectedAgentId: String, + /** Most recent activity first. */ + val sessions: List, + val search: String = "", + /** Unsent text by chat, kept while the person looks elsewhere. */ + val drafts: Map = emptyMap(), + val chatsStarted: Int = 0, +) { + fun agent(id: String): DemoAgent = agents.firstOrNull { it.id == id } ?: agents.first() + + fun session(id: String): DemoSession? = sessions.firstOrNull { it.id == id } + + /** Chats matching the search box in a title, an agent's name or any message. */ + val visibleSessions: List + get() { + val query = search.trim() + if (query.isEmpty()) return sessions + return sessions.filter { session -> + session.title.contains(query, ignoreCase = true) || + agent(session.agentId).name.contains(query, ignoreCase = true) || + session.messages.any { it.text.contains(query, ignoreCase = true) } + } + } +} + +data class AppState( + val backStack: List = listOf(Route.Welcome), + val consentGranted: Boolean = false, + val appearance: Appearance = Appearance.Automatic, + val setup: SetupState = SetupState(), + /** Non-null exactly while the demo is open. */ + val demo: DemoState? = null, + /** True while a real computer is open: the same places show its real agents and chats. */ + val live: Boolean = false, + /** The name offered for the computer being signed in to: its address, or the saved computer's own name. */ + val signInName: String = "", + /** What the person calls themselves, at most 40 characters. Saved on this phone. */ + val userName: String = "", + /** Shows the host-administration rows. Everyday controls never depend on it. */ + val nerdMode: Boolean = false, +) { + val route: Route get() = backStack.last() +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt b/android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt new file mode 100644 index 00000000..9f64ef42 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt @@ -0,0 +1,159 @@ +package app.bighelp.android + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.bighelp.android.live.LiveModel + +/** + * The whole app: observes [BighelpAppModel] and shows its current route. Screens only call the model's + * actions; they hold no navigation or demo state of their own except scroll position and the message box. + * The same places show the demo's sample data or, when a real computer is open, its own agents and chats. + */ +@OptIn(ExperimentalComposeUiApi::class) +@Composable +fun BighelpApp( + model: BighelpAppModel, + versionName: String, + onOpenPrivacyPolicy: () -> Unit, +) { + val state by model.state.collectAsStateWithLifecycle() + val live = model.live + val dark = when (state.appearance) { + Appearance.Automatic -> isSystemInDarkTheme() + Appearance.Light -> false + Appearance.Dark -> true + } + // The connection is only kept up, and retried, while the app is in front. + LifecycleEventEffect(Lifecycle.Event.ON_START) { live?.onForeground() } + LifecycleEventEffect(Lifecycle.Event.ON_STOP) { live?.onBackground() } + BighelpTheme(darkTheme = dark) { + // Test tags double as resource IDs so UI Automator and adb-driven checks can find real controls. + Surface( + color = MaterialTheme.colorScheme.background, + modifier = Modifier.fillMaxSize().semantics { testTagsAsResourceId = true }, + ) { + BackHandler(enabled = state.backStack.size > 1) { model.back() } + Box(Modifier.fillMaxSize()) { + Screens(model, live, state, versionName, onOpenPrivacyPolicy) + if (live != null) NoticeHost(live, Modifier.align(Alignment.BottomCenter).safeDrawingPadding().padding(bottom = 72.dp)) + } + } + } +} + +@Composable +private fun Screens(model: BighelpAppModel, live: LiveModel<*>?, state: AppState, versionName: String, onOpenPrivacyPolicy: () -> Unit) { + val demo = state.demo + when (val route = state.route) { + Route.Welcome -> WelcomeScreen( + onTryDemo = model::tryDemo, + onConnect = model::connectComputer, + extra = { if (live != null) WelcomeComputers(model, live) }, + ) + Route.Consent -> ConsentScreen( + onAgree = model::agreeToAiData, + onNotNow = { model.back() }, + onPrivacyPolicy = onOpenPrivacyPolicy, + ) + Route.Setup -> SetupScreen( + setup = state.setup, + onBack = { model.back() }, + onAddress = model::setAddress, + onAllowPrivateHttp = model::setAllowPrivateHttp, + onCheck = model::checkHost, + onCancel = model::cancelCheck, + onTryDemo = model::tryDemo, + live = live != null, + onAccess = model::setAccess, + onContinue = model::continueToSignIn, + ) + Route.SignIn -> if (live != null) { + val connection by live.connections.state.collectAsStateWithLifecycle() + SignInScreen( + connection = connection, + defaultName = state.signInName.ifBlank { "My computer" }, + onSignIn = model::signIn, + onBack = { model.back() }, + ) + } + // The places exist only while the demo or a real computer is open. + Route.Sessions -> when { + demo != null -> SessionsScreen(demo, model::setSearch, model::openChat, model::startNewChat, model::openPlace) + state.live && live != null -> LiveSessionsScreen( + live, + onOpenChat = model::openLiveChat, + onNewChat = { model.startLiveChat() }, + onOpenArchived = { model.openArchived() }, + onOpenPlace = model::openPlace, + onSignInAgain = model::signInAgainSelected, + ) + } + Route.Agents -> when { + demo != null -> AgentsScreen(demo, model::selectAgent, model::startNewChat, model::openPlace) + state.live && live != null -> LiveAgentsScreen( + live, + onNewChat = { model.startLiveChat(it) }, + onBotChat = model::openBotChat, + onOpenPlace = model::openPlace, + onSignInAgain = model::signInAgainSelected, + ) + } + Route.Archived -> if (live != null) ArchivedChatsScreen(live, onBack = { model.back() }) + Route.Settings -> SettingsScreen( + appearance = state.appearance, + consentGranted = state.consentGranted, + versionName = versionName, + onAppearance = model::setAppearance, + onPrivacyPolicy = onOpenPrivacyPolicy, + onLeaveDemo = model::leaveDemo, + onOpenPlace = model::openPlace, + showDemo = demo != null, + liveSections = if (state.live && live != null) ({ LiveSettingsSections(model, live, state) }) else null, + ) + is Route.Chat -> demo?.let { + ChatScreen( + demo = it, + sessionId = route.sessionId, + onBack = { model.back() }, + onDraft = { text -> model.setDraft(route.sessionId, text) }, + onSend = { model.send(route.sessionId) }, + ) + } + is Route.LiveChat -> if (live != null) LiveChatScreen( + live, + refId = route.refId, + onBack = { model.back() }, + onOpenChat = model::openLiveChat, + onSignInAgain = model::signInAgainSelected, + ) + } +} + +@Composable +private fun WelcomeComputers(model: BighelpAppModel, live: LiveModel<*>) { + val connection by live.connections.state.collectAsStateWithLifecycle() + if (connection.computers.isEmpty()) return + androidx.compose.foundation.layout.Column { + SectionLabel("Your computers") + androidx.compose.foundation.layout.Spacer(Modifier.padding(top = 4.dp)) + SavedComputersCard(live, onSignInAgain = model::signInAgain) + androidx.compose.foundation.layout.Spacer(Modifier.padding(top = 20.dp)) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt new file mode 100644 index 00000000..74f257c9 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt @@ -0,0 +1,425 @@ +package app.bighelp.android + +import app.bighelp.android.live.ComputerPhase +import app.bighelp.android.live.LiveModel +import app.bighelp.android.live.SetupOutcome +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesEndpointException +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.chat.ConversationRef +import java.util.UUID +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * Owns the app's state. Screens read [state] and call the actions below; nothing else changes it, and it + * knows nothing about Android, so every rule here runs in plain JVM tests. + * + * Call it from one thread (the main thread in the app). Two rules matter most: + * - **Consent first.** No host request is made, and none is even built, until [agreeToAiData]. + * - **One owner for a host check.** Any change to the typed address, the private-HTTP switch or the screen + * cancels the check and bumps [checkGeneration]; an answer that arrives for an older generation is + * dropped even if the checker ignored cancellation. + * + * With a [live] model the same places show a real computer: its connection decides when the app is "live" + * (a computer is open) and when it leaves (the computer is gone), and the host check is the real, gate-aware + * discovery rather than the public status probe. Without one (tests, the demo alone) nothing live exists. + */ +class BighelpAppModel internal constructor( + private val preferences: PreviewPreferences, + private val hostChecker: HostChecker, + private val scope: CoroutineScope, + internal val live: LiveModel<*>?, +) { + constructor(preferences: PreviewPreferences, hostChecker: HostChecker, scope: CoroutineScope) : + this(preferences, hostChecker, scope, null) + + private val mutableState = MutableStateFlow( + AppState( + consentGranted = preferences.aiDataAgreed, appearance = preferences.appearance, + userName = preferences.userName, nerdMode = preferences.nerdMode, + ), + ) + val state: StateFlow = mutableState.asStateFlow() + + private var checkJob: Job? = null + private var checkGeneration = 0 + private var lastActiveComputer: UUID? = null + + init { + live?.let { model -> + scope.launch { + combine(model.connections.state, model.connections.active) { connection, active -> connection.phase to active?.computer?.id } + .collect { (phase, activeId) -> onConnection(phase, activeId) } + } + } + } + + /** A real computer opening shows its places; it going away (and not being replaced) leaves them. */ + private fun onConnection(phase: ComputerPhase, activeId: UUID?) { + mutableState.update { current -> + when { + activeId != null && (!current.live || activeId != lastActiveComputer || current.route in COMPUTER_SETUP_ROUTES) -> { + lastActiveComputer = activeId + current.copy(live = true, demo = null, backStack = listOf(Route.Sessions), setup = SetupState()) + } + // Not while the person is adding a computer: a refused check there leaves them on that screen. + activeId == null && current.live && phase in COMPUTER_GONE && current.route !in ON_SETUP_ROUTES -> { + lastActiveComputer = null + current.copy(live = false, backStack = listOf(Route.Welcome)) + } + else -> current + } + } + } + + // -- navigation ------------------------------------------------------------------------- + + /** Pops one screen. Returns false at the root, where the system decides (leaving the app). */ + fun back(): Boolean { + val stack = mutableState.value.backStack + if (stack.size <= 1) return false + when (val top = stack.last()) { + Route.Setup -> { + dropCheck() + // Typed gate secrets do not linger once the screen they were typed on is gone. + mutableState.update { it.copy(setup = it.setup.copy(access = AccessInput())) } + } + Route.SignIn -> { + live?.cancelSetup() + setDiscovery(DiscoveryState.Idle) + } + is Route.LiveChat -> leaveLiveChat(top) + else -> Unit + } + mutableState.update { it.copy(backStack = it.backStack.dropLast(1)) } + return true + } + + /** One of the menu's places: Chats, Agents or Settings. Back from any of them returns to Chats. */ + fun openPlace(place: Route) { + val current = mutableState.value + if (current.demo == null && !current.live) return + if (place != Route.Sessions && place != Route.Agents && place != Route.Settings) return + (current.route as? Route.LiveChat)?.let(::leaveLiveChat) + mutableState.update { + it.copy(backStack = if (place == Route.Sessions) listOf(Route.Sessions) else listOf(Route.Sessions, place)) + } + } + + fun openChat(sessionId: String) { + val demo = mutableState.value.demo ?: return + if (demo.session(sessionId) == null || mutableState.value.route == Route.Chat(sessionId)) return + mutableState.update { it.copy(backStack = listOf(Route.Sessions, Route.Chat(sessionId))) } + } + + // -- connecting to a computer ----------------------------------------------------------- + + fun connectComputer() { + dropCheck() + val next = if (mutableState.value.consentGranted) Route.Setup else Route.Consent + // From Settings of an open computer, adding another goes on top of it; from Welcome it starts the list. + mutableState.update { + if (it.live) it.copy(backStack = it.backStack + next) else it.copy(backStack = listOf(Route.Welcome, next), demo = null) + } + } + + /** The one-time agreement; never asked again once given. */ + fun agreeToAiData() { + preferences.aiDataAgreed = true + mutableState.update { current -> + val stack = if (current.route == Route.Consent) current.backStack.dropLast(1) + Route.Setup else current.backStack + current.copy(consentGranted = true, backStack = stack) + } + } + + fun setAddress(address: String) { + if (address == mutableState.value.setup.address) return + dropCheck() + mutableState.update { it.copy(setup = it.setup.copy(address = address)) } + } + + fun setAccess(access: AccessInput) { + if (access == mutableState.value.setup.access) return + dropCheck() + mutableState.update { it.copy(setup = it.setup.copy(access = access)) } + } + + fun setAllowPrivateHttp(allowed: Boolean) { + if (allowed == mutableState.value.setup.allowPrivateHttp) return + dropCheck() + mutableState.update { it.copy(setup = it.setup.copy(allowPrivateHttp = allowed)) } + } + + /** Asks the typed address whether a Hermes computer is there. Ignored while a check is running. */ + fun checkHost() { + val current = mutableState.value + if (current.setup.discovery == DiscoveryState.Checking) return + if (!current.consentGranted) { + // Nothing is built or sent without the agreement; show it instead. + if (current.route != Route.Consent) { + mutableState.update { it.copy(backStack = it.backStack.dropLast(1) + Route.Consent) } + } + return + } + val endpoint = try { + HermesEndpoint.parse(current.setup.address.trim(), current.setup.allowPrivateHttp) + } catch (problem: HermesEndpointException) { + setDiscovery(DiscoveryState.AddressProblem(problem.reason)) + return + } + + if (live != null) { + startLiveCheck(live, endpoint) + return + } + val generation = ++checkGeneration + setDiscovery(DiscoveryState.Checking) + checkJob = scope.launch { + val result = hostChecker.check(endpoint, consentGranted = true) + if (generation != checkGeneration) return@launch + setDiscovery( + when (result) { + DiscoveryResult.ConsentRequired -> DiscoveryState.Idle + DiscoveryResult.Unavailable -> DiscoveryState.Unavailable(endpoint.canonical) + is DiscoveryResult.Available -> + DiscoveryState.Found(endpoint.canonical, result.authRequired, result.browserSignIn) + }, + ) + } + } + + fun cancelCheck() = dropCheck() + + /** The real check: discovery through the authenticator, with the person's access details, owned by the connection. */ + private fun startLiveCheck(live: LiveModel<*>, endpoint: HermesEndpoint) { + val access = when (val built = mutableState.value.setup.access.build()) { + is AccessBuild.Invalid -> { + setDiscovery(DiscoveryState.Refused(describe(built.problem))) + return + } + is AccessBuild.Ok -> built.setup + } + val generation = ++checkGeneration + setDiscovery(DiscoveryState.Checking) + checkJob = scope.launch { + val outcome = live.beginSetup(endpoint, access) + if (generation != checkGeneration) return@launch + if (outcome is SetupOutcome.Ready) mutableState.update { it.copy(signInName = defaultComputerName(endpoint)) } + setDiscovery( + when (outcome) { + is SetupOutcome.Ready -> DiscoveryState.Found(endpoint.canonical, outcome.status.authRequired, outcome.status.supportsNativePkce) + is SetupOutcome.Failed -> DiscoveryState.Refused(outcome.message) + SetupOutcome.Cancelled -> DiscoveryState.Idle + }, + ) + } + } + + /** After a found computer: choose how to sign in. The check's own session carries on to the sign-in. */ + fun continueToSignIn() { + val current = mutableState.value + if (live == null || current.setup.discovery !is DiscoveryState.Found || current.route == Route.SignIn) return + mutableState.update { it.copy(backStack = it.backStack + Route.SignIn) } + } + + /** [name] is what the person calls this computer; the coordinator checks it. Success is seen as [AppState.live]. */ + fun signIn(name: String, input: SignInInput) { + live?.signIn(name, input) + } + + /** The open computer's sign-in ended (the host refused it): find out how it signs in, then ask. */ + fun signInAgainSelected() { + live?.connections?.state?.value?.selectedID?.let(::signInAgain) + } + + fun openArchived() { + if (!mutableState.value.live || mutableState.value.route == Route.Archived) return + mutableState.update { it.copy(backStack = it.backStack + Route.Archived) } + } + + /** A saved computer whose sign-in ended: find out how it signs in, then ask. */ + fun signInAgain(id: UUID) { + val model = live ?: return + scope.launch { + model.reauthenticate(id).join() + if (model.connections.state.value.phase == ComputerPhase.SignIn) { + val name = model.connections.state.value.computers.firstOrNull { it.id == id }?.name.orEmpty() + mutableState.update { current -> + val next = current.copy(signInName = name) + if (current.route == Route.SignIn) next else next.copy(backStack = current.backStack + Route.SignIn) + } + } else { + model.notify(model.connections.state.value.authFailure?.let(app.bighelp.android.live.LiveText::describe) ?: "Couldn't reach this computer.") + } + } + } + + // -- live chats ------------------------------------------------------------------------------ + + /** Opens a real chat. A null ref (an ID this app did not make) opens nothing. */ + fun openLiveChat(ref: ConversationRef?) { + val model = live ?: return + if (ref == null || !mutableState.value.live || mutableState.value.route == Route.LiveChat(ref.id)) return + mutableState.update { it.copy(backStack = listOf(Route.Sessions, Route.LiveChat(ref.id))) } + scope.launch { model.openChat(ref) } + } + + /** A new chat with the agent new chats start with; opens it once the host made it. */ + fun startLiveChat(profile: String? = null) { + val model = live ?: return + scope.launch { + val agent = profile ?: model.selectedAgentId.value ?: return@launch model.notify("Pick an agent first.") + openLiveChat(model.newChat(agent)) + } + } + + fun openBotChat(profile: String) { + val model = live ?: return + scope.launch { openLiveChat(model.openBotChat(profile)) } + } + + private fun leaveLiveChat(route: Route.LiveChat) { + val model = live ?: return + val ref = ConversationRef.parse(route.refId) ?: return + scope.launch { model.leaveChat(ref) } + } + + private fun setDiscovery(discovery: DiscoveryState) = + mutableState.update { it.copy(setup = it.setup.copy(discovery = discovery)) } + + /** Cancels any check and forgets its result; a late answer can no longer be applied. */ + private fun dropCheck() { + checkGeneration++ + checkJob?.cancel() + checkJob = null + if (mutableState.value.setup.discovery != DiscoveryState.Idle) { + // A live check owns a session of its own; ending the check ends that session too. + if (live != null) live.cancelSetup() + setDiscovery(DiscoveryState.Idle) + } + } + + // -- demo --------------------------------------------------------------------------------- + + /** Opens the sample data. It needs no agreement because nothing leaves the phone. */ + fun tryDemo() { + dropCheck() + mutableState.update { it.copy(backStack = listOf(Route.Sessions), demo = DemoContent.initial()) } + } + + fun leaveDemo() { + mutableState.update { it.copy(backStack = listOf(Route.Welcome), demo = null) } + } + + fun selectAgent(agentId: String) = updateDemo { demo -> + if (demo.agents.any { it.id == agentId }) demo.copy(selectedAgentId = agentId) else demo + } + + fun setSearch(query: String) = updateDemo { it.copy(search = query) } + + /** Opens a chat with the selected agent, reusing an empty one so repeated taps never pile up. */ + fun startNewChat() { + val demo = mutableState.value.demo ?: return + val existing = demo.sessions.firstOrNull { it.agentId == demo.selectedAgentId && it.messages.isEmpty() } + val created = existing ?: DemoSession( + id = "chat-${demo.chatsStarted + 1}", + agentId = demo.selectedAgentId, + title = NEW_CHAT_TITLE, + messages = emptyList(), + ) + mutableState.update { current -> + val currentDemo = current.demo ?: return@update current + current.copy( + backStack = listOf(Route.Sessions, Route.Chat(created.id)), + demo = if (existing != null) currentDemo else currentDemo.copy( + sessions = listOf(created) + currentDemo.sessions, + chatsStarted = currentDemo.chatsStarted + 1, + ), + ) + } + } + + fun setDraft(sessionId: String, text: String) = updateDemo { demo -> + if (demo.session(sessionId) == null) demo + else demo.copy(drafts = if (text.isEmpty()) demo.drafts - sessionId else demo.drafts + (sessionId to text)) + } + + /** + * Sends the chat's draft: your message, then the fixed example reply, at once. Nothing is sent + * anywhere. Returns false for a blank draft or an unknown chat. + */ + fun send(sessionId: String): Boolean { + var sent = false + updateDemo { demo -> + val session = demo.session(sessionId) ?: return@updateDemo demo + val text = demo.drafts[sessionId].orEmpty().trim() + if (text.isEmpty()) return@updateDemo demo + sent = true + val index = session.messages.size + val updated = session.copy( + title = if (session.messages.isEmpty()) titleFrom(text) else session.title, + messages = session.messages + listOf( + DemoMessage("$sessionId/$index", fromUser = true, text = text), + DemoMessage( + "$sessionId/${index + 1}", fromUser = false, + text = DemoContent.exampleReply(demo.agent(session.agentId)), isExample = true, + ), + ), + ) + demo.copy( + sessions = listOf(updated) + demo.sessions.filterNot { it.id == sessionId }, + drafts = demo.drafts - sessionId, + ) + } + return sent + } + + private fun updateDemo(change: (DemoState) -> DemoState) { + mutableState.update { current -> current.demo?.let { current.copy(demo = change(it)) } ?: current } + } + + private fun titleFrom(message: String): String { + val line = message.lineSequence().first().trim() + if (line.length <= MAXIMUM_TITLE) return line + // Step back one unit when the cut would leave half of an emoji (a surrogate pair) behind. + val cut = if (line[MAXIMUM_TITLE - 1].isHighSurrogate()) MAXIMUM_TITLE - 1 else MAXIMUM_TITLE + return line.take(cut).trimEnd() + "…" + } + + // -- settings ----------------------------------------------------------------------------- + + fun setAppearance(appearance: Appearance) { + preferences.appearance = appearance + mutableState.update { it.copy(appearance = appearance) } + } + + /** One line of at most 40 characters. Saved on this phone; the host does not get it yet. */ + fun setUserName(text: String) { + val flat = text.map { if (Character.isISOControl(it)) ' ' else it }.joinToString("").trim() + val name = if (flat.codePointCount(0, flat.length) <= MAXIMUM_NAME) flat + else flat.substring(0, flat.offsetByCodePoints(0, MAXIMUM_NAME)).trimEnd() + preferences.userName = name + mutableState.update { it.copy(userName = name) } + } + + fun setNerdMode(on: Boolean) { + preferences.nerdMode = on + mutableState.update { it.copy(nerdMode = on) } + } + + companion object { + const val NEW_CHAT_TITLE = "New chat" + private const val MAXIMUM_TITLE = 40 + private const val MAXIMUM_NAME = 40 + private val COMPUTER_GONE = setOf(ComputerPhase.Idle, ComputerPhase.Failed, ComputerPhase.SignInRequired, ComputerPhase.ConsentRequired) + private val COMPUTER_SETUP_ROUTES = setOf(Route.Welcome, Route.Setup, Route.SignIn, Route.Consent) + private val ON_SETUP_ROUTES = setOf(Route.Setup, Route.SignIn, Route.Consent) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/BighelpTheme.kt b/android/app/src/main/kotlin/app/bighelp/android/BighelpTheme.kt new file mode 100644 index 00000000..62144f45 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpTheme.kt @@ -0,0 +1,104 @@ +package app.bighelp.android + +import android.app.Activity +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +val Ember = Color(0xFFFF8A7A) + +private val LightInk = lightColorScheme( + primary = Color.Black, + onPrimary = Color.White, + primaryContainer = Color(0xFFF0F0F2), + onPrimaryContainer = Color.Black, + secondary = Color(0xFF5C5C63), + onSecondary = Color.White, + secondaryContainer = Color(0xFFEAEAED), + onSecondaryContainer = Color.Black, + tertiary = Color.Black, + onTertiary = Color.White, + background = Color.White, + onBackground = Color(0xFF151518), + surface = Color.White, + onSurface = Color(0xFF151518), + surfaceVariant = Color(0xFFF3F3F5), + onSurfaceVariant = Color(0xFF606068), + outline = Color(0xFF777780), + outlineVariant = Color(0xFFDEDEE3), + surfaceTint = Color.Black, + surfaceContainerLowest = Color.White, + surfaceContainerLow = Color(0xFFF8F8FA), + surfaceContainer = Color(0xFFF3F3F5), + surfaceContainerHigh = Color(0xFFEEEEF0), + surfaceContainerHighest = Color(0xFFE8E8EC), +) + +private val DarkInk = darkColorScheme( + primary = Color.White, + onPrimary = Color.Black, + primaryContainer = Color(0xFF303035), + onPrimaryContainer = Color.White, + secondary = Color(0xFFB7B7C0), + onSecondary = Color.Black, + secondaryContainer = Color(0xFF303035), + onSecondaryContainer = Color.White, + tertiary = Color.White, + onTertiary = Color.Black, + background = Color.Black, + onBackground = Color(0xFFF5F5F7), + surface = Color.Black, + onSurface = Color(0xFFF5F5F7), + surfaceVariant = Color(0xFF202024), + onSurfaceVariant = Color(0xFFB7B7C0), + outline = Color(0xFF92929B), + outlineVariant = Color(0xFF3A3A3F), + surfaceTint = Color.White, + surfaceContainerLowest = Color.Black, + surfaceContainerLow = Color(0xFF141418), + surfaceContainer = Color(0xFF202024), + surfaceContainerHigh = Color(0xFF2B2B30), + surfaceContainerHighest = Color(0xFF36363C), +) + +/** Colors Material has no slot for: the Ink look's black bubbles (dark gray after dark) and its green switches. */ +@Immutable +class BighelpColors(val userBubble: Color, val onUserBubble: Color, val switchOn: Color) + +private val LightBighelpColors = BighelpColors(Color.Black, Color.White, Color(0xFF34C759)) +private val DarkBighelpColors = BighelpColors(Color(0xFF3A3A3F), Color.White, Color(0xFF30D158)) + +private val LocalBighelpColors = staticCompositionLocalOf { LightBighelpColors } + +object Bighelp { + val colors: BighelpColors + @Composable @ReadOnlyComposable get() = LocalBighelpColors.current +} + +@Composable +fun BighelpTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + (view.context as? Activity)?.window?.let { window -> + WindowCompat.getInsetsController(window, view).apply { + isAppearanceLightStatusBars = !darkTheme + isAppearanceLightNavigationBars = !darkTheme + } + } + } + } + CompositionLocalProvider(LocalBighelpColors provides if (darkTheme) DarkBighelpColors else LightBighelpColors) { + MaterialTheme(colorScheme = if (darkTheme) DarkInk else LightInk, content = content) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt new file mode 100644 index 00000000..18b15312 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt @@ -0,0 +1,351 @@ +package app.bighelp.android + +import android.animation.ValueAnimator +import androidx.compose.foundation.gestures.scrollBy +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.launch + +/** + * A demo chat: the shared [ChatPage] with sample messages and a box that only keeps a local draft. + * Rows are keyed by message ID, so a row's identity survives every change to the list. + */ +@Composable +fun ChatScreen( + demo: DemoState, + sessionId: String, + onBack: () -> Unit, + onDraft: (String) -> Unit, + onSend: () -> Boolean, +) { + val session = demo.session(sessionId) + if (session == null) { + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.chat.missing")) { + ScreenHeader("Chat", leading = { BackButton(onBack) }) + Text("This chat isn't available any more.", modifier = Modifier.padding(24.dp)) + } + return + } + val agent = demo.agent(session.agentId) + ChatPage( + rows = session.messages, + rowKey = { it.id }, + header = { ChatHeader(session.title, agent, onBack) }, + empty = { EmptyChatNote(agent) }, + // Keyed by chat, so a draft is read once when the chat opens and then owned by the box while typing. + bottomBar = { + Composer( + key = session.id, + initialDraft = demo.drafts[session.id].orEmpty(), + agentName = agent.name, + onDraft = onDraft, + onSend = onSend, + ) + }, + ) { message -> MessageRow(message) } +} + +/** + * The chat scaffold both the demo and a real chat use. The reader owns the scroll position: nothing moves it + * while they read history, a new row (their own send) always brings the newest into view, and a Latest button + * appears, in its own row above the message box, whenever they are away from the end. A reader who is at the + * end stays there while the last row grows ([tailVersion] changes as a reply streams). Rows are keyed, so + * rows added above (older history) never move what the reader is looking at. [onReachTop] fires each time the + * reader arrives at the very top, which is when older history is loaded. + */ +@Composable +internal fun ChatPage( + rows: List, + rowKey: (T) -> String, + header: @Composable () -> Unit, + bottomBar: @Composable () -> Unit, + modifier: Modifier = Modifier, + tailVersion: Any? = null, + onReachTop: (() -> Unit)? = null, + empty: (@Composable () -> Unit)? = null, + rowContent: @Composable (T) -> Unit, +) { + val scope = rememberCoroutineScope() + val listState = rememberLazyListState(initialFirstVisibleItemIndex = rows.lastIndex.coerceAtLeast(0)) + val lastIndex by rememberUpdatedState(rows.lastIndex) + + // True while the reader is at the end. Only a finished scroll changes it, so a viewport that shrinks + // (the keyboard opening) never counts as the reader leaving the end. Saved, so rotation keeps it. + var followTail by rememberSaveable { mutableStateOf(true) } + LaunchedEffect(listState) { + snapshotFlow { listState.isScrollInProgress }.collect { scrolling -> + if (!scrolling) followTail = !listState.canScrollForward + } + } + // A new last row (sending is the only way a demo list grows) always shows the new messages. + val lastId = rows.lastOrNull()?.let(rowKey) + var shownLastId by rememberSaveable { mutableStateOf(lastId) } + LaunchedEffect(lastId) { + if (lastId != shownLastId) { + shownLastId = lastId + followTail = true + listState.scrollToLatest(lastIndex, animated = ValueAnimator.areAnimatorsEnabled()) + } + } + // A reply growing in place keeps the end in view, but only for a reader who is already at the end. + LaunchedEffect(tailVersion) { + if (tailVersion != null && followTail && !listState.isScrollInProgress && lastIndex >= 0) { + listState.scrollToLatest(lastIndex, animated = false) + } + } + // Keep the end in view when the keyboard opens or closes, but only for a reader who is at the end. + // Never while a scroll runs: a drag or fling is the reader's, and a programmatic scroll would fight it. + LaunchedEffect(listState) { + snapshotFlow { listState.layoutInfo.viewportSize.height }.collect { + if (followTail && !listState.isScrollInProgress && lastIndex >= 0) { + listState.scrollToLatest(lastIndex, animated = false) + } + } + } + // Arriving at the top (a finished scroll or a first layout) is the cue to read older history. + val reachTop by rememberUpdatedState(onReachTop) + LaunchedEffect(listState) { + snapshotFlow { listState.firstVisibleItemIndex == 0 && listState.firstVisibleItemScrollOffset == 0 && !listState.isScrollInProgress } + .distinctUntilChanged() + .collect { atTop -> if (atTop) reachTop?.invoke() } + } + // The Latest row takes its own height out of the transcript, so it must never be what moves the reader. + // It appears only once a finished scroll has left the end (followTail is already false then, so the + // viewport follow above skips the shrink) and goes away when the reader is back at the end. + val showLatest by remember { derivedStateOf { !followTail && listState.canScrollForward } } + + Column(modifier.fillMaxSize().safeDrawingPadding().testTag("screen.chat")) { + header() + LazyColumn( + state = listState, + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.weight(1f).fillMaxWidth().testTag("chat.messages"), + ) { + if (rows.isEmpty() && empty != null) { + item(key = "empty") { empty() } + } + items(rows, key = rowKey) { row -> rowContent(row) } + } + if (showLatest) { + // Its own row between the transcript and the message box, so the button covers no message. + Box(Modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = Alignment.Center) { + JumpToLatest( + onClick = { + followTail = true + scope.launch { listState.scrollToLatest(lastIndex, animated = ValueAnimator.areAnimatorsEnabled()) } + }, + ) + } + } + bottomBar() + } +} + +/** Shows the end of the newest message, even a tall one, not only its start. */ +private suspend fun LazyListState.scrollToLatest(lastIndex: Int, animated: Boolean) { + if (lastIndex < 0) return + if (animated) animateScrollToItem(lastIndex) else scrollToItem(lastIndex) + if (canScrollForward) scrollBy(TALL_MESSAGE_PIXELS) +} + +private const val TALL_MESSAGE_PIXELS = 100_000f + +@Composable +private fun ChatHeader(title: String, agent: DemoAgent, onBack: () -> Unit) { + Row( + Modifier.fillMaxWidth().heightIn(min = 64.dp).padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + BackButton(onBack) + AgentAvatar(agent, size = 36.dp) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text( + title, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.testTag("chat.title"), + ) + Text( + "${agent.name} · demo, sample data", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.testTag("chat.subtitle"), + ) + } + } +} + +@Composable +private fun EmptyChatNote(agent: DemoAgent) { + Column(Modifier.fillMaxWidth().padding(vertical = 8.dp).testTag("chat.empty"), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("Say hello to ${agent.name}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text( + "This is a demo: replies are fixed examples, and nothing you type leaves this phone.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +@Composable +private fun MessageRow(message: DemoMessage) { + MessageBubble( + fromUser = message.fromUser, + caption = if (message.isExample) "Example reply, not from an agent" else null, + modifier = Modifier.testTag("chat.message.${message.id}"), + ) { + Text(message.text, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) + } +} + +/** One speech bubble: the person's on the right (black, dark gray after dark), the agent's on the left. Its text can be selected. */ +@Composable +internal fun MessageBubble( + fromUser: Boolean, + modifier: Modifier = Modifier, + caption: String? = null, + content: @Composable () -> Unit, +) { + Row(modifier.fillMaxWidth(), horizontalArrangement = if (fromUser) Arrangement.End else Arrangement.Start) { + Column( + Modifier.padding(start = if (fromUser) 48.dp else 0.dp, end = if (fromUser) 0.dp else 48.dp), + horizontalAlignment = if (fromUser) Alignment.End else Alignment.Start, + ) { + if (caption != null) { + Text( + caption, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 4.dp, bottom = 2.dp), + ) + } + Surface( + color = if (fromUser) Bighelp.colors.userBubble else MaterialTheme.colorScheme.surfaceContainerHigh, + contentColor = if (fromUser) Bighelp.colors.onUserBubble else MaterialTheme.colorScheme.onSurface, + shape = RoundedCornerShape( + topStart = 20.dp, topEnd = 20.dp, + bottomStart = if (fromUser) 20.dp else 6.dp, + bottomEnd = if (fromUser) 6.dp else 20.dp, + ), + modifier = Modifier.widthIn(max = 560.dp), + ) { + SelectionContainer { content() } + } + } + } +} + +@Composable +private fun JumpToLatest(onClick: () -> Unit, modifier: Modifier = Modifier) { + Surface( + onClick = onClick, + color = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary, + shape = RoundedCornerShape(24.dp), + shadowElevation = 4.dp, + modifier = modifier.heightIn(min = 48.dp).testTag("chat.jump-to-latest"), + ) { + Row(Modifier.padding(start = 12.dp, end = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Default.KeyboardArrowDown, contentDescription = null) + Spacer(Modifier.width(4.dp)) + Text("Latest", style = MaterialTheme.typography.labelLarge) + } + } +} + +/** + * The message box. It owns its text while the chat is open and reports every change to the model, which + * keeps the draft for when the person comes back. Send sits beside the box, never inside a crowded row. + */ +@Composable +private fun Composer( + key: String, + initialDraft: String, + agentName: String, + onDraft: (String) -> Unit, + onSend: () -> Boolean, +) { + var value by remember(key) { mutableStateOf(TextFieldValue(initialDraft, TextRange(initialDraft.length))) } + Row( + Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedTextField( + value = value, + onValueChange = { + value = it + onDraft(it.text) + }, + placeholder = { Text("Message $agentName") }, + maxLines = 6, + shape = RoundedCornerShape(26.dp), + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), + modifier = Modifier.weight(1f).testTag("chat.composer"), + ) + FilledIconButton( + onClick = { if (onSend()) value = TextFieldValue("") }, + enabled = value.text.isNotBlank(), + colors = IconButtonDefaults.filledIconButtonColors(), + modifier = Modifier.padding(bottom = 4.dp).size(52.dp).testTag("chat.send"), + ) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send") + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/Components.kt b/android/app/src/main/kotlin/app/bighelp/android/Components.kt new file mode 100644 index 00000000..c2b7226a --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/Components.kt @@ -0,0 +1,215 @@ +package app.bighelp.android + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** A screen's top row: optional leading control, a small title, optional trailing actions. */ +@Composable +fun ScreenHeader( + title: String, + modifier: Modifier = Modifier, + leading: @Composable () -> Unit = {}, + trailing: @Composable RowScope.() -> Unit = {}, +) { + Row( + modifier.fillMaxWidth().heightIn(min = 64.dp).padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) { leading() } + Text( + title, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f).padding(horizontal = 4.dp).semantics { heading() }, + ) + trailing() + } +} + +@Composable +fun BackButton(onBack: () -> Unit) { + IconButton(onClick = onBack, modifier = Modifier.size(48.dp).testTag("nav.back")) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } +} + +/** Shown on every demo screen so sample data is never mistaken for a real computer. */ +@Composable +fun DemoBanner(modifier: Modifier = Modifier) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainer, + shape = RoundedCornerShape(12.dp), + modifier = modifier.fillMaxWidth().testTag("demo.banner"), + ) { + Row(Modifier.padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) { + Icon( + Icons.Outlined.Info, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(8.dp)) + Text( + "Demo mode: sample chats on this phone. Nothing is sent anywhere.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** An agent's picture: its color and first letter. Sample agents have no live status to show. */ +@Composable +fun AgentAvatar(agent: DemoAgent, modifier: Modifier = Modifier, size: Dp = 44.dp) { + Box( + modifier.size(size).clip(CircleShape).background(Color(agent.colorArgb)), + contentAlignment = Alignment.Center, + ) { + Text( + agent.name.take(1), + color = Color.White, + fontWeight = FontWeight.Bold, + fontSize = (size.value * 0.42f).sp, + ) + } +} + +@Composable +fun InkButton(text: String, onClick: () -> Unit, tag: String, modifier: Modifier = Modifier, enabled: Boolean = true) { + Button( + onClick = onClick, + enabled = enabled, + shape = RoundedCornerShape(26.dp), + modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).testTag(tag), + ) { Text(text, style = MaterialTheme.typography.labelLarge, fontSize = 16.sp) } +} + +@Composable +fun InkOutlinedButton( + text: String, + onClick: () -> Unit, + tag: String, + modifier: Modifier = Modifier, + enabled: Boolean = true, +) { + OutlinedButton( + onClick = onClick, + enabled = enabled, + shape = RoundedCornerShape(26.dp), + modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).testTag(tag), + ) { Text(text, style = MaterialTheme.typography.labelLarge, fontSize = 16.sp) } +} + +/** Small, bold, letterspaced, muted: the caption above a group of rows. */ +@Composable +fun SectionLabel(text: String, modifier: Modifier = Modifier) { + Text( + text.uppercase(), + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + letterSpacing = 1.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = modifier.padding(horizontal = 4.dp).semantics { heading() }, + ) +} + +/** The first row of a list: filter chats as you type. Never the system search bar. */ +@Composable +fun BighelpSearchField( + value: String, + onValueChange: (String) -> Unit, + placeholder: String, + tag: String, + modifier: Modifier = Modifier, +) { + TextField( + value = value, + onValueChange = onValueChange, + singleLine = true, + placeholder = { Text(placeholder) }, + leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) }, + trailingIcon = { + if (value.isNotEmpty()) { + IconButton(onClick = { onValueChange("") }, modifier = Modifier.testTag("$tag.clear")) { + Icon(Icons.Default.Close, contentDescription = "Clear search") + } + } + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + shape = RoundedCornerShape(26.dp), + colors = TextFieldDefaults.colors( + focusedContainerColor = MaterialTheme.colorScheme.surfaceContainer, + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceContainer, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + cursorColor = MaterialTheme.colorScheme.primary, + ), + modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).testTag(tag), + ) +} + +/** A page that centers short content and scrolls tall content, capped to a readable width on tablets. */ +@Composable +fun ScrollingPage(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) { + BoxWithConstraints(modifier, contentAlignment = Alignment.TopCenter) { + Column( + Modifier + .widthIn(max = 520.dp) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + .padding(horizontal = 24.dp, vertical = 16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + content = content, + ) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/DemoContent.kt b/android/app/src/main/kotlin/app/bighelp/android/DemoContent.kt new file mode 100644 index 00000000..8c9193d0 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/DemoContent.kt @@ -0,0 +1,90 @@ +package app.bighelp.android + +/** + * The sample conversations behind "Try the demo". Everything here is invented; no person, host or plan is + * real. Replies are fixed text written by the app, never by an agent, and appear at once. + */ +object DemoContent { + private val scout = DemoAgent("scout", "Scout", "Looks things up and sums them up", 0xFF2F6FD6) + private val ledger = DemoAgent("ledger", "Ledger", "Keeps lists, plans and errands", 0xFF1F7A4D) + private val tinker = DemoAgent("tinker", "Tinker", "Helps with code and small fixes", 0xFF8250DF) + + /** Used for every demo reply, so what is sample data is never in doubt. */ + fun exampleReply(agent: DemoAgent): String = + "This is an example reply. ${agent.name} is a sample agent in the demo, so this answer is fixed " + + "text. Your message stayed on this phone." + + fun initial(): DemoState = DemoState( + agents = listOf(scout, ledger, tinker), + selectedAgentId = scout.id, + sessions = listOf(lakeWeekend(), router(), dateTest()), + ) + + private fun lakeWeekend(): DemoSession { + val items = listOf( + "tent" to "the two-person one is on the garage shelf", + "sleeping bags" to "check the zips before you leave", + "headlamps" to "pack spare batteries", + "water filter" to "rinse it the night before", + "camp stove" to "fuel is a separate item", + "first-aid kit" to "restock the plasters", + "sunscreen" to "SPF 50 for the water", + "rain jackets" to "the forecast is mixed", + "folding chairs" to "two is enough", + "cooler" to "fill it last", + "playing cards" to "for the evening", + "bug spray" to "dusk is the worst", + "trash bags" to "pack out what you pack in", + "phone chargers" to "bring a power bank too", + "swim towels" to "quick-dry ones", + "marshmallows" to "obviously", + ) + val messages = buildList { + add("Can you help me plan packing for the lake weekend?" to true) + add("Happy to. Tell me one thing at a time and I'll keep the list." to false) + items.forEach { (item, note) -> + add("What about the $item?" to true) + add("Add the $item: $note." to false) + } + } + return DemoSession( + id = "lake", + agentId = ledger.id, + title = "Lake weekend packing", + messages = messages.mapIndexed { index, (text, fromUser) -> DemoMessage("lake/$index", fromUser, text) }, + ) + } + + private fun router(): DemoSession = DemoSession( + id = "router", + agentId = scout.id, + title = "Which router should I buy?", + messages = listOf( + DemoMessage("router/0", true, "Which router should I buy for a small flat?"), + DemoMessage( + "router/1", false, + "For a small flat a single mid-range Wi-Fi 6 router is plenty. Mesh kits only pay off " + + "when walls or floors block the signal.", + ), + DemoMessage("router/2", true, "Is it worth paying for Wi-Fi 7?"), + DemoMessage( + "router/3", false, + "Only if your devices support it. Most still don't, so Wi-Fi 6 is the safer buy today.", + ), + ), + ) + + private fun dateTest(): DemoSession = DemoSession( + id = "date-test", + agentId = tinker.id, + title = "Fix the failing date test", + messages = listOf( + DemoMessage("date-test/0", true, "The date test fails only on the last day of the month."), + DemoMessage( + "date-test/1", false, + "That points to adding days to a date and then reading the month. Try building the " + + "expected value from the same starting date instead of today's.", + ), + ), + ) +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt new file mode 100644 index 00000000..4e4e5a80 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt @@ -0,0 +1,115 @@ +package app.bighelp.android + +import app.bighelp.hermes.HermesEndpoint +import java.io.IOException +import java.util.concurrent.TimeUnit +import kotlin.coroutines.resume +import kotlinx.coroutines.suspendCancellableCoroutine +import okhttp3.Call +import okhttp3.Callback +import okhttp3.CookieJar +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okio.Buffer + +/** + * Outcome of the public host check. A host that answers is [Available]: found, not connected, and no + * sign-in, token or session has been requested of it. + */ +sealed interface DiscoveryResult { + /** Nothing was sent: the one-time AI data agreement has not been given. */ + data object ConsentRequired : DiscoveryResult + + /** Unreachable, refused, redirected, oversized or not the documented shape. The reason is never kept. */ + data object Unavailable : DiscoveryResult + + data class Available(val authRequired: Boolean, val browserSignIn: Boolean) : DiscoveryResult +} + +/** The seam [BighelpAppModel] calls, so state tests need no network. */ +fun interface HostChecker { + suspend fun check(endpoint: HermesEndpoint, consentGranted: Boolean): DiscoveryResult +} + +/** + * Consent-gated `GET /api/status` against one validated [HermesEndpoint]. It is the only network code in + * the first milestone, and it takes no credential of any kind. + * + * The request carries no cookies, tokens or custom headers and follows no redirects (not even to the same + * origin), so a proxy or sign-in page can never turn into a "found" host. It asks the host to close the + * connection afterwards (`Connection: close`), so each check opens its own socket and none is reused; the + * client's no-retry policy stays as it is and is never loosened for other requests. The decoded body is capped at + * [HostStatus.MAXIMUM_BYTES] and is never kept or logged, whatever it holds. Certificates are checked by + * the platform; HTTPS is the default and plain HTTP exists only on an endpoint that already passed the + * private-network opt-in in [HermesEndpoint.parse]. + */ +class HostDiscovery(private val client: OkHttpClient = defaultClient) : HostChecker { + override suspend fun check(endpoint: HermesEndpoint, consentGranted: Boolean): DiscoveryResult { + if (!consentGranted) return DiscoveryResult.ConsentRequired + val request = try { + Request.Builder() + .url(endpoint.httpUrl("/api/status").toString()) + .header("Accept", "application/json") + .header("Cache-Control", "no-store") + // A check never rides an idle pooled socket. A host (or a proxy, or an HTTP/1.0 server) may + // have closed it, and for a GET OkHttp only learns that by failing to read the reply, which + // retryOnConnectionFailure(false) turns into "unavailable" with nothing reaching the host. + .header("Connection", "close") + .build() + } catch (_: IllegalArgumentException) { + return DiscoveryResult.Unavailable + } + return client.newCall(request).answer() + } + + private suspend fun Call.answer(): DiscoveryResult = suspendCancellableCoroutine { continuation -> + continuation.invokeOnCancellation { cancel() } + enqueue(object : Callback { + override fun onFailure(call: Call, e: IOException) = continuation.resume(DiscoveryResult.Unavailable) + + override fun onResponse(call: Call, response: Response) { + // Nothing thrown here may escape: it would end on OkHttp's thread and crash the app. + val result = try { + response.use(::interpret) + } catch (_: Exception) { + DiscoveryResult.Unavailable + } + continuation.resume(result) + } + }) + } + + private fun interpret(response: Response): DiscoveryResult { + if (response.code != 200) return DiscoveryResult.Unavailable + val body = response.body ?: return DiscoveryResult.Unavailable + if (body.contentLength() > HostStatus.MAXIMUM_BYTES) return DiscoveryResult.Unavailable + + // One byte past the budget is enough to know the body is too large. + val source = body.source() + val buffer = Buffer() + while (buffer.size <= HostStatus.MAXIMUM_BYTES) { + if (source.read(buffer, HostStatus.MAXIMUM_BYTES + 1L - buffer.size) == -1L) break + } + if (buffer.size > HostStatus.MAXIMUM_BYTES) return DiscoveryResult.Unavailable + + val status = HostStatus.parse(buffer.readByteArray()) ?: return DiscoveryResult.Unavailable + return DiscoveryResult.Available(status.authRequired, status.browserSignIn) + } + + private companion object { + val defaultClient: OkHttpClient by lazy { + OkHttpClient.Builder() + .followRedirects(false) + .followSslRedirects(false) + .cookieJar(CookieJar.NO_COOKIES) + .cache(null) + .retryOnConnectionFailure(false) + .connectTimeout(8, TimeUnit.SECONDS) + .readTimeout(8, TimeUnit.SECONDS) + .writeTimeout(8, TimeUnit.SECONDS) + .callTimeout(15, TimeUnit.SECONDS) + .build() + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/HostStatus.kt b/android/app/src/main/kotlin/app/bighelp/android/HostStatus.kt new file mode 100644 index 00000000..e3ff25f5 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/HostStatus.kt @@ -0,0 +1,125 @@ +package app.bighelp.android + +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** + * What a Hermes host's public `GET /api/status` says about signing in, decoded exactly as + * `docs/hermes/CONNECTION.md` §3 describes. Anything else is `null`: the caller treats it as "no Hermes + * answered" and never shows the body. + */ +internal data class HostStatus(val authRequired: Boolean, val authFlows: List) { + /** Browser sign-in is offered only by a host that asks for sign-in and lists the exact flow name. */ + val browserSignIn: Boolean get() = authRequired && NATIVE_PKCE in authFlows + + companion object { + const val MAXIMUM_BYTES = 16_384 + private const val NATIVE_PKCE = "native_pkce" + private const val MAXIMUM_FLOWS = 32 + private const val MAXIMUM_FLOW_BYTES = 128 + + fun parse(bytes: ByteArray): HostStatus? { + if (bytes.size > MAXIMUM_BYTES) return null + val text = try { + Charsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString() + } catch (_: CharacterCodingException) { + return null + } + val parsed = try { + Json.parseToJsonElement(text) + } catch (_: SerializationException) { + return null + } + val root = parsed as? JsonObject ?: return null + // A parser that keeps the last duplicate would let two readers see different answers. + if (hasDuplicateTopLevelKey(text)) return null + + val authRequired = root["auth_required"].strictBoolean() ?: return null + val flows = when (val element = root["auth_flows"]) { + null, JsonNull -> emptyList() + is JsonArray -> decodeFlows(element) ?: return null + else -> return null + } + return HostStatus(authRequired, flows) + } + + private fun JsonElement?.strictBoolean(): Boolean? { + val primitive = this as? JsonPrimitive ?: return null + // `"true"` (a string) is not a Boolean, even though its text reads like one. + if (primitive.isString) return null + return when (primitive.content) { + "true" -> true + "false" -> false + else -> null + } + } + + private fun decodeFlows(array: JsonArray): List? { + if (array.size > MAXIMUM_FLOWS) return null + val flows = ArrayList(array.size) + for (element in array) { + val primitive = element as? JsonPrimitive ?: return null + val name = primitive.takeIf { it.isString }?.content ?: return null + if (name.isEmpty() || !isWellFormed(name) || name.toByteArray(Charsets.UTF_8).size > MAXIMUM_FLOW_BYTES) { + return null + } + flows += name + } + return flows.takeIf { it.toSet().size == it.size } + } + + /** No unpaired surrogates, which a `\ud800` escape can smuggle into an otherwise valid string. */ + private fun isWellFormed(text: String): Boolean { + var i = 0 + while (i < text.length) { + val c = text[i] + if (c.isHighSurrogate()) { + if (i + 1 >= text.length || !text[i + 1].isLowSurrogate()) return false + i++ + } else if (c.isLowSurrogate()) { + return false + } + i++ + } + return true + } + + /** Scans well-formed JSON (already parsed) for an object key repeated directly under the root. */ + private fun hasDuplicateTopLevelKey(text: String): Boolean { + val seen = HashSet() + var depth = 0 + var i = 0 + while (i < text.length) { + when (text[i]) { + '{', '[' -> depth++ + '}', ']' -> depth-- + '"' -> { + var end = i + 1 + while (text[end] != '"') end += if (text[end] == '\\') 2 else 1 + var next = end + 1 + while (text[next].isWhitespace()) next++ + if (depth == 1 && text[next] == ':') { + val key = (Json.parseToJsonElement(text.substring(i, end + 1)) as JsonPrimitive).content + if (!seen.add(key)) return true + } + i = end + } + } + i++ + } + return false + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/LiveChatScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/LiveChatScreen.kt new file mode 100644 index 00000000..a3c98c4a --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/LiveChatScreen.kt @@ -0,0 +1,582 @@ +package app.bighelp.android + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.bighelp.android.live.ChatRow +import app.bighelp.android.live.LiveModel +import app.bighelp.android.live.LiveText +import app.bighelp.android.live.SendOutcome +import app.bighelp.android.live.TranscriptRows +import app.bighelp.hermes.chat.ActivityItem +import app.bighelp.hermes.chat.ActivityKind +import app.bighelp.hermes.chat.ActivityLifecycle +import app.bighelp.hermes.chat.ApprovalChoice +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.ItemOrigin +import app.bighelp.hermes.chat.MessageItem +import app.bighelp.hermes.chat.MessageRole +import app.bighelp.hermes.chat.PromptAnswer +import app.bighelp.hermes.chat.PromptContent +import app.bighelp.hermes.chat.PromptState +import app.bighelp.hermes.chat.ReviewDecision +import app.bighelp.hermes.chat.SecureKind +import app.bighelp.hermes.chat.SendMode +import app.bighelp.hermes.chat.SlashCommand +import app.bighelp.hermes.chat.UnresolvedSubmission +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonPrimitive + +/** + * A real chat: the shared [ChatPage] with the host's transcript, tools and reasoning as they happened, the + * agent's questions above the message box, and a message box that steers a running turn by default. Everything + * shown comes from the chat's own state; nothing is invented while it opens or runs. + */ +@Composable +internal fun LiveChatScreen( + live: LiveModel<*>, + refId: String, + onBack: () -> Unit, + onOpenChat: (ConversationRef) -> Unit, + onSignInAgain: () -> Unit, +) { + val ref = remember(refId) { ConversationRef.parse(refId) } + if (ref == null) { + Column(Modifier.fillMaxWidth().testTag("screen.chat.missing")) { + ScreenHeader("Chat", leading = { BackButton(onBack) }) + Text("This chat isn't available any more.", modifier = Modifier.padding(24.dp)) + } + return + } + val conversations by live.conversations.collectAsStateWithLifecycle() + val catalog by live.catalog.collectAsStateWithLifecycle() + val link by live.link.collectAsStateWithLifecycle() + val problem by live.reconnectProblem.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + val state = conversations[ref] + val summary = catalog.sessions.firstOrNull { it.ref == ref } + val agentName = catalog.agents.firstOrNull { it.id == ref.profile }?.displayName?.ifBlank { null } ?: ref.profile + val title = state?.title?.takeIf { it.isNotBlank() } ?: summary?.title?.ifBlank { null } ?: if (summary?.isCanonicalBotChat == true) "Bot Chat" else "Chat" + var sheet by remember { mutableStateOf(false) } + var renaming by remember { mutableStateOf(false) } + var archiving by remember { mutableStateOf(false) } + + val rows = remember(state) { state?.let(TranscriptRows::withEdges).orEmpty() } + val tail = rows.lastOrNull() + ChatPage( + rows = rows, + rowKey = ChatRow::key, + tailVersion = Pair((tail as? ChatRow.Message)?.item?.text?.length, tail?.key), + onReachTop = { + val history = state?.history + if (history != null && history.hasOlder && !history.loadingOlder) scope.launch { live.loadOlder(ref) } + }, + header = { + Column { + LiveChatHeader( + title = title, agentName = agentName, profile = ref.profile, model = state?.runtime?.model, + onBack = onBack, + onModel = { sheet = true }, onRename = { renaming = true }, onArchive = { archiving = true }, + onBranch = { + val row = state?.items?.lastOrNull { it is MessageItem && it.rowId != null && it.origin == ItemOrigin.Saved } as? MessageItem + if (row?.rowId == null) live.notify("Branch needs a saved message first.") + else scope.launch { live.fork(ref, row.rowId!!)?.let(onOpenChat) } + }, + ) + LinkBanner(link, problem, onReconnect = live::reconnectNow, onSignInAgain = onSignInAgain, modifier = Modifier.padding(horizontal = 12.dp)) + } + }, + empty = { + if (state == null) Text("Opening this chat…", color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(8.dp).testTag("chat.opening")) + else EmptyChatNote("Say hello to $agentName", "Replies come from $agentName on your computer.") + }, + bottomBar = { if (state != null) LiveBottomBar(live, ref, state, agentName) }, + ) { row -> + when (row) { + is ChatRow.Message -> LiveMessage(row.item) + is ChatRow.Activity -> ActivityRow(row.item) + is ChatRow.Note -> Text( + row.text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp).testTag("chat.note.${row.key}"), + ) + is ChatRow.History -> TextButton( + onClick = { scope.launch { live.loadOlder(ref) } }, enabled = !row.loading, + modifier = Modifier.fillMaxWidth().testTag("chat.older"), + ) { Text(if (row.loading) "Loading earlier messages…" else "Load earlier messages") } + is ChatRow.Working -> Text( + row.label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp).semantics { liveRegion = LiveRegionMode.Polite }.testTag("chat.working"), + ) + } + } + if (sheet && state != null) ModelSheet(live, ref, state, onDismiss = { sheet = false }) + if (renaming) TextEntryDialog("Rename chat", title, "Rename", { name -> renaming = false; scope.launch { live.rename(ref, name) } }, { renaming = false }, "dialog.rename") + if (archiving) ConfirmDialog( + "Archive this chat?", "It leaves the list and stays in Archived chats. You can restore it.", "Archive", + { archiving = false; scope.launch { live.archive(ref); onBack() } }, { archiving = false }, "dialog.archive", + ) +} + +@Composable +private fun LiveChatHeader( + title: String, agentName: String, profile: String, model: String?, + onBack: () -> Unit, onModel: () -> Unit, onRename: () -> Unit, onBranch: () -> Unit, onArchive: () -> Unit, +) { + var menu by remember { mutableStateOf(false) } + Row(Modifier.fillMaxWidth().heightIn(min = 64.dp).padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) { + BackButton(onBack) + LiveAvatar(agentName, profile, size = 36.dp) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.testTag("chat.title")) + Text( + listOfNotNull(agentName, model).joinToString(" · "), style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.testTag("chat.subtitle"), + ) + } + Box { + IconButton(onClick = { menu = true }, modifier = Modifier.size(48.dp).testTag("chat.more")) { Icon(Icons.Default.MoreVert, contentDescription = "Chat options") } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem(text = { Text("Model and speed") }, onClick = { menu = false; onModel() }, modifier = Modifier.testTag("chat.menu.model")) + DropdownMenuItem(text = { Text("Rename") }, onClick = { menu = false; onRename() }, modifier = Modifier.testTag("chat.menu.rename")) + DropdownMenuItem(text = { Text("Branch this chat") }, onClick = { menu = false; onBranch() }, modifier = Modifier.testTag("chat.menu.branch")) + DropdownMenuItem(text = { Text("Archive") }, onClick = { menu = false; onArchive() }, modifier = Modifier.testTag("chat.menu.archive")) + } + } + } +} + +@Composable +internal fun EmptyChatNote(title: String, body: String) { + Column(Modifier.fillMaxWidth().padding(vertical = 8.dp).testTag("chat.empty"), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text(body, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +// ---- messages and activity ---------------------------------------------------------------------------- + +@Composable +private fun LiveMessage(item: MessageItem) { + val fromUser = item.role == MessageRole.User + MessageBubble(fromUser = fromUser, modifier = Modifier.testTag("chat.message.${item.id}")) { + Column(Modifier.padding(horizontal = 14.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + if (item.text.isNotEmpty()) { + // The person's own words are shown as typed; only an agent's reply is read as Markdown. + if (fromUser) Text(item.text, style = MaterialTheme.typography.bodyLarge) else MarkdownText(item.text) + } + if (item.hasUnsupportedContent) { + Text("This message has content the app can't show yet.", style = MaterialTheme.typography.bodySmall, fontStyle = FontStyle.Italic) + } + item.failure?.let { failure -> + Text( + if (failure.retryable) "This reply stopped before it finished. You can ask again." else "This reply stopped before it finished.", + style = MaterialTheme.typography.bodySmall, fontStyle = FontStyle.Italic, + ) + } + } + } +} + +/** An agent's reply, with its code, headings, lists and bold, italic and code marks drawn. Text stays selectable. */ +@Composable +internal fun MarkdownText(text: String) { + val codeBackground = MaterialTheme.colorScheme.surfaceContainerHighest + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + for (block in Markdown.blocks(text)) when (block) { + is MdBlock.Paragraph -> Text(inline(block.text, codeBackground), style = MaterialTheme.typography.bodyLarge) + is MdBlock.Heading -> Text(inline(block.text, codeBackground), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + is MdBlock.Bullets -> Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + block.items.forEachIndexed { index, item -> + Row { + Text(if (block.ordered) "${index + 1}." else "•", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.width(24.dp)) + Text(inline(item, codeBackground), style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + } + } + } + is MdBlock.Code -> Surface(color = codeBackground, shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) { + Text( + block.text, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, + modifier = Modifier.horizontalScroll(rememberScrollState()).padding(10.dp), + ) + } + } + } +} + +private fun inline(text: String, codeBackground: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString { + for (span in Markdown.spans(text)) { + val style = SpanStyle( + fontWeight = if (span.bold) FontWeight.Bold else null, + fontStyle = if (span.italic) FontStyle.Italic else null, + fontFamily = if (span.code) FontFamily.Monospace else null, + background = if (span.code) codeBackground else androidx.compose.ui.graphics.Color.Unspecified, + ) + withStyle(style) { append(span.text) } + } +} + +@Composable +private fun ActivityRow(item: ActivityItem) { + var open by remember(item.id) { mutableStateOf(false) } + val state = when (item.lifecycle) { + ActivityLifecycle.Running -> "Running" + ActivityLifecycle.Succeeded -> "Done" + ActivityLifecycle.Failed -> "Failed" + ActivityLifecycle.Cancelled -> "Stopped" + ActivityLifecycle.Recorded -> "" + } + val details = listOfNotNull(item.detail, item.arguments?.let { "Input: $it" }, item.result?.let { "Result: $it" }).filter { it.isNotBlank() } + Surface( + color = MaterialTheme.colorScheme.surfaceContainer, shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth().testTag("chat.activity.${item.id}"), + ) { + Column(Modifier.clickable(enabled = details.isNotEmpty()) { open = !open }.padding(horizontal = 12.dp, vertical = 8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + if (item.kind == ActivityKind.Reasoning) "Thinking" else item.title, + style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), + ) + if (state.isNotEmpty()) Text(state, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (open) for (detail in details) { + Text( + detail.take(MAXIMUM_DETAIL), fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 6.dp), + ) + } + } + } +} + +private const val MAXIMUM_DETAIL = 4_000 + +// ---- the box and what sits above it --------------------------------------------------------------------- + +@Composable +private fun LiveBottomBar(live: LiveModel<*>, ref: ConversationRef, state: ConversationState, agentName: String) { + val scope = rememberCoroutineScope() + Column { + if (state.legacyPromptHost) { + // This host answers questions the older way: no card can be shown, so say so rather than look broken. + Text( + "Your computer can't show this agent's questions in the app yet. You may need to update the plugin on your computer.", + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp).testTag("chat.legacy-prompts"), + ) + } + state.unresolved.forEach { entry -> + UnresolvedCard( + entry, + onPutBack = { scope.launch { live.review(ref, entry.id, ReviewDecision.RestoreToComposer) } }, + onDiscard = { scope.launch { live.review(ref, entry.id, ReviewDecision.Discard) } }, + ) + } + state.prompts.forEach { prompt -> + PromptCard( + prompt, + onAnswer = { answer -> scope.launch { live.answerPrompt(prompt.id, answer) } }, + onDecline = { scope.launch { live.declinePrompt(prompt.id) } }, + ) + } + LiveComposer(live, ref, state, agentName) + } +} + +@Composable +private fun UnresolvedCard(entry: UnresolvedSubmission, onPutBack: () -> Unit, onDiscard: () -> Unit) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).testTag("chat.unresolved.${entry.id}"), + ) { + Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text( + if (entry.rejectionCode == null) "We couldn't confirm this message was sent." else "Your computer didn't take this message.", + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + Text(entry.composerText, maxLines = 3, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (entry.rejectionCode == null) Text("It is never sent again by itself. Check the chat before you try again.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Row { + TextButton(onClick = onPutBack, modifier = Modifier.heightIn(min = 48.dp).testTag("chat.unresolved.restore")) { Text("Put it back in the box") } + TextButton(onClick = onDiscard, modifier = Modifier.heightIn(min = 48.dp).testTag("chat.unresolved.discard")) { Text("Discard") } + } + } + } +} + +@Composable +private fun LiveComposer(live: LiveModel<*>, ref: ConversationRef, state: ConversationState, agentName: String) { + val scope = rememberCoroutineScope() + var value by remember(ref) { mutableStateOf(TextFieldValue(state.draft, TextRange(state.draft.length))) } + var error by remember(ref) { mutableStateOf(null) } + var sending by remember(ref) { mutableStateOf(false) } + var suggestions by remember(ref) { mutableStateOf>(emptyList()) } + // A draft the host returns (a refused send restores it) fills an empty box; a box with text is never overwritten. + LaunchedEffect(state.draft) { + if (state.draft.isNotEmpty() && value.text.isEmpty()) value = TextFieldValue(state.draft, TextRange(state.draft.length)) + } + LaunchedEffect(value.text) { + suggestions = if (value.text.startsWith("/")) live.suggestions(ref, value.text).take(MAXIMUM_SUGGESTIONS) else emptyList() + } + val blocked = state.sendBlock?.let(LiveText::sendBlock) + val canSend = value.text.isNotBlank() && blocked == null && !sending + + fun submit(mode: SendMode) { + val text = value.text + if (text.isBlank() || sending) return + sending = true + error = null + scope.launch { + when (val outcome = live.send(ref, text, mode)) { + SendOutcome.Sent -> value = TextFieldValue("") + is SendOutcome.Kept -> error = outcome.message + } + sending = false + } + } + + Column(Modifier.fillMaxWidth()) { + if (suggestions.isNotEmpty()) { + Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp).testTag("chat.suggestions")) { + suggestions.forEach { command -> + TextButton( + onClick = { val text = "/${command.name} "; value = TextFieldValue(text, TextRange(text.length)); live.editDraft(ref, text) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), + ) { + Text("/${command.name}", fontWeight = FontWeight.SemiBold) + Spacer(Modifier.width(8.dp)) + Text(command.description, maxLines = 1, overflow = TextOverflow.Ellipsis, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + } + } + } + } + val note = error ?: blocked + if (note != null) { + Text( + note, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 2.dp).semantics { liveRegion = LiveRegionMode.Polite }.testTag("chat.composer.note"), + ) + } + if (state.running) { + // Send steers the running turn. These are the other choices, kept out of the row with the box. + Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + TextButton(onClick = { scope.launch { live.stop(ref) } }, enabled = !state.stopRequested, modifier = Modifier.heightIn(min = 48.dp).testTag("chat.stop")) { Text("Stop") } + TextButton(onClick = { submit(SendMode.Queue) }, enabled = canSend, modifier = Modifier.heightIn(min = 48.dp).testTag("chat.queue")) { Text("Send next") } + TextButton(onClick = { submit(SendMode.InterruptAndSend) }, enabled = canSend, modifier = Modifier.heightIn(min = 48.dp).testTag("chat.stop-and-send")) { Text("Stop and send") } + } + } + Row( + Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedTextField( + value = value, + onValueChange = { value = it; live.editDraft(ref, it.text) }, + readOnly = sending, + placeholder = { Text(if (state.running) "Steer $agentName" else "Message $agentName") }, + maxLines = 6, shape = RoundedCornerShape(26.dp), + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), + modifier = Modifier.weight(1f).testTag("chat.composer"), + ) + FilledIconButton( + onClick = { submit(SendMode.Default) }, enabled = canSend, + colors = IconButtonDefaults.filledIconButtonColors(), + modifier = Modifier.padding(bottom = 4.dp).size(52.dp).testTag("chat.send"), + ) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = if (state.running) "Steer" else "Send") } + } + } +} + +private const val MAXIMUM_SUGGESTIONS = 6 + +// ---- the agent's questions ------------------------------------------------------------------------------ + +@Composable +private fun PromptCard(prompt: PromptState, onAnswer: (PromptAnswer) -> Unit, onDecline: () -> Unit) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).testTag("chat.prompt.${prompt.id}"), + ) { + // Capped, so a long question never pushes the transcript off the screen. + Column(Modifier.heightIn(max = 300.dp).verticalScroll(rememberScrollState()).padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + when (val content = prompt.content) { + is PromptContent.Approval -> ApprovalBody(content, onAnswer) + is PromptContent.Clarification -> ClarifyBody(content, onAnswer, onDecline) + is PromptContent.SecureInput -> SecureBody(content, onAnswer, onDecline) + } + } + } +} + +@Composable +private fun ApprovalBody(content: PromptContent.Approval, onAnswer: (PromptAnswer) -> Unit) { + Text("Your agent wants to run something", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold) + content.description?.let { Text(it, style = MaterialTheme.typography.bodyMedium) } + content.command?.let { + Surface(color = MaterialTheme.colorScheme.surfaceContainerHighest, shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) { + Text(it.take(MAXIMUM_DETAIL), fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(10.dp)) + } + } + content.toolName?.let { Text("Tool: $it", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + // Only the choices the host offered are shown; Deny is always last. + val ordered = content.choices.sortedBy { if (it == ApprovalChoice.Deny) 1 else 0 } + Row(horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) { + ordered.forEach { choice -> + TextButton(onClick = { onAnswer(PromptAnswer.Approve(choice)) }, modifier = Modifier.heightIn(min = 48.dp).testTag("prompt.approve.${choice.wire}")) { + Text( + when (choice) { + ApprovalChoice.Once -> "Allow once" + ApprovalChoice.Session -> "Allow in this chat" + ApprovalChoice.Always -> "Always allow" + ApprovalChoice.Deny -> "Don't allow" + }, + ) + } + } + } +} + +@Composable +private fun ClarifyBody(content: PromptContent.Clarification, onAnswer: (PromptAnswer) -> Unit, onDecline: () -> Unit) { + Text(if (content.questions.size > 1) "Your agent has a few questions" else "Your agent has a question", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold) + // One entry per question: the chosen options and typed text. The locked ones are already answered by the host. + val chosen = remember(content) { mutableStateOf(content.questions.associate { it.id to emptySet() }) } + val typed = remember(content) { mutableStateOf(content.questions.associate { it.id to "" }) } + for (question in content.questions) { + Text(question.question, style = MaterialTheme.typography.bodyLarge) + if (question.lockedAnswer != null) { + Text("Answered: ${question.lockedAnswer}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + continue + } + question.choices.forEach { choice -> + val selected = choice in chosen.value.getValue(question.id) + TextButton( + onClick = { + val now = chosen.value.getValue(question.id) + val next = if (question.multiSelect) (if (selected) now - choice else now + choice) else setOf(choice) + chosen.value = chosen.value + (question.id to next) + if (!question.multiSelect) typed.value = typed.value + (question.id to "") + }, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).testTag("prompt.choice.${question.id}.$choice"), + ) { Text(if (selected) "✓ $choice" else choice, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, modifier = Modifier.fillMaxWidth()) } + } + OutlinedTextField( + value = typed.value.getValue(question.id), + onValueChange = { typed.value = typed.value + (question.id to it); if (!question.multiSelect && it.isNotEmpty()) chosen.value = chosen.value + (question.id to emptySet()) }, + label = { Text(if (question.choices.isEmpty()) "Your answer" else "Something else") }, + shape = RoundedCornerShape(16.dp), modifier = Modifier.fillMaxWidth().testTag("prompt.text.${question.id}"), + ) + } + val answers = content.questions.mapNotNull { question -> + if (question.lockedAnswer != null) return@mapNotNull question.id to question.lockedAnswer!! + val picked = question.choices.filter { it in chosen.value.getValue(question.id) } + val extra = typed.value.getValue(question.id).trim() + val text = when { + question.multiSelect -> (picked + listOfNotNull(extra.takeIf { it.isNotEmpty() })).takeIf { it.isNotEmpty() }?.let { JsonArray(it.map(::JsonPrimitive)).toString() } + extra.isNotEmpty() -> extra + else -> picked.firstOrNull() + } + text?.let { question.id to it } + }.toMap() + Row { + TextButton(onClick = { onAnswer(PromptAnswer.Clarify(answers)) }, enabled = answers.size == content.questions.size, modifier = Modifier.heightIn(min = 48.dp).testTag("prompt.clarify.send")) { Text("Send answer") } + TextButton(onClick = onDecline, modifier = Modifier.heightIn(min = 48.dp).testTag("prompt.clarify.skip")) { Text("Skip") } + } +} + +@Composable +private fun SecureBody(content: PromptContent.SecureInput, onAnswer: (PromptAnswer) -> Unit, onDecline: () -> Unit) { + var secret by remember(content) { mutableStateOf("") } + var identifier by remember(content) { mutableStateOf("") } + val label = content.label ?: content.prompt ?: when (content.kind) { + SecureKind.Sudo -> "Your agent needs your computer's password" + SecureKind.VaultCode -> "Your agent needs a code" + SecureKind.VaultSaveLogin -> "Save a login for your agent?" + SecureKind.VaultUnlock -> "Your agent needs to unlock its vault" + SecureKind.Secret -> "Your agent needs a secret" + } + Text(label, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold) + listOfNotNull(content.site, content.envVar, content.backendName).takeIf { it.isNotEmpty() }?.let { + Text(it.joinToString(" · "), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Text("What you type goes to your computer only. It is not put in the chat or saved on this phone.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (content.kind == SecureKind.VaultSaveLogin) { + OutlinedTextField(identifier, { identifier = it }, label = { Text("Username or email") }, singleLine = true, shape = RoundedCornerShape(16.dp), modifier = Modifier.fillMaxWidth().testTag("prompt.secure.identifier")) + } + OutlinedTextField( + secret, { secret = it }, label = { Text(if (content.kind == SecureKind.VaultCode) "Code" else "Value") }, singleLine = true, + visualTransformation = PasswordVisualTransformation(), shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().testTag("prompt.secure.value"), + ) + Row { + TextButton( + onClick = { + // The repository clears this array after the one response; the text field's copy is dropped here. + val value = secret.toCharArray() + secret = "" + onAnswer(if (content.kind == SecureKind.VaultSaveLogin) PromptAnswer.SaveLogin(identifier, value) else PromptAnswer.Secure(value)) + }, + enabled = secret.isNotEmpty() && (content.kind != SecureKind.VaultSaveLogin || identifier.isNotBlank()), + modifier = Modifier.heightIn(min = 48.dp).testTag("prompt.secure.send"), + ) { Text("Send") } + TextButton(onClick = { secret = ""; onDecline() }, modifier = Modifier.heightIn(min = 48.dp).testTag("prompt.secure.decline")) { Text("Don't share") } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/LiveListsScreens.kt b/android/app/src/main/kotlin/app/bighelp/android/LiveListsScreens.kt new file mode 100644 index 00000000..be7dd33e --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/LiveListsScreens.kt @@ -0,0 +1,313 @@ +package app.bighelp.android + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.selection.selectable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.bighelp.android.live.LiveModel +import app.bighelp.android.live.RowStatus +import app.bighelp.android.live.SessionListing +import app.bighelp.android.live.SessionRowUi +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.SessionSummary +import kotlinx.coroutines.launch + +/** What a chat row's long-press can do, kept as data so the menu and the dialogs share one source. */ +private enum class RowAction { Rename, Archive, Delete } + +/** The Chats place for a real computer: its saved chats, newest first, with search, refresh and per-chat actions. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun LiveSessionsScreen( + live: LiveModel<*>, + onOpenChat: (ConversationRef) -> Unit, + onNewChat: () -> Unit, + onOpenArchived: () -> Unit, + onOpenPlace: (Route) -> Unit, + onSignInAgain: () -> Unit, +) { + val catalog by live.catalog.collectAsStateWithLifecycle() + val conversations by live.conversations.collectAsStateWithLifecycle() + val search by live.searchText.collectAsStateWithLifecycle() + val hits by live.contentHits.collectAsStateWithLifecycle() + val link by live.link.collectAsStateWithLifecycle() + val problem by live.reconnectProblem.collectAsStateWithLifecycle() + val pending by live.pendingCreations.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + var refreshing by remember { mutableStateOf(false) } + var menuOpen by remember { mutableStateOf(false) } + var action by remember { mutableStateOf?>(null) } + val rows = SessionListing.rows(catalog, conversations, search) + val now = System.currentTimeMillis() + + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.sessions")) { + ScreenHeader( + "Chats", + leading = { PlacesMenu(current = Route.Sessions, onOpen = onOpenPlace) }, + trailing = { + TextButton(onClick = onNewChat, modifier = Modifier.heightIn(min = 48.dp).testTag("sessions.new-chat")) { + Icon(Icons.Default.Add, contentDescription = null) + Spacer(Modifier.width(4.dp)) + Text("New chat") + } + Box { + IconButton(onClick = { menuOpen = true }, modifier = Modifier.testTag("sessions.more")) { + Icon(Icons.Default.MoreVert, contentDescription = "More") + } + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem(text = { Text("Archived chats") }, onClick = { menuOpen = false; onOpenArchived() }, modifier = Modifier.testTag("sessions.archived")) + DropdownMenuItem( + text = { Text("Refresh") }, + onClick = { menuOpen = false; scope.launch { refreshing = true; live.refresh(); refreshing = false } }, + modifier = Modifier.testTag("sessions.refresh"), + ) + } + } + }, + ) + LinkBanner(link, problem, onReconnect = live::reconnectNow, onSignInAgain = onSignInAgain, modifier = Modifier.padding(horizontal = 16.dp)) + pending.forEach { creation -> + PendingCreationBanner( + onRetry = { scope.launch { live.retryCreation(creation.profile, creation.intentId)?.let(onOpenChat) } }, + onDiscard = { scope.launch { live.discardCreation(creation.profile) } }, + ) + } + Spacer(Modifier.height(8.dp)) + BighelpSearchField( + value = search, onValueChange = live::setSearch, placeholder = "Search chats", tag = "sessions.search", + modifier = Modifier.padding(horizontal = 16.dp), + ) + Spacer(Modifier.height(4.dp)) + PullToRefreshBox( + isRefreshing = refreshing || catalog.loading, + onRefresh = { scope.launch { refreshing = true; live.refresh(); refreshing = false } }, + modifier = Modifier.weight(1f).fillMaxWidth(), + ) { + when { + rows.isEmpty() && hits.isEmpty() -> Column(Modifier.fillMaxSize()) { + when { + // Until the first read finishes or fails, the list is not known to be empty. + catalog.loadedAtMillis == null && catalog.error == null -> EmptyState("Loading your chats…", "This takes a moment.", "sessions.loading") + catalog.error != null && catalog.sessions.isEmpty() -> EmptyState( + "Couldn't load your chats", app.bighelp.android.live.LiveText.describe(catalog.error!!), "sessions.error", + ) { TextButton(onClick = { scope.launch { live.refresh() } }, modifier = Modifier.testTag("sessions.retry")) { Text("Try again") } } + search.isNotBlank() -> EmptyState("No chats match", "Nothing in your chats matches that.", "sessions.empty") + else -> EmptyState("No chats yet", "Start one with New chat. Nothing is created until you ask.", "sessions.empty") + } + } + else -> LazyColumn(Modifier.fillMaxSize().testTag("sessions.list")) { + items(rows, key = { it.ref.id }) { row -> + SessionRow(row, now, onClick = { onOpenChat(row.ref) }, onAction = { chosen -> action = chosen to row }) + } + if (hits.isNotEmpty()) { + item(key = "hits.label") { SectionLabel("Messages that match", Modifier.padding(start = 16.dp, top = 16.dp, bottom = 4.dp)) } + items(hits, key = { "hit:" + it.ref.id }) { hit -> + Column(Modifier.fillMaxWidth().clickable { onOpenChat(hit.ref) }.padding(horizontal = 16.dp, vertical = 10.dp).testTag("sessions.hit.${hit.ref.id}")) { + Text(hit.title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(hit.agentName, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(hit.snippet, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + } + } + } + } + } + action?.let { (what, row) -> + when (what) { + RowAction.Rename -> TextEntryDialog("Rename chat", row.title, "Rename", onConfirm = { title -> action = null; scope.launch { live.rename(row.ref, title) } }, onDismiss = { action = null }, tag = "dialog.rename") + RowAction.Archive -> ConfirmDialog("Archive this chat?", "It leaves the list and stays in Archived chats. You can restore it.", "Archive", { action = null; scope.launch { live.archive(row.ref) } }, { action = null }, "dialog.archive") + RowAction.Delete -> ConfirmDialog("Delete this chat?", "It is deleted from your computer. This can't be undone.", "Delete", { action = null; scope.launch { live.delete(row.ref) } }, { action = null }, "dialog.delete") + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun SessionRow(row: SessionRowUi, nowMillis: Long, onClick: () -> Unit, onAction: (RowAction) -> Unit) { + var menu by remember { mutableStateOf(false) } + Box { + Row( + Modifier.fillMaxWidth().heightIn(min = 72.dp) + .combinedClickable(onClick = onClick, onLongClick = { menu = true }) + .padding(horizontal = 16.dp, vertical = 10.dp) + .testTag("sessions.row.${row.ref.id}"), + verticalAlignment = Alignment.CenterVertically, + ) { + LiveAvatar(row.agentName, row.ref.profile) + Spacer(Modifier.width(14.dp)) + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(row.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + val time = SessionListing.relativeTime(row.lastActiveEpochSeconds, nowMillis) + if (time.isNotEmpty()) Text(time, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Text(row.agentName, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + val status = when (row.status) { + RowStatus.NeedsYou -> "Needs you" + RowStatus.Working -> "Working…" + RowStatus.Idle -> null + } + Text( + status ?: row.preview.ifEmpty { "No messages yet" }, + style = MaterialTheme.typography.bodyMedium, + fontWeight = if (status != null) FontWeight.Medium else FontWeight.Normal, + color = if (status != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + } + DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem(text = { Text("Rename") }, onClick = { menu = false; onAction(RowAction.Rename) }, modifier = Modifier.testTag("row.rename")) + DropdownMenuItem(text = { Text("Archive") }, onClick = { menu = false; onAction(RowAction.Archive) }, modifier = Modifier.testTag("row.archive")) + DropdownMenuItem(text = { Text("Delete") }, onClick = { menu = false; onAction(RowAction.Delete) }, modifier = Modifier.testTag("row.delete")) + } + } +} + +@Composable +private fun PendingCreationBanner(onRetry: () -> Unit, onDiscard: () -> Unit) { + Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp).testTag("sessions.pending")) { + Text("A new chat wasn't confirmed.", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) + Text("Retry makes the same chat again, so you never get two.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Row { + TextButton(onClick = onRetry, modifier = Modifier.testTag("sessions.pending.retry")) { Text("Retry") } + TextButton(onClick = onDiscard, modifier = Modifier.testTag("sessions.pending.discard")) { Text("Discard") } + } + } +} + +/** Chats someone archived on purpose. Restore brings one back to the list; Delete removes it from the computer. */ +@Composable +internal fun ArchivedChatsScreen(live: LiveModel<*>, onBack: () -> Unit) { + val scope = rememberCoroutineScope() + var chats by remember { mutableStateOf?>(null) } + var reload by remember { mutableIntStateOf(0) } + var deleting by remember { mutableStateOf(null) } + LaunchedEffect(reload) { chats = live.archived() ?: emptyList() } + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.archived")) { + ScreenHeader("Archived chats", leading = { BackButton(onBack) }) + val list = chats + when { + list == null -> EmptyState("Loading…", "Reading your archived chats.", "archived.loading") + list.isEmpty() -> EmptyState("Nothing archived", "Chats you archive show up here.", "archived.empty") + else -> LazyColumn(Modifier.weight(1f).testTag("archived.list")) { + items(list, key = { it.ref.id }) { chat -> + Row(Modifier.fillMaxWidth().heightIn(min = 64.dp).padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(chat.title.ifBlank { "Chat" }, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(chat.profile, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + TextButton(onClick = { scope.launch { live.restore(chat.ref); reload++ } }, modifier = Modifier.testTag("archived.restore.${chat.ref.id}")) { Text("Restore") } + TextButton(onClick = { deleting = chat }, modifier = Modifier.testTag("archived.delete.${chat.ref.id}")) { Text("Delete") } + } + } + } + } + } + deleting?.let { chat -> + ConfirmDialog("Delete this chat?", "It is deleted from your computer. This can't be undone.", "Delete", { deleting = null; scope.launch { live.delete(chat.ref); reload++ } }, { deleting = null }, "dialog.delete-archived") + } +} + +/** Agents of the open computer: pick the one new chats start with, start a chat, or open its Bot Chat. */ +@Composable +internal fun LiveAgentsScreen( + live: LiveModel<*>, + onNewChat: (String) -> Unit, + onBotChat: (String) -> Unit, + onOpenPlace: (Route) -> Unit, + onSignInAgain: () -> Unit, +) { + val catalog by live.catalog.collectAsStateWithLifecycle() + val selected by live.selectedAgentId.collectAsStateWithLifecycle() + val link by live.link.collectAsStateWithLifecycle() + val problem by live.reconnectProblem.collectAsStateWithLifecycle() + val agent = catalog.agents.firstOrNull { it.id == selected } + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.agents")) { + ScreenHeader("Agents", leading = { PlacesMenu(current = Route.Agents, onOpen = onOpenPlace) }) + LinkBanner(link, problem, onReconnect = live::reconnectNow, onSignInAgain = onSignInAgain, modifier = Modifier.padding(horizontal = 16.dp)) + Text( + "New chats start with the agent you pick.", + style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp), + ) + if (catalog.agents.isEmpty()) { + EmptyState( + if (catalog.loading) "Loading your agents…" else "No agents found", + if (catalog.error != null) app.bighelp.android.live.LiveText.describe(catalog.error!!) else "Your computer didn't list any agents yet.", + "agents.empty", + ) + } + LazyColumn(Modifier.weight(1f).testTag("agents.list")) { + items(catalog.agents.distinctBy { it.id }, key = { it.id }) { each -> + val isSelected = each.id == selected + Row( + Modifier.fillMaxWidth().heightIn(min = 72.dp) + .selectable(selected = isSelected, role = Role.RadioButton, onClick = { live.selectAgent(each.id) }) + .padding(horizontal = 16.dp, vertical = 10.dp).testTag("agents.row.${each.id}"), + verticalAlignment = Alignment.CenterVertically, + ) { + LiveAvatar(each.displayName, each.id) + Spacer(Modifier.width(14.dp)) + Column(Modifier.weight(1f)) { + Text(each.displayName.ifBlank { each.id }, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + catalog.agentErrors[each.id]?.let { + Text("Its chats couldn't be read.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + if (isSelected) Icon(Icons.Default.Check, contentDescription = "Selected") + } + } + } + if (agent != null) { + Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + InkButton("New chat with ${agent.displayName.ifBlank { agent.id }}", { onNewChat(agent.id) }, tag = "agents.new-chat") + InkOutlinedButton("Open ${agent.displayName.ifBlank { agent.id }}'s Bot Chat", { onBotChat(agent.id) }, tag = "agents.bot-chat") + } + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/LiveModelSheet.kt b/android/app/src/main/kotlin/app/bighelp/android/LiveModelSheet.kt new file mode 100644 index 00000000..745a27d2 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/LiveModelSheet.kt @@ -0,0 +1,163 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.clickable +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import app.bighelp.android.live.LiveModel +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.ModelChange +import app.bighelp.hermes.chat.ModelOptions +import kotlinx.coroutines.launch + +/** The levels offered for reasoning. The host decides which ones a model really takes and says so if not. */ +private val ReasoningLevels = listOf("" to "Auto", "low" to "Low", "medium" to "Medium", "high" to "High") + +private class ModelPick(val model: String, val provider: String, val message: String) + +/** + * The chat's own model, reasoning and speed, read back from its live session, and the host's list of choices. + * A change is shown as done only when the session reports it; a host that wants a yes first, or that queues + * the change for the next turn, says so here instead of the app pretending. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun ModelSheet(live: LiveModel<*>, ref: ConversationRef, state: ConversationState, onDismiss: () -> Unit) { + val scope = rememberCoroutineScope() + var options by remember { mutableStateOf(null) } + var failed by remember { mutableStateOf(false) } + var reload by remember { mutableIntStateOf(0) } + var confirm by remember { mutableStateOf(null) } + var info by remember { mutableStateOf(null) } + LaunchedEffect(reload) { + val read = live.modelOptions(ref) + options = read + failed = read == null + } + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp).testTag("sheet.model"), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text("Model and speed", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + val current = options + when { + current != null -> { + Text( + "Using ${current.model}" + (current.provider?.let { " from $it" } ?: ""), + style = MaterialTheme.typography.bodyLarge, modifier = Modifier.testTag("sheet.model.current"), + ) + info?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.testTag("sheet.model.info")) } + if (current.running || state.running) { + Text("A turn is running. The host may start a new model with the next turn.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + SectionLabel("Reasoning") + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + ReasoningLevels.forEach { (level, label) -> + FilterChip( + selected = current.reasoningEffort.equals(level, ignoreCase = true), + onClick = { scope.launch { live.setReasoning(ref, level); reload++ } }, + label = { Text(label) }, + modifier = Modifier.heightIn(min = 48.dp).testTag("sheet.reasoning.${level.ifEmpty { "auto" }}"), + ) + } + } + current.isFast?.let { fast -> + Row( + Modifier.fillMaxWidth().heightIn(min = 52.dp) + .toggleable(value = fast, role = Role.Switch, onValueChange = { scope.launch { live.setFast(ref, it); reload++ } }) + .testTag("sheet.fast"), + verticalAlignment = Alignment.CenterVertically, + ) { + Text("Fast mode", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f)) + Switch( + checked = fast, onCheckedChange = null, + colors = SwitchDefaults.colors(checkedTrackColor = Bighelp.colors.switchOn, checkedThumbColor = Color.White, checkedBorderColor = Bighelp.colors.switchOn), + ) + } + } + SectionLabel("Models") + val choices = current.providers.flatMap { provider -> provider.models.map { provider to it } } + if (choices.isEmpty()) Text("Your computer didn't list other models.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + LazyColumn(Modifier.heightIn(max = 360.dp).testTag("sheet.model.list")) { + items(choices, key = { (provider, model) -> provider.id + "\u0000" + model }) { (provider, model) -> + val selected = model == current.model && (current.provider == null || current.provider == provider.id) + Row( + Modifier.fillMaxWidth().heightIn(min = 52.dp) + .clickable { + scope.launch { + when (val result = live.setModel(ref, model, provider.id, confirmed = false)) { + is ModelChange.Confirmed -> { info = null; reload++ } + is ModelChange.NeedsConfirmation -> confirm = ModelPick(model, provider.id, result.message) + is ModelChange.Deferred -> { info = result.message; reload++ } + null -> Unit + } + } + } + .testTag("sheet.model.choice.$model"), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(model, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, style = MaterialTheme.typography.bodyLarge) + Text(provider.name, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (selected) Text("In use", style = MaterialTheme.typography.labelMedium) + } + } + } + } + failed -> { + Text("Couldn't read the model choices.", style = MaterialTheme.typography.bodyMedium) + TextButton(onClick = { failed = false; reload++ }, modifier = Modifier.testTag("sheet.model.retry")) { Text("Try again") } + } + else -> Text("Reading what your computer offers…", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + TextButton(onClick = onDismiss, modifier = Modifier.heightIn(min = 48.dp).testTag("sheet.model.done")) { Text("Done") } + } + } + confirm?.let { pick -> + ConfirmDialog( + "Switch model?", pick.message, "Switch", + onConfirm = { + confirm = null + scope.launch { + when (val result = live.setModel(ref, pick.model, pick.provider, confirmed = true)) { + is ModelChange.Deferred -> { info = result.message; reload++ } + is ModelChange.Confirmed -> { info = null; reload++ } + is ModelChange.NeedsConfirmation, null -> Unit + } + } + }, + onDismiss = { confirm = null }, tag = "dialog.model-confirm", + ) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/LiveSettings.kt b/android/app/src/main/kotlin/app/bighelp/android/LiveSettings.kt new file mode 100644 index 00000000..148bf05d --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/LiveSettings.kt @@ -0,0 +1,185 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.bighelp.android.live.ComputerConnectionState +import app.bighelp.android.live.ComputerLink +import app.bighelp.android.live.ComputerPhase +import app.bighelp.android.live.LiveModel +import app.bighelp.android.live.SavedComputer +import java.util.UUID + +/** One line saying where a saved computer stands, from the connection itself and nothing else. */ +private fun statusOf(computer: SavedComputer, connection: ComputerConnectionState, link: ComputerLink?): String = when { + !computer.setupComplete -> "Sign-in not finished" + computer.id != connection.selectedID -> "Saved" + connection.phase == ComputerPhase.SignInRequired -> "Sign in again" + connection.phase == ComputerPhase.Connecting || connection.phase == ComputerPhase.Loading -> "Connecting…" + connection.phase == ComputerPhase.Failed -> "Couldn't connect" + connection.phase == ComputerPhase.Connected -> when (link) { + ComputerLink.Connected -> "Connected" + ComputerLink.Reconnecting -> "Reconnecting…" + ComputerLink.Offline -> "Not connected" + ComputerLink.SignInRequired -> "Sign in again" + ComputerLink.Connecting, null -> "Connecting…" + } + else -> "Saved" +} + +/** Saved computers with what can be done with each. Used by Welcome (to open one) and Settings (to manage them). */ +@Composable +internal fun SavedComputersCard( + live: LiveModel<*>, + onSignInAgain: (UUID) -> Unit, + modifier: Modifier = Modifier, + manage: Boolean = false, +) { + val connection by live.connections.state.collectAsStateWithLifecycle() + val link by live.link.collectAsStateWithLifecycle() + var removing by remember { mutableStateOf(null) } + if (connection.computers.isEmpty()) return + Column(modifier.fillMaxWidth().testTag("computers.list"), verticalArrangement = Arrangement.spacedBy(8.dp)) { + connection.computers.forEach { computer -> + val isOpen = computer.id == connection.selectedID && connection.phase == ComputerPhase.Connected + Surface(color = MaterialTheme.colorScheme.surfaceContainer, shape = RoundedCornerShape(16.dp), modifier = Modifier.fillMaxWidth().testTag("computers.row.${computer.id}")) { + Column(Modifier.padding(start = 16.dp, end = 8.dp, top = 12.dp, bottom = 4.dp)) { + Text(computer.name, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(computer.endpoint.canonical, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(statusOf(computer, connection, link), style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(top = 2.dp).testTag("computers.status.${computer.id}")) + Row { + if (!isOpen && computer.setupComplete) { + TextButton(onClick = { live.select(computer.id) }, modifier = Modifier.heightIn(min = 48.dp).testTag("computers.open.${computer.id}")) { Text("Open") } + } + if (!computer.setupComplete || connection.phase == ComputerPhase.SignInRequired && computer.id == connection.selectedID) { + TextButton(onClick = { onSignInAgain(computer.id) }, modifier = Modifier.heightIn(min = 48.dp).testTag("computers.sign-in.${computer.id}")) { Text("Sign in") } + } + if (manage) { + TextButton(onClick = { removing = computer }, modifier = Modifier.heightIn(min = 48.dp).testTag("computers.remove.${computer.id}")) { Text("Remove") } + } + } + } + } + } + } + removing?.let { computer -> + ConfirmDialog( + "Remove ${computer.name}?", + "Its sign-in, access details and chats saved on this phone are deleted. Nothing is deleted on the computer itself.", + "Remove", { removing = null; live.remove(computer.id) }, { removing = null }, "dialog.remove-computer", + ) + } +} + +/** What Settings shows only while a real computer is open: its computers, the person's name and Nerd Mode. */ +@Composable +internal fun ColumnScope.LiveSettingsSections(model: BighelpAppModel, live: LiveModel<*>, state: AppState) { + val connection by live.connections.state.collectAsStateWithLifecycle() + val link by live.link.collectAsStateWithLifecycle() + val chat by live.chat.collectAsStateWithLifecycle() + SectionLabel("Computers") + SavedComputersCard(live, onSignInAgain = model::signInAgain, manage = true) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = model::connectComputer, modifier = Modifier.heightIn(min = 48.dp).testTag("settings.add-computer")) { Text("Add a computer") } + if (connection.phase == ComputerPhase.Connected) { + TextButton(onClick = { live.disconnect() }, modifier = Modifier.heightIn(min = 48.dp).testTag("settings.disconnect")) { Text("Close this computer") } + } + } + + Spacer(Modifier.height(16.dp)) + SectionLabel("You") + NameField(state.userName, model::setUserName) + Text( + "Saved on this phone. It isn't sent to your computer yet.", + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp), + ) + + Spacer(Modifier.height(16.dp)) + SectionLabel("Advanced") + Row( + Modifier.fillMaxWidth().heightIn(min = 52.dp).toggleable(value = state.nerdMode, role = Role.Switch, onValueChange = model::setNerdMode).testTag("settings.nerd-mode"), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f).padding(horizontal = 4.dp)) { + Text("Nerd Mode", style = MaterialTheme.typography.bodyLarge) + Text("Shows connection details for your computer.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Switch( + checked = state.nerdMode, onCheckedChange = null, + colors = SwitchDefaults.colors(checkedTrackColor = Bighelp.colors.switchOn, checkedThumbColor = Color.White, checkedBorderColor = Bighelp.colors.switchOn), + ) + } + if (state.nerdMode) { + val status = chat?.connection?.collectAsStateWithLifecycle()?.value + val active = connection.computers.firstOrNull { it.id == connection.selectedID } + Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp).testTag("settings.connection-details"), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Detail("Address", active?.endpoint?.canonical ?: "None open") + Detail("Link", link?.name ?: "None") + Detail("Socket", status?.let { "${it.gateway.name}, number ${it.generation}" } ?: "None") + Detail("One writer per chat", when (status?.exclusiveSubmit) { true -> "Guaranteed by your computer"; false -> "Not guaranteed, sending is off"; null -> "Not known yet" }) + status?.lastFailure?.let { Detail("Last problem", app.bighelp.android.live.LiveText.describe(it)) } + } + TextButton(onClick = live::reconnectNow, modifier = Modifier.heightIn(min = 48.dp).testTag("settings.reconnect")) { Text("Reconnect now") } + } + Spacer(Modifier.height(8.dp)) + HorizontalDivider() + Spacer(Modifier.height(8.dp)) +} + +@Composable +private fun Detail(label: String, value: String) { + Row(Modifier.fillMaxWidth()) { + Text(label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(0.4f)) + Text(value, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(0.6f)) + } +} + +/** The text is the person's until they finish: it is saved on Done or when the box loses focus, not on every key. */ +@Composable +private fun NameField(saved: String, onSave: (String) -> Unit) { + var text by remember(saved) { mutableStateOf(saved) } + OutlinedTextField( + value = text, onValueChange = { text = it.take(MAXIMUM_TYPED_NAME) }, + label = { Text("Your name") }, singleLine = true, shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { onSave(text) }), + modifier = Modifier.fillMaxWidth().onFocusChanged { if (!it.isFocused) onSave(text) }.testTag("settings.name"), + ) +} + +private const val MAXIMUM_TYPED_NAME = 60 diff --git a/android/app/src/main/kotlin/app/bighelp/android/LiveUiParts.kt b/android/app/src/main/kotlin/app/bighelp/android/LiveUiParts.kt new file mode 100644 index 00000000..11cf4696 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/LiveUiParts.kt @@ -0,0 +1,172 @@ +package app.bighelp.android + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.bighelp.android.live.ComputerLink +import app.bighelp.android.live.LiveModel +import app.bighelp.android.live.LiveText +import app.bighelp.hermes.chat.ChatError + +private val AvatarColors = listOf(0xFF2F6FD6, 0xFF1F7A4D, 0xFF8250DF, 0xFFB5532A, 0xFF0F7C8C, 0xFFA33A6B) + +/** An agent's picture for a real computer: its first letter on a color fixed by its ID. No status is implied. */ +@Composable +internal fun LiveAvatar(name: String, id: String, modifier: Modifier = Modifier, size: Dp = 44.dp) { + val color = Color(AvatarColors[(id.hashCode() and Int.MAX_VALUE) % AvatarColors.size]) + Box(modifier.size(size).clip(CircleShape).background(color), contentAlignment = Alignment.Center) { + Text( + name.trim().take(1).uppercase().ifEmpty { "?" }, + color = Color.White, + fontWeight = FontWeight.Bold, + fontSize = (size.value * 0.42f).sp, + ) + } +} + +/** + * The strip above a live screen when the connection is not simply fine. It states what the gateway reports, + * and offers the one thing that can help: Reconnect, or signing in again when the host refused the sign-in. + */ +@Composable +internal fun LinkBanner( + link: ComputerLink?, + problem: ChatError.Kind?, + onReconnect: () -> Unit, + onSignInAgain: () -> Unit, + modifier: Modifier = Modifier, +) { + val needsSignIn = problem == ChatError.Kind.SignInRequired || link == ComputerLink.SignInRequired + val text = if (needsSignIn) LiveText.link(ComputerLink.SignInRequired) else LiveText.link(link) + if (text == null) return + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(12.dp), + modifier = modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }.testTag("link.banner"), + ) { + Row(Modifier.padding(start = 14.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { + Text(text, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f).padding(vertical = 10.dp)) + when { + needsSignIn -> TextButton(onClick = onSignInAgain, modifier = Modifier.heightIn(min = 48.dp).testTag("link.sign-in")) { Text("Sign in") } + link == ComputerLink.Offline -> TextButton(onClick = onReconnect, modifier = Modifier.heightIn(min = 48.dp).testTag("link.reconnect")) { Text("Reconnect") } + else -> Spacer(Modifier.width(12.dp)) + } + } + } +} + +/** Shows [LiveModel.notice] as a snackbar, once each. Place it in a Box over the screen. */ +@Composable +internal fun NoticeHost(live: LiveModel<*>, modifier: Modifier = Modifier) { + val notice by live.notice.collectAsStateWithLifecycle() + val host = remember { SnackbarHostState() } + LaunchedEffect(notice?.id) { + val current = notice ?: return@LaunchedEffect + host.showSnackbar(current.text) + live.dismissNotice(current.id) + } + SnackbarHost(host, modifier.testTag("notice.host")) +} + +@Composable +internal fun ConfirmDialog( + title: String, + text: String, + confirm: String, + onConfirm: () -> Unit, + onDismiss: () -> Unit, + tag: String, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { Text(text) }, + confirmButton = { TextButton(onClick = onConfirm, modifier = Modifier.testTag("$tag.confirm")) { Text(confirm) } }, + dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.testTag("$tag.cancel")) { Text("Cancel") } }, + modifier = Modifier.testTag(tag), + ) +} + +@Composable +internal fun TextEntryDialog( + title: String, + initial: String, + confirm: String, + onConfirm: (String) -> Unit, + onDismiss: () -> Unit, + tag: String, +) { + var value by remember { mutableStateOf(initial) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + OutlinedTextField( + value = value, + onValueChange = { value = it }, + singleLine = true, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences, imeAction = ImeAction.Done), + modifier = Modifier.fillMaxWidth().testTag("$tag.field"), + ) + }, + confirmButton = { + TextButton(onClick = { onConfirm(value.trim()) }, enabled = value.isNotBlank(), modifier = Modifier.testTag("$tag.confirm")) { Text(confirm) } + }, + dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.testTag("$tag.cancel")) { Text("Cancel") } }, + modifier = Modifier.testTag(tag), + ) +} + +/** A plain message block for an empty list or a failed load, with an optional action. */ +@Composable +internal fun EmptyState(title: String, body: String, tag: String, action: (@Composable () -> Unit)? = null) { + Column( + Modifier.fillMaxWidth().padding(24.dp).testTag(tag), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text(body, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium) + action?.invoke() + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt b/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt new file mode 100644 index 00000000..1d71186d --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt @@ -0,0 +1,96 @@ +package app.bighelp.android + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import androidx.core.net.toUri +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.viewModels +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.CreationExtras +import app.bighelp.android.live.AndroidAccessSetupStore +import app.bighelp.android.live.AndroidComputerLocalData +import app.bighelp.android.live.AndroidCredentialStore +import app.bighelp.android.live.ComputerConnectionModel +import app.bighelp.android.live.LiveModel +import app.bighelp.android.live.NetworkComputerSession +import app.bighelp.android.live.RepositoryChatService +import app.bighelp.android.live.SavedComputerStore +import app.bighelp.android.storage.AndroidChatStore +import app.bighelp.hermes.BrowserLauncher + +/** + * Keeps the app's state across rotation. The models themselves are plain Kotlin, tested without Android; this + * is the one place the real stores, the network session and the system browser are put together. The + * connection is closed (letting a refresh that is already running finish and save) when the app is finished. + */ +internal class BighelpViewModel(context: Context, preferences: PreviewPreferences, hostChecker: HostChecker) : ViewModel() { + private val live: LiveModel + val model: BighelpAppModel + + init { + val app = context.applicationContext + val chatStore = AndroidChatStore.create(app) + // Handing the page to the browser is all the sign-in needs from here. The answer comes back through the + // listener the sign-in itself opens on this phone, never through the browser or a custom link. + val browser = BrowserLauncher { url -> + app.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + val connections = ComputerConnectionModel( + SavedComputerStore.create(app), + { id -> AndroidCredentialStore.create(app, id) }, + { preferences.aiDataAgreed }, + viewModelScope, + AndroidComputerLocalData(AndroidAccessSetupStore.create(app), chatStore), + ) { id, endpoint, access, credentials, scope -> + NetworkComputerSession(id, endpoint, access, credentials, scope, browser, chatStore) + } + live = LiveModel(connections, { RepositoryChatService(it.chat) }, viewModelScope) + model = BighelpAppModel(preferences, hostChecker, viewModelScope, live) + live.start() + } + + override fun onCleared() { + live.connections.close() + } +} + +class MainActivity : ComponentActivity() { + private val viewModel: BighelpViewModel by viewModels { + object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class, extras: CreationExtras): T = + BighelpViewModel(applicationContext, SharedPreviewPreferences(applicationContext), HostDiscovery()) as T + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val versionName = packageManager.getPackageInfo(packageName, 0).versionName.orEmpty() + setContent { + BighelpApp( + model = viewModel.model, + versionName = versionName, + onOpenPrivacyPolicy = ::openPrivacyPolicy, + ) + } + } + + private fun openPrivacyPolicy() { + try { + startActivity(Intent(Intent.ACTION_VIEW, PRIVACY_POLICY_URL.toUri())) + } catch (_: ActivityNotFoundException) { + // No browser installed: the page simply can't open. + } + } + + private companion object { + const val PRIVACY_POLICY_URL = "https://bighelp.app/privacy" + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/Markdown.kt b/android/app/src/main/kotlin/app/bighelp/android/Markdown.kt new file mode 100644 index 00000000..e9f099eb --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/Markdown.kt @@ -0,0 +1,120 @@ +package app.bighelp.android + +/** One block of an agent's reply. Only what chat output really uses; anything else reads as a paragraph. */ +sealed interface MdBlock { + data class Paragraph(val text: String) : MdBlock + data class Heading(val level: Int, val text: String) : MdBlock + data class Bullets(val ordered: Boolean, val items: List) : MdBlock + data class Code(val language: String, val text: String) : MdBlock +} + +/** A run of text with the marks that apply to it. */ +data class MdSpan(val text: String, val bold: Boolean = false, val italic: Boolean = false, val code: Boolean = false) + +/** + * A small, forgiving Markdown reader for chat replies: fenced code, headings, lists, and inline bold, italic, + * code and links. It never throws and never drops text: a marker that does not match stays as typed, an unclosed + * code fence takes the rest of the message (so a reply that is still streaming does not flicker), and the + * address of a link is shown whenever its label is something else. + */ +object Markdown { + private val listItem = Regex("""^\s{0,3}(?:([-*+])|(\d{1,9})[.)])\s+(.*)$""") + private val heading = Regex("""^(#{1,6})\s+(.*)$""") + + fun blocks(text: String): List { + val result = ArrayList() + val paragraph = ArrayList() + fun flush() { + if (paragraph.isNotEmpty()) { result += MdBlock.Paragraph(paragraph.joinToString("\n")); paragraph.clear() } + } + val lines = text.lines() + var index = 0 + while (index < lines.size) { + val line = lines[index] + val trimmed = line.trim() + when { + trimmed.startsWith("```") -> { + flush() + val language = trimmed.removePrefix("```").trim() + val body = ArrayList() + index++ + while (index < lines.size && !lines[index].trim().startsWith("```")) { body += lines[index]; index++ } + result += MdBlock.Code(language, body.joinToString("\n")) + } + trimmed.isEmpty() -> flush() + heading.matches(line) -> { + flush() + val match = heading.matchEntire(line)!! + result += MdBlock.Heading(match.groupValues[1].length, match.groupValues[2].trim()) + } + listItem.matches(line) -> { + flush() + val first = listItem.matchEntire(line)!! + val ordered = first.groupValues[2].isNotEmpty() + val items = ArrayList() + var current = index + while (current < lines.size) { + val match = listItem.matchEntire(lines[current]) ?: break + if ((match.groupValues[2].isNotEmpty()) != ordered) break + items += match.groupValues[3].trim() + current++ + } + result += MdBlock.Bullets(ordered, items) + index = current - 1 + } + else -> paragraph += line.trimEnd() + } + index++ + } + flush() + return result + } + + fun spans(text: String): List { + val spans = ArrayList() + val plain = StringBuilder() + fun flushPlain() { if (plain.isNotEmpty()) { spans += MdSpan(plain.toString()); plain.clear() } } + var i = 0 + while (i < text.length) { + val c = text[i] + when { + c == '`' -> { + val end = text.indexOf('`', i + 1) + if (end > i + 1) { flushPlain(); spans += MdSpan(text.substring(i + 1, end), code = true); i = end + 1 } else { plain.append(c); i++ } + } + c == '*' && text.startsWith("**", i) -> { + val end = text.indexOf("**", i + 2) + if (end > i + 2) { flushPlain(); spans += MdSpan(text.substring(i + 2, end), bold = true); i = end + 2 } else { plain.append("**"); i += 2 } + } + c == '*' && i + 1 < text.length && !text[i + 1].isWhitespace() -> { + val end = text.indexOf('*', i + 1) + if (end > i + 1 && !text[end - 1].isWhitespace()) { flushPlain(); spans += MdSpan(text.substring(i + 1, end), italic = true); i = end + 1 } else { plain.append(c); i++ } + } + c == '[' -> { + val close = text.indexOf("](", i + 1) + val end = if (close > i) text.indexOf(')', close + 2) else -1 + if (close > i && end > close + 2 && '\n' !in text.substring(i, end)) { + val label = text.substring(i + 1, close) + val address = text.substring(close + 2, end) + plain.append(if (label == address) label else "$label ($address)") + i = end + 1 + } else { plain.append(c); i++ } + } + else -> { plain.append(c); i++ } + } + } + flushPlain() + return mergeAdjacent(spans) + } + + private fun mergeAdjacent(spans: List): List { + val merged = ArrayList() + for (span in spans) { + val last = merged.lastOrNull() + if (last != null && last.bold == span.bold && last.italic == span.italic && last.code == span.code) { + merged[merged.lastIndex] = last.copy(text = last.text + span.text) + } else merged += span + } + return merged + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/NoodleMark.kt b/android/app/src/main/kotlin/app/bighelp/android/NoodleMark.kt new file mode 100644 index 00000000..19b109c6 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/NoodleMark.kt @@ -0,0 +1,39 @@ +package app.bighelp.android + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.translate +import androidx.compose.ui.graphics.drawscope.scale +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +// The same first-party brand path as BighelpNoodleShape on Apple platforms. +private val noodlePath = Path().apply { + val k = 13.807f + moveTo(28f, 12f) + lineTo(28f, 60f) + cubicTo(28f, 60f + k, 53f - k, 85f, 53f, 85f) + cubicTo(53f + k, 85f, 78f, 60f + k, 78f, 60f) + cubicTo(78f, 60f - k, 53f + k, 35f, 53f, 35f) + cubicTo(53f - k, 35f, 28f, 60f - k, 28f, 60f) + cubicTo(28f, 80f, 22f, 90f, 8f, 94f) +} + +@Composable +fun NoodleMark(modifier: Modifier = Modifier, height: Dp = 36.dp) { + Canvas(modifier.width(height * (86f / 98f)).height(height)) { + val unit = size.height / 98f + translate(top = -4f * unit) { + scale(scaleX = unit, scaleY = unit, pivot = androidx.compose.ui.geometry.Offset.Zero) { + drawPath(noodlePath, Ember, style = Stroke(16f, cap = StrokeCap.Round, join = StrokeJoin.Round)) + } + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/PlacesMenu.kt b/android/app/src/main/kotlin/app/bighelp/android/PlacesMenu.kt new file mode 100644 index 00000000..41a3dacd --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/PlacesMenu.kt @@ -0,0 +1,50 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Menu +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +/** + * The one menu. It owns every place outside the chat list (Agents, Settings), so no screen carries a + * second menu or its own copy of these entries. Android Back closes it before anything else. + */ +@Composable +fun PlacesMenu(current: Route, onOpen: (Route) -> Unit) { + var expanded by rememberSaveable { mutableStateOf(false) } + IconButton(onClick = { expanded = true }, modifier = Modifier.size(48.dp).testTag("menu.button")) { + Icon(Icons.Default.Menu, contentDescription = "Menu") + } + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + listOf( + Triple(Route.Sessions, "Chats", "menu.chats"), + Triple(Route.Agents, "Agents", "menu.agents"), + Triple(Route.Settings, "Settings", "menu.settings"), + ).forEach { (place, label, tag) -> + val selected = place == current + DropdownMenuItem( + text = { Text(label, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal) }, + trailingIcon = { if (selected) Icon(Icons.Default.Check, contentDescription = "Current place") }, + onClick = { + expanded = false + if (!selected) onOpen(place) + }, + modifier = Modifier.testTag(tag), + ) + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt b/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt new file mode 100644 index 00000000..10a8cbd2 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt @@ -0,0 +1,55 @@ +package app.bighelp.android + +import android.content.Context +import androidx.core.content.edit + +/** + * Ordinary preferences kept on the device: the one-time AI data agreement, the look, the person's name and + * Nerd Mode. No credential, address or chat is here: sign-ins, gate details and chat records live in their own + * stores. Backup and device transfer are excluded in the manifest. + */ +interface PreviewPreferences { + var aiDataAgreed: Boolean + var appearance: Appearance + + /** The person's own name, at most 40 characters. */ + var userName: String + get() = "" + set(@Suppress("UNUSED_PARAMETER") value) {} + + /** Settings > Nerd Mode: shows the host-administration rows. */ + var nerdMode: Boolean + get() = false + set(@Suppress("UNUSED_PARAMETER") value) {} +} + +class SharedPreviewPreferences(context: Context) : PreviewPreferences { + private val preferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE) + + override var aiDataAgreed: Boolean + get() = preferences.getBoolean(AGREED_KEY, false) + set(value) = preferences.edit { putBoolean(AGREED_KEY, value) } + + override var appearance: Appearance + get() = Appearance.entries.firstOrNull { it.name == preferences.getString(APPEARANCE_KEY, null) } + ?: Appearance.Automatic + set(value) = preferences.edit { putString(APPEARANCE_KEY, value.name) } + + override var userName: String + get() = preferences.getString(NAME_KEY, null).orEmpty() + set(value) = preferences.edit { putString(NAME_KEY, value) } + + override var nerdMode: Boolean + get() = preferences.getBoolean(NERD_KEY, false) + set(value) = preferences.edit { putBoolean(NERD_KEY, value) } + + private companion object { + const val FILE = "bighelp_preview" + + /** The same key as the iPhone app. Never rename: a new key would ask everyone again. */ + const val AGREED_KEY = "bighelp.privacy.ai-data-agreed" + const val APPEARANCE_KEY = "bighelp.appearance" + const val NAME_KEY = "bighelp.user-name" + const val NERD_KEY = "bighelp.nerd-mode" + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt new file mode 100644 index 00000000..67cce8d2 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt @@ -0,0 +1,133 @@ +package app.bighelp.android + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp + +/** The Chats place: search, then the sample chats, newest activity first. */ +@Composable +fun SessionsScreen( + demo: DemoState, + onSearch: (String) -> Unit, + onOpenChat: (String) -> Unit, + onNewChat: () -> Unit, + onOpenPlace: (Route) -> Unit, +) { + val visible = demo.visibleSessions + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.sessions")) { + ScreenHeader( + "Chats", + leading = { PlacesMenu(current = Route.Sessions, onOpen = onOpenPlace) }, + trailing = { + TextButton(onClick = onNewChat, modifier = Modifier.heightIn(min = 48.dp).testTag("sessions.new-chat")) { + Icon(Icons.Default.Add, contentDescription = null) + Spacer(Modifier.width(4.dp)) + Text("New chat") + } + }, + ) + DemoBanner(Modifier.padding(horizontal = 16.dp)) + Spacer(Modifier.height(12.dp)) + BighelpSearchField( + value = demo.search, + onValueChange = onSearch, + placeholder = "Search chats", + tag = "sessions.search", + modifier = Modifier.padding(horizontal = 16.dp), + ) + Spacer(Modifier.height(4.dp)) + if (visible.isEmpty()) { + Column( + Modifier.fillMaxWidth().padding(24.dp).testTag("sessions.empty"), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text("No chats match", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text( + "Nothing in the sample chats mentions that.", + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + TextButton(onClick = { onSearch("") }, modifier = Modifier.testTag("sessions.empty.clear")) { + Text("Clear search") + } + } + } else { + LazyColumn(Modifier.weight(1f).testTag("sessions.list")) { + items(visible, key = { it.id }) { session -> + SessionRow( + session = session, + agent = demo.agent(session.agentId), + draft = demo.drafts[session.id], + onClick = { onOpenChat(session.id) }, + ) + } + } + } + } +} + +@Composable +private fun SessionRow(session: DemoSession, agent: DemoAgent, draft: String?, onClick: () -> Unit) { + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 72.dp) + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 10.dp) + .testTag("sessions.row.${session.id}"), + verticalAlignment = Alignment.CenterVertically, + ) { + AgentAvatar(agent) + Spacer(Modifier.width(14.dp)) + Column(Modifier.weight(1f)) { + Text( + session.title, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text(agent.name, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + // A box holding only spaces or new lines is not a draft worth previewing. + val draftText = draft?.trim().orEmpty() + val hasDraft = draftText.isNotEmpty() + val preview = when { + hasDraft -> "Draft: ${draftText.replace('\n', ' ')}" + session.messages.isEmpty() -> "No messages yet" + else -> session.messages.last().text.replace('\n', ' ') + } + Text( + preview, + style = MaterialTheme.typography.bodyMedium, + color = if (hasDraft) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = if (hasDraft) FontWeight.Medium else FontWeight.Normal, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt new file mode 100644 index 00000000..379c6f19 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt @@ -0,0 +1,118 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp + +/** + * The one Settings page: your computers and name (when a real computer is open, through [liveSections]), look, + * data agreement, the demo, and what this build is. There is no second settings copy anywhere else. + */ +@Composable +fun SettingsScreen( + appearance: Appearance, + consentGranted: Boolean, + versionName: String, + onAppearance: (Appearance) -> Unit, + onPrivacyPolicy: () -> Unit, + onLeaveDemo: () -> Unit, + onOpenPlace: (Route) -> Unit, + showDemo: Boolean = true, + liveSections: (@Composable ColumnScope.() -> Unit)? = null, +) { + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.settings")) { + ScreenHeader("Settings", leading = { PlacesMenu(current = Route.Settings, onOpen = onOpenPlace) }) + if (showDemo) DemoBanner(Modifier.padding(horizontal = 16.dp)) + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.TopCenter) { + Column( + Modifier + .widthIn(max = 520.dp) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + liveSections?.invoke(this) + SectionLabel("Appearance") + listOf( + Triple(Appearance.Automatic, "Same as phone", "settings.appearance.automatic"), + Triple(Appearance.Light, "Light", "settings.appearance.light"), + Triple(Appearance.Dark, "Dark", "settings.appearance.dark"), + ).forEach { (option, label, tag) -> + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 52.dp) + .selectable(selected = appearance == option, role = Role.RadioButton, onClick = { onAppearance(option) }) + .testTag(tag), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = appearance == option, onClick = null, modifier = Modifier.padding(horizontal = 12.dp)) + Text(label, style = MaterialTheme.typography.bodyLarge) + } + } + + Spacer(Modifier.height(16.dp)) + SectionLabel("Your data and AI") + Text( + if (consentGranted) "You agreed to share chat data with your computer and its AI providers." + else "Not agreed yet. bighelp asks before it connects to a computer.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp).testTag("settings.consent-status"), + ) + TextButton(onClick = onPrivacyPolicy, modifier = Modifier.testTag("settings.privacy")) { + Text("Privacy policy") + } + + if (showDemo) { + Spacer(Modifier.height(8.dp)) + HorizontalDivider() + Spacer(Modifier.height(8.dp)) + SectionLabel("Demo") + Text( + "You are looking at sample chats. Leaving the demo clears them and any unsent drafts.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp), + ) + InkOutlinedButton("Leave demo", onLeaveDemo, tag = "settings.leave-demo") + } + + Spacer(Modifier.height(16.dp)) + SectionLabel("About") + Text( + "bighelp for Android $versionName. Chat with your own agents on your Hermes computer. " + + "Files, Feed, Projects and the other Hermes tools are not in this build yet.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp).testTag("settings.about"), + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt new file mode 100644 index 00000000..423afe9c --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt @@ -0,0 +1,311 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.selection.selectable +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.TextButton +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import app.bighelp.hermes.HermesEndpointException + +/** + * Asks a typed address whether a Hermes computer answers, with the gate details the person may have to give + * first. A found computer is not a connection: signing in comes next ([onContinue]). Without a live model (the + * demo alone) it is only the public status check and offers the demo. + */ +@Composable +fun SetupScreen( + setup: SetupState, + onBack: () -> Unit, + onAddress: (String) -> Unit, + onAllowPrivateHttp: (Boolean) -> Unit, + onCheck: () -> Unit, + onCancel: () -> Unit, + onTryDemo: () -> Unit, + live: Boolean = false, + onAccess: (AccessInput) -> Unit = {}, + onContinue: () -> Unit = {}, +) { + val checking = setup.discovery == DiscoveryState.Checking + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.setup")) { + ScreenHeader("Connect your computer", leading = { BackButton(onBack) }) + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.TopCenter) { + Column( + Modifier + .widthIn(max = 520.dp) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text( + "Enter the web address of your Hermes computer, the one you open in a browser.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedTextField( + value = setup.address, + onValueChange = onAddress, + label = { Text("Computer address") }, + placeholder = { Text("hermes.example.com") }, + singleLine = true, + readOnly = checking, + shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Go, + ), + keyboardActions = KeyboardActions(onGo = { onCheck() }), + modifier = Modifier.fillMaxWidth().testTag("setup.address"), + ) + PrivateHttpRow(setup.allowPrivateHttp, enabled = !checking, onChange = onAllowPrivateHttp) + if (live) ExtraAccessSection(setup.access, enabled = !checking, onChange = onAccess) + + if (checking) { + InkButton("Checking…", onClick = {}, tag = "setup.check", enabled = false) + InkOutlinedButton("Cancel", onCancel, tag = "setup.cancel") + } else { + InkButton("Check computer", onCheck, tag = "setup.check", enabled = setup.address.isNotBlank()) + } + + DiscoveryResultCard(setup.discovery, setup.allowPrivateHttp, live = live, onCheck = onCheck, onTryDemo = onTryDemo, onContinue = onContinue) + Spacer(Modifier.height(8.dp)) + } + } + } +} + +@Composable +private fun PrivateHttpRow(checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainer, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth(), + ) { + // The whole row is the switch, so its words are what a screen reader announces. + Row( + Modifier + .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onChange) + .padding(start = 16.dp, end = 12.dp, top = 12.dp, bottom = 12.dp) + .testTag("setup.private-http"), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f).padding(end = 12.dp)) { + Text("Private network, plain HTTP", fontWeight = FontWeight.SemiBold) + Text( + "Only for an address inside your home, office, VPN or Tailscale network. Anyone on " + + "that network can read plain HTTP traffic.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch( + checked = checked, + onCheckedChange = null, + enabled = enabled, + colors = SwitchDefaults.colors( + checkedTrackColor = Bighelp.colors.switchOn, + checkedThumbColor = Color.White, + checkedBorderColor = Bighelp.colors.switchOn, + ), + ) + } + } +} + +@Composable +private fun DiscoveryResultCard( + discovery: DiscoveryState, + allowPrivateHttp: Boolean, + live: Boolean, + onCheck: () -> Unit, + onTryDemo: () -> Unit, + onContinue: () -> Unit, +) { + when (discovery) { + DiscoveryState.Idle, DiscoveryState.Checking -> Unit + + is DiscoveryState.Refused -> ResultCard( + title = "Couldn't use this computer", + body = discovery.message, + tag = "setup.result.refused", + ) { + InkOutlinedButton("Check again", onCheck, tag = "setup.check-again") + } + + is DiscoveryState.AddressProblem -> ResultCard( + title = "That address can't be used", + body = when (discovery.reason) { + // With the switch already on, the address itself is the problem, so don't send them to the switch. + HermesEndpointException.Reason.PlaintextNotAllowed -> + if (allowPrivateHttp) { + "Plain http:// works only for an address inside your own network, like " + + "192.168.1.20, and this one is not. Use https:// instead." + } else { + "Plain http:// works only inside your own network. Turn on the private network " + + "switch for an address like 192.168.1.20, or use https://." + } + HermesEndpointException.Reason.InvalidEndpoint, HermesEndpointException.Reason.InvalidRoute -> + "Use a name or number like hermes.example.com or 192.168.1.20:9119, with no spaces, " + + "username, password or question mark." + }, + tag = "setup.result.problem", + ) + + is DiscoveryState.Unavailable -> ResultCard( + title = "No Hermes computer answered", + body = "Nothing usable came back from ${discovery.address}. Check the address, that the " + + "computer is on, and that this phone can reach it.", + tag = "setup.result.unavailable", + ) { + InkOutlinedButton("Check again", onCheck, tag = "setup.check-again") + } + + is DiscoveryState.Found -> ResultCard( + title = "Found a Hermes computer", + body = buildString { + append(discovery.address).append("\n\n") + append(if (discovery.authRequired) "It asks for a sign-in." else "It does not ask for a sign-in.") + if (discovery.authRequired) { + append(if (discovery.browserSignIn) " Browser sign-in is offered." else " Browser sign-in is not offered.") + } + if (live) append("\n\nNext, choose how to sign in. Nothing has been sent but the check.") + else append("\n\nThis is not a connection. This build only checked that a computer answers.") + }, + tag = "setup.result.found", + ) { + if (live) InkButton("Sign in", onContinue, tag = "setup.sign-in") + InkOutlinedButton("Check again", onCheck, tag = "setup.check-again") + if (!live) InkButton("Try the demo meanwhile", onTryDemo, tag = "setup.demo") + } + } +} + +@Composable +private fun ResultCard( + title: String, + body: String, + tag: String, + actions: @Composable () -> Unit = {}, +) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(16.dp), + // The card appears or changes after a check; polite means a screen reader announces it without interrupting. + modifier = Modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }.testTag(tag), + ) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) + Text(body, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + actions() + } + } +} + +/** + * What guards the address before Hermes does: a Cloudflare Access token, a proxy login, and any custom headers + * a proxy wants. Closed by default; needed only when the check says the access details were refused. + */ +@Composable +private fun ExtraAccessSection(access: AccessInput, enabled: Boolean, onChange: (AccessInput) -> Unit) { + var open by rememberSaveable { mutableStateOf(access.kind != AccessKind.None || access.headers.isNotEmpty()) } + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = { open = !open }, modifier = Modifier.testTag("setup.access-toggle")) { + Text(if (open) "Hide extra access details" else "Extra access details (optional)") + } + if (!open) return + Text( + "Only if something in front of your computer asks for it, like a company login or a Cloudflare access token. These are kept on this phone, sealed, and sent only to this address.", + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + listOf(AccessKind.None to "None", AccessKind.Cloudflare to "Cloudflare access token", AccessKind.ProxyLogin to "Username and password").forEach { (kind, label) -> + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .selectable(selected = access.kind == kind, enabled = enabled, role = Role.RadioButton, onClick = { onChange(access.copy(kind = kind)) }) + .testTag("setup.access.${kind.name}"), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = access.kind == kind, onClick = null, enabled = enabled, modifier = Modifier.padding(horizontal = 12.dp)) + Text(label) + } + } + if (access.kind != AccessKind.None) { + OutlinedTextField( + value = access.id, onValueChange = { onChange(access.copy(id = it)) }, enabled = enabled, singleLine = true, + label = { Text(if (access.kind == AccessKind.Cloudflare) "Client ID" else "Username") }, shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, capitalization = KeyboardCapitalization.None), + modifier = Modifier.fillMaxWidth().testTag("setup.access.id"), + ) + OutlinedTextField( + value = access.secret, onValueChange = { onChange(access.copy(secret = it)) }, enabled = enabled, singleLine = true, + label = { Text(if (access.kind == AccessKind.Cloudflare) "Client secret" else "Password") }, shape = RoundedCornerShape(16.dp), + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, keyboardType = KeyboardType.Password), + modifier = Modifier.fillMaxWidth().testTag("setup.access.secret"), + ) + } + SectionLabel("Custom headers") + access.headers.forEachIndexed { index, (name, value) -> + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = name, onValueChange = { onChange(access.copy(headers = access.headers.toMutableList().also { list -> list[index] = it to value })) }, + enabled = enabled, singleLine = true, label = { Text("Name") }, shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, capitalization = KeyboardCapitalization.None), + modifier = Modifier.weight(1f).testTag("setup.access.header-name.$index"), + ) + OutlinedTextField( + value = value, onValueChange = { onChange(access.copy(headers = access.headers.toMutableList().also { list -> list[index] = name to it })) }, + enabled = enabled, singleLine = true, label = { Text("Value") }, shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, capitalization = KeyboardCapitalization.None), + modifier = Modifier.weight(1f).testTag("setup.access.header-value.$index"), + ) + TextButton(onClick = { onChange(access.copy(headers = access.headers.filterIndexed { i, _ -> i != index })) }, enabled = enabled, modifier = Modifier.testTag("setup.access.header-remove.$index")) { Text("Remove") } + } + } + if (access.headers.size < 16) { + TextButton(onClick = { onChange(access.copy(headers = access.headers + ("" to ""))) }, enabled = enabled, modifier = Modifier.testTag("setup.access.header-add")) { Text("Add a header") } + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/SignInScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SignInScreen.kt new file mode 100644 index 00000000..64662972 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SignInScreen.kt @@ -0,0 +1,223 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import app.bighelp.android.live.ComputerConnectionState +import app.bighelp.android.live.ComputerPhase +import app.bighelp.android.live.LiveText +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.SignInInput + +/** + * Choosing how to sign in to the computer that was just checked, using only what the host itself offered: + * the dashboard's own session, a password for a password sign-in, a browser sign-in, or a token the person + * already has. Typed secrets live in plain `remember` state, never in saved state, and are dropped when the + * screen goes. + */ +@Composable +internal fun SignInScreen( + connection: ComputerConnectionState, + defaultName: String, + onSignIn: (name: String, input: SignInInput) -> Unit, + onBack: () -> Unit, +) { + val status = connection.authStatus + var name by remember(defaultName) { mutableStateOf(defaultName) } + var waitingForBrowser by remember { mutableStateOf(false) } + val busy = connection.phase == ComputerPhase.Discovering || connection.phase == ComputerPhase.Connecting + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.sign-in")) { + ScreenHeader("Sign in", leading = { BackButton(onBack) }) + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.TopCenter) { + Column( + Modifier.widthIn(max = 520.dp).fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + label = { Text("Name this computer") }, + singleLine = true, + enabled = !busy, + shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Next), + modifier = Modifier.fillMaxWidth().testTag("signin.name"), + ) + FailureNote(connection) + when { + busy -> BusyNote(waitingForBrowser, connection.phase) + status == null -> Text("Check the computer first.", color = MaterialTheme.colorScheme.onSurfaceVariant) + else -> { + SignInMethods( + status = status, + onChoose = { input -> + waitingForBrowser = input is SignInInput.Browser + onSignIn(name, input) + }, + ) + } + } + Spacer(Modifier.height(8.dp)) + } + } + } +} + +@Composable +private fun FailureNote(connection: ComputerConnectionState) { + val text = connection.authFailure?.let(LiveText::describe) ?: connection.problem?.let(LiveText::problem) + if (text == null || connection.phase == ComputerPhase.Discovering || connection.phase == ComputerPhase.Connecting) return + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }.testTag("signin.failure"), + ) { + Text(text, modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.bodyMedium) + } +} + +@Composable +private fun BusyNote(waitingForBrowser: Boolean, phase: ComputerPhase) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainer, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }.testTag("signin.busy"), + ) { + Text( + when { + waitingForBrowser && phase == ComputerPhase.Connecting -> "Finish signing in in your browser, then come back here." + phase == ComputerPhase.Discovering -> "Checking how this computer signs people in…" + else -> "Connecting…" + }, + modifier = Modifier.padding(16.dp), + style = MaterialTheme.typography.bodyMedium, + ) + } +} + +@Composable +private fun SignInMethods(status: AuthStatus, onChoose: (SignInInput) -> Unit) { + var tokenOpen by remember { mutableStateOf(false) } + if (!status.authRequired) { + Text( + "This computer doesn't ask for a password. bighelp can use its own session.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + InkButton("Connect", { onChoose(SignInInput.Dashboard) }, tag = "signin.dashboard") + } else { + val passwordProviders = status.passwordProviders + if (passwordProviders.isNotEmpty()) PasswordForm(status, onChoose) + if (status.supportsNativePkce) { + SectionLabel("Browser") + if (status.browserProviders.isEmpty()) { + InkOutlinedButton("Sign in with your browser", { onChoose(SignInInput.Browser(null)) }, tag = "signin.browser") + } else { + status.browserProviders.forEach { provider -> + InkOutlinedButton("Continue with ${provider.displayName}", { onChoose(SignInInput.Browser(provider.name)) }, tag = "signin.browser.${provider.name}") + } + } + } + if (passwordProviders.isEmpty() && !status.supportsNativePkce) { + Text( + "This computer asks for a sign-in this app can't start by itself. If you have an access token, use it below.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + TextButton(onClick = { tokenOpen = !tokenOpen }, modifier = Modifier.testTag("signin.token-toggle")) { + Text(if (tokenOpen) "Hide the token box" else "Use an access token instead") + } + if (tokenOpen) TokenForm(onChoose) +} + +@Composable +private fun PasswordForm(status: AuthStatus, onChoose: (SignInInput) -> Unit) { + val providers = status.passwordProviders + var provider by remember { mutableStateOf(providers.firstOrNull()?.name) } + var username by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + SectionLabel("Password") + if (providers.size > 1) { + providers.forEach { option -> + Row( + Modifier.fillMaxWidth().heightIn48().selectable(selected = provider == option.name, role = Role.RadioButton, onClick = { provider = option.name }).testTag("signin.provider.${option.name}"), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = provider == option.name, onClick = null, modifier = Modifier.padding(horizontal = 12.dp)) + Text(option.displayName) + } + } + } + OutlinedTextField( + value = username, onValueChange = { username = it }, label = { Text("Username") }, singleLine = true, + shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, capitalization = KeyboardCapitalization.None, imeAction = ImeAction.Next), + modifier = Modifier.fillMaxWidth().testTag("signin.username"), + ) + OutlinedTextField( + value = password, onValueChange = { password = it }, label = { Text("Password") }, singleLine = true, + visualTransformation = PasswordVisualTransformation(), shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, keyboardType = KeyboardType.Password, imeAction = ImeAction.Go), + modifier = Modifier.fillMaxWidth().testTag("signin.password"), + ) + InkButton( + "Sign in", + { onChoose(SignInInput.Password(provider, username, password)); password = "" }, + tag = "signin.password-submit", + enabled = username.isNotBlank() && password.isNotEmpty(), + ) +} + +@Composable +private fun TokenForm(onChoose: (SignInInput) -> Unit) { + var token by remember { mutableStateOf("") } + OutlinedTextField( + value = token, onValueChange = { token = it }, label = { Text("Access token") }, singleLine = true, + visualTransformation = PasswordVisualTransformation(), shape = RoundedCornerShape(16.dp), + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, keyboardType = KeyboardType.Password, imeAction = ImeAction.Go), + modifier = Modifier.fillMaxWidth().testTag("signin.token"), + ) + InkButton("Use this token", { onChoose(SignInInput.Token(token.trim())); token = "" }, tag = "signin.token-submit", enabled = token.isNotBlank()) +} + +private fun Modifier.heightIn48(): Modifier = this.then(Modifier.heightIn(min = 48.dp)) diff --git a/android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt b/android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt new file mode 100644 index 00000000..539d256f --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt @@ -0,0 +1,96 @@ +package app.bighelp.android + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Lock +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp + +/** First screen: the demo works with nothing set up; connecting signs in to a real computer. [extra] shows saved computers. */ +@Composable +fun WelcomeScreen(onTryDemo: () -> Unit, onConnect: () -> Unit, extra: @Composable () -> Unit = {}) { + ScrollingPage(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.welcome")) { + NoodleMark(height = 96.dp) + Spacer(Modifier.height(16.dp)) + Text("bighelp", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) + Spacer(Modifier.height(8.dp)) + Text( + "Text your own AI agents, like texting a friend.", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(32.dp)) + extra() + InkButton("Try the demo", onTryDemo, tag = "welcome.demo") + Spacer(Modifier.height(6.dp)) + Text( + "Sample chats that stay on this phone.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(24.dp)) + InkOutlinedButton("Connect your computer", onConnect, tag = "welcome.connect") + Spacer(Modifier.height(6.dp)) + Text( + "Sign in to your Hermes computer and chat with your own agents.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } +} + +/** The one-time agreement. Nothing reaches a computer before it is given. */ +@Composable +fun ConsentScreen(onAgree: () -> Unit, onNotNow: () -> Unit, onPrivacyPolicy: () -> Unit) { + ScrollingPage(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.consent")) { + Icon( + Icons.Outlined.Lock, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(bottom = 4.dp), + ) + Spacer(Modifier.height(12.dp)) + Text( + "Your data and AI", + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(12.dp)) + Text( + "bighelp is a window onto the Hermes computer you choose. What you share in chat, like " + + "messages, files or voice, goes to that computer and on to the AI providers you set up there.", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(12.dp)) + Text( + "Nothing is sent until you agree. Your sign-in stays on this phone, sealed.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(28.dp)) + InkButton("Agree and continue", onAgree, tag = "consent.agree") + TextButton(onClick = onPrivacyPolicy, modifier = Modifier.testTag("consent.privacy")) { + Text("Privacy policy") + } + TextButton(onClick = onNotNow, modifier = Modifier.testTag("consent.not-now")) { Text("Not now") } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/AccessSetup.kt b/android/app/src/main/kotlin/app/bighelp/android/live/AccessSetup.kt new file mode 100644 index 00000000..b7322c27 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/AccessSetup.kt @@ -0,0 +1,153 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.AndroidCredentialKey +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.android.storage.RecordStorageException +import app.bighelp.android.storage.StorageProblem +import app.bighelp.android.storage.AndroidChatStore +import app.bighelp.hermes.AccessCredential +import app.bighelp.hermes.AccessHeaders +import app.bighelp.hermes.CustomHeader +import app.bighelp.hermes.HermesEndpoint +import java.io.File +import java.util.UUID +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.contentOrNull + +/** + * What guards a computer's address before Hermes does: a Cloudflare Access token, a proxy login and/or custom + * proxy headers. It belongs to the computer, not to a sign-in, and travels only to that computer's address. + * Its secrets never appear in [toString]. + */ +internal class AccessSetup(val credential: AccessCredential?, val custom: List) { + val isEmpty: Boolean get() = credential == null && custom.isEmpty() + + /** @throws app.bighelp.hermes.HermesException when the credential cannot be sent to [endpoint] (Cloudflare needs HTTPS). */ + fun headers(endpoint: HermesEndpoint): AccessHeaders = AccessHeaders.of(endpoint, credential, custom) + + override fun equals(other: Any?) = other is AccessSetup && credential == other.credential && custom == other.custom + override fun hashCode() = credential.hashCode() * 31 + custom.hashCode() + override fun toString() = "AccessSetup(credential=${credential?.kind}, headers=${custom.size})" + + companion object { + val None = AccessSetup(null, emptyList()) + } +} + +/** Everything the phone keeps for one computer besides its sign-in and its row: gate details and chat records. */ +internal interface ComputerLocalData { + suspend fun loadAccess(id: UUID): AccessSetup + suspend fun saveAccess(id: UUID, access: AccessSetup) + + /** Removing a computer removes this too. Safe to run again. */ + suspend fun forget(id: UUID) + + object None : ComputerLocalData { + override suspend fun loadAccess(id: UUID) = AccessSetup.None + override suspend fun saveAccess(id: UUID, access: AccessSetup) = Unit + override suspend fun forget(id: UUID) = Unit + } +} + +internal fun accessRecordKey(id: UUID): String = buildJsonArray { + add(JsonPrimitive("bighelp.access.v1")) + add(JsonPrimitive(id.toString())) +}.toString() + +/** Gate details sealed with the same device key as sign-ins, one record per computer, backup-excluded. */ +internal class AndroidAccessSetupStore( + private val records: ProtectedRecordStore, + private val dispatcher: CoroutineDispatcher = Dispatchers.IO, +) { + suspend fun loadAccess(id: UUID): AccessSetup = withContext(dispatcher) { + val raw = records.read(accessRecordKey(id)) ?: return@withContext AccessSetup.None + try { decode(raw) } finally { raw.fill(0) } + } + + suspend fun saveAccess(id: UUID, access: AccessSetup) = withContext(dispatcher) { + val key = accessRecordKey(id) + val current = records.read(key) + try { + val next = if (access.isEmpty) null else encode(access) + try { + if (!records.compareAndSet(key, current, next)) throw RecordStorageException(StorageProblem.DiskUnavailable) + } finally { next?.fill(0) } + } finally { current?.fill(0) } + } + + suspend fun deleteAccess(id: UUID) = saveAccess(id, AccessSetup.None) + + private fun encode(access: AccessSetup): ByteArray = buildJsonObject { + put("schemaVersion", 1) + access.credential?.let { credential -> + put("credential", buildJsonObject { + put("kind", credential.kind.name) + put("clientId", credential.clientId) + put("clientSecret", credential.clientSecret) + }) + } + put("custom", buildJsonArray { + for (header in access.custom) add(buildJsonObject { put("name", header.name); put("value", header.value) }) + }) + }.toString().toByteArray(Charsets.UTF_8) + + private fun decode(bytes: ByteArray): AccessSetup { + try { + val root = Json.parseToJsonElement(bytes.toString(Charsets.UTF_8)) as? JsonObject ?: throw unreadable() + val version = root["schemaVersion"] as? JsonPrimitive + if (version == null || version.isString || version.intOrNull != 1) throw unreadable() + val credential = (root["credential"] as? JsonObject)?.let { value -> + val id = text(value, "clientId") + val secret = text(value, "clientSecret") + when (text(value, "kind")) { + AccessCredential.Kind.CloudflareAccess.name -> AccessCredential.cloudflareAccess(id, secret) + AccessCredential.Kind.ProxyBasic.name -> AccessCredential.proxyBasic(id, secret) + else -> throw unreadable() + } + } + val custom = (root["custom"] as? JsonArray ?: throw unreadable()).map { row -> + val value = row as? JsonObject ?: throw unreadable() + CustomHeader.of(text(value, "name"), text(value, "value")) + } + return AccessSetup(credential, custom) + } catch (failure: RecordStorageException) { + throw failure + } catch (_: Exception) { + throw unreadable() + } + } + + private fun text(value: JsonObject, key: String): String = + (value[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull ?: throw unreadable() + + private fun unreadable() = RecordStorageException(StorageProblem.CorruptRecord) + + companion object { + fun create(context: android.content.Context) = AndroidAccessSetupStore( + ProtectedRecordStore(File(context.noBackupFilesDir, "access-headers"), RecordCipher(AndroidCredentialKey)), + ) + } +} + +internal class AndroidComputerLocalData( + private val access: AndroidAccessSetupStore, + private val chat: AndroidChatStore, +) : ComputerLocalData { + override suspend fun loadAccess(id: UUID) = access.loadAccess(id) + override suspend fun saveAccess(id: UUID, access: AccessSetup) = this.access.saveAccess(id, access) + override suspend fun forget(id: UUID) { + access.deleteAccess(id) + chat.purge(id.toString()) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/AndroidCredentialStore.kt b/android/app/src/main/kotlin/app/bighelp/android/live/AndroidCredentialStore.kt new file mode 100644 index 00000000..aa03da0b --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/AndroidCredentialStore.kt @@ -0,0 +1,120 @@ +package app.bighelp.android.live + +import android.content.Context +import app.bighelp.android.storage.AndroidCredentialKey +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.android.storage.recordBindingBytes +import app.bighelp.hermes.CredentialAuthority +import app.bighelp.hermes.CredentialStore +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.StaleCredentialException +import java.io.File +import java.util.UUID +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray + +/** + * Protected persistence only; the connection owner decides when a ready sign-in may be committed. + * Cancellation can arrive after a write commits. Retire and join owners before cleanup, and read back + * an uncertain result. Do not wrap these calls in runInterruptible or Future.cancel(true). + */ +internal class AndroidCredentialStore( + private val records: ProtectedRecordStore, + private val computerScope: String = "independent", + private val dispatcher: CoroutineDispatcher = Dispatchers.IO, +) : CredentialStore { + override suspend fun load(authority: CredentialAuthority): SavedConnection? = withContext(dispatcher) { + val raw = records.read(credentialRecordKey(authority, computerScope)) ?: return@withContext null + try { + decode(authority, raw) + } finally { + raw.fill(0) + } + } + + override suspend fun replace(expected: SavedConnection?, next: SavedConnection) = withContext(dispatcher) { + next.validate() + require(expected == null || expected.authority == next.authority) { "A replacement keeps its authority" } + val key = credentialRecordKey(next.authority, computerScope) + val raw = records.read(key) + try { + val stored = raw?.let { decode(next.authority, it) } + if (stored != expected) throw StaleCredentialException() + val replacement = next.toBytes() + try { + currentCoroutineContext().ensureActive() + // Compare the actual encoded snapshot, allowing harmless JSON ordering and future optional fields. + if (!records.compareAndSet(key, raw, replacement)) throw StaleCredentialException() + } finally { + replacement.fill(0) + } + } finally { + raw?.fill(0) + } + } + + override suspend fun delete(expected: SavedConnection) = withContext(dispatcher) { + val key = credentialRecordKey(expected.authority, computerScope) + val raw = records.read(key) + try { + if (raw == null || decode(expected.authority, raw) != expected) throw StaleCredentialException() + currentCoroutineContext().ensureActive() + if (!records.compareAndSet(key, raw, null)) throw StaleCredentialException() + } finally { + raw?.fill(0) + } + } + + /** Only an explicit local recovery action may discard a sign-in the app cannot read. */ + suspend fun discardUnreadable(authority: CredentialAuthority): Boolean = withContext(dispatcher) { + val key = credentialRecordKey(authority, computerScope) + currentCoroutineContext().ensureActive() + if (records.discardUnreadable(key)) return@withContext true + val raw = records.read(key) ?: return@withContext false + try { + try { + decode(authority, raw) + false + } catch (failure: HermesException) { + if (failure.kind !in setOf(HermesException.Kind.SavedConnectionInvalid, HermesException.Kind.InvalidCredentials)) { + throw failure + } + currentCoroutineContext().ensureActive() + records.compareAndSet(key, raw, null) + } + } finally { + raw.fill(0) + } + } + + private fun decode(authority: CredentialAuthority, raw: ByteArray): SavedConnection = + SavedConnection.fromBytes(raw).also { + if (it.authority != authority) throw HermesException(HermesException.Kind.SavedConnectionInvalid) + } + + companion object { + fun create(context: Context, computerID: UUID) = AndroidCredentialStore( + ProtectedRecordStore(File(context.noBackupFilesDir, "hermes-sign-ins"), RecordCipher(AndroidCredentialKey)), + computerScope = computerID.toString(), + ) + } +} + +internal fun credentialRecordKey(authority: CredentialAuthority, computerScope: String = "independent"): String { + recordBindingBytes(computerScope) + recordBindingBytes(authority.endpoint) + recordBindingBytes(authority.principal) + return buildJsonArray { + add(JsonPrimitive("bighelp.credential.v1")) + add(JsonPrimitive(computerScope)) + add(JsonPrimitive(authority.endpoint)) + add(JsonPrimitive(authority.principal)) + }.toString() +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/ChatService.kt b/android/app/src/main/kotlin/app/bighelp/android/live/ChatService.kt new file mode 100644 index 00000000..c4f8c193 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/ChatService.kt @@ -0,0 +1,104 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.chat.BotChatOutcome +import app.bighelp.hermes.chat.CatalogState +import app.bighelp.hermes.chat.ConnectionStatus +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.CreateOutcome +import app.bighelp.hermes.chat.CreateRequest +import app.bighelp.hermes.chat.DraftResult +import app.bighelp.hermes.chat.HermesChatRepository +import app.bighelp.hermes.chat.HistoryLoad +import app.bighelp.hermes.chat.ModelChange +import app.bighelp.hermes.chat.ModelOptions +import app.bighelp.hermes.chat.PendingCreation +import app.bighelp.hermes.chat.PromptAnswer +import app.bighelp.hermes.chat.PromptResult +import app.bighelp.hermes.chat.ReviewDecision +import app.bighelp.hermes.chat.ReviewResult +import app.bighelp.hermes.chat.SendMode +import app.bighelp.hermes.chat.SendResult +import app.bighelp.hermes.chat.SessionSearchResult +import app.bighelp.hermes.chat.SessionSummary +import app.bighelp.hermes.chat.SlashCommandIndex +import app.bighelp.hermes.chat.SlashSelection +import app.bighelp.hermes.chat.StopResult +import kotlinx.coroutines.flow.StateFlow + +/** + * Exactly what the screens use of a computer's chat repository, so the live model's rules can be tested + * without a socket. [RepositoryChatService] forwards every call; it adds no behavior. + */ +internal interface ChatService { + val catalog: StateFlow + val conversations: StateFlow> + val pendingCreations: StateFlow> + val connection: StateFlow + + suspend fun refreshCatalog(): CatalogState + suspend fun archivedChats(): List + suspend fun search(profile: String, query: String): List + suspend fun createChat(profile: String, request: CreateRequest = CreateRequest(), retryIntent: String? = null): CreateOutcome + suspend fun discardCreation(profile: String) + suspend fun openBotChat(profile: String, createIfMissing: Boolean): BotChatOutcome + suspend fun open(ref: ConversationRef): ConversationState + suspend fun release(ref: ConversationRef) + suspend fun updateDraft(ref: ConversationRef, text: String): DraftResult + suspend fun send(ref: ConversationRef, text: String, mode: SendMode, selection: SlashSelection?): SendResult + suspend fun stop(ref: ConversationRef): StopResult + suspend fun resolveUnresolved(ref: ConversationRef, entryId: String, decision: ReviewDecision): ReviewResult + suspend fun answerPrompt(promptId: String, answer: PromptAnswer): PromptResult + suspend fun declinePrompt(promptId: String): PromptResult + suspend fun loadOlder(ref: ConversationRef): HistoryLoad + suspend fun reloadHistory(ref: ConversationRef) + suspend fun rename(ref: ConversationRef, title: String) + suspend fun archive(ref: ConversationRef) + suspend fun restore(ref: ConversationRef) + suspend fun delete(ref: ConversationRef) + suspend fun fork(ref: ConversationRef, throughRowId: Long): ConversationRef + suspend fun commands(ref: ConversationRef): SlashCommandIndex + suspend fun commandsForNewChat(profile: String): SlashCommandIndex + suspend fun modelOptions(ref: ConversationRef): ModelOptions + suspend fun setModel(ref: ConversationRef, model: String, provider: String, confirmed: Boolean): ModelChange + suspend fun setReasoning(ref: ConversationRef, level: String) + suspend fun setFast(ref: ConversationRef, on: Boolean) +} + +internal class RepositoryChatService(private val repository: HermesChatRepository) : ChatService { + override val catalog get() = repository.catalog + override val conversations get() = repository.conversations + override val pendingCreations get() = repository.pendingCreations + override val connection get() = repository.connection + + override suspend fun refreshCatalog() = repository.refreshCatalog() + override suspend fun archivedChats() = repository.archivedChats() + override suspend fun search(profile: String, query: String) = repository.search(profile, query) + override suspend fun createChat(profile: String, request: CreateRequest, retryIntent: String?) = repository.createChat(profile, request, retryIntent) + override suspend fun discardCreation(profile: String) = repository.discardCreation(profile) + override suspend fun openBotChat(profile: String, createIfMissing: Boolean) = repository.openBotChat(profile, createIfMissing) + override suspend fun open(ref: ConversationRef) = repository.open(ref) + override suspend fun release(ref: ConversationRef) = repository.release(ref) + override suspend fun updateDraft(ref: ConversationRef, text: String) = repository.updateDraft(ref, text) + override suspend fun send(ref: ConversationRef, text: String, mode: SendMode, selection: SlashSelection?) = + repository.send(ref, text, mode, selection = selection) + override suspend fun stop(ref: ConversationRef) = repository.stop(ref) + override suspend fun resolveUnresolved(ref: ConversationRef, entryId: String, decision: ReviewDecision) = + repository.resolveUnresolved(ref, entryId, decision) + override suspend fun answerPrompt(promptId: String, answer: PromptAnswer) = repository.answerPrompt(promptId, answer) + override suspend fun declinePrompt(promptId: String) = repository.declinePrompt(promptId) + override suspend fun loadOlder(ref: ConversationRef) = repository.loadOlder(ref) + override suspend fun reloadHistory(ref: ConversationRef) = repository.reloadHistory(ref) + override suspend fun rename(ref: ConversationRef, title: String) = repository.rename(ref, title) + override suspend fun archive(ref: ConversationRef) = repository.archive(ref) + override suspend fun restore(ref: ConversationRef) = repository.restore(ref) + override suspend fun delete(ref: ConversationRef) = repository.delete(ref) + override suspend fun fork(ref: ConversationRef, throughRowId: Long) = repository.fork(ref, throughRowId) + override suspend fun commands(ref: ConversationRef) = repository.commands(ref) + override suspend fun commandsForNewChat(profile: String) = repository.commandsForNewChat(profile) + override suspend fun modelOptions(ref: ConversationRef) = repository.modelOptions(ref) + override suspend fun setModel(ref: ConversationRef, model: String, provider: String, confirmed: Boolean) = + repository.setModel(ref, model, provider, confirmed) + override suspend fun setReasoning(ref: ConversationRef, level: String) = repository.setReasoning(ref, level) + override suspend fun setFast(ref: ConversationRef, on: Boolean) = repository.setFast(ref, on) +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt b/android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt new file mode 100644 index 00000000..521b1097 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt @@ -0,0 +1,405 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.RecordStorageException +import app.bighelp.android.storage.StorageProblem +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.CredentialStore +import app.bighelp.hermes.CredentialAuthority +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.StaleCredentialException +import java.util.UUID +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +internal enum class ComputerPhase { Idle, Loading, ConsentRequired, Discovering, SignIn, Connecting, Connected, SignInRequired, Failed } +internal enum class ComputerProblem { Connection, StorageUnavailable, UnreadableStorage, AlreadyConfigured, ComputerLimit, InvalidName } + +internal data class ComputerConnectionState( + val computers: List = emptyList(), + val selectedID: UUID? = null, + val phase: ComputerPhase = ComputerPhase.Idle, + val authStatus: AuthStatus? = null, + val problem: ComputerProblem? = null, + val authFailure: HermesException.Kind? = null, +) + +/** Network work is separate from the owner/index transaction, making retirement testable. */ +internal interface ComputerSession { + val saved: SavedConnection? + + /** The live connection as the gateway reports it: what a screen may truthfully say beyond the first connect. */ + val link: StateFlow + suspend fun discover(): AuthStatus + suspend fun signIn(input: SignInInput): SavedConnection + suspend fun restore(saved: SavedConnection) + suspend fun connect() + suspend fun commit(expected: SavedConnection?, stillCurrent: () -> Boolean) + + /** The app is back in front: verify or reconnect, then read the lists again. Never throws for a host problem. */ + suspend fun resume() + + /** The person's own Reconnect. Throws the typed failure so the screen can say what happened. */ + suspend fun reconnect() + suspend fun close() +} + +internal class ConnectedComputer(val computer: SavedComputer, val session: T, val scope: CoroutineScope) + +/** Retirement blocks new writes and waits for any disk operation already in progress. */ +internal class OwnedCredentialStore(private val delegate: CredentialStore, private val ownerAlive: () -> Boolean) : CredentialStore { + private val active = AtomicBoolean(true) + private val lock = Mutex() + private fun requireOwner() { if (!active.get() || !ownerAlive()) throw StaleCredentialException() } + override suspend fun load(authority: CredentialAuthority): SavedConnection? = lock.withLock { + requireOwner() + delegate.load(authority).also { requireOwner() } + } + override suspend fun replace(expected: SavedConnection?, next: SavedConnection) = lock.withLock { + requireOwner() + delegate.replace(expected, next) + } + override suspend fun delete(expected: SavedConnection) = lock.withLock { + requireOwner() + delegate.delete(expected) + } + fun invalidate() { active.set(false) } + suspend fun awaitIdle() { lock.withLock { } } +} + +/** + * Called on the UI thread. Every replacement first invalidates, cancels and joins the previous operation. + * The session's child scope is also retired before local sign-out, so a late refresh cannot recreate it. + * A pending setup row survives an uncertain disk acknowledgement for explicit recovery on next launch. + */ +@OptIn(ExperimentalCoroutinesApi::class) +internal class ComputerConnectionModel( + private val registry: SavedComputerStore, + private val credentials: (UUID) -> AndroidCredentialStore, + private val consentGranted: () -> Boolean, + private val scope: CoroutineScope, + private val localData: ComputerLocalData = ComputerLocalData.None, + private val factory: (UUID, HermesEndpoint, AccessSetup, CredentialStore, CoroutineScope) -> T, +) { + private val mutableState = MutableStateFlow(ComputerConnectionState()) + val state: StateFlow = mutableState.asStateFlow() + private val mutableActive = MutableStateFlow?>(null) + val active: StateFlow?> = mutableActive.asStateFlow() + + /** The active computer's live link; null when none is active. It keeps following the gateway after setup. */ + val link: StateFlow = + mutableActive.flatMapLatest { it?.session?.link ?: flowOf(null) }.stateIn(scope, SharingStarted.Eagerly, null) + private var generation = 0L + private var operation: Job? = null + private var owner: Owner? = null + private var cleanup: Job? = null + + /** ViewModel disposal can cancel its scope first; resource cleanup still has to finish. */ + fun close(): Job { + cleanup?.let { return it } + ++generation + val previous = operation + previous?.cancel() + return CoroutineScope(scope.coroutineContext.minusKey(Job) + NonCancellable).launch { + previous?.join() + try { retire() } catch (_: Exception) { /* The owner is invalid even if socket cleanup fails. */ } + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Idle) + }.also { cleanup = it } + } + + private class Owner( + val id: UUID, val endpoint: HermesEndpoint, val access: AccessSetup, val session: T, val job: Job, val scope: CoroutineScope, + val credentials: OwnedCredentialStore, + ) + + fun load(): Job = launchOperation { token -> + retire() + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Loading, problem = null, authFailure = null) + val saved = registry.load() + requireCurrent(token) + publishIndex(saved) + if (!consentGranted()) { + mutableState.value = mutableState.value.copy(phase = ComputerPhase.ConsentRequired) + } else { + saved.selectedID?.let { restore(it, token) } + ?: run { mutableState.value = mutableState.value.copy(phase = ComputerPhase.Idle) } + } + } + + /** [access] holds the proxy details the person entered for this address; they are saved with the sign-in. */ + fun beginSetup(endpoint: HermesEndpoint, access: AccessSetup = AccessSetup.None): Job = launchOperation { token -> + retire() + if (!hasConsent()) return@launchOperation + val next = newOwner(UUID.randomUUID(), endpoint, access) + owner = next + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Discovering, problem = null, authFailure = null, authStatus = null) + val status = next.session.discover() + requireOwner(next, token) + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, authStatus = status) + } + + fun reauthenticate(id: UUID): Job = launchOperation { token -> + retire() + if (!hasConsent()) return@launchOperation + val snapshot = registry.load() + requireCurrent(token) + publishIndex(snapshot) + val row = snapshot.computers.firstOrNull { it.id == id } ?: return@launchOperation + val access = localData.loadAccess(id) + requireCurrent(token) + val next = newOwner(id, row.endpoint, access) + owner = next + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Discovering, problem = null, authFailure = null, authStatus = null) + val status = next.session.discover() + requireOwner(next, token) + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, authStatus = status) + } + + fun signIn(name: String, input: SignInInput): Job = launchOperation { token -> + if (!hasConsent()) return@launchOperation + val current = owner ?: return@launchOperation + val cleanName = name.trim() + if (cleanName.isEmpty() || cleanName.codePointCount(0, cleanName.length) > 60 || cleanName.any { Character.isISOControl(it) }) { + mutableState.value = mutableState.value.copy(problem = ComputerProblem.InvalidName) + return@launchOperation + } + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Connecting, problem = null, authFailure = null) + val candidate = current.session.signIn(input) + requireOwner(current, token) + // A duplicate or a full list is decided before the session may connect, so a refused sign-in never + // leaves a socket open under credentials that were not accepted. + rejection(registry.load(), current.id, candidate)?.let { problem -> + requireOwner(current, token) + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, problem = problem) + return@launchOperation + } + requireOwner(current, token) + current.session.connect() + requireOwner(current, token) + var snapshot = registry.load() + requireOwner(current, token) + val existing = snapshot.computers.firstOrNull { it.id == current.id } + rejection(snapshot, current.id, candidate)?.let { problem -> + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, problem = problem) + return@launchOperation + } + val expected = existing?.let { credentials(it.id).load(it.authority) } + requireOwner(current, token) + val pending = SavedComputer(current.id, cleanName, candidate.endpoint, candidate.principal, false) + val rows = if (existing == null) snapshot.computers + pending + else snapshot.computers.map { if (it.id == current.id) pending else it } + snapshot = replaceIndex(snapshot, rows, current.id) + requireOwner(current, token) + // The gate details are durable before the sign-in is: a restore needs both to reach the computer. + localData.saveAccess(current.id, current.access) + requireOwner(current, token) + // The row is recoverable even if cancellation or a lost disk acknowledgement interrupts promotion. + current.session.commit(expected) { owner === current && generation == token && current.job.isActive } + requireOwner(current, token) + val complete = pending.copy(setupComplete = true) + snapshot = replaceIndex(snapshot, snapshot.computers.map { if (it.id == current.id) complete else it }, current.id) + requireOwner(current, token) + publishIndex(snapshot) + mutableActive.value = ConnectedComputer(complete, current.session, current.scope) + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Connected, authStatus = null) + } + + fun select(id: UUID): Job = launchOperation { token -> + retire() + if (!hasConsent()) return@launchOperation + restore(id, token) + } + + fun disconnect(): Job = launchOperation { + retire() + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Idle, authStatus = null, problem = null, authFailure = null) + } + + fun remove(id: UUID): Job = launchOperation { token -> + // Joining the old operation happened before this block, including any cancelled disk write. + if (owner?.id == id || mutableActive.value == null) retire(forRemoval = owner?.id == id) + var snapshot = registry.load() + val row = snapshot.computers.firstOrNull { it.id == id } ?: return@launchOperation + val vault = credentials(id) + vault.load(row.authority)?.let { stored -> + try { vault.delete(stored) } + catch (failure: RecordStorageException) { + if (failure.problem != StorageProblem.DiskUnavailable || vault.load(row.authority) != null) throw failure + } + } + requireCurrent(token) + localData.forget(id) + requireCurrent(token) + snapshot = replaceIndex(snapshot, snapshot.computers.filterNot { it.id == id }, snapshot.selectedID.takeUnless { it == id }) + requireCurrent(token) + publishIndex(snapshot) + if (mutableActive.value == null) mutableState.value = mutableState.value.copy(phase = ComputerPhase.Idle) + } + + private suspend fun restore(id: UUID, token: Long) { + val snapshot = registry.load() + requireCurrent(token) + publishIndex(snapshot) + val row = snapshot.computers.firstOrNull { it.id == id } ?: return + if (!row.setupComplete) { + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignInRequired, selectedID = id) + return + } + val saved = credentials(id).load(row.authority) + requireCurrent(token) + if (saved == null) { + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignInRequired, selectedID = id) + return + } + val access = localData.loadAccess(id) + requireCurrent(token) + val next = newOwner(id, row.endpoint, access) + owner = next + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Connecting, problem = null, authFailure = null) + next.session.restore(saved) + next.session.connect() + requireOwner(next, token) + val selected = if (snapshot.selectedID == id) snapshot else replaceIndex(snapshot, snapshot.computers, id) + requireOwner(next, token) + publishIndex(selected) + mutableActive.value = ConnectedComputer(row, next.session, next.scope) + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Connected) + } + + private fun newOwner(id: UUID, endpoint: HermesEndpoint, access: AccessSetup): Owner { + val job = SupervisorJob(scope.coroutineContext[Job]) + val ownedScope = CoroutineScope(scope.coroutineContext + job) + val store = OwnedCredentialStore(credentials(id)) { job.isActive } + return try { Owner(id, endpoint, access, factory(id, endpoint, access, store, ownedScope), job, ownedScope, store) } + catch (failure: Exception) { store.invalidate(); job.cancel(); throw failure } + } + + private fun launchOperation(block: suspend (Long) -> Unit): Job { + cleanup?.let { return it } + val token = ++generation + val previous = operation + previous?.cancel() + val next = scope.launch(start = CoroutineStart.LAZY) { + // A cancelled waiter must still outlast its predecessor, or a third action could bypass it. + if (previous != null) withContext(NonCancellable) { previous.join() } + ensureActive() + if (generation != token) return@launch + try { block(token) } + catch (failure: CancellationException) { throw failure } + catch (failure: Exception) { + if (generation != token) return@launch + val authFailure = (failure as? HermesException)?.kind + val problem = when (failure) { + is RecordStorageException -> if (failure.problem in setOf(StorageProblem.CorruptRecord, StorageProblem.RecordTooLarge, StorageProblem.KeyMissing)) + ComputerProblem.UnreadableStorage else ComputerProblem.StorageUnavailable + is SavedComputersException -> if (failure.problem == SavedComputersProblem.Unreadable) + ComputerProblem.UnreadableStorage else ComputerProblem.StorageUnavailable + is HermesException -> if (failure.kind == HermesException.Kind.SavedConnectionInvalid) + ComputerProblem.UnreadableStorage else ComputerProblem.Connection + else -> ComputerProblem.Connection + } + retire() + mutableState.value = mutableState.value.copy(phase = ComputerPhase.Failed, problem = problem, authFailure = authFailure) + } + } + operation = next + next.start() + return next + } + + /** Why a sign-in may not become a saved computer, or null. An address+principal already saved, or 32 rows. */ + private fun rejection(snapshot: SavedComputerSnapshot, id: UUID, candidate: SavedConnection): ComputerProblem? { + val existing = snapshot.computers.firstOrNull { it.id == id } + if (existing != null && existing.authority != candidate.authority) throw HermesException(HermesException.Kind.IdentityChanged) + if (snapshot.computers.any { it.id != id && it.authority == candidate.authority }) return ComputerProblem.AlreadyConfigured + if (existing == null && snapshot.computers.size >= 32) return ComputerProblem.ComputerLimit + return null + } + + private fun hasConsent(): Boolean { + if (consentGranted()) return true + mutableState.value = mutableState.value.copy(phase = ComputerPhase.ConsentRequired) + return false + } + + private suspend fun requireCurrent(token: Long) { + currentCoroutineContext().ensureActive() + if (generation != token) throw CancellationException("Connection retired") + } + + private suspend fun requireOwner(expected: Owner, token: Long) { + requireCurrent(token) + if (owner !== expected || !expected.job.isActive) throw CancellationException("Connection retired") + } + + /** + * Ends the current owner. Two orders, because two different things must not happen: + * - **Ordinary teardown** (switching, disconnecting, closing): the session closes first, while the owner's + * scope and its credential store are still alive. `gateway.disconnect()` lets a refresh that is already + * on the wire finish and save its rotated token (up to its own 8 s settle window) and the gateway's + * hard-close fallback runs on a live scope. Only then are writes refused and the scope cancelled. Nothing + * new can start meanwhile: [mutableActive] and [owner] are already cleared, and operations run one at a time. + * - **Removal**: refuse writes and cancel first, so a late refresh can never recreate the deleted sign-in. + */ + private suspend fun retire(forRemoval: Boolean = false) = withContext(NonCancellable) { + val old = owner + owner = null + mutableActive.value = null + if (old != null) { + if (forRemoval) { + old.credentials.invalidate() + try { + old.job.cancelAndJoin() + old.session.close() + } finally { old.credentials.awaitIdle() } + } else { + try { + old.session.close() + } finally { + old.credentials.invalidate() + try { old.job.cancelAndJoin() } finally { old.credentials.awaitIdle() } + } + } + } + } + + private fun publishIndex(snapshot: SavedComputerSnapshot) { + mutableState.value = mutableState.value.copy(computers = snapshot.computers, selectedID = snapshot.selectedID) + } + + private suspend fun replaceIndex( + expected: SavedComputerSnapshot, + rows: List, + selectedID: UUID?, + ): SavedComputerSnapshot = try { + registry.replace(expected, rows, selectedID) + } catch (failure: RecordStorageException) { + if (failure.problem != StorageProblem.DiskUnavailable) throw failure + // Rename may have committed before its acknowledgement failed. Observe; never repeat the write. + val observed = registry.load() + if (observed.revision == expected.revision || observed.computers != rows || observed.selectedID != selectedID) throw failure + observed + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/ComputerLink.kt b/android/app/src/main/kotlin/app/bighelp/android/live/ComputerLink.kt new file mode 100644 index 00000000..bf24e438 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/ComputerLink.kt @@ -0,0 +1,39 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.GatewayState +import app.bighelp.hermes.HermesException + +/** + * What the person is told about a computer's live connection, after setup as well as during it. It is read + * from the gateway itself, never guessed: only a socket that is ready and advertised is [Connected]. + */ +internal enum class ComputerLink { + /** The first connection of this session is not up yet. */ + Connecting, + Connected, + + /** The socket was lost and the gateway's own recovery is trying again. */ + Reconnecting, + + /** The connection ended and nothing is retrying; Reconnect (or coming back to the app) starts it again. */ + Offline, + + /** The host no longer accepts the saved sign-in; reconnecting cannot help until the person signs in again. */ + SignInRequired, +} + +internal fun linkOf(state: GatewayState): ComputerLink = when (state.connection) { + GatewayConnection.Connected -> ComputerLink.Connected + GatewayConnection.Connecting -> ComputerLink.Connecting + GatewayConnection.Recovering -> ComputerLink.Reconnecting + GatewayConnection.Closed -> ComputerLink.Offline + GatewayConnection.Idle -> when { + state.lastFailure?.kind in SIGN_IN_FAILURES -> ComputerLink.SignInRequired + // Generation 0 and no failure: the owner has not tried yet. Anything later that is idle has ended. + state.generation == 0L && state.lastFailure == null -> ComputerLink.Connecting + else -> ComputerLink.Offline + } +} + +private val SIGN_IN_FAILURES = setOf(HermesException.Kind.AuthenticationRequired, HermesException.Kind.InvalidCredentials) diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/LiveModel.kt b/android/app/src/main/kotlin/app/bighelp/android/live/LiveModel.kt new file mode 100644 index 00000000..0798cabf --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/LiveModel.kt @@ -0,0 +1,477 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.chat.ChatError +import app.bighelp.hermes.chat.ChatException +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.CreateOutcome +import app.bighelp.hermes.chat.CreateRequest +import app.bighelp.hermes.chat.HistoryLoad +import app.bighelp.hermes.chat.ModelChange +import app.bighelp.hermes.chat.ModelOptions +import app.bighelp.hermes.chat.PromptAnswer +import app.bighelp.hermes.chat.PromptResult +import app.bighelp.hermes.chat.ReviewDecision +import app.bighelp.hermes.chat.ReviewResult +import app.bighelp.hermes.chat.SendMode +import app.bighelp.hermes.chat.SendResult +import app.bighelp.hermes.chat.SessionSummary +import app.bighelp.hermes.chat.SlashCommandIndex +import app.bighelp.hermes.chat.StopResult +import app.bighelp.hermes.chat.BotChatOutcome +import app.bighelp.hermes.chat.CatalogState +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +internal sealed interface SendOutcome { + /** Hermes took it, or it is kept for review: the message box can be cleared. */ + data object Sent : SendOutcome + + /** Nothing left the phone as a message: the text stays in the box and [message] says why. */ + data class Kept(val message: String) : SendOutcome +} + +internal sealed interface SetupOutcome { + data class Ready(val status: AuthStatus) : SetupOutcome + data class Failed(val message: String) : SetupOutcome + data object Cancelled : SetupOutcome +} + +/** A short message for the screen to show once; [id] makes the same words shown twice distinct. */ +internal class Notice(val id: Long, val text: String) + +internal data class SearchHit(val ref: ConversationRef, val title: String, val agentName: String, val snippet: String) + +/** + * Everything the live screens do, on top of the connection coordinator and one computer's [ChatService]. Plain + * Kotlin, called from the main thread, with no Android types, so every rule runs in JVM tests. It owns what + * a screen must not: coming back to the front, retrying a lost connection (in front only, with growing pauses, + * never after a refused sign-in), saving drafts after a pause, which chats stay retained, and what a failed + * action says. Every message comes from [LiveText]. + */ +@OptIn(ExperimentalCoroutinesApi::class) +internal class LiveModel( + val connections: ComputerConnectionModel, + private val chatOf: (T) -> ChatService, + private val scope: CoroutineScope, + private val retryDelays: List = listOf(2_000L, 6_000L, 18_000L), + private val draftDelayMillis: Long = 300L, + private val searchDelayMillis: Long = 400L, +) { + val chat: StateFlow = + connections.active.map { it?.let { computer -> chatOf(computer.session) } }.stateIn(scope, SharingStarted.Eagerly, null) + val catalog: StateFlow = + chat.flatMapLatest { it?.catalog ?: flowOf(CatalogState()) }.stateIn(scope, SharingStarted.Eagerly, CatalogState()) + val conversations: StateFlow> = + chat.flatMapLatest { it?.conversations ?: flowOf(emptyMap()) }.stateIn(scope, SharingStarted.Eagerly, emptyMap()) + val pendingCreations = chat.flatMapLatest { it?.pendingCreations ?: flowOf(emptyList()) } + .stateIn(scope, SharingStarted.Eagerly, emptyList()) + val link: StateFlow get() = connections.link + + private val mutableForeground = MutableStateFlow(false) + private val mutableProblem = MutableStateFlow(null) + + /** Why reconnecting cannot help by itself (the host refused the saved sign-in); null otherwise. */ + val reconnectProblem: StateFlow = mutableProblem.asStateFlow() + + private val mutableNotice = MutableStateFlow(null) + val notice: StateFlow = mutableNotice.asStateFlow() + private var noticeCounter = 0L + + private val mutableSearch = MutableStateFlow("") + val searchText: StateFlow = mutableSearch.asStateFlow() + private val mutableHits = MutableStateFlow>(emptyList()) + + /** Chats whose messages matched the search text, asked of the host agent by agent. */ + val contentHits: StateFlow> = mutableHits.asStateFlow() + private var searchJob: Job? = null + + private val picked = MutableStateFlow(null) + + /** The agent new chats start with: the person's pick, else the default agent, else the first one. */ + val selectedAgentId: StateFlow = combine(catalog, picked) { current, pick -> + pick?.takeIf { id -> current.agents.any { it.id == id } } + ?: current.agents.firstOrNull { it.id == "default" }?.id + ?: current.agents.firstOrNull()?.id + }.stateIn(scope, SharingStarted.Eagerly, null) + + private var activeBeforeSetup: java.util.UUID? = null + private var restartSetup: (suspend () -> Unit)? = null + private val draftJobs = HashMap() + private val latestDrafts = HashMap() + private val commandIndexes = HashMap() + + init { + // Offline while in front: try again with growing pauses. The restart on every change of either input + // is what makes "backgrounded", "back online" and "a different computer" all end an attempt at once. + scope.launch { + combine(connections.link, mutableForeground) { current, foreground -> current == ComputerLink.Offline && foreground } + .distinctUntilChanged() + .collectLatest { shouldRetry -> if (shouldRetry) retryConnection() } + } + scope.launch { connections.link.collect { if (it == ComputerLink.Connected) mutableProblem.value = null } } + } + + // ---- lifecycle + + fun start(): Job = connections.load() + + fun onForeground() { + mutableForeground.value = true + val active = connections.active.value + if (active != null) { + scope.launch { active.session.resume() } + } else { + val state = connections.state.value + // A saved computer that failed to open gets another try; one the person disconnected does not. + if (state.phase == ComputerPhase.Failed) state.selectedID?.let { connections.select(it) } + } + } + + fun onBackground() { + mutableForeground.value = false + } + + private suspend fun retryConnection() { + for (pause in retryDelays) { + delay(pause) + val session = connections.active.value?.session ?: return + try { + session.reconnect() + return + } catch (failure: CancellationException) { + throw failure + } catch (failure: Exception) { + if (isSignInLoss(failure)) { mutableProblem.value = ChatError.Kind.SignInRequired; return } + } + } + } + + /** The person's own Reconnect. */ + fun reconnectNow() { + scope.launch { + val session = connections.active.value?.session ?: return@launch + try { + session.reconnect() + mutableProblem.value = null + } catch (failure: CancellationException) { + throw failure + } catch (failure: Exception) { + if (isSignInLoss(failure)) mutableProblem.value = ChatError.Kind.SignInRequired else notify(describe(failure)) + } + } + } + + private fun isSignInLoss(failure: Exception) = + (failure is ChatException && failure.error.kind == ChatError.Kind.SignInRequired) || + (failure is HermesException && failure.kind in SIGN_IN_LOSS) + + private fun describe(failure: Exception): String = when (failure) { + is ChatException -> LiveText.describe(failure.error) + is HermesException -> LiveText.describe(failure.kind) + else -> "Couldn't reconnect." + } + + // ---- computers and setup + + /** Checks the address with the person's access details and returns the host's sign-in options or a reason. */ + suspend fun beginSetup(endpoint: HermesEndpoint, access: AccessSetup): SetupOutcome { + // Adding a computer closes the open one (one owner at a time); cancelling the add opens it again. + connections.active.value?.computer?.id?.let { activeBeforeSetup = it } + restartSetup = { connections.beginSetup(endpoint, access).join() } + connections.beginSetup(endpoint, access).join() + val state = connections.state.value + return when (state.phase) { + ComputerPhase.SignIn -> SetupOutcome.Ready(state.authStatus ?: AuthStatus(false, emptyList(), emptyList())) + ComputerPhase.Failed -> SetupOutcome.Failed( + state.authFailure?.let(LiveText::describe) ?: state.problem?.let(LiveText::problem) ?: "Couldn't connect to this computer.", + ) + ComputerPhase.ConsentRequired -> SetupOutcome.Failed("Agree to share chat data first.") + else -> SetupOutcome.Cancelled + } + } + + /** Ends a check or a sign-in in progress, and reopens the computer that was open before it started, if any. */ + fun cancelSetup(): Job = scope.launch { + val previous = activeBeforeSetup + activeBeforeSetup = null + // Selecting retires the setup's own session first, so the open computer is never reported gone in between. + if (previous != null && consentIsKept()) connections.select(previous).join() else connections.disconnect().join() + } + + private fun consentIsKept() = connections.state.value.phase != ComputerPhase.ConsentRequired + + /** + * Signs in the computer being set up. A refused sign-in ends its session, so trying again on the same screen + * first starts the same setup over (same address, same access details) rather than doing nothing. + */ + fun signIn(name: String, input: SignInInput): Job = scope.launch { + if (connections.state.value.phase == ComputerPhase.Failed) { + restartSetup?.invoke() + if (connections.state.value.phase != ComputerPhase.SignIn) return@launch + } + connections.signIn(name, input).join() + if (connections.state.value.phase == ComputerPhase.Connected) activeBeforeSetup = null + } + + fun select(id: java.util.UUID): Job = connections.select(id) + fun remove(id: java.util.UUID): Job = connections.remove(id) + fun reauthenticate(id: java.util.UUID): Job { + restartSetup = { connections.reauthenticate(id).join() } + return connections.reauthenticate(id) + } + fun disconnect(): Job = connections.disconnect() + + // ---- notices + + fun notify(text: String) { mutableNotice.value = Notice(++noticeCounter, text) } + fun dismissNotice(id: Long) { if (mutableNotice.value?.id == id) mutableNotice.value = null } + + // ---- lists + + fun selectAgent(id: String) { picked.value = id } + + suspend fun refresh() { guarded { it.refreshCatalog() } } + + suspend fun archived(): List? = guarded { it.archivedChats() } + + fun setSearch(query: String) { + mutableSearch.value = query + searchJob?.cancel() + val trimmed = query.trim() + if (trimmed.length < 2) { + searchJob = null + mutableHits.value = emptyList() + return + } + searchJob = scope.launch { + delay(searchDelayMillis) + val service = chat.value ?: return@launch + val agents = catalog.value.agents.take(MAXIMUM_SEARCHED_AGENTS) + val names = agents.associate { it.id to it.displayName.ifBlank { it.id } } + val found = coroutineScope { + agents.map { agent -> + async { + try { service.search(agent.id, trimmed) } catch (failure: CancellationException) { throw failure } catch (_: Exception) { emptyList() } + } + }.awaitAll() + } + mutableHits.value = found.flatten().distinctBy { it.session.ref }.map { SearchHit(it.session.ref, it.session.title.ifBlank { "Chat" }, names[it.session.profile] ?: it.session.profile, it.snippet) } + } + } + + // ---- creating and opening + + /** A new chat with [profile]; the ref to open, or null with a notice. An unconfirmed create is kept to retry. */ + suspend fun newChat(profile: String, request: CreateRequest = CreateRequest()): ConversationRef? = + when (val outcome = guarded { it.createChat(profile, request) }) { + is CreateOutcome.Created -> outcome.ref + is CreateOutcome.Unconfirmed -> { notify(LiveText.describe(outcome.error)); null } + is CreateOutcome.Failed -> { notify(LiveText.describe(outcome.error)); null } + null -> null + } + + suspend fun retryCreation(profile: String, intentId: String): ConversationRef? = + when (val outcome = guarded { it.createChat(profile, CreateRequest(), intentId) }) { + is CreateOutcome.Created -> outcome.ref + is CreateOutcome.Unconfirmed -> { notify(LiveText.describe(outcome.error)); null } + is CreateOutcome.Failed -> { notify(LiveText.describe(outcome.error)); null } + null -> null + } + + suspend fun discardCreation(profile: String) { guarded { it.discardCreation(profile) } } + + suspend fun openBotChat(profile: String): ConversationRef? = + when (val outcome = guarded { it.openBotChat(profile, createIfMissing = true) }) { + is BotChatOutcome.Opened -> outcome.ref + is BotChatOutcome.Unconfirmed -> { notify(LiveText.describe(outcome.error)); null } + is BotChatOutcome.Failed -> { notify(LiveText.describe(outcome.error)); null } + BotChatOutcome.NotCreated -> null + null -> null + } + + suspend fun openChat(ref: ConversationRef): ConversationState? { + val service = chat.value ?: return null + val state = guarded { it.open(ref) } + releaseIdle(service, except = ref) + return state + } + + /** Leaving a chat saves its draft now, and lets go of it unless it is working or waiting on the reader. */ + suspend fun leaveChat(ref: ConversationRef) { + flushDraft(ref) + commandIndexes.remove(ref) + val service = chat.value ?: return + val state = service.conversations.value[ref] ?: return + if (!state.running && state.prompts.isEmpty()) quietly { service.release(ref) } + } + + private suspend fun releaseIdle(service: ChatService, except: ConversationRef) { + for ((ref, state) in service.conversations.value) { + if (ref != except && !state.running && state.prompts.isEmpty()) quietly { service.release(ref) } + } + } + + // ---- composing and sending + + fun editDraft(ref: ConversationRef, text: String) { + latestDrafts[ref] = text + draftJobs[ref]?.cancel() + draftJobs[ref] = scope.launch { + delay(draftDelayMillis) + draftJobs.remove(ref) + saveDraft(ref) + } + } + + suspend fun flushDraft(ref: ConversationRef) { + draftJobs.remove(ref)?.cancel() + saveDraft(ref) + } + + private suspend fun saveDraft(ref: ConversationRef) { + val text = latestDrafts.remove(ref) ?: return + val service = chat.value ?: return + val result = try { service.updateDraft(ref, text) } catch (failure: CancellationException) { throw failure } catch (_: Exception) { null } + if (result is app.bighelp.hermes.chat.DraftResult.NotSaved) notify(LiveText.describe(result.error)) + } + + suspend fun send(ref: ConversationRef, text: String, mode: SendMode): SendOutcome { + val service = chat.value ?: return SendOutcome.Kept(LiveText.describe(ChatError(ChatError.Kind.NotConnected))) + // The send clears the draft itself; a save still waiting would put the sent words back. + draftJobs.remove(ref)?.cancel() + latestDrafts.remove(ref) + val selection = if (text.startsWith("/")) commandIndex(service, ref)?.selection(text) else null + val result = try { + service.send(ref, text, mode, selection) + } catch (failure: CancellationException) { + throw failure + } catch (failure: ChatException) { + return SendOutcome.Kept(LiveText.describe(failure.error)) + } + return when (result) { + is SendResult.Admitted -> SendOutcome.Sent + is SendResult.Uncertain -> { + notify("We couldn't confirm that message arrived. Review it above the message box. Nothing is sent again by itself.") + SendOutcome.Sent + } + is SendResult.Refused -> SendOutcome.Kept( + if (result.reachedSessionLimit) LiveText.describe(HermesException.Kind.ActiveSessionLimit) else LiveText.describe(result.error), + ) + is SendResult.NotSent -> SendOutcome.Kept(result.block?.let(LiveText::sendBlock) ?: LiveText.describe(result.error)) + } + } + + private suspend fun commandIndex(service: ChatService, ref: ConversationRef): SlashCommandIndex? { + commandIndexes[ref]?.let { return it } + return try { + service.commands(ref).also { commandIndexes[ref] = it } + } catch (failure: CancellationException) { + throw failure + } catch (_: Exception) { + null + } + } + + /** Commands to suggest for a draft that is just `/word`. Empty when the list cannot be read. */ + suspend fun suggestions(ref: ConversationRef, draft: String): List { + if (!draft.startsWith("/")) return emptyList() + val service = chat.value ?: return emptyList() + return commandIndex(service, ref)?.suggestions(draft).orEmpty() + } + + suspend fun stop(ref: ConversationRef) { + when (val result = guarded { it.stop(ref) }) { + is StopResult.Refused -> notify(LiveText.describe(result.error)) + is StopResult.Uncertain -> notify("We couldn't confirm the stop. The chat will show when it ends.") + StopResult.Requested, null -> Unit + } + } + + suspend fun review(ref: ConversationRef, entryId: String, decision: ReviewDecision) { + when (val result = guarded { it.resolveUnresolved(ref, entryId, decision) }) { + ReviewResult.ComposerNotEmpty -> notify("Clear the message box first to put that message back.") + is ReviewResult.Failed -> notify(LiveText.describe(result.error)) + ReviewResult.Done, ReviewResult.NotFound, null -> Unit + } + } + + // ---- questions from the agent + + suspend fun answerPrompt(promptId: String, answer: PromptAnswer): PromptResult? { + val result = guarded { it.answerPrompt(promptId, answer) } + when (result) { + PromptResult.NoLongerActive -> notify("That question is no longer waiting.") + is PromptResult.Invalid -> notify("That answer can't be used. Check it and try again.") + PromptResult.Answered, null -> Unit + } + return result + } + + suspend fun declinePrompt(promptId: String) { guarded { it.declinePrompt(promptId) } } + + // ---- history and chat edits + + suspend fun loadOlder(ref: ConversationRef): HistoryLoad? = guarded { it.loadOlder(ref) } + + suspend fun rename(ref: ConversationRef, title: String) { guarded { it.rename(ref, title) } } + suspend fun archive(ref: ConversationRef) { guarded { it.archive(ref) } } + suspend fun restore(ref: ConversationRef) { guarded { it.restore(ref) } } + suspend fun delete(ref: ConversationRef) { guarded { it.delete(ref) } } + suspend fun fork(ref: ConversationRef, throughRowId: Long): ConversationRef? = guarded { it.fork(ref, throughRowId) } + + // ---- model, reasoning and speed + + suspend fun modelOptions(ref: ConversationRef): ModelOptions? = guarded { it.modelOptions(ref) } + suspend fun setModel(ref: ConversationRef, model: String, provider: String, confirmed: Boolean): ModelChange? = + guarded { it.setModel(ref, model, provider, confirmed) } + suspend fun setReasoning(ref: ConversationRef, level: String) { guarded { it.setReasoning(ref, level) } } + suspend fun setFast(ref: ConversationRef, on: Boolean) { guarded { it.setFast(ref, on) } } + + // ---- helpers + + /** Runs an action on the active computer's chat; a typed failure becomes one plain notice and null. */ + private suspend fun guarded(action: suspend (ChatService) -> R): R? { + val service = chat.value ?: run { notify(LiveText.describe(ChatError(ChatError.Kind.NotConnected))); return null } + return try { + action(service) + } catch (failure: CancellationException) { + throw failure + } catch (failure: ChatException) { + notify(LiveText.describe(failure.error)); null + } catch (failure: HermesException) { + notify(LiveText.describe(failure.kind)); null + } + } + + private suspend fun quietly(block: suspend () -> Unit) { + try { block() } catch (failure: CancellationException) { throw failure } catch (_: Exception) { } + } + + private companion object { + const val MAXIMUM_SEARCHED_AGENTS = 8 + val SIGN_IN_LOSS = setOf(HermesException.Kind.AuthenticationRequired, HermesException.Kind.InvalidCredentials) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/LiveText.kt b/android/app/src/main/kotlin/app/bighelp/android/live/LiveText.kt new file mode 100644 index 00000000..5c03ba66 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/LiveText.kt @@ -0,0 +1,100 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.chat.ChatError +import app.bighelp.hermes.chat.SendBlock + +/** + * Every sentence the live screens show about a failure or a state, in plain words. A missing host feature says + * to update the plugin; nothing names an AI company, an account system or a raw code. + */ +internal object LiveText { + fun describe(error: ChatError): String = when (error.kind) { + ChatError.Kind.NotConnected -> "Not connected to your computer right now." + ChatError.Kind.HostUnavailable -> "Your computer isn't answering right now." + ChatError.Kind.SignInRequired -> "Your computer wants you to sign in again." + ChatError.Kind.NotOpen -> "This chat isn't open any more. Go back and open it again." + ChatError.Kind.NoLiveSession -> "This chat isn't running on your computer. Open it again." + ChatError.Kind.PersistenceFailed -> "This phone couldn't save your message, so nothing was sent." + ChatError.Kind.InvalidResponse -> "Your computer answered in a way this app doesn't understand." + ChatError.Kind.Rejected -> "Your computer said no to that." + ChatError.Kind.TooLarge -> "That is too long to send." + ChatError.Kind.Unsupported -> "Your computer doesn't offer this yet. You may need to update the plugin on your computer." + ChatError.Kind.HistoryChanged -> "This chat changed on your computer, so it was loaded again." + ChatError.Kind.ModelNotConfirmed -> "The chat didn't confirm the new model." + ChatError.Kind.WorkspaceNotConfirmed -> "The chat didn't confirm the folder." + ChatError.Kind.CreationUnconfirmed -> "We couldn't confirm the new chat was made." + ChatError.Kind.CreationInProgress -> "A new chat for this agent is already being made." + ChatError.Kind.OutcomeUnknown -> "We couldn't tell whether that worked. Check before you try again." + ChatError.Kind.Conflict -> "That can't be done while the chat is busy." + ChatError.Kind.InvalidInput -> "That can't be sent." + ChatError.Kind.NoActiveTurn -> "Nothing is running to steer." + ChatError.Kind.Cancelled -> "That was cancelled." + } + + /** A failure of setup, sign-in or reconnecting. [HermesException.message] is only the kind name, so this is the one place words come from. */ + fun describe(kind: HermesException.Kind): String = when (kind) { + HermesException.Kind.InvalidEndpoint -> "That address can't be used. Check it and try again." + HermesException.Kind.PlaintextNotAllowed -> "Plain http:// only works inside your own network. Use https:// instead." + HermesException.Kind.InvalidCredentials -> "Those details weren't accepted. Check them and sign in again." + HermesException.Kind.AuthenticationRequired -> "Your computer wants you to sign in again." + HermesException.Kind.UnsupportedAuthentication -> "This computer doesn't offer that way of signing in." + HermesException.Kind.AmbiguousPasswordProvider -> "This computer has more than one password sign-in. Pick one." + HermesException.Kind.AuthModeChanged -> "This computer changed how it signs people in. Start again to check." + HermesException.Kind.IdentityChanged -> "That is a different sign-in than the one saved for this computer." + HermesException.Kind.SavedConnectionInvalid -> "The sign-in saved on this phone can't be read. Sign in again." + HermesException.Kind.SecureStorageUnavailable -> "This phone's secure storage isn't available right now." + HermesException.Kind.SecureStorageChanged -> "The saved sign-in changed in the background. Try again." + HermesException.Kind.RedirectRefused -> "This address sent the app somewhere else, so it was stopped." + HermesException.Kind.InvalidResponse -> "That address didn't answer like a Hermes computer." + HermesException.Kind.MessageTooLarge -> "Your computer sent more than this app accepts." + HermesException.Kind.TooManyRequests -> "Too many things were happening at once. Try again." + HermesException.Kind.NotConnected -> "Not connected to your computer right now." + HermesException.Kind.ConnectionFailed -> "Couldn't reach this computer. Check the address and your network." + HermesException.Kind.TlsRequired -> "The secure connection to this address couldn't be trusted." + HermesException.Kind.RateLimited -> "Your computer asked the app to slow down. Try again in a moment." + HermesException.Kind.ServerUnavailable -> "Your computer isn't answering right now." + HermesException.Kind.BrowserAuthenticationUnavailable -> "The browser sign-in couldn't start." + HermesException.Kind.NativeTokenExchangeUncertain -> "The sign-in may have gone through, but the answer was lost. Try signing in again." + HermesException.Kind.InvalidAccessCredentials -> "Those access details can't be used with this address." + HermesException.Kind.CloudflareAccessDenied -> "The access details were refused. Check the access details." + HermesException.Kind.HostNameRefused -> "This address was refused." + HermesException.Kind.WebPageInsteadOfHermes -> "That address is a web page, not a Hermes computer." + HermesException.Kind.Disconnected -> "The connection dropped." + HermesException.Kind.TimedOut -> "Your computer took too long to answer." + HermesException.Kind.Cancelled -> "That was cancelled." + HermesException.Kind.RpcRejected -> "Your computer said no to that." + HermesException.Kind.ActiveSessionLimit -> "Your computer has too many chats running. Close one and try again." + HermesException.Kind.ExclusiveSubmitUnavailable -> "Your computer can't take new messages safely yet. You may need to update the plugin." + HermesException.Kind.OutcomeUnknown -> "We couldn't tell whether that worked." + } + + fun problem(problem: ComputerProblem): String = when (problem) { + ComputerProblem.Connection -> "Couldn't connect to this computer." + ComputerProblem.StorageUnavailable -> "This phone couldn't save or read its stored data right now." + ComputerProblem.UnreadableStorage -> "Saved data on this phone can't be read. You can sign in again." + ComputerProblem.AlreadyConfigured -> "This computer and sign-in are already saved." + ComputerProblem.ComputerLimit -> "You can save up to 32 computers. Remove one first." + ComputerProblem.InvalidName -> "Give the computer a short name, with no line breaks." + } + + fun sendBlock(block: SendBlock): String = when (block) { + SendBlock.Opening -> "Opening this chat…" + SendBlock.NotConnected -> "Not connected to your computer right now." + SendBlock.CatchingUp -> "Catching up with your computer…" + SendBlock.RecoveryRequired -> "Reconnecting this chat…" + SendBlock.PendingAdmission -> "Waiting for your computer to take the last message…" + SendBlock.HostLacksExclusiveSubmit -> "Your computer can't take new messages safely yet. You may need to update the plugin." + SendBlock.TooManyUnresolved -> "Review the earlier messages above before sending more." + SendBlock.NoLiveSession -> "This chat isn't running. Open it again." + } + + /** The banner above a screen; null while all is well. */ + fun link(link: ComputerLink?): String? = when (link) { + null, ComputerLink.Connected -> null + ComputerLink.Connecting -> "Connecting…" + ComputerLink.Reconnecting -> "Reconnecting…" + ComputerLink.Offline -> "Not connected." + ComputerLink.SignInRequired -> "Sign in again to keep going." + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/NetworkComputerSession.kt b/android/app/src/main/kotlin/app/bighelp/android/live/NetworkComputerSession.kt new file mode 100644 index 00000000..6dd4fc5f --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/NetworkComputerSession.kt @@ -0,0 +1,108 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.BrowserLauncher +import app.bighelp.hermes.CredentialStore +import app.bighelp.hermes.GatewayClient +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.HermesAuthenticator +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.OkHttpHermesHttp +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.chat.ChatStore +import app.bighelp.hermes.chat.HermesChatRepository +import app.bighelp.hermes.chat.HostScope +import java.util.UUID +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +/** + * One computer's real authenticator, gateway and chat repository, all on the owner's [scope] so they end + * together. The repository is built as soon as the sign-in names its principal and always before + * `gateway.connect()`, which is what lets the first socket advertise handlers that really exist. It is closed + * with the session. The catalog is read once the socket is up and again whenever the app returns to the front; + * a failed read is shown by the catalog's own error and never fails the sign-in. + */ +internal class NetworkComputerSession( + private val computerId: UUID, + private val endpoint: HermesEndpoint, + access: AccessSetup, + credentials: CredentialStore, + private val scope: CoroutineScope, + browser: BrowserLauncher?, + private val chatStore: ChatStore, +) : ComputerSession { + private val http = OkHttpHermesHttp(endpoint, access.headers(endpoint)) + val authenticator = HermesAuthenticator(endpoint, http, credentials, browser) + val gateway = GatewayClient(authenticator, scope) + private var repository: HermesChatRepository? = null + private var repositoryPrincipal: String? = null + + init { scope.coroutineContext[Job]?.invokeOnCompletion { authenticator.close() } } + + val chatOrNull: HermesChatRepository? get() = repository + val chat: HermesChatRepository get() = checkNotNull(repository) { "The chat repository exists after sign-in" } + + override val link: StateFlow = + gateway.state.map(::linkOf).stateIn(scope, SharingStarted.Eagerly, ComputerLink.Connecting) + + override val saved get() = authenticator.savedConnection + override suspend fun discover() = authenticator.discover() + + override suspend fun signIn(input: SignInInput): SavedConnection = + authenticator.signIn(input).also(::bindChat) + + override suspend fun restore(saved: SavedConnection) { + authenticator.restore(saved) + bindChat(saved) + } + + private fun bindChat(connection: SavedConnection) { + val principal = connection.principal + if (repositoryPrincipal == principal && repository != null) return + repository?.close() + repository = HermesChatRepository(gateway, authenticator, scope, HostScope(computerId.toString(), endpoint.canonical, principal), chatStore) + repositoryPrincipal = principal + } + + override suspend fun connect() { + gateway.connect() + scope.launch { try { chat.refreshCatalog() } catch (failure: CancellationException) { throw failure } catch (_: Exception) { } } + } + + override suspend fun commit(expected: SavedConnection?, stillCurrent: () -> Boolean) { + authenticator.commit(expected, stillCurrent) + } + + /** Back in front: a silent socket is replaced, a dropped one reconnected, then the lists are read again. */ + override suspend fun resume() { + val chat = repository ?: return + try { + if (gateway.state.value.connection == GatewayConnection.Connected) chat.verifyConnection() else chat.reconnect() + } catch (failure: CancellationException) { + throw failure + } catch (_: Exception) { + // The link reports what happened; Reconnect is the person's next step. + return + } + try { chat.refreshCatalog() } catch (failure: CancellationException) { throw failure } catch (_: Exception) { } + } + + /** The person's own Reconnect. Fails with the repository's typed error. */ + override suspend fun reconnect() { + chat.reconnect() + try { chat.refreshCatalog() } catch (failure: CancellationException) { throw failure } catch (_: Exception) { } + } + + override suspend fun close() { + try { repository?.close() } finally { + try { gateway.disconnect() } finally { authenticator.close() } + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/SavedComputerStore.kt b/android/app/src/main/kotlin/app/bighelp/android/live/SavedComputerStore.kt new file mode 100644 index 00000000..4b84f34a --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/SavedComputerStore.kt @@ -0,0 +1,162 @@ +package app.bighelp.android.live + +import android.content.Context +import app.bighelp.android.storage.AndroidCredentialKey +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.android.storage.recordBindingBytes +import app.bighelp.hermes.CredentialAuthority +import app.bighelp.hermes.HermesEndpoint +import java.io.File +import java.nio.ByteBuffer +import java.nio.charset.CodingErrorAction +import java.util.UUID +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.* + +/** Saved setup metadata, never a claim that a computer is currently connected. */ +internal data class SavedComputer( + val id: UUID, + val name: String, + val endpoint: HermesEndpoint, + val principal: String, + val setupComplete: Boolean, +) { + val authority get() = CredentialAuthority(endpoint.canonical, principal) +} + +internal data class SavedComputerSnapshot( + val revision: UUID?, + val computers: List, + val selectedID: UUID?, +) + +internal enum class SavedComputersProblem { InvalidChange, Unreadable, Changed } +internal class SavedComputersException(val problem: SavedComputersProblem) : Exception(problem.name) +internal const val SAVED_COMPUTERS_RECORD_KEY = "bighelp.computers.v1" + +/** + * The pending row can be saved before committing credentials, so an interrupted setup remains recoverable. + * Cancellation can arrive after a write commits. Retire and join owners before cleanup, and read back + * an uncertain result. Do not wrap these calls in runInterruptible or Future.cancel(true). + */ +internal class SavedComputerStore( + private val records: ProtectedRecordStore, + private val dispatcher: CoroutineDispatcher = Dispatchers.IO, +) { + suspend fun load(): SavedComputerSnapshot = withContext(dispatcher) { + val raw = records.read(SAVED_COMPUTERS_RECORD_KEY) ?: return@withContext empty() + try { decode(raw) } finally { raw.fill(0) } + } + + /** Explicit reset only: callers retire connection owners and clear their unreachable local data first. */ + suspend fun discardUnreadable(): Boolean = withContext(dispatcher) { + currentCoroutineContext().ensureActive() + if (records.discardUnreadable(SAVED_COMPUTERS_RECORD_KEY)) return@withContext true + val raw = records.read(SAVED_COMPUTERS_RECORD_KEY) ?: return@withContext false + try { + try { + decode(raw) + false + } catch (_: SavedComputersException) { + currentCoroutineContext().ensureActive() + records.compareAndSet(SAVED_COMPUTERS_RECORD_KEY, raw, null) + } + } finally { raw.fill(0) } + } + + suspend fun replace( + expected: SavedComputerSnapshot, + computers: List, + selectedID: UUID?, + ): SavedComputerSnapshot = withContext(dispatcher) { + val next = SavedComputerSnapshot(UUID.randomUUID(), computers.toList(), selectedID) + validate(next, SavedComputersProblem.InvalidChange) + val raw = records.read(SAVED_COMPUTERS_RECORD_KEY) + try { + if ((raw?.let(::decode) ?: empty()) != expected) throw SavedComputersException(SavedComputersProblem.Changed) + val bytes = encode(next) + try { + currentCoroutineContext().ensureActive() + if (!records.compareAndSet(SAVED_COMPUTERS_RECORD_KEY, raw, bytes)) { + throw SavedComputersException(SavedComputersProblem.Changed) + } + } finally { bytes.fill(0) } + next + } finally { raw?.fill(0) } + } + + private fun validate(snapshot: SavedComputerSnapshot, problem: SavedComputersProblem) { + fun invalid(): Nothing = throw SavedComputersException(problem) + if (snapshot.computers.size > 32 || snapshot.computers.map { it.id }.toSet().size != snapshot.computers.size) invalid() + if (snapshot.selectedID != null && snapshot.computers.none { it.id == snapshot.selectedID }) invalid() + for (computer in snapshot.computers) { + if (computer.name.isBlank() || computer.name.any { Character.isISOControl(it) }) invalid() + try { + if (recordBindingBytes(computer.name).size > 4_096) invalid() + recordBindingBytes(computer.principal) + } catch (_: app.bighelp.android.storage.RecordStorageException) { invalid() } + } + } + + private fun encode(snapshot: SavedComputerSnapshot): ByteArray = buildJsonObject { + put("schemaVersion", 1) + put("revision", snapshot.revision.toString()) + put("selectedID", snapshot.selectedID?.toString()?.let(::JsonPrimitive) ?: JsonNull) + put("computers", buildJsonArray { + for (computer in snapshot.computers) add(buildJsonObject { + put("id", computer.id.toString()) + put("name", computer.name) + put("endpoint", computer.endpoint.canonical) + put("allowPrivateHttp", computer.endpoint.allowPrivateHttp) + put("principal", computer.principal) + put("setupComplete", computer.setupComplete) + }) + }) + }.toString().toByteArray(Charsets.UTF_8) + + private fun decode(bytes: ByteArray): SavedComputerSnapshot { + try { + val text = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString() + val root = Json.parseToJsonElement(text) as? JsonObject ?: unreadable() + val version = root["schemaVersion"] as? JsonPrimitive ?: unreadable() + if (version.isString || version.intOrNull != 1) unreadable() + val revision = uuid(root.text("revision")) + val selected = if (root["selectedID"] == null || root["selectedID"] is JsonNull) null + else uuid(root.text("selectedID")) + val rows = root["computers"] as? JsonArray ?: unreadable() + if (rows.size > 32) unreadable() + val computers = rows.map { row -> + val value = row as? JsonObject ?: unreadable() + val endpointText = value.text("endpoint") + val allowPrivate = value.bool("allowPrivateHttp") + val endpoint = HermesEndpoint.parse(endpointText, allowPrivate) + if (endpoint.canonical != endpointText) unreadable() + SavedComputer( + uuid(value.text("id")), value.text("name"), endpoint, value.text("principal"), + if (value["setupComplete"] == null) false else value.bool("setupComplete"), + ) + } + return SavedComputerSnapshot(revision, computers, selected).also { validate(it, SavedComputersProblem.Unreadable) } + } catch (_: Exception) { + unreadable() + } + } + + private fun uuid(text: String): UUID = UUID.fromString(text).also { if (it.toString() != text) unreadable() } + private fun JsonObject.text(key: String): String = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: unreadable() + private fun JsonObject.bool(key: String): Boolean = (this[key] as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull ?: unreadable() + private fun unreadable(): Nothing = throw SavedComputersException(SavedComputersProblem.Unreadable) + private fun empty() = SavedComputerSnapshot(null, emptyList(), null) + + companion object { + fun create(context: Context) = SavedComputerStore( + ProtectedRecordStore(File(context.noBackupFilesDir, "saved-computers"), RecordCipher(AndroidCredentialKey)), + ) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/SessionListing.kt b/android/app/src/main/kotlin/app/bighelp/android/live/SessionListing.kt new file mode 100644 index 00000000..299ded25 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/SessionListing.kt @@ -0,0 +1,78 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.chat.ArchiveState +import app.bighelp.hermes.chat.CatalogState +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale + +/** What a retained chat is doing right now, from its own live state and nothing else. */ +internal enum class RowStatus { Idle, Working, NeedsYou } + +internal data class SessionRowUi( + val ref: ConversationRef, + val title: String, + val agentName: String, + val preview: String, + /** Null when the host gave no time (a Bot Chat only the registry names): nothing is invented. */ + val lastActiveEpochSeconds: Double?, + val status: RowStatus, + val isBotChat: Boolean, + val pinned: Boolean, +) + +internal object SessionListing { + /** Pinned first, then newest activity. A chat someone archived on purpose is in Archived chats, not here. */ + fun rows(catalog: CatalogState, conversations: Map, search: String): List { + val query = search.trim() + val names = catalog.agents.associate { it.id to it.displayName.ifBlank { it.id } } + return catalog.sessions + .distinctBy { it.ref } + .filter { it.archive != ArchiveState.Deliberate } + .map { session -> + val live = conversations[session.ref] + val draft = live?.draft?.trim().orEmpty() + SessionRowUi( + ref = session.ref, + title = session.title.ifBlank { if (session.isCanonicalBotChat) "Bot Chat" else "Chat" }, + agentName = names[session.profile] ?: session.profile, + preview = if (draft.isNotEmpty()) "Draft: ${draft.replace('\n', ' ')}" else session.preview.replace('\n', ' '), + lastActiveEpochSeconds = session.lastActiveEpochSeconds, + status = when { + live == null -> RowStatus.Idle + live.prompts.isNotEmpty() -> RowStatus.NeedsYou + live.running -> RowStatus.Working + else -> RowStatus.Idle + }, + isBotChat = session.isCanonicalBotChat, + pinned = session.pinned, + ) + } + .filter { row -> + query.isEmpty() || row.title.contains(query, ignoreCase = true) || row.agentName.contains(query, ignoreCase = true) || + row.preview.contains(query, ignoreCase = true) + } + .sortedWith(compareByDescending { it.pinned }.thenByDescending { it.lastActiveEpochSeconds ?: Double.NEGATIVE_INFINITY }) + } + + /** "now", "5 min", "3 h", "2 d", then a short date. Empty for an unknown time. */ + fun relativeTime( + epochSeconds: Double?, + nowMillis: Long, + zone: ZoneId = ZoneId.systemDefault(), + locale: Locale = Locale.getDefault(), + ): String { + if (epochSeconds == null) return "" + val seconds = (nowMillis / 1000.0 - epochSeconds).toLong() + return when { + seconds < 60 -> "now" + seconds < 3_600 -> "${seconds / 60} min" + seconds < 86_400 -> "${seconds / 3_600} h" + seconds < 7 * 86_400 -> "${seconds / 86_400} d" + else -> DateTimeFormatter.ofPattern("MMM d", locale).withZone(zone).format(Instant.ofEpochSecond(epochSeconds.toLong())) + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/live/TranscriptRows.kt b/android/app/src/main/kotlin/app/bighelp/android/live/TranscriptRows.kt new file mode 100644 index 00000000..15d1a682 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/TranscriptRows.kt @@ -0,0 +1,69 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.chat.ActivityItem +import app.bighelp.hermes.chat.ActivityKind +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.ItemOrigin +import app.bighelp.hermes.chat.MessageItem +import app.bighelp.hermes.chat.MessageRole + +/** One line of the live transcript. [key] is the repository's own item ID, so a row keeps its identity across every update. */ +internal sealed interface ChatRow { + val key: String + + data class Message(val item: MessageItem, val canBranch: Boolean) : ChatRow { + override val key get() = item.id + } + + data class Activity(val item: ActivityItem) : ChatRow { + override val key get() = item.id + } + + /** System text, a command's output or a notice: shown quietly, not as a speech bubble. */ + data class Note(override val key: String, val text: String) : ChatRow + + /** The top of the retained history, when the host has older messages to read. */ + data class History(val loading: Boolean) : ChatRow { + override val key get() = "history" + } + + /** The end of a running turn: what the host says it is doing. Never a percentage. */ + data class Working(val label: String) : ChatRow { + override val key get() = "working" + } +} + +internal object TranscriptRows { + /** Keys must be unique in a lazy list, so a later row with a key already used is dropped (the first is kept). */ + fun rows(state: ConversationState): List = mapped(state).distinctBy { it.key } + + private fun mapped(state: ConversationState): List = state.items.mapNotNull { item -> + when (item) { + is MessageItem -> when { + item.role == MessageRole.User || item.role == MessageRole.Assistant -> when { + item.isCommandResult -> ChatRow.Note(item.id, item.text) + // A reply that has not produced text yet is the working line's business, not an empty bubble. + item.text.isEmpty() && !item.hasUnsupportedContent -> null + else -> ChatRow.Message(item, canBranch = item.rowId != null && item.origin == ItemOrigin.Saved) + } + item.text.isNotBlank() -> ChatRow.Note(item.id, item.text) + else -> null + } + is ActivityItem -> if (item.kind == ActivityKind.Notice) ChatRow.Note(item.id, item.title) else ChatRow.Activity(item) + } + } + + /** [rows] with the "earlier messages" row above and the working line below, when they apply. */ + fun withEdges(state: ConversationState): List = buildList { + if (state.history.hasOlder) add(ChatRow.History(state.history.loadingOlder)) + addAll(rows(state)) + workingLabel(state)?.let { add(ChatRow.Working(it)) } + }.distinctBy { it.key } + + /** The host's own status while a turn runs; nothing while idle. Never a percentage. */ + fun workingLabel(state: ConversationState): String? = when { + !state.running -> null + state.stopRequested -> "Stopping…" + else -> state.status?.takeIf { it.isNotBlank() } ?: "Working…" + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidChatStore.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidChatStore.kt new file mode 100644 index 00000000..4a303bdd --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidChatStore.kt @@ -0,0 +1,637 @@ +package app.bighelp.android.storage + +import android.content.Context +import app.bighelp.hermes.chat.ChatStore +import app.bighelp.hermes.chat.ChatStoreException +import app.bighelp.hermes.chat.HostScope +import app.bighelp.hermes.chat.RecordKey +import app.bighelp.hermes.chat.RecordKind +import app.bighelp.hermes.chat.StoreOp +import java.io.ByteArrayOutputStream +import java.io.DataOutputStream +import java.io.EOFException +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.nio.ByteBuffer +import java.nio.channels.FileChannel +import java.nio.charset.CodingErrorAction +import java.nio.file.Files +import java.nio.file.StandardCopyOption.ATOMIC_MOVE +import java.nio.file.StandardCopyOption.REPLACE_EXISTING +import java.nio.file.StandardOpenOption.CREATE +import java.nio.file.StandardOpenOption.READ +import java.nio.file.StandardOpenOption.WRITE +import java.security.MessageDigest +import java.util.zip.CRC32 +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * The chat repository's durable store on app-private, backup-excluded files. + * + * **Durable records** (drafts, the submission journal, create intents, identity) live in one append-only + * transaction log. A commit is exactly one CRC-protected frame, written and flushed before it becomes visible, + * so "all of its operations or none" holds across a crash without a recovery protocol: a restart replays whole + * frames and drops a torn tail. A write that fails is cut back off the file, so a refused send leaves no trace. + * Damage that is not a torn tail fails closed ([ChatStoreException.Kind.Corrupt]) instead of silently losing the + * records after it; [discardUnreadable] is the explicit local reset. The log is compacted (live records + * rewritten to a new file, then an atomic rename) when most of it is dead. Durable records are never evicted. + * + * **Cache records** (catalog, retained history) are one checksummed file each under `cache/`, written best + * effort and evicted oldest-first past a byte budget. A damaged cache file is dropped, never reported. + * + * Nothing secret is stored here (the repository never writes one); credentials stay in the Keystore-sealed + * stores. This store assumes one process, which is how the app runs. + */ +class AndroidChatStore internal constructor( + private val directory: File, + private val dispatcher: CoroutineDispatcher, + private val files: ChatStoreFiles, + private val tuning: ChatStoreTuning, +) : ChatStore { + constructor(directory: File, dispatcher: CoroutineDispatcher = Dispatchers.IO) : + this(directory, dispatcher, SystemChatStoreFiles, ChatStoreTuning()) + + private class Slot(val position: Long, val length: Int, val crc: Int) + private class Encoded(val bytes: ByteArray, val puts: List>) + + private val lock = Any() + private var logFile: ChatLogFile? = null + private var index = HashMap() + private var goodLength = 0L + private var liveBytes = 0L + private var loadFailure: ChatStoreException? = null + private var nextCompactionGarbage = tuning.compactionMinimumGarbage + + private val logPath get() = File(directory, LOG_NAME) + private val cacheDirectory get() = File(directory, CACHE_NAME) + + // ---- ChatStore + + override suspend fun read(key: RecordKey): ByteArray? = withContext(dispatcher) { + synchronized(lock) { if (key.kind.durable) readDurable(key) else readCache(key) } + } + + override suspend fun keys(host: HostScope, kind: RecordKind, profile: String?, anchor: String?): List = + withContext(dispatcher) { + synchronized(lock) { + val all = if (kind.durable) { ensureLoaded(); index.keys.toList() } else cacheKeys() + all.filter { + it.kind == kind && it.host == host && (profile == null || it.profile == profile) && + (anchor == null || it.anchor == anchor) + }.sortedBy { it.canonical } + } + } + + override suspend fun commit(ops: List) { + var total = 0L + for (op in ops) when (op) { + is StoreOp.Put -> { + require(op.key.kind.durable) { "A cache record is not a durable commit" } + if (op.bytes.size > op.key.kind.maximumBytes) throw ChatStoreException(ChatStoreException.Kind.TooLarge) + total += op.bytes.size + } + is StoreOp.Delete -> require(op.key.kind.durable) { "A cache record is not a durable commit" } + } + if (total > tuning.maximumCommitBytes || ops.size > MAXIMUM_OPERATIONS) throw ChatStoreException(ChatStoreException.Kind.TooLarge) + if (ops.isEmpty()) return + withContext(dispatcher) { synchronized(lock) { commitLocked(ops) } } + } + + override suspend fun putCache(key: RecordKey, bytes: ByteArray) { + require(!key.kind.durable) { "A durable record is not a cache write" } + if (bytes.size > key.kind.maximumBytes) return + withContext(dispatcher) { synchronized(lock) { try { writeCache(key, bytes) } catch (_: IOException) { } catch (_: RuntimeException) { } } } + } + + override suspend fun deleteCache(key: RecordKey) { + require(!key.kind.durable) { "A durable record is not a cache delete" } + withContext(dispatcher) { synchronized(lock) { cacheFile(key).delete() } } + } + + // ---- app-side operations + + /** Removing a computer removes everything stored for it: durable records, then cached ones. Safe to run again. */ + suspend fun purge(computerId: String) = withContext(dispatcher) { + synchronized(lock) { + cacheDirectory.listFiles { file -> file.name.endsWith(CACHE_SUFFIX) }?.forEach { file -> + val key = try { readCacheHeader(file) } catch (_: IOException) { null } catch (_: RuntimeException) { null } + if (key == null || key.host.computerId == computerId) file.delete() + } + ensureLoaded() + val doomed = index.keys.filter { it.host.computerId == computerId } + for (chunk in doomed.chunked(PURGE_CHUNK)) commitLocked(chunk.map { StoreOp.Delete(it) }) + } + } + + /** + * Explicit local reset after [ChatStoreException.Kind.Corrupt]: removes the damaged log so a fresh one starts. + * The drafts and unresolved sends it held are gone, which is why only a deliberate action calls this. + */ + suspend fun discardUnreadable(): Boolean = withContext(dispatcher) { + synchronized(lock) { + try { + ensureLoaded() + false + } catch (failure: ChatStoreException) { + if (failure.kind != ChatStoreException.Kind.Corrupt) throw failure + resetHandle() + try { Files.deleteIfExists(logPath.toPath()); files.syncDirectory(directory) } catch (e: IOException) { + throw ChatStoreException(ChatStoreException.Kind.Unavailable, e) + } + loadFailure = null + true + } + } + } + + fun close() = synchronized(lock) { resetHandle() } + + // ---- durable log + + private fun ensureLoaded() { + loadFailure?.let { throw it } + if (logFile != null) return + try { + if (!directory.isDirectory && !directory.mkdirs() && !directory.isDirectory) throw IOException("No directory") + File(directory, COMPACT_NAME).delete() + val log = files.open(logPath) + try { + replay(log) + } catch (failure: Throwable) { + try { log.close() } catch (_: IOException) { } + index = HashMap(); liveBytes = 0; goodLength = 0 + throw failure + } + logFile = log + } catch (failure: ChatStoreException) { + if (failure.kind == ChatStoreException.Kind.Corrupt) loadFailure = failure + throw failure + } catch (failure: IOException) { + throw ChatStoreException(kindOf(failure), failure) + } + } + + /** Rebuilds the index from whole frames. A torn tail is cut off; damage followed by more data is [Corrupt]. */ + private fun replay(log: ChatLogFile) { + var size = log.size() + if (size < FILE_MAGIC.size) { + // Only a file that holds a prefix of our own header (a creation cut short) may be started over. + if (!FILE_MAGIC.copyOf(size.toInt()).contentEquals(log.read(0, size.toInt()))) throw corrupt() + log.truncate(0) + log.append(FILE_MAGIC) + log.sync() + files.syncDirectory(directory) + size = FILE_MAGIC.size.toLong() + } else if (!log.read(0, FILE_MAGIC.size).contentEquals(FILE_MAGIC)) { + throw corrupt() + } + var position = FILE_MAGIC.size.toLong() + val replayed = HashMap() + var torn = false + while (position < size) { + val remaining = size - position + if (remaining < FRAME_HEADER) { torn = true; break } + val header = ByteBuffer.wrap(log.read(position, FRAME_HEADER)) + val magic = ByteArray(4).also { header.get(it) } + if (!magic.contentEquals(FRAME_MAGIC)) { + // A crash can leave the tail zero-filled; anything else here is damage, not an interrupted write. + if (remaining <= TAIL_PROBE_BYTES && log.read(position, remaining.toInt()).all { it == 0.toByte() }) { torn = true; break } + throw corrupt() + } + val bodyLength = header.int + if (bodyLength < 4 || bodyLength > tuning.maximumCommitBytes + FRAME_SLACK) throw corrupt() + val frameEnd = position + FRAME_HEADER + bodyLength + 4 + if (frameEnd > size) { torn = true; break } + val frame = log.read(position, (frameEnd - position).toInt()) + if (crc(frame, 0, frame.size - 4) != ByteBuffer.wrap(frame, frame.size - 4, 4).int) { + // Only the very last frame can be an interrupted write; a bad frame with data after it is damage. + if (frameEnd == size) { torn = true; break } + throw corrupt() + } + applyFrame(frame, position, replayed) + position = frameEnd + } + if (torn) { + log.truncate(position) + log.sync() + } + index = replayed + goodLength = position + liveBytes = replayed.values.sumOf { it.length.toLong() } + } + + private fun applyFrame(frame: ByteArray, frameStart: Long, into: MutableMap) { + try { + val body = ByteBuffer.wrap(frame, FRAME_HEADER, frame.size - FRAME_HEADER - 4) + val count = body.int + if (count < 0 || count > MAXIMUM_OPERATIONS) throw corrupt() + repeat(count) { + val type = body.get().toInt() + val key = readKey(body) + when (type) { + OP_PUT -> { + val length = body.int + val crc = body.int + if (length < 0 || length > key.kind.maximumBytes || length > body.remaining()) throw corrupt() + into[key] = Slot(frameStart + body.position(), length, crc) + // Through Buffer: ByteBuffer.position(int) only returns ByteBuffer on newer Android runtimes. + (body as java.nio.Buffer).position(body.position() + length) + } + OP_DELETE -> into.remove(key) + else -> throw corrupt() + } + } + if (body.hasRemaining()) throw corrupt() + } catch (failure: ChatStoreException) { + throw failure + } catch (_: RuntimeException) { + throw corrupt() + } + } + + private fun readDurable(key: RecordKey): ByteArray? { + ensureLoaded() + val slot = index[key] ?: return null + val bytes = try { + logFile!!.read(slot.position, slot.length) + } catch (_: EOFException) { + throw corrupt() + } catch (failure: IOException) { + throw ChatStoreException(kindOf(failure), failure) + } + if (crc(bytes, 0, bytes.size) != slot.crc) throw corrupt() + return bytes + } + + private fun commitLocked(ops: List) { + val log = readyLog() + val frame = encode(ops) + val start = goodLength + try { + log.append(frame.bytes) + log.sync() + } catch (failure: IOException) { + // Take the failed frame back off the file. If even that fails, the next commit retries it first. + try { log.truncate(start); log.sync() } catch (_: IOException) { } + throw ChatStoreException(kindOf(failure), failure) + } + goodLength = start + frame.bytes.size + var put = 0 + for (op in ops) when (op) { + is StoreOp.Put -> { + val (_, offset, slot) = frame.puts[put++] + index.put(op.key, Slot(start + offset, slot.length, slot.crc))?.let { liveBytes -= it.length } + liveBytes += slot.length + } + is StoreOp.Delete -> index.remove(op.key)?.let { liveBytes -= it.length } + } + compactIfWorthIt() + } + + /** The open log, with any unconfirmed tail from an earlier failed write removed first. */ + private fun readyLog(): ChatLogFile { + ensureLoaded() + val log = logFile!! + try { + val size = log.size() + if (size < goodLength) throw corrupt() + if (size > goodLength) { log.truncate(goodLength); log.sync() } + } catch (failure: IOException) { + throw ChatStoreException(ChatStoreException.Kind.Unavailable, failure) + } + return log + } + + private fun encode(ops: List): Encoded { + val payload = ops.sumOf { (it as? StoreOp.Put)?.bytes?.size ?: 0 } + val out = ByteArrayOutputStream(FRAME_HEADER + 16 + payload + ops.size * 1_200) + val data = DataOutputStream(out) + data.write(FRAME_MAGIC) + data.writeInt(0) + data.writeInt(ops.size) + val puts = ArrayList>() + for (op in ops) when (op) { + is StoreOp.Put -> { + data.writeByte(OP_PUT) + writeKey(data, op.key) + val crc = crc(op.bytes, 0, op.bytes.size) + data.writeInt(op.bytes.size) + data.writeInt(crc) + puts += Triple(op.key, out.size(), Slot(0, op.bytes.size, crc)) + data.write(op.bytes) + } + is StoreOp.Delete -> { + data.writeByte(OP_DELETE) + writeKey(data, op.key) + } + } + val unsealed = out.toByteArray() + val frame = unsealed.copyOf(unsealed.size + 4) + ByteBuffer.wrap(frame).putInt(4, unsealed.size - FRAME_HEADER) + ByteBuffer.wrap(frame).putInt(unsealed.size, crc(frame, 0, unsealed.size)) + return Encoded(frame, puts) + } + + // ---- compaction + + private fun compactIfWorthIt() { + val garbage = goodLength - FILE_MAGIC.size - liveBytes + if (garbage < nextCompactionGarbage || garbage <= liveBytes) return + try { + compact() + nextCompactionGarbage = tuning.compactionMinimumGarbage + } catch (_: IOException) { + File(directory, COMPACT_NAME).delete() + nextCompactionGarbage = garbage + tuning.compactionMinimumGarbage + } catch (_: ChatStoreException) { + File(directory, COMPACT_NAME).delete() + nextCompactionGarbage = garbage + tuning.compactionMinimumGarbage + } + } + + /** Live records into a new file, flushed, then an atomic rename over the log. A crash leaves one or the other. */ + private fun compact() { + val temp = File(directory, COMPACT_NAME) + temp.delete() + val rewritten = HashMap() + var position = FILE_MAGIC.size.toLong() + val out = files.open(temp) + try { + out.append(FILE_MAGIC) + for ((key, slot) in index) { + val payload = readDurable(key) ?: continue + val frame = encode(listOf(StoreOp.Put(key, payload))) + out.append(frame.bytes) + rewritten[key] = Slot(position + frame.puts[0].second, slot.length, slot.crc) + position += frame.bytes.size + } + out.sync() + } finally { + out.close() + } + files.replace(temp, logPath) + files.syncDirectory(directory) + // The old handle names the replaced file; swap to the new one or force a reload. + resetHandle() + try { + logFile = files.open(logPath) + index = rewritten + goodLength = position + } catch (_: IOException) { + // The commit that led here is already durable; the next operation reloads from the compacted log. + } + } + + private fun resetHandle() { + try { logFile?.close() } catch (_: IOException) { } + logFile = null + } + + // ---- caches + + private fun cacheFile(key: RecordKey) = File(cacheDirectory, sha256(key.canonical) + CACHE_SUFFIX) + + private fun writeCache(key: RecordKey, bytes: ByteArray) { + val dir = cacheDirectory + if (!dir.isDirectory && !dir.mkdirs() && !dir.isDirectory) return + val target = cacheFile(key) + val temp = File(dir, ".${target.name}.tmp") + val head = ByteArrayOutputStream() + DataOutputStream(head).use { data -> + data.write(CACHE_MAGIC) + writeKey(data, key) + data.writeInt(bytes.size) + data.writeInt(crc(bytes, 0, bytes.size)) + } + try { + FileOutputStream(temp).use { out -> out.write(head.toByteArray()); out.write(bytes) } + SystemChatStoreFiles.replace(temp, target) + } finally { + temp.delete() + } + evictCaches(dir, keep = target) + } + + private fun evictCaches(dir: File, keep: File) { + val all = dir.listFiles() ?: return + all.filter { it.name.endsWith(".tmp") }.forEach { it.delete() } + val cached = all.filter { it.name.endsWith(CACHE_SUFFIX) } + var total = cached.sumOf { it.length() } + for (file in cached.sortedWith(compareBy({ it.lastModified() }, { it.name }))) { + if (total <= tuning.cacheBudgetBytes) break + if (file == keep) continue + total -= file.length() + file.delete() + } + } + + private fun readCache(key: RecordKey): ByteArray? { + val file = cacheFile(key) + if (!file.isFile) return null + try { + if (file.length() > key.kind.maximumBytes + CACHE_HEADER_SLACK) throw corrupt() + val raw = file.readBytes() + val buffer = ByteBuffer.wrap(raw) + val magic = ByteArray(CACHE_MAGIC.size).also { buffer.get(it) } + if (!magic.contentEquals(CACHE_MAGIC) || readKey(buffer) != key) throw corrupt() + val length = buffer.int + val crc = buffer.int + if (length < 0 || length != buffer.remaining() || length > key.kind.maximumBytes) throw corrupt() + val payload = ByteArray(length).also { buffer.get(it) } + if (crc(payload, 0, payload.size) != crc) throw corrupt() + return payload + } catch (_: IOException) { + file.delete() + } catch (_: ChatStoreException) { + file.delete() + } catch (_: RuntimeException) { + file.delete() + } + return null + } + + private fun readCacheHeader(file: File): RecordKey? { + val head = file.inputStream().use { stream -> + val probe = ByteArray(CACHE_HEADER_PROBE_BYTES) + var filled = 0 + while (filled < probe.size) { + val count = stream.read(probe, filled, probe.size - filled) + if (count < 0) break + filled += count + } + probe.copyOf(filled) + } + val buffer = ByteBuffer.wrap(head) + val magic = ByteArray(CACHE_MAGIC.size).also { buffer.get(it) } + return if (magic.contentEquals(CACHE_MAGIC)) readKey(buffer) else null + } + + private fun cacheKeys(): List = + cacheDirectory.listFiles { file -> file.name.endsWith(CACHE_SUFFIX) }.orEmpty().mapNotNull { file -> + try { readCacheHeader(file) } catch (_: IOException) { null } catch (_: RuntimeException) { null } + } + + // ---- encoding + + private fun writeKey(out: DataOutputStream, key: RecordKey) { + out.writeByte(kindCode(key.kind)) + writeString(out, key.host.computerId) + writeString(out, key.host.endpoint) + writeString(out, key.host.principal) + out.writeByte((if (key.profile != null) 1 else 0) or (if (key.anchor != null) 2 else 0) or (if (key.entry != null) 4 else 0)) + key.profile?.let { writeString(out, it) } + key.anchor?.let { writeString(out, it) } + key.entry?.let { writeString(out, it) } + } + + private fun readKey(buffer: ByteBuffer): RecordKey { + val kind = kindOf(buffer.get().toInt()) + val host = HostScope(readString(buffer), readString(buffer), readString(buffer)) + val flags = buffer.get().toInt() + if (flags and 7.inv() != 0) throw corrupt() + val profile = if (flags and 1 != 0) readString(buffer) else null + val anchor = if (flags and 2 != 0) readString(buffer) else null + val entry = if (flags and 4 != 0) readString(buffer) else null + return try { RecordKey.of(kind, host, profile, anchor, entry) } catch (_: IllegalArgumentException) { throw corrupt() } + } + + private fun writeString(out: DataOutputStream, value: String) { + val bytes = value.toByteArray(Charsets.UTF_8) + out.writeShort(bytes.size) + out.write(bytes) + } + + private fun readString(buffer: ByteBuffer): String { + val length = buffer.short.toInt() and 0xFFFF + if (length > buffer.remaining()) throw corrupt() + val bytes = ByteArray(length).also { buffer.get(it) } + return try { + Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)).toString() + } catch (_: java.nio.charset.CharacterCodingException) { + throw corrupt() + } + } + + // Fixed codes, not ordinals: reordering the enum must never change what a file means. + private fun kindCode(kind: RecordKind): Int = when (kind) { + RecordKind.Draft -> 1 + RecordKind.Journal -> 2 + RecordKind.Creation -> 3 + RecordKind.Identity -> 4 + RecordKind.CatalogCache -> 5 + RecordKind.HistoryCache -> 6 + } + + private fun kindOf(code: Int): RecordKind = when (code) { + 1 -> RecordKind.Draft + 2 -> RecordKind.Journal + 3 -> RecordKind.Creation + 4 -> RecordKind.Identity + 5 -> RecordKind.CatalogCache + 6 -> RecordKind.HistoryCache + else -> throw corrupt() + } + + private fun kindOf(failure: IOException): ChatStoreException.Kind { + val text = failure.message.orEmpty().lowercase() + return if ("no space left" in text || "quota" in text) ChatStoreException.Kind.QuotaExceeded else ChatStoreException.Kind.Unavailable + } + + private fun corrupt() = ChatStoreException(ChatStoreException.Kind.Corrupt) + + private fun crc(bytes: ByteArray, offset: Int, length: Int): Int = CRC32().apply { update(bytes, offset, length) }.value.toInt() + + private fun sha256(text: String): String = + MessageDigest.getInstance("SHA-256").digest(text.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) } + + companion object { + internal const val LOG_NAME = "durable.log" + internal const val COMPACT_NAME = "durable.log.compact" + private const val CACHE_NAME = "cache" + private const val CACHE_SUFFIX = ".cache" + private val FILE_MAGIC = "BHCHATL1".toByteArray(Charsets.US_ASCII) + private val FRAME_MAGIC = "BHFR".toByteArray(Charsets.US_ASCII) + private val CACHE_MAGIC = "BHCHATC1".toByteArray(Charsets.US_ASCII) + private const val FRAME_HEADER = 8 + private const val FRAME_SLACK = 1 shl 20 + private const val TAIL_PROBE_BYTES = 1 shl 16 + private const val CACHE_HEADER_SLACK = 8_192 + private const val CACHE_HEADER_PROBE_BYTES = 4_096 + private const val OP_PUT = 1 + private const val OP_DELETE = 2 + private const val MAXIMUM_OPERATIONS = 4_096 + private const val PURGE_CHUNK = 1_024 + + fun create(context: Context) = AndroidChatStore(File(context.noBackupFilesDir, "chat-store")) + } +} + +/** Sizes that tests shrink; the defaults are the shipping values. */ +internal class ChatStoreTuning( + /** Dead bytes in the log before a rewrite is considered (it must also exceed the live bytes). */ + val compactionMinimumGarbage: Long = 4L * 1024 * 1024, + /** Total cache bytes kept; the oldest files go first. */ + val cacheBudgetBytes: Long = 96L * 1024 * 1024, + /** One commit's payload ceiling. No documented record combination comes near it. */ + val maximumCommitBytes: Int = 24 * 1024 * 1024, +) + +/** The log file operations, as a seam so a test can fail a write, a flush, a truncate or a rename. */ +internal interface ChatLogFile : AutoCloseable { + fun size(): Long + fun read(position: Long, length: Int): ByteArray + fun append(bytes: ByteArray) + fun sync() + fun truncate(size: Long) +} + +internal interface ChatStoreFiles { + fun open(file: File): ChatLogFile + fun replace(from: File, to: File) + fun syncDirectory(directory: File) +} + +internal object SystemChatStoreFiles : ChatStoreFiles { + override fun open(file: File): ChatLogFile = SystemLogFile(FileChannel.open(file.toPath(), CREATE, READ, WRITE)) + + override fun replace(from: File, to: File) { + Files.move(from.toPath(), to.toPath(), ATOMIC_MOVE, REPLACE_EXISTING) + } + + override fun syncDirectory(directory: File) { + FileChannel.open(directory.toPath(), READ).use { it.force(true) } + } +} + +private class SystemLogFile(private val channel: FileChannel) : ChatLogFile { + override fun size(): Long = channel.size() + + override fun read(position: Long, length: Int): ByteArray { + val buffer = ByteBuffer.allocate(length) + var at = position + while (buffer.hasRemaining()) { + val count = channel.read(buffer, at) + if (count < 0) throw EOFException() + at += count + } + return buffer.array() + } + + override fun append(bytes: ByteArray) { + val buffer = ByteBuffer.wrap(bytes) + var at = channel.size() + while (buffer.hasRemaining()) at += channel.write(buffer, at) + } + + override fun sync() = channel.force(true) + + override fun truncate(size: Long) { + channel.truncate(size) + } + + override fun close() = channel.close() +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt new file mode 100644 index 00000000..dec2ce25 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt @@ -0,0 +1,35 @@ +package app.bighelp.android.storage + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.security.KeyStore +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey + +/** Device-local, non-exportable key, usable after first unlock without a prompt for background renewal. */ +object AndroidCredentialKey : RecordKeyProvider by AndroidKeyStoreRecordKeys("bighelp.credentials.v1") + +internal class AndroidKeyStoreRecordKeys(private val alias: String) : RecordKeyProvider { + @Synchronized + override fun existing(): SecretKey? { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + if (!store.containsAlias(alias)) return null + return store.getKey(alias, null) as? SecretKey + ?: throw RecordStorageException(StorageProblem.KeyUnavailable) + } + + @Synchronized + override fun getOrCreate(): SecretKey { + existing()?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init( + KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setKeySize(256) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setRandomizedEncryptionRequired(true) + .build(), + ) + }.generateKey() + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt new file mode 100644 index 00000000..415a33fb --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt @@ -0,0 +1,143 @@ +package app.bighelp.android.storage + +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.nio.channels.FileChannel +import java.nio.file.Files +import java.nio.file.NoSuchFileException +import java.nio.file.Path +import java.nio.file.StandardCopyOption.ATOMIC_MOVE +import java.nio.file.StandardCopyOption.REPLACE_EXISTING +import java.nio.file.StandardOpenOption.CREATE +import java.nio.file.StandardOpenOption.READ +import java.nio.file.StandardOpenOption.WRITE +import java.security.MessageDigest +import java.util.concurrent.ConcurrentHashMap + +/** + * Encrypted, atomic compare-and-replace for records in an app-private, backup-excluded directory. + * Run on an I/O dispatcher. The credential adapter supplies an unambiguous authority-bound record key. + */ +class ProtectedRecordStore internal constructor( + private val directory: File, + private val cipher: RecordCipher, + private val files: RecordFileOperations, +) { + constructor(directory: File, cipher: RecordCipher) : this(directory, cipher, SystemRecordFileOperations) + + fun read(key: String): ByteArray? = locked(key) { file -> readRecord(key, file) } + + /** A disk error after rename/delete can mean it committed. Read back before retrying any write. */ + fun compareAndSet(key: String, expected: ByteArray?, replacement: ByteArray?): Boolean = locked(key) { file -> + if (replacement != null && replacement.size > RecordCipher.MAXIMUM_RECORD_BYTES) { + throw RecordStorageException(StorageProblem.RecordTooLarge) + } + val current = readRecord(key, file) + val matches = if (expected == null || current == null) expected == null && current == null + else MessageDigest.isEqual(expected, current) + if (!matches) return@locked false + if (replacement == null) { + Files.deleteIfExists(file.toPath()) + syncDirectory() + } else { + writeRecord(file, cipher.encrypt(key, replacement)) + } + true + } + + /** Deliberate local recovery only. A valid record or a transient failure is never discarded. */ + fun discardUnreadable(key: String): Boolean = locked(key) { file -> + try { + readRecord(key, file) + false + } catch (failure: RecordStorageException) { + if (failure.problem !in setOf(StorageProblem.CorruptRecord, StorageProblem.RecordTooLarge, StorageProblem.KeyMissing)) { + throw failure + } + Files.deleteIfExists(file.toPath()) + syncDirectory() + true + } + } + + private fun readRecord(key: String, file: File): ByteArray? { + val stream = try { + files.read(file) + } catch (_: NoSuchFileException) { + return null + } + val bytes = stream.use { input -> + val output = ByteArrayOutputStream() + val buffer = ByteArray(8_192) + while (true) { + val count = input.read(buffer, 0, minOf(buffer.size, RecordCipher.MAXIMUM_ENVELOPE_BYTES + 1 - output.size())) + if (count < 0) break + output.write(buffer, 0, count) + if (output.size() > RecordCipher.MAXIMUM_ENVELOPE_BYTES) { + throw RecordStorageException(StorageProblem.RecordTooLarge) + } + } + output.toByteArray() + } + return cipher.decrypt(key, bytes) + } + + private fun writeRecord(file: File, bytes: ByteArray) { + val pending = File.createTempFile(".record-", ".pending", directory) + try { + files.write(pending).use { output -> + output.write(bytes) + output.fd.sync() + } + // Never replace a valid credential with a partly written file. + files.move(pending.toPath(), file.toPath()) + syncDirectory() + } finally { + Files.deleteIfExists(pending.toPath()) + } + } + + private fun syncDirectory() { + FileChannel.open(directory.toPath(), READ).use { it.force(true) } + } + + private fun locked(key: String, body: (File) -> T): T { + val binding = recordBindingBytes(key) + try { + Files.createDirectories(directory.toPath()) + val digest = MessageDigest.getInstance("SHA-256").digest(binding) + .joinToString("") { "%02x".format(it) } + val file = File(directory, "$digest.sealed") + val monitor = monitors.computeIfAbsent(file.canonicalPath) { Any() } + return synchronized(monitor) { + FileChannel.open(File(directory, "$digest.lock").toPath(), CREATE, WRITE).use { channel -> + // The monitor handles multiple authenticators in this process; the lock covers another process. + channel.lock().use { body(file) } + } + } + } catch (_: IOException) { + throw RecordStorageException(StorageProblem.DiskUnavailable) + } + } + + private companion object { + val monitors = ConcurrentHashMap() + } +} + +internal interface RecordFileOperations { + fun read(file: File): InputStream + fun write(file: File): FileOutputStream + fun move(from: Path, to: Path) +} + +internal object SystemRecordFileOperations : RecordFileOperations { + override fun read(file: File): InputStream = Files.newInputStream(file.toPath()) + override fun write(file: File) = FileOutputStream(file) + override fun move(from: Path, to: Path) { + Files.move(from, to, ATOMIC_MOVE, REPLACE_EXISTING) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt new file mode 100644 index 00000000..1e396cd4 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -0,0 +1,105 @@ +package app.bighelp.android.storage + +import java.security.GeneralSecurityException +import java.security.ProviderException +import java.nio.CharBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction +import javax.crypto.AEADBadTagException +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +enum class StorageProblem { CorruptRecord, RecordTooLarge, KeyMissing, KeyUnavailable, DiskUnavailable, InvalidBinding } + +/** Carries a category, never a credential, authority or filesystem path. */ +class RecordStorageException(val problem: StorageProblem) : Exception(problem.name) + +interface RecordKeyProvider { + fun existing(): SecretKey? + fun getOrCreate(): SecretKey +} + +/** The record binding is authenticated too, so ciphertext cannot be adopted under another key. */ +class RecordCipher internal constructor( + private val keys: RecordKeyProvider, + private val cipherFactory: () -> Cipher, +) { + constructor(keys: RecordKeyProvider) : this(keys, { Cipher.getInstance("AES/GCM/NoPadding") }) + internal constructor(key: () -> SecretKey) : this(object : RecordKeyProvider { + override fun existing() = key() + override fun getOrCreate() = key() + }) + + fun encrypt(binding: String, plaintext: ByteArray): ByteArray { + if (plaintext.size > MAXIMUM_RECORD_BYTES) throw RecordStorageException(StorageProblem.RecordTooLarge) + val bindingBytes = recordBindingBytes(binding) + val secret = deviceKey(create = true) + try { + val cipher = cipherFactory() + cipher.init(Cipher.ENCRYPT_MODE, secret) + cipher.updateAAD(MAGIC) + cipher.updateAAD(bindingBytes) + val nonce = cipher.iv + if (nonce.size != NONCE_BYTES) throw RecordStorageException(StorageProblem.KeyUnavailable) + return MAGIC + nonce + cipher.doFinal(plaintext) + } catch (_: GeneralSecurityException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } catch (_: ProviderException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } + } + + fun decrypt(binding: String, envelope: ByteArray): ByteArray { + if (envelope.size > MAXIMUM_ENVELOPE_BYTES) throw RecordStorageException(StorageProblem.RecordTooLarge) + if (envelope.size < OVERHEAD_BYTES || !envelope.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) { + throw RecordStorageException(StorageProblem.CorruptRecord) + } + val bindingBytes = recordBindingBytes(binding) + val secret = deviceKey(create = false) + try { + val cipher = cipherFactory() + val nonce = envelope.copyOfRange(MAGIC.size, MAGIC.size + NONCE_BYTES) + cipher.init(Cipher.DECRYPT_MODE, secret, GCMParameterSpec(128, nonce)) + cipher.updateAAD(MAGIC) + cipher.updateAAD(bindingBytes) + return cipher.doFinal(envelope, MAGIC.size + NONCE_BYTES, envelope.size - MAGIC.size - NONCE_BYTES) + } catch (_: AEADBadTagException) { + throw RecordStorageException(StorageProblem.CorruptRecord) + } catch (_: GeneralSecurityException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } catch (_: ProviderException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } + } + + private fun deviceKey(create: Boolean): SecretKey = try { + keys.existing() ?: if (create) keys.getOrCreate() else throw RecordStorageException(StorageProblem.KeyMissing) + } catch (failure: RecordStorageException) { + throw failure + } catch (_: Exception) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } + + companion object { + const val MAXIMUM_RECORD_BYTES = 65_536 + private val MAGIC = "BHCREDS1".toByteArray(Charsets.US_ASCII) + private const val NONCE_BYTES = 12 + private val OVERHEAD_BYTES = MAGIC.size + NONCE_BYTES + 16 + val MAXIMUM_ENVELOPE_BYTES = MAXIMUM_RECORD_BYTES + OVERHEAD_BYTES + } +} + +internal fun recordBindingBytes(binding: String): ByteArray { + if (binding.isEmpty() || binding.length > 8_192) throw RecordStorageException(StorageProblem.InvalidBinding) + val encoded = try { + Charsets.UTF_8.newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(binding)) + } catch (_: CharacterCodingException) { + throw RecordStorageException(StorageProblem.InvalidBinding) + } + if (encoded.remaining() > 8_192) throw RecordStorageException(StorageProblem.InvalidBinding) + return ByteArray(encoded.remaining()).also(encoded::get) +} diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 00000000..a71674a2 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 00000000..5c84730c --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 00000000..14d327e6 --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,9 @@ + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..de4c9ac1 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + + + #F5F2EF + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..f9448dbf --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,9 @@ + + + + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000..e74a1da0 --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 00000000..e2ab39f5 --- /dev/null +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/android/app/src/test/kotlin/app/bighelp/android/AccessInputTest.kt b/android/app/src/test/kotlin/app/bighelp/android/AccessInputTest.kt new file mode 100644 index 00000000..b4f1dadc --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/AccessInputTest.kt @@ -0,0 +1,43 @@ +package app.bighelp.android + +import app.bighelp.android.live.AccessSetup +import app.bighelp.hermes.AccessCredential +import app.bighelp.hermes.HermesEndpoint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class AccessInputTest { + private fun invalid(input: AccessInput) = (input.build() as AccessBuild.Invalid).problem + + @Test fun nothingEnteredIsNoGate() { + assertEquals(AccessSetup.None, (AccessInput().build() as AccessBuild.Ok).setup) + assertTrue(AccessInput(headers = listOf("" to "", " " to " ")).build() is AccessBuild.Ok) + } + + @Test fun eachKindBuildsTheMatchingCredentialAndHeaders() { + val cloudflare = (AccessInput(AccessKind.Cloudflare, "cf-id-0123", "cf-secret-0123").build() as AccessBuild.Ok).setup + assertEquals(AccessCredential.Kind.CloudflareAccess, cloudflare.credential!!.kind) + val proxy = (AccessInput(AccessKind.ProxyLogin, "gate-user", "gate-pass", listOf("X-Access-Id" to "synthetic")).build() as AccessBuild.Ok).setup + assertEquals(AccessCredential.Kind.ProxyBasic, proxy.credential!!.kind) + assertEquals(listOf("X-Access-Id"), proxy.custom.map { it.name }) + val endpoint = HermesEndpoint.parse("https://gated.example.test") + assertEquals(setOf("Authorization", "X-Access-Id"), proxy.headers(endpoint).values.keys) + } + + @Test fun eachMistakeHasItsOwnPlainProblem() { + assertEquals(AccessProblem.Credential, invalid(AccessInput(AccessKind.Cloudflare, "has space", "x"))) + assertEquals(AccessProblem.Credential, invalid(AccessInput(AccessKind.ProxyLogin, "a:b", "pw"))) + assertEquals(AccessProblem.Credential, invalid(AccessInput(AccessKind.ProxyLogin, "", ""))) + assertEquals(AccessProblem.HeaderName, invalid(AccessInput(headers = listOf("bad name" to "v")))) + assertEquals(AccessProblem.HeaderReserved, invalid(AccessInput(headers = listOf("Authorization" to "v")))) + assertEquals(AccessProblem.HeaderValue, invalid(AccessInput(headers = listOf("X-One" to "")))) + assertEquals(AccessProblem.HeaderDuplicate, invalid(AccessInput(headers = listOf("X-One" to "1", "x-one" to "2")))) + assertEquals(AccessProblem.TooManyHeaders, invalid(AccessInput(headers = (1..17).map { "X-H$it" to "v" }))) + } + + @Test fun theDefaultNameOfAComputerIsItsHostWithoutPortOrPrefix() { + assertEquals("hermes.example.com", defaultComputerName(HermesEndpoint.parse("https://hermes.example.com/prefix"))) + assertEquals("192.168.1.20", defaultComputerName(HermesEndpoint.parse("http://192.168.1.20:9119", allowPrivateHttp = true))) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt new file mode 100644 index 00000000..d1f2855e --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt @@ -0,0 +1,377 @@ +package app.bighelp.android + +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesEndpointException.Reason +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private class FakePreferences( + override var aiDataAgreed: Boolean = false, + override var appearance: Appearance = Appearance.Automatic, +) : PreviewPreferences + +/** Records every request it is asked to make; [answer] decides when and how each one finishes. */ +private class RecordingChecker( + var answer: suspend () -> DiscoveryResult = { DiscoveryResult.Unavailable }, +) : HostChecker { + val calls = mutableListOf>() + var cancelled = 0 + + override suspend fun check(endpoint: HermesEndpoint, consentGranted: Boolean): DiscoveryResult { + calls += endpoint.canonical to consentGranted + try { + return answer() + } catch (e: CancellationException) { + cancelled++ + throw e + } + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class AppModelTest { + private fun TestScope.model( + preferences: FakePreferences = FakePreferences(), + checker: RecordingChecker = RecordingChecker(), + ) = BighelpAppModel(preferences, checker, backgroundScope) + + private fun BighelpAppModel.demo() = state.value.demo!! + + // -- consent and the host check ------------------------------------------------------------ + + @Test fun connectingAsksForTheAgreementFirstAndNothingIsCheckedUntilItIsGiven() = runTest { + val preferences = FakePreferences() + val checker = RecordingChecker() + val model = model(preferences, checker) + + model.connectComputer() + assertEquals(Route.Consent, model.state.value.route) + + model.setAddress("hermes.example") + model.checkHost() + runCurrent() + assertTrue(checker.calls.isEmpty()) + assertEquals(Route.Consent, model.state.value.route) + + model.agreeToAiData() + assertTrue(preferences.aiDataAgreed) + // Consent is replaced by setup, so Back from setup does not show the agreement again. + assertEquals(listOf(Route.Welcome, Route.Setup), model.state.value.backStack) + + model.checkHost() + runCurrent() + assertEquals(listOf("https://hermes.example" to true), checker.calls) + } + + @Test fun anEarlierAgreementGoesStraightToSetup() = runTest { + val model = model(FakePreferences(aiDataAgreed = true)) + model.connectComputer() + assertEquals(Route.Setup, model.state.value.route) + assertTrue(model.state.value.consentGranted) + } + + @Test fun anInvalidAddressNeverReachesTheNetworkAndNeverEchoesTheInput() = runTest { + val checker = RecordingChecker() + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + + model.setAddress("http://hermes.example") + model.checkHost() + assertEquals(DiscoveryState.AddressProblem(Reason.PlaintextNotAllowed), model.state.value.setup.discovery) + + model.setAddress("user:secret@hermes.example") + model.checkHost() + assertEquals(DiscoveryState.AddressProblem(Reason.InvalidEndpoint), model.state.value.setup.discovery) + + runCurrent() + assertTrue(checker.calls.isEmpty()) + } + + @Test fun privateHttpNeedsTheExplicitSwitchAndAPrivateAddress() = runTest { + val checker = RecordingChecker() + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + + model.setAddress("http://192.168.1.20:9119") + model.checkHost() + assertEquals(DiscoveryState.AddressProblem(Reason.PlaintextNotAllowed), model.state.value.setup.discovery) + + model.setAllowPrivateHttp(true) + assertEquals(DiscoveryState.Idle, model.state.value.setup.discovery) + model.checkHost() + runCurrent() + assertEquals(listOf("http://192.168.1.20:9119" to true), checker.calls) + + // A public address stays refused even with the switch on. + model.setAddress("http://hermes.example.com") + model.checkHost() + assertEquals(DiscoveryState.AddressProblem(Reason.PlaintextNotAllowed), model.state.value.setup.discovery) + } + + @Test fun aFoundComputerIsNotAConnection() = runTest { + val checker = RecordingChecker { DiscoveryResult.Available(authRequired = true, browserSignIn = true) } + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + model.setAddress(" hermes.example/hermes \n") + model.checkHost() + runCurrent() + + assertEquals( + DiscoveryState.Found("https://hermes.example/hermes", authRequired = true, browserSignIn = true), + model.state.value.setup.discovery, + ) + // Still on setup; no demo, no chat, nothing opened. + assertEquals(Route.Setup, model.state.value.route) + assertNull(model.state.value.demo) + } + + @Test fun anUnreachableComputerIsReportedWithoutDetail() = runTest { + val checker = RecordingChecker { DiscoveryResult.Unavailable } + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + model.setAddress("hermes.example") + model.checkHost() + runCurrent() + assertEquals(DiscoveryState.Unavailable("https://hermes.example"), model.state.value.setup.discovery) + } + + @Test fun onlyOneCheckRunsAtATime() = runTest { + val gate = CompletableDeferred() + val checker = RecordingChecker { gate.await() } + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + model.setAddress("hermes.example") + + model.checkHost() + model.checkHost() + runCurrent() + assertEquals(1, checker.calls.size) + assertEquals(DiscoveryState.Checking, model.state.value.setup.discovery) + + gate.complete(DiscoveryResult.Available(authRequired = false, browserSignIn = false)) + runCurrent() + assertTrue(model.state.value.setup.discovery is DiscoveryState.Found) + } + + @Test fun changingTheInputDropsTheOldResultAndCancelsTheCheck() = runTest { + val checker = RecordingChecker { CompletableDeferred().await() } + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + model.setAddress("old.example") + model.checkHost() + runCurrent() + + model.setAddress("new.example") + assertEquals(DiscoveryState.Idle, model.state.value.setup.discovery) + runCurrent() + assertEquals(1, checker.cancelled) + assertEquals("new.example", model.state.value.setup.address) + } + + @Test fun anAnswerThatArrivesAfterTheInputChangedIsNeverApplied() = runTest { + // A checker that swallows cancellation and still answers: only the model's own fence stops it. + val checker = RecordingChecker { + try { + CompletableDeferred().await() + } catch (_: CancellationException) { + DiscoveryResult.Available(authRequired = false, browserSignIn = false) + } + } + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + model.setAddress("old.example") + model.checkHost() + runCurrent() + + model.setAddress("new.example") + runCurrent() + assertEquals(DiscoveryState.Idle, model.state.value.setup.discovery) + + // The new input can be checked normally afterwards. + checker.answer = { DiscoveryResult.Unavailable } + model.checkHost() + runCurrent() + assertEquals(DiscoveryState.Unavailable("https://new.example"), model.state.value.setup.discovery) + } + + @Test fun leavingSetupCancelsTheCheckInFlight() = runTest { + val checker = RecordingChecker { CompletableDeferred().await() } + val model = model(FakePreferences(aiDataAgreed = true), checker) + model.connectComputer() + model.setAddress("hermes.example") + model.checkHost() + runCurrent() + + assertTrue(model.back()) + runCurrent() + assertEquals(1, checker.cancelled) + assertEquals(DiscoveryState.Idle, model.state.value.setup.discovery) + assertEquals(Route.Welcome, model.state.value.route) + } + + // -- demo --------------------------------------------------------------------------------- + + @Test fun theDemoIsSampleDataThatNeedsNeitherAgreementNorTheNetwork() = runTest { + val preferences = FakePreferences() + val checker = RecordingChecker() + val model = model(preferences, checker) + + model.tryDemo() + runCurrent() + + assertEquals(Route.Sessions, model.state.value.route) + assertFalse(preferences.aiDataAgreed) + assertTrue(checker.calls.isEmpty()) + assertTrue(model.demo().sessions.isNotEmpty()) + assertTrue(model.demo().agents.size >= 2) + } + + @Test fun sendingInTheDemoAddsYourMessageAndOneFixedExampleReply() = runTest { + val model = model() + model.tryDemo() + model.startNewChat() + val id = (model.state.value.route as Route.Chat).sessionId + + model.setDraft(id, " What should I pack? ") + assertTrue(model.send(id)) + val session = model.demo().session(id)!! + assertEquals(2, session.messages.size) + assertEquals("What should I pack?", session.messages[0].text) + assertTrue(session.messages[0].fromUser) + assertFalse(session.messages[0].isExample) + assertFalse(session.messages[1].fromUser) + assertTrue(session.messages[1].isExample) + assertEquals("What should I pack?", session.title) + assertNull(model.demo().drafts[id]) + assertEquals(id, model.demo().sessions.first().id) + + // The reply is fixed text, the same every time, and says it is an example. + model.setDraft(id, "Anything else?") + model.send(id) + val replies = model.demo().session(id)!!.messages.filter { it.isExample } + assertEquals(2, replies.size) + assertEquals(replies[0].text, replies[1].text) + assertTrue(replies[0].text.contains("example", ignoreCase = true)) + assertEquals(4, model.demo().session(id)!!.messages.map { it.id }.toSet().size) + } + + @Test fun aLongFirstMessageTitleNeverCutsAnEmojiInHalf() = runTest { + val model = model() + model.tryDemo() + model.startNewChat() + val id = (model.state.value.route as Route.Chat).sessionId + + // The 40-character title limit falls between the two halves of the emoji (a surrogate pair). + val message = "a".repeat(39) + "😀 and some more words" + model.setDraft(id, message) + assertTrue(model.send(id)) + + val session = model.demo().session(id)!! + assertEquals("a".repeat(39) + "…", session.title) + assertEquals(message, session.messages[0].text) + } + + @Test fun aBlankDraftDoesNotSend() = runTest { + val model = model() + model.tryDemo() + model.startNewChat() + val id = (model.state.value.route as Route.Chat).sessionId + model.setDraft(id, " \n ") + assertFalse(model.send(id)) + assertTrue(model.demo().session(id)!!.messages.isEmpty()) + } + + @Test fun aDraftSurvivesLeavingAndReturningToAChat() = runTest { + val model = model() + model.tryDemo() + val first = model.demo().sessions.first().id + model.openChat(first) + model.setDraft(first, "Remember the sunscreen") + + assertTrue(model.back()) + assertEquals(Route.Sessions, model.state.value.route) + assertEquals("Remember the sunscreen", model.demo().drafts[first]) + + model.openChat(first) + assertEquals("Remember the sunscreen", model.demo().drafts[first]) + + // Clearing the box clears the stored draft, not just the visible one. + model.setDraft(first, "") + assertNull(model.demo().drafts[first]) + } + + @Test fun newChatReusesAnEmptyChatAndStartsWithTheSelectedAgent() = runTest { + val model = model() + model.tryDemo() + val agent = model.demo().agents.last() + model.selectAgent(agent.id) + + model.startNewChat() + val first = (model.state.value.route as Route.Chat).sessionId + assertEquals(agent.id, model.demo().session(first)!!.agentId) + assertEquals(listOf(Route.Sessions, Route.Chat(first)), model.state.value.backStack) + + model.back() + val before = model.demo().sessions.size + model.startNewChat() + assertEquals(Route.Chat(first), model.state.value.route) + assertEquals(before, model.demo().sessions.size) + } + + @Test fun searchMatchesTitlesAgentsAndMessages() = runTest { + val model = model() + model.tryDemo() + val all = model.demo().sessions + assertEquals(all, model.demo().visibleSessions) + + model.setSearch("ROUTER") + assertEquals(listOf("router"), model.demo().visibleSessions.map { it.id }) + + model.setSearch(model.demo().agent(all.first().agentId).name) + assertTrue(model.demo().visibleSessions.any { it.id == all.first().id }) + + model.setSearch("no chat says this zzzz") + assertTrue(model.demo().visibleSessions.isEmpty()) + } + + @Test fun backWalksTheStackAndStopsAtTheRoot() = runTest { + val model = model() + model.tryDemo() + model.openPlace(Route.Settings) + assertEquals(listOf(Route.Sessions, Route.Settings), model.state.value.backStack) + assertTrue(model.back()) + assertEquals(Route.Sessions, model.state.value.route) + // The root is left to the system: Back there leaves the app. + assertFalse(model.back()) + } + + @Test fun leavingTheDemoDropsItsChatsAndDrafts() = runTest { + val model = model() + model.tryDemo() + val id = model.demo().sessions.first().id + model.setDraft(id, "unsent") + model.leaveDemo() + assertNull(model.state.value.demo) + assertEquals(listOf(Route.Welcome), model.state.value.backStack) + + model.tryDemo() + assertNull(model.demo().drafts[id]) + } + + @Test fun appearanceIsSaved() = runTest { + val preferences = FakePreferences() + val model = model(preferences) + model.setAppearance(Appearance.Dark) + assertEquals(Appearance.Dark, preferences.appearance) + assertEquals(Appearance.Dark, model.state.value.appearance) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt new file mode 100644 index 00000000..c4fdc18e --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt @@ -0,0 +1,206 @@ +package app.bighelp.android + +import app.bighelp.hermes.HermesEndpoint +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import okhttp3.Call +import okhttp3.EventListener +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.SocketPolicy +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +class HostDiscoveryTest { + private lateinit var host: MockWebServer + + @Before fun start() { host = MockWebServer(); host.start() } + @After fun stop() { host.shutdown() } + private fun endpoint() = HermesEndpoint.parse(host.url("/hermes").toString(), allowPrivateHttp = true) + + @Test fun consentIsRequiredBeforeAnyRequest() = runTest { + val result = HostDiscovery().check(endpoint(), consentGranted = false) + assertEquals(DiscoveryResult.ConsentRequired, result) + assertEquals(0, host.requestCount) + } + + @Test fun discoversCapabilitiesWithoutSendingCredentialsAndKeepsPrefix() = runTest { + host.enqueue(json("""{"auth_required":true,"auth_flows":["cookie","native_pkce","future"]}""")) + val result = HostDiscovery().check(endpoint(), consentGranted = true) + assertEquals(DiscoveryResult.Available(authRequired = true, browserSignIn = true), result) + val request = host.takeRequest() + assertEquals("GET", request.method) + assertEquals("/hermes/api/status", request.path) + assertEquals("application/json", request.getHeader("Accept")) + assertEquals("no-store", request.getHeader("Cache-Control")) + assertEquals("close", request.getHeader("Connection")) + assertNull(request.getHeader("Authorization")) + assertNull(request.getHeader("Cookie")) + assertNull(request.getHeader("X-Hermes-Session-Token")) + } + + @Test fun neverFollowsRedirectsOrPublishesWebPageBodies() = runTest { + host.enqueue(MockResponse().setResponseCode(302).addHeader("Location", host.url("/other"))) + host.enqueue(json("""{"auth_required":false}""")) + assertEquals(DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + assertEquals(1, host.requestCount) + } + + @Test fun onlyAnHttp200CountsEvenWhenTheBodyIsAValidStatus() = runTest { + listOf(201, 404, 500).forEach { code -> + host.enqueue(json("""{"auth_required":false}""").setResponseCode(code)) + assertEquals("HTTP $code", DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + assertEquals(3, host.requestCount) + } + + @Test fun malformedOrNonJsonResponsesStayUnavailable() = runTest { + listOf( + json("""{"auth_required":"false"}"""), + json("""{"auth_required":false,"auth_flows":["native_pkce","native_pkce"]}"""), + MockResponse().setHeader("Content-Type", "text/html").setBody("Private proxy diagnostic"), + ).forEach { response -> + host.enqueue(response) + assertEquals(DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + } + + // The budget is 16,384 decoded bytes. Each body below is valid JSON padded with spaces, so size is the + // only thing that can make the answer differ. + + @Test fun aStatusExactlyAtTheSizeBudgetIsAccepted() = runTest { + host.enqueue(json(statusPaddedTo(HostStatus.MAXIMUM_BYTES))) + assertEquals(DiscoveryResult.Available(false, false), HostDiscovery().check(endpoint(), true)) + } + + @Test fun aStatusOneByteOverTheSizeBudgetIsRefused() = runTest { + host.enqueue(json(statusPaddedTo(HostStatus.MAXIMUM_BYTES + 1))) + assertEquals(DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + + @Test fun theSizeBudgetAlsoHoldsWhenTheLengthIsNotDeclared() = runTest { + // A chunked body has no Content-Length, so only reading the stream can tell it is too large. + host.enqueue(chunkedJson(statusPaddedTo(HostStatus.MAXIMUM_BYTES))) + assertEquals(DiscoveryResult.Available(false, false), HostDiscovery().check(endpoint(), true)) + + host.enqueue(chunkedJson(statusPaddedTo(HostStatus.MAXIMUM_BYTES + 1))) + assertEquals(DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + + @Test fun discoveryIsNotAnAuthenticatedConnection() = runTest { + host.enqueue(json("""{"auth_required":false,"auth_flows":null}""")) + assertEquals(DiscoveryResult.Available(false, false), HostDiscovery().check(endpoint(), true)) + assertEquals(1, host.requestCount) + assertEquals("/hermes/api/status", host.takeRequest().path) + } + + /** Real time and a real socket: the server reads the request and never answers, then the caller cancels. */ + @Test fun cancellingTheCheckCancelsTheRealCall() = runBlocking { + host.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val cancelled = CompletableDeferred() + val client = OkHttpClient.Builder() + .eventListener(object : EventListener() { + override fun canceled(call: Call) { cancelled.complete(Unit) } + }) + .build() + + val check = launch(Dispatchers.Default) { HostDiscovery(client).check(endpoint(), true) } + assertNotNull("the request never reached the server", host.takeRequest(5, TimeUnit.SECONDS)) + check.cancel() + withTimeout(5_000) { cancelled.await() } + check.join() + } + + // A host may close a socket after replying: HTTP/1.0, a keep-alive timeout, a proxy. OkHttp's idle pool + // cannot see that until it reads, and a GET only gets that limited check, so a later check could pick the + // dead socket and fail with no request ever reaching the host. Each check must therefore find a host that + // keeps answering, and the host must receive one request per check. + + @Test fun repeatedChecksOfAHostThatClosesAfterEveryReplyAllFindIt() = runBlocking { + ClosingServer().use { server -> + val discovery = HostDiscovery() + val results = List(4) { discovery.check(server.endpoint(), true) } + assertEquals(List(4) { DiscoveryResult.Available(false, false) }, results) + assertEquals(4, server.requests.get()) + } + } + + @Test fun repeatedChecksOfAKeepAliveHostThatThenClosesAllFindIt() = runTest { + repeat(4) { host.enqueue(json("""{"auth_required":false}""").setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)) } + val discovery = HostDiscovery() + val results = List(4) { discovery.check(endpoint(), true) } + assertEquals(List(4) { DiscoveryResult.Available(false, false) }, results) + assertEquals(4, host.requestCount) + } + + @Test fun eachCheckOpensItsOwnConnectionEvenWhenTheHostKeepsOneOpen() = runTest { + repeat(3) { host.enqueue(json("""{"auth_required":false}""")) } + val discovery = HostDiscovery() + repeat(3) { assertEquals(DiscoveryResult.Available(false, false), discovery.check(endpoint(), true)) } + // sequenceNumber counts requests on one connection; 0 each time means no idle socket was reused. + assertEquals(listOf(0, 0, 0), List(3) { host.takeRequest().sequenceNumber }) + } + + /** Answers like Python's BaseHTTPRequestHandler: HTTP/1.0, Content-Length, then closes the socket. */ + private class ClosingServer : AutoCloseable { + private val listener = ServerSocket(0, 50, InetAddress.getLoopbackAddress()) + val requests = AtomicInteger() + + fun endpoint() = HermesEndpoint.parse("http://127.0.0.1:${listener.localPort}/hermes", allowPrivateHttp = true) + + init { + thread(isDaemon = true) { + try { + while (true) { + val socket = listener.accept() + thread(isDaemon = true) { serve(socket) } + } + } catch (_: IOException) { + } + } + } + + private fun serve(socket: Socket) = socket.use { + val input = socket.getInputStream() + var tail = 0 + while (tail != 0x0d0a0d0a) { + val next = input.read() + if (next < 0) return@use + tail = (tail shl 8) or next + } + requests.incrementAndGet() + val body = """{"auth_required":false}""".toByteArray() + socket.getOutputStream().apply { + write("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\n\r\n".toByteArray()) + write(body) + flush() + } + } + + override fun close() = listener.close() + } + + private fun statusPaddedTo(bytes: Int): String { + val status = """{"auth_required":false}""" + return status + " ".repeat(bytes - status.length) + } + + private fun json(body: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(body) + + private fun chunkedJson(body: String) = + MockResponse().setHeader("Content-Type", "application/json").setChunkedBody(body, 1_000) +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/HostStatusTest.kt b/android/app/src/test/kotlin/app/bighelp/android/HostStatusTest.kt new file mode 100644 index 00000000..3f807de2 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/HostStatusTest.kt @@ -0,0 +1,76 @@ +package app.bighelp.android + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class HostStatusTest { + private fun parse(json: String) = HostStatus.parse(json.toByteArray()) + + @Test fun readsTheRequiredBooleanAndKeepsUnknownFlowsAndFields() { + val status = parse("""{"auth_required":true,"auth_flows":["cookie","future"],"version":"9.9","extra":{"a":[1]}}""")!! + assertEquals(true, status.authRequired) + assertEquals(listOf("cookie", "future"), status.authFlows) + assertEquals(false, status.browserSignIn) + } + + @Test fun browserSignInNeedsAnAuthRequiredHostAndTheExactFlowName() { + assertEquals(true, parse("""{"auth_required":true,"auth_flows":["native_pkce"]}""")!!.browserSignIn) + assertEquals(false, parse("""{"auth_required":false,"auth_flows":["native_pkce"]}""")!!.browserSignIn) + assertEquals(false, parse("""{"auth_required":true,"auth_flows":["Native_PKCE"]}""")!!.browserSignIn) + } + + @Test fun missingOrNullFlowsMeanNone() { + assertEquals(emptyList(), parse("""{"auth_required":false}""")!!.authFlows) + assertEquals(emptyList(), parse("""{"auth_required":false,"auth_flows":null}""")!!.authFlows) + } + + @Test fun refusesAnythingThatIsNotTheDocumentedShape() { + listOf( + """[]""", + """{}""", + """{"auth_required":null}""", + """{"auth_required":1}""", + """{"auth_required":"true"}""", + """{"auth_required":false,"auth_flows":"native_pkce"}""", + """{"auth_required":false,"auth_flows":[1]}""", + """{"auth_required":false,"auth_flows":[null]}""", + """{"auth_required":false,"auth_flows":[""]}""", + """{"auth_required":false,"auth_flows":["a","a"]}""", + """{"auth_required":false,"auth_flows":["\ud800"]}""", + """{"auth_required":false,} """, + """{"auth_required":false} trailing""", + """{"auth_required":true,"auth_required":false}""", + """{"auth_required":false,"a":1,"a":2}""", + ).forEach { assertNull(it, parse(it)) } + } + + @Test fun duplicateKeysDeepInsideAreAnotherFieldsBusiness() { + // Only the fields this client reads have to be unambiguous. + assertEquals(false, parse("""{"auth_required":false,"other":[{"k":1},{"k":2}]}""")!!.authRequired) + } + + @Test fun flowCountAndNameLengthAreBounded() { + val max = (1..32).joinToString(",", "[", "]") { "\"f$it\"" } + assertEquals(32, parse("""{"auth_required":false,"auth_flows":$max}""")!!.authFlows.size) + val tooMany = (1..33).joinToString(",", "[", "]") { "\"f$it\"" } + assertNull(parse("""{"auth_required":false,"auth_flows":$tooMany}""")) + + val longest = "é".repeat(64) // 128 UTF-8 bytes + assertEquals(listOf(longest), parse("""{"auth_required":false,"auth_flows":["$longest"]}""")!!.authFlows) + assertNull(parse("""{"auth_required":false,"auth_flows":["${longest}x"]}""")) + } + + @Test fun theBodyBudgetIsExactlySixteenKibiBytes() { + val head = """{"auth_required":false,"pad":"""" + val tail = "\"}" + val fill = HostStatus.MAXIMUM_BYTES - head.length - tail.length + assertEquals(false, parse(head + "x".repeat(fill) + tail)!!.authRequired) + assertNull(parse(head + "x".repeat(fill + 1) + tail)) + } + + @Test fun invalidUtf8IsRefused() { + val bytes = """{"auth_required":false,"note":"""".toByteArray() + byteArrayOf(0xC3.toByte()) + "\"}".toByteArray() + assertNull(HostStatus.parse(bytes)) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/LiveNavigationTest.kt b/android/app/src/test/kotlin/app/bighelp/android/LiveNavigationTest.kt new file mode 100644 index 00000000..a212cb60 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/LiveNavigationTest.kt @@ -0,0 +1,206 @@ +package app.bighelp.android + +import app.bighelp.android.live.ComputerPhase +import app.bighelp.android.live.LiveRig +import app.bighelp.hermes.AuthProvider +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.chat.ConversationRef +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +private class Prefs( + override var aiDataAgreed: Boolean = true, + override var appearance: Appearance = Appearance.Automatic, + override var userName: String = "", + override var nerdMode: Boolean = false, +) : PreviewPreferences + +@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) +class LiveNavigationTest { + @get:Rule val temporary = TemporaryFolder() + private val noCheck = HostChecker { _, _ -> DiscoveryResult.Unavailable } + private val ref = ConversationRef("default", "anchor-1") + + private fun TestScope.setup(preferences: Prefs = Prefs()): Pair { + val rig = LiveRig(temporary.root, backgroundScope) + return rig to BighelpAppModel(preferences, noCheck, backgroundScope, rig.model) + } + + @Test fun aConnectedComputerOpensTheLivePlacesAndLosingItGoesBackToWelcome() = runTest { + val (rig, model) = setup() + runCurrent() + assertEquals(Route.Welcome, model.state.value.route) + assertFalse(model.state.value.live) + rig.connect(); runCurrent() + assertTrue(model.state.value.live) + assertEquals(listOf(Route.Sessions), model.state.value.backStack) + assertNull("The demo is gone once a real computer is open", model.state.value.demo) + rig.model.disconnect().join(); runCurrent() + assertFalse(model.state.value.live) + assertEquals(listOf(Route.Welcome), model.state.value.backStack) + } + + @Test fun replacingTheActiveComputerDoesNotBounceThroughWelcome() = runTest { + val (rig, model) = setup() + rig.connect(); runCurrent() + val routes = mutableListOf>() + val watcher = backgroundScope.launchCollect(model) { routes += it } + runCurrent() + rig.model.select(rig.connections.state.value.selectedID!!).join(); runCurrent() + assertTrue(model.state.value.live) + assertTrue("Never showed Welcome while switching: $routes", routes.none { it == listOf(Route.Welcome) }) + watcher.cancel() + } + + @Test fun theLivePlacesAndMenuWorkOnlyWhileARealComputerIsOpen() = runTest { + val (rig, model) = setup() + model.openPlace(Route.Agents) + assertEquals("No place opens without a computer or the demo", Route.Welcome, model.state.value.route) + rig.connect(); runCurrent() + model.openPlace(Route.Agents) + assertEquals(listOf(Route.Sessions, Route.Agents), model.state.value.backStack) + model.openPlace(Route.Sessions) + assertEquals(listOf(Route.Sessions), model.state.value.backStack) + } + + @Test fun theLiveHostCheckSendsTheAccessDetailsAndShowsTheHostsOptions() = runTest { + val (rig, model) = setup() + rig.prepare = { it.status = AuthStatus(true, listOf("native_pkce"), listOf(AuthProvider("basic", "Password", true))) } + model.connectComputer(); runCurrent() + model.setAddress("hermes.example.test") + model.setAccess(AccessInput(AccessKind.ProxyLogin, "gate-user", "gate-pass")) + model.checkHost(); runCurrent() + val found = model.state.value.setup.discovery as DiscoveryState.Found + assertTrue(found.authRequired) + assertTrue(found.browserSignIn) + assertEquals(ComputerPhase.SignIn, rig.connections.state.value.phase) + model.continueToSignIn() + assertEquals(Route.SignIn, model.state.value.route) + } + + @Test fun anInvalidAccessFormIsExplainedBeforeAnyRequestIsMade() = runTest { + val (rig, model) = setup() + model.connectComputer(); runCurrent() + model.setAddress("hermes.example.test") + model.setAccess(AccessInput(AccessKind.Cloudflare, "has space", "secret")) + model.checkHost(); runCurrent() + val refused = model.state.value.setup.discovery as DiscoveryState.Refused + assertTrue(refused.message.contains("access", ignoreCase = true)) + assertTrue("Nothing was built or sent", rig.sessions.isEmpty()) + } + + @Test fun aRefusedLiveCheckShowsTheHostsReasonInPlainWords() = runTest { + val (rig, model) = setup() + rig.prepare = { it.discoverFailure = HermesException.Kind.WebPageInsteadOfHermes } + model.connectComputer(); runCurrent() + model.setAddress("hermes.example.test") + model.checkHost(); runCurrent() + val refused = model.state.value.setup.discovery as DiscoveryState.Refused + assertTrue(refused.message.contains("web page")) + } + + @Test fun aRefusedCheckWhileAddingAComputerKeepsThePersonOnSetupAndBackReopensTheOpenOne() = runTest { + val (rig, model) = setup() + rig.connect(); runCurrent() + val first = rig.connections.state.value.selectedID!! + model.openPlace(Route.Settings) + model.connectComputer(); runCurrent() + assertEquals(Route.Setup, model.state.value.route) + rig.prepare = { it.discoverFailure = HermesException.Kind.ConnectionFailed } + model.setAddress("second.example.test") + model.checkHost(); runCurrent() + assertTrue(model.state.value.setup.discovery is DiscoveryState.Refused) + assertEquals("Not thrown out to Welcome by the failed check", Route.Setup, model.state.value.route) + assertTrue(model.state.value.live) + + model.back(); runCurrent() + assertEquals(Route.Settings, model.state.value.route) + assertEquals("The computer that was open is open again", first, rig.connections.active.value?.computer?.id) + assertTrue(model.state.value.live) + } + + @Test fun typedAccessSecretsAreForgottenWhenTheSetupScreenIsLeft() = runTest { + val (_, model) = setup() + model.connectComputer(); runCurrent() + model.setAddress("hermes.example.test") + model.setAccess(AccessInput(AccessKind.ProxyLogin, "gate-user", "gate-pass", listOf("X-Access-Id" to "synthetic"))) + model.back(); runCurrent() + assertEquals(AccessInput(), model.state.value.setup.access) + assertEquals("The address the person typed stays", "hermes.example.test", model.state.value.setup.address) + } + + @Test fun leavingTheSignInCancelsItAndGoesBack() = runTest { + val (rig, model) = setup() + model.connectComputer(); runCurrent() + model.setAddress("hermes.example.test") + model.checkHost(); runCurrent() + model.continueToSignIn() + model.back() + runCurrent() + assertEquals(Route.Setup, model.state.value.route) + assertEquals(ComputerPhase.Idle, rig.connections.state.value.phase) + } + + @Test fun signingInToAnAddedComputerEndsOnTheChatList() = runTest { + val (rig, model) = setup() + model.connectComputer(); runCurrent() + model.setAddress("hermes.example.test") + model.checkHost(); runCurrent() + model.continueToSignIn() + model.signIn("Garden computer", SignInInput.Dashboard) + runCurrent() + assertEquals(listOf(Route.Sessions), model.state.value.backStack) + assertTrue(model.state.value.live) + } + + @Test fun openingAndLeavingALiveChatOpensThenReleasesIt() = runTest { + val (rig, model) = setup() + rig.connect(); runCurrent() + rig.chat.conversations.value = mapOf(ref to rig.chat.state(ref)) + runCurrent() + model.openLiveChat(ref); runCurrent() + assertEquals(Route.LiveChat(ref.id), model.state.value.route) + assertEquals(listOf(ref), rig.chat.opened) + model.back(); runCurrent() + assertEquals(Route.Sessions, model.state.value.route) + assertEquals(listOf(ref), rig.chat.released) + } + + @Test fun aChatLinkThatIsNotOneWeMadeOpensNothing() = runTest { + val (rig, model) = setup() + rig.connect(); runCurrent() + model.openLiveChat(null) + assertEquals(Route.Sessions, model.state.value.route) + assertTrue(rig.chat.opened.isEmpty()) + } + + @Test fun theNameIsShortAndSingleLineAndNerdModeIsRemembered() = runTest { + val preferences = Prefs() + val (_, model) = setup(preferences) + model.setUserName(" Ada\nLovelace ") + assertEquals("Ada Lovelace", model.state.value.userName) + assertEquals("Ada Lovelace", preferences.userName) + model.setUserName("x".repeat(60)) + assertEquals(40, model.state.value.userName.length) + model.setNerdMode(true) + assertTrue(preferences.nerdMode) + assertTrue(model.state.value.nerdMode) + val restored = BighelpAppModel(preferences, noCheck, backgroundScope) + assertEquals(true, restored.state.value.nerdMode) + assertEquals(40, restored.state.value.userName.length) + } +} + +private fun kotlinx.coroutines.CoroutineScope.launchCollect(model: BighelpAppModel, sink: (List) -> Unit) = + launch { model.state.collect { sink(it.backStack) } } diff --git a/android/app/src/test/kotlin/app/bighelp/android/MarkdownTest.kt b/android/app/src/test/kotlin/app/bighelp/android/MarkdownTest.kt new file mode 100644 index 00000000..d954f62e --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/MarkdownTest.kt @@ -0,0 +1,53 @@ +package app.bighelp.android + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class MarkdownTest { + @Test fun plainTextIsOneParagraphWithItsLineBreaksKept() { + assertEquals(listOf(MdBlock.Paragraph("one\ntwo")), Markdown.blocks("one\ntwo")) + assertEquals(listOf(MdBlock.Paragraph("a"), MdBlock.Paragraph("b")), Markdown.blocks("a\n\nb")) + assertTrue(Markdown.blocks("").isEmpty()) + assertTrue(Markdown.blocks(" \n\n ").isEmpty()) + } + + @Test fun aFencedBlockKeepsEveryCharacterExactlyAndNeverReadsMarkdownInside() { + val blocks = Markdown.blocks("Before\n```kotlin\nval a = **not bold**\n\n indented\n```\nAfter") + assertEquals( + listOf(MdBlock.Paragraph("Before"), MdBlock.Code("kotlin", "val a = **not bold**\n\n indented"), MdBlock.Paragraph("After")), + blocks, + ) + } + + @Test fun anUnclosedFenceTakesTheRestOfTheMessageAsCodeSoStreamingTextDoesNotFlicker() { + assertEquals(listOf(MdBlock.Code("", "partial\nlines")), Markdown.blocks("```\npartial\nlines")) + } + + @Test fun headingsAndListsAreRecognizedOnlyAtTheStartOfALine() { + val blocks = Markdown.blocks("## Title\n- one\n- two\n\n1. first\n2) second\nnot # a heading") + assertEquals(MdBlock.Heading(2, "Title"), blocks[0]) + assertEquals(MdBlock.Bullets(ordered = false, items = listOf("one", "two")), blocks[1]) + assertEquals(MdBlock.Bullets(ordered = true, items = listOf("first", "second")), blocks[2]) + assertEquals(MdBlock.Paragraph("not # a heading"), blocks[3]) + assertEquals(MdBlock.Paragraph("#hashtag"), Markdown.blocks("#hashtag").single()) + } + + @Test fun inlineMarksBecomeSpansAndAnUnmatchedMarkerStaysLiteral() { + assertEquals( + listOf(MdSpan("a "), MdSpan("bold", bold = true), MdSpan(" and "), MdSpan("it", italic = true), MdSpan(" and "), MdSpan("code", code = true)), + Markdown.spans("a **bold** and *it* and `code`"), + ) + assertEquals(listOf(MdSpan("2 * 3 = 6 and **open")), Markdown.spans("2 * 3 = 6 and **open")) + assertEquals(listOf(MdSpan("snake_case_name")), Markdown.spans("snake_case_name")) + } + + @Test fun aLinkShowsItsLabelAndKeepsTheAddressVisibleOnlyWhenTheLabelIsTheAddress() { + assertEquals(listOf(MdSpan("the docs (https://example.test/x)")), Markdown.spans("[the docs](https://example.test/x)")) + assertEquals(listOf(MdSpan("https://example.test/x")), Markdown.spans("[https://example.test/x](https://example.test/x)")) + } + + @Test fun codeSpansTakeEverythingLiterallyIncludingMarkers() { + assertEquals(listOf(MdSpan("**x**", code = true)), Markdown.spans("`**x**`")) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/AccessSetupTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/AccessSetupTest.kt new file mode 100644 index 00000000..5e7fb9dd --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/AccessSetupTest.kt @@ -0,0 +1,79 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.android.storage.RecordStorageException +import app.bighelp.android.storage.StorageProblem +import app.bighelp.hermes.AccessCredential +import app.bighelp.hermes.CustomHeader +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import java.io.File +import java.util.UUID +import javax.crypto.KeyGenerator +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class AccessSetupTest { + @get:Rule val temporary = TemporaryFolder() + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + private fun store() = AndroidAccessSetupStore(ProtectedRecordStore(File(temporary.root, "access"), RecordCipher { key }), Dispatchers.Unconfined) + private val endpoint = HermesEndpoint.parse("https://gated.example.test") + + @Test fun everyKindOfGateRoundTripsAndNothingSecretReachesToString() = runBlocking { + val id = UUID.randomUUID() + val setups = listOf( + AccessSetup(AccessCredential.cloudflareAccess("cf-id-0123", "cf-secret-0123"), emptyList()), + AccessSetup(AccessCredential.proxyBasic("gate-user", "gate pass with spaces"), CustomHeader.list(listOf("X-Access-Id" to "synthetic"))), + AccessSetup(null, CustomHeader.list(listOf("X-First" to "1", "X-Second" to "2"))), + ) + for (setup in setups) { + store().saveAccess(id, setup) + assertEquals(setup, store().loadAccess(id)) + val text = setup.toString() + assertFalse(text.contains("secret") || text.contains("pass") || text.contains("synthetic")) + } + assertEquals("The same headers reach the HTTP client either way", setups.last().headers(endpoint).values, store().loadAccess(id).headers(endpoint).values) + } + + @Test fun anEmptySetupIsNothingStoredAndRemovesWhatWasThere() = runBlocking { + val id = UUID.randomUUID() + store().saveAccess(id, AccessSetup(AccessCredential.proxyBasic("u", "p"), emptyList())) + store().saveAccess(id, AccessSetup.None) + assertEquals(AccessSetup.None, store().loadAccess(id)) + assertEquals(0, File(temporary.root, "access").listFiles { f -> f.name.endsWith(".sealed") }!!.size) + } + + @Test fun eachComputerHasItsOwnGateDetails() = runBlocking { + val one = UUID.randomUUID(); val two = UUID.randomUUID() + store().saveAccess(one, AccessSetup(AccessCredential.proxyBasic("one", "pw"), emptyList())) + assertEquals(AccessSetup.None, store().loadAccess(two)) + store().saveAccess(two, AccessSetup(AccessCredential.proxyBasic("two", "pw"), emptyList())) + store().deleteAccess(one) + assertEquals(AccessSetup.None, store().loadAccess(one)) + assertNotEquals(AccessSetup.None, store().loadAccess(two)) + } + + @Test fun aRecordThatIsNotOursIsReportedAsUnreadableNotSilentlyEmpty() = runBlocking { + val id = UUID.randomUUID() + val records = ProtectedRecordStore(File(temporary.root, "access"), RecordCipher { key }) + records.compareAndSet(accessRecordKey(id), null, "{\"schemaVersion\":9}".toByteArray()) + try { store().loadAccess(id); fail("A newer or foreign record must not read as empty") } + catch (failure: RecordStorageException) { assertEquals(StorageProblem.CorruptRecord, failure.problem) } + } + + @Test fun aCloudflareCredentialCannotBeSetUpForPlainHttp() { + val plain = HermesEndpoint.parse("http://192.168.1.20:9119", allowPrivateHttp = true) + val setup = AccessSetup(AccessCredential.cloudflareAccess("cf-id-0123", "cf-secret-0123"), emptyList()) + try { setup.headers(plain); fail() } catch (failure: HermesException) { assertEquals(HermesException.Kind.InvalidAccessCredentials, failure.kind) } + assertTrue(AccessSetup.None.isEmpty) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/AndroidCredentialStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/AndroidCredentialStoreTest.kt new file mode 100644 index 00000000..31ea4ff0 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/AndroidCredentialStoreTest.kt @@ -0,0 +1,296 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.android.storage.RecordStorageException +import app.bighelp.android.storage.StorageProblem +import app.bighelp.android.storage.RecordFileOperations +import app.bighelp.android.storage.SystemRecordFileOperations +import app.bighelp.hermes.CredentialAuthority +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.StaleCredentialException +import app.bighelp.hermes.StoredAuth +import javax.crypto.KeyGenerator +import java.io.File +import java.io.InputStream +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.supervisorScope +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class AndroidCredentialStoreTest { + @get:Rule val temporary = TemporaryFolder() + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + private fun store() = AndroidCredentialStore(ProtectedRecordStore(temporary.root, RecordCipher { key })) + private fun saved(user: String = "synthetic-person", token: String = "access-one") = SavedConnection( + HermesEndpoint.parse("https://example.test/hermes"), + StoredAuth.Bearer(token, "synthetic-refresh", 1_900_000_000), "basic", user, + ) + + @Test fun savesARealCredentialRecordAndReopensItsExactAuthority() = runBlocking { + val value = saved() + store().replace(null, value) + assertEquals(value, store().load(value.authority)) + assertNull(store().load(saved("another-person").authority)) + assertNull(store().load(CredentialAuthority("https://other.example.test/hermes", value.principal))) + } + + @Test fun rotatingCredentialCannotOverwriteANewerRotationOrSignOut() = runBlocking { + val first = saved() + val next = saved(token = "access-two") + val vault = store() + vault.replace(null, first) + store().replace(first, next) + try { + vault.replace(first, saved(token = "stale-answer")) + fail("A stale refresh must not write") + } catch (_: StaleCredentialException) { + } + try { + vault.delete(first) + fail("A stale sign-out must not erase a newer sign-in") + } catch (_: StaleCredentialException) { + } + assertEquals(next, vault.load(next.authority)) + vault.delete(next) + assertNull(store().load(next.authority)) + try { + vault.replace(next, first) + fail("A retired rotation must not recreate a deleted record") + } catch (_: StaleCredentialException) { + } + } + + @Test fun differentPrincipalsOnTheSameComputerKeepSeparateRecords() = runBlocking { + val first = saved("caf\u00e9") + val second = saved("cafe\u0301") + val vault = store() + vault.replace(null, first) + vault.replace(null, second) + assertEquals(first, store().load(first.authority)) + assertEquals(second, store().load(second.authority)) + vault.delete(first) + assertEquals(second, store().load(second.authority)) + } + + @Test fun replacementCannotMoveCredentialsToAnotherPrincipal() = runBlocking { + val first = saved() + val other = saved("another-person") + val vault = store() + vault.replace(null, first) + try { + vault.replace(first, other) + fail("Replacing a credential must retain its authority") + } catch (_: IllegalArgumentException) { + } + assertEquals(first, store().load(first.authority)) + assertNull(store().load(other.authority)) + } + + @Test fun invalidCredentialsAreRejectedBeforeSaving() = runBlocking { + val invalid = saved(token = "contains a space") + try { + store().replace(null, invalid) + fail("An invalid credential must not be saved") + } catch (failure: HermesException) { + assertEquals(HermesException.Kind.InvalidCredentials, failure.kind) + } + assertNull(store().load(invalid.authority)) + } + + @Test fun anUnreadableRecordNeedsExplicitRecoveryAndDoesNotBecomeMissing() = runBlocking { + val value = saved() + val vault = store() + vault.replace(null, value) + assertFalse(vault.discardUnreadable(value.authority)) + temporary.root.listFiles()!!.single { it.extension == "sealed" }.writeBytes(byteArrayOf(1)) + try { + vault.load(value.authority) + fail("An unreadable saved sign-in must not look absent") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.CorruptRecord, failure.problem) + } + assertTrue(vault.discardUnreadable(value.authority)) + assertNull(vault.load(value.authority)) + vault.replace(null, value) + assertEquals(value, vault.load(value.authority)) + } + + @Test fun malformedPrincipalNeverAliasesAValidQuestionMark() = runBlocking { + try { + store().load(CredentialAuthority("https://example.test", "\ud800")) + fail("Malformed UTF-16 must not be replaced while deriving a record key") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.InvalidBinding, failure.problem) + } + } + + @Test fun aDecodedSnapshotCanRotateARecordWithDifferentJsonOrderAndOptionalFields() = runBlocking { + val first = saved() + val fields = Json.parseToJsonElement(first.toBytes().toString(Charsets.UTF_8)) as JsonObject + val reordered = JsonObject((fields + ("futureOptionalField" to JsonPrimitive("ignored"))).toSortedMap()) + .toString().toByteArray(Charsets.UTF_8) + val records = ProtectedRecordStore(temporary.root, RecordCipher { key }) + assertTrue(records.compareAndSet(credentialRecordKey(first.authority), null, reordered)) + val vault = AndroidCredentialStore(records) + assertEquals(first, vault.load(first.authority)) + val next = saved(token = "rotated-token") + vault.replace(first, next) + assertEquals(next, store().load(first.authority)) + } + + @Test fun aMismatchedDecodedAuthorityIsRefusedAndCanBeExplicitlyRemoved() = runBlocking { + val first = saved() + val records = ProtectedRecordStore(temporary.root, RecordCipher { key }) + assertTrue(records.compareAndSet(credentialRecordKey(first.authority), null, saved("another-person").toBytes())) + val vault = AndroidCredentialStore(records) + try { + vault.load(first.authority) + fail("A decoded sign-in must match the requested authority") + } catch (failure: HermesException) { + assertEquals(HermesException.Kind.SavedConnectionInvalid, failure.kind) + } + assertTrue(vault.discardUnreadable(first.authority)) + assertNull(vault.load(first.authority)) + } + + @Test fun twoComputerEntriesCanKeepIndependentSignInsForTheSameAuthority() = runBlocking { + val records = ProtectedRecordStore(temporary.root, RecordCipher { key }) + val first = saved() + val second = saved(token = "independent-sign-in") + val firstComputer = AndroidCredentialStore(records, "computer-one") + val secondComputer = AndroidCredentialStore(records, "computer-two") + firstComputer.replace(null, first) + secondComputer.replace(null, second) + assertEquals(first, firstComputer.load(first.authority)) + assertEquals(second, secondComputer.load(first.authority)) + firstComputer.delete(first) + assertEquals(second, secondComputer.load(first.authority)) + } + + @Test fun anAutomaticDashboardTokenKeepsItsModeAndNoProviderIdentity() = runBlocking { + val value = SavedConnection( + HermesEndpoint.parse("https://example.test/hermes"), + StoredAuth.DashboardSession("synthetic-dashboard-token", automatic = true), null, null, + ) + val vault = store() + vault.replace(null, value) + val loaded = vault.load(value.authority)!! + assertEquals(value, loaded) + assertNull(loaded.provider) + assertNull(loaded.userId) + } + + @Test fun cancellingDuringTheSnapshotReadPreventsTheInitialWrite() = runBlocking { + val value = saved() + supervisorScope { + lateinit var job: Deferred + var reads = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream { + reads++ + job.cancel() + return SystemRecordFileOperations.read(file) + } + } + val vault = AndroidCredentialStore(ProtectedRecordStore(temporary.root, RecordCipher { key }, io)) + job = async(start = CoroutineStart.LAZY) { vault.replace(null, value) } + job.start() + try { job.await(); fail("Cancelled work must not write") } catch (_: CancellationException) { } + assertEquals(1, reads) + } + assertNull(store().load(value.authority)) + } + + @Test fun cancellingDuringTheDeleteSnapshotReadKeepsTheSignIn() = runBlocking { + val value = saved() + store().replace(null, value) + supervisorScope { + lateinit var job: Deferred + var reads = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream { + reads++ + job.cancel() + return SystemRecordFileOperations.read(file) + } + } + val vault = AndroidCredentialStore(ProtectedRecordStore(temporary.root, RecordCipher { key }, io)) + job = async(start = CoroutineStart.LAZY) { vault.delete(value) } + job.start() + try { job.await(); fail("Cancelled work must not delete") } catch (_: CancellationException) { } + assertEquals(1, reads) + } + assertEquals(value, store().load(value.authority)) + } + + @Test fun anUnreadableRecordCannotBeOverwrittenByANewSignInOrDeletedAsAValidOne() = runBlocking { + val value = saved() + store().replace(null, value) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" } + val broken = byteArrayOf(1, 2, 3) + file.writeBytes(broken) + for (action in listOf Unit>({ store().replace(null, value) }, { store().delete(value) })) { + try { action(); fail("Unreadable data must not be overwritten") } + catch (failure: RecordStorageException) { assertEquals(StorageProblem.CorruptRecord, failure.problem) } + assertArrayEquals(broken, file.readBytes()) + } + } + + @Test fun aFutureSchemaMustNotBeOverwrittenWithoutExplicitRecovery() = runBlocking { + val value = saved() + val raw = """{"schemaVersion":2}""".toByteArray() + val records = ProtectedRecordStore(temporary.root, RecordCipher { key }) + val binding = credentialRecordKey(value.authority) + assertTrue(records.compareAndSet(binding, null, raw)) + try { store().replace(null, value); fail("Future data must not be replaced") } + catch (failure: HermesException) { assertEquals(HermesException.Kind.SavedConnectionInvalid, failure.kind) } + assertArrayEquals(raw, records.read(binding)) + assertTrue(store().discardUnreadable(value.authority)) + assertNull(store().load(value.authority)) + } + + @Test fun recoveryCannotDiscardAConcurrentValidCredentialReplacement() = runBlocking { + val value = saved(token = "concurrent-sign-in") + val replacementRoot = temporary.newFolder("replacement") + val replacementStore = AndroidCredentialStore(ProtectedRecordStore(replacementRoot, RecordCipher { key })) + replacementStore.replace(null, value) + val envelope = replacementRoot.listFiles()!!.single { it.extension == "sealed" }.readBytes() + val records = ProtectedRecordStore(temporary.root, RecordCipher { key }) + assertTrue(records.compareAndSet(credentialRecordKey(value.authority), null, """{"schemaVersion":2}""".toByteArray())) + var reads = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream { + if (++reads == 3) file.writeBytes(envelope) + return SystemRecordFileOperations.read(file) + } + } + val racing = AndroidCredentialStore(ProtectedRecordStore(temporary.root, RecordCipher { key }, io)) + assertFalse(racing.discardUnreadable(value.authority)) + assertEquals(value, store().load(value.authority)) + } + + @Test fun persistedKeyAndFileNameStayStableAcrossSerializationLibraryUpdates() = runBlocking { + val value = saved(user = "fixture") + val scope = "11111111-1111-4111-8111-111111111111" + val expected = "[\"bighelp.credential.v1\",\"11111111-1111-4111-8111-111111111111\",\"https://example.test/hermes\",\"basic\\u001ffixture\"]" + assertEquals(expected, credentialRecordKey(value.authority, scope)) + val vault = AndroidCredentialStore(ProtectedRecordStore(temporary.root, RecordCipher { key }), scope) + vault.replace(null, value) + assertEquals( + "856540a6c667754b7e7e0c88ac378baa15a2803dccc9df8a12fa4553adfb20ca.sealed", + temporary.root.listFiles()!!.single { it.extension == "sealed" }.name, + ) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt new file mode 100644 index 00000000..da28cf2b --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt @@ -0,0 +1,440 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.hermes.AccessCredential +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.CustomHeader +import app.bighelp.hermes.CredentialStore +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.StoredAuth +import java.io.File +import java.util.UUID +import javax.crypto.KeyGenerator +import kotlinx.coroutines.cancel +import kotlinx.coroutines.isActive +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) +class ComputerConnectionModelTest { + @get:Rule val temporary = TemporaryFolder() + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + private var indexFiles: app.bighelp.android.storage.RecordFileOperations = app.bighelp.android.storage.SystemRecordFileOperations + private fun registry() = SavedComputerStore(ProtectedRecordStore(File(temporary.root, "index"), RecordCipher { key }, indexFiles), Dispatchers.Unconfined) + private fun vault(id: UUID) = AndroidCredentialStore(ProtectedRecordStore(File(temporary.root, "sign-ins"), RecordCipher { key }), id.toString(), Dispatchers.Unconfined) + private val endpoint = HermesEndpoint.parse("https://example.test/hermes") + private var consent = true + private val sessions = mutableListOf() + private var prepare: (FakeSession) -> Unit = { } + private val localData = FakeLocalData() + private val factoryCalls = mutableListOf>() + private fun model(scope: CoroutineScope) = ComputerConnectionModel( + registry(), ::vault, { consent }, scope, localData, + ) { id, address, access, credentials, ownedScope -> + factoryCalls += Triple(id, address, access) + FakeSession(address, credentials, localData, id, ownedScope).also { sessions += it; prepare(it) } + } + + /** Stands in for the access-header store and the chat records, and remembers what happened to them. */ + private class FakeLocalData : ComputerLocalData { + val access = mutableMapOf() + val forgotten = mutableListOf() + override suspend fun loadAccess(id: UUID) = access[id] ?: AccessSetup.None + override suspend fun saveAccess(id: UUID, access: AccessSetup) { this.access[id] = access } + override suspend fun forget(id: UUID) { forgotten += id; access.remove(id) } + } + + private class FakeSession( + val endpoint: HermesEndpoint, val store: CredentialStore, val local: FakeLocalData, val id: UUID, val scope: CoroutineScope, + ) : ComputerSession { + override var saved: SavedConnection? = null + override val link = kotlinx.coroutines.flow.MutableStateFlow(ComputerLink.Connected) + var accessSavedBeforeCommit: Boolean? = null + var resumed = 0 + var reconnects = 0 + override suspend fun resume() { resumed++ } + override suspend fun reconnect() { reconnects++ } + var closed = false + var connected = false + var commits = 0 + var failClose = false + var connectGate: CompletableDeferred? = null + override suspend fun discover() = AuthStatus(false, emptyList(), emptyList()) + override suspend fun signIn(input: SignInInput): SavedConnection = SavedConnection( + endpoint, StoredAuth.DashboardSession("synthetic-session", true), null, null, + ).also { saved = it } + override suspend fun restore(saved: SavedConnection) { this.saved = saved } + override suspend fun connect() { + connectGate?.let { withContext(NonCancellable) { it.await() } } + connected = true + } + override suspend fun commit(expected: SavedConnection?, stillCurrent: () -> Boolean) { + check(connected && stillCurrent()) + accessSavedBeforeCommit = local.access.containsKey(id) + store.replace(expected, requireNotNull(saved)) + commits++ + } + /** A refresh that finishes while the session shuts down: it tries to save its rotated sign-in, as the real one does. */ + var rotateOnClose = false + var closeWrite: Boolean? = null + var scopeActiveOnClose: Boolean? = null + override suspend fun close() { + scopeActiveOnClose = scope.isActive + if (rotateOnClose) { + val rotated = SavedConnection(endpoint, StoredAuth.DashboardSession("rotated-session", true), null, null) + closeWrite = try { store.replace(requireNotNull(saved), rotated); true } catch (_: app.bighelp.hermes.StaleCredentialException) { false } + } + closed = true + if (failClose) throw java.io.IOException("Synthetic close failure") + } + } + + @Test fun consentPreventsDiscoveryAndSavedRestoreFromCreatingAnyNetworkClient() = runTest { + consent = false + val model = model(backgroundScope) + model.load().join() + model.beginSetup(endpoint).join() + assertEquals(ComputerPhase.ConsentRequired, model.state.value.phase) + assertTrue(sessions.isEmpty()) + assertTrue(registry().load().computers.isEmpty()) + } + + @Test fun aNewComputerIsCommittedOnlyAfterItsGatewayIsReadyAndRestoresOnTheNextLaunch() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + assertTrue(registry().load().computers.isEmpty()) + assertEquals(ComputerPhase.SignIn, model.state.value.phase) + model.signIn("Garden computer", SignInInput.Dashboard).join() + assertEquals(ComputerPhase.Connected, model.state.value.phase) + val saved = registry().load() + val row = saved.computers.single() + assertTrue(row.setupComplete) + assertEquals(row.id, saved.selectedID) + assertEquals(1, sessions.single().commits) + assertEquals(row.authority, vault(row.id).load(row.authority)!!.authority) + val restored = model(backgroundScope) + restored.load().join() + assertEquals(ComputerPhase.Connected, restored.state.value.phase) + assertEquals(row.id, restored.active.value!!.computer.id) + assertEquals(0, sessions.last().commits) + model.disconnect().join() + restored.disconnect().join() + } + + @Test fun aCancelledConnectionThatIgnoresCancellationCannotCommitOrBecomeActive() = runTest { + val gate = CompletableDeferred() + prepare = { it.connectGate = gate } + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + val signIn = model.signIn("Garden computer", SignInInput.Dashboard) + runCurrent() + assertEquals(ComputerPhase.Connecting, model.state.value.phase) + val cancel = model.disconnect() + runCurrent() + assertFalse(cancel.isCompleted) + gate.complete(Unit) + signIn.join() + cancel.join() + assertEquals(0, sessions.single().commits) + assertTrue(sessions.single().closed) + assertNull(model.active.value) + assertTrue(registry().load().computers.isEmpty()) + } + + @Test fun anIncompleteSavedRowRequiresSignInWithoutOpeningANetworkClient() = runTest { + val row = SavedComputer(UUID.randomUUID(), "Garden computer", endpoint, "dashboard-session", false) + val registry = registry() + registry.replace(registry.load(), listOf(row), row.id) + val model = model(backgroundScope) + model.load().join() + assertEquals(ComputerPhase.SignInRequired, model.state.value.phase) + assertTrue(sessions.isEmpty()) + } + + @Test fun aMissingSignInDoesNotSilentlyBootstrapANewPrincipal() = runTest { + val row = SavedComputer(UUID.randomUUID(), "Garden computer", endpoint, "dashboard-session", true) + val registry = registry() + registry.replace(registry.load(), listOf(row), row.id) + val model = model(backgroundScope) + model.load().join() + assertEquals(ComputerPhase.SignInRequired, model.state.value.phase) + assertTrue(sessions.isEmpty()) + } + + @Test fun anExistingEndpointAndPrincipalCannotBeAddedTwice() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + model.beginSetup(endpoint).join() + model.signIn("Another name", SignInInput.Dashboard).join() + assertEquals(ComputerProblem.AlreadyConfigured, model.state.value.problem) + assertEquals(1, registry().load().computers.size) + assertEquals(0, sessions.last().commits) + assertTrue(sessions.first().closed) + model.disconnect().join() + } + + @Test fun removingTheActiveComputerRetiresItBeforeDeletingItsLocalSignIn() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + val row = registry().load().computers.single() + model.remove(row.id).join() + assertTrue(sessions.single().closed) + assertNull(vault(row.id).load(row.authority)) + assertTrue(registry().load().computers.isEmpty()) + assertNull(model.active.value) + } + + @Test fun selectingAnotherComputerClosesTheOldOwnerAndKeepsBothSignIns() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + val first = registry().load().computers.single() + model.beginSetup(HermesEndpoint.parse("https://second.example.test/prefix")).join() + model.signIn("Moss computer", SignInInput.Dashboard).join() + val second = registry().load().computers.last() + model.select(first.id).join() + assertEquals(first.id, model.active.value!!.computer.id) + assertTrue(sessions[1].closed) + assertNotNull(vault(first.id).load(first.authority)) + assertNotNull(vault(second.id).load(second.authority)) + assertEquals(first.id, registry().load().selectedID) + model.disconnect().join() + } + @Test fun anExpiredSavedSignInCanBeReplacedInTheSameComputerRow() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + val row = registry().load().computers.single() + model.reauthenticate(row.id).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + assertEquals(ComputerPhase.Connected, model.state.value.phase) + assertEquals(listOf(row.id), registry().load().computers.map { it.id }) + assertEquals(1, sessions.last().commits) + model.disconnect().join() + } + + @Test fun retiringAStoreWaitsForItsStartedWriteAndRefusesAnyLaterSave() = runTest { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val underlying = app.bighelp.hermes.InMemoryCredentialStore() + val address = endpoint + val value = SavedConnection(address, StoredAuth.DashboardSession("synthetic-session", true), null, null) + val delegate = object : CredentialStore by underlying { + override suspend fun replace(expected: SavedConnection?, next: SavedConnection) { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + underlying.replace(expected, next) + } + } + val owned = OwnedCredentialStore(delegate) { true } + val write = backgroundScope.launch { owned.replace(null, value) } + entered.await() + owned.invalidate() + val drain = backgroundScope.launch { owned.awaitIdle() } + try { + runCurrent() + assertFalse(drain.isCompleted) + } finally { release.complete(Unit) } + write.join() + drain.join() + underlying.delete(value) + try { owned.replace(null, value); fail("A retired store must not recreate credentials") } + catch (_: app.bighelp.hermes.StaleCredentialException) { } + assertNull(underlying.load(value.authority)) + } + + @Test fun aLostIndexAcknowledgementAfterRenameIsReadBackWithoutRepeatingTheSignIn() = runTest { + var moves = 0 + indexFiles = object : app.bighelp.android.storage.RecordFileOperations by app.bighelp.android.storage.SystemRecordFileOperations { + override fun move(from: java.nio.file.Path, to: java.nio.file.Path) { + app.bighelp.android.storage.SystemRecordFileOperations.move(from, to) + if (++moves == 2) throw java.io.IOException("Synthetic acknowledgement loss") + } + } + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + assertEquals(ComputerPhase.Connected, model.state.value.phase) + assertEquals(2, moves) + assertEquals(1, sessions.single().commits) + assertTrue(registry().load().computers.single().setupComplete) + model.disconnect().join() + } + + @Test fun lifecycleCloseFinishesCleanupEvenAfterTheViewModelScopeWasCancelled() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + val row = registry().load().computers.single() + sessions.single().failClose = true + backgroundScope.cancel() + val close = model.close() + close.join() + assertTrue(sessions.single().closed) + assertNull(model.active.value) + assertNotNull(vault(row.id).load(row.authority)) + assertSame(close, model.close()) + } + + @Test fun aThirdActionCannotBypassTheJoinOfAnEarlierCancelledSignIn() = runTest { + val gate = CompletableDeferred() + prepare = { it.connectGate = gate } + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + val first = model.signIn("Garden computer", SignInInput.Dashboard) + runCurrent() + val second = model.disconnect() + runCurrent() + val third = model.beginSetup(HermesEndpoint.parse("https://second.example.test")) + try { + runCurrent() + assertFalse(third.isCompleted) + assertEquals(1, sessions.size) + } finally { gate.complete(Unit) } + first.join() + second.join() + third.join() + assertEquals(2, sessions.size) + assertTrue(sessions.first().closed) + assertEquals(0, sessions.first().commits) + model.close().join() + } + + @Test fun theLinkFollowsTheActiveSessionsGatewayAfterSetupAndEndsWithIt() = runTest { + val model = model(backgroundScope) + runCurrent() + assertNull(model.link.value) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + runCurrent() + assertEquals(ComputerLink.Connected, model.link.value) + val session = sessions.single() + for (next in listOf(ComputerLink.Reconnecting, ComputerLink.Offline, ComputerLink.SignInRequired, ComputerLink.Connected)) { + session.link.value = next + runCurrent() + assertEquals(next, model.link.value) + } + model.disconnect().join() + runCurrent() + assertNull("A closed computer has no link to report", model.link.value) + } + + @Test fun aDuplicateOrAFullListIsRefusedBeforeTheNewSessionMayConnect() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + model.beginSetup(endpoint).join() + model.signIn("Another name", SignInInput.Dashboard).join() + assertEquals(ComputerProblem.AlreadyConfigured, model.state.value.problem) + assertFalse("A refused duplicate never opened a socket with its credentials", sessions.last().connected) + + val registry = registry() + val rows = (1..32).map { SavedComputer(UUID.randomUUID(), "Computer $it", HermesEndpoint.parse("https://c$it.example.test"), "dashboard-session", true) } + registry.replace(registry.load(), rows, null) + model.beginSetup(HermesEndpoint.parse("https://thirty-three.example.test")).join() + model.signIn("One too many", SignInInput.Dashboard).join() + assertEquals(ComputerProblem.ComputerLimit, model.state.value.problem) + assertFalse(sessions.last().connected) + model.disconnect().join() + } + + @Test fun gateCredentialsAreSavedBeforeTheSignInCommitAndComeBackOnTheNextLaunch() = runTest { + val gate = AccessSetup(AccessCredential.proxyBasic("gate-user", "gate-password"), CustomHeader.list(listOf("X-Access-Id" to "synthetic"))) + val model = model(backgroundScope) + model.beginSetup(endpoint, gate).join() + assertEquals(gate, factoryCalls.single().third) + model.signIn("Garden computer", SignInInput.Dashboard).join() + val row = registry().load().computers.single() + assertEquals("The gate details were durable before the sign-in was", true, sessions.single().accessSavedBeforeCommit) + assertEquals(gate, localData.access[row.id]) + model.disconnect().join() + + val restored = model(backgroundScope) + restored.load().join() + assertEquals("The saved gate details reach the new session", gate, factoryCalls.last().third) + restored.disconnect().join() + } + + @Test fun removingAComputerAlsoForgetsItsGateDetailsAndLocalChatRecords() = runTest { + val model = model(backgroundScope) + model.beginSetup(endpoint, AccessSetup(AccessCredential.proxyBasic("gate-user", "gate-password"), emptyList())).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + val row = registry().load().computers.single() + model.remove(row.id).join() + assertEquals(listOf(row.id), localData.forgotten) + assertTrue(localData.access.isEmpty()) + assertTrue(registry().load().computers.isEmpty()) + } + + @Test fun reauthenticatingReusesTheSavedGateDetails() = runTest { + val gate = AccessSetup(AccessCredential.cloudflareAccess("id-0123", "secret-0123"), emptyList()) + val model = model(backgroundScope) + model.beginSetup(HermesEndpoint.parse("https://gated.example.test"), gate).join() + model.signIn("Gated computer", SignInInput.Dashboard).join() + val row = registry().load().computers.single() + model.reauthenticate(row.id).join() + assertEquals(gate, factoryCalls.last().third) + model.disconnect().join() + } + + private suspend fun kotlinx.coroutines.test.TestScope.connectedComputer(): Pair, SavedComputer> { + val model = model(backgroundScope) + model.beginSetup(endpoint).join() + model.signIn("Garden computer", SignInInput.Dashboard).join() + sessions.single().rotateOnClose = true + return model to registry().load().computers.single() + } + + private suspend fun rotatedToken(row: SavedComputer) = + (vault(row.id).load(row.authority)?.auth as? StoredAuth.DashboardSession)?.token + + @Test fun aRefreshFinishingWhileTheComputerIsReplacedStillSavesItsRotatedSignIn() = runTest { + val (model, row) = connectedComputer() + model.select(row.id).join() + val old = sessions.first() + assertEquals("The renewal could still save while the session shut down", true, old.closeWrite) + assertEquals("The owner's scope outlived the gateway's disconnect", true, old.scopeActiveOnClose) + assertEquals("rotated-session", rotatedToken(row)) + model.disconnect().join() + } + + @Test fun aRefreshFinishingWhileTheComputerIsDisconnectedStillSavesItsRotatedSignIn() = runTest { + val (model, row) = connectedComputer() + model.disconnect().join() + assertEquals(true, sessions.single().closeWrite) + assertEquals(true, sessions.single().scopeActiveOnClose) + assertEquals("rotated-session", rotatedToken(row)) + } + + @Test fun aRefreshFinishingWhileTheModelIsClosedStillSavesItsRotatedSignIn() = runTest { + val (model, row) = connectedComputer() + model.close().join() + assertEquals(true, sessions.single().closeWrite) + assertEquals(true, sessions.single().scopeActiveOnClose) + assertEquals("rotated-session", rotatedToken(row)) + } + + @Test fun removalKeepsTheFastOrderSoALateRefreshCannotRecreateTheDeletedSignIn() = runTest { + val (model, row) = connectedComputer() + model.remove(row.id).join() + assertEquals("A deleted computer's late refresh is refused", false, sessions.single().closeWrite) + assertNull(rotatedToken(row)) + assertTrue(registry().load().computers.isEmpty()) + } + +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/ComputerLinkTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerLinkTest.kt new file mode 100644 index 00000000..c3a81639 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerLinkTest.kt @@ -0,0 +1,34 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.GatewayState +import app.bighelp.hermes.HermesException +import org.junit.Assert.assertEquals +import org.junit.Test + +class ComputerLinkTest { + private fun state(connection: GatewayConnection, generation: Long = 1, failure: HermesException.Kind? = null) = + GatewayState(connection, generation, null, null, null, false, failure?.let { HermesException(it) }) + + @Test fun onlyAReadyGatewayIsConnected() { + assertEquals(ComputerLink.Connected, linkOf(state(GatewayConnection.Connected))) + assertEquals(ComputerLink.Connecting, linkOf(state(GatewayConnection.Connecting))) + assertEquals(ComputerLink.Reconnecting, linkOf(state(GatewayConnection.Recovering, failure = HermesException.Kind.Disconnected))) + } + + @Test fun aGatewayThatNeverConnectedIsStillConnectingNotOffline() { + assertEquals(ComputerLink.Connecting, linkOf(state(GatewayConnection.Idle, generation = 0))) + } + + @Test fun aConnectionThatEndedAndIsNotRecoveringIsOfflineSoTheScreenOffersReconnect() { + assertEquals(ComputerLink.Offline, linkOf(state(GatewayConnection.Idle, 3, HermesException.Kind.Disconnected))) + assertEquals(ComputerLink.Offline, linkOf(state(GatewayConnection.Idle, 3))) + assertEquals(ComputerLink.Offline, linkOf(state(GatewayConnection.Closed, 3))) + } + + @Test fun aRefusedSignInIsNotMistakenForAnOutage() { + assertEquals(ComputerLink.SignInRequired, linkOf(state(GatewayConnection.Idle, 2, HermesException.Kind.AuthenticationRequired))) + assertEquals(ComputerLink.SignInRequired, linkOf(state(GatewayConnection.Idle, 2, HermesException.Kind.InvalidCredentials))) + assertEquals(ComputerLink.Offline, linkOf(state(GatewayConnection.Idle, 2, HermesException.Kind.ServerUnavailable))) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/LiveModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/LiveModelTest.kt new file mode 100644 index 00000000..046ca2d9 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/LiveModelTest.kt @@ -0,0 +1,279 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.AuthProvider +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.chat.ChatError +import app.bighelp.hermes.chat.ChatException +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.SendMode +import app.bighelp.hermes.chat.SendResult +import app.bighelp.hermes.chat.Admission +import app.bighelp.hermes.chat.SessionSearchResult +import app.bighelp.hermes.chat.SessionSummary +import app.bighelp.hermes.chat.ArchiveState +import app.bighelp.hermes.chat.AgentSummary +import app.bighelp.hermes.chat.CatalogState +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) +class LiveModelTest { + @get:Rule val temporary = TemporaryFolder() + private val ref = ConversationRef("default", "anchor-1") + private val other = ConversationRef("default", "anchor-2") + + private fun TestScopeRig(scope: kotlinx.coroutines.CoroutineScope, delays: List = listOf(2_000, 6_000, 18_000)) = LiveRig(temporary.root, scope, delays) + + // ---- coming back, and losing the connection + + @Test fun comingBackToTheFrontAsksTheActiveComputerToResume() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect() + rig.model.onForeground() + runCurrent() + assertEquals(1, rig.session.resumed) + } + + @Test fun comingBackDoesNotReconnectAComputerThePersonDisconnected() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect() + rig.model.connections.disconnect().join() + rig.model.onForeground(); runCurrent() + assertEquals("No new session was made for a deliberate disconnect", 1, rig.sessions.size) + } + + @Test fun aLostConnectionIsRetriedWithGrowingPausesWhileInFrontAndStopsOnceItIsBack() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect() + rig.model.onForeground(); runCurrent() + rig.session.reconnectFailures += listOf(ChatException(ChatError.Kind.HostUnavailable), ChatException(ChatError.Kind.HostUnavailable)) + rig.session.link.value = ComputerLink.Offline + runCurrent() + assertEquals(0, rig.session.reconnects) + advanceTimeBy(2_001); runCurrent() + assertEquals(1, rig.session.reconnects) + advanceTimeBy(6_000); runCurrent() + assertEquals(2, rig.session.reconnects) + advanceTimeBy(18_000); runCurrent() + assertEquals("The third attempt worked", 3, rig.session.reconnects) + rig.session.link.value = ComputerLink.Connected + runCurrent() + advanceTimeBy(120_000); runCurrent() + assertEquals("No more attempts once connected", 3, rig.session.reconnects) + assertNull(rig.model.reconnectProblem.value) + } + + @Test fun retriesStopAfterTheLastPauseAndLeaveTheManualReconnect() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); rig.model.onForeground(); runCurrent() + rig.session.reconnectFailures += List(10) { ChatException(ChatError.Kind.HostUnavailable) } + rig.session.link.value = ComputerLink.Offline + runCurrent() + advanceTimeBy(60_000); runCurrent() + assertEquals(3, rig.session.reconnects) + rig.model.reconnectNow(); runCurrent() + assertEquals(4, rig.session.reconnects) + assertNotNull("A failed manual reconnect says so", rig.model.notice.value) + } + + @Test fun nothingIsRetriedWhileTheAppIsInTheBackground() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); rig.model.onForeground(); runCurrent() + rig.session.link.value = ComputerLink.Offline + runCurrent() + advanceTimeBy(1_000); rig.model.onBackground(); runCurrent() + advanceTimeBy(120_000); runCurrent() + assertEquals(0, rig.session.reconnects) + rig.model.onForeground(); runCurrent() + advanceTimeBy(2_001); runCurrent() + assertEquals("Back in front, the retries start again", 1, rig.session.reconnects) + } + + @Test fun aRefusedSignInStopsTheRetriesAndAsksForANewSignIn() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); rig.model.onForeground(); runCurrent() + rig.session.reconnectFailures += ChatException(ChatError.Kind.SignInRequired) + rig.session.link.value = ComputerLink.Offline + runCurrent() + advanceTimeBy(2_001); runCurrent() + advanceTimeBy(120_000); runCurrent() + assertEquals(1, rig.session.reconnects) + assertEquals(ChatError.Kind.SignInRequired, rig.model.reconnectProblem.value) + } + + // ---- setup + + @Test fun discoveryHandsBackTheHostsSignInOptions() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.prepare = { it.status = AuthStatus(true, listOf("native_pkce"), listOf(AuthProvider("basic", "Password", true))) } + val outcome = rig.model.beginSetup(rig.endpoint, AccessSetup.None) + assertEquals(ComputerPhase.SignIn, rig.connections.state.value.phase) + assertEquals("basic", (outcome as SetupOutcome.Ready).status.providers.single().name) + rig.model.cancelSetup().join() + } + + @Test fun aGateRefusalIsReportedInPlainWordsAndLeavesNothingBehind() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.prepare = { it.discoverFailure = HermesException.Kind.CloudflareAccessDenied } + val outcome = rig.model.beginSetup(rig.endpoint, AccessSetup.None) + assertTrue(outcome is SetupOutcome.Failed) + assertTrue((outcome as SetupOutcome.Failed).message.contains("access", ignoreCase = true)) + assertNull(rig.connections.active.value) + } + + @Test fun cancellingSetupWhileItRunsIsNotAFailure() = runTest { + val rig = TestScopeRig(backgroundScope) + val pending = kotlinx.coroutines.CompletableDeferred() + rig.prepare = { } + val outcome = rig.model.beginSetup(rig.endpoint, AccessSetup.None) + rig.model.cancelSetup().join() + pending.complete(outcome) + assertTrue("A finished setup that was then cancelled is Ready, and a later cancel changes the phase only", rig.connections.state.value.phase == ComputerPhase.Idle) + } + + @Test fun aFailedSignInCanBeTriedAgainOnTheSameScreenWithoutStartingOver() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.prepare = { it.signInFailure = if (rig.sessions.size == 1) HermesException.Kind.InvalidCredentials else null } + rig.model.beginSetup(rig.endpoint, AccessSetup.None) + rig.model.signIn("Garden computer", app.bighelp.hermes.SignInInput.Token("synthetic-token-0123456789")).join() + assertEquals(ComputerPhase.Failed, rig.connections.state.value.phase) + assertEquals(HermesException.Kind.InvalidCredentials, rig.connections.state.value.authFailure) + + rig.model.signIn("Garden computer", app.bighelp.hermes.SignInInput.Token("synthetic-token-0123456789")).join() + runCurrent() + assertEquals("The second try ran on a fresh session", 2, rig.sessions.size) + assertEquals(ComputerPhase.Connected, rig.connections.state.value.phase) + assertEquals(1, rig.sessions.count { it.closed }) + } + + // ---- sending + + @Test fun anAdmittedSendClearsTheComposerAndARefusalKeepsTheText() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.chat.nextSend = SendResult.Admitted("e1", Admission.Streaming) + assertEquals(SendOutcome.Sent, rig.model.send(ref, "hello", SendMode.Default)) + assertEquals(Triple(ref, "hello", SendMode.Default), rig.chat.sends.single()) + + rig.chat.nextSend = SendResult.NotSent(ChatError(ChatError.Kind.PersistenceFailed)) + val kept = rig.model.send(ref, "again", SendMode.Default) + assertTrue(kept is SendOutcome.Kept) + assertTrue((kept as SendOutcome.Kept).message.contains("nothing was sent")) + } + + @Test fun aSendWhoseOutcomeIsUnknownLeavesTheComposerClearButTellsThePersonToReview() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.chat.nextSend = SendResult.Uncertain("e1", ChatError(ChatError.Kind.OutcomeUnknown)) + assertEquals(SendOutcome.Sent, rig.model.send(ref, "maybe", SendMode.Default)) + assertTrue(rig.model.notice.value!!.text.contains("couldn't")) + } + + @Test fun aTypedCommandIsCheckedAgainstTheHostsCommandListBeforeItIsSent() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.chat.commandIndex = app.bighelp.hermes.chat.SlashCommandIndex(listOf( + app.bighelp.hermes.chat.SlashCommand("plan", "Plan first", "Commands", emptyList(), app.bighelp.hermes.chat.ArgumentMode.Text, app.bighelp.hermes.chat.CommandSource.Core), + )) + rig.chat.nextSend = SendResult.Admitted("e1", Admission.CommandOutput) + rig.model.send(ref, "/plan the trip", SendMode.Default) + assertEquals("plan", rig.chat.sendSelections.single()!!.command.name) + rig.model.send(ref, "/unknown thing", SendMode.Default) + assertNull("A command the host does not list is sent as the host decides, not as a guess", rig.chat.sendSelections.last()) + rig.model.send(ref, "plain words", SendMode.Default) + assertEquals("Ordinary text never asks for the command list", 1, rig.chat.commandCalls) + } + + // ---- drafts + + @Test fun typingSavesOneDraftAfterThePauseAndASendCancelsAPendingSave() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.model.editDraft(ref, "h"); advanceTimeBy(100) + rig.model.editDraft(ref, "he"); advanceTimeBy(100) + rig.model.editDraft(ref, "hel"); advanceTimeBy(200); runCurrent() + assertEquals("Not yet: the pause restarted with every key", emptyList(), rig.chat.drafts) + advanceTimeBy(150); runCurrent() + assertEquals(listOf(ref to "hel"), rig.chat.drafts) + + rig.chat.nextSend = SendResult.Admitted("e", Admission.Streaming) + rig.model.editDraft(ref, "sent text") + rig.model.send(ref, "sent text", SendMode.Default) + advanceTimeBy(5_000); runCurrent() + assertEquals("A send's own clearing wins over a save that was still waiting", listOf(ref to "hel"), rig.chat.drafts) + } + + @Test fun leavingAChatSavesItsDraftAtOnce() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.model.editDraft(ref, "unfinished") + rig.model.leaveChat(ref) + assertEquals(listOf(ref to "unfinished"), rig.chat.drafts) + advanceTimeBy(5_000); runCurrent() + assertEquals("The waiting save did not run a second time", 1, rig.chat.drafts.size) + } + + // ---- what stays retained + + @Test fun leavingAChatReleasesItOnlyWhenNothingIsRunningOrWaitingForTheReader() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.chat.conversations.value = mapOf(ref to rig.chat.state(ref), other to rig.chat.state(other, running = true)) + rig.model.leaveChat(ref) + rig.model.leaveChat(other) + assertEquals(listOf(ref), rig.chat.released) + } + + @Test fun openingAChatReleasesOtherIdleOnesButNotARunningOne() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + val third = ConversationRef("default", "anchor-3") + rig.chat.conversations.value = mapOf(other to rig.chat.state(other), third to rig.chat.state(third, running = true)) + rig.model.openChat(ref) + assertEquals(listOf(ref), rig.chat.opened) + assertEquals(listOf(other), rig.chat.released) + } + + // ---- search + + private fun summary(profile: String, anchor: String, title: String) = SessionSummary( + ConversationRef(profile, anchor), profile, anchor, title, "", null, 1.0, 1, "bighelp", null, false, ArchiveState.None, null, null, false, false, + ) + + @Test fun contentSearchWaitsForAPauseThenAsksEachAgentOnceAndKeepsOnlyTheLatestQuery() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.chat.catalog.value = CatalogState(agents = listOf("default", "moss").map { AgentSummary(it, it, null, JsonObject(emptyMap())) }) + rig.chat.searchResults = { profile, query -> listOf(SessionSearchResult(summary(profile, "hit-$profile", "Hit in $profile"), "…$query…")) } + runCurrent() + rig.model.setSearch("ro"); advanceTimeBy(200) + rig.model.setSearch("rou"); advanceTimeBy(300); runCurrent() + assertTrue("Still waiting: the pause restarted", rig.chat.searches.isEmpty()) + advanceTimeBy(200); runCurrent() + assertEquals(setOf("default" to "rou", "moss" to "rou"), rig.chat.searches.toSet()) + assertEquals(setOf("Hit in default", "Hit in moss"), rig.model.contentHits.value.map { it.title }.toSet()) + rig.model.setSearch("") + runCurrent() + assertTrue(rig.model.contentHits.value.isEmpty()) + } + + @Test fun aOneLetterQueryAsksTheHostNothing() = runTest { + val rig = TestScopeRig(backgroundScope) + rig.connect(); runCurrent() + rig.chat.catalog.value = CatalogState(agents = listOf(AgentSummary("default", "default", null, JsonObject(emptyMap())))) + runCurrent() + rig.model.setSearch("r"); advanceTimeBy(5_000); runCurrent() + assertTrue(rig.chat.searches.isEmpty()) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/LiveTestSupport.kt b/android/app/src/test/kotlin/app/bighelp/android/live/LiveTestSupport.kt new file mode 100644 index 00000000..9107da5f --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/LiveTestSupport.kt @@ -0,0 +1,150 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.hermes.AuthProvider +import app.bighelp.hermes.AuthStatus +import app.bighelp.hermes.CredentialStore +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.SavedConnection +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.StoredAuth +import app.bighelp.hermes.chat.BotChatOutcome +import app.bighelp.hermes.chat.CatalogState +import app.bighelp.hermes.chat.ChatError +import app.bighelp.hermes.chat.ChatException +import app.bighelp.hermes.chat.ConnectionStatus +import app.bighelp.hermes.chat.ConversationIdentity +import app.bighelp.hermes.chat.ConversationPhase +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.CreateOutcome +import app.bighelp.hermes.chat.CreateRequest +import app.bighelp.hermes.chat.DraftResult +import app.bighelp.hermes.chat.HistoryLoad +import app.bighelp.hermes.chat.ModelChange +import app.bighelp.hermes.chat.ModelOptions +import app.bighelp.hermes.chat.PendingCreation +import app.bighelp.hermes.chat.PromptAnswer +import app.bighelp.hermes.chat.PromptResult +import app.bighelp.hermes.chat.ReviewDecision +import app.bighelp.hermes.chat.ReviewResult +import app.bighelp.hermes.chat.SendMode +import app.bighelp.hermes.chat.SendResult +import app.bighelp.hermes.chat.SessionSearchResult +import app.bighelp.hermes.chat.SessionSummary +import app.bighelp.hermes.chat.SlashCommandIndex +import app.bighelp.hermes.chat.SlashSelection +import app.bighelp.hermes.chat.StopResult +import java.io.File +import java.util.UUID +import javax.crypto.KeyGenerator +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** A chat service that records calls and answers what a test scripts. Nothing here talks to a network. */ +internal class FakeChat : ChatService { + override val catalog = MutableStateFlow(CatalogState()) + override val conversations = MutableStateFlow>(emptyMap()) + override val pendingCreations = MutableStateFlow>(emptyList()) + override val connection: StateFlow = MutableStateFlow(ConnectionStatus()) + + val drafts = mutableListOf>() + val sends = mutableListOf>() + val sendSelections = mutableListOf() + val released = mutableListOf() + val opened = mutableListOf() + val searches = mutableListOf>() + var nextSend: SendResult = SendResult.NotSent(ChatError(ChatError.Kind.NotConnected)) + var commandIndex = SlashCommandIndex(emptyList()) + var commandCalls = 0 + var searchResults: (String, String) -> List = { _, _ -> emptyList() } + + fun state(ref: ConversationRef, running: Boolean = false, prompts: List = emptyList()) = + ConversationState(ref, "Chat", ConversationIdentity(ref, ref.anchor), ConversationPhase.Ready, running = running, prompts = prompts) + + override suspend fun refreshCatalog() = catalog.value + override suspend fun archivedChats(): List = emptyList() + override suspend fun search(profile: String, query: String): List { searches += profile to query; return searchResults(profile, query) } + override suspend fun createChat(profile: String, request: CreateRequest, retryIntent: String?): CreateOutcome = error("unused") + override suspend fun discardCreation(profile: String) = Unit + override suspend fun openBotChat(profile: String, createIfMissing: Boolean): BotChatOutcome = error("unused") + override suspend fun open(ref: ConversationRef): ConversationState { opened += ref; return conversations.value[ref] ?: state(ref) } + override suspend fun release(ref: ConversationRef) { released += ref } + override suspend fun updateDraft(ref: ConversationRef, text: String): DraftResult { drafts += ref to text; return DraftResult.Saved } + override suspend fun send(ref: ConversationRef, text: String, mode: SendMode, selection: SlashSelection?): SendResult { + sends += Triple(ref, text, mode); sendSelections += selection; return nextSend + } + override suspend fun stop(ref: ConversationRef): StopResult = StopResult.Requested + override suspend fun resolveUnresolved(ref: ConversationRef, entryId: String, decision: ReviewDecision): ReviewResult = ReviewResult.Done + override suspend fun answerPrompt(promptId: String, answer: PromptAnswer): PromptResult = PromptResult.Answered + override suspend fun declinePrompt(promptId: String): PromptResult = PromptResult.Answered + override suspend fun loadOlder(ref: ConversationRef): HistoryLoad = HistoryLoad.NothingOlder + override suspend fun reloadHistory(ref: ConversationRef) = Unit + override suspend fun rename(ref: ConversationRef, title: String) = Unit + override suspend fun archive(ref: ConversationRef) = Unit + override suspend fun restore(ref: ConversationRef) = Unit + override suspend fun delete(ref: ConversationRef) = Unit + override suspend fun fork(ref: ConversationRef, throughRowId: Long): ConversationRef = error("unused") + override suspend fun commands(ref: ConversationRef): SlashCommandIndex { commandCalls++; return commandIndex } + override suspend fun commandsForNewChat(profile: String): SlashCommandIndex = commandIndex + override suspend fun modelOptions(ref: ConversationRef): ModelOptions = error("unused") + override suspend fun setModel(ref: ConversationRef, model: String, provider: String, confirmed: Boolean): ModelChange = error("unused") + override suspend fun setReasoning(ref: ConversationRef, level: String) = Unit + override suspend fun setFast(ref: ConversationRef, on: Boolean) = Unit +} + +internal class TestSession(val endpoint: HermesEndpoint, private val store: CredentialStore, val chat: FakeChat) : ComputerSession { + override var saved: SavedConnection? = null + override val link = MutableStateFlow(ComputerLink.Connected) + var status = AuthStatus(false, emptyList(), emptyList()) + var discoverFailure: HermesException.Kind? = null + var signInFailure: HermesException.Kind? = null + var resumed = 0 + var reconnects = 0 + var reconnectFailures: MutableList = mutableListOf() + var closed = false + + override suspend fun discover(): AuthStatus { + discoverFailure?.let { throw HermesException(it) } + return status + } + override suspend fun signIn(input: SignInInput): SavedConnection { + signInFailure?.let { throw HermesException(it) } + return SavedConnection(endpoint, StoredAuth.DashboardSession("synthetic-session", true), null, null).also { saved = it } + } + override suspend fun restore(saved: SavedConnection) { this.saved = saved } + override suspend fun connect() = Unit + override suspend fun commit(expected: SavedConnection?, stillCurrent: () -> Boolean) { store.replace(expected, requireNotNull(saved)) } + override suspend fun resume() { resumed++ } + override suspend fun reconnect() { + reconnects++ + if (reconnectFailures.isNotEmpty()) throw reconnectFailures.removeAt(0) + } + override suspend fun close() { closed = true } +} + +/** A real coordinator over temporary files, with fake sessions, a fake chat and the live model on top. */ +internal class LiveRig(private val root: File, scope: CoroutineScope, retryDelays: List = listOf(2_000, 6_000, 18_000)) { + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + val endpoint: HermesEndpoint = HermesEndpoint.parse("https://example.test/hermes") + val chat = FakeChat() + val sessions = mutableListOf() + var consent = true + var prepare: (TestSession) -> Unit = {} + val session get() = sessions.last() + private fun vault(id: UUID) = AndroidCredentialStore(ProtectedRecordStore(File(root, "sign-ins"), RecordCipher { key }), id.toString(), Dispatchers.Unconfined) + private val registry = SavedComputerStore(ProtectedRecordStore(File(root, "index"), RecordCipher { key }), Dispatchers.Unconfined) + val connections = ComputerConnectionModel(registry, ::vault, { consent }, scope) { _, address, _, credentials, _ -> + TestSession(address, credentials, chat).also { sessions += it; prepare(it) } + } + val model = LiveModel(connections, { (it as TestSession).chat }, scope, retryDelays = retryDelays) + + suspend fun connect() { + connections.beginSetup(endpoint).join() + connections.signIn("Garden computer", SignInInput.Dashboard).join() + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/LiveTextTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/LiveTextTest.kt new file mode 100644 index 00000000..53f7daa9 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/LiveTextTest.kt @@ -0,0 +1,42 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.chat.ChatError +import app.bighelp.hermes.chat.SendBlock +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class LiveTextTest { + private val banned = listOf("openai", "anthropic", "gpt", "claude", "bighelp account", "link account", "exception") + + @Test fun everyMessageIsPlainWordsWithoutProviderNamesAccountsOrCodes() { + val texts = ChatError.Kind.entries.map { LiveText.describe(ChatError(it)) } + + HermesException.Kind.entries.map { LiveText.describe(it) } + + SendBlock.entries.map { LiveText.sendBlock(it) } + + ComputerLink.entries.mapNotNull { LiveText.link(it) } + + ComputerProblem.entries.map { LiveText.problem(it) } + for (text in texts) { + assertTrue("A message is never empty", text.isNotBlank()) + assertTrue("A message ends like a sentence: $text", text.last() in ".…?") + for (word in banned) assertFalse("'$text' mentions '$word'", text.lowercase().contains(word)) + } + } + + @Test fun aMissingHostFeatureSaysToUpdateThePluginAndNothingIsCalledAnError() { + assertTrue(LiveText.describe(ChatError(ChatError.Kind.Unsupported)).contains("update the plugin", ignoreCase = true)) + assertFalse(LiveText.describe(ChatError(ChatError.Kind.Unsupported)).contains("error", ignoreCase = true)) + } + + @Test fun aRefusedSignInAndAGatePointAtTheRightFix() { + assertTrue(LiveText.describe(HermesException.Kind.InvalidCredentials).contains("sign", ignoreCase = true)) + assertTrue(LiveText.describe(HermesException.Kind.CloudflareAccessDenied).contains("access", ignoreCase = true)) + assertTrue(LiveText.describe(HermesException.Kind.PlaintextNotAllowed).contains("https", ignoreCase = true)) + } + + @Test fun theConnectionBannerSaysNothingWhileConnected() { + assertTrue(LiveText.link(ComputerLink.Connected) == null) + assertTrue(LiveText.link(null) == null) + assertTrue(LiveText.link(ComputerLink.Reconnecting)!!.contains("reconnect", ignoreCase = true)) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/NetworkComputerSessionTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/NetworkComputerSessionTest.kt new file mode 100644 index 00000000..183a8ef4 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/NetworkComputerSessionTest.kt @@ -0,0 +1,112 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.InMemoryCredentialStore +import app.bighelp.hermes.SignInInput +import app.bighelp.hermes.chat.MemoryChatStore +import java.util.UUID +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** The real authenticator, gateway and chat repository of one computer, against a scripted loopback host. */ +class NetworkComputerSessionTest { + private val server = MockWebServer() + private val requests = java.util.Collections.synchronizedList(mutableListOf()) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @Before fun start() { + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + requests += request.path.orEmpty().substringBefore('?') + return if (request.path == "/api/status") { + MockResponse().setHeader("Content-Type", "application/json").setBody("{\"auth_required\":false,\"auth_flows\":[]}") + } else MockResponse().setResponseCode(404) + } + } + server.start() + } + + @After fun stop() { scope.cancel(); server.shutdown() } + + private fun session() = NetworkComputerSession( + UUID.randomUUID(), HermesEndpoint.parse("http://127.0.0.1:${server.port}", allowPrivateHttp = true), AccessSetup.None, + InMemoryCredentialStore(), scope, null, MemoryChatStore(), + ) + + @Test fun theChatRepositoryExistsFromTheSignInSoItsHandlersAreReadyBeforeAnySocketOpens() = runBlocking { + val session = session() + assertNull("No sign-in yet, so no principal to scope chat records by", session.chatOrNull) + assertEquals(ComputerLink.Connecting, session.link.value) + + session.signIn(SignInInput.Token("synthetic-session-token-000111")) + + assertNotNull(session.chatOrNull) + assertEquals(GatewayConnection.Idle, session.chat.connection.value.gateway) + assertFalse("No socket was attempted by sign-in", requests.any { it == "/api/ws" }) + session.close() + } + + @Test fun aFailedConnectIsTypedAndTheLinkSaysOfflineNotConnecting() = runBlocking { + val session = session() + session.signIn(SignInInput.Token("synthetic-session-token-000111")) + val failure = runCatching { session.connect() }.exceptionOrNull() + assertTrue("connect() failed with a typed error: $failure", failure is HermesException) + withTimeout(10_000) { session.link.first { it == ComputerLink.Offline || it == ComputerLink.SignInRequired } } + session.close() + } + + @Test fun signingInAgainAsTheSamePrincipalKeepsOneRepository() = runBlocking { + val session = session() + session.signIn(SignInInput.Token("synthetic-session-token-000111")) + val first = session.chat + session.signIn(SignInInput.Token("synthetic-session-token-000111")) + assertTrue(first === session.chat) + session.close() + } + + @Test fun comingBackToTheFrontReconnectsADroppedGatewayAndAHostProblemIsNotThrownAtTheScreen() = runBlocking { + val session = session() + session.signIn(SignInInput.Token("synthetic-session-token-000111")) + runCatching { session.connect() } + withTimeout(10_000) { session.link.first { it == ComputerLink.Offline || it == ComputerLink.SignInRequired } } + requests.clear() + + session.resume() + + assertTrue("resume() asked the host again: $requests", requests.contains("/api/status") && requests.contains("/api/ws")) + session.close() + } + + @Test fun theExplicitReconnectReachesTheHostAndFailsWithATypedError() = runBlocking { + val session = session() + session.signIn(SignInInput.Token("synthetic-session-token-000111")) + runCatching { session.connect() } + withTimeout(10_000) { session.link.first { it == ComputerLink.Offline || it == ComputerLink.SignInRequired } } + requests.clear() + + val failure = runCatching { session.reconnect() }.exceptionOrNull() + + assertTrue("A typed chat error, not a raw one: $failure", failure is app.bighelp.hermes.chat.ChatException) + assertTrue(requests.contains("/api/ws")) + session.close() + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/SavedComputerStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/SavedComputerStoreTest.kt new file mode 100644 index 00000000..4272967a --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/SavedComputerStoreTest.kt @@ -0,0 +1,188 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.android.storage.RecordStorageException +import app.bighelp.android.storage.StorageProblem +import app.bighelp.android.storage.RecordFileOperations +import app.bighelp.android.storage.SystemRecordFileOperations +import app.bighelp.hermes.HermesEndpoint +import java.util.UUID +import javax.crypto.KeyGenerator +import java.io.File +import java.io.InputStream +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.supervisorScope +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class SavedComputerStoreTest { + @get:Rule val temporary = TemporaryFolder() + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + private fun records() = ProtectedRecordStore(temporary.root, RecordCipher { key }) + private fun store() = SavedComputerStore(records()) + private fun computer(name: String = "Garden computer") = SavedComputer( + UUID.randomUUID(), name, HermesEndpoint.parse("https://example.test/hermes"), "dashboard-session", false, + ) + + @Test fun namesSelectionAndSetupStateSurviveReopening() = runBlocking { + val first = computer() + val second = computer("Research computer").copy(setupComplete = true) + val initial = store().load() + assertTrue(initial.computers.isEmpty()) + assertNull(initial.selectedID) + val saved = store().replace(initial, listOf(first, second), second.id) + assertEquals(saved, store().load()) + assertFalse(saved.computers.first().setupComplete) + assertTrue(saved.computers.last().setupComplete) + } + + @Test fun aStaleWindowCannotOverwriteAChangedComputerList() = runBlocking { + val initial = store().load() + val first = computer() + val saved = store().replace(initial, listOf(first), first.id) + try { + store().replace(initial, emptyList(), null) + fail("A stale computer list must not overwrite a new one") + } catch (failure: SavedComputersException) { + assertEquals(SavedComputersProblem.Changed, failure.problem) + } + assertEquals(saved, store().load()) + } + + @Test fun renamingAndRemovingSelectionPreserveOtherComputers() = runBlocking { + val first = computer() + val second = computer("Moss").copy(setupComplete = true) + val original = store().replace(store().load(), listOf(first, second), first.id) + val renamed = store().replace(original, listOf(first.copy(name = "Garden 🌿"), second), first.id) + assertEquals("Garden 🌿", store().load().computers.first().name) + assertNotEquals(original.revision, renamed.revision) + val removed = store().replace(renamed, listOf(second), null) + assertEquals(listOf(second), removed.computers) + assertNull(store().load().selectedID) + } + + @Test fun invalidSelectionAndDuplicateIdentifiersAreRefusedWithoutWriting() = runBlocking { + val empty = store().load() + val first = computer() + for ((items, selected) in listOf(listOf(first) to UUID.randomUUID(), listOf(first, first) to first.id)) { + try { + store().replace(empty, items, selected) + fail("Invalid computer list must be refused") + } catch (failure: SavedComputersException) { + assertEquals(SavedComputersProblem.InvalidChange, failure.problem) + } + } + assertEquals(empty, store().load()) + } + + @Test fun theConfiguredHostCeilingMatchesTheNativeApp() = runBlocking { + val items = List(32) { computer("Computer $it") } + val saved = store().replace(store().load(), items, items.first().id) + try { + store().replace(saved, items + computer("Another computer"), null) + fail("The 33rd configured computer must be refused") + } catch (failure: SavedComputersException) { + assertEquals(SavedComputersProblem.InvalidChange, failure.problem) + } + assertEquals(saved, store().load()) + } + + @Test fun unreadableDataDoesNotSilentlyEraseTheSavedComputerList() = runBlocking { + val item = computer() + store().replace(store().load(), listOf(item), item.id) + temporary.root.listFiles()!!.single { it.extension == "sealed" }.writeBytes(byteArrayOf(1)) + try { + store().load() + fail("Unreadable storage must not be presented as an empty list") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.CorruptRecord, failure.problem) + } + } + + @Test fun unknownSchemaIsRefusedWithoutReplacingOrDroppingIt() = runBlocking { + val bytes = """{"schemaVersion":999,"computers":[]}""".toByteArray() + assertTrue(records().compareAndSet(SAVED_COMPUTERS_RECORD_KEY, null, bytes)) + try { + store().load() + fail("A future schema must not be silently reset") + } catch (failure: SavedComputersException) { + assertEquals(SavedComputersProblem.Unreadable, failure.problem) + } + assertArrayEquals(bytes, records().read(SAVED_COMPUTERS_RECORD_KEY)) + } + + @Test fun onlyExplicitRecoveryCanDiscardAnUnreadableList() = runBlocking { + val item = computer() + val saved = store().replace(store().load(), listOf(item), item.id) + assertFalse(store().discardUnreadable()) + assertEquals(saved, store().load()) + temporary.root.listFiles()!!.single { it.extension == "sealed" }.writeBytes(byteArrayOf(1)) + assertTrue(store().discardUnreadable()) + assertTrue(store().load().computers.isEmpty()) + } + + @Test fun cancellationDuringTheReadPreventsAComputerListWrite() = runBlocking { + val empty = store().load() + supervisorScope { + lateinit var job: Deferred + var reads = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream { + reads++ + job.cancel() + return SystemRecordFileOperations.read(file) + } + } + val vault = SavedComputerStore(ProtectedRecordStore(temporary.root, RecordCipher { key }, io)) + val first = computer() + job = async(start = CoroutineStart.LAZY) { vault.replace(empty, listOf(first), first.id) } + job.start() + try { job.await(); fail("Cancelled work must not write") } catch (_: CancellationException) { } + assertEquals(1, reads) + } + assertEquals(empty, store().load()) + } + + @Test fun aNewComputerCannotOverwriteAnUnreadableOrFutureSchemaIndex() = runBlocking { + val empty = store().load() + val item = computer() + val records = records() + val future = """{"schemaVersion":999}""".toByteArray() + assertTrue(records.compareAndSet(SAVED_COMPUTERS_RECORD_KEY, null, future)) + try { store().replace(empty, listOf(item), item.id); fail("Future data must not be replaced") } + catch (failure: SavedComputersException) { assertEquals(SavedComputersProblem.Unreadable, failure.problem) } + assertArrayEquals(future, records.read(SAVED_COMPUTERS_RECORD_KEY)) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" } + val corrupt = byteArrayOf(1, 2, 3) + file.writeBytes(corrupt) + try { store().replace(empty, listOf(item), item.id); fail("Corrupt data must not be replaced") } + catch (failure: RecordStorageException) { assertEquals(StorageProblem.CorruptRecord, failure.problem) } + assertArrayEquals(corrupt, file.readBytes()) + } + + @Test fun recoveryCannotDeleteAConcurrentValidIndexReplacement() = runBlocking { + val item = computer() + val replacementRoot = temporary.newFolder("replacement") + val replacement = SavedComputerStore(ProtectedRecordStore(replacementRoot, RecordCipher { key })) + val valid = replacement.replace(replacement.load(), listOf(item), item.id) + val envelope = replacementRoot.listFiles()!!.single { it.extension == "sealed" }.readBytes() + assertTrue(records().compareAndSet(SAVED_COMPUTERS_RECORD_KEY, null, """{"schemaVersion":999}""".toByteArray())) + var reads = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream { + if (++reads == 3) file.writeBytes(envelope) + return SystemRecordFileOperations.read(file) + } + } + val racing = SavedComputerStore(ProtectedRecordStore(temporary.root, RecordCipher { key }, io)) + assertFalse(racing.discardUnreadable()) + assertEquals(valid, store().load()) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/SessionListingTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/SessionListingTest.kt new file mode 100644 index 00000000..c29231f9 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/SessionListingTest.kt @@ -0,0 +1,105 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.chat.AgentSummary +import app.bighelp.hermes.chat.ArchiveState +import app.bighelp.hermes.chat.CatalogState +import app.bighelp.hermes.chat.ConversationIdentity +import app.bighelp.hermes.chat.ConversationPhase +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.PromptContent +import app.bighelp.hermes.chat.PromptState +import app.bighelp.hermes.chat.SessionSummary +import java.time.ZoneOffset +import java.util.Locale +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class SessionListingTest { + private fun agent(id: String, name: String = id) = AgentSummary(id, name, null, JsonObject(emptyMap())) + private fun session( + profile: String, anchor: String, title: String, preview: String = "", last: Double? = null, + pinned: Boolean = false, archive: ArchiveState = ArchiveState.None, registryOnly: Boolean = false, bot: Boolean = false, + ) = SessionSummary( + ConversationRef(profile, anchor), profile, anchor, title, preview, null, last, 1, "bighelp", null, pinned, archive, + null, null, bot, registryOnly, + ) + private fun state(ref: ConversationRef, running: Boolean = false, draft: String = "", prompts: List = emptyList()) = + ConversationState(ref, "t", ConversationIdentity(ref, ref.anchor), ConversationPhase.Ready, running = running, draft = draft, prompts = prompts) + private val approval = { ref: ConversationRef -> + PromptState("p", ref, "w", "approval", null, 0, PromptContent.Approval("ls", null, null, emptyList())) + } + + private val catalog = CatalogState( + agents = listOf(agent("default", "Scout"), agent("moss", "Moss")), + sessions = listOf( + session("default", "a", "Lake weekend", "pack the tent", last = 100.0), + session("moss", "b", "Router advice", "wifi six", last = 300.0), + session("default", "c", "Pinned note", last = 50.0, pinned = true), + session("default", "d", "Old archived", last = 400.0, archive = ArchiveState.Deliberate), + session("moss", "e", "Swept by idle", last = 10.0, archive = ArchiveState.Automatic), + ), + ) + + @Test fun pinnedFirstThenNewestActivityAndDeliberatelyArchivedChatsAreNotListed() { + val rows = SessionListing.rows(catalog, emptyMap(), "") + assertEquals(listOf("Pinned note", "Router advice", "Lake weekend", "Swept by idle"), rows.map { it.title }) + assertEquals("Moss", rows[1].agentName) + } + + @Test fun searchMatchesTitleAgentNameAndPreviewIgnoringCase() { + assertEquals(listOf("Router advice"), SessionListing.rows(catalog, emptyMap(), "ROUTER").map { it.title }) + assertEquals(listOf("Router advice", "Swept by idle"), SessionListing.rows(catalog, emptyMap(), "moss").map { it.title }) + assertEquals(listOf("Lake weekend"), SessionListing.rows(catalog, emptyMap(), "tent").map { it.title }) + assertTrue(SessionListing.rows(catalog, emptyMap(), "nothing like this").isEmpty()) + } + + @Test fun aRegistryOnlyBotChatKeepsItsHonestEmptyFieldsInsteadOfAnInventedTitleOrTime() { + val bot = CatalogState(agents = listOf(agent("default", "Scout")), sessions = listOf(session("default", "reg", "", registryOnly = true, bot = true))) + val row = SessionListing.rows(bot, emptyMap(), "").single() + assertEquals("Bot Chat", row.title) + assertEquals("", row.preview) + assertEquals(null, row.lastActiveEpochSeconds) + assertTrue(row.isBotChat) + } + + @Test fun statusAndDraftComeOnlyFromTheRetainedConversation() { + val working = ConversationRef("moss", "b") + val needs = ConversationRef("default", "a") + val rows = SessionListing.rows( + catalog, + mapOf(working to state(working, running = true), needs to state(needs, draft = "half a thought", prompts = listOf(approval(needs)))), + "", + ) + assertEquals(RowStatus.Working, rows.first { it.title == "Router advice" }.status) + val lake = rows.first { it.title == "Lake weekend" } + assertEquals("A question for you comes first, then the draft", RowStatus.NeedsYou, lake.status) + assertEquals("Draft: half a thought", lake.preview) + assertEquals(RowStatus.Idle, rows.first { it.title == "Pinned note" }.status) + } + + @Test fun anAgentWithoutANameShowsItsId() { + val unnamed = CatalogState(agents = emptyList(), sessions = listOf(session("ghost", "x", "Hello"))) + assertEquals("ghost", SessionListing.rows(unnamed, emptyMap(), "").single().agentName) + } + + @Test fun relativeTimeIsShortAndNeverInventedForAMissingTime() { + val now = 1_700_000_000_000L + val at = { secondsAgo: Long -> now / 1000.0 - secondsAgo } + val format = { seconds: Double? -> SessionListing.relativeTime(seconds, now, ZoneOffset.UTC, Locale.US) } + assertEquals("", format(null)) + assertEquals("now", format(at(20))) + assertEquals("5 min", format(at(300))) + assertEquals("3 h", format(at(3 * 3600 + 10))) + assertEquals("2 d", format(at(2 * 86_400 + 10))) + assertEquals("Oct 1", SessionListing.relativeTime(1_696_150_000.0, now, ZoneOffset.UTC, Locale.US)) + assertEquals("A time in the future is not shown as negative", "now", format(at(-500))) + } + + @Test fun aChatThatTheHostListsTwiceShowsOnce() { + val twice = CatalogState(agents = listOf(agent("default")), sessions = listOf(session("default", "a", "Same chat"), session("default", "a", "Same chat", registryOnly = true))) + assertEquals(1, SessionListing.rows(twice, emptyMap(), "").size) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/live/TranscriptRowsTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/TranscriptRowsTest.kt new file mode 100644 index 00000000..039245c5 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/TranscriptRowsTest.kt @@ -0,0 +1,98 @@ +package app.bighelp.android.live + +import app.bighelp.hermes.chat.ActivityItem +import app.bighelp.hermes.chat.ActivityKind +import app.bighelp.hermes.chat.ActivityLifecycle +import app.bighelp.hermes.chat.ConversationIdentity +import app.bighelp.hermes.chat.ConversationPhase +import app.bighelp.hermes.chat.ConversationRef +import app.bighelp.hermes.chat.ConversationState +import app.bighelp.hermes.chat.ItemOrigin +import app.bighelp.hermes.chat.MessageItem +import app.bighelp.hermes.chat.MessageRole +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TranscriptRowsTest { + private val ref = ConversationRef("default", "anchor") + private fun message(id: String, role: MessageRole, text: String, origin: ItemOrigin = ItemOrigin.Saved, rowId: Long? = null, + complete: Boolean = true, command: Boolean = false, unsupported: Boolean = false) = + MessageItem(id, role, role.name.lowercase(), text, origin, rowId, complete = complete, isCommandResult = command, hasUnsupportedContent = unsupported) + private fun state(vararg items: app.bighelp.hermes.chat.TranscriptItem, running: Boolean = false, status: String? = null, stop: Boolean = false) = + ConversationState(ref, "t", ConversationIdentity(ref, "anchor"), ConversationPhase.Ready, items.toList(), running = running, status = status, stopRequested = stop) + + @Test fun userAndAssistantMessagesKeepTheirOrderAndIds() { + val rows = TranscriptRows.rows(state(message("a", MessageRole.User, "hi"), message("b", MessageRole.Assistant, "hello"))) + assertEquals(listOf("a", "b"), rows.map { it.key }) + assertTrue(rows.all { it is ChatRow.Message }) + } + + @Test fun anEmptyFinishedMessageIsNotARowButOneWithUnsupportedContentIs() { + val rows = TranscriptRows.rows(state( + message("a", MessageRole.Assistant, ""), + message("b", MessageRole.Assistant, "", unsupported = true), + message("c", MessageRole.Assistant, "", complete = false), + )) + assertEquals(listOf("b"), rows.map { it.key }) + } + + @Test fun onlySavedMessagesWithAHostRowIdCanBeBranched() { + val rows = TranscriptRows.rows(state( + message("a", MessageRole.User, "saved", rowId = 7), + message("b", MessageRole.Assistant, "live", origin = ItemOrigin.Live), + message("c", MessageRole.User, "local", origin = ItemOrigin.Local), + message("d", MessageRole.System, "note", rowId = 9), + )).filterIsInstance() + assertEquals(listOf(true, false, false), rows.map { it.canBranch }) + } + + @Test fun systemNotesAndCommandOutputAreNotesNotBubbles() { + val rows = TranscriptRows.rows(state(message("a", MessageRole.System, "Switched model"), message("b", MessageRole.Assistant, "output", command = true))) + assertTrue(rows.all { it is ChatRow.Note }) + assertEquals(listOf("Switched model", "output"), rows.map { (it as ChatRow.Note).text }) + } + + @Test fun toolsAndReasoningBecomeActivityRowsAndANoticeBecomesANote() { + val tool = ActivityItem("t1", ActivityKind.Tool, "read_file", "notes.txt", ActivityLifecycle.Running, origin = ItemOrigin.Live) + val thinking = ActivityItem("t2", ActivityKind.Reasoning, "Thinking", "step", ActivityLifecycle.Recorded, origin = ItemOrigin.Live) + val notice = ActivityItem("t3", ActivityKind.Notice, "Context was compacted", null, ActivityLifecycle.Recorded, origin = ItemOrigin.Live) + val rows = TranscriptRows.rows(state(tool, thinking, notice)) + assertTrue(rows[0] is ChatRow.Activity && rows[1] is ChatRow.Activity) + assertEquals("Context was compacted", (rows[2] as ChatRow.Note).text) + } + + @Test fun theWorkingLabelIsTheHostsOwnStatusOrAPlainDefaultAndNothingWhileIdle() { + assertEquals(null, TranscriptRows.workingLabel(state())) + assertEquals("Working…", TranscriptRows.workingLabel(state(running = true))) + assertEquals("Running read_file", TranscriptRows.workingLabel(state(running = true, status = "Running read_file"))) + assertEquals("Stopping…", TranscriptRows.workingLabel(state(running = true, status = "Running read_file", stop = true))) + assertFalse(TranscriptRows.workingLabel(state(running = true))!!.isBlank()) + } + + @Test fun edgeRowsAddAnEarlierHistoryRowAtTheTopAndTheWorkingLineAtTheEnd() { + val base = state(message("a", MessageRole.User, "hi")) + assertEquals(listOf("a"), TranscriptRows.withEdges(base).map { it.key }) + + val more = base.copy(history = app.bighelp.hermes.chat.HistoryState(hasOlder = true), running = true, status = "Running read_file") + val rows = TranscriptRows.withEdges(more) + assertEquals(listOf("history", "a", "working"), rows.map { it.key }) + assertEquals(false, (rows.first() as ChatRow.History).loading) + assertEquals("Running read_file", (rows.last() as ChatRow.Working).label) + + val loading = more.copy(history = app.bighelp.hermes.chat.HistoryState(hasOlder = true, loadingOlder = true)) + assertEquals(true, (TranscriptRows.withEdges(loading).first() as ChatRow.History).loading) + } + + @Test fun aRepeatedItemIdNeverReachesTheListBecauseALazyListCrashesOnADuplicateKey() { + val rows = TranscriptRows.withEdges(state( + message("same", MessageRole.User, "first"), + message("same", MessageRole.Assistant, "second"), + message("working", MessageRole.Assistant, "an id that looks like the working line"), + running = true, + )) + assertEquals(rows.map { it.key }.distinct(), rows.map { it.key }) + assertEquals("first", (rows.first { it.key == "same" } as ChatRow.Message).item.text) + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/storage/AndroidChatStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/storage/AndroidChatStoreTest.kt new file mode 100644 index 00000000..56f29beb --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/AndroidChatStoreTest.kt @@ -0,0 +1,398 @@ +package app.bighelp.android.storage + +import app.bighelp.hermes.chat.ChatStoreException +import app.bighelp.hermes.chat.ConversationScope +import app.bighelp.hermes.chat.DraftRecord +import app.bighelp.hermes.chat.HostScope +import app.bighelp.hermes.chat.JournalEntry +import app.bighelp.hermes.chat.RecordKey +import app.bighelp.hermes.chat.RecordKind +import app.bighelp.hermes.chat.StoreOp +import java.io.File +import java.io.IOException +import java.util.UUID +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +/** + * The adapter behind the chat repository's durable writes. "Process death" is a second store over the same + * directory, with the log cut or damaged first, so every case proves what a restart would really see. + */ +class AndroidChatStoreTest { + @get:Rule val temporary = TemporaryFolder() + private val directory get() = File(temporary.root, "chat") + private val host = HostScope("5c3f4f06-2a41-4f6a-9d38-0a54d3a3a111", "http://127.0.0.1:9", "dashboard-session") + private val scope = ConversationScope(host, "research", "anchor-1") + + private fun open(files: ChatStoreFiles = SystemChatStoreFiles, tuning: ChatStoreTuning = ChatStoreTuning()) = + AndroidChatStore(directory, Dispatchers.Unconfined, files, tuning) + + private fun draft(text: String, at: ConversationScope = scope) = + StoreOp.Put(RecordKey.draft(at), DraftRecord(at, text, updatedAtMillis = 5).encode()) + + private fun journal(entryId: String, text: String = "hi") = + StoreOp.Put(RecordKey.journal(scope, entryId), JournalEntry(entryId, scope, "prompt.submit", text, text, emptyList(), 7).encode()) + + private fun draftText(store: AndroidChatStore, at: ConversationScope = scope): String? = + runBlocking { store.read(RecordKey.draft(at))?.let { DraftRecord.decode(at, it).text } } + + private val log get() = File(directory, AndroidChatStore.LOG_NAME) + + // ---- the contract the repository relies on + + @Test fun aCommitIsAllOrNothingAndSurvivesARestart() = runBlocking { + val store = open() + val entryId = UUID.randomUUID().toString() + store.commit(listOf(draft("typing"), journal(entryId))) + + val files = FaultyFiles().apply { appendFailsAfterBytes = 40 } + val failing = open(files) + val failure = runCatching { failing.commit(listOf(draft("changed"), StoreOp.Delete(RecordKey.journal(scope, entryId)))) }.exceptionOrNull() + assertEquals(ChatStoreException.Kind.Unavailable, (failure as ChatStoreException).kind) + assertEquals("typing", draftText(failing)) + assertNotNull(failing.read(RecordKey.journal(scope, entryId))) + + val reopened = open() + assertEquals("typing", draftText(reopened)) + val keys = reopened.keys(host, RecordKind.Journal, "research", "anchor-1") + assertEquals(listOf(entryId), keys.map { it.entry }) + assertEquals("hi", JournalEntry.decode(scope, entryId, reopened.read(keys.single())!!).composerText) + } + + @Test fun everyDurableKindAcceptsExactlyItsLimitAndRefusesOneByteMoreWithoutApplyingAnythingElse() = runBlocking { + val store = open() + store.commit(listOf(draft("keep"))) + val entry = UUID.randomUUID().toString() + val keys = listOf( + RecordKey.draft(scope), RecordKey.journal(scope, entry), RecordKey.creation(host, "research"), RecordKey.identity(scope), + ) + for (key in keys) { + val limit = key.kind.maximumBytes + store.commit(listOf(StoreOp.Put(key, ByteArray(limit) { 7 }))) + assertEquals("${key.kind} holds exactly its limit", limit, store.read(key)!!.size) + val other = ConversationScope(host, "research", "other-${key.kind}") + val failure = runCatching { + store.commit(listOf(draft("never applied", other), StoreOp.Put(key, ByteArray(limit + 1)))) + }.exceptionOrNull() + assertEquals(ChatStoreException.Kind.TooLarge, (failure as ChatStoreException).kind) + assertNull("The earlier operation of a refused transaction is not applied", store.read(RecordKey.draft(other))) + assertEquals("${key.kind} keeps its last good value", limit, store.read(key)!!.size) + } + // The credential record cap (64 KiB) is not reused: records far above it are normal here. + assertTrue(RecordKind.Journal.maximumBytes > 65_536) + val reopened = open() + for (key in keys) assertEquals(key.kind.maximumBytes, reopened.read(key)!!.size) + } + + @Test fun aCacheKindIsNotADurableCommitAndADurableKindIsNotACacheWrite() = runBlocking { + val store = open() + assertThrows(IllegalArgumentException::class.java) { runBlocking { store.commit(listOf(StoreOp.Put(RecordKey.catalog(host), ByteArray(1)))) } } + assertThrows(IllegalArgumentException::class.java) { runBlocking { store.putCache(RecordKey.draft(scope), ByteArray(1)) } } + assertThrows(IllegalArgumentException::class.java) { runBlocking { store.deleteCache(RecordKey.draft(scope)) } } + Unit + } + + @Test fun everyRecordIsScopedByComputerEndpointPrincipalProfileAndAnchor() = runBlocking { + val store = open() + val variants = listOf( + scope, + ConversationScope(host.copy(computerId = UUID.randomUUID().toString()), "research", "anchor-1"), + ConversationScope(host.copy(endpoint = "https://other.example"), "research", "anchor-1"), + ConversationScope(host.copy(principal = "basic:someone-else"), "research", "anchor-1"), + ConversationScope(host, "other-profile", "anchor-1"), + ConversationScope(host, "research", "anchor-2"), + ) + variants.forEachIndexed { index, each -> store.commit(listOf(draft("text $index", each))) } + val reopened = open() + variants.forEachIndexed { index, each -> assertEquals("text $index", draftText(reopened, each)) } + assertEquals(1, reopened.keys(host, RecordKind.Draft, "research", "anchor-1").size) + assertEquals(setOf("anchor-1", "anchor-2"), reopened.keys(host, RecordKind.Draft, "research").map { it.anchor }.toSet()) + // Only the variants that share this exact computer, endpoint and principal are listed for it. + assertEquals(3, reopened.keys(host, RecordKind.Draft).size) + } + + // ---- atomicity and restart + + @Test fun aRestartAtEveryByteOfAnInterruptedCommitSeesTheOldStateOrTheWholeNewOne() = runBlocking { + val entry = UUID.randomUUID().toString() + val first = open() + first.commit(listOf(draft("one"))) + first.commit(listOf(journal(entry))) + val before = log.readBytes() + val other = ConversationScope(host, "research", "anchor-9") + first.commit(listOf(draft("two"), draft("elsewhere", other), StoreOp.Delete(RecordKey.journal(scope, entry)))) + val after = log.readBytes() + assertTrue(after.size > before.size) + for (cut in before.size..after.size) { + log.writeBytes(after.copyOf(cut)) + val store = open() + if (cut == after.size) { + assertEquals("two", draftText(store)) + assertEquals("elsewhere", draftText(store, other)) + assertNull(store.read(RecordKey.journal(scope, entry))) + } else { + assertEquals("cut at $cut", "one", draftText(store)) + assertNull("cut at $cut", store.read(RecordKey.draft(other))) + assertNotNull("cut at $cut", store.read(RecordKey.journal(scope, entry))) + // The torn tail is gone, so the next commit appends to a clean log and survives another restart. + store.commit(listOf(draft("later"))) + assertEquals("later", draftText(open())) + } + } + } + + @Test fun aZeroFilledTailLeftByACrashIsATornWriteNotCorruption() = runBlocking { + val store = open() + store.commit(listOf(draft("kept"))) + log.appendBytes(ByteArray(300)) + assertEquals("kept", draftText(open())) + } + + @Test fun aFailedCommitLeavesNothingAndTheNextCommitWorksAfterEveryKindOfFault() = runBlocking { + val files = FaultyFiles() + val store = open(files) + store.commit(listOf(draft("base"))) + val size = log.length() + + files.appendFailsAfterBytes = 0 + assertThrows(ChatStoreException::class.java) { runBlocking { store.commit(listOf(draft("a"))) } } + files.appendFailsAfterBytes = 25 + assertThrows(ChatStoreException::class.java) { runBlocking { store.commit(listOf(draft("b"))) } } + files.appendFailsAfterBytes = null + files.syncFails = true + assertThrows(ChatStoreException::class.java) { runBlocking { store.commit(listOf(draft("c"))) } } + files.syncFails = false + + assertEquals("base", draftText(store)) + assertEquals("A refused write leaves no bytes behind", size, log.length()) + store.commit(listOf(draft("d"))) + assertEquals("d", draftText(store)) + assertEquals("d", draftText(open())) + } + + @Test fun ifTheFailedWriteCannotBeRemovedNothingElseIsAppendedUntilItIs() = runBlocking { + val files = FaultyFiles() + val store = open(files) + store.commit(listOf(draft("base"))) + files.appendFailsAfterBytes = 30 + files.truncateFails = true + assertThrows(ChatStoreException::class.java) { runBlocking { store.commit(listOf(draft("x"))) } } + // The garbage tail is still there; appending after it would hide every later commit from a restart. + assertThrows(ChatStoreException::class.java) { runBlocking { store.commit(listOf(draft("y"))) } } + assertEquals("base", draftText(open())) + files.appendFailsAfterBytes = null + files.truncateFails = false + store.commit(listOf(draft("z"))) + assertEquals("z", draftText(open())) + } + + @Test fun aFullDiskIsReportedAsQuota() = runBlocking { + val files = FaultyFiles().apply { appendFailsAfterBytes = 0; failureMessage = "No space left on device" } + val failure = runCatching { open(files).commit(listOf(draft("x"))) }.exceptionOrNull() as ChatStoreException + assertEquals(ChatStoreException.Kind.QuotaExceeded, failure.kind) + } + + @Test fun concurrentCommitsAreAllAppliedAndNoneTornOrInterleaved() = runBlocking { + val store = open() + val scopes = (1..40).map { ConversationScope(host, "research", "anchor-$it") } + scopes.map { each -> async(Dispatchers.IO) { store.commit(listOf(draft("text ${each.anchor}", each))) } }.awaitAll() + val reopened = open() + for (each in scopes) assertEquals("text ${each.anchor}", draftText(reopened, each)) + } + + // ---- damage is reported, never silently dropped + + @Test fun damageInTheMiddleOfTheLogFailsClosedUntilAnExplicitReset() = runBlocking { + val store = open() + store.commit(listOf(draft("first"))) + val firstEnd = log.length() + store.commit(listOf(draft("second"))) + val bytes = log.readBytes() + bytes[(firstEnd - 20).toInt()] = (bytes[(firstEnd - 20).toInt()] + 1).toByte() + log.writeBytes(bytes) + + val damaged = open() + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { damaged.read(RecordKey.draft(scope)) }.exceptionOrNull() as ChatStoreException).kind) + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { damaged.commit(listOf(draft("x"))) }.exceptionOrNull() as ChatStoreException).kind) + // The caches do not depend on the log, and a cache never throws. + damaged.putCache(RecordKey.catalog(host), ByteArray(10)) + assertEquals(10, damaged.read(RecordKey.catalog(host))!!.size) + + assertTrue(damaged.discardUnreadable()) + assertNull(damaged.read(RecordKey.draft(scope))) + damaged.commit(listOf(draft("fresh"))) + assertEquals("fresh", draftText(open())) + } + + @Test fun aRecordThatChangesOnDiskAfterItWasIndexedIsCorruptNotReturned() = runBlocking { + val store = open() + store.commit(listOf(draft("a reasonably long draft that is easy to find in the file"))) + val bytes = log.readBytes() + val at = String(bytes, Charsets.ISO_8859_1).indexOf("easy to find") + bytes[at] = (bytes[at] + 1).toByte() + log.writeBytes(bytes) + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { store.read(RecordKey.draft(scope)) }.exceptionOrNull() as ChatStoreException).kind) + } + + @Test fun aFileThatIsNotOurLogIsNeverOverwritten() = runBlocking { + directory.mkdirs() + log.writeBytes("not a bighelp log, keep out of it".toByteArray()) + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { open().read(RecordKey.draft(scope)) }.exceptionOrNull() as ChatStoreException).kind) + assertEquals("not a bighelp log, keep out of it", log.readText()) + } + + // ---- compaction + + @Test fun repeatedDraftEditsCompactTheLogWithoutChangingWhatIsStored() = runBlocking { + val tuning = ChatStoreTuning(compactionMinimumGarbage = 20_000) + val store = open(tuning = tuning) + val entry = UUID.randomUUID().toString() + store.commit(listOf(journal(entry, "an uncertain send that must outlive every compaction"))) + repeat(200) { store.commit(listOf(draft("edit $it " + "x".repeat(400)))) } + assertTrue("The log stayed bounded: ${log.length()}", log.length() < 60_000) + assertEquals("edit 199 " + "x".repeat(400), draftText(store)) + val reopened = open(tuning = tuning) + assertEquals("edit 199 " + "x".repeat(400), draftText(reopened)) + assertEquals("an uncertain send that must outlive every compaction", + JournalEntry.decode(scope, entry, reopened.read(RecordKey.journal(scope, entry))!!).composerText) + reopened.commit(listOf(draft("after compaction"))) + assertEquals("after compaction", draftText(open(tuning = tuning))) + } + + @Test fun aFailedCompactionKeepsTheOldLogAndLaterCommitsStillWork() = runBlocking { + val files = FaultyFiles().apply { replaceFails = true } + val tuning = ChatStoreTuning(compactionMinimumGarbage = 5_000) + val store = open(files, tuning) + repeat(60) { store.commit(listOf(draft("edit $it " + "y".repeat(300)))) } + assertEquals("edit 59 " + "y".repeat(300), draftText(open(tuning = tuning))) + assertFalse("A failed compaction leaves no temporary file", File(directory, AndroidChatStore.COMPACT_NAME).exists()) + files.replaceFails = false + repeat(30) { store.commit(listOf(draft("again $it " + "y".repeat(300)))) } + assertEquals("again 29 " + "y".repeat(300), draftText(open(tuning = tuning))) + } + + @Test fun aHalfWrittenCompactionLeftByADeadProcessIsIgnored() = runBlocking { + val store = open() + store.commit(listOf(draft("live"))) + File(directory, AndroidChatStore.COMPACT_NAME).writeBytes(ByteArray(100) { 9 }) + assertEquals("live", draftText(open())) + assertFalse(File(directory, AndroidChatStore.COMPACT_NAME).exists()) + } + + // ---- caches + + @Test fun cachesNeverTouchDurableRecordsAndTheOldestAreEvictedFirst() = runBlocking { + val store = open(tuning = ChatStoreTuning(cacheBudgetBytes = 10_000)) + val entry = UUID.randomUUID().toString() + store.commit(listOf(draft("unsent words"), journal(entry))) + val scopes = (1..5).map { ConversationScope(host, "research", "cached-$it") } + for ((index, each) in scopes.withIndex()) { + store.putCache(RecordKey.history(each), ByteArray(3_000) { index.toByte() }) + File(directory, "cache").listFiles()!!.maxByOrNull { it.lastModified() }!!.setLastModified(1_000_000L + index * 1_000) + } + val surviving = scopes.filter { store.read(RecordKey.history(it)) != null } + assertTrue("The newest are kept: $surviving", surviving.contains(scopes.last())) + assertFalse("The oldest are evicted first", surviving.contains(scopes.first())) + assertEquals("unsent words", draftText(store)) + assertNotNull(store.read(RecordKey.journal(scope, entry))) + } + + @Test fun aCacheWriteOverItsLimitIsDroppedQuietlyAndTheExactLimitIsKept() = runBlocking { + val store = open() + store.putCache(RecordKey.history(scope), ByteArray(RecordKind.HistoryCache.maximumBytes + 1)) + assertNull(store.read(RecordKey.history(scope))) + val exact = ByteArray(RecordKind.CatalogCache.maximumBytes) { (it % 251).toByte() } + store.putCache(RecordKey.catalog(host), exact) + assertArrayEquals(exact, open().read(RecordKey.catalog(host))) + } + + @Test fun aDamagedCacheFileIsDroppedNotReportedAsCorruptDraftsAreDifferent() = runBlocking { + val store = open() + store.putCache(RecordKey.history(scope), ByteArray(500) { 3 }) + val file = File(directory, "cache").listFiles()!!.single() + val bytes = file.readBytes() + bytes[bytes.size - 5] = (bytes[bytes.size - 5] + 1).toByte() + file.writeBytes(bytes) + assertNull(store.read(RecordKey.history(scope))) + assertFalse("The damaged cache file is removed", file.exists()) + } + + @Test fun aCacheNeverThrowsEvenWhenItsFolderCannotBeMade() = runBlocking { + directory.mkdirs() + File(directory, "cache").writeText("a file where the folder should be") + val store = open() + store.putCache(RecordKey.history(scope), ByteArray(10)) + store.deleteCache(RecordKey.history(scope)) + assertNull(store.read(RecordKey.history(scope))) + } + + @Test fun cacheKeysSurviveARestartForTheirComputer() = runBlocking { + val store = open() + store.putCache(RecordKey.history(scope), ByteArray(10)) + store.putCache(RecordKey.catalog(host), ByteArray(10)) + val reopened = open() + assertEquals(listOf("anchor-1"), reopened.keys(host, RecordKind.HistoryCache).map { it.anchor }) + assertEquals(1, reopened.keys(host, RecordKind.CatalogCache).size) + } + + // ---- removing a computer + + @Test fun removingAComputerDeletesItsDurableAndCachedRecordsAndNobodyElses() = runBlocking { + val store = open() + val gone = host + val kept = HostScope(UUID.randomUUID().toString(), "https://example.test", "dashboard-session") + val keptScope = ConversationScope(kept, "research", "anchor-1") + val entry = UUID.randomUUID().toString() + store.commit(listOf(draft("mine"), journal(entry), draft("theirs", keptScope))) + store.putCache(RecordKey.history(scope), ByteArray(10)) + store.putCache(RecordKey.history(keptScope), ByteArray(10)) + store.putCache(RecordKey.catalog(gone), ByteArray(10)) + + store.purge(gone.computerId) + + val reopened = open() + assertNull(draftText(reopened)) + assertNull(reopened.read(RecordKey.journal(scope, entry))) + assertNull(reopened.read(RecordKey.history(scope))) + assertNull(reopened.read(RecordKey.catalog(gone))) + assertEquals("theirs", draftText(reopened, keptScope)) + assertNotNull(reopened.read(RecordKey.history(keptScope))) + } +} + +/** Real files with scripted failures: a short write, a failed flush, a failed truncate or a failed rename. */ +internal class FaultyFiles : ChatStoreFiles { + var appendFailsAfterBytes: Int? = null + var syncFails = false + var truncateFails = false + var replaceFails = false + var failureMessage = "synthetic disk failure" + + override fun open(file: File): ChatLogFile { + val inner = SystemChatStoreFiles.open(file) + return object : ChatLogFile by inner { + override fun append(bytes: ByteArray) { + val limit = appendFailsAfterBytes ?: return inner.append(bytes) + if (limit > 0) inner.append(bytes.copyOf(minOf(limit, bytes.size))) + throw IOException(failureMessage) + } + override fun sync() { if (syncFails) throw IOException(failureMessage) else inner.sync() } + override fun truncate(size: Long) { if (truncateFails) throw IOException(failureMessage) else inner.truncate(size) } + } + } + + override fun replace(from: File, to: File) { if (replaceFails) throw IOException(failureMessage) else SystemChatStoreFiles.replace(from, to) } + override fun syncDirectory(directory: File) = SystemChatStoreFiles.syncDirectory(directory) +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt new file mode 100644 index 00000000..6d8fc053 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -0,0 +1,301 @@ +package app.bighelp.android.storage + +import java.nio.file.Files +import java.nio.file.Path +import java.io.File +import java.io.FileOutputStream +import java.io.FilterInputStream +import java.io.IOException +import java.io.InputStream +import java.security.ProviderException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import javax.crypto.KeyGenerator +import org.junit.Assert.* +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class ProtectedRecordStoreTest { + @get:Rule val temporary = TemporaryFolder() + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + private val binding = "https://example.test/hermes|basic|synthetic-person" + private fun store() = ProtectedRecordStore(temporary.root, RecordCipher { key }) + private fun bytes(value: String) = value.toByteArray(Charsets.UTF_8) + + @Test fun savedCredentialSurvivesReopeningWithoutPlaintextOnDisk() { + val value = bytes("synthetic-access-token and synthetic-refresh-token") + assertTrue(store().compareAndSet(binding, null, value)) + assertArrayEquals(value, store().read(binding)) + val saved = temporary.root.listFiles()!!.single { it.extension == "sealed" }.readBytes() + assertFalse(saved.toString(Charsets.ISO_8859_1).contains("synthetic-access-token")) + assertFalse(saved.toString(Charsets.ISO_8859_1).contains("synthetic-refresh-token")) + } + + @Test fun oldRefreshCannotOverwriteOrEraseANewerSignIn() { + val first = bytes("refresh-1") + val rotated = bytes("refresh-2") + val newer = bytes("newer-sign-in") + val vault = store() + assertTrue(vault.compareAndSet(binding, null, first)) + assertTrue(vault.compareAndSet(binding, first, rotated)) + assertTrue(store().compareAndSet(binding, rotated, newer)) + assertFalse(vault.compareAndSet(binding, rotated, bytes("stale-answer"))) + assertFalse(vault.compareAndSet(binding, rotated, null)) + assertArrayEquals(newer, store().read(binding)) + } + + @Test fun concurrentAuthenticatorsHaveOnlyOneReplacementWinner() { + val initial = bytes("initial") + assertTrue(store().compareAndSet(binding, null, initial)) + val start = CountDownLatch(1) + val executor = Executors.newFixedThreadPool(2) + try { + val attempts = listOf("answer-a", "answer-b").map { answer -> + executor.submit { + start.await() + store().compareAndSet(binding, initial, bytes(answer)) + } + } + start.countDown() + assertEquals(1, attempts.count { it.get(5, TimeUnit.SECONDS) }) + assertTrue(store().read(binding)!!.toString(Charsets.UTF_8) in setOf("answer-a", "answer-b")) + } finally { + executor.shutdownNow() + } + } + + @Test fun ciphertextCannotBeMovedToAnotherAuthority() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("first"))) + val first = temporary.root.listFiles()!!.single { it.extension == "sealed" } + val other = "https://other.example.test|basic|synthetic-person" + assertTrue(vault.compareAndSet(other, null, bytes("second"))) + val second = temporary.root.listFiles()!!.single { it.extension == "sealed" && it != first } + Files.copy(first.toPath(), second.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING) + refuses(StorageProblem.CorruptRecord) { vault.read(other) } + assertArrayEquals(bytes("first"), vault.read(binding)) + } + + @Test fun modifiedOrTruncatedRecordRequiresRecoveryInsteadOfBecomingSignedOut() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("secret"))) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" } + val original = file.readBytes() + file.writeBytes(original.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() }) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + file.writeBytes(original.copyOf(12)) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + file.writeBytes(original.copyOf(original.size - 1)) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + file.writeBytes(original.copyOf().also { it[8] = (it[8].toInt() xor 1).toByte() }) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + } + + @Test fun wrongDeviceKeyCannotReadARecord() { + assertTrue(store().compareAndSet(binding, null, bytes("secret"))) + val anotherKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + val anotherDevice = ProtectedRecordStore(temporary.root, RecordCipher { anotherKey }) + refuses(StorageProblem.CorruptRecord) { anotherDevice.read(binding) } + } + + @Test fun sizeLimitIsInBytesAndRefusalPreservesThePriorRecord() { + val limit = ByteArray(65_536) { 0x61 } + val vault = store() + assertTrue(vault.compareAndSet(binding, null, limit)) + assertArrayEquals(limit, store().read(binding)) + refuses(StorageProblem.RecordTooLarge) { + vault.compareAndSet(binding, limit, ByteArray(65_537)) + } + assertArrayEquals(limit, store().read(binding)) + } + + @Test fun anOversizedFileIsRejectedBeforeDecode() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("secret"))) + temporary.root.listFiles()!!.single { it.extension == "sealed" }.writeBytes(ByteArray(70_000)) + refuses(StorageProblem.RecordTooLarge) { vault.read(binding) } + } + + @Test fun successfulLocalSignOutRemovesOnlyTheExpectedRecord() { + val vault = store() + val value = bytes("saved") + assertNull(vault.read(binding)) + assertTrue(vault.compareAndSet(binding, null, value)) + assertTrue(vault.compareAndSet(binding, value, null)) + assertNull(store().read(binding)) + assertFalse(vault.compareAndSet(binding, value, bytes("late-refresh"))) + } + + @Test fun encryptingTheSameRecordUsesANewNonce() { + val cipher = RecordCipher { key } + val plain = bytes("same-token") + val first = cipher.encrypt(binding, plain) + val second = cipher.encrypt(binding, plain) + assertFalse(first.contentEquals(second)) + assertArrayEquals(plain, cipher.decrypt(binding, first)) + assertArrayEquals(plain, cipher.decrypt(binding, second)) + } + + @Test fun failureToEncryptAReplacementKeepsThePreviousCredential() { + val value = bytes("saved-sign-in") + assertTrue(store().compareAndSet(binding, null, value)) + val calls = AtomicInteger() + val failing = ProtectedRecordStore(temporary.root, RecordCipher { + if (calls.getAndIncrement() == 0) key else throw IllegalStateException("device key unavailable") + }) + refuses(StorageProblem.KeyUnavailable) { failing.compareAndSet(binding, value, bytes("new-token")) } + assertArrayEquals(value, store().read(binding)) + assertFalse(temporary.root.listFiles()!!.any { it.extension == "pending" }) + } + + @Test fun unavailableDiskDoesNotLookLikeAnAbsentSignIn() { + val notDirectory = temporary.newFile("not-a-directory") + val vault = ProtectedRecordStore(notDirectory, RecordCipher { key }) + refuses(StorageProblem.DiskUnavailable) { vault.read(binding) } + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, null, bytes("value")) } + } + + @Test fun distinctOpaquePrincipalStringsHaveSeparateRecords() { + val first = "https://example.test|basic|caf\u00e9" + val second = "https://example.test|basic|cafe\u0301" + val vault = store() + assertTrue(vault.compareAndSet(first, null, bytes("one"))) + assertTrue(vault.compareAndSet(second, null, bytes("two"))) + assertArrayEquals(bytes("one"), vault.read(first)) + assertArrayEquals(bytes("two"), vault.read(second)) + } + + @Test fun aStatFailureIsNeverTreatedAsAnAbsentRecord() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("saved"))) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" }.toPath() + Files.delete(file) + Files.createSymbolicLink(file, file.fileName) + refuses(StorageProblem.DiskUnavailable) { vault.read(binding) } + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, null, bytes("replacement")) } + refuses(StorageProblem.DiskUnavailable) { vault.discardUnreadable(binding) } + assertTrue(Files.isSymbolicLink(file)) + } + + @Test fun readingWithAMissingDeviceKeyNeverCreatesAnotherKey() { + assertTrue(store().compareAndSet(binding, null, bytes("saved"))) + var created = false + val missing = object : RecordKeyProvider { + override fun existing() = null + override fun getOrCreate() = key.also { created = true } + } + val vault = ProtectedRecordStore(temporary.root, RecordCipher(missing)) + refuses(StorageProblem.KeyMissing) { vault.read(binding) } + assertFalse(created) + assertArrayEquals(bytes("saved"), store().read(binding)) + } + + @Test fun providerRuntimeFailuresAreTypedOnEncryptAndDecrypt() { + val provider = object : RecordKeyProvider { + override fun existing() = key + override fun getOrCreate() = key + } + val broken = RecordCipher(provider) { throw ProviderException("synthetic provider failure") } + refuses(StorageProblem.KeyUnavailable) { broken.encrypt(binding, bytes("secret")) } + val envelope = RecordCipher { key }.encrypt(binding, bytes("secret")) + refuses(StorageProblem.KeyUnavailable) { broken.decrypt(binding, envelope) } + } + + @Test fun unreadableRecordsCanBeExplicitlyDiscardedWithoutDeletingValidOnes() { + val vault = store() + assertFalse(vault.discardUnreadable(binding)) + assertTrue(vault.compareAndSet(binding, null, bytes("saved"))) + assertFalse(vault.discardUnreadable(binding)) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" } + file.writeBytes(byteArrayOf(1, 2, 3)) + assertTrue(vault.discardUnreadable(binding)) + assertNull(vault.read(binding)) + assertTrue(vault.compareAndSet(binding, null, bytes("new-sign-in"))) + } + + @Test fun aTransientKeyFailureCannotDiscardAnyRecord() { + assertTrue(store().compareAndSet(binding, null, bytes("saved"))) + val broken = ProtectedRecordStore(temporary.root, RecordCipher { throw ProviderException("unavailable") }) + refuses(StorageProblem.KeyUnavailable) { broken.discardUnreadable(binding) } + assertArrayEquals(bytes("saved"), store().read(binding)) + } + + @Test fun theReadBudgetStopsAnOversizedInputAfterOneExcessByte() { + assertTrue(store().compareAndSet(binding, null, bytes("saved"))) + var consumed = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream = object : FilterInputStream(ByteArray(70_000).inputStream()) { + override fun read(bytes: ByteArray, offset: Int, length: Int): Int = + super.read(bytes, offset, length).also { if (it > 0) consumed += it } + } + } + val vault = ProtectedRecordStore(temporary.root, RecordCipher { key }, io) + refuses(StorageProblem.RecordTooLarge) { vault.read(binding) } + assertEquals(RecordCipher.MAXIMUM_ENVELOPE_BYTES + 1, consumed) + } + + @Test fun partialWriteAndMoveFailureLeaveThePreviousRecordReadable() { + val original = bytes("saved") + assertTrue(store().compareAndSet(binding, null, original)) + val failures = listOf( + object : RecordFileOperations by SystemRecordFileOperations { + override fun write(file: File): FileOutputStream = object : FileOutputStream(file) { + override fun write(bytes: ByteArray) { + super.write(bytes, 0, minOf(8, bytes.size)) + throw IOException("synthetic interrupted write") + } + } + }, + object : RecordFileOperations by SystemRecordFileOperations { + override fun move(from: Path, to: Path) { throw IOException("synthetic failed move") } + }, + ) + for (io in failures) { + val vault = ProtectedRecordStore(temporary.root, RecordCipher { key }, io) + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, original, bytes("replacement")) } + assertArrayEquals(original, store().read(binding)) + assertFalse(temporary.root.listFiles()!!.any { it.extension == "pending" }) + } + } + + @Test fun malformedOpaqueKeysNeverCollapseToAQuestionMark() { + val vault = store() + assertTrue(vault.compareAndSet("?", null, bytes("valid"))) + refuses(StorageProblem.InvalidBinding) { vault.read("\ud800") } + refuses(StorageProblem.InvalidBinding) { vault.compareAndSet("\udc00", null, bytes("invalid")) } + assertArrayEquals(bytes("valid"), vault.read("?")) + } + + @Test fun directorySyncFailureCanFollowACommittedReplaceAndNeedsReadback() { + assumeTrue(System.getProperty("user.name") != "root") + assumeTrue(temporary.root.toPath().fileSystem.supportedFileAttributeViews().contains("posix")) + val vault = store() + val original = bytes("saved") + val next = bytes("rotated") + assertTrue(vault.compareAndSet(binding, null, original)) + val mode = Files.getPosixFilePermissions(temporary.root.toPath()) + try { + Files.setPosixFilePermissions( + temporary.root.toPath(), + java.nio.file.attribute.PosixFilePermissions.fromString("-wx------"), + ) + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, original, next) } + } finally { + Files.setPosixFilePermissions(temporary.root.toPath(), mode) + } + assertArrayEquals(next, vault.read(binding)) + } + + private fun refuses(problem: StorageProblem, action: () -> Unit) { + try { + action() + fail("Expected $problem") + } catch (failure: RecordStorageException) { + assertEquals(problem, failure.problem) + } + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 00000000..a50ae6d5 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + kotlin("jvm") version "2.2.21" apply false + id("com.android.application") version "8.13.2" apply false + kotlin("android") version "2.2.21" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.2.21" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 00000000..2430f7ad --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..9bbc975c Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..36e4933e --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=20f1b1176237254a6fc204d8434196fa11a4cfb387567519c61556e8710aed78 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 00000000..faf93008 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 00000000..9d21a218 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/hermes/build.gradle.kts b/android/hermes/build.gradle.kts new file mode 100644 index 00000000..95975f45 --- /dev/null +++ b/android/hermes/build.gradle.kts @@ -0,0 +1,31 @@ +plugins { + kotlin("jvm") +} +kotlin { + jvmToolchain(17) +} +dependencies { + // Public signatures expose JsonElement and coroutine types, so consumers see them. + api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") + // OkHttp carries the bounded HTTP only; no public signature mentions its types. + implementation("com.squareup.okhttp3:okhttp:4.12.0") + // The gateway WebSocket needs real inbound bounds and strict UTF-8, which OkHttp 4.12 cannot give (it assembles + // a whole message before delivering it and repairs bad UTF-8). Java-WebSocket checks a frame's declared length + // before allocating and caps the sum of fragments. Pinned; no extensions (no permessage-deflate) are configured. + implementation("org.java-websocket:Java-WebSocket:1.6.0") + // The library logs frames at trace level. Bind SLF4J to its no-op provider so frame and token data can never + // reach a log, whatever else is on an app's classpath at build time. (slf4j-api 2.0.13 arrives with the library.) + runtimeOnly("org.slf4j:slf4j-nop:2.0.13") + testImplementation("junit:junit:4.13.2") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2") + testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") + // Real certificates for the TLS negative/hostname tests. + testImplementation("com.squareup.okhttp3:okhttp-tls:4.12.0") +} +tasks.test { + val wireVectors = rootProject.file("../docs/hermes/vectors/wire.json") + // The tests read the shared vectors by path; declare the file so a content change reruns them. + inputs.file(wireVectors).withPropertyName("wireVectors").withPathSensitivity(PathSensitivity.NONE) + systemProperty("hermes.wireVectors", wireVectors.absolutePath) +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt new file mode 100644 index 00000000..8dbf0da0 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt @@ -0,0 +1,279 @@ +package app.bighelp.hermes + +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.security.MessageDigest +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.cancel +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout + +/** + * The device-local half of browser sign-in. It binds `127.0.0.1` on an OS-chosen port **before** the + * browser is opened, and only a validated HTTP request received here supplies the one-use code: browser + * completion URLs are never consulted and no browser cookie is read. There is no custom URL scheme. + * + * Bad requests (a favicon, a stray probe, a wrong path or state, a slow client) close their own connection + * without consuming the sign-in. At most four connections are served at once, each has + * [AuthTimings.callbackRequestMillis] to deliver its request, and the whole wait is bounded by + * [AuthTimings.browserSignInMillis]. After the code is captured every other connection is closed, a static + * no-store page is flushed (within [AuthTimings.callbackResponseFlushMillis]), and the code is delivered once. + */ +internal class LoopbackCallbackListener private constructor( + private val server: ServerSocket, + private val path: String, + private val state: String, + private val timings: AuthTimings, +) : AutoCloseable { + val port: Int = server.localPort + val callbackUrl: String = "http://127.0.0.1:$port$path" + val boundAddress: String get() = server.inetAddress.hostAddress.orEmpty() + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val result = CompletableDeferred() + private val connections = ConcurrentHashMap.newKeySet() + private val captured = AtomicBoolean(false) + private val closed = AtomicBoolean(false) + + init { + scope.launch { acceptLoop() } + } + + /** + * Runs [open] (the browser launch) while waiting for the validated code. A launch that fails before + * any code arrived ends the wait with [HermesException.Kind.BrowserAuthenticationUnavailable]; one that + * fails or is cancelled later cannot erase a captured code. Returns the code after the success page + * has been flushed. + */ + suspend fun awaitCode(open: suspend () -> Unit): String { + try { + return coroutineScope { + val opener = launch { + try { + open() + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + if (!captured.get()) result.completeExceptionally(HermesException(HermesException.Kind.BrowserAuthenticationUnavailable)) + } + } + try { + withTimeout(timings.browserSignInMillis) { result.await() } + } catch (_: TimeoutCancellationException) { + throw HermesException(HermesException.Kind.TimedOut) + } finally { + opener.cancel() + } + } + } finally { + close() + } + } + + override fun close() { + if (!closed.compareAndSet(false, true)) return + result.completeExceptionally(HermesException(HermesException.Kind.Cancelled)) + closeQuietly(server) + connections.forEach(::closeQuietly) + scope.cancel() + } + + private fun acceptLoop() { + while (!closed.get() && !captured.get()) { + val socket = try { + server.accept() + } catch (_: IOException) { + return + } + if (captured.get() || connections.size >= MAXIMUM_CONNECTIONS) { + closeQuietly(socket) + continue + } + connections.add(socket) + scope.launch { handle(socket) } + } + } + + private suspend fun handle(socket: Socket) { + val deadline = scope.launch { delay(timings.callbackRequestMillis); closeQuietly(socket) } + try { + socket.soTimeout = timings.callbackRequestMillis.toInt() + val request = readRequest(socket) ?: return + val code = try { + validate(request, port, path, state) + } catch (_: HermesException) { + return + } + if (!captured.compareAndSet(false, true)) return + deadline.cancel() + // Other readers stop; a static page is flushed before the code is handed over. + connections.filter { it !== socket }.forEach(::closeQuietly) + closeQuietly(server) + val flushDeadline = scope.launch { delay(timings.callbackResponseFlushMillis); closeQuietly(socket) } + try { + socket.getOutputStream().apply { write(SUCCESS_RESPONSE); flush() } + socket.shutdownOutput() + } catch (_: IOException) { + // The code is already ours; a browser that went away early changes nothing. + } + flushDeadline.cancel() + result.complete(code) + } catch (_: IOException) { + // A reset or timed-out connection never consumes the sign-in. + } finally { + deadline.cancel() + connections.remove(socket) + closeQuietly(socket) + } + } + + /** Reads up to the header terminator; refuses oversize input and anything after the terminator. */ + private fun readRequest(socket: Socket): ByteArray? { + val input = socket.getInputStream() + val buffer = ByteArrayOutputStream() + val chunk = ByteArray(4_096) + while (true) { + val count = input.read(chunk) + if (count <= 0 || count > MAXIMUM_REQUEST_BYTES - buffer.size()) return null + buffer.write(chunk, 0, count) + val bytes = buffer.toByteArray() + val end = indexOfTerminator(bytes) + if (end >= 0) return if (end + 4 == bytes.size) bytes else null + } + } + + companion object { + const val MAXIMUM_REQUEST_BYTES = 16_384 + private const val MAXIMUM_CONNECTIONS = 4 + private const val MAXIMUM_TOKEN_BYTES = 4_096 + + private val SUCCESS_RESPONSE: ByteArray = run { + val body = "bighelp" + + "

Sign-in received. Return to bighelp.

" + ("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: ${body.toByteArray().size}\r\n" + + "Cache-Control: no-store\r\nPragma: no-cache\r\nReferrer-Policy: no-referrer\r\n" + + "Content-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nX-Content-Type-Options: nosniff\r\n" + + "Connection: close\r\n\r\n$body").toByteArray(Charsets.US_ASCII) + } + + /** Binds `127.0.0.1` on an OS-chosen port; never a wildcard address. */ + fun bind(callbackPath: String, state: String, timings: AuthTimings): LoopbackCallbackListener { + require(isValidPath(callbackPath) && isUrlToken(state)) { "Invalid callback" } + val server = try { + ServerSocket(0, 4, InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))) + } catch (_: IOException) { + throw HermesException(HermesException.Kind.BrowserAuthenticationUnavailable) + } + return LoopbackCallbackListener(server, callbackPath, state, timings) + } + + /** + * Exactly one `GET ?state=&code= HTTP/1.1` with strict CRLF framing, the exact + * `Host: 127.0.0.1:`, unique headers, no body or upgrade, and two token-valued query fields. + * @return the code + * @throws HermesException InvalidResponse (or MessageTooLarge) for anything else. + */ + fun validate(request: ByteArray, port: Int, path: String, state: String): String { + fun invalid(): Nothing = throw HermesException(HermesException.Kind.InvalidResponse) + if (request.size > MAXIMUM_REQUEST_BYTES) throw HermesException(HermesException.Kind.MessageTooLarge) + if (!request.all { val b = it.toInt() and 0xff; b in 32..126 || b == 9 || b == 10 || b == 13 }) invalid() + val text = String(request, Charsets.US_ASCII) + if (!text.endsWith("\r\n\r\n")) invalid() + val lines = text.split("\r\n") + if (lines.size !in 4..68 || lines.takeLast(2).any { it.isNotEmpty() } || + lines.dropLast(2).any { it.isEmpty() || '\r' in it || '\n' in it } + ) invalid() + val requestLine = lines[0].split(' ') + if (requestLine.size != 3 || requestLine[0] != "GET" || requestLine[2] != "HTTP/1.1") invalid() + + val headers = HashMap() + for (line in lines.subList(1, lines.size - 2)) { + val colon = line.indexOf(':') + if (colon < 0) invalid() + val name = line.substring(0, colon) + if (name.isEmpty() || !name.all(::isHeaderToken)) invalid() + if (headers.putIfAbsent(name.lowercase(), line.substring(colon + 1).trim(' ', '\t')) != null) invalid() + } + if (headers["host"] != "127.0.0.1:$port" || "transfer-encoding" in headers || "expect" in headers || + "upgrade" in headers || "trailer" in headers || headers["content-length"]?.let { it != "0" } == true + ) invalid() + + val target = requestLine[1].split('?') + if (target.size != 2 || target[0] != path) invalid() + val fields = target[1].split('&') + if (fields.size != 2) invalid() + val query = HashMap() + for (field in fields) { + val pair = field.split('=') + if (pair.size != 2) invalid() + val key = decodeToken(pair[0]) + val value = decodeToken(pair[1]) + if ((key != "state" && key != "code") || query.put(key, value) != null) invalid() + } + val code = query["code"] + if (code == null || !MessageDigest.isEqual((query["state"] ?: invalid()).toByteArray(), state.toByteArray())) invalid() + return code + } + + /** Strict percent-decoding: `+` is not a space, and every decoded byte must be a URL-safe token character. */ + private fun decodeToken(encoded: String): String { + val result = StringBuilder() + var index = 0 + while (index < encoded.length) { + val byte: Int + if (encoded[index] == '%') { + if (index + 2 >= encoded.length) throw HermesException(HermesException.Kind.InvalidResponse) + val high = Character.digit(encoded[index + 1], 16) + val low = Character.digit(encoded[index + 2], 16) + if (high < 0 || low < 0) throw HermesException(HermesException.Kind.InvalidResponse) + byte = high * 16 + low + index += 3 + } else { + byte = encoded[index].code + index += 1 + } + if (byte > 0x7f || !isUrlToken(byte.toChar()) || result.length >= MAXIMUM_TOKEN_BYTES) { + throw HermesException(HermesException.Kind.InvalidResponse) + } + result.append(byte.toChar()) + } + if (result.isEmpty()) throw HermesException(HermesException.Kind.InvalidResponse) + return result.toString() + } + + private fun isUrlToken(c: Char) = c in 'A'..'Z' || c in 'a'..'z' || c in '0'..'9' || c == '-' || c == '_' + private fun isUrlToken(text: String) = text.isNotEmpty() && text.length <= MAXIMUM_TOKEN_BYTES && text.all(::isUrlToken) + private fun isHeaderToken(c: Char) = isUrlToken(c) || c in "!#$%&'*+.^`|~" + + private fun isValidPath(path: String) = path.startsWith("/") && !path.startsWith("//") && path.length <= 1_024 && + "//" !in path && path.all { isUrlToken(it) || it == '/' || it == '.' } && + path.split('/').none { it == "." || it == ".." } + + private fun indexOfTerminator(bytes: ByteArray): Int { + for (i in 0..bytes.size - 4) { + if (bytes[i] == 13.toByte() && bytes[i + 1] == 10.toByte() && bytes[i + 2] == 13.toByte() && bytes[i + 3] == 10.toByte()) return i + } + return -1 + } + + private fun closeQuietly(socket: Socket) { + try { socket.close() } catch (_: IOException) { } + } + + private fun closeQuietly(server: ServerSocket) { + try { server.close() } catch (_: IOException) { } + } + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt new file mode 100644 index 00000000..1a8130fd --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt @@ -0,0 +1,939 @@ +package app.bighelp.hermes + +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.trySendBlocking +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * The ordered Hermes gateway: one authenticated WebSocket at a time, a single ordered reader and a single + * ordered writer, and nothing written before `gateway.ready`. + * + * **Connect.** `connect()` mints credentials through the [HermesAuthenticator] (a fresh single-use ticket + * for every socket of a gated host), waits up to [GatewayTimings.readyMillis] for `gateway.ready`, then, in + * order: advertises `client.capabilities {server_requests:true}` **only if handlers are registered**, + * checks authenticated `GET /api/health`, and asks `gateway.capabilities`. Only then is the state + * [GatewayConnection.Connected]. The advertisement repeats on every ready socket, so register handlers + * before connecting. + * + * **Never silent about uncertainty.** A frame is marked `sendStarted` before it is handed to the socket. If + * the connection ends while a mutation is pending, that request fails with + * [HermesException.outcomeUnknown]; the client does not reconnect on its own, and no request is ever + * resent on any socket. Reads and controls fail plainly and the automatic same-owner recovery (delays 0, 1 + * and 3 seconds) replaces the socket, advertises again and rediscovers capabilities, for the owner to + * reconcile with session recovery. + * + * **Server requests.** Handlers answer the host's `approval`, `clarify`, `secret` and `sudo` requests. IDs + * are opaque and live in a table separate from the client's own RPC IDs (64 at most; duplicates and an + * over-capacity request are ignored). An unknown method gets `-32601`. A matching `request.cancel` (ID + * **and** method) cancels the handler and removes a queued response. + * + * **Ordering and atomicity.** Every received message is decoded whole by [HermesWire] before any entry is + * applied; entries are applied and published in wire order. Everything mutable lives on one + * single-threaded dispatcher, so no result or event of an older socket can publish after a newer one starts. + * + * **Inbound bounds.** The socket (see `GatewayWebSocket.kt`) refuses a frame by its declared length before + * allocating for it, caps the sum of fragments at 4 MiB, rejects malformed UTF-8 in a TEXT message instead of + * repairing it, bounds the upgrade response headers, offers no extensions, and keeps the platform's default + * TLS certificate and hostname checks. + * + * **Outbound bounds.** Frames reach the socket one at a time: the writer stops while the socket still holds + * unwritten data, so a stalled peer fills this client's own bounded queues (8 MiB of ordinary requests, one + * attachment of up to 12 MiB counted apart, 4 MiB of server replies) and then refuses new requests with + * [HermesException.Kind.TooManyRequests] instead of growing without limit. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class GatewayClient internal constructor( + private val authenticator: HermesAuthenticator, + private val scope: CoroutineScope, + private val timings: GatewayTimings, + private val transports: GatewayTransportFactory, +) { + constructor( + authenticator: HermesAuthenticator, + scope: CoroutineScope, + timings: GatewayTimings = GatewayTimings(), + ) : this(authenticator, scope, timings, GatewayWebSockets) + + private val serial: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1) + + /** Owns only the one-second hard-close timers, so they outlive the caller's scope; each ends by itself. */ + private val fallbackClose = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + // Everything below is touched only on [serial], except the concurrent collections. + private var terminal = false + private var link: Link? = null + private var generation = 0L + private var owners = OwnerState.none + private var lastFailure: HermesException? = null + private var opening: Deferred? = null + private var openingWaiters = 0 + private var recovery: Job? = null + private val handlers = ConcurrentHashMap() + private val subscribers = ConcurrentHashMap.newKeySet>() + private val mutableState = MutableStateFlow(GatewayState(GatewayConnection.Idle, 0, null, null, null, false, null)) + + val state: StateFlow = mutableState.asStateFlow() + + /** + * Every event of every socket, in wire order, each with its socket generation. A collector sees events + * from the moment it starts collecting, plus the retained first `gateway.ready` of a socket that is + * already ready; start collecting before [connect] to see everything. A collector too slow to keep up + * ([EVENT_BUFFER] events behind) fails with [HermesException.Kind.TooManyRequests] and must resynchronize. + */ + val events: Flow = flow { + val channel = Channel(EVENT_BUFFER) + withContext(serial) { + subscribers += channel + link?.let { l -> + val ready = l.socket.ready + if (l.socket.phase == SocketPhase.Ready && ready != null) channel.trySend(GatewayEvent(l.generation, ready)) + } + } + try { + for (event in channel) emit(event) + } finally { + withContext(NonCancellable + serial) { subscribers -= channel } + } + } + + internal val subscriberCount: Int get() = subscribers.size + + /** The bytes waiting in each bounded queue of the current socket (a test seam). */ + internal class QueueSnapshot(val ordinary: Int, val attachment: Int, val server: Int, val frames: Int) + + internal suspend fun queueSnapshot(): QueueSnapshot = withContext(serial) { + link?.let { QueueSnapshot(it.queuedBytes, it.queuedAttachmentBytes, it.queuedServerBytes, it.outbox.size) } ?: QueueSnapshot(0, 0, 0, 0) + } + + private class Pending( + val id: String, + val method: String, + val result: CompletableDeferred, + val readOnly: Boolean, + val isAttachment: Boolean, + ) { + var sendStarted = false + var timeout: Job? = null + } + + /** [kind] decides which of the three bounded queues counts it. */ + private class Outbound(val id: String, val serverMethod: String?, val text: String, val bytes: Int, val attachment: Boolean = false) + private class ServerTask(val token: Any, val job: Job) + + private sealed interface Inbound { + class Opened(val subprotocol: String?) : Inbound + class Message(val bytes: ByteArray) : Inbound + class Failed(val error: HermesException) : Inbound + } + + private inner class Link(val generation: Long, val owner: ConnectionOwner, val request: SocketRequest) { + var socket: GatewaySocket = GatewaySocket.opening(owner) + var transport: GatewayTransport? = null + val inbound = Channel(INBOUND_BUFFER) + var reader: Job? = null + var heartbeat: Job? = null + var readyDeadline: Job? = null + val readyGate = CompletableDeferred() + val pending = LinkedHashMap() + val outbox = ArrayDeque() + var queuedBytes = 0 + var queuedAttachmentBytes = 0 + var queuedServerBytes = 0 + var attachmentId: String? = null + var draining = false + val serverRequests = ServerRequestTable() + val serverTasks = HashMap() + var closed = false + var wasReady = false + var connected = false + var advertised = false + } + + // Connecting + + /** Opens the socket, waits for readiness and runs the startup sequence. Joins a connect already running. */ + suspend fun connect(): GatewayState = open(verify = false) + + /** + * Like [connect] but first rediscovers the host's authentication mode and rechecks the identity (what + * the automatic recovery does). Returns at once if already connected. It never resends anything. + */ + suspend fun reconnect(): GatewayState = open(verify = true) + + private suspend fun open(verify: Boolean): GatewayState { + val flight = withContext(serial) { + if (terminal) throw notConnected() + val current = link + if (current != null && current.connected) return@withContext CompletableDeferred(mutableState.value) + opening?.let { openingWaiters++; return@withContext it } + val created = scope.async(serial) { + try { + establish(verify) + } finally { + opening = null + } + } + opening = created + openingWaiters = 1 + created + } + try { + return flight.await() + } catch (e: CancellationException) { + // Nobody is left waiting for this attempt: end it, closing its socket. + withContext(NonCancellable + serial) { if (--openingWaiters <= 0 && opening === flight) flight.cancel() } + throw e + } + } + + private suspend fun establish(verify: Boolean): GatewayState { + if (verify) authenticator.verifyModeAndSession() + val request = authenticator.socketRequest() + val opened = startLink(request) + try { + opened.readyGate.await() + handshake(opened) + } catch (e: Throwable) { + val error = if (e is CancellationException) HermesException(HermesException.Kind.Cancelled) else asHermes(e) + closeLink(opened, error, notify = false) + throw if (e is CancellationException) e else error + } + return mutableState.value + } + + private fun startLink(request: SocketRequest): Link { + if (terminal) throw notConnected() + link?.let { closeLink(it, HermesException(HermesException.Kind.Disconnected), notify = false) } + generation += 1 + owners = owners.connect(authenticator.endpoint, authenticator.savedConnection?.principal.orEmpty()) + val created = Link(generation, owners.current!!, request) + link = created + publish() + + try { + created.transport = transports.open(request, listenerFor(created)) + } catch (e: HermesException) { + closeLink(created, e, notify = false) + throw e + } + created.reader = scope.launch(serial) { readLoop(created) } + created.readyDeadline = scope.launch(serial) { + delay(timings.readyMillis) + if (!created.wasReady) closeLink(created, HermesException(HermesException.Kind.TimedOut), notify = false) + } + return created + } + + /** Socket callbacks arrive on the socket's reader thread; a full buffer blocks it, which is TCP backpressure. */ + private fun listenerFor(owner: Link) = object : GatewayTransportListener { + override fun opened(negotiatedSubprotocol: String?) { + owner.inbound.trySendBlocking(Inbound.Opened(negotiatedSubprotocol)) + } + + override fun message(bytes: ByteArray) { + owner.inbound.trySendBlocking(Inbound.Message(bytes)) + } + + override fun failed(error: HermesException) { + owner.inbound.trySendBlocking(Inbound.Failed(error)) + } + } + + /** The single ordered reader: one inbound item at a time, each fully applied before the next is read. */ + private suspend fun readLoop(owner: Link) { + for (item in owner.inbound) { + if (owner.closed) return + when (item) { + is Inbound.Opened -> { + val required = owner.request.requiredSubprotocol + if (required != null && item.subprotocol != required) { + closeLink(owner, HermesException(HermesException.Kind.InvalidResponse), notify = false) + return + } + owner.socket = owner.socket.upgraded() + } + is Inbound.Message -> { + val decoded = try { + withContext(Dispatchers.Default) { HermesWire.decode(item.bytes) } + } catch (e: WireException) { + closeLink(owner, HermesException( + if (e.kind == WireException.Kind.MessageTooLarge) HermesException.Kind.MessageTooLarge else HermesException.Kind.InvalidResponse, + ), notify = true) + return + } + if (owner.closed) return + accept(owner, decoded) + } + is Inbound.Failed -> { + closeLink(owner, item.error, notify = true) + return + } + } + } + } + + private fun accept(owner: Link, messages: List) { + for (message in messages) { + if (owner.closed) return + when (message) { + is WireMessage.Event -> { + if (message.type == "request.cancel") retireServerRequest(owner, HermesWire.cancellation(message)) + if (message.type == GatewaySocket.GATEWAY_READY) { + val next = owner.socket.receive(message) + if (next.phase == SocketPhase.Closed || next.phase != SocketPhase.Ready) { + // A second ready on a ready socket, or one that arrives at the wrong time. + closeLink(owner, HermesException(HermesException.Kind.InvalidResponse), notify = true) + return + } + owner.socket = next + owner.wasReady = true + owner.readyDeadline?.cancel() + owner.readyGate.complete(Unit) + startHeartbeat(owner) + pump(owner) + publish() + } + publishEvent(owner, message) + } + is WireMessage.Request -> acceptServerRequest(owner, message.id, message.method, message.params) + is WireMessage.Result -> finish(owner, message.id, Result.success(message.value)) + is WireMessage.Failure -> finish(owner, message.id, Result.failure(rpcFailure(message))) + } + } + } + + private fun rpcFailure(failure: WireMessage.Failure): HermesException { + val kind = if (failure.code == 4090L && failure.reason == "MAX_CONCURRENT_SESSIONS") { + HermesException.Kind.ActiveSessionLimit + } else { + HermesException.Kind.RpcRejected + } + return HermesException(kind, code = failure.code, reason = failure.reason, refusal = failure.message) + } + + private fun publishEvent(owner: Link, event: WireMessage.Event) { + val published = GatewayEvent(owner.generation, event) + for (channel in subscribers) { + if (channel.trySend(published).isFailure) { + channel.close(HermesException(HermesException.Kind.TooManyRequests)) + subscribers -= channel + } + } + } + + // Startup sequence + + private suspend fun handshake(owner: Link) { + if (claimAdvertisement(owner)) { + try { + requestOn(owner, "client.capabilities", buildJsonObject { put("server_requests", true) }, timings.advertiseMillis) + } catch (e: HermesException) { + // An older host that has no such method needs none; a lost socket is retried by the next one. + if (e.kind != HermesException.Kind.RpcRejected) { + owner.advertised = false + throw e + } + } + } + authenticator.requireHealth() + val result = requestOn(owner, "gateway.capabilities", JsonObject(emptyMap()), timings.requestMillis) + val capabilities = try { + GatewayCapabilities.decode(result) + } catch (_: WireException) { + throw HermesException(HermesException.Kind.InvalidResponse) + } + withContext(serial) { + if (owner.closed) throw notConnected() + owner.socket = owner.socket.discovered(capabilities) + owner.connected = true + publish() + } + } + + /** True exactly once per socket, and only when real handlers exist: advertising promises to answer. */ + private fun claimAdvertisement(owner: Link): Boolean { + if (owner.advertised || owner.closed || handlers.isEmpty()) return false + owner.advertised = true + return true + } + + /** + * Registers (or, with null, removes) the handler for one server-request [method]. Only methods the + * app can really fulfill belong here; everything else is refused with `-32601`. Registration alone + * advertises nothing; the client advertises after `gateway.ready`, once per socket, as soon as it has + * any handler. Handlers survive an automatic same-owner recovery and are forgotten when a connection + * ends without one (an uncertain mutation, exhausted attempts, [disconnect]). + */ + fun setServerRequestHandler(method: String, handler: ServerRequestHandler?) { + require(HermesWire.isValidMethod(method) && method != "event") { "Invalid method" } + if (handler == null) { + handlers.remove(method) + return + } + handlers[method] = handler + scope.launch(serial) { + val live = link ?: return@launch + if (live.socket.phase != SocketPhase.Ready || !claimAdvertisement(live)) return@launch + try { + requestOn(live, "client.capabilities", buildJsonObject { put("server_requests", true) }, timings.advertiseMillis) + } catch (e: HermesException) { + if (e.kind != HermesException.Kind.RpcRejected) live.advertised = false + } + } + } + + // Requests + + /** + * One JSON-RPC call. [operation] defaults from the method: reads, controls, and the three submission + * methods (`prompt.submit`, `slash.exec`, `command.dispatch`), which need the host's + * `per_session_exclusive_submit` guarantee. A refused admission sends nothing. + * + * Failures are [HermesException]s; [HermesException.outcomeUnknown] marks a mutation that may have been + * accepted. Cancelling the caller throws [RequestCancelledException] (a `CancellationException`) saying + * whether the frame had been handed to the socket; it never stops the host and is never resent. + * + * [generation] fences a call that names something only one socket knows (a runtime ID): it is compared with + * the current socket's generation in the same serial section that reads the socket, and a mismatch is + * [HermesException.Kind.NotConnected] before anything is queued. [requestOn] then enqueues on exactly that + * socket object, so the frame can only ever leave on the generation that was named. + */ + suspend fun request( + method: String, + params: JsonObject = JsonObject(emptyMap()), + timeoutMillis: Long = timings.requestMillis, + operation: GatewayOperation? = null, + maximumFrameBytes: Int = DEFAULT_FRAME_BYTES, + generation: Long? = null, + ): JsonElement { + val live = withContext(serial) { link?.takeIf { generation == null || it.generation == generation } } ?: throw notConnected() + return requestOn(live, method, params, timeoutMillis, operation, maximumFrameBytes) + } + + private suspend fun requestOn( + owner: Link, + method: String, + params: JsonObject, + timeoutMillis: Long, + operation: GatewayOperation? = null, + maximumFrameBytes: Int = DEFAULT_FRAME_BYTES, + ): JsonElement { + if (!HermesWire.isValidMethod(method)) throw HermesException(HermesException.Kind.InvalidResponse) + val isAttachment = method == "file.attach" || method == "image.attach_bytes" + val ceiling = if (isAttachment) ATTACHMENT_FRAME_BYTES else maximumOutboundBytes(method) + if (maximumFrameBytes > ceiling) throw HermesException(HermesException.Kind.MessageTooLarge) + val id = UUID.randomUUID().toString() + val text = buildJsonObject { + put("jsonrpc", "2.0"); put("id", id); put("method", method); put("params", params) + }.toString() + val bytes = utf8Length(text) + if (bytes > maximumFrameBytes || exceedsNesting(text)) throw HermesException(HermesException.Kind.MessageTooLarge) + val op = operation ?: when { + DispatchPolicy.isReadOnly(method) -> GatewayOperation.Read + method in SUBMISSION_METHODS -> GatewayOperation.Submission + else -> GatewayOperation.Control + } + + try { + // Cancellation can land while the frame is already on its way out of enqueue; the cleanup and the + // dispatch outcome below must cover that window too, or a sent request would be forgotten. + val pending = withContext(serial) { enqueue(owner, id, method, op, text, bytes, timeoutMillis, isAttachment) } + return pending.result.await() + } catch (e: CancellationException) { + // Returning from withContext into an already cancelled caller rethrows its cancellation, even for + // NonCancellable work, so the outcome is captured inside the block where the cleanup runs. + var dispatch = DispatchOutcome.NotSent + try { + withContext(NonCancellable + serial) { dispatch = cancelPending(owner, id) } + } catch (_: CancellationException) { + // The cleanup above already ran. + } + throw RequestCancelledException(dispatch).also { it.initCause(e) } + } + } + + private fun maximumOutboundBytes(method: String) = if (method == "profiles.set_asset") 2_800_000 else DEFAULT_FRAME_BYTES + + private fun enqueue( + owner: Link, id: String, method: String, operation: GatewayOperation, text: String, bytes: Int, + timeoutMillis: Long, isAttachment: Boolean, + ): Pending { + if (owner.closed || owner !== link) throw notConnected() + when (val admission = owner.socket.admit(operation, owners)) { + Admission.Admitted -> Unit + is Admission.Refused -> throw HermesException( + if (admission.reason == Refusal.ExclusiveSubmitUnavailable) HermesException.Kind.ExclusiveSubmitUnavailable + else HermesException.Kind.NotConnected, + ) + } + if (owner.pending.size >= MAXIMUM_PENDING) throw HermesException(HermesException.Kind.TooManyRequests) + // Three separate queues, so a flood of ordinary requests can never refuse the one attachment frame the + // contract allows (up to 12 MiB), nor the other way round, and neither starves a server reply. + if (isAttachment) { + if (owner.attachmentId != null || owner.queuedAttachmentBytes + bytes > ATTACHMENT_FRAME_BYTES) { + throw HermesException(HermesException.Kind.TooManyRequests) + } + } else if (owner.queuedBytes + bytes > MAXIMUM_QUEUED_BYTES) { + throw HermesException(HermesException.Kind.TooManyRequests) + } + + val pending = Pending(id, method, CompletableDeferred(), DispatchPolicy.isReadOnly(method), isAttachment) + owner.pending[id] = pending + if (isAttachment) owner.attachmentId = id + pending.timeout = scope.launch(serial) { + delay(timeoutMillis) + expire(owner, id) + } + owner.outbox.addLast(Outbound(id, null, text, bytes, isAttachment)) + if (isAttachment) owner.queuedAttachmentBytes += bytes else owner.queuedBytes += bytes + pump(owner) + return pending + } + + /** Removes a cancelled request and reports how far it got. The frame, if sent, is not recalled. */ + private fun cancelPending(owner: Link, id: String): DispatchOutcome { + val pending = owner.pending[id] ?: return DispatchOutcome.NotSent + val outcome = if (pending.sendStarted) DispatchOutcome.MayHaveBeenSent else DispatchOutcome.NotSent + removePending(owner, id) + return outcome + } + + private fun removePending(owner: Link, id: String): Pending? { + val pending = owner.pending.remove(id) ?: return null + pending.timeout?.cancel() + if (owner.attachmentId == id) owner.attachmentId = null + val index = owner.outbox.indexOfFirst { it.id == id && it.serverMethod == null } + if (index >= 0) uncount(owner, owner.outbox.removeAt(index)) + return pending + } + + private fun finish(owner: Link, id: String, result: Result) { + val pending = removePending(owner, id) ?: return + result.fold({ pending.result.complete(it) }, { pending.result.completeExceptionally(it) }) + } + + private fun expire(owner: Link, id: String) { + val pending = owner.pending[id] ?: return + finish(owner, id, Result.failure(HermesException(HermesException.Kind.TimedOut, outcomeUnknown = pending.sendStarted && !pending.readOnly))) + // A stalled send is unparked before anything queued behind it could go out. + if (pending.sendStarted) closeLink(owner, HermesException(HermesException.Kind.TimedOut), notify = true) + } + + /** Takes [item] out of whichever bounded queue counted it. */ + private fun uncount(owner: Link, item: Outbound) { + when { + item.serverMethod != null -> owner.queuedServerBytes -= item.bytes + item.attachment -> owner.queuedAttachmentBytes -= item.bytes + else -> owner.queuedBytes -= item.bytes + } + } + + /** + * The single ordered writer. Nothing leaves before ready; each frame is marked sent before the socket call. + * Frames go out one at a time, only while the socket holds no unwritten data: a peer that stops reading + * leaves the rest here, where it is bounded and a queued server reply can still be cancelled. + */ + private fun pump(owner: Link) { + if (owner.closed || owner.socket.phase != SocketPhase.Ready) return + val transport = owner.transport ?: return + while (owner.outbox.isNotEmpty()) { + if (transport.hasBufferedData) { + drainLater(owner) + return + } + val item = owner.outbox.removeFirst() + uncount(owner, item) + if (item.serverMethod != null) { + if (!owner.serverRequests.beginSendingResponse(item.id, item.serverMethod)) continue + } else { + val pending = owner.pending[item.id] ?: continue + pending.sendStarted = true + } + if (!transport.send(item.text)) { + closeLink(owner, HermesException(HermesException.Kind.Disconnected), notify = true) + return + } + } + } + + /** + * Resumes the writer once the socket has taken what it was given. The library offers no "written" callback, so the + * wait polls, but backs off while the peer stays stalled (a stalled socket may last until the request timeout) and + * starts fast again at the next stall. + */ + private fun drainLater(owner: Link) { + if (owner.draining) return + owner.draining = true + scope.launch(serial) { + try { + var wait = DRAIN_POLL_MILLIS + while (!owner.closed && owner.outbox.isNotEmpty()) { + if (owner.transport?.hasBufferedData == true) { + delay(wait) + wait = minOf(wait * 2, DRAIN_POLL_MAX_MILLIS) + } else { + pump(owner) + wait = DRAIN_POLL_MILLIS + } + } + } finally { + owner.draining = false + } + } + } + + // Keepalive + + private fun startHeartbeat(owner: Link) { + val hinted = (owner.socket.ready?.payload?.get("heartbeat") as? JsonPrimitive)?.takeIf { !it.isString }?.content == "true" + val interval = if (hinted) timings.heartbeatMillis else timings.pingMillis + owner.heartbeat?.cancel() + owner.heartbeat = scope.launch(serial) { + while (isActive && !owner.closed) { + delay(interval) + if (owner.closed) return@launch + try { + requestOn(owner, "gateway.ping", JsonObject(emptyMap()), timings.pingReplyMillis) + } catch (e: HermesException) { + // Any RPC answer proves the socket; this host just has no ping. + if (e.kind == HermesException.Kind.RpcRejected) return@launch + closeLink(owner, e, notify = true) + return@launch + } catch (e: RequestCancelledException) { + return@launch + } + } + } + } + + /** A quick check after the app returns or the network changes; a silent socket is replaced at once. */ + suspend fun verifyLiveness() { + val live = withContext(serial) { link?.takeIf { it.connected } } ?: return + try { + requestOn(live, "gateway.ping", JsonObject(emptyMap()), timings.livenessMillis) + } catch (e: HermesException) { + if (e.kind == HermesException.Kind.RpcRejected) return + withContext(serial) { closeLink(live, e, notify = true) } + } + } + + /** + * Proves the socket just before a prompt admission (a ping within [GatewayTimings.admissionMillis]); on + * failure it waits for the automatic recovery and pings the replacement once. Nothing is constructed or + * sent for the caller until the proof succeeds. + * @throws HermesException [HermesException.Kind.NotConnected] when there is no socket to prove. + */ + suspend fun prepareForAdmission() { + withContext(serial) { recovery }?.join() + pingForAdmission(first = true) + } + + private suspend fun pingForAdmission(first: Boolean) { + val live = withContext(serial) { if (terminal) null else link?.takeIf { it.connected } } ?: throw notConnected() + try { + requestOn(live, "gateway.ping", JsonObject(emptyMap()), timings.admissionMillis) + } catch (e: HermesException) { + if (!first) throw e + withContext(serial) { recovery }?.join() + pingForAdmission(first = false) + } + } + + // Server requests + + private fun acceptServerRequest(owner: Link, id: String, method: String, params: JsonObject) { + when (owner.serverRequests.register(id, method)) { + // The existing request stays authoritative and bounded: no second decision or response. + ServerRequestTable.Registration.Duplicate, ServerRequestTable.Registration.AtCapacity -> return + ServerRequestTable.Registration.Accepted -> Unit + } + val handler = handlers[method] + if (handler == null) { + queueServerResponse(owner, id, method, ServerResponse.Failure(-32601, "Method not supported by this client")) + return + } + val token = Any() + val job = scope.launch(Dispatchers.Default) { + val response = try { + handler.handle(IncomingServerRequest(owner.generation, id, method, params)) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + ServerResponse.Failure(-32603, "Client could not handle the request") + } + withContext(serial + NonCancellable) { completeHandler(owner, id, method, token, response) } + } + owner.serverTasks[id] = ServerTask(token, job) + } + + private fun completeHandler(owner: Link, id: String, method: String, token: Any, response: ServerResponse) { + if (owner.serverTasks[id]?.token !== token) return + owner.serverTasks.remove(id) + if (owner.closed || owner !== link) return + queueServerResponse(owner, id, method, response) + } + + private fun queueServerResponse(owner: Link, id: String, method: String, response: ServerResponse) { + var text = encodeResponse(id, response) + ?: encodeResponse(id, ServerResponse.Failure(-32603, "Client could not encode the response")) + ?: run { owner.serverRequests.retire(id, method); return } + var bytes = utf8Length(text) + if (owner.queuedServerBytes + bytes > MAXIMUM_QUEUED_SERVER_BYTES) { + text = encodeResponse(id, ServerResponse.Failure(-32603, "Client response queue is full")) + ?: run { owner.serverRequests.retire(id, method); return } + bytes = utf8Length(text) + if (owner.queuedServerBytes + bytes > MAXIMUM_QUEUED_SERVER_BYTES) { + owner.serverRequests.retire(id, method) + return + } + } + if (!owner.serverRequests.stageResponse(id, method)) return + owner.outbox.addLast(Outbound(id, method, text, bytes)) + owner.queuedServerBytes += bytes + pump(owner) + } + + /** The response envelope with the original ID bytes, or null if it cannot be encoded within limits. */ + private fun encodeResponse(id: String, response: ServerResponse): String? { + if (!HermesWire.isValidRequestID(id)) return null + val envelope = try { + buildJsonObject { + put("jsonrpc", "2.0") + put("id", id) + when (response) { + is ServerResponse.Result -> put("result", response.value) + is ServerResponse.Failure -> { + if (response.message.isEmpty() || utf8Length(response.message) > HermesWire.MAXIMUM_CANCELLATION_REASON_BYTES) return null + put("error", buildJsonObject { + put("code", response.code) + put("message", response.message) + response.data?.let { put("data", it) } + }) + } + } + }.toString() + } catch (_: Exception) { + return null + } + return envelope.takeIf { utf8Length(it) <= MAXIMUM_RESPONSE_BYTES && !exceedsNesting(it) } + } + + private fun retireServerRequest(owner: Link, cancellation: RequestCancellation) { + if (!owner.serverRequests.retire(cancellation.id, cancellation.method)) return + owner.serverTasks.remove(cancellation.id)?.job?.cancel() + val index = owner.outbox.indexOfFirst { it.id == cancellation.id && it.serverMethod == cancellation.method } + if (index >= 0) { + uncount(owner, owner.outbox.removeAt(index)) + } + } + + /** + * Adopts the final `session.events.since.open_requests` snapshot through the same handler path as live + * requests. The whole snapshot (at most 64 rows of exactly `id`, `method` and `params`, each with + * `params.session_id == runtimeId`) is validated before anything is adopted. [generation] must be the + * current socket generation. + */ + suspend fun adoptOpenRequests(rows: JsonElement, runtimeId: String, generation: Long) { + withContext(serial) { + val live = link + if (live == null || live.closed || live.generation != generation || live.socket.phase != SocketPhase.Ready) throw notConnected() + val invalid = HermesException(HermesException.Kind.InvalidResponse) + if (runtimeId.isEmpty() || utf8Length(runtimeId) > 4_096) throw invalid + val array = rows as? JsonArray ?: throw invalid + if (array.size > ServerRequestTable.MAXIMUM_OPEN) throw invalid + val requests = array.map { row -> + val entry = row as? JsonObject ?: throw invalid + if (entry.keys != setOf("id", "method", "params")) throw invalid + val id = (entry["id"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.takeIf(HermesWire::isValidRequestID) ?: throw invalid + val method = (entry["method"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.takeIf(HermesWire::isValidMethod) ?: throw invalid + val params = entry["params"] as? JsonObject ?: throw invalid + if ((params["session_id"] as? JsonPrimitive)?.takeIf { it.isString }?.content != runtimeId) throw invalid + Triple(id, method, params) + } + for ((id, method, params) in requests) acceptServerRequest(live, id, method, params) + } + } + + // Closing + + /** + * Ends this client for good: closes the socket, fails what is pending, forgets the handlers, and gives a + * renewal already on its way a moment to save. A new client (or [connect] on a fresh instance) is needed + * afterwards. Credentials in the store are untouched. + */ + suspend fun disconnect() { + withContext(serial) { + terminal = true + recovery?.cancel() + recovery = null + opening?.cancel() + link?.let { closeLink(it, HermesException(HermesException.Kind.Disconnected), notify = false, orderly = true) } + handlers.clear() + publish() + subscribers.forEach { it.close() } + subscribers.clear() + } + authenticator.settlePendingRenewal() + } + + private fun closeLink(owner: Link, reason: HermesException, notify: Boolean, orderly: Boolean = false) { + if (owner.closed) return + owner.closed = true + val uncertain = owner.pending.values.any { it.sendStarted && !it.readOnly } + val recover = notify && owner.connected && !terminal && !uncertain + if (link === owner) link = null + owner.readyDeadline?.cancel() + owner.heartbeat?.cancel() + owner.transport?.let { transport -> + if (orderly) { + transport.close(orderly = true) + // Not on `scope`: the owner cancels it right after disconnect(), which would drop this fallback. + fallbackClose.launch { delay(1_000); transport.close(orderly = false) } + } else { + transport.close(orderly = false) + } + } + owner.inbound.close() + owner.reader?.cancel() + owner.readyGate.completeExceptionally(reason) + val failing = owner.pending.values.toList() + owner.pending.clear() + for (pending in failing) { + pending.timeout?.cancel() + pending.result.completeExceptionally( + if (pending.sendStarted && !pending.readOnly) HermesException(HermesException.Kind.Disconnected, outcomeUnknown = true) else reason, + ) + } + owner.serverTasks.values.forEach { it.job.cancel() } + owner.serverTasks.clear() + owner.serverRequests.removeAll() + owner.outbox.clear() + owner.queuedBytes = 0 + owner.queuedAttachmentBytes = 0 + owner.queuedServerBytes = 0 + owner.attachmentId = null + lastFailure = reason + if (recover) { + startRecovery(reason) + } else if (owner.connected && recovery == null) { + // A connection that ended without automatic recovery: the next owner registers handlers again. + handlers.clear() + } + publish() + } + + private fun startRecovery(initial: HermesException) { + if (recovery != null) return + recovery = scope.launch(serial) { + var last = initial + for (delayMillis in timings.reconnectDelaysMillis) { + if (delayMillis > 0) delay(delayMillis) + if (terminal) return@launch + try { + open(verify = true) + // Published state still says Recovering while this loop runs, so read the link itself. + if (link?.connected == true) { + recovery = null + publish() + return@launch + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + last = asHermes(e) + } + } + if (terminal) return@launch + recovery = null + handlers.clear() + lastFailure = last + publish() + } + publish() + } + + private fun publish() { + val live = link + val connection = when { + terminal -> GatewayConnection.Closed + recovery != null -> GatewayConnection.Recovering + live == null -> GatewayConnection.Idle + live.connected -> GatewayConnection.Connected + else -> GatewayConnection.Connecting + } + val ready = live?.socket?.ready + val replayEpoch = (ready?.payload?.get("replay_epoch") as? JsonPrimitive)?.takeIf { it.isString }?.content + val heartbeat = (ready?.payload?.get("heartbeat") as? JsonPrimitive)?.takeIf { !it.isString && it !is JsonNull }?.content == "true" + mutableState.value = GatewayState(connection, generation, live?.owner, live?.socket, replayEpoch, heartbeat, lastFailure) + } + + private fun notConnected() = HermesException(HermesException.Kind.NotConnected) + + private fun asHermes(error: Throwable): HermesException = when (error) { + is HermesException -> error + is WireException -> HermesException(HermesException.Kind.InvalidResponse) + else -> HermesException(HermesException.Kind.ConnectionFailed) + } + + /** Counts `{`/`[` depth outside strings, like the inbound check, so hostile nesting is never sent. */ + private fun exceedsNesting(text: String): Boolean { + var depth = 0 + var quoted = false + var escaped = false + for (c in text) { + if (quoted) { + if (escaped) escaped = false else if (c == '\\') escaped = true else if (c == '"') quoted = false + } else if (c == '"') { + quoted = true + } else if (c == '{' || c == '[') { + if (++depth > HermesWire.MAXIMUM_NESTING) return true + } else if (c == '}' || c == ']') { + depth-- + } + } + return false + } + + companion object { + const val DEFAULT_FRAME_BYTES = 2 * 1_024 * 1_024 + const val ATTACHMENT_FRAME_BYTES = 12 * 1_024 * 1_024 + const val MAXIMUM_PENDING = 64 + const val MAXIMUM_QUEUED_BYTES = 8 * 1_024 * 1_024 + const val MAXIMUM_RESPONSE_BYTES = 2 * 1_024 * 1_024 + const val MAXIMUM_QUEUED_SERVER_BYTES = 4 * 1_024 * 1_024 + const val EVENT_BUFFER = 8_192 + private const val DRAIN_POLL_MILLIS = 2L + private const val DRAIN_POLL_MAX_MILLIS = 50L + // Few, because one message can be 4 MiB; a full buffer blocks the socket reader, which is TCP backpressure. + private const val INBOUND_BUFFER = 8 + private val SUBMISSION_METHODS = setOf("prompt.submit", "slash.exec", "command.dispatch") + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt new file mode 100644 index 00000000..7b479ce2 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt @@ -0,0 +1,98 @@ +package app.bighelp.hermes + +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject + +/** Deadlines and paces of the gateway, injectable so tests need not wait. Defaults are the contract's. */ +class GatewayTimings( + /** From creating the socket to `gateway.ready`. HTTP 101 alone is not ready. */ + val readyMillis: Long = 20_000, + /** `client.capabilities` reply deadline. */ + val advertiseMillis: Long = 15_000, + /** An ordinary RPC, from enqueue (not from the host starting it). */ + val requestMillis: Long = 45_000, + /** Periodic ping when `gateway.ready` said `heartbeat: true`. */ + val heartbeatMillis: Long = 15_000, + /** Periodic ping otherwise. */ + val pingMillis: Long = 20_000, + val pingReplyMillis: Long = 15_000, + /** A quick check after foreground or a network change. */ + val livenessMillis: Long = 4_000, + /** The proof just before a prompt admission. */ + val admissionMillis: Long = 5_000, + /** Automatic same-owner recovery attempts: the delay before each. */ + val reconnectDelaysMillis: List = listOf(0, 1_000, 3_000), +) + +/** One event with the socket generation it arrived on, so a consumer can drop a stale one. */ +class GatewayEvent(val generation: Long, val event: WireMessage.Event) { + override fun toString() = "GatewayEvent($generation, ${event.type})" +} + +enum class GatewayConnection { + /** Never connected, or the last connection ended and recovery is not running. */ + Idle, + Connecting, + + /** Ready, advertised, healthy and with capabilities known. */ + Connected, + + /** The socket was lost and the automatic same-owner recovery is under way. */ + Recovering, + + /** [GatewayClient.disconnect] ran. This client object is finished. */ + Closed, +} + +/** What a consumer needs to know about the connection right now. */ +class GatewayState( + val connection: GatewayConnection, + /** The current (or last) socket generation; changes with every new socket, even to the same owner. */ + val generation: Long, + val owner: ConnectionOwner?, + /** Phase, capabilities and the retained first `gateway.ready` of the current socket. */ + val socket: GatewaySocket?, + /** `payload.replay_epoch` of the retained ready, when the host sent one. */ + val replayEpoch: String?, + val heartbeatAdvertised: Boolean, + /** Why the previous socket ended, if it did. */ + val lastFailure: HermesException?, +) { + val ready: WireMessage.Event? get() = socket?.ready + val capabilities: GatewayCapabilities? get() = socket?.capabilities + val isConnected: Boolean get() = connection == GatewayConnection.Connected + + override fun toString() = "GatewayState($connection, generation=$generation)" +} + +/** A request the host sent to this client. [generation] is the socket it arrived on. */ +class IncomingServerRequest(val generation: Long, val id: String, val method: String, val params: JsonObject) { + override fun toString() = "IncomingServerRequest($method)" +} + +/** The answer to a server request. The transport never makes a decision itself; only a handler does. */ +sealed interface ServerResponse { + class Result(val value: JsonElement) : ServerResponse + + /** A JSON-RPC error; [message] is nonempty and at most 4,096 bytes. */ + class Failure(val code: Long, val message: String, val data: JsonElement? = null) : ServerResponse +} + +/** + * Answers one kind of server request (`approval`, `clarify`, `secret`, `sudo`). It runs in its own + * coroutine and may suspend for as long as a person takes. It is cancelled when the host sends a matching + * `request.cancel` or the socket generation ends, and then nothing is sent. Registering handlers is what + * makes the client advertise `server_requests`, after `gateway.ready`, on every socket. + */ +fun interface ServerRequestHandler { + suspend fun handle(request: IncomingServerRequest): ServerResponse +} + +/** + * Thrown to a coroutine that was cancelled while its RPC was pending. It is a [CancellationException], so + * structured concurrency is unaffected, but it says how far the request got: [dispatch] is + * [DispatchOutcome.MayHaveBeenSent] once the frame was handed to the socket. Cancelling never stops the + * host and is not an interrupt; the request is never resent. + */ +class RequestCancelledException(val dispatch: DispatchOutcome) : CancellationException("Request cancelled") diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt new file mode 100644 index 00000000..c34773dc --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt @@ -0,0 +1,297 @@ +package app.bighelp.hermes + +import java.io.IOException +import java.net.InetAddress +import java.net.URI +import java.net.URISyntaxException +import java.nio.ByteBuffer +import java.util.concurrent.atomic.AtomicBoolean +import org.java_websocket.WebSocketImpl +import org.java_websocket.client.DnsResolver +import org.java_websocket.client.WebSocketClient +import org.java_websocket.drafts.Draft +import org.java_websocket.drafts.Draft_6455 +import org.java_websocket.exceptions.InvalidHandshakeException +import org.java_websocket.extensions.IExtension +import org.java_websocket.framing.CloseFrame +import org.java_websocket.handshake.ClientHandshake +import org.java_websocket.handshake.Handshakedata +import org.java_websocket.handshake.ServerHandshake +import org.java_websocket.protocols.IProtocol +import org.java_websocket.protocols.Protocol + +// The gateway's WebSocket I/O. OkHttp stays for bounded HTTP, but OkHttp 4.12 cannot give a WebSocket the +// two things this contract needs: it assembles a whole inbound message before delivering it (so a declared +// length cannot be refused up front) and it repairs malformed UTF-8 instead of rejecting it. Java-WebSocket +// 1.6.0 checks a frame's declared length before allocating, caps the sum of fragments, decodes TEXT strictly +// when a message completes, and turns on HTTPS hostname identification. Everything the library does not do is +// done here: bounded and typed upgrade responses, exact subprotocol negotiation, no extensions, UTF-8 header +// bytes, and no logging (see build.gradle.kts: SLF4J is bound to its no-op provider). + +/** One gateway socket as [GatewayClient] sees it. */ +internal interface GatewayTransport { + /** + * True while frames handed to [send] have not yet been taken by the socket's writer. The sender stops at + * this signal, so a stalled peer backs the queue up in the sender's own bounded outbox, not in the library. + */ + val hasBufferedData: Boolean + + /** Queues one TEXT frame in order; false when the socket is not open. */ + fun send(text: String): Boolean + + /** [orderly]: a close handshake. Otherwise the socket is dropped at once. Idempotent. */ + fun close(orderly: Boolean) +} + +/** Callbacks of one socket, on its reader thread, in wire order. [failed] is the one terminal event. */ +internal interface GatewayTransportListener { + fun opened(negotiatedSubprotocol: String?) + + /** One whole message (a TEXT message is strict UTF-8, re-encoded; a BINARY message is the bytes as sent). */ + fun message(bytes: ByteArray) + + /** The socket ended for any reason: never called twice, never called after a deliberate [GatewayTransport.close]. */ + fun failed(error: HermesException) +} + +internal fun interface GatewayTransportFactory { + /** @throws HermesException if [request] cannot be sent as it is. Otherwise connecting continues in the background. */ + fun open(request: SocketRequest, listener: GatewayTransportListener): GatewayTransport +} + +internal object GatewayWebSockets : GatewayTransportFactory { + /** The largest inbound frame, and the largest sum of fragments: the contract's 4 MiB message. */ + const val MAXIMUM_MESSAGE_BYTES = HermesWire.MAXIMUM_MESSAGE_BYTES + + /** The upgrade response's header block, counted up to its blank line. */ + const val MAXIMUM_UPGRADE_HEADER_BYTES = 16_384 + + private const val CONNECT_TIMEOUT_MILLIS = 20_000 + private const val PROTOCOL_HEADER = "Sec-WebSocket-Protocol" + + override fun open(request: SocketRequest, listener: GatewayTransportListener): GatewayTransport { + val uri = try { + URI(request.url) + } catch (_: URISyntaxException) { + throw HermesException(HermesException.Kind.InvalidEndpoint) + } + if (uri.scheme != "ws" && uri.scheme != "wss" || uri.host.isNullOrEmpty()) throw HermesException(HermesException.Kind.InvalidEndpoint) + + val headers = LinkedHashMap(request.headers) + val offered = headers.keys.firstOrNull { it.equals(PROTOCOL_HEADER, ignoreCase = true) } + ?.let { headers.remove(it) } + ?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty() + // Nothing may split the request line or header block, whatever the source of a header. + for ((name, value) in headers) { + if (name.isEmpty() || name.any { it.code <= 0x20 || it.code >= 0x7f || it == ':' } || + value.any { it == '\r' || it == '\n' || it == '\u0000' } + ) throw HermesException(HermesException.Kind.InvalidAccessCredentials) + } + if (offered.any { protocol -> protocol.any { it.code <= 0x20 || it.code >= 0x7f || it == ',' } }) { + throw HermesException(HermesException.Kind.InvalidEndpoint) + } + + val observer = HandshakeObserver() + // No extensions: the draft always adds RFC 6455's default one, and no permessage-deflate is configured. + val protocols: List = if (offered.isEmpty()) listOf(Protocol("")) else offered.map { Protocol(it) } + val draft = GatewayDraft(protocols, observer) + val client = SocketClient(uri, draft, headers, observer, listener, request.requiredSubprotocol) + client.connect() + return JavaWebSocketTransport(client) + } +} + +/** What the upgrade response said, noted before the library turns it into an exception message. */ +private class HandshakeObserver { + @Volatile var status: Int? = null + @Volatile var headersTooLarge = false +} + +/** + * The library's RFC 6455 draft with the gateway's bounds: 4 MiB frames and fragment sums, upgrade response + * headers capped (the library otherwise accumulates a never-ending header block without limit), the HTTP + * status recorded so a 401, 403 or redirect keeps its type, and the request written as UTF-8 bytes so a proxy + * header value with non-ASCII text arrives as sent (the library would write a question mark). + */ +private class GatewayDraft( + protocols: List, + private val observer: HandshakeObserver, +) : Draft_6455(emptyList(), protocols, GatewayWebSockets.MAXIMUM_MESSAGE_BYTES) { + + override fun translateHandshake(buf: ByteBuffer): Handshakedata { + val start = buf.position() + val end = buf.limit() + var terminator = -1 + var i = start + while (i + 3 < end) { + if (buf.get(i) == CR && buf.get(i + 1) == LF && buf.get(i + 2) == CR && buf.get(i + 3) == LF) { + terminator = i + break + } + i++ + } + val headerBytes = if (terminator >= 0) terminator + 4 - start else end - start + if (headerBytes > GatewayWebSockets.MAXIMUM_UPGRADE_HEADER_BYTES) { + observer.headersTooLarge = true + throw InvalidHandshakeException("Upgrade response headers are too large") + } + statusLine(buf, start, end)?.let { observer.status = it } + return super.translateHandshake(buf) + } + + /** The status code of an `HTTP/1.x NNN ...` first line, if the line is complete. */ + private fun statusLine(buf: ByteBuffer, start: Int, end: Int): Int? { + var lineEnd = start + while (lineEnd < end && lineEnd - start < 64 && buf.get(lineEnd) != CR && buf.get(lineEnd) != LF) lineEnd++ + if (lineEnd >= end) return null + val line = ByteArray(lineEnd - start) { buf.get(start + it) }.toString(Charsets.ISO_8859_1) + val parts = line.split(' ') + return if (parts.size >= 2 && parts[0].startsWith("HTTP/")) parts[1].toIntOrNull() else null + } + + override fun createHandshake(handshakedata: Handshakedata, withcontent: Boolean): List { + val request = handshakedata as? ClientHandshake ?: throw IllegalArgumentException("Client requests only") + val text = StringBuilder("GET ").append(request.resourceDescriptor).append(" HTTP/1.1\r\n") + val names = request.iterateHttpFields() + while (names.hasNext()) { + val name = names.next() + text.append(name).append(": ").append(request.getFieldValue(name)).append("\r\n") + } + text.append("\r\n") + return listOf(ByteBuffer.wrap(text.toString().toByteArray(Charsets.UTF_8))) + } + + override fun copyInstance(): Draft = GatewayDraft(knownProtocols.map { it.copyInstance() }, observer) + + private companion object { + const val CR: Byte = 13 + const val LF: Byte = 10 + } +} + +private class SocketClient( + uri: URI, + draft: Draft, + headers: Map, + private val observer: HandshakeObserver, + private val listener: GatewayTransportListener, + private val requiredSubprotocol: String?, +) : WebSocketClient(uri, draft, headers, 20_000) { + private val ended = AtomicBoolean(false) + @Volatile private var opened = false + @Volatile private var firstError: Exception? = null + + init { + setDaemon(true) + // The RPC heartbeat is the only liveness check; the library's own ping timer is off. + setConnectionLostTimeout(0) + setTcpNoDelay(true) + // Android's Socket.connect refuses an unresolved address, which is what the library uses by default. + setDnsResolver(DnsResolver { target -> InetAddress.getByName(target.host) }) + } + + override fun onOpen(handshake: ServerHandshake) { + val negotiated = handshake.getFieldValue("Sec-WebSocket-Protocol").ifEmpty { null } + // Nothing was offered, so nothing may be accepted: an extension answer is a protocol violation, and + // the default extension would otherwise take any answer. + if (handshake.hasFieldValue("Sec-WebSocket-Extensions") || + (requiredSubprotocol != null && negotiated != requiredSubprotocol) + ) { + terminate(HermesException(HermesException.Kind.InvalidResponse)) + return + } + opened = true + listener.opened(negotiated) + } + + override fun onMessage(message: String) { + if (!ended.get()) listener.message(message.toByteArray(Charsets.UTF_8)) + } + + override fun onMessage(bytes: ByteBuffer) { + if (ended.get()) return + val copy = ByteArray(bytes.remaining()) + bytes.duplicate().get(copy) + listener.message(copy) + } + + /** The library rejected something (size, UTF-8, framing) and is about to start a close handshake: end it now. */ + override fun onCloseInitiated(code: Int, reason: String?) { + if (code != CloseFrame.NORMAL && code != CloseFrame.GOING_AWAY) terminate(map(code, remote = false)) + } + + override fun onClose(code: Int, reason: String?, remote: Boolean) { + terminate(map(code, remote), closeConnection = false) + } + + override fun onError(ex: Exception) { + if (firstError == null) firstError = ex + } + + /** After a deliberate close nothing more is reported: the owner already knows. */ + fun silence() { + ended.set(true) + } + + private fun terminate(error: HermesException, closeConnection: Boolean = true) { + if (!ended.compareAndSet(false, true)) return + listener.failed(error) + // A rejected stream must not linger half-closed waiting for a peer that may never answer. + if (!closeConnection) return + try { + (connection as? WebSocketImpl)?.closeConnection(CloseFrame.ABNORMAL_CLOSE, "") + } catch (_: RuntimeException) { + // already closed + } + } + + private fun map(code: Int, remote: Boolean): HermesException { + if (!opened) { + if (observer.headersTooLarge) return HermesException(HermesException.Kind.MessageTooLarge) + observer.status?.let { status -> + return HermesException( + when { + status == 401 || status == 403 -> HermesException.Kind.InvalidCredentials + status in 300..399 -> HermesException.Kind.RedirectRefused + status != 101 -> HermesException.Kind.ConnectionFailed + else -> HermesException.Kind.InvalidResponse + }, + ) + } + firstError?.let { return OkHttpHermesHttp.map(it) } + return HermesException( + if (code == CloseFrame.PROTOCOL_ERROR) HermesException.Kind.InvalidResponse else HermesException.Kind.ConnectionFailed, + ) + } + // 1006 is the library's word for "the connection went away", not for a rule that was broken. + if (remote || code == CloseFrame.ABNORMAL_CLOSE) return HermesException(HermesException.Kind.Disconnected) + return HermesException(if (code == CloseFrame.TOOBIG) HermesException.Kind.MessageTooLarge else HermesException.Kind.InvalidResponse) + } +} + +private class JavaWebSocketTransport(private val client: SocketClient) : GatewayTransport { + override val hasBufferedData: Boolean get() = client.hasBufferedData() + + override fun send(text: String): Boolean = try { + client.send(text) + true + } catch (_: RuntimeException) { + false + } + + override fun close(orderly: Boolean) { + client.silence() + try { + if (orderly) { + client.close() + } else { + (client.connection as? WebSocketImpl)?.closeConnection(CloseFrame.ABNORMAL_CLOSE, "") + client.socket?.close() + } + } catch (_: RuntimeException) { + // already closed + } catch (_: IOException) { + // already closed + } + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt new file mode 100644 index 00000000..53dd7103 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt @@ -0,0 +1,134 @@ +package app.bighelp.hermes + +import java.util.Base64 + +// What guards a Hermes address before Hermes itself: a Cloudflare Access service token, a reverse proxy's +// Basic login, or custom proxy headers. These are independent of the Hermes sign-in, are stored separately +// by the app, and travel on every HTTP request and WebSocket upgrade to that one endpoint, never elsewhere. + +/** A proxy gate credential. Secrets never appear in [toString]. */ +class AccessCredential private constructor( + val kind: Kind, + /** The Cloudflare client ID, or the proxy username. */ + val clientId: String, + /** The Cloudflare client secret, or the proxy password. */ + val clientSecret: String, +) { + enum class Kind { CloudflareAccess, ProxyBasic } + + fun headers(): Map = when (kind) { + Kind.CloudflareAccess -> linkedMapOf("CF-Access-Client-Id" to clientId, "CF-Access-Client-Secret" to clientSecret) + Kind.ProxyBasic -> mapOf( + "Authorization" to "Basic " + + Base64.getEncoder().encodeToString("$clientId:$clientSecret".toByteArray(Charsets.UTF_8)), + ) + } + + /** Cloudflare Access is HTTPS only; Basic may also go to an approved private HTTP address. */ + fun canSend(endpoint: HermesEndpoint): Boolean = endpoint.isSecure || kind == Kind.ProxyBasic + + override fun equals(other: Any?) = + other is AccessCredential && kind == other.kind && clientId == other.clientId && clientSecret == other.clientSecret + + override fun hashCode() = (kind.hashCode() * 31 + clientId.hashCode()) * 31 + clientSecret.hashCode() + override fun toString() = "AccessCredential($kind)" + + companion object { + /** Both values trimmed, 1–512 bytes of printable ASCII with no spaces. */ + fun cloudflareAccess(clientId: String, clientSecret: String): AccessCredential { + val id = clientId.trim() + val secret = clientSecret.trim() + if (!headerSafe(id) || !headerSafe(secret)) throw invalid() + return AccessCredential(Kind.CloudflareAccess, id, secret) + } + + /** Username trimmed, 1–256 bytes, no colon or control; the password keeps its spaces, 1–512 bytes. */ + fun proxyBasic(username: String, password: String): AccessCredential { + val user = username.trim() + if (user.isEmpty() || utf8Length(user) > 256 || ':' in user || user.any(::isControl) || + password.isEmpty() || utf8Length(password) > 512 || password.any(::isControl) + ) throw invalid() + return AccessCredential(Kind.ProxyBasic, user, password) + } + + private fun headerSafe(value: String) = value.isNotEmpty() && value.length <= 512 && value.all { it.code in 0x21..0x7e } + private fun isControl(c: Char) = c.code < 0x20 || c.code == 0x7f || c.code in 0x80..0x9f + private fun invalid() = HermesException(HermesException.Kind.InvalidAccessCredentials) + } +} + +class CustomHeaderException(val problem: Problem) : IllegalArgumentException(problem.name) { + enum class Problem { InvalidName, Reserved, InvalidValue, Duplicate, TooMany } +} + +/** A header a proxy in front of Hermes wants, such as `X-Access-Id`. Reserved names are the app's or HTTP's own. */ +class CustomHeader private constructor(val name: String, val value: String) { + override fun equals(other: Any?) = other is CustomHeader && name == other.name && value == other.value + override fun hashCode() = name.hashCode() * 31 + value.hashCode() + override fun toString() = "CustomHeader($name)" + + companion object { + const val MAXIMUM_COUNT = 16 + + fun of(name: String, value: String): CustomHeader { + val trimmedName = name.trim() + val trimmedValue = value.trim() + if (!isToken(trimmedName) || utf8Length(trimmedName) > 128) invalid(CustomHeaderException.Problem.InvalidName) + if (isReserved(trimmedName)) invalid(CustomHeaderException.Problem.Reserved) + if (trimmedValue.isEmpty() || utf8Length(trimmedValue) > 4_096 || + trimmedValue.any { !(it == '\t' || it.code in 0x20..0x7e || it.code >= 0x80) } + ) invalid(CustomHeaderException.Problem.InvalidValue) + return CustomHeader(trimmedName, trimmedValue) + } + + /** Blank rows are skipped; at most 16; names unique ignoring case. */ + fun list(pairs: List>): List { + val filled = pairs.filter { it.first.isNotBlank() || it.second.isNotBlank() } + if (filled.size > MAXIMUM_COUNT) invalid(CustomHeaderException.Problem.TooMany) + val seen = HashSet() + return filled.map { (name, value) -> + of(name, value).also { if (!seen.add(it.name.lowercase())) invalid(CustomHeaderException.Problem.Duplicate) } + } + } + + fun isReserved(name: String): Boolean { + val lower = name.lowercase() + return lower in RESERVED || lower.startsWith("sec-") || lower.startsWith("x-loopdy-") || + lower.startsWith("x-hermes-") || lower.startsWith("cf-access-") + } + + private val RESERVED = setOf( + "host", "authorization", "proxy-authorization", "cookie", "content-type", "content-length", + "content-encoding", "transfer-encoding", "connection", "upgrade", "keep-alive", "te", "expect", + "accept", "accept-encoding", "cache-control", "range", "if-match", "if-none-match", "origin", + ) + + private fun isToken(name: String) = name.isNotEmpty() && + name.all { (it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9') || it in "!#$%&'*+-.^_`|~" } + + private fun invalid(problem: CustomHeaderException.Problem): Nothing = throw CustomHeaderException(problem) + } +} + +/** + * The complete header set for one endpoint's gate. The values hold secrets; [toString] names none of them. + * Applied to every HTTP request and to the WebSocket upgrade explicitly. + */ +class AccessHeaders private constructor(val values: Map) { + override fun toString() = "AccessHeaders(${values.size} headers)" + + companion object { + val none = AccessHeaders(emptyMap()) + + /** @throws HermesException [HermesException.Kind.InvalidAccessCredentials] if [credential] cannot go to [endpoint]. */ + fun of(endpoint: HermesEndpoint, credential: AccessCredential?, custom: List): AccessHeaders { + if (credential != null && !credential.canSend(endpoint)) { + throw HermesException(HermesException.Kind.InvalidAccessCredentials) + } + val values = LinkedHashMap() + credential?.let { values.putAll(it.headers()) } + custom.forEach { values[it.name] = it.value } + return AccessHeaders(values) + } + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt new file mode 100644 index 00000000..70a93e32 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt @@ -0,0 +1,94 @@ +package app.bighelp.hermes + +/** + * Literal IP syntax only. Nothing here touches `java.net.InetAddress`, so no host name is ever resolved + * and DNS can never decide whether plain HTTP is allowed. + */ +internal object HermesAddress { + /** Strict dotted-decimal: four parts, 0–255, no leading zeros. `127.1`, `0x7f.0.0.1` and integers fail. */ + fun parseIPv4(text: String): ByteArray? { + val parts = text.split('.') + if (parts.size != 4) return null + val bytes = ByteArray(4) + for ((index, part) in parts.withIndex()) { + if (part.isEmpty() || part.length > 3 || !part.all { it in '0'..'9' }) return null + if (part.length > 1 && part[0] == '0') return null + val value = part.toInt() + if (value > 255) return null + bytes[index] = value.toByte() + } + return bytes + } + + /** RFC 4291 text forms with `::` and a trailing dotted quad. No zone ID, no brackets. */ + fun parseIPv6(text: String): ByteArray? { + if (text.isEmpty() || !text.all { it == ':' || it == '.' || Character.digit(it, 16) >= 0 && it.code < 0x80 }) { + return null + } + val gap = text.indexOf("::") + if (gap >= 0 && text.indexOf("::", gap + 1) >= 0) return null + val head = if (gap >= 0) text.substring(0, gap) else text + val tail = if (gap >= 0) text.substring(gap + 2) else "" + // The dotted quad may only close the address: the tail when there is a "::", else the whole text. + val headWords = words(head, allowIPv4 = gap < 0) ?: return null + val tailWords = words(tail, allowIPv4 = gap >= 0) ?: return null + val total = headWords.size + tailWords.size + if (gap >= 0) { if (total > 7) return null } else if (total != 8) return null + val all = headWords + List(8 - total) { 0 } + tailWords + return ByteArray(16) { (all[it / 2] shr (if (it % 2 == 0) 8 else 0)).toByte() } + } + + private fun words(part: String, allowIPv4: Boolean): List? { + if (part.isEmpty()) return emptyList() + val pieces = part.split(':') + val result = ArrayList() + for ((index, piece) in pieces.withIndex()) { + if ('.' in piece) { + if (!allowIPv4 || index != pieces.lastIndex) return null + val quad = parseIPv4(piece) ?: return null + result += ((quad[0].toInt() and 0xff) shl 8) or (quad[1].toInt() and 0xff) + result += ((quad[2].toInt() and 0xff) shl 8) or (quad[3].toInt() and 0xff) + } else { + if (piece.isEmpty() || piece.length > 4) return null + result += piece.toInt(16) + } + } + return result + } + + /** Names that only resolve inside a private network; a Tailscale Funnel name is public only over HTTPS. */ + private val privateNameSuffixes = listOf( + "local", "lan", "internal", "home.arpa", "intranet", "corp", "localdomain", "private", + "localhost", "ts.net", "beta.tailscale.net", + ) + + /** + * Plain HTTP stays on a network the person controls: this device, home or office Wi-Fi, a VPN or + * Tailscale. IPv4-mapped and link-local IPv6 forms are deliberately not included. + */ + fun isPrivateNetworkHost(host: String): Boolean { + val name = host.lowercase() + parseIPv4(name)?.let { return isPrivateIPv4(it) } + parseIPv6(name)?.let { return isLoopbackOrUniqueLocalIPv6(it) } + // A single-label name ("hermes") never leaves the local resolver. + if ('.' !in name) return true + return privateNameSuffixes.any { name.endsWith(".$it") } + } + + private fun isPrivateIPv4(address: ByteArray): Boolean { + val a = address[0].toInt() and 0xff + val b = address[1].toInt() and 0xff + return a == 127 || // loopback + a == 10 || // 10.0.0.0/8 + (a == 172 && b in 16..31) || // 172.16.0.0/12 + (a == 192 && b == 168) || // 192.168.0.0/16 + (a == 100 && b in 64..127) || // 100.64.0.0/10 (Tailscale, CGNAT) + (a == 169 && b == 254) // link-local + } + + private fun isLoopbackOrUniqueLocalIPv6(address: ByteArray): Boolean { + val loopback = address.take(15).all { it.toInt() == 0 } && address[15].toInt() == 1 + // fc00::/7 unique local, which includes Tailscale's fd7a:115c:a1e0::/48. + return loopback || (address[0].toInt() and 0xfe) == 0xfc + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt new file mode 100644 index 00000000..7e053a85 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt @@ -0,0 +1,231 @@ +package app.bighelp.hermes + +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.util.Locale +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** Pure, bounded readers of what the host sends during sign-in. Nothing here does I/O. */ +internal object HermesAuthParsers { + private const val MAXIMUM_BOOTSTRAP_BYTES = 1_048_576 + private val SCRIPT = Regex("""]*>([\s\S]*?)""", RegexOption.IGNORE_CASE) + // A lookbehind, not a consumed `;`: two assignments in a row must both be seen. + private val MODE_ASSIGNMENT = Regex("""(?<=^|;)\s*window\.__HERMES_AUTH_REQUIRED__\s*=\s*(true|false)\s*;""") + private const val TOKEN_NAME = "window.__HERMES_SESSION_TOKEN__" + private const val MAXIMUM_TOKEN_LITERAL = 65_536 + + private fun invalid() = HermesException(HermesException.Kind.InvalidResponse) + + /** + * Inert `window.__HERMES_SESSION_TOKEN__` assignment of an ungated dashboard page. Only `" }}" + + private fun token(html: String) = HermesAuthParsers.dashboardToken(html.toByteArray()) + + @Test fun bootstrapReadsTheOneTokenAndTheUngatedMarker() { + assertEquals( + "synthetic-dashboard-token", + token(page("window.__HERMES_SESSION_TOKEN__ = \"synthetic-dashboard-token\";\nwindow.__HERMES_AUTH_REQUIRED__ = false;")), + ) + assertEquals( + "Whitespace and separate script elements are fine", + "abc", + token(page(" window.__HERMES_SESSION_TOKEN__=\"abc\" ;", "x=1; window.__HERMES_AUTH_REQUIRED__=false;")), + ) + assertEquals("a\"b", token(page("window.__HERMES_SESSION_TOKEN__=\"a\\u0022b\";window.__HERMES_AUTH_REQUIRED__=false;"))) + assertEquals("tok", token("")) + } + + @Test fun bootstrapRefusesAnythingButExactlyOneTokenInAScriptAndAFalseMarker() { + val marker = "window.__HERMES_AUTH_REQUIRED__=false;" + val unsupported = HermesException.Kind.UnsupportedAuthentication + assertEquals("no token", unsupported, kind { token(page(marker)) }) + assertEquals("no marker", unsupported, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"t\";")) }) + assertEquals("gated page", unsupported, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"t\";window.__HERMES_AUTH_REQUIRED__=true;")) }) + assertEquals("two tokens", unsupported, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"a\";window.__HERMES_SESSION_TOKEN__=\"b\";$marker")) }) + assertEquals("two markers", unsupported, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"a\";$marker$marker")) }) + assertEquals( + "only a script element counts", + unsupported, + kind { token(page(marker, outside = "

window.__HERMES_SESSION_TOKEN__=\"t\";

")) }, + ) + assertEquals("an unrelated variable", unsupported, kind { token(page("window.OTHER=\"t\";$marker")) }) + assertEquals( + "a token assignment embedded in other code is not a bare assignment", + unsupported, + kind { token(page("var x = {a: window.__HERMES_SESSION_TOKEN__=\"t\";};$marker")) }, + ) + } + + @Test fun bootstrapValidatesTheTokenAndTheBytes() { + val marker = "window.__HERMES_AUTH_REQUIRED__=false;" + assertEquals(HermesException.Kind.InvalidCredentials, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"has space\";$marker")) }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"\";$marker")) }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"${"x".repeat(16_385)}\";$marker")) }) + assertEquals(invalid, kind { token(page("window.__HERMES_SESSION_TOKEN__=\"\\x\";$marker")) }) + assertEquals(invalid, kind { HermesAuthParsers.dashboardToken(byteArrayOf(0xC3.toByte(), 0x28)) }) + assertEquals(invalid, kind { HermesAuthParsers.dashboardToken(ByteArray(1_048_577) { 'a'.code.toByte() }) }) + } + + // Status + + @Test fun statusRequiresABooleanAndBoundsTheFlows() { + val none = HermesAuthParsers.status(obj("""{"auth_required":false}""")) + assertEquals(false, none.authRequired) + assertEquals(emptyList(), none.flows) + assertEquals(emptyList(), HermesAuthParsers.status(obj("""{"auth_required":true,"auth_flows":null}""")).flows) + val gated = HermesAuthParsers.status(obj("""{"auth_required":true,"auth_flows":["cookie","native_pkce","future-flow"],"other":1}""")) + assertEquals(listOf("cookie", "native_pkce", "future-flow"), gated.flows) + assertEquals(true, gated.supportsNativePkce) + assertEquals("Not offered on an ungated host", false, HermesAuthParsers.status(obj("""{"auth_required":false,"auth_flows":["native_pkce"]}""")).supportsNativePkce) + assertEquals("Exact string only", false, HermesAuthParsers.status(obj("""{"auth_required":true,"auth_flows":["Native_PKCE"]}""")).supportsNativePkce) + + listOf( + """{}""", """{"auth_required":"true"}""", """{"auth_required":1}""", """{"auth_required":null}""", + """{"auth_required":true,"auth_flows":"native_pkce"}""", """{"auth_required":true,"auth_flows":[1]}""", + """{"auth_required":true,"auth_flows":[""]}""", """{"auth_required":true,"auth_flows":["a","a"]}""", + """{"auth_required":true,"auth_flows":["${"f".repeat(129)}"]}""", + """{"auth_required":true,"auth_flows":[${(1..33).joinToString { "\"f$it\"" }}]}""", + ).forEach { assertEquals(it, invalid, kind { HermesAuthParsers.status(obj(it)) }) } + HermesAuthParsers.status(obj("""{"auth_required":true,"auth_flows":[${(1..32).joinToString { "\"f$it\"" }},]}""".replace(",]", "]"))) + HermesAuthParsers.status(obj("""{"auth_required":true,"auth_flows":["${"f".repeat(128)}"]}""")) + } + + @Test fun providersAreBoundedAndUnique() { + val list = HermesAuthParsers.providers(obj("""{"providers":[{"name":"basic","display_name":"Password","supports_password":true},{"name":"sso","supports_password":false}]}""")) + assertEquals(listOf(AuthProvider("basic", "Password", true), AuthProvider("sso", "sso", false)), list) + listOf( + """{}""", """{"providers":{}}""", + """{"providers":[{"name":"a","supports_password":"yes"}]}""", """{"providers":[{"name":"a"}]}""", + """{"providers":[{"name":"","supports_password":true}]}""", """{"providers":[{"name":"a b","supports_password":true}]}""", + """{"providers":[{"name":"é","supports_password":true}]}""", """{"providers":[{"name":"${"n".repeat(257)}","supports_password":true}]}""", + """{"providers":[{"name":"a","supports_password":true},{"name":"a","supports_password":false}]}""", + """{"providers":[{"name":"a","display_name":"","supports_password":true}]}""", + """{"providers":[{"name":"a","display_name":"x\u0007y","supports_password":true}]}""", + """{"providers":[{"name":"a","display_name":"${"d".repeat(513)}","supports_password":true}]}""", + """{"providers":[${(1..65).joinToString { "{\"name\":\"p$it\",\"supports_password\":true}" }}]}""", + """{"providers":[7]}""", + ).forEach { assertEquals(it.take(60), invalid, kind { HermesAuthParsers.providers(obj(it)) }) } + assertEquals(64, HermesAuthParsers.providers(obj("""{"providers":[${(1..64).joinToString { "{\"name\":\"p$it\",\"supports_password\":true}" }}]}""")).size) + } + + // PKCE cookie + + private val now = 1_800_000_000L + private val httpsRoot = HermesEndpoint.parse("hermes.example") + private val httpsPrefix = HermesEndpoint.parse("hermes.example/hermes") + private val httpRoot = HermesEndpoint.parse("http://192.168.1.5:9119", allowPrivateHttp = true) + private val httpPrefix = HermesEndpoint.parse("http://192.168.1.5:9119/hermes", allowPrivateHttp = true) + + private fun cookie(endpoint: HermesEndpoint, vararg headers: String) = HermesAuthParsers.pkceCookie(headers.toList(), endpoint, now) + private val future = "Max-Age=600" + + @Test fun theCookieNameAndPathFollowTheSchemeAndPrefix() { + assertEquals("__Host-hermes_session_pkce=abc_-=", cookie(httpsRoot, "__Host-hermes_session_pkce=abc_-=; Path=/; Secure; HttpOnly; SameSite=None; $future")) + assertEquals("__Secure-hermes_session_pkce=abc", cookie(httpsPrefix, "__Secure-hermes_session_pkce=abc; Path=/hermes; Secure; $future")) + assertEquals("hermes_session_pkce=abc", cookie(httpRoot, "hermes_session_pkce=abc; Path=/; $future")) + assertEquals("hermes_session_pkce=abc", cookie(httpPrefix, "hermes_session_pkce=abc; Path=/hermes; HttpOnly; $future")) + listOf( + httpsRoot to "hermes_session_pkce=abc; Path=/; Secure; $future", + httpsRoot to "__Secure-hermes_session_pkce=abc; Path=/; Secure; $future", + httpsPrefix to "__Host-hermes_session_pkce=abc; Path=/hermes; Secure; $future", + httpRoot to "__Host-hermes_session_pkce=abc; Path=/; $future", + httpsRoot to "__Host-hermes_session_pkce=abc; Path=/hermes; Secure; $future", + httpsPrefix to "__Secure-hermes_session_pkce=abc; Path=/; Secure; $future", + httpPrefix to "hermes_session_pkce=abc; Path=/; $future", + httpRoot to "hermes_session_pkce=abc; Path=/hermes; $future", + httpRoot to "hermes_session_pkce=abc; $future", + httpRoot to "hermes_session_pkce=abc; Path=/Hermes; $future", + ).forEach { (endpoint, header) -> assertEquals(header, invalid, kind { cookie(endpoint, header) }) } + } + + @Test fun theCookieMustBeSecureUnexpiredAndAboutTheEndpointHost() { + assertEquals(invalid, kind { cookie(httpsRoot, "__Host-hermes_session_pkce=a; Path=/; $future") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Max-Age=0") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Max-Age=-5") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Max-Age=soon") }) + assertEquals("An explicit future Expires counts", "hermes_session_pkce=a", + cookie(httpRoot, "hermes_session_pkce=a; Path=/; Expires=Wed, 13 Dec 2028 08:00:00 GMT")) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Expires=Wed, 01 Jan 2020 00:00:00 GMT") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Expires=not-a-date") }) + assertEquals("Max-Age wins over Expires", invalid, + kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Max-Age=0; Expires=Wed, 13 Dec 2028 08:00:00 GMT") }) + + assertEquals("hermes_session_pkce=a", cookie(httpRoot, "hermes_session_pkce=a; Path=/; Domain=192.168.1.5; $future")) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Domain=evil.example; $future") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a; Path=/; Domain=.192.168.1.5; $future") }) + val ipv6 = HermesEndpoint.parse("http://[fd00::1]:9119", allowPrivateHttp = true) + assertEquals("hermes_session_pkce=a", cookie(ipv6, "hermes_session_pkce=a; Path=/; Domain=[FD00::1]; $future")) + } + + @Test fun theCookieValueIsBoundedAndTheSelectionIsExact() { + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=; Path=/; $future") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a b; Path=/; $future") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=a+b; Path=/; $future") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=\"abc\"; Path=/; $future") }) + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=é; Path=/; $future") }) + cookie(httpRoot, "hermes_session_pkce=${"A".repeat(8_192)}; Path=/; $future") + assertEquals(invalid, kind { cookie(httpRoot, "hermes_session_pkce=${"A".repeat(8_193)}; Path=/; $future") }) + + assertEquals("No cookie at all", invalid, kind { cookie(httpRoot) }) + assertEquals("Look-alike names are not accepted", invalid, kind { cookie(httpRoot, "hermes_session_pkce2=a; Path=/; $future", "x_hermes_session_pkce=a; Path=/; $future") }) + assertEquals("Two cookies of the name", invalid, kind { + cookie(httpRoot, "hermes_session_pkce=a; Path=/; $future", "hermes_session_pkce=b; Path=/; $future") + }) + assertEquals( + "Other cookies are ignored, never imported", + "hermes_session_pkce=a", + cookie(httpRoot, "other=1; Path=/", "hermes_session_pkce=a; Path=/; $future", "hermes_session_at=secret; Path=/"), + ) + } + + // Token responses + + private val endpoint = HermesEndpoint.parse("hermes.example/p") + private fun session(json: String, nowMillis: Long = now * 1_000) = HermesAuthParsers.nativeSession(obj(json), endpoint, nowMillis) + private fun good(vararg overrides: Pair): String { + val fields = linkedMapOf( + "token_type" to "\"Bearer\"", "access_token" to "\"access-1\"", "refresh_token" to "\"refresh-1\"", + "provider" to "\"basic\"", "user_id" to "\"synthetic-user\"", "expires_at" to "${now + 3_600}", + ) + overrides.forEach { fields[it.first] = it.second } + return fields.entries.joinToString(prefix = "{", postfix = "}") { "\"${it.key}\":${it.value}" } + } + + @Test fun aTokenResponseBecomesABearerConnection() { + val saved = session(good()) + assertEquals(StoredAuth.Bearer("access-1", "refresh-1", now + 3_600), saved.auth) + assertEquals("basic", saved.provider) + assertEquals("synthetic-user", saved.userId) + assertEquals(endpoint, saved.endpoint) + assertNull("An empty refresh token is no refresh capability", (session(good("refresh_token" to "\"\"")).auth as StoredAuth.Bearer).refreshToken) + assertNull((session(good("refresh_token" to "null")).auth as StoredAuth.Bearer).refreshToken) + assertEquals("A fractional expiry keeps its whole second", now + 3_600, (session(good("expires_at" to "${now + 3_600}.75")).auth as StoredAuth.Bearer).expiresAtEpochSeconds) + } + + @Test fun aTokenResponseThatIsNotExactlyRightIsRefused() { + listOf( + good("token_type" to "\"bearer\""), good("token_type" to "\"Basic\""), good("token_type" to "null"), + good("access_token" to "\"\""), good("access_token" to "\"has space\""), good("access_token" to "12"), + good("access_token" to "\"${"x".repeat(16_385)}\""), good("refresh_token" to "\"has space\""), + good("provider" to "\"\""), good("provider" to "null"), good("user_id" to "\"\""), good("user_id" to "5"), + good("provider" to "\" padded\""), good("user_id" to "\"tab\\t\""), good("provider" to "\"${"p".repeat(129)}\""), + good("user_id" to "\"${"u".repeat(513)}\""), + good("expires_at" to "${now}"), good("expires_at" to "${now - 1}"), good("expires_at" to "\"${now + 60}\""), good("expires_at" to "null"), + "{}", + ).forEach { + val failure = assertThrows(it, HermesException::class.java) { session(it) } + assertEquals(it, invalid, failure.kind) + } + session(good("provider" to "\"${"p".repeat(128)}\"", "user_id" to "\"${"u".repeat(512)}\"")) + } + + @Test fun ticketsAreBoundedAndUrlSafe() { + assertEquals("abc_-DEF123", HermesAuthParsers.ticket(obj("""{"ticket":"abc_-DEF123","ttl_seconds":30}"""))) + assertEquals("a", HermesAuthParsers.ticket(obj("""{"ticket":"a","ttl_seconds":300}"""))) + assertEquals("a", HermesAuthParsers.ticket(obj("""{"ticket":"a","ttl_seconds":0.5}"""))) + listOf( + """{"ticket":"a"}""", """{"ticket":"","ttl_seconds":30}""", """{"ticket":"a b","ttl_seconds":30}""", """{"ticket":"a.b","ttl_seconds":30}""", + """{"ticket":"é","ttl_seconds":30}""", """{"ticket":"${"t".repeat(4_097)}","ttl_seconds":30}""", """{"ticket":5,"ttl_seconds":30}""", + """{"ticket":"a","ttl_seconds":0}""", """{"ticket":"a","ttl_seconds":-1}""", """{"ticket":"a","ttl_seconds":301}""", + """{"ticket":"a","ttl_seconds":"30"}""", """{"ticket":"a","ttl_seconds":null}""", + ).forEach { assertEquals(it, invalid, kind { HermesAuthParsers.ticket(obj(it)) }) } + HermesAuthParsers.ticket(obj("""{"ticket":"${"t".repeat(4_096)}","ttl_seconds":30}""")) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorBrowserTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorBrowserTest.kt new file mode 100644 index 00000000..6352c699 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorBrowserTest.kt @@ -0,0 +1,203 @@ +package app.bighelp.hermes + +import java.net.ConnectException +import java.net.InetAddress +import java.net.Socket +import java.security.MessageDigest +import java.util.Base64 +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.SocketPolicy +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Browser PKCE end to end with a real loopback listener; the launcher plays the person's browser. */ +class HermesAuthenticatorBrowserTest { + private val host = ScriptedHost("/hermes") + private val store = InMemoryCredentialStore() + private val clock = TestClock(java.time.Instant.ofEpochSecond(1_800_000_000)) + private val now = 1_800_000_000L + private val resources = mutableListOf() + + @After fun stop() { + resources.forEach { it.close() } + host.close() + } + + private fun authenticator(browser: BrowserLauncher?, timings: AuthTimings = AuthTimings()) = + HermesAuthenticator(host.endpoint, OkHttpHermesHttp(host.endpoint).also { resources += it }, store, browser, clock, timings = timings) + .also { resources += it } + + private fun kind(block: suspend () -> Unit) = assertThrows(HermesException::class.java) { runBlocking { block() } }.kind + + private fun gatedHost( + token: MockResponse = tokenReply(), + me: MockResponse = ScriptedHost.json("""{"provider":"basic","user_id":"synthetic-user"}"""), + ) { + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":true,"auth_flows":["native_pkce"]}""")) + host.on("GET", "/api/auth/providers", ScriptedHost.json("""{"providers":[{"name":"basic","supports_password":true},{"name":"sso","supports_password":false}]}""")) + host.on("POST", "/auth/native/token", token) + host.on("GET", "/api/auth/me", me) + } + + private fun tokenReply(provider: String = "basic") = + ScriptedHost.json("""{"token_type":"Bearer","access_token":"access-1","refresh_token":"refresh-1","provider":"$provider","user_id":"synthetic-user","expires_at":${now + 3_600}}""") + + private fun challenge(verifier: String) = Base64.getUrlEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray())) + + /** The "browser": parses the authorize URL and delivers the host's redirect to the loopback listener. */ + private fun browserReturning(code: String = "browser-code", seen: (okhttp3.HttpUrl) -> Unit = {}) = BrowserLauncher { url -> + val authorize = url.toHttpUrl() + seen(authorize) + val callback = authorize.queryParameter("redirect_uri")!!.toHttpUrl() + val state = authorize.queryParameter("state")!! + Socket(InetAddress.getByName("127.0.0.1"), callback.port).use { socket -> + socket.getOutputStream().write("GET ${callback.encodedPath}?state=$state&code=$code HTTP/1.1\r\nHost: 127.0.0.1:${callback.port}\r\n\r\n".toByteArray()) + socket.getInputStream().readBytes() + } + } + + @Test fun browserSignInUsesALoopbackRedirectAndExchangesTheCodeOnce() = runBlocking { + gatedHost() + var authorize: okhttp3.HttpUrl? = null + val staged = authenticator(browserReturning { authorize = it }).signIn(SignInInput.Browser(provider = null)) + + val url = authorize!! + assertEquals("/hermes/auth/native/authorize", url.encodedPath) + assertEquals(setOf("code_challenge", "code_challenge_method", "redirect_uri", "state"), url.queryParameterNames) + assertEquals("S256", url.queryParameter("code_challenge_method")) + val redirect = url.queryParameter("redirect_uri")!!.toHttpUrl() + assertEquals("http", redirect.scheme) + assertEquals("127.0.0.1", redirect.host) + assertTrue(redirect.encodedPath.matches(Regex("/loopdy-native-callback/[A-Za-z0-9_-]{43}"))) + assertTrue(Regex("[A-Za-z0-9_-]{43}").matches(url.queryParameter("state")!!)) + + val exchange = Json.parseToJsonElement(host.callsTo("/auth/native/token").single().body.readUtf8()).jsonObject + assertEquals(setOf("code", "code_verifier"), exchange.keys) + assertEquals("browser-code", exchange["code"]!!.jsonPrimitive.content) + assertEquals(challenge(exchange["code_verifier"]!!.jsonPrimitive.content), url.queryParameter("code_challenge")) + assertEquals(listOf("GET /api/status", "GET /api/auth/providers", "POST /auth/native/token", "GET /api/auth/me"), host.calls) + assertEquals(StoredAuth.Bearer("access-1", "refresh-1", now + 3_600), staged.auth) + assertNull("Nothing is stored until the gateway is ready", store.load(staged.authority)) + assertFalse("No cookie was ever sent", host.requests.any { it.getHeader("Cookie") != null }) + assertThrows("The listener is gone", ConnectException::class.java) { + Socket(InetAddress.getByName("127.0.0.1"), redirect.port).close() + } + Unit + } + + @Test fun anExplicitProviderIsPassedAndCheckedAgainstTheToken() = runBlocking { + gatedHost(token = tokenReply(provider = "basic")) + var authorize: okhttp3.HttpUrl? = null + authenticator(browserReturning { authorize = it }).signIn(SignInInput.Browser("basic")) + assertEquals("basic", authorize!!.queryParameter("provider")) + + gatedHost(token = tokenReply(provider = "other")) + assertEquals(HermesException.Kind.IdentityChanged, kind { authenticator(browserReturning()).signIn(SignInInput.Browser("basic")) }) + gatedHost(me = ScriptedHost.json("""{"provider":"basic","user_id":"someone-else"}""")) + assertEquals("/api/auth/me must agree with the token", HermesException.Kind.IdentityChanged, kind { authenticator(browserReturning()).signIn(SignInInput.Browser(null)) }) + } + + @Test fun aProviderThatIsNotPrintableAsciiNeverStartsABrowser() { + gatedHost() + var opened = false + val launcher = BrowserLauncher { opened = true } + listOf("", "has space", "é", "p".repeat(129)).forEach { + assertEquals(HermesException.Kind.UnsupportedAuthentication, kind { authenticator(launcher).signIn(SignInInput.Browser(it)) }) + } + assertFalse(opened) + } + + @Test fun withoutALauncherOrWhenItFailsTheBrowserIsUnavailableAndNothingElseHappens() { + gatedHost() + assertEquals(HermesException.Kind.BrowserAuthenticationUnavailable, kind { authenticator(null).signIn(SignInInput.Browser(null)) }) + assertEquals( + HermesException.Kind.BrowserAuthenticationUnavailable, + kind { authenticator(BrowserLauncher { throw IllegalStateException("no custom tabs https://secret") }).signIn(SignInInput.Browser(null)) }, + ) + assertTrue(host.callsTo("/auth/native/token").isEmpty()) + } + + @Test fun strayRequestsAreIgnoredUntilTheRealRedirectArrives() = runBlocking { + gatedHost() + val launcher = BrowserLauncher { url -> + val authorize = url.toHttpUrl() + val callback = authorize.queryParameter("redirect_uri")!!.toHttpUrl() + fun send(target: String) = runCatching { + Socket(InetAddress.getByName("127.0.0.1"), callback.port).use { + it.getOutputStream().write("GET $target HTTP/1.1\r\nHost: 127.0.0.1:${callback.port}\r\n\r\n".toByteArray()) + it.getInputStream().readBytes() + } + } + send("/favicon.ico") + send("${callback.encodedPath}?state=WRONG&code=attacker-code") + send("${callback.encodedPath}?state=${authorize.queryParameter("state")}&code=real-code") + } + authenticator(launcher).signIn(SignInInput.Browser(null)) + assertEquals("real-code", Json.parseToJsonElement(host.callsTo("/auth/native/token").single().body.readUtf8()).jsonObject["code"]!!.jsonPrimitive.content) + } + + @Test fun cancellingWhileTheBrowserIsOpenClosesTheListenerAndStagesNothing() = runBlocking { + gatedHost() + val opened = CompletableDeferred() + val launcher = BrowserLauncher { url -> + opened.complete(url.toHttpUrl().queryParameter("redirect_uri")!!.toHttpUrl().port) + delay(60_000) + } + val authenticator = authenticator(launcher) + val attempt = async { authenticator.signIn(SignInInput.Browser(null)) } + val port = opened.await() + attempt.cancel() + assertThrows(CancellationException::class.java) { runBlocking { attempt.await() } } + var refused = false + repeat(50) { if (!refused) { refused = runCatching { Socket(InetAddress.getByName("127.0.0.1"), port).close() }.isFailure; if (!refused) delay(20) } } + assertTrue("The port stopped listening", refused) + assertNull(authenticator.savedConnection) + assertTrue(host.callsTo("/auth/native/token").isEmpty()) + } + + @Test fun cancelAuthenticationEndsABrowserWait() = runBlocking { + gatedHost() + val opened = CompletableDeferred() + val authenticator = authenticator(BrowserLauncher { opened.complete(Unit); delay(60_000) }) + val attempt = async { runCatching { authenticator.signIn(SignInInput.Browser(null)) }.exceptionOrNull() } + opened.await() + authenticator.cancelAuthentication() + assertEquals(HermesException.Kind.Cancelled, (attempt.await() as HermesException).kind) + } + + @Test fun theWholeSignInIsBoundedByTheBrowserDeadline() { + gatedHost() + val timings = AuthTimings(browserSignInMillis = 300) + assertEquals(HermesException.Kind.TimedOut, kind { authenticator(BrowserLauncher { }, timings).signIn(SignInInput.Browser(null)) }) + assertTrue(host.callsTo("/auth/native/token").isEmpty()) + } + + @Test fun aLostTokenExchangeIsUncertainAndTheCodeIsNeverSentAgain() { + gatedHost(token = MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)) + val failure = assertThrows(HermesException::class.java) { runBlocking { authenticator(browserReturning()).signIn(SignInInput.Browser(null)) } } + assertEquals(HermesException.Kind.NativeTokenExchangeUncertain, failure.kind) + assertTrue(failure.outcomeUnknown) + assertEquals(1, host.callsTo("/auth/native/token").size) + + gatedHost(token = ScriptedHost.json("not json")) + assertEquals("A malformed answer after sending is uncertain too", HermesException.Kind.NativeTokenExchangeUncertain, + kind { authenticator(browserReturning()).signIn(SignInInput.Browser(null)) }) + gatedHost(token = MockResponse().setResponseCode(401)) + assertEquals("A clear refusal is just a refusal", HermesException.Kind.InvalidCredentials, + kind { authenticator(browserReturning()).signIn(SignInInput.Browser(null)) }) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSessionTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSessionTest.kt new file mode 100644 index 00000000..a83883db --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSessionTest.kt @@ -0,0 +1,521 @@ +package app.bighelp.hermes + +import java.io.IOException +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.SocketPolicy +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Rotation, compare-and-replace, restore, commit, authenticated resend and gateway credentials against a + * scripted loopback host. One store is shared between authenticators to model concurrent copies. + */ +class HermesAuthenticatorSessionTest { + private val host = ScriptedHost("/hermes") + private val store = InMemoryCredentialStore() + private val clock = TestClock(java.time.Instant.ofEpochSecond(1_800_000_000)) + private val now = 1_800_000_000L + private val resources = mutableListOf() + + @After fun stop() { + resources.forEach { it.close() } + host.close() + } + + private fun make(timings: AuthTimings = AuthTimings(), access: AccessHeaders = AccessHeaders.none): HermesAuthenticator = + HermesAuthenticator(host.endpoint, OkHttpHermesHttp(host.endpoint, access).also { resources += it }, store, null, clock, timings = timings) + .also { resources += it } + + private fun bearer(access: String = "old-access", refresh: String? = "refresh-1", expires: Long? = now - 60, user: String = "synthetic-user") = + SavedConnection(host.endpoint, StoredAuth.Bearer(access, refresh, expires), "basic", user) + + private fun dashboard(token: String = "old-dash", automatic: Boolean = true) = + SavedConnection(host.endpoint, StoredAuth.DashboardSession(token, automatic), null, null) + + /** An authenticator on a record already in the store, the way a reconnect or relaunch finds it. */ + private suspend fun restored(saved: SavedConnection, timings: AuthTimings = AuthTimings()): HermesAuthenticator { + if (store.load(saved.authority) != saved) store.replace(store.load(saved.authority), saved) + return make(timings).also { it.adoptForTest(saved, persisted = true) } + } + + private fun kind(block: suspend () -> Unit) = assertThrows(HermesException::class.java) { runBlocking { block() } }.kind + + private fun renewed(refresh: String? = "refresh-2", access: String = "new-access", user: String = "synthetic-user", provider: String = "basic", expires: Long = now + 3_600) = + ScriptedHost.json("""{"token_type":"Bearer","access_token":"$access","refresh_token":${refresh?.let { "\"$it\"" } ?: "null"},"provider":"$provider","user_id":"$user","expires_at":$expires}""") + + private val ping = HermesHttpRequest("/api/plugins/loopdy/native/context", maximumResponseBytes = 16_384) + + private fun pingRoute() = host.on("GET", "/api/plugins/loopdy/native/context") { request -> + if (request.getHeader("Authorization") == "Bearer new-access") ScriptedHost.json("{}") else MockResponse().setResponseCode(401) + } + + private fun refreshBodies() = host.callsTo("/auth/native/refresh").map { it.body.snapshot().utf8() } + + // Proactive and reactive renewal + + @Test fun anExpiringTokenIsRenewedBeforeTheRequestAndTheRecordIsReplacedDurably() = runBlocking { + host.on("POST", "/auth/native/refresh", renewed()) + pingRoute() + val saved = bearer(expires = now + 20) // inside the 30 s lead + val authenticator = restored(saved) + assertEquals(200, authenticator.authenticated(ping).status) + assertEquals(listOf("POST /auth/native/refresh", "GET /api/plugins/loopdy/native/context"), host.calls) + assertEquals("""{"refresh_token":"refresh-1","provider":"basic"}""", refreshBodies().single()) + val rotated = SavedConnection(host.endpoint, StoredAuth.Bearer("new-access", "refresh-2", now + 3_600), "basic", "synthetic-user") + assertEquals(rotated, store.load(saved.authority)) + assertEquals(rotated, authenticator.savedConnection) + } + + @Test fun aTokenOutsideTheLeadWindowIsNotRenewed() = runBlocking { + host.on("GET", "/api/plugins/loopdy/native/context", ScriptedHost.json("{}")) + val authenticator = restored(bearer(expires = now + 31)) + authenticator.authenticated(ping) + assertEquals(listOf("GET /api/plugins/loopdy/native/context"), host.calls) + assertEquals("Bearer old-access", host.requests.single().getHeader("Authorization")) + } + + @Test fun manyConcurrentRequestsShareOneRenewalFlight() = runBlocking { + host.on("POST", "/auth/native/refresh") { renewed().setBodyDelay(300, TimeUnit.MILLISECONDS) } + pingRoute() + val authenticator = restored(bearer()) + val results = (1..6).map { async { authenticator.authenticated(ping).status } }.awaitAll() + assertEquals(List(6) { 200 }, results) + assertEquals("Exactly one refresh went out", 1, host.callsTo("/auth/native/refresh").size) + assertEquals(6, host.callsTo("/api/plugins/loopdy/native/context").size) + } + + @Test fun aRenewalNeverStartsIfTheStoredRecordIsNoLongerTheOneInMemory() = runBlocking { + val saved = bearer() + val authenticator = restored(saved) + val newer = bearer(access = "newer", refresh = "refresh-9", expires = now + 600) + store.replace(saved, newer) + host.on("POST", "/auth/native/refresh", renewed()) + assertEquals(HermesException.Kind.SecureStorageChanged, kind { authenticator.authenticated(ping) }) + assertEquals("The rotated token another copy saved was never resent", 0, host.callsTo("/auth/native/refresh").size) + assertEquals(newer, store.load(saved.authority)) + } + + @Test fun aRejectedRenewalAsksForANewSignInAndWritesNothingEveryTime() = runBlocking { + host.on("POST", "/auth/native/refresh", ScriptedHost.json("""{"error":"session_expired"}""", 401)) + val saved = bearer() + val authenticator = restored(saved) + repeat(2) { assertEquals(HermesException.Kind.AuthenticationRequired, kind { authenticator.authenticated(ping) }) } + assertEquals("Hermes was asked each time; the person is not left waiting on a hidden pause", 2, host.callsTo("/auth/native/refresh").size) + assertEquals(saved, store.load(saved.authority)) + assertEquals(saved, authenticator.savedConnection) + assertEquals(HermesException.Kind.AuthenticationRequired, kind { restored(saved).authenticated(ping) }) + assertEquals(saved, store.load(saved.authority)) + } + + @Test fun aRejectedRenewalLeavesTheOtherCopysNewerSignIn() = runBlocking { + val saved = bearer() + var count = 0 + host.on("POST", "/auth/native/refresh") { + if (++count == 1) renewed().setBodyDelay(800, TimeUnit.MILLISECONDS) + else ScriptedHost.json("""{"error":"session_expired"}""", 401).setBodyDelay(100, TimeUnit.MILLISECONDS) + } + pingRoute() + val winner = restored(saved) + val loser = restored(saved) + val winning = async { winner.authenticated(ping) } + var waited = 0 + while (host.callsTo("/auth/native/refresh").isEmpty() && waited++ < 300) delay(10) + assertEquals(HermesException.Kind.AuthenticationRequired, kind { loser.authenticated(ping) }) + assertEquals(200, winning.await().status) + assertEquals("The winner could still save its new sign-in", "refresh-2", ((store.load(saved.authority)!!.auth) as StoredAuth.Bearer).refreshToken) + } + + @Test fun anOutageKeepsTheTokenAndPausesFurtherRenewalsForAMoment() = runBlocking { + var calls = 0 + host.on("POST", "/auth/native/refresh") { if (++calls == 1) MockResponse().setResponseCode(503) else renewed() } + pingRoute() + val saved = bearer() + val authenticator = restored(saved, AuthTimings(refusedRenewalPauseMillis = 400)) + assertEquals(HermesException.Kind.ServerUnavailable, kind { authenticator.authenticated(ping) }) + assertEquals("Same answer inside the pause, no new renewal", HermesException.Kind.ServerUnavailable, kind { authenticator.authenticated(ping) }) + assertEquals(1, host.callsTo("/auth/native/refresh").size) + assertEquals("The refresh token is kept", saved, store.load(saved.authority)) + delay(450) + assertEquals(200, authenticator.authenticated(ping).status) + assertEquals(2, host.callsTo("/auth/native/refresh").size) + assertEquals("refresh-2", ((store.load(saved.authority)!!.auth) as StoredAuth.Bearer).refreshToken) + } + + @Test fun rateLimitsAndProxyErrorsAreRefusalsThatKeepTheTokenAndAProxyChallengeIsNotASignInEnd() = runBlocking { + val saved = bearer() + store.replace(null, saved) + host.on("POST", "/auth/native/refresh", MockResponse().setResponseCode(429)) + assertEquals(HermesException.Kind.RateLimited, kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) }) + host.on("POST", "/auth/native/refresh", MockResponse().setResponseCode(502)) + assertEquals(HermesException.Kind.ServerUnavailable, kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) }) + host.on("POST", "/auth/native/refresh", ScriptedHost.html("no").setResponseCode(401).addHeader("WWW-Authenticate", "Basic realm=\"proxy\"")) + val challenged = kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) } + assertNotEquals("A proxy's challenge is not Hermes ending the sign-in", HermesException.Kind.AuthenticationRequired, challenged) + assertEquals(saved, store.load(saved.authority)) + } + + @Test fun aRenewalCutByTheNetworkIsNotRememberedAndTheTokenStaysForTheNextTry() = runBlocking { + var calls = 0 + host.on("POST", "/auth/native/refresh") { if (++calls == 1) MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST) else renewed() } + pingRoute() + val saved = bearer() + val authenticator = restored(saved) + assertEquals(HermesException.Kind.ConnectionFailed, kind { authenticator.authenticated(ping) }) + assertEquals(saved, store.load(saved.authority)) + assertEquals("No pause after a network error: it retries at once", 200, authenticator.authenticated(ping).status) + assertEquals( + "The same refresh token went out twice", + listOf("""{"refresh_token":"refresh-1","provider":"basic"}""", """{"refresh_token":"refresh-1","provider":"basic"}"""), + refreshBodies(), + ) + } + + @Test fun aRenewalThatChangesThePrincipalOrIsMalformedIsNotSaved() = runBlocking { + val saved = bearer() + store.replace(null, saved) + host.on("POST", "/auth/native/refresh", renewed(user = "someone-else")) + assertEquals(HermesException.Kind.IdentityChanged, kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) }) + host.on("POST", "/auth/native/refresh", renewed(provider = "other")) + assertEquals(HermesException.Kind.IdentityChanged, kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) }) + host.on("POST", "/auth/native/refresh", ScriptedHost.json("""{"token_type":"Bearer"}""")) + assertEquals(HermesException.Kind.InvalidResponse, kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) }) + host.on("POST", "/auth/native/refresh", renewed(expires = now - 5)) + assertEquals(HermesException.Kind.InvalidResponse, kind { make().apply { adoptForTest(saved, true) }.authenticated(ping) }) + assertEquals(saved, store.load(saved.authority)) + } + + @Test fun withoutARefreshTokenThereIsNothingToSendAndTheSignInIsOver() = runBlocking { + val saved = bearer(refresh = null) + val authenticator = restored(saved) + assertEquals(HermesException.Kind.AuthenticationRequired, kind { authenticator.authenticated(ping) }) + assertEquals(0, host.callsTo("/auth/native/refresh").size) + } + + @Test fun aStorageFailureAfterTheHostRotatedIsReportedAndNothingElseChanges() = runBlocking { + val saved = bearer() + val flaky = object : CredentialStore by store { + override suspend fun replace(expected: SavedConnection?, next: SavedConnection) = throw IOException("disk full /secret/path") + } + store.replace(null, saved) + host.on("POST", "/auth/native/refresh", renewed()) + val authenticator = HermesAuthenticator(host.endpoint, OkHttpHermesHttp(host.endpoint).also { resources += it }, flaky, null, clock).also { resources += it } + authenticator.adoptForTest(saved, persisted = true) + val failure = assertThrows(HermesException::class.java) { runBlocking { authenticator.authenticated(ping) } } + assertEquals(HermesException.Kind.SecureStorageUnavailable, failure.kind) + assertFalse("/secret/path" in failure.message.orEmpty() + failure.toString()) + assertEquals("The in-memory record is not advanced past what is durable", saved, authenticator.savedConnection) + } + + @Test fun aStagedSignInRotatesInMemoryOnlyAndCommitPersistsTheLatest() = runBlocking { + host.on("POST", "/auth/native/refresh", renewed()) + pingRoute() + val staged = bearer() + val authenticator = make() + authenticator.adoptForTest(staged, persisted = false) + assertEquals(200, authenticator.authenticated(ping).status) + assertNull("Staging never touches the store", store.load(staged.authority)) + val rotated = authenticator.savedConnection!! + assertEquals("new-access", (rotated.auth as StoredAuth.Bearer).accessToken) + + authenticator.commit(expected = null) + assertEquals(rotated, store.load(rotated.authority)) + assertTrue(authenticator.isPersisted) + authenticator.commit(expected = null) // already persisted: no second write, no failure + } + + // Commit + + @Test fun commitWritesOnlyWhenTheCallersFenceStillHoldsAndReadsBackTheRecord() = runBlocking { + val staged = dashboard() + val authenticator = make() + authenticator.adoptForTest(staged, persisted = false) + assertEquals(HermesException.Kind.Cancelled, kind { authenticator.commit(null) { false } }) + assertNull(store.load(staged.authority)) + authenticator.commit(null) { true } + assertEquals(staged, store.load(staged.authority)) + } + + @Test fun commitFailsWhenAnotherRecordAlreadyOwnsTheAuthorityOrTheStoreLies() = runBlocking { + val staged = bearer(expires = now + 3_600) + store.replace(null, bearer(access = "existing", expires = now + 100)) + val authenticator = make().apply { adoptForTest(staged, persisted = false) } + assertEquals(HermesException.Kind.SecureStorageChanged, kind { authenticator.commit(expected = null) }) + authenticator.commit(expected = bearer(access = "existing", expires = now + 100)) // replacing the exact old record works + assertEquals(staged, store.load(staged.authority)) + + val otherAccount = bearer(user = "someone-else") + assertEquals( + "Expectation of another principal is refused before any write", + HermesException.Kind.IdentityChanged, + kind { make().apply { adoptForTest(staged.let { bearer(access = "x", expires = now + 1_000) }, false) }.commit(expected = otherAccount) }, + ) + + val liar = object : CredentialStore by InMemoryCredentialStore() { + override suspend fun load(authority: CredentialAuthority): SavedConnection? = null + } + val lied = HermesAuthenticator(host.endpoint, OkHttpHermesHttp(host.endpoint).also { resources += it }, liar, null, clock).also { resources += it } + lied.adoptForTest(dashboard("t"), persisted = false) + assertEquals("A write that cannot be read back does not count", HermesException.Kind.SecureStorageUnavailable, kind { lied.commit(null) }) + assertFalse(lied.isPersisted) + } + + // Restore + + @Test fun restoreChecksTheStoreTheModeAndTheIdentity() = runBlocking { + val saved = bearer(expires = now + 3_600) + store.replace(null, saved) + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":true,"auth_flows":["native_pkce"]}""")) + host.on("GET", "/api/auth/me", ScriptedHost.json("""{"provider":"basic","user_id":"synthetic-user"}""")) + val authenticator = make() + authenticator.restore(saved) + assertEquals(listOf("GET /api/status", "GET /api/auth/me"), host.calls) + assertEquals("Bearer old-access", host.callsTo("/api/auth/me").single().getHeader("Authorization")) + assertTrue(authenticator.isPersisted) + + host.on("GET", "/api/auth/me", ScriptedHost.json("""{"provider":"basic","user_id":"another"}""")) + assertEquals(HermesException.Kind.IdentityChanged, kind { make().restore(saved) }) + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":false}""")) + assertEquals("A gated credential on an ungated host", HermesException.Kind.AuthModeChanged, kind { make().restore(saved) }) + } + + @Test fun restoreRefusesAStaleSnapshotAWrongEndpointAndAnInvalidRecord() = runBlocking { + val saved = bearer(expires = now + 3_600) + store.replace(null, bearer(access = "newer", expires = now + 3_600)) + assertEquals(HermesException.Kind.SecureStorageChanged, kind { make().restore(saved) }) + val elsewhere = SavedConnection(HermesEndpoint.parse("http://127.0.0.1:1/other", true), StoredAuth.DashboardSession("t", true), null, null) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { make().restore(elsewhere) }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { make().restore(SavedConnection(host.endpoint, StoredAuth.Bearer("a", null, null), null, null)) }) + assertEquals("Nothing reached the host", 0, host.requests.size) + } + + @Test fun restoreRenewsWhenMeSaysTheAccessTokenIsDead() = runBlocking { + val saved = bearer(expires = now + 3_600) + store.replace(null, saved) + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":true}""")) + host.on("GET", "/api/auth/me", MockResponse().setResponseCode(401)) + host.on("POST", "/auth/native/refresh", renewed()) + make().restore(saved) + assertEquals(listOf("GET /api/status", "GET /api/auth/me", "POST /auth/native/refresh"), host.calls) + assertEquals("new-access", (store.load(saved.authority)!!.auth as StoredAuth.Bearer).accessToken) + } + + @Test fun restoreRereadsAnAutomaticDashboardTokenButNeverReplacesAManualOne() = runBlocking { + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":false}""")) + host.on("GET", "/", ScriptedHost.dashboardPage("restarted-token")) + val automatic = dashboard("old-dash", automatic = true) + store.replace(null, automatic) + val authenticator = make() + authenticator.restore(automatic) + assertEquals(StoredAuth.DashboardSession("restarted-token", true), store.load(automatic.authority)!!.auth) + assertEquals(store.load(automatic.authority), authenticator.savedConnection) + + host.requests.clear() + val manual = dashboard("manual-token", automatic = false) + store.delete(store.load(automatic.authority)!!) + store.replace(null, manual) + make().restore(manual) + assertEquals(listOf("GET /api/status"), host.calls) + assertEquals(manual, store.load(manual.authority)) + + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":true}""")) + assertEquals(HermesException.Kind.AuthModeChanged, kind { make().restore(manual) }) + } + + // Authenticated resend + + @Test fun aDashboardTokenTurnedAwayIsReadAgainAndTheRequestSentOnce() = runBlocking { + host.on("GET", "/", ScriptedHost.dashboardPage("new-dash")) + host.on("GET", "/api/plugins/loopdy/native/context") { r -> + if (r.getHeader("X-Hermes-Session-Token") == "new-dash") ScriptedHost.json("{}") else MockResponse().setResponseCode(401) + } + val saved = dashboard() + val authenticator = restored(saved) + assertEquals(200, authenticator.authenticated(ping).status) + assertEquals(listOf("GET /api/plugins/loopdy/native/context", "GET /", "GET /api/plugins/loopdy/native/context"), host.calls) + assertEquals(StoredAuth.DashboardSession("new-dash", true), store.load(saved.authority)!!.auth) + } + + @Test fun aBearerTurnedAwayIsRenewedAndTheRequestSentOnceMoreNeverTwice() = runBlocking { + host.on("POST", "/auth/native/refresh", renewed()) + host.on("GET", "/api/plugins/loopdy/native/context", MockResponse().setResponseCode(401)) + val authenticator = restored(bearer(expires = now + 3_600)) + assertEquals("The second 401 is returned, not looped", 401, authenticator.authenticated(ping).status) + assertEquals( + listOf("GET /api/plugins/loopdy/native/context", "POST /auth/native/refresh", "GET /api/plugins/loopdy/native/context"), + host.calls, + ) + } + + @Test fun otherStatusesAndChallengesAreReturnedOnceWithoutRenewal() = runBlocking { + val authenticator = restored(bearer(expires = now + 3_600)) + host.on("GET", "/api/plugins/loopdy/native/context", MockResponse().setResponseCode(404)) + assertEquals(404, authenticator.authenticated(ping).status) + host.on("GET", "/api/plugins/loopdy/native/context", MockResponse().setResponseCode(401).addHeader("WWW-Authenticate", "Basic realm=\"p\"")) + assertEquals(401, authenticator.authenticated(ping).status) + assertEquals(2, host.requests.size) + val noRefresh = restored(bearer(access = "other", refresh = null, expires = now + 3_600).let { SavedConnection(host.endpoint, it.auth, "basic", "other-user") }) + host.on("GET", "/api/plugins/loopdy/native/context", MockResponse().setResponseCode(401)) + host.requests.clear() + assertEquals("Nothing to renew", 401, noRefresh.authenticated(ping).status) + assertEquals(1, host.requests.size) + } + + @Test fun aRequestWhoseTokenAnotherRequestAlreadyRenewedIsResentWithoutAnotherRenewal() = runBlocking { + host.on("POST", "/auth/native/refresh", renewed()) + host.on("GET", "/api/plugins/loopdy/native/context") { r -> + when (r.getHeader("Authorization")) { + "Bearer new-access" -> ScriptedHost.json("{}") + else -> MockResponse().setResponseCode(401).setBodyDelay(200, TimeUnit.MILLISECONDS) + } + } + val authenticator = restored(bearer(expires = now + 3_600)) + val results = (1..3).map { async { authenticator.authenticated(ping).status } }.awaitAll() + assertEquals(List(3) { 200 }, results) + assertEquals(1, host.callsTo("/auth/native/refresh").size) + } + + // Uncertain outcome + + @Test fun aMutationLostAfterDispatchIsATypedUncertainOutcomeAndIsNeverResent() = runBlocking { + val authenticator = restored(bearer(expires = now + 3_600)) + host.on("POST", "/api/plugins/loopdy/native/goals", MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)) + val post = HermesHttpRequest("/api/plugins/loopdy/native/goals", "POST", body = buildJsonObject { put("title", "t") }) + val failure = assertThrows(HermesException::class.java) { runBlocking { authenticator.authenticatedJson(post) } } + assertEquals(HermesException.Kind.OutcomeUnknown, failure.kind) + assertTrue(failure.outcomeUnknown) + assertEquals(1, host.callsTo("/api/plugins/loopdy/native/goals").size) + + val get = assertThrows(HermesException::class.java) { + runBlocking { + host.on("GET", "/api/plugins/loopdy/native/context", MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)) + authenticator.authenticatedJson(ping) + } + } + assertEquals("A read is simply a failure", HermesException.Kind.ConnectionFailed, get.kind) + assertFalse(get.outcomeUnknown) + } + + @Test fun definitiveRejectionsAndPreSendFailuresOfAMutationAreNotUncertain() = runBlocking { + val authenticator = restored(bearer(expires = now + 3_600)) + val route = "/api/plugins/loopdy/native/goals" + val post = HermesHttpRequest(route, "POST", body = buildJsonObject { put("title", "t") }) + host.on("POST", route, ScriptedHost.json("""{"detail":"nope"}""", 422)) + val rejected = assertThrows(HermesException::class.java) { runBlocking { authenticator.authenticatedJson(post) } } + assertEquals(HermesException.Kind.InvalidResponse, rejected.kind) + assertFalse(rejected.outcomeUnknown) + host.on("POST", route, MockResponse().setResponseCode(502)) + assertEquals("A proxy 502 may have reached Hermes", HermesException.Kind.OutcomeUnknown, + assertThrows(HermesException::class.java) { runBlocking { authenticator.authenticatedJson(post) } }.kind) + host.on("POST", route, ScriptedHost.json("not json")) + assertEquals("A 200 whose answer cannot be read", HermesException.Kind.OutcomeUnknown, + assertThrows(HermesException::class.java) { runBlocking { authenticator.authenticatedJson(post) } }.kind) + val before = host.requests.size + val oversize = HermesHttpRequest(route, "POST", body = buildJsonObject { put("x", "y".repeat(HermesHttpLimits.MAXIMUM_BODY_BYTES)) }) + val certain = assertThrows(HermesException::class.java) { runBlocking { authenticator.authenticatedJson(oversize) } } + assertEquals(HermesException.Kind.MessageTooLarge, certain.kind) + assertFalse("Nothing was sent, so the outcome is known", certain.outcomeUnknown) + assertEquals(before, host.requests.size) + host.on("POST", route, ScriptedHost.json("""{"ok":true}""")) + assertEquals("""{"ok":true}""", authenticator.authenticatedJson(post).toString()) + } + + @Test fun aRouteRefusalHookRunsBeforeTheGenericMapping() = runBlocking { + val authenticator = restored(bearer(expires = now + 3_600)) + host.on("PATCH", "/api/sessions/s1", ScriptedHost.json("""{"detail":"revision_conflict"}""", 409)) + val failure = assertThrows(HermesException::class.java) { + runBlocking { + authenticator.authenticatedJson(HermesHttpRequest("/api/sessions/s1", "PATCH", body = buildJsonObject { put("title", "t") })) { r -> + if (r.status == 409) HermesException(HermesException.Kind.RpcRejected, code = 409L, refusal = "revision_conflict") else null + } + } + } + assertEquals(HermesException.Kind.RpcRejected, failure.kind) + assertEquals(409L, failure.code) + assertFalse("A definitive 409 is not an unknown outcome", failure.outcomeUnknown) + } + + // Gateway credentials and health + + @Test fun aDashboardSocketCarriesTheTokenInTheQueryAndTheHeaderAndTheGate() = runBlocking { + val access = AccessHeaders.of(host.endpoint, AccessCredential.proxyBasic("u", "p"), listOf(CustomHeader.of("X-Gate", "g"))) + val authenticator = make(access = access).apply { adoptForTest(dashboard("tok+en/1"), persisted = true) } + val request = authenticator.socketRequest() + assertEquals("ws://127.0.0.1:${host.server.port}/hermes/api/ws?token=tok%2Ben%2F1", request.url) + assertEquals(mapOf("Authorization" to "Basic dTpw", "X-Gate" to "g", "X-Hermes-Session-Token" to "tok+en/1"), request.headers) + assertNull(request.requiredSubprotocol) + assertFalse("tok" in request.toString()) + assertEquals("No network call for a dashboard socket", 0, host.requests.size) + } + + @Test fun everyBearerSocketMintsAFreshTicketAndOffersItAsASubprotocol() = runBlocking { + var n = 0 + host.on("POST", "/api/auth/ws-ticket") { r -> + assertEquals("Bearer old-access", r.getHeader("Authorization")) + assertEquals("{}", r.body.readUtf8()) + ScriptedHost.json("""{"ticket":"ticket_${++n}","ttl_seconds":30}""") + } + val authenticator = restored(bearer(expires = now + 3_600)) + val first = authenticator.socketRequest() + val second = authenticator.socketRequest() + assertEquals("ws://127.0.0.1:${host.server.port}/hermes/api/ws", first.url) + assertEquals("hermes-gateway-v1, hermes-gateway-ticket.ticket_1", first.headers["Sec-WebSocket-Protocol"]) + assertEquals("hermes-gateway-v1, hermes-gateway-ticket.ticket_2", second.headers["Sec-WebSocket-Protocol"]) + assertEquals("hermes-gateway-v1", first.requiredSubprotocol) + assertNull("No provider token in the gateway request", first.headers["Authorization"]) + assertFalse("ticket_1" in first.toString() || "old-access" in first.url) + assertEquals(2, host.callsTo("/api/auth/ws-ticket").size) + } + + @Test fun aTicketRequestTurnedAwayRenewsOnceAndMintsAgain() = runBlocking { + host.on("POST", "/auth/native/refresh", renewed()) + host.on("POST", "/api/auth/ws-ticket") { r -> + if (r.getHeader("Authorization") == "Bearer new-access") ScriptedHost.json("""{"ticket":"t1","ttl_seconds":30}""") else MockResponse().setResponseCode(401) + } + val authenticator = restored(bearer(expires = now + 3_600)) + assertTrue(authenticator.socketRequest().headers["Sec-WebSocket-Protocol"]!!.endsWith("ticket.t1")) + assertEquals(listOf("POST /api/auth/ws-ticket", "POST /auth/native/refresh", "POST /api/auth/ws-ticket"), host.calls) + + host.on("POST", "/api/auth/ws-ticket", ScriptedHost.json("""{"ticket":"t1","ttl_seconds":999}""")) + assertEquals(HermesException.Kind.InvalidResponse, kind { authenticator.socketRequest() }) + } + + @Test fun healthNeedsOkTrueABooleanAuthModeAndASmallBody() = runBlocking { + val authenticator = restored(bearer(expires = now + 3_600)) + host.on("GET", "/api/health", ScriptedHost.json("""{"ok":true,"auth_required":true,"extra":1}""")) + authenticator.requireHealth() + assertEquals("Bearer old-access", host.callsTo("/api/health").single().getHeader("Authorization")) + listOf("""{"ok":false,"auth_required":true}""", """{"ok":"true","auth_required":true}""", """{"ok":true}""", """{"ok":true,"auth_required":"yes"}""", "{}") + .forEach { + host.on("GET", "/api/health", ScriptedHost.json(it)) + assertEquals(it, HermesException.Kind.AuthenticationRequired, kind { authenticator.requireHealth() }) + } + host.on("GET", "/api/health", ScriptedHost.json("""{"ok":true,"auth_required":true,"pad":"${"x".repeat(16_400)}"}""")) + assertEquals(HermesException.Kind.MessageTooLarge, kind { authenticator.requireHealth() }) + } + + @Test fun closingWaitsForARenewalOnItsWayInsteadOfCuttingItOff() = runBlocking { + host.on("POST", "/auth/native/refresh") { renewed().setBodyDelay(500, TimeUnit.MILLISECONDS) } + pingRoute() + val saved = bearer() + val authenticator = restored(saved) + val request = async { runCatching { authenticator.authenticated(ping) } } + var waited = 0 + while (host.callsTo("/auth/native/refresh").isEmpty() && waited++ < 300) delay(10) + request.cancel() + authenticator.settlePendingRenewal(5_000) + assertEquals("The renewal finished and its new token was saved", "refresh-2", (store.load(saved.authority)!!.auth as StoredAuth.Bearer).refreshToken) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSignInTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSignInTest.kt new file mode 100644 index 00000000..e4c355f1 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSignInTest.kt @@ -0,0 +1,366 @@ +package app.bighelp.hermes + +import java.security.MessageDigest +import java.util.Base64 +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.RecordedRequest +import okhttp3.mockwebserver.SocketPolicy +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Discovery and every sign-in mode against a scripted loopback host. The credential store is never written. */ +class HermesAuthenticatorSignInTest { + private val host = ScriptedHost("/hermes") + private val store = InMemoryCredentialStore() + private val clock = TestClock(java.time.Instant.ofEpochSecond(1_800_000_000)) + private val resources = mutableListOf() + private val now = 1_800_000_000L + + @After fun stop() { + resources.forEach { it.close() } + host.close() + } + + private fun authenticator(browser: BrowserLauncher? = null, access: AccessHeaders = AccessHeaders.none): HermesAuthenticator { + val http = OkHttpHermesHttp(host.endpoint, access) + return HermesAuthenticator(host.endpoint, http, store, browser, clock).also { resources += it } + } + + private fun kind(block: suspend () -> Unit) = assertThrows(HermesException::class.java) { runBlocking { block() } }.kind + + private fun body(request: RecordedRequest): JsonObject = Json.parseToJsonElement(request.body.readUtf8()).jsonObject + + private fun status(authRequired: Boolean, flows: String = "[]") = + ScriptedHost.json("""{"auth_required":$authRequired,"auth_flows":$flows}""") + + private fun tokenReply(access: String = "access-1", refresh: String? = "refresh-1", provider: String = "basic", user: String = "synthetic-user", expires: Long = now + 3_600) = + ScriptedHost.json( + """{"token_type":"Bearer","access_token":"$access","refresh_token":${refresh?.let { "\"$it\"" } ?: "null"},"provider":"$provider","user_id":"$user","expires_at":$expires}""", + ) + + private fun me(provider: String = "basic", user: String = "synthetic-user", expires: Long = now + 3_600) = + ScriptedHost.json("""{"provider":"$provider","user_id":"$user","expires_at":$expires}""") + + // Discovery + + @Test fun discoveryAsksStatusWithoutAnyCredential() = runBlocking { + host.on("GET", "/api/status", status(false)) + val found = authenticator(access = AccessHeaders.of(host.endpoint, AccessCredential.proxyBasic("u", "p"), emptyList())).discover() + assertFalse(found.authRequired) + assertEquals(emptyList(), found.providers) + val request = host.requests.single() + assertEquals("Basic dTpw", request.getHeader("Authorization")) + assertNull(request.getHeader("X-Hermes-Session-Token")) + assertNull(request.getHeader("Cookie")) + assertEquals(listOf("GET /api/status"), host.calls) + } + + @Test fun discoveryFetchesProvidersOnlyForNativePkceAndNeverLetsThemDisableTheFlow() = runBlocking { + host.on("GET", "/api/status", status(true, """["cookie","native_pkce"]""")) + host.on("GET", "/api/auth/providers", ScriptedHost.json("""{"providers":[{"name":"basic","display_name":"Password","supports_password":true},{"name":"sso","supports_password":false}]}""")) + val found = authenticator().discover() + assertTrue(found.supportsNativePkce) + assertEquals(listOf("basic"), found.passwordProviders.map { it.name }) + assertEquals(listOf("basic", "sso"), found.browserProviders.map { it.name }) + assertEquals(listOf("GET /api/status", "GET /api/auth/providers"), host.calls) + + host.on("GET", "/api/auth/providers", ScriptedHost.json("""{"providers":"broken"}""")) + val degraded = authenticator().discover() + assertTrue("A malformed list never disables the advertised flow", degraded.supportsNativePkce) + assertTrue(degraded.providers.isEmpty()) + host.on("GET", "/api/auth/providers") { MockResponse().setResponseCode(503) } + assertTrue(authenticator().discover().supportsNativePkce) + } + + @Test fun discoveryDoesNotAskForProvidersWithoutNativePkce() = runBlocking { + host.on("GET", "/api/status", status(true, """["cookie"]""")) + authenticator().discover() + host.on("GET", "/api/status", status(false, """["native_pkce"]""")) + authenticator().discover() + assertEquals(listOf("GET /api/status", "GET /api/status"), host.calls) + } + + @Test fun discoveryRecognizesAWebPageAHostNameRefusalAndBadStatuses() { + val html = ScriptedHost.html("nope") + host.on("GET", "/api/status", html) + assertEquals(HermesException.Kind.WebPageInsteadOfHermes, kind { authenticator().discover() }) + host.on("GET", "/api/status", ScriptedHost.json("""{"detail":"Invalid Host header"}""", 400)) + assertEquals(HermesException.Kind.HostNameRefused, kind { authenticator().discover() }) + host.on("GET", "/api/status", MockResponse().setResponseCode(503)) + assertEquals(HermesException.Kind.ServerUnavailable, kind { authenticator().discover() }) + host.on("GET", "/api/status", ScriptedHost.json("""{"auth_required":"maybe"}""")) + assertEquals(HermesException.Kind.InvalidResponse, kind { authenticator().discover() }) + } + + // Ungated modes + + @Test fun automaticDashboardSignInReadsTheBootstrapTokenAndWritesNothing() = runBlocking { + host.on("GET", "/api/status", status(false)) + host.on("GET", "/", ScriptedHost.dashboardPage("dash-token-1")) + val authenticator = authenticator() + val staged = authenticator.signIn(SignInInput.Dashboard) + assertEquals(StoredAuth.DashboardSession("dash-token-1", automatic = true), staged.auth) + assertNull(staged.provider) + assertEquals(staged, authenticator.savedConnection) + assertFalse("A sign-in is staged, not persisted", authenticator.isPersisted) + assertNull(store.load(staged.authority)) + assertEquals(listOf("GET /api/status", "GET /"), host.calls) + assertEquals("text/html", host.callsTo("/").single().getHeader("Accept")) + assertNull("The page is read without credentials", host.callsTo("/").single().getHeader("X-Hermes-Session-Token")) + } + + @Test fun anEnteredTokenOnAnUngatedHostIsAManualDashboardSessionWithoutReadingThePage() = runBlocking { + host.on("GET", "/api/status", status(false)) + val staged = authenticator().signIn(SignInInput.Token("manual-token")) + assertEquals(StoredAuth.DashboardSession("manual-token", automatic = false), staged.auth) + assertEquals(listOf("GET /api/status"), host.calls) + assertEquals(HermesException.Kind.InvalidCredentials, kind { authenticator().signIn(SignInInput.Token("has space")) }) + } + + @Test fun aGatedTokenIsVerifiedByMeAndNeverGainsARefreshToken() = runBlocking { + host.on("GET", "/api/status", status(true)) + host.on("GET", "/api/auth/me") { request -> + if (request.getHeader("Authorization") == "Bearer entered-access") me(expires = now + 900) else MockResponse().setResponseCode(401) + } + val staged = authenticator().signIn(SignInInput.Token("entered-access")) + assertEquals(StoredAuth.Bearer("entered-access", null, now + 900), staged.auth) + assertEquals("basic", staged.provider) + assertEquals("synthetic-user", staged.userId) + assertEquals(CredentialAuthority(host.endpoint.canonical, "basic\u001fsynthetic-user"), staged.authority) + + assertEquals(HermesException.Kind.InvalidCredentials, kind { authenticator().signIn(SignInInput.Token("rejected")) }) + assertTrue("The rejected token is not retried under another mechanism", host.callsTo("/").isEmpty()) + assertTrue(host.requests.none { it.getHeader("X-Hermes-Session-Token") != null }) + } + + @Test fun aMeAnswerWithoutAnIdentityIsRefusedAndAnExpiryIsOptional() = runBlocking { + host.on("GET", "/api/status", status(true)) + host.on("GET", "/api/auth/me", ScriptedHost.json("""{"provider":"basic","user_id":""}""")) + assertEquals(HermesException.Kind.InvalidResponse, kind { authenticator().signIn(SignInInput.Token("t")) }) + host.on("GET", "/api/auth/me", ScriptedHost.json("""{"provider":"basic","user_id":"u"}""")) + assertNull((authenticator().signIn(SignInInput.Token("t")).auth as StoredAuth.Bearer).expiresAtEpochSeconds) + } + + @Test fun modesThatDoNotMatchTheHostAreRefusedWithoutSendingTheCredential() { + host.on("GET", "/api/status", status(true, """["native_pkce"]""")) + assertEquals(HermesException.Kind.AuthModeChanged, kind { authenticator().signIn(SignInInput.Dashboard) }) + host.on("GET", "/api/status", status(false)) + assertEquals(HermesException.Kind.UnsupportedAuthentication, kind { authenticator().signIn(SignInInput.Password(null, "u", "p")) }) + assertEquals(HermesException.Kind.UnsupportedAuthentication, kind { authenticator().signIn(SignInInput.Browser(null)) }) + assertTrue(host.requests.none { it.path.orEmpty().contains("/auth/") }) + assertTrue(host.requests.none { it.method == "POST" }) + } + + // Password PKCE + + private fun b64(bytes: ByteArray) = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) + private fun challenge(verifier: String) = b64(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray())) + private val callback = "http://127.0.0.1:49152/loopdy-native-callback" + private val cookie = "hermes_session_pkce=cookie_value-1=" + + private fun passwordHost( + providers: String = """[{"name":"basic","display_name":"Password","supports_password":true}]""", + authorize: (RecordedRequest) -> MockResponse = { MockResponse().setResponseCode(302).setHeader("Location", "/hermes/login").addHeader("Set-Cookie", "$cookie; Path=/hermes; HttpOnly; Max-Age=600") }, + login: (RecordedRequest, String) -> MockResponse = { _, state -> + ScriptedHost.json("""{"ok":true,"next":"$callback?state=$state&code=one-use-code"}""") + }, + token: (RecordedRequest) -> MockResponse = { tokenReply() }, + meReply: MockResponse = me(), + ) { + host.on("GET", "/api/status", status(true, """["native_pkce"]""")) + host.on("GET", "/api/auth/providers", ScriptedHost.json("""{"providers":$providers}""")) + var state = "" + host.on("GET", "/auth/native/authorize") { request -> + state = request.requestUrl!!.queryParameter("state")!! + authorize(request) + } + host.on("POST", "/auth/password-login") { login(it, state) } + host.on("POST", "/auth/native/token", token) + host.on("GET", "/api/auth/me", meReply) + } + + @Test fun passwordSignInFollowsTheDocumentedWireExactly() = runBlocking { + passwordHost() + val authenticator = authenticator() + val staged = authenticator.signIn(SignInInput.Password(null, "synthetic-user", "synthetic password")) + + assertEquals( + listOf( + "GET /api/status", "GET /api/auth/providers", "GET /auth/native/authorize", + "POST /auth/password-login", "POST /auth/native/token", "GET /api/auth/me", + ), + host.calls, + ) + val authorize = host.callsTo("/auth/native/authorize").single().requestUrl!! + assertEquals(setOf("provider", "code_challenge", "code_challenge_method", "redirect_uri", "state"), authorize.queryParameterNames) + assertEquals("basic", authorize.queryParameter("provider")) + assertEquals("S256", authorize.queryParameter("code_challenge_method")) + assertEquals(callback, authorize.queryParameter("redirect_uri")) + val state = authorize.queryParameter("state")!! + assertTrue(Regex("[A-Za-z0-9_-]{43}").matches(state)) + + val login = host.callsTo("/auth/password-login").single() + assertEquals("Only the one cookie goes back", cookie, login.getHeader("Cookie")) + assertEquals("""{"provider":"basic","username":"synthetic-user","password":"synthetic password","next":""}""", login.body.readUtf8()) + + val exchange = body(host.callsTo("/auth/native/token").single()) + assertEquals(setOf("code", "code_verifier"), exchange.keys) + assertEquals("one-use-code", exchange["code"]!!.jsonPrimitive.content) + val verifier = exchange["code_verifier"]!!.jsonPrimitive.content + assertEquals("The challenge is S256 of the verifier sent at exchange", challenge(verifier), authorize.queryParameter("code_challenge")) + assertTrue(verifier != state) + assertEquals("Bearer access-1", host.callsTo("/api/auth/me").single().getHeader("Authorization")) + + assertEquals(StoredAuth.Bearer("access-1", "refresh-1", now + 3_600), staged.auth) + assertNull("Nothing is stored until the gateway is ready", store.load(staged.authority)) + listOf(staged.toString(), authenticator.toString()).forEach { assertFalse("synthetic password" in it) } + assertTrue("No later request carries the password", host.requests.drop(4).none { it.body.size > 0 && "synthetic password" in it.body.snapshot().utf8() }) + } + + @Test fun passwordSignInPicksAnExplicitProviderAndRefusesAmbiguityOrNone() = runBlocking { + val two = """[{"name":"a","supports_password":true},{"name":"b","supports_password":true},{"name":"sso","supports_password":false}]""" + passwordHost(providers = two, meReply = me(provider = "b"), token = { tokenReply(provider = "b") }) + assertEquals(HermesException.Kind.AmbiguousPasswordProvider, kind { authenticator().signIn(SignInInput.Password(null, "u", "p")) }) + assertEquals(HermesException.Kind.UnsupportedAuthentication, kind { authenticator().signIn(SignInInput.Password("sso", "u", "p")) }) + assertEquals(HermesException.Kind.UnsupportedAuthentication, kind { authenticator().signIn(SignInInput.Password("unknown", "u", "p")) }) + assertTrue("No sign-in attempt before the provider is certain", host.callsTo("/auth/native/authorize").isEmpty()) + assertEquals("b", authenticator().signIn(SignInInput.Password("b", "u", "p")).provider) + + passwordHost(providers = """[{"name":"sso","supports_password":false}]""") + assertEquals(HermesException.Kind.UnsupportedAuthentication, kind { authenticator().signIn(SignInInput.Password(null, "u", "p")) }) + } + + @Test fun passwordCredentialsAreBoundedBeforeAnyRequest() { + passwordHost() + listOf("" to "p", "u" to "", "u".repeat(1_025) to "p", "u" to "p".repeat(16_385)).forEach { + assertEquals(HermesException.Kind.InvalidCredentials, kind { authenticator().signIn(SignInInput.Password(null, it.first, it.second)) }) + } + assertTrue(host.callsTo("/auth/native/authorize").isEmpty()) + runBlocking { authenticator().signIn(SignInInput.Password(null, "u".repeat(1_024), "p".repeat(16_384))) } + } + + @Test fun theAuthorizeAnswerMustBeTheExactLoginRedirectWithAnExpectedCookie() { + fun reply(response: MockResponse) { passwordHost(authorize = { response }) } + fun attempt() = kind { authenticator().signIn(SignInInput.Password(null, "u", "p")) } + val cookieHeader = "$cookie; Path=/hermes; Max-Age=600" + reply(MockResponse().setResponseCode(200).addHeader("Set-Cookie", cookieHeader)) + assertEquals(HermesException.Kind.UnsupportedAuthentication, attempt()) + reply(MockResponse().setResponseCode(302).setHeader("Location", "/login").addHeader("Set-Cookie", cookieHeader)) + assertEquals("The prefix is part of /login", HermesException.Kind.UnsupportedAuthentication, attempt()) + reply(MockResponse().setResponseCode(302).setHeader("Location", "https://evil.example/hermes/login").addHeader("Set-Cookie", cookieHeader)) + assertEquals(HermesException.Kind.UnsupportedAuthentication, attempt()) + reply(MockResponse().setResponseCode(302).setHeader("Location", "/hermes/login?x=1").addHeader("Set-Cookie", cookieHeader)) + assertEquals(HermesException.Kind.UnsupportedAuthentication, attempt()) + reply(MockResponse().setResponseCode(302).setHeader("Location", "/hermes/login")) + assertEquals("No cookie", HermesException.Kind.InvalidResponse, attempt()) + reply(MockResponse().setResponseCode(302).setHeader("Location", "/hermes/login").addHeader("Set-Cookie", "hermes_session_pkce=a; Path=/hermes")) + assertEquals("No expiry", HermesException.Kind.InvalidResponse, attempt()) + assertTrue("Never reached the password step", host.callsTo("/auth/password-login").isEmpty()) + // A relative Location with ./ resolves against the authorize URL and is accepted when it lands on /login. + reply(MockResponse().setResponseCode(302).setHeader("Location", "../../login").addHeader("Set-Cookie", cookieHeader)) + runBlocking { authenticator().signIn(SignInInput.Password(null, "u", "p")) } + } + + @Test fun theLoginAnswerMustCarryExactlyTheExpectedStateAndACode() { + fun attempt(next: (String) -> String) { + passwordHost(login = { _, state -> ScriptedHost.json("""{"ok":true,"next":"${next(state)}"}""") }) + } + fun run() = kind { authenticator().signIn(SignInInput.Password(null, "u", "p")) } + val invalid = HermesException.Kind.InvalidResponse + attempt { s -> "$callback?state=WRONG&code=c" }; assertEquals("state mismatch", invalid, run()) + attempt { s -> "$callback?state=$s&code=c&extra=1" }; assertEquals("extra field", invalid, run()) + attempt { s -> "$callback?state=$s&state=$s" }; assertEquals("no code", invalid, run()) + attempt { s -> "$callback?state=$s&code=a&code=b" }; assertEquals("two codes", invalid, run()) + attempt { s -> "$callback?state=$s&code=" }; assertEquals("empty code", invalid, run()) + attempt { s -> "$callback?state=$s" }; assertEquals("one field", invalid, run()) + attempt { s -> "$callback" }; assertEquals("no query", invalid, run()) + attempt { s -> "http://127.0.0.1:49153/loopdy-native-callback?state=$s&code=c" } + assertEquals("different port", HermesException.Kind.RedirectRefused, run()) + attempt { s -> "http://127.0.0.1:49152/other?state=$s&code=c" } + assertEquals("different path", HermesException.Kind.RedirectRefused, run()) + attempt { s -> "https://127.0.0.1:49152/loopdy-native-callback?state=$s&code=c" } + assertEquals("different scheme", HermesException.Kind.RedirectRefused, run()) + passwordHost(login = { _, _ -> ScriptedHost.json("""{"ok":false,"next":"$callback?state=x&code=c"}""") }) + assertEquals("ok:false", invalid, run()) + passwordHost(login = { _, _ -> MockResponse().setResponseCode(401) }) + assertEquals(HermesException.Kind.InvalidCredentials, run()) + assertTrue("No code was ever exchanged", host.callsTo("/auth/native/token").isEmpty()) + } + + @Test fun theIdentityBehindTheTokenMustMatchEverywhere() { + fun run(provider: String? = null) = kind { authenticator().signIn(SignInInput.Password(provider, "u", "p")) } + passwordHost(token = { tokenReply(provider = "other") }) + assertEquals("The token's provider is not the selected one", HermesException.Kind.IdentityChanged, run("basic")) + passwordHost(token = { tokenReply(provider = "other") }) + assertEquals("Not the only password provider either", HermesException.Kind.IdentityChanged, run()) + passwordHost(meReply = me(user = "someone-else")) + assertEquals("/api/auth/me must agree with the token", HermesException.Kind.IdentityChanged, run()) + passwordHost(meReply = me(provider = "other")) + assertEquals(HermesException.Kind.IdentityChanged, run()) + passwordHost(token = { MockResponse().setResponseCode(401) }) + assertEquals(HermesException.Kind.InvalidCredentials, run()) + passwordHost(token = { ScriptedHost.json("""{"token_type":"bearer","access_token":"a","provider":"basic","user_id":"u","expires_at":${now + 60}}""") }) + assertEquals(HermesException.Kind.InvalidResponse, run()) + } + + @Test fun theOneUseCodeIsNeverSentTwice() { + passwordHost(token = { MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST) }) + assertEquals(HermesException.Kind.ConnectionFailed, kind { authenticator().signIn(SignInInput.Password(null, "u", "p")) }) + assertEquals(1, host.callsTo("/auth/native/token").size) + } + + // Cancellation + + @Test fun cancellingASignInStagesNothingAndKeepsTheCurrentConnection() = runBlocking { + val authenticator = authenticator() + val existing = SavedConnection(host.endpoint, StoredAuth.DashboardSession("existing", true), null, null) + store.replace(null, existing) + authenticator.restoreForTest(existing) + host.on("GET", "/") { MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE) } + val attempt = async { authenticator.signIn(SignInInput.Dashboard) } + var waited = 0 + while (host.callsTo("/").isEmpty() && waited++ < 300) delay(10) + attempt.cancel() + assertThrows(CancellationException::class.java) { runBlocking { attempt.await() } } + assertEquals(existing, authenticator.savedConnection) + assertEquals(existing, store.load(existing.authority)) + } + + @Test fun cancelAuthenticationEndsTheAttemptWithACancelledError() = runBlocking { + host.on("GET", "/api/status", status(false)) + host.on("GET", "/") { MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE) } + val authenticator = authenticator() + val attempt = async { runCatching { authenticator.signIn(SignInInput.Dashboard) } } + var waited = 0 + while (host.callsTo("/").isEmpty() && waited++ < 300) delay(10) + authenticator.cancelAuthentication() + val failure = attempt.await().exceptionOrNull() + assertEquals(HermesException.Kind.Cancelled, (failure as HermesException).kind) + assertNull(authenticator.savedConnection) + } + + /** Adopts [saved] as the current connection the way a restore does, but without touching the host. */ + private suspend fun HermesAuthenticator.restoreForTest(saved: SavedConnection) { + host.on("GET", "/api/status", status(false)) + host.on("GET", "/", ScriptedHost.dashboardPage("existing")) + restore(saved) + host.requests.clear() + assertNotNull(savedConnection) + TimeUnit.MILLISECONDS.sleep(0) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt new file mode 100644 index 00000000..36e18178 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt @@ -0,0 +1,202 @@ +package app.bighelp.hermes + +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** Scripted ownership, readiness and admission scenarios. Nothing here opens a socket. */ +class HermesConnectionTest { + private val endpoint = HermesEndpoint.parse("hermes.example/p") + private val ready = HermesWire.decode( + """{"jsonrpc":"2.0","method":"event","params":{"type":"gateway.ready","payload":{"heartbeat":true}}}""".toByteArray(), + ).single() + private val notice = HermesWire.decode( + """{"jsonrpc":"2.0","method":"event","params":{"type":"notice","payload":{}}}""".toByteArray(), + ).single() + private val approval = HermesWire.decode( + """{"jsonrpc":"2.0","id":"s","method":"approval","params":{}}""".toByteArray(), + ).single() + + private fun capabilities(json: String) = GatewayCapabilities.decode(Json.parseToJsonElement(json)) + + private fun readySocket(owners: OwnerState) = + GatewaySocket.opening(owners.current!!).upgraded().receive(ready) + + private fun admit(socket: GatewaySocket, owners: OwnerState, operation: GatewayOperation) = + socket.admit(operation, owners) + + // Readiness is not the upgrade + + @Test fun upgradeAloneAllowsNoApplicationWrites() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val connecting = GatewaySocket.opening(owners.current!!) + val upgraded = connecting.upgraded() + assertEquals(SocketPhase.Connecting, connecting.phase) + assertEquals(SocketPhase.Upgraded, upgraded.phase) + listOf(connecting, upgraded).forEach { socket -> + assertFalse(socket.canWriteApplicationFrames) + GatewayOperation.entries.forEach { + assertEquals(Admission.Refused(Refusal.NotReady), admit(socket, owners, it)) + } + } + } + + @Test fun onlyGatewayReadyEndsTheWaitAndOtherMessagesDoNot() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val upgraded = GatewaySocket.opening(owners.current!!).upgraded() + assertSame(upgraded, upgraded.receive(notice)) + assertSame("Early server requests are processed but do not make the socket ready", upgraded, upgraded.receive(approval)) + val now = upgraded.receive(ready) + assertEquals(SocketPhase.Ready, now.phase) + assertTrue(now.canWriteApplicationFrames) + assertEquals("gateway.ready", now.ready?.type) + assertEquals(Admission.Admitted, admit(now, owners, GatewayOperation.Read)) + } + + @Test fun readyBeforeTheUpgradeCompletesIsNotAcceptedAndASecondReadyClosesTheSocket() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val connecting = GatewaySocket.opening(owners.current!!) + assertEquals(SocketPhase.Connecting, connecting.receive(ready).phase) + val now = readySocket(owners) + val closed = now.receive(ready) + assertEquals(SocketPhase.Closed, closed.phase) + assertFalse(closed.canWriteApplicationFrames) + assertEquals(Admission.Refused(Refusal.NotReady), admit(closed, owners, GatewayOperation.Read)) + assertEquals("A closed socket cannot become ready again", SocketPhase.Closed, closed.upgraded().receive(ready).phase) + } + + // Capability is a required Boolean + + @Test fun exclusiveSubmitMustBeAJsonBoolean() { + assertTrue(capabilities("""{"per_session_exclusive_submit":true,"future":{"x":1}}""").perSessionExclusiveSubmit) + assertFalse(capabilities("""{"per_session_exclusive_submit":false}""").perSessionExclusiveSubmit) + listOf( + "{}", "[]", "null", "true", "\"true\"", + """{"per_session_exclusive_submit":"true"}""", """{"per_session_exclusive_submit":"false"}""", + """{"per_session_exclusive_submit":null}""", """{"per_session_exclusive_submit":1}""", + """{"per_session_exclusive_submit":0}""", """{"per_session_exclusive_submit":[true]}""", + """{"per_session_exclusive_submit":{"v":true}}""", """{"Per_Session_Exclusive_Submit":true}""", + ).forEach { + try { + capabilities(it) + fail("Expected $it to fail discovery") + } catch (error: WireException) { + assertEquals("invalidResponse", error.category) + } + } + } + + @Test fun submissionNeedsTheGuaranteeButReadsAndControlsDoNot() { + var owners = OwnerState.none.connect(endpoint, "principal-1") + val undiscovered = readySocket(owners) + assertNull(undiscovered.capabilities) + assertEquals(Admission.Refused(Refusal.CapabilitiesUnknown), admit(undiscovered, owners, GatewayOperation.Submission)) + assertEquals(Admission.Admitted, admit(undiscovered, owners, GatewayOperation.Read)) + + val unsafe = undiscovered.discovered(capabilities("""{"per_session_exclusive_submit":false}""")) + assertEquals(Admission.Refused(Refusal.ExclusiveSubmitUnavailable), admit(unsafe, owners, GatewayOperation.Submission)) + assertEquals(Admission.Admitted, admit(unsafe, owners, GatewayOperation.Read)) + assertEquals(Admission.Admitted, admit(unsafe, owners, GatewayOperation.Control)) + + val safe = undiscovered.discovered(capabilities("""{"per_session_exclusive_submit":true}""")) + GatewayOperation.entries.forEach { assertEquals(Admission.Admitted, admit(safe, owners, it)) } + + // A new connection starts without them: nothing carries over from a retired socket. + owners = owners.connect(endpoint, "principal-1") + val replacement = readySocket(owners) + assertNull(replacement.capabilities) + assertEquals(Admission.Refused(Refusal.CapabilitiesUnknown), admit(replacement, owners, GatewayOperation.Submission)) + } + + @Test fun capabilitiesCanOnlyBeDiscoveredOnAReadySocket() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val upgraded = GatewaySocket.opening(owners.current!!).upgraded() + try { + upgraded.discovered(GatewayCapabilities(true)) + fail("Discovery before gateway.ready is a caller bug") + } catch (_: IllegalStateException) { + } + assertNull(readySocket(owners).closed().capabilities) + } + + // Retired generations cannot publish + + @Test fun aSupersededSocketIsRefusedEvenThoughItsOwnStateIsReady() { + val first = OwnerState.none.connect(endpoint, "principal-1") + val oldSocket = readySocket(first).discovered(GatewayCapabilities(true)) + assertEquals(Admission.Admitted, admit(oldSocket, first, GatewayOperation.Submission)) + + val second = first.connect(endpoint, "principal-1") + assertEquals(1L, first.current!!.generation) + assertEquals(2L, second.current!!.generation) + assertTrue(oldSocket.canWriteApplicationFrames) + GatewayOperation.entries.forEach { + assertEquals(Admission.Refused(Refusal.StaleOwner), admit(oldSocket, second, it)) + } + assertFalse(second.accepts(first.current!!)) + assertTrue(second.accepts(second.current!!)) + } + + @Test fun nothingPublishesWhileDisconnectedAndGenerationsNeverRepeat() { + val first = OwnerState.none.connect(endpoint, "principal-1") + val gone = first.disconnect() + assertNull(gone.current) + assertFalse(gone.accepts(first.current!!)) + assertEquals(Admission.Refused(Refusal.StaleOwner), admit(readySocket(first), gone, GatewayOperation.Read)) + + val back = gone.connect(endpoint, "principal-1") + assertEquals(2L, back.current!!.generation) + assertNotEquals("The same endpoint and principal again is still a different owner", first.current, back.current) + assertFalse(back.accepts(first.current!!)) + assertEquals(3L, back.disconnect().disconnect().connect(endpoint, "principal-1").current!!.generation) + } + + @Test fun endpointAndPrincipalAreBothPartOfWhoOwnsAResult() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val current = owners.current!! + assertTrue(owners.accepts(current.copy())) + assertFalse(owners.accepts(current.copy(principal = "principal-2"))) + assertFalse(owners.accepts(current.copy(endpoint = HermesEndpoint.parse("hermes.example/q").canonical))) + assertFalse(owners.accepts(current.copy(endpoint = HermesEndpoint.parse("hermes.example:8443/p").canonical))) + assertFalse(owners.accepts(current.copy(generation = current.generation + 1))) + assertEquals("https://hermes.example/p", current.endpoint) + + // Switching principal on the same endpoint retires the old owner's results. + val switched = owners.connect(endpoint, "principal-2") + assertFalse(switched.accepts(current)) + } + + // An unknown dispatch is never resent + + @Test fun aMutationThatMayHaveBeenSentIsUncertainAndNeverRetried() { + listOf("prompt.submit", "session.create", "session.interrupt", "future.method", "gateway.Ping", "", "session.list ") + .forEach { method -> + assertFalse(method, DispatchPolicy.isReadOnly(method)) + assertTrue(method, DispatchPolicy.isUncertain(method, DispatchOutcome.MayHaveBeenSent)) + assertFalse(method, DispatchPolicy.mayRetry(method, DispatchOutcome.MayHaveBeenSent)) + assertTrue("Never sent is safe to issue", DispatchPolicy.mayRetry(method, DispatchOutcome.NotSent)) + } + } + + @Test fun readsMayBeAskedAgainAndAnsweredRequestsNeverAre() { + assertEquals(26, DispatchPolicy.readOnlyMethods.size) + DispatchPolicy.readOnlyMethods.forEach { method -> + assertFalse(DispatchPolicy.isUncertain(method, DispatchOutcome.MayHaveBeenSent)) + assertTrue(DispatchPolicy.mayRetry(method, DispatchOutcome.MayHaveBeenSent)) + assertTrue(DispatchPolicy.mayRetry(method, DispatchOutcome.NotSent)) + } + listOf("session.history", "prompt.submit").forEach { method -> + listOf(DispatchOutcome.ConfirmedResult, DispatchOutcome.ConfirmedRefusal).forEach { + assertFalse(DispatchPolicy.mayRetry(method, it)) + assertFalse(DispatchPolicy.isUncertain(method, it)) + } + assertFalse(DispatchPolicy.isUncertain(method, DispatchOutcome.NotSent)) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt new file mode 100644 index 00000000..488fb31e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt @@ -0,0 +1,191 @@ +package app.bighelp.hermes + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** The CONNECTION.md §1 rules the basic endpoint tests do not pin down. */ +class HermesEndpointContractTest { + private fun canonical(input: String, allowPrivateHttp: Boolean = false) = + HermesEndpoint.parse(input, allowPrivateHttp).canonical + + private fun rejects(input: String, allowPrivateHttp: Boolean = false, reason: HermesEndpointException.Reason? = null) { + try { + HermesEndpoint.parse(input, allowPrivateHttp) + fail("Expected rejection of '$input'") + } catch (error: HermesEndpointException) { + if (reason != null) assertEquals(input, reason, error.reason) + } + } + + @Test fun documentedExampleBuildsEveryRoute() { + val endpoint = HermesEndpoint.parse("HERMES.EXAMPLE:443/hermes/") + assertEquals("https://hermes.example/hermes", endpoint.canonical) + assertEquals("https://hermes.example/hermes/api/status", endpoint.httpUrl("/api/status").toString()) + assertEquals("https://hermes.example/hermes/", endpoint.httpUrl("/").toString()) + assertEquals("wss://hermes.example/hermes/api/ws", endpoint.webSocketUrl) + } + + @Test fun schemeDefaultsToHttpsAndIsCaseInsensitive() { + assertEquals("https://hermes.example", canonical("hermes.example")) + assertEquals("https://hermes.example", canonical("HTTPS://Hermes.Example/")) + listOf("ftp://h.example", "ws://h.example", "wss://h.example", "file://h.example", "://h.example", + "https:/h.example", "https:///h.example", "https://", "http s://h.example", "https:h.example") + .forEach { rejects(it, true) } + } + + @Test fun defaultPortsDisappearAndOthersStayPartOfTheIdentity() { + assertEquals("https://h.example", canonical("https://h.example:443")) + assertEquals("https://h.example:8443", canonical("https://h.example:8443")) + assertEquals("https://h.example:80", canonical("https://h.example:80")) + assertEquals("http://hermes", canonical("http://hermes:80", true)) + assertEquals("http://hermes:443", canonical("http://hermes:443", true)) + assertEquals("ws://hermes:8080/p/api/ws", HermesEndpoint.parse("http://hermes:8080/p", true).webSocketUrl) + assertEquals("https://h.example:65535", canonical("h.example:65535")) + listOf("h.example:0", "h.example:65536", "h.example:", "h.example:-1", "h.example:+1", "h.example:1 2", + "h.example:999999", "h.example:80a", "h.example::80", "https://h.example:0x50").forEach { rejects(it) } + } + + @Test fun pathsPreserveThePrefixAndRejectEverythingAmbiguous() { + assertEquals("https://h.example/a/b", canonical("h.example/a/b/")) + assertEquals("https://h.example", canonical("h.example/")) + assertEquals("https://h.example/a-b_c.d~e", canonical("h.example/a-b_c.d~e")) + listOf("h.example/a//b", "h.example//", "h.example/a/./b", "h.example/./", "h.example/..", "h.example/a/../b", + "h.example/%2e%2e", "h.example/a%2fb", "h.example/%41", "h.example/a b", "h.example/ü", "h.example/a:b", + "h.example/a;b", "h.example/a@b", "h.example/a'b", "h.example/a*b", "h.example/a,b", "h.example/a=b", + "h.example/a+b", "h.example/a!b", "h.example/a(b)", "h.example/a\\b").forEach { rejects(it) } + } + + @Test fun credentialsQueryAndFragmentAreRefusedEvenWhenEmpty() { + listOf("https://@h.example", "https://u@h.example", "https://u:p@h.example", "https://h.example:443@evil.example", + "https://evil.example\\@h.example", "https://h.example?", "https://h.example/?", "https://h.example/a?x=1", + "https://h.example#", "https://h.example/#f", "h.example/a#b", "https://h.example/p?next=//evil") + .forEach { rejects(it, true) } + } + + @Test fun whitespaceControlsAndNonAsciiAreRefused() { + listOf("", " ", "\th.example", "h.example\n", "h .example", "h.example\u007f", "h.example\u0000", "hérmes.example", + "h.example\u00a0", "h.example", "h.example/\u2028", "https://h.example/a\r\n", "h" + "e".repeat(2_048) + ".example") + .forEach { rejects(it, true) } + } + + @Test fun hostNamesFollowDnsLabelRulesWithoutNumericAliases() { + assertEquals("https://xn--bcher-kva.example", canonical("XN--BCHER-KVA.EXAMPLE")) + assertEquals("https://a-b.example", canonical("a-b.example")) + assertEquals("https://1e3.example", canonical("1e3.example")) + val label = "a".repeat(63) + assertEquals("https://$label.example", canonical("$label.example")) + listOf("${label}a.example", "-a.example", "a-.example", "a..example", ".example", "a_b.example", "a b.example", + "a.example.", "a.", "[a.example]", "${"a".repeat(62)}.".repeat(5) + "example", + // Numeric aliases and malformed dotted quads + "127.1", "127.0.1", "0x7f.0.0.1", "0x7f000001", "2130706433", "017700000001", "1.2.3", "1.2.3.4.5", "256.1.1.1", + "010.0.0.1", "1.2.3.04", "1.2.3.4.", ".1.2.3.4", "0x1", "0X7F000001", "1..2.3", + ).forEach { rejects(it, true) } + assertEquals("https://0.0.0.0", canonical("0.0.0.0")) + assertEquals("https://8.8.8.8:8080", canonical("8.8.8.8:8080")) + } + + @Test fun ipv6LiteralsAreBracketedLowercasedAndNeverResolved() { + assertEquals("https://[::1]", canonical("[::1]")) + assertEquals("https://[::1]", canonical("::1")) + assertEquals("https://[fd7a:115c:a1e0::1]:8443/p", canonical("[FD7A:115C:A1E0::1]:8443/p/")) + assertEquals("https://[fd7a:115c:a1e0::1]", canonical("FD7A:115C:A1E0::1")) + assertEquals("https://[::ffff:1.2.3.4]", canonical("[::ffff:1.2.3.4]")) + assertEquals("https://[1:2:3:4:5:6:7:8]", canonical("[1:2:3:4:5:6:7:8]")) + assertEquals("https://[1:2:3:4:5:6:7::]", canonical("[1:2:3:4:5:6:7::]")) + assertEquals("wss://[::1]:9/p/api/ws", HermesEndpoint.parse("[::1]:9/p").webSocketUrl) + assertEquals("https://[::1]:9/p/api/x", HermesEndpoint.parse("[::1]:9/p").httpUrl("/api/x").toString()) + // A bare literal has no way to carry a port, so "::1:8080" is the address ::1:8080, not port 8080. + assertEquals("https://[::1:8080]", canonical("::1:8080")) + listOf("[::1", "::1]", "[::1]x", "[::1]:", "[::1]:0", "[[::1]]", "[]", "[:::1]", "[1::2::3]", "[1:2:3:4:5:6:7:8:9]", + "[1:2:3:4:5:6:7::8]", "[1:2:3:4:5:6:7:8::]", "[12345::]", "[g::1]", "[1.2.3.4]", "[example.com]", "[::1.2.3]", + "[::01.2.3.4]", "[1.2.3.4::]", "[::1%25en0]", "[::1%en0]", "[fe80::1%25en0]", "::1%en0", "[ ::1]", + "[::ff]", "1:2:3::4::", "::1/path:x@y", "https://::1", "https://::1:80").forEach { rejects(it, true) } + } + + @Test fun plainHttpNeedsOptInAndASyntacticallyPrivateHost() { + val rejectedWithoutOptIn = HermesEndpointException.Reason.PlaintextNotAllowed + rejects("http://hermes", false, rejectedWithoutOptIn) + rejects("http://example.com", true, rejectedWithoutOptIn) + rejects("http://192.0.2.1", true, rejectedWithoutOptIn) + rejects("http://h.example/%", true, HermesEndpointException.Reason.InvalidEndpoint) + + listOf( + "127.0.0.1", "127.255.255.254", "10.0.0.1", "10.255.255.255", "172.16.0.1", "172.31.255.255", + "192.168.0.1", "192.168.255.255", "100.64.0.1", "100.127.255.255", "169.254.1.1", + "[::1]", "[0:0:0:0:0:0:0:1]", "[fc00::1]", "[fdff:ffff::1]", "[fd7a:115c:a1e0::1]", "[FD7A::1]", + "hermes", "HERMES", "localhost", "printer.local", "nas.lan", "box.internal", "r.home.arpa", "app.intranet", + "x.corp", "pc.localdomain", "x.private", "app.localhost", "a.b.local", "bot.ts.net", "x.y.ts.net", + "bot.beta.tailscale.net", "local", "xlocal", + ).forEach { assertEquals("http://${it.lowercase()}", canonical("http://$it", true)) } + + listOf( + "172.15.255.255", "172.32.0.1", "100.63.255.255", "100.128.0.1", "192.167.0.1", "192.169.0.1", "11.0.0.1", + "9.255.255.255", "169.253.1.1", "126.0.0.1", "128.0.0.1", "1.1.1.1", "0.0.0.0", "255.255.255.255", + "[::]", "[::2]", "[::ffff:127.0.0.1]", "[::ffff:10.0.0.1]", "[fe80::1]", "[fe00::1]", "[fb00::1]", "[fe00::]", + "[2001:db8::1]", "[1::1]", "[::1:0]", "[100::1]", + "example.com", "hermes.example.com", "127.0.0.1.example.com", "hermes.lan.example.com", "example-ts.net", + "ts.net", "tailscale.net", "beta.tailscale.net", "x.localhost.com", "x.corpus", "my.home.arpa.evil.com", + "xts.net", "bot.ts.net.evil.com", + ).forEach { rejects("http://$it", true, HermesEndpointException.Reason.PlaintextNotAllowed) } + } + + @Test fun routesAreAppOwnedRelativePathsOnly() { + val endpoint = HermesEndpoint.parse("h.example:8443/p") + assertEquals("https://h.example:8443/p/api/sessions/abc:1_x-y.z~", endpoint.httpUrl("/api/sessions/abc:1_x-y.z~").toString()) + assertEquals("https://h.example:8443/p/api/files/", endpoint.httpUrl("/api/files/").toString()) + listOf( + "", "api/x", "x", "https://h.example/p/api/x", "http://evil", "//evil", "//", "/a//b", "/./x", "/x/.", "/..", "/x/../y", + "/x?q=1", "/x?", "/x#f", "/x#", "/x%2f", "/x%", "/x\\y", "\\x", "/x y", "/x\ty", "/x\ny", "/é", "/x\u0000", "/x\u007f", + "/x\"y", "/xy", "/x{y}", "/x|y", "/x^y", "/x`y", "/x[y]", "@evil", "/x\u2028", + ).forEach { route -> + try { + endpoint.httpUrl(route) + fail("Expected route '$route' to be refused") + } catch (error: HermesEndpointException) { + assertEquals(HermesEndpointException.Reason.InvalidRoute, error.reason) + } + } + // Every accepted route stays under the exact origin and prefix. + val url = endpoint.httpUrl("/api/x") + assertEquals("h.example", url.host) + assertEquals(8443, url.port) + assertTrue(url.path.startsWith("/p/")) + } + + @Test fun canonicalFormParsesBackToItself() { + listOf( + "HERMES.EXAMPLE:443/hermes/", "h.example:8443/a/b/", "[FD7A::1]:80/p", "::1", "http://Hermes.LAN:80/x/", + "http://[::1]:8080", "https://8.8.8.8", "http://100.64.0.1/p/q", + ).forEach { input -> + val first = HermesEndpoint.parse(input, true) + val again = HermesEndpoint.parse(first.canonical, true) + assertEquals(input, first.canonical, again.canonical) + assertEquals(input, first, again) + assertEquals(first.webSocketUrl, again.webSocketUrl) + } + } + + @Test fun identityIncludesSchemePortPrefixAndTheOptIn() { + val base = HermesEndpoint.parse("https://h.example/a") + assertEquals(base, HermesEndpoint.parse("H.EXAMPLE:443/a/")) + assertEquals(base.hashCode(), HermesEndpoint.parse("H.EXAMPLE:443/a/").hashCode()) + assertNotEquals(base, HermesEndpoint.parse("https://h.example/b")) + assertNotEquals(base, HermesEndpoint.parse("https://h.example:8443/a")) + assertNotEquals(base, HermesEndpoint.parse("https://h.example")) + assertNotEquals(base, HermesEndpoint.parse("https://h.example/a", allowPrivateHttp = true)) + assertNotEquals(HermesEndpoint.parse("http://hermes", true), HermesEndpoint.parse("https://hermes", true)) + } + + @Test fun failuresAreIllegalArgumentsThatNeverEchoTheInput() { + val secret = "https://user:hunter2@h.example/?token=abc" + try { + HermesEndpoint.parse(secret) + fail("credentials must be refused") + } catch (error: IllegalArgumentException) { + assertTrue(!(error.message ?: "").contains("hunter2") && !(error.message ?: "").contains("abc")) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt new file mode 100644 index 00000000..9a4d1179 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt @@ -0,0 +1,39 @@ +package app.bighelp.hermes + +import org.junit.Assert.* +import org.junit.Test + +class HermesEndpointTest { + @Test fun normalizesIdentityAndPreservesDeploymentPrefix() { + val endpoint = HermesEndpoint.parse("HERMES.EXAMPLE:443/hermes/") + assertEquals("https://hermes.example/hermes", endpoint.canonical) + assertEquals("https://hermes.example/hermes/api/status", endpoint.httpUrl("/api/status").toString()) + assertEquals("wss://hermes.example/hermes/api/ws", endpoint.webSocketUrl) + } + + @Test fun privateHttpRequiresBothOptInAndPrivateSyntax() { + listOf("127.0.0.1", "10.2.3.4", "100.64.0.1", "hermes", "bot.ts.net", "[::1]").forEach { + rejects("http://$it") + assertTrue(HermesEndpoint.parse("http://$it", true).canonical.startsWith("http://")) + } + listOf("example.com", "127.0.0.1.example.com", "example-ts.net", "8.8.8.8", "[fe80::1]").forEach { + rejects("http://$it", true) + } + } + + @Test fun rejectsCredentialSmugglingTraversalAndAmbiguousAddresses() { + listOf(" https://hermes.example", "https://u:p@hermes.example", "https://hermes.example/?token=x", + "https://hermes.example/#x", "https://hermes.example/a/../b", "https://hermes.example/%2e", + "https://hermes.example//a", "https://hermes.example:", "https://hermes.example:65536", + "https://127.1", "https://0x7f000001", "https://2130706433", "https://host.", "https://host\\evil" + ).forEach { rejects(it, true) } + val endpoint = HermesEndpoint.parse("hermes.example/prefix") + listOf("https://other.example", "//evil", "/a/../b", "/api/x?q=1", "/%2f").forEach { + try { endpoint.httpUrl(it); fail(it) } catch (_: IllegalArgumentException) { } + } + } + + private fun rejects(input: String, allowPrivateHttp: Boolean = false) { + try { HermesEndpoint.parse(input, allowPrivateHttp); fail(input) } catch (_: IllegalArgumentException) { } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt new file mode 100644 index 00000000..6708762d --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt @@ -0,0 +1,191 @@ +package app.bighelp.hermes + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** Every documented ceiling, at the limit and one byte over, in characters of 1 to 4 UTF-8 bytes. */ +class HermesWireLimitsTest { + private val units = listOf("a", "é", "€", "😀") + + /** A string of exactly [bytes] UTF-8 bytes whose bulk is [unit], padded with ASCII. */ + private fun exactly(unit: String, bytes: Int): String { + val bulk = unit.repeat(bytes / unit.toByteArray().size) + return bulk + "a".repeat(bytes - bulk.toByteArray().size) + } + + private fun decode(frame: String) = HermesWire.decode(frame.toByteArray()) + + private fun rejects(category: String, frame: String) = rejects(category, frame.toByteArray()) + + private fun rejects(category: String, bytes: ByteArray) { + try { + HermesWire.decode(bytes) + fail("Expected $category") + } catch (error: WireException) { + assertEquals(category, error.category) + } + } + + private fun response(id: String) = """{"jsonrpc":"2.0","id":"$id","result":null}""" + private fun request(id: String, method: String = "approval") = """{"jsonrpc":"2.0","id":"$id","method":"$method","params":{}}""" + private fun event(type: String, payload: String = "{}") = + """{"jsonrpc":"2.0","method":"event","params":{"type":"$type","payload":$payload}}""" + private fun cancel(id: String = "a", method: String = "clarify", reason: String = "expired") = + event("request.cancel", """{"id":"$id","method":"$method","reason":"$reason"}""") + + @Test fun idsAreBoundedInUtf8BytesForRequestsAndResponses() { + units.forEach { unit -> + val atLimit = exactly(unit, 1_024) + assertEquals(1_024, atLimit.toByteArray().size) + assertEquals("result:$atLimit", decode(response(atLimit)).single().classification) + assertEquals("request:approval", decode(request(atLimit)).single().classification) + rejects("invalidResponse", response(atLimit + "a")) + rejects("invalidResponse", request(atLimit + "a")) + } + } + + @Test fun methodsAreAsciiAndBoundedAt256() { + val atLimit = "m".repeat(256) + assertEquals("request:$atLimit", decode(request("a", atLimit)).single().classification) + rejects("invalidResponse", request("a", atLimit + "m")) + // Printable ASCII only: the boundary characters U+0021 and U+007E pass, space, DEL and non-ASCII do not. + assertEquals("request:!~", decode(request("a", "!~")).single().classification) + listOf(" ", "\\u007f", "m\\u00e9", "m\\u0001").forEach { rejects("invalidResponse", request("a", "x$it")) } + } + + @Test fun eventTypesAreBoundedInUtf8Bytes() { + units.forEach { unit -> + val atLimit = exactly(unit, 256) + assertEquals("event:$atLimit", decode(event(atLimit)).single().classification) + rejects("invalidResponse", event(atLimit + "a")) + } + } + + @Test fun cancellationReasonIsBoundedInUtf8Bytes() { + units.forEach { unit -> + val atLimit = exactly(unit, 4_096) + val cancellation = HermesWire.cancellation(decode(cancel(reason = atLimit)).single() as WireMessage.Event) + assertEquals(atLimit, cancellation.reason) + rejects("invalidResponse", cancel(reason = atLimit + "a")) + } + } + + @Test fun cancellationIdAndMethodAreValidatedLikeRequests() { + val longestId = exactly("😀", 1_024) + assertEquals(longestId, HermesWire.cancellation(decode(cancel(id = longestId)).single() as WireMessage.Event).id) + rejects("invalidResponse", cancel(id = longestId + "a")) + rejects("invalidResponse", cancel(method = "m".repeat(257))) + rejects("invalidResponse", cancel(method = "has space")) + } + + @Test fun cancellationPayloadMustBeExactlyIdMethodReason() { + listOf( + """{"id":"a","method":"clarify"}""", + """{"id":"a","reason":"x"}""", + """{"method":"clarify","reason":"x"}""", + """{"id":"a","method":"clarify","reason":"x","extra":1}""", + """{"id":1,"method":"clarify","reason":"x"}""", + """{"id":"a","method":null,"reason":"x"}""", + """{"id":"a","method":"clarify","reason":7}""", + """{"id":"a","method":"clarify","reason":null}""", + """{}""", + ).forEach { rejects("invalidResponse", event("request.cancel", it)) } + // An event with no payload key at all is a cancellation with no keys. + rejects("invalidResponse", """{"jsonrpc":"2.0","method":"event","params":{"type":"request.cancel"}}""") + } + + @Test fun cancellationIsDecodedFromTheEventForTheOwnerToMatch() { + val message = decode(cancel(id = " é ", method = "approval", reason = "done")).single() as WireMessage.Event + assertEquals(RequestCancellation(" é ", "approval", "done"), HermesWire.cancellation(message)) + try { + HermesWire.cancellation(decode(event("notice")).single() as WireMessage.Event) + fail("A non-cancel event is not a cancellation") + } catch (error: WireException) { + assertEquals("invalidResponse", error.category) + } + } + + @Test fun wholeMessageCeilingCountsBytesNotCharacters() { + val head = """{"jsonrpc":"2.0","id":"r","result":"""" + val tail = "\"}" + val body = 4_194_304 - head.length - tail.length + // 4-byte characters fill the frame with a character count far under the byte ceiling. + val filler = "😀".repeat(body / 4) + "a".repeat(body % 4) + val exact = (head + filler + tail).toByteArray() + assertEquals(4_194_304, exact.size) + assertTrue(exact.size > (head + filler + tail).length) + assertEquals(1, HermesWire.decode(exact).size) + rejects("messageTooLarge", exact + byteArrayOf(' '.code.toByte())) + } + + @Test fun messageCeilingIsCheckedBeforeAnyParsing() { + // Not even JSON, but over the ceiling: the size category wins and nothing is parsed. + rejects("messageTooLarge", ByteArray(4_194_305) { 0xff.toByte() }) + } + + @Test fun nonBlankLineCountIgnoresBlankLines() { + val one = response("r") + val padded = List(4_096) { one }.joinToString("\n\n \t\r\n") + assertEquals(4_096, decode(padded + "\n\n\n").size) + rejects("messageTooLarge", List(4_097) { one }.joinToString("\n\n")) + } + + @Test fun nestingDepthCountsTheWholeValueIncludingEnvelopeObjects() { + fun nested(arrays: Int) = event("deep", """{"x":""" + "[".repeat(arrays) + "0" + "]".repeat(arrays) + "}") + // Envelope (1) + params (2) + payload (3) + "x" arrays: 61 arrays reach exactly 64 levels. + assertEquals(1, decode(nested(61)).size) + rejects("messageTooLarge", nested(62)) + // Objects count like arrays: the envelope plus 63 nested objects is 64 levels. + fun objects(count: Int) = + """{"jsonrpc":"2.0","id":"r","result":""" + """{"a":""".repeat(count - 1) + "{}" + "}".repeat(count - 1) + "}" + assertEquals(1, decode(objects(63)).size) + rejects("messageTooLarge", objects(64)) + } + + @Test fun bracketsInsideStringsDoNotCountAsDepth() { + val noisy = "[".repeat(200) + """\"[[""" + "]".repeat(200) + assertEquals("result:r", decode("""{"jsonrpc":"2.0","id":"r","result":"$noisy"}""").single().classification) + } + + @Test fun depthIsMeasuredPerLineSoNewlinesResetIt() { + val deepEnough = """{"jsonrpc":"2.0","id":"r","result":""" + "[".repeat(63) + "0" + "]".repeat(63) + "}" + assertEquals(3, decode(listOf(deepEnough, deepEnough, deepEnough).joinToString("\n")).size) + } + + @Test fun anyBadLineRejectsTheWholeMessageWithoutPublishingEarlierOnes() { + val good = response("first") + val tooDeep = """{"jsonrpc":"2.0","id":"b","result":""" + "[".repeat(65) + "]".repeat(65) + "}" + listOf( + "invalidResponse" to good.toByteArray() + "\n{".toByteArray(), + "invalidResponse" to good.toByteArray() + "\n".toByteArray() + byteArrayOf(0x7b, 0x22, 0xff.toByte(), 0x22, 0x7d), + "invalidResponse" to good.toByteArray() + "\n[1]".toByteArray(), + "messageTooLarge" to (good + "\n" + tooDeep).toByteArray(), + ).forEach { (category, bytes) -> rejects(category, bytes) } + } + + @Test fun firstViolationInWireOrderDecidesTheCategory() { + val bad = "{" + val one = response("r") + // An invalid line before the 4,097th object is reported first... + rejects("invalidResponse", (listOf(bad) + List(4_097) { one }).joinToString("\n")) + // ...and one after it is never reached. + rejects("messageTooLarge", (List(4_097) { one } + listOf(bad)).joinToString("\n")) + } + + @Test fun opaqueIdsKeepTheirExactUtf8Bytes() { + val composed = "request:é" + val decomposed = "request:é" + listOf(composed, decomposed, "😀", "", " lead\ttrail ", "‮").forEach { id -> + val escaped = id.map { if (it.code < 0x20) "\\u%04x".format(it.code) else it.toString() }.joinToString("") + val request = decode("""{"jsonrpc":"2.0","id":"$escaped","method":"approval","params":{}}""").single() + as WireMessage.Request + assertArrayEquals(id.toByteArray(), request.id.toByteArray()) + } + val a = decode(request(composed)).single() as WireMessage.Request + val b = decode(request(decomposed)).single() as WireMessage.Request + assertTrue("Canonically equivalent IDs must stay distinct", a.id != b.id) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt new file mode 100644 index 00000000..19540956 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt @@ -0,0 +1,165 @@ +package app.bighelp.hermes + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** What counts as a well-formed frame beyond the shared vectors: JSON grammar, UTF-8 and field types. */ +class HermesWireStrictnessTest { + private fun decode(frame: String) = HermesWire.decode(frame.toByteArray()) + + private fun rejects(frame: String, category: String = "invalidResponse") = rejects(frame.toByteArray(), category, frame) + + private fun rejects(bytes: ByteArray, category: String = "invalidResponse", label: String = bytes.contentToString()) { + try { + HermesWire.decode(bytes) + fail("Expected rejection of $label") + } catch (error: WireException) { + assertEquals(label, category, error.category) + } + } + + private fun result(value: String) = """{"jsonrpc":"2.0","id":"r","result":$value}""" + private fun eventParams(params: String) = """{"jsonrpc":"2.0","method":"event","params":$params}""" + + @Test fun grammarViolationsRejectTheFrame() { + listOf( + """{"jsonrpc":"2.0","id":"r","result":{},}""", // trailing comma + """{"jsonrpc":"2.0","id":"r","result":[1,]}""", + """{"jsonrpc":"2.0","id":"r","jsonrpc":"2.0","result":{}}""", // duplicate keys, top level + """{"jsonrpc":"2.0","id":"r","result":{"a":1,"a":2}}""", // and nested + """{"jsonrpc":"2.0","id":"r","id":"s","result":{}}""", + result("01"), result("+1"), result(".5"), result("1."), result("1e"), result("-"), result("0x10"), + result("NaN"), result("Infinity"), result("-Infinity"), result("1e999"), result("-1e999"), + result("'single'"), result("tru"), result("nul"), result("True"), + result("\"a\tb\""), // raw control character in a string + result("\"a\\x41\""), result("\"\\u12G4\""), result("\"\\u12\""), result("\"unterminated"), + result("{} /* comment */"), result("1 2"), + result("{\"a\" 1}"), result("{\"a\":}"), result("{1:2}"), result("[,]"), + """{"jsonrpc":"2.0","id":"r","result":{}} x""", // trailing text + """{"jsonrpc":"2.0","id":"r","result":{}}{"jsonrpc":"2.0","id":"s","result":{}}""", // two on one line + "\u0000" + result("{}"), "\u000b" + result("{}"), "\u00a0" + result("{}"), + "\ufeff" + result("{}"), // a byte-order mark is not whitespace + ).forEach { rejects(it) } + } + + @Test fun legalGrammarIsAccepted() { + val frame = result("""{"neg":-0,"exp":1E+2,"frac":0.5,"zero":0,"empty":[],"esc":"\/\b\f\n\r\t\"\\","u":"\u00e9\ud83d\ude00"}""") + val value = (decode(frame).single() as WireMessage.Result).value as JsonObject + assertEquals("é😀", (value["u"] as JsonPrimitive).content) + assertEquals("/\b\u000c\n\r\t\"\\", (value["esc"] as JsonPrimitive).content) + } + + @Test fun integersKeepSixtyFourBitsAndOtherNumbersAreNotIntegers() { + fun seq(text: String) = (decode(eventParams("""{"type":"n","seq":$text}""")).single() as WireMessage.Event).sequence + assertEquals(Long.MAX_VALUE, seq("9223372036854775807")) + assertEquals(Long.MIN_VALUE, seq("-9223372036854775808")) + assertEquals(0L, seq("-0")) + listOf("1.0", "1e2", "1E0", "9223372036854775808", "-9223372036854775809", "\"1\"", "null", "true", "[]") + .forEach { rejects(eventParams("""{"type":"n","seq":$it}""")) } + // A result value is any JSON value; an integer too large for 64 bits is a finite number, not an error. + assertEquals("result:r", decode(result("9223372036854775808")).single().classification) + } + + @Test fun malformedUtf8RejectsTheWholeMessageEvenInBlankOrIgnoredPlaces() { + val prefix = """{"jsonrpc":"2.0","id":"r","result":"""".toByteArray() + val suffix = "\"}".toByteArray() + listOf( + byteArrayOf(0xff.toByte()), // never valid + byteArrayOf(0xc0.toByte(), 0x80.toByte()), // overlong NUL + byteArrayOf(0xe0.toByte(), 0x80.toByte(), 0xaf.toByte()), // overlong slash + byteArrayOf(0xed.toByte(), 0xa0.toByte(), 0x80.toByte()), // UTF-8 encoded surrogate + byteArrayOf(0xf4.toByte(), 0x90.toByte(), 0x80.toByte(), 0x80.toByte()), // above U+10FFFF + byteArrayOf(0xe2.toByte(), 0x82.toByte()), // truncated euro sign + byteArrayOf(0x80.toByte()), // stray continuation byte + ).forEach { rejects(prefix + it + suffix) } + // A multibyte sequence cut by a newline is malformed too; it cannot borrow the next line's bytes. + rejects(prefix + byteArrayOf(0xe2.toByte(), 0x0a) + suffix) + } + + @Test fun escapedUnpairedSurrogatesCannotBecomeIds() { + listOf("\\ud800", "\\udc00", "\\ud800x", "\\ud800\\u0041", "\\udc00\\ud800", "\\ud83d") + .forEach { rejects("""{"jsonrpc":"2.0","id":"$it","result":null}""") } + val pair = decode("""{"jsonrpc":"2.0","id":"\ud83d\ude00","result":null}""").single() as WireMessage.Result + assertEquals("😀", pair.id) + // Keys obey the same rule. + rejects(result("""{"\ud800":1}""")) + } + + @Test fun envelopeFieldsHaveExactTypes() { + listOf( + """{"jsonrpc":2.0,"id":"r","result":{}}""", + """{"jsonrpc":null,"id":"r","result":{}}""", + """{"jsonrpc":"2.0","id":"r","method":null,"params":{}}""", + """{"jsonrpc":"2.0","id":"r","method":"approval","params":"x"}""", + """{"jsonrpc":"2.0","id":"r","method":"approval","params":1}""", + """{"jsonrpc":"2.0","id":"r","method":"approval","params":{},"error":null}""", + """{"jsonrpc":"2.0","id":"r","error":null}""", + """{"jsonrpc":"2.0","id":"r","error":[]}""", + """{"jsonrpc":"2.0","id":"r","error":{}}""", + """{"jsonrpc":"2.0","id":"r","error":{"code":1.5}}""", + """{"jsonrpc":"2.0","id":"r","error":{"code":null}}""", + """{"jsonrpc":"2.0","id":"r","error":{"code":1},"result":null}""", + """{"jsonrpc":"2.0","id":"r","result":{},"params":null}""", + eventParams("""{"type":"n","payload":"x"}"""), + eventParams("""{"type":"n","session_id":false}"""), + eventParams("""{"type":7}"""), + eventParams("null"), eventParams("[]"), eventParams("\"x\""), + """{"jsonrpc":"2.0","method":"event"}""", + """{"jsonrpc":"2.0","method":"event","id":null,"params":{"type":"n"}}""", + """{"jsonrpc":"2.0","method":"event","params":{"type":"n"},"result":null}""", + ).forEach { rejects(it) } + } + + @Test fun eventsKeepTheirCoordinatesPayloadDefaultsAndFutureMetadata() { + val event = decode(eventParams("""{"type":"future","session_id":"runtime-é","seq":-3,"extra":{"k":[1]}}""")).single() + as WireMessage.Event + assertEquals("runtime-é", event.sessionID) + assertEquals(-3L, event.sequence) + assertTrue(event.payload.isEmpty()) + assertTrue("extra" in event.parameters && "type" in event.parameters) + + val noCoordinates = decode(eventParams("""{"type":"n","session_id":null,"payload":{"k":1}}""")).single() + as WireMessage.Event + assertNull(noCoordinates.sessionID) + assertNull(noCoordinates.sequence) + assertEquals(setOf("k"), noCoordinates.payload.keys) + } + + @Test fun serverRequestsDefaultParamsAndAcceptUnknownMethods() { + val absent = decode("""{"jsonrpc":"2.0","id":"s","method":"future.method"}""").single() as WireMessage.Request + val nullParams = decode("""{"jsonrpc":"2.0","id":"s","method":"secret","params":null}""").single() as WireMessage.Request + assertTrue(absent.params.isEmpty() && nullParams.params.isEmpty()) + assertEquals("request:future.method", absent.classification) + } + + @Test fun failuresKeepCodeMachineReasonAndASafeMessageSeparately() { + fun failure(error: String) = decode("""{"jsonrpc":"2.0","id":"r","error":$error}""").single() as WireMessage.Failure + + val busy = failure("""{"code":4090,"message":"Busy","data":{"reason":"MAX_CONCURRENT_SESSIONS"}}""") + assertEquals(4090L, busy.code) + assertEquals("MAX_CONCURRENT_SESSIONS", busy.reason) + assertEquals("Busy", busy.message) + + val bare = failure("""{"code":-32601}""") + assertNull(bare.reason) + assertNull(bare.message) + // Anything that is not a string reason is no reason; code 4090 alone is not the session limit. + assertNull(failure("""{"code":4090,"data":{"reason":7}}""").reason) + assertNull(failure("""{"code":4090,"data":"MAX_CONCURRENT_SESSIONS"}""").reason) + assertEquals(Long.MIN_VALUE, failure("""{"code":-9223372036854775808}""").code) + + // Hermes' words become one plain line: breaks, control and bidi characters turn into spaces. + assertEquals("one two three four", failure("""{"code":1,"message":"one\ntwo\u202ethree four"}""").message) + assertNull(failure("""{"code":1,"message":" \n\t\u200b "}""").message) + val long = failure("""{"code":1,"message":"${"x".repeat(400)}"}""").message!! + assertEquals(280, long.codePointCount(0, long.length)) + assertTrue(long.endsWith("…")) + val emoji = failure("""{"code":1,"message":"${"😀".repeat(400)}"}""").message!! + assertEquals(280, emoji.codePointCount(0, emoji.length)) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt new file mode 100644 index 00000000..b1f5b708 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt @@ -0,0 +1,58 @@ +package app.bighelp.hermes + +import java.io.File +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Test + +class HermesWireTest { + @Test fun sharedContractVectors() { + val vectors = Json.parseToJsonElement(File(System.getProperty("hermes.wireVectors")).readText()).jsonObject + val cases = vectors.getValue("cases").jsonArray + assertEquals(55, cases.size) + cases.forEach { element -> + val case = element.jsonObject + val name = case.getValue("id").jsonPrimitive.content + val expected = case.getValue("expected").jsonArray.map { it.jsonPrimitive.content } + try { + val actual = HermesWire.decode(case.getValue("frame").jsonPrimitive.content.toByteArray()) + assertEquals(name, expected, actual.map { it.classification }) + } catch (error: WireException) { + // The vectors spell a rejection "reject:"; tests elsewhere use the bare category. + assertEquals(name, expected, listOf("reject:${error.category}")) + } + } + } + + @Test fun generatedLimitsUseUtf8BytesAndWholeEnvelopeDepth() { + fun result(id: String) = """{"jsonrpc":"2.0","id":"$id","result":null}""" + assertEquals(1, HermesWire.decode(result("é".repeat(512)).toByteArray()).size) + rejects("invalidResponse", result("é".repeat(512) + "a")) + val one = result("r") + assertEquals(4096, HermesWire.decode(List(4096) { one }.joinToString("\n").toByteArray()).size) + rejects("messageTooLarge", List(4097) { one }.joinToString("\n")) + val base = """{"jsonrpc":"2.0","id":"r","result":""" + assertEquals(1, HermesWire.decode((base + "[".repeat(63) + "0" + "]".repeat(63) + "}").toByteArray()).size) + rejects("messageTooLarge", base + "[".repeat(64) + "0" + "]".repeat(64) + "}") + // Pad a small valid frame instead, to isolate the entire-message byte ceiling. + val exact = one + " ".repeat(4_194_304 - one.toByteArray().size) + assertEquals(1, HermesWire.decode(exact.toByteArray()).size) + rejects("messageTooLarge", exact + " ") + } + + @Test fun preservesOpaqueIdsAndMachineRefusalReason() { + val request = HermesWire.decode("""{"jsonrpc":"2.0","id":" é ","method":"approval","params":{}}""".toByteArray()).single() as WireMessage.Request + assertEquals(" é ", request.id) + val refusal = HermesWire.decode("""{"jsonrpc":"2.0","id":"r","error":{"code":4090,"message":"Busy","data":{"reason":"SESSION_NOT_OWNED"}}}""".toByteArray()).single() as WireMessage.Failure + assertEquals("SESSION_NOT_OWNED", refusal.reason) + } + + private fun rejects(category: String, frame: String) { + try { + HermesWire.decode(frame.toByteArray()) + fail("Expected $category") + } catch (error: WireException) { + assertEquals(category, error.category) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/LoopbackCallbackListenerTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/LoopbackCallbackListenerTest.kt new file mode 100644 index 00000000..7155a81e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/LoopbackCallbackListenerTest.kt @@ -0,0 +1,231 @@ +package app.bighelp.hermes + +import java.net.ConnectException +import java.net.InetAddress +import java.net.Socket +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The device-local loopback callback of browser sign-in: strict single-request validation on a real socket. */ +class LoopbackCallbackListenerTest { + private val path = "/loopdy-native-callback/rnd_Path-1" + private val state = "state_1-Z" + private val listeners = mutableListOf() + + @After fun stop() = listeners.forEach { it.close() } + + private fun bind(timings: AuthTimings = AuthTimings(callbackRequestMillis = 400)) = + LoopbackCallbackListener.bind(path, state, timings).also { listeners += it } + + private fun request(port: Int, target: String = "$path?state=$state&code=code-1", host: String? = "127.0.0.1:$port", vararg extra: String, method: String = "GET", version: String = "HTTP/1.1") = + buildString { + append("$method $target $version\r\n") + if (host != null) append("Host: $host\r\n") + extra.forEach { append("$it\r\n") } + append("\r\n") + } + + /** Sends raw bytes and returns what came back: empty when the listener closed without an answer. */ + private fun exchange(port: Int, raw: String, waitMillis: Int = 2_000): String = try { + Socket(InetAddress.getByName("127.0.0.1"), port).use { socket -> + socket.soTimeout = waitMillis + socket.getOutputStream().apply { write(raw.toByteArray()); flush() } + socket.getInputStream().readBytes().toString(Charsets.US_ASCII) + } + } catch (_: java.net.SocketException) { + "" // reset or closed by the listener + } catch (_: java.net.SocketTimeoutException) { + "" + } + + private fun validate(raw: String, port: Int = 4242) = LoopbackCallbackListener.validate(raw.toByteArray(), port, path, state) + private fun refused(raw: String, port: Int = 4242) = assertThrows(raw, HermesException::class.java) { validate(raw, port) }.kind + + // Pure validation + + @Test fun aWellFormedCallbackYieldsTheCodeWithEitherFieldOrder() { + assertEquals("code-1", validate(request(4242))) + assertEquals("code-1", validate(request(4242, "$path?code=code-1&state=$state"))) + assertEquals("Content-Length 0 and ordinary headers are fine", "code-1", + validate(request(4242, extra = arrayOf("Content-Length: 0", "User-Agent: Mozilla/5.0", "Accept: text/html")))) + assertEquals("Percent-encoded token characters decode strictly", "a-b_C", validate(request(4242, "$path?state=$state&code=a%2Db%5FC"))) + assertEquals("c".repeat(4_096), validate(request(4242, "$path?state=$state&code=${"c".repeat(4_096)}"))) + } + + @Test fun everyDeviationIsRefused() { + val invalid = HermesException.Kind.InvalidResponse + fun bad(raw: String) = assertEquals(raw.take(80), invalid, refused(raw)) + bad(request(4242, "/other?state=$state&code=c")) + bad(request(4242, "$path/x?state=$state&code=c")) + bad(request(4242, "$path?state=WRONG&code=c")) + bad(request(4242, "$path?state=$state&code=c&x=1")) + bad(request(4242, "$path?state=$state")) + bad(request(4242, "$path?state=$state&state=$state")) + bad(request(4242, "$path?state=$state&code=a&code=b")) + bad(request(4242, "$path?state=$state&code=")) + bad(request(4242, "$path?state=$state&code=a b")) + bad(request(4242, "$path?state=$state&code=a+b")) + bad(request(4242, "$path?state=$state&code=a.b")) + bad(request(4242, "$path?state=$state&code=a%2Bb")) + bad(request(4242, "$path?state=$state&code=a%2")) + bad(request(4242, "$path?state=$state&code=a%zz")) + bad(request(4242, "$path?state=$state&code=${"c".repeat(4_097)}")) + bad(request(4242, "$path?state=$state&code=a?b")) + bad(request(4242, "$path?state=$state&code")) + bad(request(4242, "$path")) + bad(request(4242, "$path?")) + bad(request(4242, "$path#frag?state=$state&code=c")) + bad(request(4242, method = "POST")) + bad(request(4242, method = "HEAD")) + bad(request(4242, method = "get")) + bad(request(4242, version = "HTTP/1.0")) + bad(request(4242, host = "localhost:4242")) + bad(request(4242, host = "127.0.0.1:4243")) + bad(request(4242, host = "127.0.0.1")) + bad(request(4242, host = null)) + bad(request(4242, extra = arrayOf("Host: 127.0.0.1:4242"))) + bad(request(4242, extra = arrayOf("host: 127.0.0.1:4242"))) + bad(request(4242, extra = arrayOf("Transfer-Encoding: chunked"))) + bad(request(4242, extra = arrayOf("Expect: 100-continue"))) + bad(request(4242, extra = arrayOf("Upgrade: websocket"))) + bad(request(4242, extra = arrayOf("Trailer: X"))) + bad(request(4242, extra = arrayOf("Content-Length: 5"))) + bad(request(4242, extra = arrayOf(" folded: continuation"))) + bad(request(4242, extra = arrayOf("Bad Name: v"))) + bad(request(4242, extra = arrayOf("NoColon"))) + bad(request(4242, extra = arrayOf(""))) + bad("GET $path?state=$state&code=c HTTP/1.1\nHost: 127.0.0.1:4242\n\n") + bad("GET $path?state=$state&code=c HTTP/1.1\r\nHost: 127.0.0.1:4242\r\n\r\nGET / HTTP/1.1\r\n\r\n") + bad("GET $path?state=$state&code=c HTTP/1.1 \r\nHost: 127.0.0.1:4242\r\n\r\n") + bad("GET $path?state=$state&code=c HTTP/1.1\r\nHost: 127.0.0.1:4242\r\n\r\n") + bad("GET $path?state=é&code=c HTTP/1.1\r\nHost: 127.0.0.1:4242\r\n\r\n") + bad(request(4242, extra = arrayOf("X: a\u0001b"))) + assertEquals(HermesException.Kind.MessageTooLarge, refused(request(4242, extra = arrayOf("X: ${"v".repeat(16_400)}")))) + // 4–68 lines in total including the final two empty ones. + validate(request(4242, extra = Array(64) { "X-H$it: v" })) + bad(request(4242, extra = Array(66) { "X-H$it: v" })) + } + + // Real socket + + @Test fun itListensOnlyOnLoopbackAtAnOsChosenPortAndSuppliesAnExactCallbackUrl() { + val listener = bind() + assertTrue(listener.port in 1024..65_535) + assertEquals("http://127.0.0.1:${listener.port}$path", listener.callbackUrl) + assertEquals("127.0.0.1", listener.boundAddress) + assertTrue("Two sign-ins never share a port", bind().port != listener.port) + } + + @Test fun aValidRequestIsAnsweredWithAStaticNoStorePageAndDeliversTheCodeOnce() = runBlocking { + val listener = bind() + val waiting = async { listener.awaitCode { } } + val reply = exchange(listener.port, request(listener.port, "$path?state=$state&code=secret-code-9")) + assertEquals("secret-code-9", withTimeout(5_000) { waiting.await() }) + assertTrue(reply.startsWith("HTTP/1.1 200 OK\r\n")) + listOf("Cache-Control: no-store", "Pragma: no-cache", "Referrer-Policy: no-referrer", "X-Content-Type-Options: nosniff", + "Content-Security-Policy: default-src 'none'; frame-ancestors 'none'", "Connection: close", "Content-Type: text/html; charset=utf-8") + .forEach { assertTrue(it, it in reply) } + assertFalse("The page never reflects the code or state", "secret-code-9" in reply || state in reply) + val body = reply.substringAfter("\r\n\r\n") + assertEquals(body.length, Regex("Content-Length: (\\d+)").find(reply)!!.groupValues[1].toInt()) + assertTrue("Sign-in received" in body) + } + + @Test fun badRequestsCloseWithoutConsumingTheSignIn() = runBlocking { + val listener = bind() + val waiting = async { listener.awaitCode { } } + listOf( + request(listener.port, "/favicon.ico"), + request(listener.port, "$path?state=WRONG&code=c"), + request(listener.port, method = "POST"), + request(listener.port, host = "evil.example"), + request(listener.port, extra = arrayOf("Transfer-Encoding: chunked")), + "garbage\r\n\r\n", + ).forEach { assertEquals("No answer for ${it.take(40)}", "", exchange(listener.port, it)) } + assertFalse("Still waiting for the real callback", waiting.isCompleted) + exchange(listener.port, request(listener.port, "$path?state=$state&code=real")) + assertEquals("real", withTimeout(5_000) { waiting.await() }) + } + + @Test fun anOversizeOrIncompleteOrSlowRequestIsClosedWithoutAnAnswer() = runBlocking { + val listener = bind(AuthTimings(callbackRequestMillis = 300)) + val waiting = async { listener.awaitCode { } } + assertEquals("", exchange(listener.port, "GET /x HTTP/1.1\r\nX: ${"v".repeat(17_000)}\r\n\r\n")) + val started = System.nanoTime() + assertEquals("A request that never finishes is dropped at the deadline", "", exchange(listener.port, "GET $path?state=$state&code=c HTTP/1.1\r\nHost: 127.0.0.1:${listener.port}\r\n")) + assertTrue("Dropped near 300 ms, not the client's 2 s wait", System.nanoTime() - started < 1_500_000_000) + assertFalse(waiting.isCompleted) + exchange(listener.port, request(listener.port)) + assertEquals("code-1", withTimeout(5_000) { waiting.await() }) + } + + @Test fun atMostFourConnectionsAreServedAtOnce() = runBlocking { + val listener = bind(AuthTimings(callbackRequestMillis = 1_500)) + val waiting = async { listener.awaitCode { } } + val idle = List(4) { Socket(InetAddress.getByName("127.0.0.1"), listener.port) } + delay(100) + val fifth = Socket(InetAddress.getByName("127.0.0.1"), listener.port).apply { soTimeout = 1_000 } + assertEquals("The fifth is closed at once", -1, runCatching { fifth.getInputStream().read() }.getOrDefault(-1)) + fifth.close() + idle.forEach { it.close() } + delay(150) + exchange(listener.port, request(listener.port)) + assertEquals("code-1", withTimeout(5_000) { waiting.await() }) + } + + @Test fun onceTheCodeIsCapturedLaterRequestsAreIgnoredAndTheCodeIsDeliveredExactlyOnce() = runBlocking { + val listener = bind() + val waiting = async { listener.awaitCode { } } + exchange(listener.port, request(listener.port, "$path?state=$state&code=first")) + assertEquals("first", withTimeout(5_000) { waiting.await() }) + val second = runCatching { exchange(listener.port, request(listener.port, "$path?state=$state&code=second")) } + assertTrue("Nothing answers a second callback: ${second.getOrNull()}", second.isFailure || second.getOrNull() == "") + } + + @Test fun closingStopsListeningAndCancellingTheWaiterClosesThePort() = runBlocking { + val listener = bind() + val port = listener.port + val waiting = async { listener.awaitCode { } } + delay(50) + waiting.cancel() + assertThrows(CancellationException::class.java) { runBlocking { waiting.await() } } + listener.close() + listener.close() // idempotent + assertThrows(ConnectException::class.java) { Socket(InetAddress.getByName("127.0.0.1"), port).close() } + Unit + } + + @Test fun theWholeSignInHasADeadlineThatClosesTheListener() = runBlocking { + val listener = bind(AuthTimings(browserSignInMillis = 250)) + val port = listener.port + val failure = assertThrows(HermesException::class.java) { runBlocking { listener.awaitCode { } } } + assertEquals(HermesException.Kind.TimedOut, failure.kind) + listener.close() + assertThrows(ConnectException::class.java) { Socket(InetAddress.getByName("127.0.0.1"), port).close() } + Unit + } + + @Test fun aBrowserThatCannotOpenFailsTheWaitUnlessACodeWasAlreadyCaptured() = runBlocking { + val failing = bind() + assertEquals( + HermesException.Kind.BrowserAuthenticationUnavailable, + assertThrows(HermesException::class.java) { runBlocking { failing.awaitCode { throw IllegalStateException("no browser /secret") } } }.kind, + ) + val late = bind() + val code = late.awaitCode { + exchange(late.port, request(late.port, "$path?state=$state&code=kept")) + delay(50) + throw IllegalStateException("the tab was dismissed afterwards") + } + assertEquals("A late browser cancellation never erases a captured code", "kept", code) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpHermesHttpTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpHermesHttpTest.kt new file mode 100644 index 00000000..a422f758 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpHermesHttpTest.kt @@ -0,0 +1,399 @@ +package app.bighelp.hermes + +import java.io.ByteArrayOutputStream +import java.util.concurrent.TimeUnit +import java.util.zip.GZIPOutputStream +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.SocketPolicy +import okio.Buffer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Real HTTP to a loopback server: headers on the wire, no redirects/cookies/retries, byte budgets, cancellation. */ +class OkHttpHermesHttpTest { + private val server = MockWebServer() + private val opened = mutableListOf() + + @After fun stop() { + opened.forEach { it.close() } + server.shutdown() + } + + private fun http(prefix: String = "/hermes", access: AccessHeaders = AccessHeaders.none): OkHttpHermesHttp { + server.start() + val endpoint = HermesEndpoint.parse("http://127.0.0.1:${server.port}$prefix", allowPrivateHttp = true) + return OkHttpHermesHttp(endpoint, access).also { opened += it } + } + + private fun kind(block: suspend () -> Unit) = assertThrows(HermesException::class.java) { runBlocking { block() } }.kind + private fun json(body: String = "{}") = MockResponse().setHeader("Content-Type", "application/json").setBody(body) + + // Wire shape + + @Test fun getCarriesTheContractHeadersAndTheDeploymentPrefixAndNothingElse() = runBlocking { + val http = http() + server.enqueue(json("""{"auth_required":false}""")) + val result = http.send(HermesHttpRequest("/api/status", query = listOf("q" to "a b&c=d+é"))) + assertEquals(200, result.status) + assertEquals("""{"auth_required":false}""", result.text()) + val request = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("GET", request.method) + assertEquals("/hermes/api/status?q=a%20b%26c%3Dd%2B%C3%A9", request.path) + assertEquals("application/json", request.getHeader("Accept")) + assertEquals("no-store", request.getHeader("Cache-Control")) + assertEquals("close", request.getHeader("Connection")) + assertNull(request.getHeader("Authorization")) + assertNull(request.getHeader("X-Hermes-Session-Token")) + assertNull(request.getHeader("Cookie")) + assertNull(request.getHeader("Origin")) + assertNull(request.getHeader("Content-Type")) + } + + @Test fun bearerAndDashboardCredentialsUseTheirOwnHeader() = runBlocking { + val http = http() + server.enqueue(json()) + server.enqueue(json()) + http.send(HermesHttpRequest("/api/auth/me", auth = HttpAuth.Bearer("access.token-1"))) + http.send(HermesHttpRequest("/api/sessions", auth = HttpAuth.DashboardSession("dash~token"))) + val bearer = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("Bearer access.token-1", bearer.getHeader("Authorization")) + assertNull(bearer.getHeader("X-Hermes-Session-Token")) + val dashboard = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("dash~token", dashboard.getHeader("X-Hermes-Session-Token")) + assertNull(dashboard.getHeader("Authorization")) + } + + @Test fun anInvalidTokenIsRefusedBeforeAnythingIsSent() { + val http = http() + listOf("", "has space", "tab\t", "é", "x".repeat(16_385)).forEach { + assertEquals(it, HermesException.Kind.InvalidCredentials, kind { http.send(HermesHttpRequest("/x", auth = HttpAuth.Bearer(it))) }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { http.send(HermesHttpRequest("/x", auth = HttpAuth.DashboardSession(it))) }) + } + assertEquals("Nothing reached the host", 0, server.requestCount) + } + + @Test fun jsonBodiesAreBoundedAndSentWithTheirContentType() = runBlocking { + val http = http() + server.enqueue(json()) + http.send(HermesHttpRequest("/auth/native/token", "POST", body = buildJsonObject { put("code", "c"); put("code_verifier", "v") })) + val request = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("POST", request.method) + assertEquals("application/json", request.getHeader("Content-Type")) + assertEquals("""{"code":"c","code_verifier":"v"}""", request.body.readUtf8()) + + val tooBig = buildJsonObject { put("x", "y".repeat(HermesHttpLimits.MAXIMUM_BODY_BYTES)) } + assertEquals(HermesException.Kind.MessageTooLarge, kind { http.send(HermesHttpRequest("/x", "POST", body = tooBig)) }) + assertEquals("The oversize body was never sent", 1, server.requestCount) + } + + @Test fun gateHeadersAreSentAndAHermesBearerReplacesAProxyBasicAuthorization() = runBlocking { + val access = AccessHeaders.of( + HermesEndpoint.parse("http://127.0.0.1:1", allowPrivateHttp = true), + AccessCredential.proxyBasic("user", "pass"), + listOf(CustomHeader.of("X-Gate", "g")), + ) + val http = http(access = access) + server.enqueue(json()) + server.enqueue(json()) + http.send(HermesHttpRequest("/api/status")) + http.send(HermesHttpRequest("/api/auth/me", auth = HttpAuth.Bearer("tok"))) + val plain = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("Basic dXNlcjpwYXNz", plain.getHeader("Authorization")) + assertEquals("g", plain.getHeader("X-Gate")) + val bearer = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("There is only one Authorization header", "Bearer tok", bearer.headers.values("Authorization").single()) + assertEquals("g", bearer.getHeader("X-Gate")) + } + + @Test fun theCookieHeaderExistsOnlyWhenTheCallerSuppliesOne() = runBlocking { + val http = http() + server.enqueue(json().addHeader("Set-Cookie", "session=server-cookie; Path=/")) + server.enqueue(json()) + server.enqueue(json()) + http.send(HermesHttpRequest("/a")) + http.send(HermesHttpRequest("/b")) + http.send(HermesHttpRequest("/c", cookie = "hermes_session_pkce=abc")) + server.takeRequest(5, TimeUnit.SECONDS) + assertNull("No jar remembers a Set-Cookie", server.takeRequest(5, TimeUnit.SECONDS)!!.getHeader("Cookie")) + assertEquals("hermes_session_pkce=abc", server.takeRequest(5, TimeUnit.SECONDS)!!.getHeader("Cookie")) + } + + @Test fun nativeGuardHeadersOnlyOnPluginPostsWithExactlyOneCredential() = runBlocking { + val http = http() + val guard = NativeGuard("\"etag-1\"", "123e4567-e89b-42d3-a456-426614174000") + val session = HttpAuth.DashboardSession("t") + val route = "/api/plugins/loopdy/native/goals" + repeat(2) { server.enqueue(json()) } + http.send(HermesHttpRequest(route, "POST", body = buildJsonObject {}, auth = session, nativeGuard = guard)) + val request = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("\"etag-1\"", request.getHeader("If-Match")) + assertEquals("123e4567-e89b-42d3-a456-426614174000", request.getHeader("X-Loopdy-Request-ID")) + http.send(HermesHttpRequest("/api/plugins/loopdy/native/telemetry", "PUT", body = buildJsonObject {}, auth = session, nativeGuard = guard)) + assertEquals("PUT", server.takeRequest(5, TimeUnit.SECONDS)!!.method) + + fun refused(request: HermesHttpRequest) = assertEquals(HermesException.Kind.InvalidResponse, kind { http.send(request) }) + refused(HermesHttpRequest("/api/sessions", "POST", body = buildJsonObject {}, auth = session, nativeGuard = guard)) + refused(HermesHttpRequest(route, "POST", body = buildJsonObject {}, auth = session, + nativeGuard = NativeGuard("\"e\"", "NOT-A-LOWERCASE-UUID"))) + refused(HermesHttpRequest(route, "GET", auth = session, nativeGuard = guard)) + refused(HermesHttpRequest(route, "POST", body = buildJsonObject {}, nativeGuard = guard)) + refused(HermesHttpRequest(route, "POST", body = buildJsonObject {}, auth = session, cookie = "a=b", nativeGuard = guard)) + assertEquals("Every refusal happened before sending", 2, server.requestCount) + } + + // Redirects + + @Test fun noRedirectIsFollowedAndTheTargetIsNeverContacted() { + val http = http() + listOf(301, 302, 303, 307, 308).forEach { code -> + server.enqueue(MockResponse().setResponseCode(code).setHeader("Location", "/hermes/elsewhere")) + assertEquals(code.toString(), HermesException.Kind.RedirectRefused, kind { http.send(HermesHttpRequest("/api/status")) }) + } + assertEquals(5, server.requestCount) + repeat(5) { assertEquals("/hermes/api/status", server.takeRequest(5, TimeUnit.SECONDS)!!.path) } + } + + @Test fun onlyTheAuthorizeCallMayReturnItsOwn302Unfollowed() = runBlocking { + val http = http() + server.enqueue(MockResponse().setResponseCode(302).setHeader("Location", "/hermes/login")) + val result = http.send(HermesHttpRequest("/auth/native/authorize", allowAuthorizeRedirect = true)) + assertEquals(302, result.status) + assertEquals("/hermes/login", result.header("Location")) + server.enqueue(MockResponse().setResponseCode(301).setHeader("Location", "/hermes/login")) + assertEquals(HermesException.Kind.RedirectRefused, kind { + http.send(HermesHttpRequest("/auth/native/authorize", allowAuthorizeRedirect = true)) + }) + assertEquals("Neither Location was followed", 2, server.requestCount) + } + + @Test fun aCloudflareAccessLoginRedirectIsADenialNotAGenericRedirect() { + val http = http() + server.enqueue(MockResponse().setResponseCode(302).setHeader("Location", "https://team.cloudflareaccess.com/cdn-cgi/access/login")) + assertEquals(HermesException.Kind.CloudflareAccessDenied, kind { http.send(HermesHttpRequest("/api/status")) }) + server.enqueue(MockResponse().setResponseCode(302).setHeader("Location", "https://evilcloudflareaccess.com/x")) + assertEquals("Only the real domain counts", HermesException.Kind.RedirectRefused, kind { http.send(HermesHttpRequest("/api/status")) }) + } + + @Test fun aServiceTokenRejectionPageIsCloudflareAccessDeniedOnlyWhenATokenWasSent() = runBlocking { + val credentialed = AccessHeaders.of( + HermesEndpoint.parse("https://127.0.0.1:1"), AccessCredential.cloudflareAccess("id", "secret"), emptyList(), + ) + // The service token is HTTPS only, so prove the page rule through the HTTP-capable check directly. + val page = MockResponse().setResponseCode(403).setHeader("Content-Type", "text/html; charset=utf-8") + .setHeader("CF-RAY", "abc123-AMS").setBody("blocked") + val http = http() + server.enqueue(page) + val plain = http.send(HermesHttpRequest("/api/status")) + assertEquals("Without a token this is just a 403 page", 403, plain.status) + assertTrue(credentialed.values.containsKey("CF-Access-Client-Id")) + assertTrue(OkHttpHermesHttp.isCloudflareAccessDenial(403, "text/html", hasRay = true, sentAccessToken = true)) + assertFalse(OkHttpHermesHttp.isCloudflareAccessDenial(403, "application/json", hasRay = true, sentAccessToken = true)) + assertFalse(OkHttpHermesHttp.isCloudflareAccessDenial(403, "text/html", hasRay = false, sentAccessToken = true)) + assertFalse(OkHttpHermesHttp.isCloudflareAccessDenial(200, "text/html", hasRay = true, sentAccessToken = true)) + } + + // Response budgets + + @Test fun aDeclaredLengthOverTheBudgetFailsWithoutReadingTheBody() { + val http = http() + server.enqueue(MockResponse().setBody("x".repeat(200))) + assertEquals(HermesException.Kind.MessageTooLarge, kind { http.send(HermesHttpRequest("/x", maximumResponseBytes = 100)) }) + } + + @Test fun bytesAreCountedWhileReadingSoAnUndeclaredLengthCannotOverflow() = runBlocking { + val http = http() + val body = "z".repeat(1_000) + server.enqueue(MockResponse().setChunkedBody(body, 64)) + assertEquals(HermesException.Kind.MessageTooLarge, kind { http.send(HermesHttpRequest("/x", maximumResponseBytes = 999)) }) + server.enqueue(MockResponse().setChunkedBody(body, 64)) + assertEquals("Exactly the budget is allowed", 1_000, http.send(HermesHttpRequest("/x", maximumResponseBytes = 1_000)).body.size) + } + + @Test fun theBudgetCountsDecodedBytesSoACompressedBombIsRefused() { + val http = http() + val bomb = ByteArrayOutputStream().also { out -> GZIPOutputStream(out).use { it.write(ByteArray(2_000_000) { 'a'.code.toByte() }) } } + assertTrue("The bomb is small on the wire", bomb.size() < 10_000) + server.enqueue(MockResponse().setHeader("Content-Encoding", "gzip").setBody(Buffer().write(bomb.toByteArray()))) + assertEquals(HermesException.Kind.MessageTooLarge, kind { http.send(HermesHttpRequest("/x", maximumResponseBytes = 1_000_000)) }) + } + + @Test fun aBudgetBeyondTheRouteCeilingIsRefusedBeforeSending() { + val http = http() + assertEquals(HermesException.Kind.MessageTooLarge, kind { http.send(HermesHttpRequest("/api/status", maximumResponseBytes = 0)) }) + assertEquals(HermesException.Kind.MessageTooLarge, kind { + http.send(HermesHttpRequest("/api/status", maximumResponseBytes = HermesWire.MAXIMUM_MESSAGE_BYTES + 1)) + }) + assertEquals(0, server.requestCount) + assertEquals(4 * 1_024 * 1_024, HermesHttpLimits.responseCeiling("/api/sessions", "GET", emptyList())) + assertEquals(25 * 1_024 * 1_024, HermesHttpLimits.responseCeiling("/api/sessions/abc/export", "GET", emptyList())) + assertEquals(4 * 1_024 * 1_024, HermesHttpLimits.responseCeiling("/api/sessions/a/b/export", "GET", emptyList())) + assertEquals(12 * 1_024 * 1_024, HermesHttpLimits.responseCeiling("/api/plugins/loopdy/native/board/media", "POST", emptyList())) + assertEquals(4 * 1_024 * 1_024, HermesHttpLimits.responseCeiling("/api/plugins/loopdy/native/board/media", "POST", listOf("x" to "y"))) + assertEquals( + HermesHttpLimits.MAXIMUM_MEDIA_RESPONSE_BYTES, + HermesHttpLimits.responseCeiling("/api/media", "GET", listOf("path" to "/out/a.png")), + ) + assertEquals(4 * 1_024 * 1_024, HermesHttpLimits.responseCeiling("/api/media", "GET", listOf("path" to "/out/../a.png"))) + assertEquals(1_000L, HermesHttpLimits.clampTimeoutMillis(1)) + assertEquals(75_000L, HermesHttpLimits.clampTimeoutMillis(10_000_000)) + } + + @Test fun responseBodiesDecodeStrictly() = runBlocking { + val http = http() + server.enqueue(MockResponse().setBody(Buffer().write(byteArrayOf('{'.code.toByte(), 0xC3.toByte(), '}'.code.toByte())))) + val bad = http.send(HermesHttpRequest("/x")) + assertEquals(HermesException.Kind.InvalidResponse, kind { bad.json() }) + server.enqueue(json("""{"a":1,"a":2}""")) + assertEquals("A duplicate key is not guessed", HermesException.Kind.InvalidResponse, kind { http.send(HermesHttpRequest("/x")).json() }) + server.enqueue(json("[1]")) + assertEquals(HermesException.Kind.InvalidResponse, kind { http.send(HermesHttpRequest("/x")).jsonObject() }) + } + + // Status mapping + + @Test fun statusMappingFollowsTheGenericContract() { + fun status(code: Int) = HttpResult(code, emptyList(), ByteArray(0)) + listOf(200, 204, 299).forEach { status(it).requireSuccess() } + mapOf( + 401 to HermesException.Kind.InvalidCredentials, 403 to HermesException.Kind.InvalidCredentials, + 404 to HermesException.Kind.UnsupportedAuthentication, 405 to HermesException.Kind.UnsupportedAuthentication, + 429 to HermesException.Kind.RateLimited, 500 to HermesException.Kind.ServerUnavailable, + 503 to HermesException.Kind.ServerUnavailable, 418 to HermesException.Kind.InvalidResponse, + 302 to HermesException.Kind.InvalidResponse, + ).forEach { (code, expected) -> assertEquals(code.toString(), expected, kind { status(code).requireSuccess() }) } + } + + @Test fun hostNameRefusalAndWebPagesAreRecognizedWithoutShowingTheBody() { + fun result(code: Int, type: String, body: String, vararg extra: Pair) = + HttpResult(code, listOf("Content-Type" to type) + extra, body.toByteArray()) + assertEquals( + HermesException.Kind.HostNameRefused, + kind { result(400, "application/json", """{"detail":"Invalid Host header: evil.example"}""").requireHermesAnswer() }, + ) + val page = assertThrows(HermesException::class.java) { result(200, "text/html", "

SECRET

").requireHermesAnswer() } + assertEquals(HermesException.Kind.WebPageInsteadOfHermes, page.kind) + assertFalse(page.throughCloudflare) + assertFalse("SECRET" in page.message.orEmpty() || "SECRET" in page.toString()) + assertTrue(assertThrows(HermesException::class.java) { + result(400, "text/html", "x", "CF-RAY" to "1-AMS").requireHermesAnswer() + }.throughCloudflare) + result(401, "text/html", "x").requireHermesAnswer() + result(503, "text/html", "x").requireHermesAnswer() + result(200, "application/json", "{}").requireHermesAnswer() + } + + // No retry, no stale pooled socket + + @Test fun aDroppedRequestIsNeverSentAgain() = runBlocking { + val http = http() + // The canary stays queued if (and only if) nothing was resent. + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)) + server.enqueue(json()) + assertEquals(HermesException.Kind.ConnectionFailed, kind { + http.send(HermesHttpRequest("/auth/native/token", "POST", body = buildJsonObject { put("code", "once") })) + }) + assertEquals("A one-use code reached the host exactly once", 1, server.requestCount) + assertEquals("The canary was still waiting", 200, http.send(HermesHttpRequest("/api/status")).status) + + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)) + server.enqueue(json()) + assertEquals(HermesException.Kind.ConnectionFailed, kind { http.send(HermesHttpRequest("/api/status")) }) + assertEquals("Not even a GET is retried by the transport", 3, server.requestCount) + } + + @Test fun aHostThatClosesAfterEachKeepAliveReplyNeverBreaksTheNextRequest() = runBlocking { + val http = http() + repeat(4) { server.enqueue(json().setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)) } + repeat(4) { assertEquals(200, http.send(HermesHttpRequest("/api/status")).status) } + repeat(4) { + assertEquals("Each request opened its own connection", 0, server.takeRequest(5, TimeUnit.SECONDS)!!.sequenceNumber) + } + } + + @Test fun errorsNameNoUrlTokenOrBody() { + val http = http() + server.shutdown() + val e = assertThrows(HermesException::class.java) { + runBlocking { http.send(HermesHttpRequest("/api/x", query = listOf("secret" to "QUERY-SECRET"), auth = HttpAuth.Bearer("BEARER-SECRET"))) } + } + assertEquals(HermesException.Kind.ConnectionFailed, e.kind) + assertNull("No cause that could carry the URL", e.cause) + val text = e.message.orEmpty() + e.toString() + listOf("QUERY-SECRET", "BEARER-SECRET", "127.0.0.1", "/api/x").forEach { assertFalse(it, it in text) } + } + + @Test fun aTlsHandshakeAgainstAPlainHostIsATlsFailure() { + // A host that answers the ClientHello with plain HTTP text, as a misconfigured proxy would. + val plain = java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1")) + val thread = Thread { + runCatching { + plain.accept().use { socket -> + socket.getInputStream().read(ByteArray(512)) + socket.getOutputStream().write("HTTP/1.1 400 Bad Request\r\n\r\n".toByteArray()) + } + } + }.also { it.start() } + val http = OkHttpHermesHttp(HermesEndpoint.parse("https://127.0.0.1:${plain.localPort}")).also { opened += it } + try { + assertEquals(HermesException.Kind.TlsRequired, kind { http.send(HermesHttpRequest("/api/status", timeoutMillis = 5_000)) }) + } finally { + plain.close() + thread.join(2_000) + } + } + + // Time and cancellation + + @Test fun aSlowHostTimesOutAtTheRequestBudget() { + val http = http() + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val start = System.nanoTime() + assertEquals(HermesException.Kind.TimedOut, kind { http.send(HermesHttpRequest("/x", timeoutMillis = 1_000)) }) + assertTrue("Failed near one second, not five", System.nanoTime() - start < TimeUnit.SECONDS.toNanos(3)) + } + + @Test fun cancellingTheCallerCancelsTheRealCallPromptly() = runBlocking { + val http = http() + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val call = async { http.send(HermesHttpRequest("/x")) } + var waited = 0 + while (http.activeCalls == 0 && waited++ < 200) delay(10) + assertEquals(1, http.activeCalls) + call.cancel() + val start = System.nanoTime() + assertThrows(CancellationException::class.java) { runBlocking { withTimeout(3_000) { call.await() } } } + waited = 0 + while (http.activeCalls != 0 && waited++ < 200) delay(10) + assertEquals("The underlying call was cancelled, not abandoned", 0, http.activeCalls) + assertTrue(System.nanoTime() - start < TimeUnit.SECONDS.toNanos(3)) + } + + @Test fun closingTheClientCancelsRunningCallsAndRefusesNewOnes() { + val http = http() + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val running = Thread { + runCatching { runBlocking { http.send(HermesHttpRequest("/x")) } } + }.also { it.start() } + var waited = 0 + while (http.activeCalls == 0 && waited++ < 200) Thread.sleep(10) + http.close() + running.join(3_000) + assertFalse(running.isAlive) + assertEquals(HermesException.Kind.NotConnected, kind { http.send(HermesHttpRequest("/y")) }) + assertNotNull(http) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/RawPeer.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/RawPeer.kt new file mode 100644 index 00000000..eddd12cd --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/RawPeer.kt @@ -0,0 +1,225 @@ +package app.bighelp.hermes + +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.security.MessageDigest +import java.util.Base64 +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * A hand-written WebSocket peer on raw TCP: it builds frames byte by byte, so a test can send a frame header + * with no payload, split a code point across fragments, put invalid bytes in a TEXT frame, or answer the + * upgrade any way it likes. It also answers the few plain HTTP routes a connect needs. Test double only. + */ +class RawPeer : AutoCloseable { + private val server = ServerSocket(0, 16, InetAddress.getByName("127.0.0.1")) + val port: Int get() = server.localPort + val upgrades = LinkedBlockingQueue() + val httpPaths = CopyOnWriteArrayList() + @Volatile var healthBody = """{"ok":true,"auth_required":false}""" + @Volatile var capabilitiesResult = """{"per_session_exclusive_submit":true}""" + private val tickets = java.util.concurrent.atomic.AtomicInteger() + + init { + Thread({ + while (!server.isClosed) { + val socket = try { server.accept() } catch (_: IOException) { return@Thread } + Thread({ serve(socket) }, "raw-peer-connection").also { it.isDaemon = true }.start() + } + }, "raw-peer-accept").also { it.isDaemon = true }.start() + } + + private fun serve(socket: Socket) { + try { + socket.soTimeout = 10_000 + val head = readHead(socket) ?: return socket.close() + val lines = head.split("\r\n") + val path = lines[0].split(' ').getOrNull(1).orEmpty() + val headers = lines.drop(1).filter { ':' in it }.associate { it.substringBefore(':').lowercase() to it.substringAfter(':').trim() } + if (headers["upgrade"].equals("websocket", ignoreCase = true) && path.startsWith("/api/ws")) { + upgrades.add(Session(socket, head, lines[0], headers)) + return + } + httpPaths += path.substringBefore('?') + val body = when (path.substringBefore('?')) { + "/api/health" -> healthBody + "/api/status" -> """{"auth_required":false}""" + "/api/auth/ws-ticket" -> """{"ticket":"raw_ticket_${tickets.incrementAndGet()}","ttl_seconds":30}""" + else -> null + } + val response = if (body == null) "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + else "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n$body" + socket.getOutputStream().write(response.toByteArray()) + socket.getOutputStream().flush() + socket.close() + } catch (_: IOException) { + runCatching { socket.close() } + } + } + + private fun readHead(socket: Socket): String? { + val buffer = ByteArrayOutputStream() + val input = socket.getInputStream() + while (buffer.size() < 65_536) { + val b = input.read() + if (b < 0) return null + buffer.write(b) + val bytes = buffer.toByteArray() + if (bytes.size >= 4 && bytes[bytes.size - 4] == 13.toByte() && bytes[bytes.size - 3] == 10.toByte() && + bytes[bytes.size - 2] == 13.toByte() && bytes[bytes.size - 1] == 10.toByte() + ) return String(bytes, Charsets.ISO_8859_1).removeSuffix("\r\n\r\n") + } + return null + } + + fun awaitUpgrade(timeoutMillis: Long = 5_000): Session = + upgrades.poll(timeoutMillis, TimeUnit.MILLISECONDS) ?: throw AssertionError("The client never asked to upgrade") + + override fun close() { + runCatching { server.close() } + upgrades.forEach { runCatching { it.socket.close() } } + } + + /** A frame the client sent, unmasked. */ + class ClientFrame(val opcode: Int, val fin: Boolean, val payload: ByteArray) { + val text: String get() = String(payload, Charsets.UTF_8) + } + + inner class Session(val socket: Socket, val head: String, val requestLine: String, private val headers: Map) { + private val out = socket.getOutputStream() + private val input = socket.getInputStream() + val receivedMethods = CopyOnWriteArrayList() + val receivedFrames = LinkedBlockingQueue() + @Volatile var clientClosed = false + + fun header(name: String): String? = headers[name.lowercase()] + fun hasHeader(name: String) = headers.containsKey(name.lowercase()) + val path: String get() = requestLine.split(' ').getOrNull(1).orEmpty() + + // Upgrade answers + + fun accept(subprotocol: String? = null, extensions: String? = null, extraHeaders: List = emptyList()) { + val key = header("sec-websocket-key") ?: error("no key") + val accept = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((key + GUID).toByteArray())) + val reply = buildString { + append("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $accept\r\n") + subprotocol?.let { append("Sec-WebSocket-Protocol: $it\r\n") } + extensions?.let { append("Sec-WebSocket-Extensions: $it\r\n") } + extraHeaders.forEach { append("$it\r\n") } + append("\r\n") + } + raw(reply.toByteArray()) + } + + fun rawText(text: String) = raw(text.toByteArray(Charsets.ISO_8859_1)) + + fun raw(bytes: ByteArray) { + out.write(bytes) + out.flush() + } + + // Frames (server to client: never masked) + + fun frame(opcode: Int, payload: ByteArray, fin: Boolean = true, rsv: Int = 0) = raw(frameHeader(opcode, payload.size.toLong(), fin, rsv) + payload) + + /** The header alone: the declared length with none of the payload. */ + fun frameHeaderOnly(opcode: Int, declaredLength: Long, fin: Boolean = true) = raw(frameHeader(opcode, declaredLength, fin, 0)) + + fun text(text: String) = frame(0x1, text.toByteArray(Charsets.UTF_8)) + fun binary(bytes: ByteArray) = frame(0x2, bytes) + fun event(type: String, payload: String = "{}", seq: Long? = null) = text(ScriptedGateway.eventLine(type, payload, null, seq)) + fun ready(payload: String = """{"heartbeat":true,"replay_epoch":"epoch-raw"}""") = event("gateway.ready", payload) + fun result(id: String, json: String = "{}") = text("""{"jsonrpc":"2.0","id":${ScriptedGateway.quote(id)},"result":$json}""") + + // Client frames + + fun readFrame(timeoutMillis: Int = 3_000): ClientFrame? { + socket.soTimeout = timeoutMillis + return try { + val b0 = input.read() + if (b0 < 0) return null.also { clientClosed = true } + val b1 = input.read() + var length = (b1 and 0x7f).toLong() + if (length == 126L) length = (input.read().toLong() shl 8) or input.read().toLong() + else if (length == 127L) { length = 0; repeat(8) { length = (length shl 8) or input.read().toLong() } } + val mask = if (b1 and 0x80 != 0) ByteArray(4).also { readFully(it) } else null + val payload = ByteArray(length.toInt()).also { readFully(it) } + if (mask != null) for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte() + ClientFrame(b0 and 0x0f, b0 and 0x80 != 0, payload) + } catch (_: SocketTimeoutException) { + null + } catch (_: IOException) { + clientClosed = true + null + } + } + + private fun readFully(target: ByteArray) { + var read = 0 + while (read < target.size) { + val n = input.read(target, read, target.size - read) + if (n < 0) throw IOException("eof") + read += n + } + } + + /** + * Answers the connect sequence and records the rest, on a background thread, until the client goes away. + * `client.capabilities` and `gateway.ping` get an empty result; `gateway.capabilities` the peer's result. + */ + fun serve(answerPings: Boolean = true) { + Thread({ + while (true) { + val frame = readFrame(60_000) ?: if (clientClosed) return@Thread else continue + if (frame.opcode == 0x8) { clientClosed = true; return@Thread } + receivedFrames.add(frame) + if (frame.opcode != 0x1) continue + val json = runCatching { Json.parseToJsonElement(frame.text).jsonObject }.getOrNull() ?: continue + val method = json["method"]?.jsonPrimitive?.content ?: continue + receivedMethods += method + val id = json["id"]?.jsonPrimitive?.content ?: continue + when (method) { + "client.capabilities" -> runCatching { result(id) } + "gateway.ping" -> if (answerPings) runCatching { result(id) } + "gateway.capabilities" -> runCatching { result(id, capabilitiesResult) } + } + } + }, "raw-peer-serve").also { it.isDaemon = true }.start() + } + + /** True once the client closed the TCP connection or sent a close frame. */ + fun awaitClientGone(timeoutMillis: Long = 5_000): Boolean { + val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis) + while (System.nanoTime() < deadline) { + if (clientClosed) return true + val frame = receivedFrames.poll(100, TimeUnit.MILLISECONDS) + if (frame?.opcode == 0x8) return true + } + return clientClosed + } + + fun close() = runCatching { socket.close() } + } + + companion object { + private const val GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + fun frameHeader(opcode: Int, length: Long, fin: Boolean, rsv: Int): ByteArray { + val first = ((if (fin) 0x80 else 0) or (rsv shl 4) or opcode).toByte() + return when { + length < 126 -> byteArrayOf(first, length.toByte()) + length <= 0xFFFF -> byteArrayOf(first, 126, (length shr 8).toByte(), length.toByte()) + else -> byteArrayOf(first, 127) + ByteArray(8) { (length shr (56 - 8 * it)).toByte() } + } + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt new file mode 100644 index 00000000..8ae9cb61 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt @@ -0,0 +1,359 @@ +package app.bighelp.hermes + +import java.io.File +import java.util.UUID +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import okhttp3.Cookie +import okhttp3.CookieJar +import okhttp3.FormBody +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test + +/** + * Real Hermes, real sockets: the disposable hosts prepared for Android verification (stock Hermes plus a + * scripted local model, so no AI spend). Skipped unless `BIGHELP_E2E_CREDENTIALS` names the private + * `credentials.json`. Credentials are read from that file at run time and are never printed, logged or kept. + * + * This is protocol-level JVM evidence only: not Android, not an emulator or device, and not real inference. + */ +class RealHostIntegrationTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val closeables = mutableListOf() + private val clients = mutableListOf() + private lateinit var hosts: JsonObject + + @Before fun requireHosts() { + val path = System.getenv("BIGHELP_E2E_CREDENTIALS") + assumeTrue("Set BIGHELP_E2E_CREDENTIALS to run against the disposable hosts", path != null && File(path).isFile) + hosts = Json.parseToJsonElement(File(path!!).readText()).jsonObject["hosts"]!!.jsonObject + } + + @After fun cleanup() = runBlocking { + clients.forEach { runCatching { it.disconnect() } } + scope.cancel() + closeables.forEach { runCatching { it.close() } } + } + + private fun host(name: String) = hosts[name]!!.jsonObject + private fun text(obj: JsonObject, key: String) = obj[key]!!.jsonPrimitive.content + private fun endpoint(name: String) = HermesEndpoint.parse(text(host(name), "proxy_origin"), allowPrivateHttp = true) + + private fun authenticator(name: String, store: CredentialStore = InMemoryCredentialStore(), browser: BrowserLauncher? = null): HermesAuthenticator { + val endpoint = endpoint(name) + return HermesAuthenticator(endpoint, OkHttpHermesHttp(endpoint), store, browser).also { closeables += it } + } + + /** What a chat screen would register: it records the request and answers the way a person would. */ + private class Prompts { + val seen = CopyOnWriteArrayList() + + fun install(client: GatewayClient) { + client.setServerRequestHandler("clarify") { request -> + seen += request + val questions = request.params["questions"] as? JsonArray + if (questions != null) { + ServerResponse.Result(buildJsonObject { + put("answers", buildJsonObject { + questions.forEach { q -> put(q.jsonObject["qid"]!!.jsonPrimitive.content, "Alpha") } + }) + }) + } else { + ServerResponse.Result(buildJsonObject { put("answer", "Alpha") }) + } + } + // Declined, never answered with a value: Hermes stores an answered secret in the host's .env, which + // would make every later run (and the host's own scripted scenario) skip the prompt. + client.setServerRequestHandler("secret") { request -> + seen += request + ServerResponse.Result(buildJsonObject { put("value", "") }) + } + client.setServerRequestHandler("approval") { request -> + seen += request + ServerResponse.Result(buildJsonObject { put("choice", "deny"); put("all", false) }) + } + } + + fun methods() = seen.map { it.method } + } + + private class Turn(val receipt: String, val eventTypes: List, val finalText: String?, val sessionRunningFalse: Boolean) + + private suspend fun GatewayClient.newSession(profile: String, project: String): Pair { + val created = request("session.create", buildJsonObject { + put("profile", profile) + put("source", "bighelp") + put("idempotency_key", UUID.randomUUID().toString()) + put("cwd", project) + put("cwd_explicit", true) + put("title", "Synthetic Android protocol check") + }).jsonObject + return created["session_id"]!!.jsonPrimitive.content to created["stored_session_id"]!!.jsonPrimitive.content + } + + private suspend fun GatewayClient.runTurn(events: MutableList, runtime: String, profile: String, prompt: String, wait: Long = 30_000): Turn { + val receipt = request( + "prompt.submit", + buildJsonObject { put("session_id", runtime); put("profile", profile); put("text", prompt); put("queued", true) }, + ).jsonObject["status"]!!.jsonPrimitive.content + fun mine() = events.filter { it.event.sessionID == runtime } + withTimeout(wait) { + while (mine().none { it.event.type == "message.complete" || it.event.type == "error" } || + mine().none { it.event.type == "session.info" && it.event.payload["running"]?.toString() == "false" } + ) delay(50) + } + val complete = mine().firstOrNull { it.event.type == "message.complete" } + return Turn( + receipt, mine().map { it.event.type }.distinct(), + (complete?.event?.payload?.get("text") as? JsonPrimitive)?.content, + mine().any { it.event.type == "session.info" && it.event.payload["running"]?.toString() == "false" }, + ) + } + + private fun collect(client: GatewayClient): MutableList { + val events = CopyOnWriteArrayList() + scope.launch { client.events.collect { events += it } } + runBlocking { withTimeout(5_000) { while (client.subscriberCount == 0) delay(10) } } + return events + } + + // The ungated host: automatic dashboard session + + @Test fun openHostDashboardSignInConnectsAndStreamsARealTurnWithPromptsAnsweredOverTheWire() = runBlocking { + val authenticator = authenticator("open") + val status = authenticator.discover() + assertFalse(status.authRequired) + + val staged = authenticator.signIn(SignInInput.Dashboard) + assertEquals(true, (staged.auth as StoredAuth.DashboardSession).automatic) + + val client = GatewayClient(authenticator, scope).also { clients += it } + val prompts = Prompts().also { it.install(client) } + val events = collect(client) + val state = client.connect() + assertEquals(GatewayConnection.Connected, state.connection) + assertNotNull("gateway.ready carried its payload", state.ready) + assertTrue("The stock host guarantees serialized submitters", state.capabilities!!.perSessionExclusiveSubmit) + authenticator.commit() // only after gateway.ready + + val profiles = client.request("profiles.list", buildJsonObject { put("include_sessions", true) }).jsonObject["profiles"] as JsonArray + val names = profiles.map { it.jsonObject["name"]!!.jsonPrimitive.content } + assertTrue(names.toString(), names.containsAll(listOf("default", "moss", "cobalt"))) + + val project = text(host("open"), "project") + val (runtime, stored) = client.newSession("default", project) + assertNotEquals("Runtime and stored identifiers stay separate values", "", stored) + val turn = client.runTurn(events, runtime, "default", "hello from the Android protocol check") + assertTrue("A turn that is streaming or already done: ${turn.receipt}", turn.receipt in setOf("streaming", "ok")) + assertTrue(turn.eventTypes.toString(), "message.complete" in turn.eventTypes) + assertTrue("The turn ends on session.info running:false", turn.sessionRunningFalse) + assertFalse(turn.finalText.isNullOrBlank()) + println("REAL-HOST open: socketGeneration=${state.generation} replayEpochPresent=${state.replayEpoch != null} heartbeat=${state.heartbeatAdvertised} " + + "exclusiveSubmit=${state.capabilities!!.perSessionExclusiveSubmit} receipt=${turn.receipt} events=${turn.eventTypes} finalText=\"${turn.finalText}\"") + + for ((prompt, expected) in listOf("question test" to "clarify", "approval test" to "approval")) { + val (rt, _) = client.newSession("default", project) + client.runTurn(events, rt, "default", prompt) + assertTrue("$prompt should raise $expected but saw ${prompts.methods()}", expected in prompts.methods()) + assertTrue("The request carried the runtime session", prompts.seen.any { it.params["session_id"]?.jsonPrimitive?.content == rt }) + } + println("REAL-HOST open prompts answered over the wire: ${prompts.methods()}") + assertTrue("An approval was denied by the handler, so the disposable directory still exists", + File(project, "approval-only-delete").isDirectory) + } + + /** + * "secure input test 2" makes the scripted fixture ask for `SECURE_INPUT_FIXTURE_2`, a name an earlier answered + * run cannot have filled, and a declined value is never saved, so this stays repeatable. A host that does not + * ask is a failure here, not a skip: the fixture is known to support it. + */ + @Test fun openHostSecureInputRequestReachesTheHandlerAndIsDeclinedWithoutStoringAnything() = runBlocking { + val authenticator = authenticator("open") + authenticator.signIn(SignInInput.Dashboard) + val client = GatewayClient(authenticator, scope).also { clients += it } + val prompts = Prompts().also { it.install(client) } + val events = collect(client) + client.connect() + val (runtime, _) = client.newSession("default", text(host("open"), "project")) + client.runTurn(events, runtime, "default", "secure input test 2") + assertTrue("The fixture must ask for the secret; it asked for ${prompts.methods()}", "secret" in prompts.methods()) + val request = prompts.seen.first { it.method == "secret" } + assertEquals("SECURE_INPUT_FIXTURE_2", request.params["env_var"]?.jsonPrimitive?.content) + assertEquals(runtime, request.params["session_id"]?.jsonPrimitive?.content) + println("REAL-HOST open secure input: asked=${request.params["env_var"]?.jsonPrimitive?.content} answeredWith=decline") + } + + @Test fun openHostRestFollowsTheDashboardTokenAndTheNativeContextIsGuardedByItsEtag() = runBlocking { + val authenticator = authenticator("open") + authenticator.signIn(SignInInput.Dashboard) + authenticator.requireHealth() + val context = authenticator.authenticated(HermesHttpRequest("/api/plugins/loopdy/native/context", maximumResponseBytes = 1_048_576)) + assertEquals(200, context.status) + val etag = context.header("ETag") + assertNotNull("The plugin context returns the ETag its guard needs", etag) + val features = context.jsonObject()["features"] + assertNotNull(features) + val unauthenticated = HermesHttpRequest("/api/sessions").let { OkHttpHermesHttp(endpoint("open")).also { c -> closeables += c }.send(it) } + assertTrue("Without the session token Hermes refuses", unauthenticated.status in setOf(401, 403)) + } + + // The gated host: password PKCE, rotation and tickets + + @Test fun passwordPkceSignsInStagesThenPersistsOnlyAfterReadyAndRotatesDurably() = runBlocking { + val credentials = host("password") + val store = InMemoryCredentialStore() + val authenticator = authenticator("password", store) + val status = authenticator.discover() + assertTrue(status.supportsNativePkce) + assertTrue(status.passwordProviders.any { it.name == "basic" }) + + val staged = authenticator.signIn(SignInInput.Password("basic", text(credentials, "username"), text(credentials, "password"))) + val bearer = staged.auth as StoredAuth.Bearer + assertNotNull("The host minted a rotating refresh token", bearer.refreshToken) + assertNull("Nothing persisted before the gateway is ready", store.load(staged.authority)) + assertFalse(staged.toString().contains(bearer.accessToken)) + + val client = GatewayClient(authenticator, scope).also { clients += it } + val prompts = Prompts().also { it.install(client) } + val events = collect(client) + val state = client.connect() + assertEquals(GatewayConnection.Connected, state.connection) + authenticator.commit(expected = null) + assertEquals(staged, store.load(staged.authority)) + + val project = text(credentials, "project") + val (runtime, _) = client.newSession("default", project) + val turn = client.runTurn(events, runtime, "default", "hello through a ticketed socket") + assertTrue("message.complete" in turn.eventTypes) + assertTrue(turn.sessionRunningFalse) + println("REAL-HOST password: provider=${staged.provider} refreshToken=${bearer.refreshToken != null} ticketSubprotocolRequired=${state.socket != null} receipt=${turn.receipt} events=${turn.eventTypes}") + client.disconnect() + + // A second authenticator restores the persisted sign-in, then the access token is forced to expire. + val expired = SavedConnection(staged.endpoint, StoredAuth.Bearer(bearer.accessToken, bearer.refreshToken, 1L), staged.provider, staged.userId) + store.replace(staged, expired) + val restoredAuthenticator = authenticator("password", store) + restoredAuthenticator.restore(expired) // expiry in the past: renews before anything else + val rotated = store.load(staged.authority)!! + val rotatedBearer = rotated.auth as StoredAuth.Bearer + // Value-free assertions: a failure message must never carry a token. The host derives its access token from + // the issue second alone, so a renewal in the same second can repeat it; the refresh token is what rotates. + assertTrue("The refresh token rotated", rotatedBearer.refreshToken != null && rotatedBearer.refreshToken != bearer.refreshToken) + assertTrue("The stored record is the renewed one, not the expired one", rotated != expired) + assertEquals("Same principal", staged.authority, rotated.authority) + assertTrue((rotatedBearer.expiresAtEpochSeconds ?: 0) > System.currentTimeMillis() / 1_000) + assertEquals(rotated, restoredAuthenticator.savedConnection) + println("REAL-HOST password rotation: refreshChanged=${bearer.refreshToken != rotatedBearer.refreshToken}") + + // Two tickets, two sockets: a fresh single-use ticket every attempt. + val first = restoredAuthenticator.socketRequest() + val second = restoredAuthenticator.socketRequest() + assertTrue("A fresh single-use ticket per socket", first.headers["Sec-WebSocket-Protocol"] != second.headers["Sec-WebSocket-Protocol"]) + val again = GatewayClient(restoredAuthenticator, scope).also { clients += it } + assertEquals(GatewayConnection.Connected, again.connect().connection) + assertTrue(prompts.seen.isEmpty() || prompts.seen.isNotEmpty()) + val health = restoredAuthenticator.authenticated(HermesHttpRequest("/api/health", maximumResponseBytes = 16_384)) + assertEquals(200, health.status) + } + + @Test fun aBadPasswordIsRefusedWithoutWritingOrLeakingAnything() = runBlocking { + val credentials = host("password") + val store = InMemoryCredentialStore() + val authenticator = authenticator("password", store) + val failure = runCatching { + authenticator.signIn(SignInInput.Password("basic", text(credentials, "username"), "definitely-the-wrong-password")) + }.exceptionOrNull() as HermesException + assertTrue(failure.toString(), failure.kind in setOf(HermesException.Kind.InvalidCredentials, HermesException.Kind.InvalidResponse)) + assertNull(authenticator.savedConnection) + assertFalse("definitely-the-wrong-password" in failure.toString() + failure.message.orEmpty()) + } + + // The gated host: browser PKCE through the mock single sign-on, with a test-side "browser" + + private class SimpleCookieJar : CookieJar { + private val cookies = mutableListOf() + override fun saveFromResponse(url: HttpUrl, cookies: List) { + cookies.forEach { fresh -> this.cookies.removeAll { it.name == fresh.name && it.domain == fresh.domain && it.path == fresh.path }; this.cookies += fresh } + } + + override fun loadForRequest(url: HttpUrl): List = cookies.filter { it.matches(url) } + } + + /** Plays the person's browser: follows Hermes to the mock identity provider, approves, and lands on the loopback listener. */ + private fun mockBrowser(proxyOrigin: String): BrowserLauncher = BrowserLauncher { authorizeUrl -> + val browser = OkHttpClient.Builder().followRedirects(false).followSslRedirects(false).cookieJar(SimpleCookieJar()).build() + fun get(url: String) = browser.newCall(Request.Builder().url(url).build()).execute() + val authorize = get(authorizeUrl) + check(authorize.code == 302) { "authorize answered ${authorize.code}" } + val idpLocation = authorize.header("Location")!! + authorize.close() + val page = get(idpLocation) + val html = page.body!!.string() + page.close() + val form = FormBody.Builder().also { builder -> + Regex("""]*name="([^"]+)"[^>]*value="([^"]*)"""").findAll(html).forEach { builder.add(it.groupValues[1], it.groupValues[2]) } + }.build() + val idp = idpLocation.toHttpUrl() + val approve = browser.newCall(Request.Builder().url("${idp.scheme}://${idp.host}:${idp.port}/approve").post(form).build()).execute() + check(approve.code == 302) { "approve answered ${approve.code}" } + val back = approve.header("Location")!!.toHttpUrl() + approve.close() + val callback = get(proxyOrigin + back.encodedPath + (back.encodedQuery?.let { "?$it" } ?: "")) + check(callback.code == 302) { "callback answered ${callback.code}" } + val loopback = callback.header("Location")!! + callback.close() + check(loopback.startsWith("http://127.0.0.1:")) { "the host redirected somewhere other than the device-local listener" } + get(loopback).close() + } + + @Test fun browserPkceThroughTheMockSsoDeliversTheCodeToTheLoopbackListenerAndConnects() = runBlocking { + val credentials = host("password") + val store = InMemoryCredentialStore() + val authenticator = authenticator("password", store, mockBrowser(text(credentials, "proxy_origin"))) + val staged = authenticator.signIn(SignInInput.Browser("self-hosted")) + assertEquals("self-hosted", staged.provider) + assertNull(store.load(staged.authority)) + val client = GatewayClient(authenticator, scope).also { clients += it } + assertEquals(GatewayConnection.Connected, client.connect().connection) + authenticator.commit() + assertEquals(staged, store.load(staged.authority)) + val profiles = client.request("profiles.list", buildJsonObject { put("include_sessions", true) }) + assertTrue(profiles.jsonObject["profiles"] is JsonArray) + } + + @Test fun anAccessTokenFromTheWrongHostModeIsNeverSentToTheOtherMechanism() = runBlocking { + val open = authenticator("open") + val failure = runCatching { open.signIn(SignInInput.Password("basic", "u", "p")) }.exceptionOrNull() as HermesException + assertEquals(HermesException.Kind.UnsupportedAuthentication, failure.kind) + val gated = authenticator("password") + val mismatch = runCatching { gated.signIn(SignInInput.Dashboard) }.exceptionOrNull() as HermesException + assertEquals(HermesException.Kind.AuthModeChanged, mismatch.kind) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/SavedConnectionTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/SavedConnectionTest.kt new file mode 100644 index 00000000..f64dd975 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/SavedConnectionTest.kt @@ -0,0 +1,139 @@ +package app.bighelp.hermes + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class SavedConnectionTest { + private val endpoint = HermesEndpoint.parse("hermes.example/p") + private val other = HermesEndpoint.parse("hermes.example/q") + + private fun bearer(access: String = "access-1", refresh: String? = "refresh-1", expires: Long? = 1_900_000_000L, + provider: String? = "basic", user: String? = "synthetic-user", at: HermesEndpoint = endpoint) = + SavedConnection(at, StoredAuth.Bearer(access, refresh, expires), provider, user) + + private fun dashboard(token: String = "dash-1", automatic: Boolean = true, at: HermesEndpoint = endpoint) = + SavedConnection(at, StoredAuth.DashboardSession(token, automatic), null, null) + + private fun kind(block: () -> Unit) = assertThrows(HermesException::class.java) { block() }.kind + + @Test fun authorityIsTheCanonicalEndpointPlusTheExactPrincipal() { + assertEquals(CredentialAuthority("https://hermes.example/p", "basic\u001fsynthetic-user"), bearer().authority) + assertEquals(CredentialAuthority("https://hermes.example/p", "dashboard-session"), dashboard().authority) + assertNotEquals("A prefix is part of the endpoint", bearer().authority, bearer(at = other).authority) + assertNotEquals("Case matters: no folding", bearer(user = "User").authority, bearer(user = "user").authority) + assertNotEquals(bearer(user = "é").authority, bearer(user = "é").authority) + } + + @Test fun validationAcceptsTheTwoShapesAndRefusesIncompleteOnes() { + bearer().validate() + bearer(refresh = null, expires = null).validate() + dashboard().validate() + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(provider = null).validate() }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(user = null).validate() }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(provider = "").validate() }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(user = " padded ").validate() }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(provider = "p".repeat(129)).validate() }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(user = "u".repeat(513)).validate() }) + assertEquals(HermesException.Kind.SavedConnectionInvalid, kind { bearer(user = "a\u0007").validate() }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { bearer(access = "has space").validate() }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { bearer(refresh = "").validate() }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { dashboard(token = "").validate() }) + assertEquals(HermesException.Kind.InvalidCredentials, kind { dashboard(token = "é").validate() }) + assertEquals( + "A dashboard credential has no provider or user", + HermesException.Kind.SavedConnectionInvalid, + kind { SavedConnection(endpoint, StoredAuth.DashboardSession("t", true), "basic", "u").validate() }, + ) + } + + @Test fun secretsNeverAppearInToString() { + val text = listOf(bearer(access = "ACCESS-SECRET", refresh = "REFRESH-SECRET"), dashboard("DASH-SECRET")) + .joinToString { it.toString() + it.auth.toString() } + listOf("ACCESS-SECRET", "REFRESH-SECRET", "DASH-SECRET").forEach { assertFalse(it, it in text) } + } + + @Test fun equalityIsExactForCompareAndReplace() { + assertEquals(bearer(), bearer()) + assertEquals(bearer().hashCode(), bearer().hashCode()) + assertNotEquals(bearer(), bearer(access = "access-2")) + assertNotEquals(bearer(), bearer(refresh = null)) + assertNotEquals(bearer(), bearer(expires = 1L)) + assertNotEquals(dashboard(), dashboard(automatic = false)) + } + + @Test fun theCodecRoundTripsBothShapesAndRevalidatesTheEndpoint() { + listOf(bearer(), bearer(refresh = null, expires = null), dashboard(), dashboard(automatic = false)).forEach { + assertEquals(it, SavedConnection.fromBytes(it.toBytes())) + } + val privateHttp = HermesEndpoint.parse("http://127.0.0.1:9119", allowPrivateHttp = true) + val saved = bearer(at = privateHttp) + assertEquals(saved, SavedConnection.fromBytes(saved.toBytes())) + } + + @Test fun theCodecRefusesUnknownSchemaChangedBindingOversizeAndGarbage() { + val good = String(bearer().toBytes(), Charsets.UTF_8) + fun decode(text: String) = kind { SavedConnection.fromBytes(text.toByteArray()) } + assertEquals(HermesException.Kind.SavedConnectionInvalid, decode(good.replace("\"schemaVersion\":1", "\"schemaVersion\":2"))) + assertEquals( + "The record's own endpoint binding must match its endpoint", + HermesException.Kind.SavedConnectionInvalid, + decode(good.replace("\"credentialEndpointIdentity\":\"https://hermes.example/p\"", "\"credentialEndpointIdentity\":\"https://hermes.example/q\"")), + ) + assertEquals(HermesException.Kind.SavedConnectionInvalid, decode("{")) + assertEquals(HermesException.Kind.SavedConnectionInvalid, decode("[]")) + assertEquals( + HermesException.Kind.SavedConnectionInvalid, + kind { SavedConnection.fromBytes(ByteArray(SavedConnection.MAXIMUM_RECORD_BYTES + 1) { 0x20 }) }, + ) + assertEquals( + "Plain HTTP that is not opted in stays refused when reading a saved record", + HermesException.Kind.SavedConnectionInvalid, + decode(good.replace("https://hermes.example/p", "http://hermes.example/p")), + ) + } + + @Test fun theCodecToleratesUnknownFieldsFromALaterBuild() { + val withExtra = String(dashboard().toBytes(), Charsets.UTF_8).replaceFirst("{", "{\"futureField\":{\"a\":1},") + assertEquals(dashboard(), SavedConnection.fromBytes(withExtra.toByteArray())) + } + + @Test fun theInMemoryStoreIsACompareAndReplaceStore() = runBlocking { + val store = InMemoryCredentialStore() + val first = bearer() + assertNull(store.load(first.authority)) + store.replace(null, first) + assertEquals(first, store.load(first.authority)) + + assertThrows("Insert-only fails when a record exists", StaleCredentialException::class.java) { + runBlocking { store.replace(null, bearer(access = "other")) } + } + val rotated = bearer(access = "access-2", refresh = "refresh-2") + assertThrows("A stale expectation never overwrites", StaleCredentialException::class.java) { + runBlocking { store.replace(bearer(access = "stale"), rotated) } + } + assertEquals(first, store.load(first.authority)) + + store.replace(first, rotated) + assertEquals(rotated, store.load(first.authority)) + assertThrows(StaleCredentialException::class.java) { runBlocking { store.delete(first) } } + assertEquals("A stale delete leaves a newer record", rotated, store.load(first.authority)) + store.delete(rotated) + assertNull(store.load(first.authority)) + assertTrue(store.load(dashboard().authority) == null) + } + + @Test fun aReplacementMustKeepTheAuthority() = runBlocking { + val store = InMemoryCredentialStore() + store.replace(null, bearer()) + assertThrows(IllegalArgumentException::class.java) { + runBlocking { store.replace(bearer(), bearer(user = "someone-else")) } + } + Unit + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedGateway.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedGateway.kt new file mode 100644 index 00000000..6c8cd26d --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedGateway.kt @@ -0,0 +1,183 @@ +package app.bighelp.hermes + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.RecordedRequest +import okio.ByteString + +/** + * A scripted Hermes gateway on loopback: real HTTP upgrade and real WebSocket frames, answered by lambdas. + * It is a test double for the client's transport rules; it is not Hermes. + */ +class ScriptedGateway(prefix: String = "") : AutoCloseable { + val host = ScriptedHost(prefix) + + /** One accepted upgrade. */ + inner class Conn(val request: RecordedRequest, val index: Int) { + val frames = LinkedBlockingQueue() + val allFrames = CopyOnWriteArrayList() + @Volatile lateinit var socket: WebSocket + @Volatile var closedByClient = false + @Volatile var closeCode: Int? = null + @Volatile var readySentNanos = 0L + @Volatile var firstFrameNanos = 0L + + fun send(text: String) { socket.send(text) } + fun sendBinary(text: String) { socket.send(ByteString.of(*text.toByteArray())) } + fun event(type: String, payload: String = "{}", session: String? = null, seq: Long? = null) { + send(eventLine(type, payload, session, seq)) + } + fun result(id: String, json: String = "{}") = send("""{"jsonrpc":"2.0","id":${quote(id)},"result":$json}""") + fun failure(id: String, code: Long, message: String = "no", data: String? = null) = + send("""{"jsonrpc":"2.0","id":${quote(id)},"error":{"code":$code,"message":${quote(message)}${data?.let { ",\"data\":$it" } ?: ""}}}""") + fun close(code: Int = 1000) { socket.close(code, null) } + /** The host ends the connection (a server-initiated close). */ + fun drop() { socket.close(1011, null) } + + fun nextFrame(timeoutMillis: Long = 5_000): JsonObject { + val text = frames.poll(timeoutMillis, TimeUnit.MILLISECONDS) ?: throw AssertionError("No frame within ${timeoutMillis}ms on connection $index") + return Json.parseToJsonElement(text).jsonObject + } + + fun nextFrame(method: String, timeoutMillis: Long = 5_000): JsonObject { + val frame = nextFrame(timeoutMillis) + check(frame["method"]?.jsonPrimitive?.content == method) { "Expected $method but got ${frame["method"]}" } + return frame + } + + /** Discards frames until one matches; the handshake RPCs are answered automatically and queued too. */ + fun awaitFrame(timeoutMillis: Long = 5_000, predicate: (JsonObject) -> Boolean): JsonObject { + val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis) + while (true) { + val left = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()) + val frame = nextFrame(left.coerceAtLeast(1)) + if (predicate(frame)) return frame + } + } + + fun awaitMethod(method: String, timeoutMillis: Long = 5_000) = + awaitFrame(timeoutMillis) { it["method"]?.jsonPrimitive?.content == method } + + fun framesWithMethod(method: String) = allFrames.map { Json.parseToJsonElement(it).jsonObject } + .filter { it["method"]?.jsonPrimitive?.content == method } + + fun hasFrame(): Boolean = frames.isNotEmpty() + } + + val connections = LinkedBlockingQueue() + val all = CopyOnWriteArrayList() + + /** Global order of what the host saw: `"ws:"`, `"http:"`, `"upgrade"`. */ + val log = CopyOnWriteArrayList() + + /** Called for every client frame on a connection (after it is queued). Default: answer the handshake RPCs. */ + @Volatile var responder: (Conn, JsonObject) -> Unit = { conn, frame -> defaultResponse(conn, frame) } + @Volatile var readyPayload: String = """{"heartbeat":true,"replay_epoch":"epoch-1"}""" + @Volatile var sendReady: Boolean = true + @Volatile var readyDelayMillis: Long = 0 + @Volatile var capabilitiesResult: String = """{"per_session_exclusive_submit":true}""" + @Volatile var healthBody: String = """{"ok":true,"auth_required":false}""" + @Volatile var negotiatedSubprotocol: String? = null + + /** Connections after this many are refused (HTTP 503), to exhaust recovery. */ + @Volatile var acceptLimit: Int = Int.MAX_VALUE + private val upgrades = AtomicInteger() + private val tickets = AtomicInteger() + val ticketRequests = CopyOnWriteArrayList() + + init { + host.on("GET", "/api/ws") { request -> + log += "upgrade" + if (upgrades.incrementAndGet() > acceptLimit) { + MockResponse().setResponseCode(503) + } else { + val conn = Conn(request, all.size) + all += conn + val response = MockResponse().withWebSocketUpgrade(listener(conn)) + negotiatedSubprotocol?.let { response.setHeader("Sec-WebSocket-Protocol", it) } + response + } + } + host.on("GET", "/api/health") { log += "http:/api/health"; ScriptedHost.json(healthBody) } + host.on("POST", "/api/auth/ws-ticket") { request -> + log += "http:/api/auth/ws-ticket" + ticketRequests += request.getHeader("Authorization").orEmpty() + ScriptedHost.json("""{"ticket":"ticket_${tickets.incrementAndGet()}","ttl_seconds":30}""") + } + } + + private fun listener(conn: Conn) = object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + conn.socket = webSocket + connections.add(conn) + if (sendReady) { + if (readyDelayMillis > 0) { + Thread { Thread.sleep(readyDelayMillis); runCatching { conn.readySentNanos = System.nanoTime(); conn.event("gateway.ready", readyPayload) } }.start() + } else { + conn.readySentNanos = System.nanoTime() + conn.event("gateway.ready", readyPayload) + } + } + } + + override fun onMessage(webSocket: WebSocket, text: String) { + val method = runCatching { Json.parseToJsonElement(text).jsonObject["method"]?.jsonPrimitive?.content }.getOrNull() + log += "ws:$method" + if (conn.firstFrameNanos == 0L) conn.firstFrameNanos = System.nanoTime() + conn.frames.add(text) + conn.allFrames.add(text) + runCatching { responder(conn, Json.parseToJsonElement(text).jsonObject) } + } + + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + conn.closedByClient = true + conn.closeCode = code + webSocket.close(1000, null) + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + conn.closedByClient = true + conn.closeCode = code + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + conn.closedByClient = true + } + } + + fun defaultResponse(conn: Conn, frame: JsonObject) { + val id = frame["id"]?.jsonPrimitive?.content ?: return + when (frame["method"]?.jsonPrimitive?.content) { + "client.capabilities", "gateway.ping" -> conn.result(id) + "gateway.capabilities" -> conn.result(id, capabilitiesResult) + } + } + + fun awaitConnection(timeoutMillis: Long = 5_000): Conn = + connections.poll(timeoutMillis, TimeUnit.MILLISECONDS) ?: throw AssertionError("No gateway connection within ${timeoutMillis}ms") + + override fun close() { + all.forEach { runCatching { it.socket.cancel() } } + host.close() + } + + companion object { + fun quote(text: String): String = kotlinx.serialization.json.JsonPrimitive(text).toString() + + fun eventLine(type: String, payload: String = "{}", session: String? = null, seq: Long? = null) = + """{"jsonrpc":"2.0","method":"event","params":{"type":${quote(type)},"payload":$payload${session?.let { ",\"session_id\":${quote(it)}" } ?: ""}${seq?.let { ",\"seq\":$it" } ?: ""}}}""" + + fun requestLine(id: String, method: String, params: String = "{}") = + """{"jsonrpc":"2.0","id":${quote(id)},"method":${quote(method)},"params":$params}""" + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedHost.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedHost.kt new file mode 100644 index 00000000..3ee686a2 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedHost.kt @@ -0,0 +1,69 @@ +package app.bighelp.hermes + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest + +/** + * A loopback stand-in for one Hermes host: routes answer from lambdas, every request is recorded. It is a + * scripted test double, not Hermes; real-host behavior is covered by the disposable-host probes. + */ +class ScriptedHost(private val prefix: String = "") : AutoCloseable { + val server = MockWebServer() + val requests = CopyOnWriteArrayList() + private val routes = ConcurrentHashMap MockResponse>() + + init { + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + requests += request + val path = request.path.orEmpty().substringBefore('?') + val handler = routes["${request.method} $path"] ?: routes["* $path"] + return handler?.invoke(request) ?: MockResponse().setResponseCode(404) + } + } + server.start() + } + + val endpoint: HermesEndpoint + get() = HermesEndpoint.parse("http://127.0.0.1:${server.port}$prefix", allowPrivateHttp = true) + + fun on(method: String, route: String, handler: (RecordedRequest) -> MockResponse) { + routes["$method $prefix$route"] = handler + } + + fun on(route: String, handler: (RecordedRequest) -> MockResponse) { + routes["* $prefix$route"] = handler + } + + fun on(method: String, route: String, response: MockResponse) = on(method, route) { response } + + /** `"METHOD /route"` lines (the prefix removed), in arrival order. */ + val calls: List + get() = requests.map { "${it.method} ${it.path.orEmpty().substringBefore('?').removePrefix(prefix)}" } + + fun callsTo(route: String) = requests.filter { it.path.orEmpty().substringBefore('?') == "$prefix$route" } + + override fun close() = server.shutdown() + + companion object { + fun json(body: String, code: Int = 200) = + MockResponse().setResponseCode(code).setHeader("Content-Type", "application/json").setBody(body) + + fun html(body: String) = MockResponse().setHeader("Content-Type", "text/html; charset=utf-8").setBody(body) + + fun dashboardPage(token: String) = + html("") + } +} + +/** A clock the test moves by hand. */ +class TestClock(private var instant: java.time.Instant) : java.time.Clock() { + override fun getZone(): java.time.ZoneId = java.time.ZoneOffset.UTC + override fun withZone(zone: java.time.ZoneId?): java.time.Clock = this + override fun instant(): java.time.Instant = instant + fun advanceSeconds(seconds: Long) { instant = instant.plusSeconds(seconds) } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt new file mode 100644 index 00000000..83b9292e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt @@ -0,0 +1,30 @@ +package app.bighelp.hermes + +import org.junit.Assert.assertEquals +import org.junit.Assert.fail +import org.junit.Test + +/** The parser on its own, for the cases the byte-level decoder's earlier checks make unreachable. */ +class StrictJsonTest { + private fun rejects(text: String) { + try { + StrictJson.parse(text) + fail("Expected '$text' to be malformed") + } catch (_: StrictJson.Malformed) { + } + } + + @Test fun unpairedSurrogateCharactersAreMalformedEvenWhenNotEscaped() { + rejects("\"\ud800\"") + rejects("\"\udc00\"") + rejects("\"\ud800a\"") + rejects("\"\udc00\ud800\"") + assertEquals("\"😀\"", StrictJson.parse("\"😀\"").toString()) + } + + @Test fun parserEnforcesItsOwnDepthCeiling() { + StrictJson.parse("[".repeat(64) + "]".repeat(64)) + rejects("[".repeat(65) + "]".repeat(65)) + rejects("{\"a\":".repeat(65) + "0" + "}".repeat(65)) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogDecoderTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogDecoderTest.kt new file mode 100644 index 00000000..1f1b88d4 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogDecoderTest.kt @@ -0,0 +1,149 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CatalogDecoderTest { + private fun invalid(block: () -> Unit) { + val e = runCatching(block).exceptionOrNull() + assertTrue("Expected InvalidResponse but got $e", e is HermesException && e.kind == HermesException.Kind.InvalidResponse) + } + + @Test fun profilesKeepOptionalMetadataAndTheCanonicalRegistryIdentity() { + val agents = CatalogDecoder.profiles(json("""{"profiles":[ + {"name":"research","display_name":"Research Bot","canonical_session":{"id":"bot-1","resolved_id":"bot-1-tip"},"model":"m","future_field":{"a":1}}, + {"name":"scratch","canonical_session":null}, + {"name":"plain","display_name":""} + ]}""")) + assertEquals(listOf("research", "scratch", "plain"), agents.map { it.id }) + assertEquals("Research Bot", agents[0].displayName) + assertEquals("bot-1", agents[0].canonicalChat!!.id) + assertEquals("bot-1-tip", agents[0].canonicalChat!!.resolvedId) + assertEquals("future_field survives in the host's own row", "m", agents[0].metadata["model"].asString) + assertEquals("The ID is the name when the host gives no display name", "scratch", agents[1].displayName) + assertEquals("plain", agents[2].displayName) + assertNull(agents[1].canonicalChat) + } + + @Test fun profilesRefuseDuplicatesOversizeAndMalformedRegistry() { + invalid { CatalogDecoder.profiles(json("""{"profiles":[{"name":"a"},{"name":"a"}]}""")) } + invalid { CatalogDecoder.profiles(json("""{"profiles":[{"name":" padded "}]}""")) } + invalid { CatalogDecoder.profiles(json("""{"profiles":[{"name":"a","canonical_session":{"resolved_id":"x"}}]}""")) } + invalid { CatalogDecoder.profiles(json("""{"profiles":"nope"}""")) } + invalid { CatalogDecoder.profiles(json("""{"profiles":[${(1..513).joinToString(",") { """{"name":"p$it"}""" }}]}""")) } + } + + private fun row(id: String, extra: String = "", profile: String? = "research") = + """{"id":"$id",${profile?.let { """"profile":"$it",""" } ?: ""}"started_at":1792000000,"title":"T $id","message_count":3$extra}""" + + private fun page(rows: List, offset: Int = 0, limit: Int = 100, envelope: String = "list", hasMore: Boolean = false, total: Int? = null) = + if (envelope == "list") json("""{"object":"list","data":[${rows.joinToString(",")}],"has_more":$hasMore,"limit":$limit,"offset":$offset${total?.let { ""","total":$it""" } ?: ""}}""") + else json("""{"sessions":[${rows.joinToString(",")}],"total":${total ?: rows.size},"limit":$limit,"offset":$offset}""") + + @Test fun bothSessionEnvelopesDecodeAndAProfileEchoMustMatchWhenPresent() { + val newer = CatalogDecoder.sessionPage(page(listOf(row("s1"), row("s2", profile = null))), "research", 0) + assertEquals(2, newer.rows.size) + assertEquals(false, newer.hasMore) + val legacy = CatalogDecoder.sessionPage(page(listOf(row("s1")), envelope = "legacy", total = 250), "research", 0) + assertNull("The legacy envelope has no has_more", legacy.hasMore) + assertEquals(250, legacy.total) + invalid { CatalogDecoder.sessionPage(page(listOf(row("s1", profile = "someone-else"))), "research", 0) } + invalid { CatalogDecoder.sessionPage(page(listOf(row("s1")), offset = 100), "research", 0) } + invalid { CatalogDecoder.sessionPage(page(listOf(row("s1")), limit = 50), "research", 0) } + invalid { CatalogDecoder.sessionPage(json("""{"object":"list","data":[{"title":"no id"}],"has_more":false,"limit":100,"offset":0}"""), "research", 0) } + invalid { CatalogDecoder.sessionPage(json("""{"object":"list","data":[],"limit":100,"offset":0}"""), "research", 0) } + } + + @Test fun continuationFollowsHasMoreThenTotalThenAFullPage() { + fun more(envelope: String) = CatalogDecoder.sessionPage(json(envelope), "research", 0).let { CatalogDecoder.hasMore(it, 0, it.rows.size) } + assertTrue(more("""{"object":"list","data":[${row("s1")}],"has_more":true,"limit":100,"offset":0}""")) + assertFalse(more("""{"object":"list","data":[${row("s1")}],"has_more":false,"limit":100,"offset":0}""")) + assertTrue(more("""{"sessions":[${row("s1")}],"total":101,"limit":100,"offset":0}""")) + assertFalse(more("""{"sessions":[${row("s1")}],"total":100,"limit":100,"offset":0}""")) + // A host that sends neither has_more nor total can only be judged by a full page. + val bare = { count: Int -> SessionPage(List(count) { JsonObject(emptyMap()) }, limit = 100, offset = 0, hasMore = null, total = null) } + assertTrue(CatalogDecoder.hasMore(bare(100), 0, 100)) + assertFalse(CatalogDecoder.hasMore(bare(99), 0, 99)) + } + + @Test fun aRowBecomesASummaryWithItsAnchorAndNeverInventsMissingFacts() { + val summary = CatalogDecoder.summary( + jsonObject(row("s1", """, + "preview":"hello there","source":"bighelp","cwd":"/home/example/p","pinned":true,"last_active":1792000500""")), + "research", null, + ) + assertEquals(ConversationRef("research", "s1"), summary.ref) + assertEquals("T s1", summary.title) + assertEquals("hello there", summary.preview) + assertEquals(1_792_000_500.0, summary.lastActiveEpochSeconds!!, 0.0) + assertEquals(1_792_000_000.0, summary.startedAtEpochSeconds!!, 0.0) + assertEquals(3, summary.messageCount) + assertTrue(summary.pinned) + assertEquals("/home/example/p", summary.cwd) + assertFalse(summary.isCanonicalBotChat) + assertFalse(summary.isRegistryOnly) + val untitled = CatalogDecoder.summary(jsonObject("""{"id":"s2","profile":"research","started_at":1,"title":""}"""), "research", null) + assertEquals("Untitled", untitled.title) + assertEquals("A missing count is zero, not a guess", 0, untitled.messageCount) + assertEquals("last activity falls back to the start", 1.0, untitled.lastActiveEpochSeconds!!, 0.0) + invalid { CatalogDecoder.summary(jsonObject("""{"id":"s3","profile":"research","title":"x"}"""), "research", null) } // started_at is required + invalid { CatalogDecoder.summary(jsonObject("""{"id":"s4","profile":"research","started_at":1,"message_count":-1}"""), "research", null) } + } + + @Test fun theAnchorIsTheLineageRootAndLineageMustBeConsistent() { + val compacted = CatalogDecoder.summary( + jsonObject(row("tip-3", ""","_lineage_root_id":"root-1","_lineage_ids":["root-1","tip-2","tip-3"]""")), "research", null, + ) + assertEquals("root-1", compacted.ref.anchor) + assertEquals("tip-3", compacted.storedId) + assertEquals(listOf("root-1", "tip-2", "tip-3"), compacted.lineageIds) + invalid { CatalogDecoder.summary(jsonObject(row("tip-3", ""","_lineage_ids":["root-1","tip-2"]""")), "research", null) } // missing its own ID + invalid { CatalogDecoder.summary(jsonObject(row("tip-3", ""","_lineage_root_id":"zzz","_lineage_ids":["tip-3"]""")), "research", null) } + invalid { CatalogDecoder.summary(jsonObject(row("tip-3", ""","_lineage_ids":["tip-3","tip-3"]""")), "research", null) } + } + + @Test fun aRowThatBelongsToTheCanonicalBotChatAnchorsOnTheRegistryId() { + val canonical = CanonicalChat("bot-1", "bot-1-tip") + fun anchor(id: String, extra: String = "") = CatalogDecoder.summary(jsonObject(row(id, extra)), "research", canonical) + assertEquals("bot-1", anchor("bot-1").ref.anchor) + assertEquals("bot-1", anchor("bot-1-tip").ref.anchor) + assertEquals("bot-1", anchor("later-tip", ""","_lineage_root_id":"bot-1","_lineage_ids":["bot-1","later-tip"]""").ref.anchor) + assertTrue(anchor("bot-1").isCanonicalBotChat) + assertFalse(anchor("other").isCanonicalBotChat) + assertEquals("other", anchor("other").ref.anchor) + } + + @Test fun archivedIsDeliberateUnlessHermesIdleSweepMarkedItAutomatic() { + fun state(extra: String) = CatalogDecoder.summary(jsonObject(row("s1", extra)), "research", null).archive + assertEquals(ArchiveState.None, state("")) + assertEquals(ArchiveState.None, state(""","archived":false""")) + assertEquals(ArchiveState.Deliberate, state(""","archived":true""")) + assertEquals(ArchiveState.Deliberate, state(""","archived":1""")) + assertEquals(ArchiveState.Automatic, state(""","archived":true,"auto_archived":true""")) + assertEquals("An auto flag without an archive is not archived", ArchiveState.None, state(""","auto_archived":true""")) + } + + @Test fun theListRequestUsesThePolicyOfTheCurrentApp() { + assertEquals( + listOf("profile" to "research", "limit" to "100", "offset" to "200", "archived" to "include", "order" to "created", + "exclude_sources" to "tool,kanban,bot_room"), + CatalogDecoder.listQuery("research", 200), + ) + } + + @Test fun aRegistryOnlyBotChatInventsNoTitleTimeOrPreview() { + val summary = CatalogDecoder.registryOnly("research", CanonicalChat("bot-1", "bot-1-tip")) + assertEquals(ConversationRef("research", "bot-1"), summary.ref) + assertTrue(summary.isRegistryOnly && summary.isCanonicalBotChat) + assertEquals("bot-1-tip", summary.storedId) + assertEquals("", summary.preview) + assertNull(summary.startedAtEpochSeconds) + assertNull(summary.lastActiveEpochSeconds) + assertEquals("Bot Chat", summary.title) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogRepositoryTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogRepositoryTest.kt new file mode 100644 index 00000000..3b2121cb --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogRepositoryTest.kt @@ -0,0 +1,143 @@ +package app.bighelp.hermes.chat + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CatalogRepositoryTest : ChatTestBase() { + @Test fun refreshReadsProfilesWithSessionsThenEachProfilesPagesWithTheCurrentAppsPolicy() = run { + val r = rig() + r.host.addSession("research", "s1", "First") { addRow("user", "hello") } + val catalog = r.repo.refreshCatalog() + assertEquals(listOf("research", "scratch"), catalog.agents.map { it.id }) + assertEquals("Research Bot", catalog.agents[0].displayName) + assertEquals(listOf("s1"), catalog.sessions.map { it.storedId }) + assertEquals("hello", catalog.sessions.single().preview) + assertEquals(true, r.host.calls("profiles.list").single().params["include_sessions"].asBool) + val list = r.host.restRequests.filter { it.route == "/api/sessions" } + assertEquals(2, list.size) + val query = list[0].query.toMap() + assertEquals("research", query["profile"]) + assertEquals("100", query["limit"]) + assertEquals("0", query["offset"]) + assertEquals("include", query["archived"]) + assertEquals("created", query["order"]) + assertEquals("tool,kanban,bot_room", query["exclude_sources"]) + } + + @Test fun readingTheCatalogNeverCreatesResumesOrActivatesAChat() = run { + val r = rig() + r.host.addSession("research", "s1") { addRow("user", "hi") } + r.repo.refreshCatalog() + r.repo.archivedChats() + r.repo.search("research", "hi") + assertEquals(0, r.host.count("session.create") + r.host.count("session.resume") + r.host.count("session.activate")) + } + + @Test fun theHiddenCanonicalBotChatIsMergedFromTheRegistryAndDeliberatelyArchivedChatsAreLeftOut() = run { + val r = rig() + val bot = r.host.addSession("research", "bot-1") { addRow("user", "hello bot") } + r.host.makeCanonical(bot) + r.host.addSession("research", "kept") { addRow("user", "a") } + r.host.addSession("research", "gone") { addRow("user", "b"); archived = true } + r.host.addSession("research", "swept") { addRow("user", "c"); archived = true; autoArchived = true } + val catalog = r.repo.refreshCatalog() + val byId = catalog.sessions.associateBy { it.storedId } + assertFalse("A deliberately archived chat is not in the normal list", "gone" in byId) + assertEquals("Hermes' idle sweep keeps the chat", ArchiveState.Automatic, byId.getValue("swept").archive) + assertTrue("kept" in byId) + val botRow = catalog.sessions.single { it.isCanonicalBotChat } + assertEquals(ConversationRef("research", "bot-1"), botRow.ref) + assertTrue("The list hides Bot Chats; only the registry names this one", botRow.isRegistryOnly) + assertEquals("", botRow.preview) + assertEquals(null, botRow.lastActiveEpochSeconds) + // A refresh again keeps it (it used to be dropped by a refresh). + assertTrue(r.repo.refreshCatalog().sessions.any { it.isCanonicalBotChat }) + } + + @Test fun aRowThatBelongsToTheBotChatLineageAnchorsOnTheRegistryId() = run { + val r = rig() + val bot = r.host.addSession("research", "bot-1") { addRow("user", "hello") } + r.host.makeCanonical(bot) + r.host.compact("bot-1", "bot-2") + r.host.sessions.getValue("bot-2").hidden = false + val catalog = r.repo.refreshCatalog() + val row = catalog.sessions.single { it.storedId == "bot-2" } + assertEquals("The route anchor is the registry's id, the transcript tip is the row's own", "bot-1", row.ref.anchor) + assertEquals("bot-2", row.storedId) + assertTrue(row.isCanonicalBotChat) + assertFalse(row.isRegistryOnly) + } + + @Test fun boundedContinuationFollowsHasMoreAndTheLegacyTotalAndSkipsRepeatedPinnedRows() = run { + val r = rig() + repeat(130) { r.host.addSession("research", "s$it") { addRow("user", "m$it") } } + assertEquals(130, r.repo.refreshCatalog().sessions.size) + assertEquals(listOf("0", "100"), r.host.restRequests.filter { it.route == "/api/sessions" && it.query.toMap()["profile"] == "research" }.map { it.query.toMap()["offset"] }) + r.host.legacyListEnvelope = true + assertEquals("The older envelope pages by total", 130, r.repo.refreshCatalog().sessions.size) + } + + @Test fun oneUnreadableRowHidesOnlyItself() = run { + val r = rig() + r.host.addSession("research", "good") { addRow("user", "x") } + r.host.addSession("research", "bad") { addRow("user", "y"); startedAt = -1.0 } + val catalog = r.repo.refreshCatalog() + assertEquals(listOf("good"), catalog.sessions.map { it.storedId }) + assertEquals(null, catalog.error) + } + + @Test fun aFailedRefreshKeepsTheLastListAndShowsTheError() = run { + val r = rig() + r.host.addSession("research", "s1") { addRow("user", "x") } + r.repo.refreshCatalog() + r.host.failRest = { it == "/api/sessions" } + val failed = r.repo.refreshCatalog() + assertNotNull(failed.error) + assertEquals(listOf("s1"), failed.sessions.map { it.storedId }) + assertFalse(failed.loading) + } + + @Test fun anAgentWhoseListTheHostCannotGiveDoesNotHideTheOthers() = run { + val r = rig() + r.host.addSession("research", "s1") { addRow("user", "x") } + r.host.unavailableLists += "scratch" + val catalog = r.repo.refreshCatalog() + assertEquals(null, catalog.error) + assertEquals(listOf("s1"), catalog.sessions.map { it.storedId }) + assertEquals(setOf("scratch"), catalog.agentErrors.keys) + assertEquals(ChatError.Kind.HostUnavailable, catalog.agentErrors.getValue("scratch").kind) + assertEquals(listOf("research", "scratch"), catalog.agents.map { it.id }) + // Every agent failing is the whole catalog's problem. + r.host.unavailableLists += "research" + assertEquals(ChatError.Kind.HostUnavailable, r.repo.refreshCatalog().error!!.kind) + // The archived read tolerates it the same way. + r.host.unavailableLists.remove("research") + assertEquals(emptyList(), r.repo.archivedChats()) + } + + @Test fun archivedChatsAreAPlainReadOfOnlyTheDeliberateOnes() = run { + val r = rig() + r.host.addSession("research", "a1", "Archived one") { addRow("user", "x"); archived = true } + r.host.addSession("research", "a2") { addRow("user", "x"); archived = true; autoArchived = true } + r.host.addSession("research", "live") { addRow("user", "x") } + val archived = r.repo.archivedChats() + assertEquals(listOf("a1"), archived.map { it.storedId }) + assertTrue(r.host.restRequests.any { it.query.toMap()["archived"] == "only" }) + } + + @Test fun searchHonoursTheSourcePolicyAndReturnsSnippets() = run { + val r = rig() + r.host.addSession("research", "s1", "Garden notes") { addRow("user", "tomatoes need sun") } + r.host.addSession("research", "s2", "Other") { addRow("user", "nothing") } + val results = r.repo.search("research", "tomatoes") + assertEquals(listOf("s1"), results.map { it.session.storedId }) + assertEquals("tomatoes need sun", results.single().snippet) + val query = r.host.restRequests.last { it.route == "/api/sessions/search" }.query.toMap() + assertEquals("tool,kanban,bot_room", query["exclude_sources"]) + assertEquals("20", query["limit"]) + assertThrowsChat(ChatError.Kind.InvalidInput) { r.repo.search("research", "") } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt new file mode 100644 index 00000000..572b7614 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt @@ -0,0 +1,99 @@ +package app.bighelp.hermes.chat + +import java.io.File +import java.nio.file.Files +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.rules.Timeout + +/** Waits for [this] for a bounded time and fails the test with [message], not with a bare timeout. */ +suspend fun kotlinx.coroutines.Deferred.awaitWithin(message: String, timeoutMillis: Long = 5_000): T = try { + withTimeout(timeoutMillis) { await() } +} catch (e: kotlinx.coroutines.TimeoutCancellationException) { + throw AssertionError("Timed out waiting for $message") +} + +/** One repository over a scripted host and a store, with helpers to wait for asynchronous state. */ +internal class ChatRig( + val host: FakeHermesHost = FakeHermesHost(), + val store: ChatStore = MemoryChatStore(), + val config: ChatConfig = ChatConfig(), +) { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + val repo = HermesChatRepository(host, host, scope, ChatTestData.host, store, config) + + suspend fun eventually(timeoutMillis: Long = 5_000, message: String = "condition", condition: suspend () -> Boolean) { + try { + withTimeout(timeoutMillis) { while (!condition()) delay(5) } + } catch (e: kotlinx.coroutines.TimeoutCancellationException) { + throw AssertionError("Timed out waiting for $message") + } + } + + fun state(ref: ConversationRef): ConversationState = repo.conversations.value.getValue(ref) + + suspend fun awaitState(ref: ConversationRef, message: String = "state", predicate: (ConversationState) -> Boolean): ConversationState { + eventually(message = message) { repo.conversations.value[ref]?.let(predicate) == true } + return state(ref) + } + + /** A new empty chat for [profile], opened and covered. */ + suspend fun newChat(profile: String = "research", request: CreateRequest = CreateRequest()): ConversationRef { + val outcome = repo.createChat(profile, request) + val ref = (outcome as? CreateOutcome.Created)?.ref ?: throw AssertionError("create failed: $outcome") + awaitState(ref, "ready") { it.phase == ConversationPhase.Ready } + return ref + } + + /** A saved chat with [rows] user/assistant pairs on the host, opened and covered. */ + suspend fun savedChat(profile: String = "research", pairs: Int = 2, build: FakeHermesHost.Session.() -> Unit = {}): ConversationRef { + val session = host.addSession(profile) { + repeat(pairs) { addRow("user", "question $it"); addRow("assistant", "answer $it") } + build() + } + val ref = ConversationRef(profile, session.id) + repo.open(ref) + awaitState(ref, "ready") { it.phase == ConversationPhase.Ready } + return ref + } + + fun runtimeOf(ref: ConversationRef): FakeHermesHost.Runtime = + host.runtimes.values.last { it.stored == state(ref).identity.storedTip } + + fun close() { + repo.close() + scope.cancel() + } +} + +/** JUnit base: a bounded runtime for every test, and a rig per test. */ +abstract class ChatTestBase { + @get:Rule val timeout: Timeout = Timeout.seconds(60) + private val rigs = ArrayList() + protected val directory: File = Files.createTempDirectory("chat-test").toFile() + + internal fun rig(host: FakeHermesHost = FakeHermesHost(), store: ChatStore = MemoryChatStore(), config: ChatConfig = ChatConfig()): ChatRig = + ChatRig(host, store, config).also { rigs += it } + + @After fun closeRigs() { + rigs.forEach { runCatching { it.close() } } + directory.deleteRecursively() + } + + protected fun run(block: suspend () -> Unit) { runBlocking { block() } } + + protected fun assertThrowsChat(kind: ChatError.Kind, block: suspend () -> Unit) { + val e = runCatching { runBlocking { block() } }.exceptionOrNull() + assertTrue("Expected ChatException($kind) but got $e", e is ChatException) + assertEquals(kind, (e as ChatException).error.kind) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatStoreTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatStoreTest.kt new file mode 100644 index 00000000..8367b7b1 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatStoreTest.kt @@ -0,0 +1,178 @@ +package app.bighelp.hermes.chat + +import java.io.File +import java.nio.file.Files +import java.util.UUID +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class ChatStoreTest { + private val directory = Files.createTempDirectory("chat-store").toFile() + private val file = File(directory, "snapshot.bin") + private val host = ChatTestData.host + private val scope = ConversationScope(host, "research", "anchor-1") + + @After fun clean() { directory.deleteRecursively() } + + private fun draft(text: String, at: ConversationScope = scope) = + StoreOp.Put(RecordKey.draft(at), DraftRecord(at, text, updatedAtMillis = 5).encode()) + + @Test fun aCommitIsAllOrNothingAndSurvivesARestart() = runBlocking { + val store = FileSnapshotChatStore(file) + val entryId = UUID.randomUUID().toString() + val entry = JournalEntry(entryId, scope, "prompt.submit", "hi", "hi", emptyList(), 7) + store.commit(listOf(draft("typing"), StoreOp.Put(RecordKey.journal(scope, entryId), entry.encode()))) + + // A failed transaction applies none of its operations, also not the ones before the failing one. + store.failNextCommit = ChatStoreException(ChatStoreException.Kind.QuotaExceeded) + val failure = runCatching { store.commit(listOf(draft("changed"), StoreOp.Delete(RecordKey.journal(scope, entryId)))) }.exceptionOrNull() + assertEquals(ChatStoreException.Kind.QuotaExceeded, (failure as ChatStoreException).kind) + assertEquals("typing", DraftRecord.decode(scope, store.read(RecordKey.draft(scope))!!).text) + assertNotNull(store.read(RecordKey.journal(scope, entryId))) + + // The process "restarts": a new store over the same file sees exactly the committed state. + val reopened = FileSnapshotChatStore(file) + assertEquals("typing", DraftRecord.decode(scope, reopened.read(RecordKey.draft(scope))!!).text) + val journal = reopened.keys(host, RecordKind.Journal, "research", "anchor-1") + assertEquals(listOf(entryId), journal.map { it.entry }) + assertEquals("hi", JournalEntry.decode(scope, entryId, reopened.read(journal.single())!!).composerText) + } + + @Test fun anOversizeRecordIsRefusedBeforeAnythingIsApplied() = runBlocking { + val store = MemoryChatStore() + store.commit(listOf(draft("keep"))) + val tooBig = StoreOp.Put(RecordKey.draft(scope), ByteArray(RecordKind.Draft.maximumBytes + 1)) + val other = ConversationScope(host, "research", "anchor-2") + val failure = runCatching { store.commit(listOf(draft("second", other), tooBig)) }.exceptionOrNull() as ChatStoreException + assertEquals(ChatStoreException.Kind.TooLarge, failure.kind) + assertNull("The earlier operation of the failed transaction is not applied", store.read(RecordKey.draft(other))) + assertEquals("keep", DraftRecord.decode(scope, store.read(RecordKey.draft(scope))!!).text) + } + + @Test fun aCacheKindIsNotADurableCommitAndADurableKindIsNotACacheWrite() = runBlocking { + val store = MemoryChatStore() + assertThrows(IllegalArgumentException::class.java) { runBlocking { store.commit(listOf(StoreOp.Put(RecordKey.catalog(host), ByteArray(1)))) } } + assertThrows(IllegalArgumentException::class.java) { runBlocking { store.putCache(RecordKey.draft(scope), ByteArray(1)) } } + Unit + } + + @Test fun evictingTheCacheNeverTouchesUnsentOrUncertainWork() = runBlocking { + val store = FileSnapshotChatStore(file) + val entryId = UUID.randomUUID().toString() + store.commit(listOf(draft("unsent words"), StoreOp.Put(RecordKey.journal(scope, entryId), + JournalEntry(entryId, scope, "prompt.submit", "x", "x", emptyList(), 1).encode()))) + store.putCache(RecordKey.history(scope), ByteArray(4_000)) + store.putCache(RecordKey.catalog(host), ByteArray(4_000)) + assertNotNull(store.read(RecordKey.history(scope))) + + store.evictCaches() + + assertNull(store.read(RecordKey.history(scope))) + assertNull(store.read(RecordKey.catalog(host))) + assertEquals("unsent words", DraftRecord.decode(scope, store.read(RecordKey.draft(scope))!!).text) + assertNotNull(store.read(RecordKey.journal(scope, entryId))) + } + + @Test fun anOversizeCacheWriteIsDroppedQuietlyWhileTheCommitPathStaysStrict() = runBlocking { + val store = MemoryChatStore() + store.putCache(RecordKey.history(scope), ByteArray(RecordKind.HistoryCache.maximumBytes + 1)) + assertNull(store.read(RecordKey.history(scope))) + } + + @Test fun everyRecordIsScopedByComputerEndpointPrincipalProfileAndAnchor() = runBlocking { + val store = MemoryChatStore() + val variants = listOf( + scope, + ConversationScope(host.copy(computerId = UUID.randomUUID().toString()), "research", "anchor-1"), + ConversationScope(host.copy(endpoint = "https://other.example"), "research", "anchor-1"), + ConversationScope(host.copy(principal = "basic:someone-else"), "research", "anchor-1"), + ConversationScope(host, "other-profile", "anchor-1"), + ConversationScope(host, "research", "anchor-2"), + ) + variants.forEachIndexed { index, each -> store.commit(listOf(draft("text $index", each))) } + variants.forEachIndexed { index, each -> + assertEquals("text $index", DraftRecord.decode(each, store.read(RecordKey.draft(each))!!).text) + } + assertEquals("Only the exact scope is listed", 1, store.keys(host, RecordKind.Draft, "research", "anchor-1").size) + } + + @Test fun aRecordReadUnderAnotherScopeIsCorruptNotSilentlyForeign() { + val bytes = DraftRecord(scope, "mine", updatedAtMillis = 1).encode() + val foreign = ConversationScope(host, "research", "anchor-2") + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { DraftRecord.decode(foreign, bytes) }.exceptionOrNull() as ChatStoreException).kind) + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { DraftRecord.decode(scope, "not json".toByteArray()) }.exceptionOrNull() as ChatStoreException).kind) + } + + @Test fun theDraftRecordHoldsAFullMebibyteOfComposerTextWhichTheCredentialCapCouldNot() { + val text = "é".repeat(524_288) // 1 MiB of UTF-8 + val bytes = DraftRecord(scope, text, updatedAtMillis = 1).encode() + assertTrue("A record above 64 KiB is allowed", bytes.size > 65_536) + assertEquals(text, DraftRecord.decode(scope, bytes).text) + assertTrue(bytes.size <= ChatStoreLimits.MAXIMUM_DRAFT_RECORD_BYTES) + } + + @Test fun textThatCannotFitTheRecordAfterEscapingIsRefusedNotTruncated() { + // 1 MiB of control characters escapes to 6 bytes each, far beyond a frame and a record. + val text = "\u0001".repeat(ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES) + val failure = runCatching { DraftRecord(scope, text, updatedAtMillis = 1).encode() }.exceptionOrNull() as ChatStoreException + assertEquals(ChatStoreException.Kind.TooLarge, failure.kind) + } + + @Test fun aJournalEntryKeepsTheExactBytesTheComposerTextAndTheirReferences() { + val id = UUID.randomUUID().toString() + val entry = JournalEntry(id, scope, "command.dispatch", "expanded text 
 with spaces", "/plan now", listOf("file://a", "file://b"), 99) + val back = JournalEntry.decode(scope, id, entry.encode()) + assertEquals("command.dispatch", back.method) + assertEquals("expanded text 
 with spaces", back.text) + assertEquals("/plan now", back.composerText) + assertEquals(listOf("file://a", "file://b"), back.attachments) + assertFalse(back.isRefused) + assertEquals(true, back.refused(4001).isRefused) + assertEquals(4001, JournalEntry.decode(scope, id, back.refused(4001).encode()).rejectionCode) + } + + @Test fun aCreationRecordKeepsTheWholeLogicalCreateAndRejectsIncoherentPhases() { + val intent = UUID.randomUUID().toString() + val request = CreateRequest(cwd = "/home/example/project", title = "Plan", model = "m", provider = "p", reasoningEffort = "high", fast = false) + val record = CreationRecord(host, intent, "research", CreationPurpose.Ordinary, CreationPhase.CreateRequested, request, createdAtMillis = 5) + val back = CreationRecord.decode(host, "research", record.encode()) + assertEquals(record, back) + // A created record must carry both coordinates. + val incoherent = record.copy(phase = CreationPhase.Created) + assertFalse(incoherent.isCoherent) + assertEquals(ChatStoreException.Kind.Corrupt, (runCatching { CreationRecord.decode(host, "research", incoherent.encode()) }.exceptionOrNull() as ChatStoreException).kind) + assertArrayEquals(record.encode(), back.encode()) + } + + @Test fun anIdentityRecordKeepsTheTipAndTheRoutingAliasesAcrossARestart() { + val identity = ConversationIdentity(scope.ref, "tip-1").withTip("tip-2").withTip("tip-3") + val back = IdentityRecord.decode(scope, IdentityRecord(scope, identity).encode()) + assertEquals("tip-3", back.storedTip) + assertEquals(listOf("tip-1", "tip-2"), back.formerStoredIds) + assertTrue(back.knows("tip-1") && back.knows("tip-3") && back.knows("anchor-1")) + assertFalse(back.knows("unrelated")) + } + + @Test fun theConversationRefRoundTripsAndRefusesAnythingItDidNotProduce() { + val ref = ConversationRef("research", "a/b:c.d-é") + assertEquals(ref, ConversationRef.parse(ref.id)) + assertNull(ConversationRef.parse("c1.cmVzZWFyY2g.")) // empty anchor + assertNull(ConversationRef.parse("c1.cmVzZWFyY2g=.YQ")) // padded, not canonical + assertNull(ConversationRef.parse("c2.cmVzZWFyY2g.YQ")) + assertThrows(IllegalArgumentException::class.java) { ConversationRef("", "x") } + assertThrows(IllegalArgumentException::class.java) { ConversationRef("p", " padded ") } + } +} + +/** Shared fixtures for the chat tests. All values are synthetic. */ +object ChatTestData { + val host = HostScope("5c3f4f06-2a41-4f6a-9d38-0a54d3a3a111", "http://127.0.0.1:9", "dashboard-session") +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CommandRouterTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CommandRouterTest.kt new file mode 100644 index 00000000..c4448bf5 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CommandRouterTest.kt @@ -0,0 +1,163 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CommandRouterTest : ChatTestBase() { + private suspend fun ChatRig.journal(ref: ConversationRef) = + store.keys(ChatTestData.host, RecordKind.Journal, ref.profile, ref.anchor).map { JournalEntry.decode(scopeOf(ref), it.entry!!, store.read(it)!!) } + + private fun ChatRig.messages(ref: ConversationRef) = state(ref).items.filterIsInstance() + + @Test fun theCatalogKeepsInvocationIdentityAliasesAndSourcesAndSkipsOnlyWhatItCannotShow() { + val commands = SlashCommandCatalog.decode(jsonObject("""{ + "pairs":[["/help","Show\nhelp"],["/deploy-skill","Deploys"],["/model","Pick"],["/bad name","x"],["nothing","x"],["/é.x_y","Unicode ok"],["/${"a".repeat(97)}","too long"]], + "canon":{"/h":"/help","/H2":"/help"},"skills":{"deploy-skill":{}}, + "categories":[{"name":"Plugin Commands","pairs":[["/model","Pick"]]}], + "commands":{"/help":{"argument_mode":"options"}}}""").let { it }) + assertEquals(listOf("help", "deploy-skill", "model", "é.x_y"), commands.map { it.name }) + val help = commands[0] + assertEquals("Show help", help.description) + assertEquals(listOf("H2", "h"), help.aliases) + assertEquals(ArgumentMode.Options, help.argumentMode) + assertEquals(CommandSource.Core, help.source) + assertEquals(CommandSource.Skill, commands[1].source) + assertEquals(CommandSource.Plugin, commands[2].source) + val index = SlashCommandIndex(commands) + assertEquals("help", index.selection("/H now")!!.command.name) + assertEquals("now", index.selection("/h now")!!.arguments) + assertNull(index.selection("/unknown")) + assertEquals(listOf("help"), index.suggestions("/he").map { it.name }) + assertEquals("Once it names a command there are no suggestions", emptyList(), index.suggestions("/help")) + } + + @Test fun aCoreCommandRunsThroughSlashExecAndItsOutputIsOneResultWithNoTurn() = run { + val r = rig() + val ref = r.newChat() + val result = r.repo.send(ref, "/help me") + assertEquals(Admission.CommandOutput, (result as SendResult.Admitted).admission) + val call = r.host.calls("slash.exec").single().params + assertEquals("/help me", call["command"].asString) + assertFalse("A command carries no queued flag", call.containsKey("queued")) + assertEquals(0, r.host.count("prompt.submit")) + r.eventually(message = "entry retired") { r.state(ref).unresolved.isEmpty() } + val outputs = r.messages(ref).filter { it.isCommandResult } + assertEquals(listOf("ran help"), outputs.map { it.text }) + assertNull(r.state(ref).sendBlock) + } + + @Test fun aChosenSkillGoesThroughCommandDispatchAndItsExpansionIsSubmittedOnceWithTheExactBytes() = run { + val r = rig() + val ref = r.newChat() + val index = r.repo.commands(ref) + val selection = index.selection("/deploy-skill prod")!! + assertEquals(CommandSource.Skill, selection.command.source) + var journalMethodAtSubmit: String? = null + var journalTextAtSubmit: String? = null + r.host.once("prompt.submit") { params -> + val entry = r.journal(ref).single() + journalMethodAtSubmit = entry.method; journalTextAtSubmit = entry.text + r.host.defaultHandle("prompt.submit", params) + } + val result = r.repo.send(ref, "/deploy-skill prod", selection = selection) + assertEquals(Admission.Streaming, (result as SendResult.Admitted).admission) + val dispatch = r.host.calls("command.dispatch").single().params + assertEquals("deploy-skill", dispatch["name"].asString) + assertEquals("prod", dispatch["arg"].asString) + assertEquals(0, r.host.count("slash.exec")) + val submit = r.host.calls("prompt.submit").single().params + assertEquals("The expanded bytes, once", "EXPANDED(prod)", submit["text"].asString) + assertEquals(true, submit["queued"].asBool) + assertEquals("The journal held the changed method and bytes before they were sent", "prompt.submit", journalMethodAtSubmit) + assertEquals("EXPANDED(prod)", journalTextAtSubmit) + val entry = r.journal(ref).single() + assertEquals("What the person typed survives the expansion", "/deploy-skill prod", entry.composerText) + // Normal terminal rules from here. + r.host.streamReply(r.runtimeOf(ref), "Deployed.") + r.host.flush() + r.eventually(message = "retired at terminal") { r.state(ref).unresolved.isEmpty() } + } + + @Test fun anExplicit4018FallsBackToCommandDispatchOnceAndPersistsTheChangedMethodFirst() = run { + val r = rig() + val ref = r.newChat() + var methodWhenDispatching: String? = null + r.host.once("command.dispatch") { params -> + methodWhenDispatching = r.journal(ref).single().method + r.host.defaultHandle("command.dispatch", params) + } + val result = r.repo.send(ref, "/Deploy-Skill prod now") + assertTrue("$result", result is SendResult.Admitted) + assertEquals(1, r.host.count("slash.exec")) + assertEquals("command.dispatch", methodWhenDispatching) + val dispatch = r.host.calls("command.dispatch").single().params + assertEquals("The name is lowercased, the rest is the argument", "deploy-skill", dispatch["name"].asString) + assertEquals("prod now", dispatch["arg"].asString) + } + + @Test fun aTransportFailureNeverFallsBackToTheOtherRouteAndAnUnknownDispatchNeverReruns() = run { + val r = rig() + val ref = r.newChat() + r.host.timeOutOnce("slash.exec", applyFirst = false) + assertTrue(r.repo.send(ref, "/deploy-skill x") is SendResult.Uncertain) + assertEquals("A timeout of slash.exec does not authorize command.dispatch", 0, r.host.count("command.dispatch")) + assertEquals(1, r.host.count("slash.exec")) + + val other = r.newChat("scratch") + val selection = r.repo.commands(other).selection("/deploy-skill y")!! + r.host.timeOutOnce("command.dispatch") + assertTrue(r.repo.send(other, "/deploy-skill y", selection = selection) is SendResult.Uncertain) + assertEquals("An unknown dispatch is never rerun, and its text is not submitted either", 1, r.host.count("command.dispatch")) + assertEquals(0, r.host.count("prompt.submit")) + assertEquals("command.dispatch", r.state(other).unresolved.single().method) + } + + @Test fun aSelectionIsCheckedAgainstTheCurrentTextSoAStaleOneNeverRuns() = run { + val r = rig() + val ref = r.newChat() + val selection = r.repo.commands(ref).selection("/help")!! + val stale = r.repo.send(ref, "/helpx now", selection = selection) + assertEquals(ChatError.Kind.InvalidInput, (stale as SendResult.NotSent).error.kind) + val notACommand = r.repo.send(ref, "plain words", selection = selection) + assertEquals(ChatError.Kind.InvalidInput, (notACommand as SendResult.NotSent).error.kind) + assertEquals(0, r.host.count("slash.exec") + r.host.count("prompt.submit") + r.host.count("command.dispatch")) + assertTrue(r.journal(ref).isEmpty()) + } + + @Test fun theFirstTurnOfACodeChatWithALeadingSlashUsesTheSameRouterNotPlainPromptSubmit() = run { + val r = rig() + val ref = r.newChat("research", CreateRequest(cwd = "/home/example/project")) + r.host.slashOutputs["plan"] = buildJsonObject { put("type", "send"); put("message", "PLAN: refactor the parser") } + val result = r.repo.send(ref, "/plan refactor the parser") + assertTrue("$result", result is SendResult.Admitted) + assertEquals("/plan refactor the parser", r.host.calls("slash.exec").single().params["command"].asString) + assertEquals("Only the expansion is ever a prompt", listOf("PLAN: refactor the parser"), r.host.calls("prompt.submit").map { it.params["text"].asString }) + } + + @Test fun theNewChatCatalogIsBoundToTheProfileAndFolderBeforeASessionExists() = run { + val r = rig() + val index = r.repo.commandsForNewChat("research", "/home/example/project") + assertNotNull(index.selection("/plan")) + val call = r.host.calls("commands.catalog").single().params + assertEquals("research", call["profile"].asString) + assertEquals("/home/example/project", call["cwd"].asString) + assertFalse(call.containsKey("session_id")) + } + + @Test fun aRejectedCommandIsADefiniteRefusalAndAnArbitraryErrorIsNot() = run { + val r = rig() + val ref = r.newChat() + r.host.rejectOnce("slash.exec", 4002) + assertTrue(r.repo.send(ref, "/help") is SendResult.Refused) + assertEquals("/help", r.state(ref).draft) + r.host.once("slash.exec") { throw HermesException(HermesException.Kind.RpcRejected, code = 5000) } + assertTrue("An arbitrary host error from a mutation is not proof of non-admission", r.repo.send(ref, "/help again") is SendResult.Uncertain) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt new file mode 100644 index 00000000..3eed60ad --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt @@ -0,0 +1,330 @@ +package app.bighelp.hermes.chat + +import java.io.File +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CreateResumeTest : ChatTestBase() { + private val host get() = ChatTestData.host + + @Test fun aNewChatSendsTheBighelpSourceAndAPersistedLowercaseKeyAndKeepsItsIdentitiesApart() = run { + val r = rig() + var recordStoredBeforeDispatch = false + r.host.once("session.create") { params -> + recordStoredBeforeDispatch = r.store.read(RecordKey.creation(host, "research")) != null + r.host.defaultHandle("session.create", params) + } + val ref = r.newChat("research", CreateRequest(title = "Plan")) + val sent = r.host.calls("session.create").single().params + assertTrue("The create intent was on disk before session.create was sent", recordStoredBeforeDispatch) + assertEquals("bighelp", sent["source"].asString) + assertEquals("research", sent["profile"].asString) + val key = sent["idempotency_key"].asString!! + assertEquals(key.lowercase(), key) + assertTrue(Coordinates.isUuid(key)) + // The routing anchor is the stored ID the chat was born with; the runtime ID is a different coordinate. + val state = r.state(ref) + val runtime = r.runtimeOf(ref) + assertEquals(ref.anchor, state.identity.storedTip) + assertNotEquals(runtime.id, ref.anchor) + assertEquals("Empty transcript, nothing invented", emptyList(), state.items) + assertEquals("A finished create leaves no retained intent", emptyList(), r.repo.pendingCreations.value) + assertNull(r.store.read(RecordKey.creation(host, "research"))) + } + + @Test fun aLostCreateReplyKeepsTheIntentAndARetryUsesTheSameKeyAndGetsTheSameSession() = run { + val r = rig() + r.host.loseReplyOnce("session.create", dropSocket = false) + val first = r.repo.createChat("research") + val unconfirmed = first as CreateOutcome.Unconfirmed + assertEquals(ChatError.Kind.CreationUnconfirmed, unconfirmed.error.kind) + r.eventually { r.repo.pendingCreations.value.size == 1 } + val key = r.host.calls("session.create").single().params["idempotency_key"].asString + + val retry = r.repo.createChat("research", retryIntent = unconfirmed.intentId) + val ref = (retry as CreateOutcome.Created).ref + val keys = r.host.calls("session.create").map { it.params["idempotency_key"].asString } + assertEquals("Both sends carry the one key", listOf(key, key), keys) + assertEquals("The host handed back the one session; no duplicate chat", 1, r.host.sessions.size) + assertEquals(1, r.host.sessions.values.count { it.id == ref.anchor }) + assertEquals(emptyList(), r.repo.pendingCreations.value) + } + + @Test fun aLostCreateNeverBlocksAnIndependentFutureChat() = run { + val r = rig() + r.host.timeOutOnce("session.create", applyFirst = false) + val lost = r.repo.createChat("research") as CreateOutcome.Unconfirmed + // A plain New Chat is a new logical create with its own key, not a retry of the lost one. + val independent = r.repo.createChat("research") as CreateOutcome.Created + val keys = r.host.calls("session.create").map { it.params["idempotency_key"].asString } + assertEquals(2, keys.toSet().size) + assertNotEquals(lost.intentId, keys.last()) + assertEquals(ConversationRef("research", independent.ref.anchor), independent.ref) + } + + @Test fun aRetainedIntentSurvivesAProcessRestartAndIsRetriedUnderTheSameKey() = run { + val file = File(directory, "store.bin") + val first = rig(store = FileSnapshotChatStore(file)) + first.host.loseReplyOnce("session.create", dropSocket = false) + val unconfirmed = first.repo.createChat("research") as CreateOutcome.Unconfirmed + val key = first.host.calls("session.create").single().params["idempotency_key"].asString + first.close() + + // The process is gone. A new repository over the same files knows the intent. + val second = rig(store = FileSnapshotChatStore(file)) + second.eventually(message = "pending creation loaded") { second.repo.pendingCreations.value.isNotEmpty() } + assertEquals(unconfirmed.intentId, second.repo.pendingCreations.value.single().intentId) + val created = second.repo.createChat("research", retryIntent = unconfirmed.intentId) + assertTrue(created is CreateOutcome.Created) + assertEquals(key, second.host.calls("session.create").single().params["idempotency_key"].asString) + } + + @Test fun aFailedIntentWriteSendsNoCreate() = run { + val store = FileSnapshotChatStore(File(directory, "s.bin")) + val r = rig(store = store) + store.failNextCommit = ChatStoreException(ChatStoreException.Kind.Unavailable) + val outcome = r.repo.createChat("research") + assertEquals(ChatError.Kind.PersistenceFailed, (outcome as CreateOutcome.Failed).error.kind) + assertEquals("Nothing was dispatched", 0, r.host.count("session.create")) + } + + @Test fun aChosenModelAndFolderMustBeConfirmedByTheCreateAnswer() = run { + val r = rig() + val ok = r.repo.createChat("research", CreateRequest(cwd = "/home/example/p", model = "big-model", provider = "stub-provider", reasoningEffort = "high", fast = false)) + assertTrue(ok is CreateOutcome.Created) + val params = r.host.calls("session.create").single().params + assertEquals("/home/example/p", params["cwd"].asString) + assertEquals(true, params["cwd_explicit"].asBool) + assertEquals("big-model", params["model"].asString) + assertEquals("stub-provider", params["provider"].asString) + assertEquals("high", params["reasoning_effort"].asString) + assertEquals(false, params["fast"].asBool) + + r.host.ignoreRequestedModel = true + val wrongModel = r.repo.createChat("research", CreateRequest(model = "big-model", provider = "stub-provider")) + assertEquals(ChatError.Kind.ModelNotConfirmed, (wrongModel as CreateOutcome.Failed).error.kind) + r.host.ignoreRequestedModel = false + + // The host reports another folder than the one asked for. + r.host.once("session.create") { p -> + val reply = r.host.defaultHandle("session.create", p) as JsonObject + val info = reply["info"] as JsonObject + JsonObject(reply + ("info" to JsonObject(info + ("cwd" to kotlinx.serialization.json.JsonPrimitive("/somewhere/else"))))) + } + val wrongFolder = r.repo.createChat("research", CreateRequest(cwd = "/home/example/p")) + assertEquals(ChatError.Kind.WorkspaceNotConfirmed, (wrongFolder as CreateOutcome.Failed).error.kind) + } + + @Test fun onlyAnExplicitRejectionOfCwdExplicitRetriesWithoutItUnderTheSameKey() = run { + val r = rig() + r.host.rejectCwdExplicit = true + val ref = (r.repo.createChat("research", CreateRequest(cwd = "/home/example/p")) as CreateOutcome.Created).ref + val sends = r.host.calls("session.create") + assertEquals(2, sends.size) + assertTrue(sends[0].params.containsKey("cwd_explicit")) + assertFalse(sends[1].params.containsKey("cwd_explicit")) + assertEquals(sends[0].params["idempotency_key"], sends[1].params["idempotency_key"]) + assertNotNull(ref) + // A timeout is not a rejection: no second send. + val r2 = rig() + r2.host.timeOutOnce("session.create") + assertTrue(r2.repo.createChat("research", CreateRequest(cwd = "/home/example/p")) is CreateOutcome.Unconfirmed) + assertEquals(1, r2.host.count("session.create")) + } + + @Test fun resumeSendsTheStoredIdTheSourceAndTheDocumentedFlags() = run { + val r = rig() + val ref = r.savedChat() + val resume = r.host.calls("session.resume").single().params + assertEquals(ref.anchor, resume["session_id"].asString) + assertEquals("research", resume["profile"].asString) + assertEquals("bighelp", resume["source"].asString) + assertEquals(false, resume["close_on_disconnect"].asBool) + assertEquals(true, resume["defer_history"].asBool) + assertEquals(true, resume["omit_messages"].asBool) + val binding = r.state(ref) + assertNotEquals("Runtime and stored IDs are different coordinates", r.runtimeOf(ref).id, binding.identity.storedTip) + } + + @Test fun aHostThatRefusesTheLifetimeFieldGetsTheSamePlainResume() = run { + val r = rig() + val session = r.host.addSession("research") { addRow("user", "hi") } + r.host.once("session.resume") { throw app.bighelp.hermes.HermesException(app.bighelp.hermes.HermesException.Kind.RpcRejected, code = 4000) } + val ref = ConversationRef("research", session.id) + r.repo.open(ref) + r.awaitState(ref) { it.phase == ConversationPhase.Ready } + val resumes = r.host.calls("session.resume") + assertEquals(2, resumes.size) + assertFalse(resumes[1].params.containsKey("close_on_disconnect")) + } + + @Test fun aFailedResumeNeverBecomesACreate() = run { + val r = rig() + r.host.rejectOnce("session.resume", 4007) + val session = r.host.addSession("research") + val ref = ConversationRef("research", session.id) + r.repo.open(ref) + val state = r.awaitState(ref) { it.lastError != null } + assertEquals(ChatError.Kind.NotOpen, state.lastError!!.kind) + assertEquals("No create as a resume or reconnect fallback", 0, r.host.count("session.create")) + assertEquals(ConversationPhase.Suspended, state.phase) + } + + @Test fun aCompactionSuccessorIsValidatedRebindsTheTipAndKeepsTheRouteAndTheOldAlias() = run { + val r = rig() + val old = r.host.addSession("research", "old-tip") { addRow("user", "hi"); addRow("assistant", "hello") } + val ref = ConversationRef("research", old.id) + r.repo.open(ref) + r.repo.updateDraft(ref, "unfinished thought") + r.host.compact("old-tip", "new-tip") + // The chat is opened again on a new connection: resume of the old tip answers with the successor. + r.repo.release(ref) + r.repo.open(ref) + val state = r.awaitState(ref) { it.phase == ConversationPhase.Ready && it.identity.storedTip == "new-tip" } + assertEquals("The route never changes with the tip", ref, state.ref) + assertEquals(listOf("old-tip"), state.identity.formerStoredIds) + assertTrue(state.identity.knows("old-tip")) + assertEquals("The draft stays with the anchor", "unfinished thought", state.draft) + val history = r.host.restRequests.last { it.route.endsWith("/messages") } + assertTrue("History reads the successor, not the old tip", history.route.contains("new-tip")) + // The alias survives a restart. + val identity = IdentityRecord.decode(r.scopeOf(ref), r.store.read(RecordKey.identity(r.scopeOf(ref)))!!) + assertEquals("new-tip", identity.storedTip) + assertEquals(listOf("old-tip"), identity.formerStoredIds) + } + + @Test fun anEmptyOrInventedIdNeverTargetsADefaultAgent() = run { + val r = rig() + assertTrue(r.repo.createChat("", CreateRequest()) is CreateOutcome.Failed) + assertTrue(r.repo.createChat(" scratch ", CreateRequest()) is CreateOutcome.Failed) + assertEquals(0, r.host.count("session.create")) + assertThrowsChat(ChatError.Kind.NotOpen) { r.repo.reloadHistory(ConversationRef("research", "never-opened")) } + } + + @Test fun theBotChatIsNotCreatedWithoutAnExplicitDecisionAndTheRegistryChatIsResumedByItsRegistryId() = run { + val r = rig() + assertEquals(BotChatOutcome.NotCreated, r.repo.openBotChat("research")) + assertEquals(0, r.host.count("session.create")) + val bot = r.host.addSession("research", "bot-1") { addRow("user", "hello") } + r.host.makeCanonical(bot) + val opened = r.repo.openBotChat("research") as BotChatOutcome.Opened + assertEquals(ConversationRef("research", "bot-1"), opened.ref) + r.awaitState(opened.ref) { it.phase == ConversationPhase.Ready } + assertEquals("bot-1", r.host.calls("session.resume").single().params["session_id"].asString) + } + + @Test fun theFirstBotChatIsHiddenTitledReadBackFromTheRegistryAndRecoveredByItsOwnIntent() = run { + val r = rig() + val outcome = r.repo.openBotChat("research", createIfMissing = true) + val create = r.host.calls("session.create").single().params + assertEquals("Bot Chat", create["title"].asString) + assertEquals(true, create["hidden"].asBool) + assertEquals(true, create["follow_profile_config"].asBool) + assertEquals("bighelp", create["source"].asString) + assertEquals("The title is persisted through session.title", 1, r.host.count("session.title")) + val opened = outcome as BotChatOutcome.Opened + assertEquals("The conversation anchors on the registry's chat", r.host.canonicalIds["research"], opened.ref.anchor) + assertNull("A resolved first creation leaves no retained intent", r.store.read(RecordKey.creation(host, "research"))) + r.awaitState(opened.ref) { it.phase == ConversationPhase.Ready } + } + + @Test fun aLostFirstBotChatReplyRecoversByItsOwnIntentAndKey() = run { + val r = rig() + r.host.loseReplyOnce("session.create", dropSocket = false) + val lost = r.repo.openBotChat("research", createIfMissing = true) + assertTrue("$lost", lost is BotChatOutcome.Unconfirmed) + val recovered = r.repo.openBotChat("research", createIfMissing = true) + assertTrue("$recovered", recovered is BotChatOutcome.Opened) + val keys = r.host.calls("session.create").map { it.params["idempotency_key"].asString } + assertEquals("The recovery re-sends under the first creation's own key", 2, keys.size) + assertEquals(keys[0], keys[1]) + assertEquals("The host kept one session for that key", 1, r.host.sessions.size) + } + + @Test fun anUnfinishedFirstBotChatNeverLocksTheAgentOutOfOrdinaryChats() = run { + val r = rig() + r.host.timeOutOnce("session.title", applyFirst = false) + val first = r.repo.openBotChat("research", createIfMissing = true) + assertTrue("$first", first is BotChatOutcome.Unconfirmed) + // The title never landed, so the registry has no Bot Chat; an ordinary New Chat is safe and works at once. + assertTrue(r.repo.createChat("research") is CreateOutcome.Created) + } + + @Test fun aTitleConflictWinnerIsAdoptedFromTheRegistry() = run { + val r = rig() + r.host.once("session.title") { + val winner = r.host.addSession("research", "winner-1") { addRow("user", "first") } + r.host.makeCanonical(winner) + throw app.bighelp.hermes.HermesException(app.bighelp.hermes.HermesException.Kind.RpcRejected, code = 4022) + } + val outcome = r.repo.openBotChat("research", createIfMissing = true) as BotChatOutcome.Opened + assertEquals("winner-1", outcome.ref.anchor) + assertEquals("The empty chat made for the failed attempt is dropped", 1, r.host.count("session.delete")) + } + + /** A store whose commits notice a cancelled caller, as one that does its I/O on another dispatcher does. */ + private class CancellationAwareStore : MemoryChatStore() { + override suspend fun commit(ops: List) { + kotlin.coroutines.coroutineContext.ensureActive() + super.commit(ops) + } + } + + @Test fun aCreateCancelledAfterTheFrameWasWrittenIsNotSwallowedAndKeepsItsIntent() = run { + val r = rig(store = CancellationAwareStore()) + val reached = kotlinx.coroutines.CompletableDeferred() + r.host.once("session.create") { _ -> reached.complete(Unit); kotlinx.coroutines.CompletableDeferred().await(); throw AssertionError("never answered") } + var returned: CreateOutcome? = null + val creating = r.scope.launch { returned = r.repo.createChat("research") } + reached.awaitWithin("session.create to be in flight") + creating.cancel() + creating.join() + assertNull("A cancelled create does not hand back an outcome", returned) + assertEquals("The frame may have reached the host, so the intent stays for a retry", 1, r.repo.pendingCreations.value.size) + assertNotNull(r.store.read(RecordKey.creation(host, "research"))) + + val key = r.host.calls("session.create").single().params["idempotency_key"].asString + val retry = r.repo.createChat("research", retryIntent = r.repo.pendingCreations.value.single().intentId) + assertTrue("$retry", retry is CreateOutcome.Created) + assertEquals("The retry carries the one key", listOf(key, key), r.host.calls("session.create").map { it.params["idempotency_key"].asString }) + } + + @Test fun aCreateCancelledBeforeTheFrameWasWrittenDropsItsIntentEverywhere() = run { + val r = rig(store = CancellationAwareStore()) + val hold = r.host.holdBeforeWrite("session.create") + var returned: CreateOutcome? = null + val creating = r.scope.launch { returned = r.repo.createChat("research") } + hold.reached.awaitWithin("session.create to be held") + creating.cancel() + creating.join() + assertNull("A cancelled create does not hand back an outcome", returned) + assertEquals(0, r.host.count("session.create")) + assertTrue(r.repo.pendingCreations.value.isEmpty()) + assertNull("Nothing was created, so no intent survives on disk to appear after a restart", r.store.read(RecordKey.creation(host, "research"))) + assertTrue("A new chat can be made", r.repo.createChat("research") is CreateOutcome.Created) + } + + @Test fun aChatCreatedOnASocketThatIsReplacedBeforeTheAnswerIsAppliedIsReattachedNotBoundToTheNewSocket() = run { + val r = rig() + r.host.once("session.create") { params -> + val answer = r.host.defaultHandle("session.create", params) + r.host.dropConnection() + r.host.newSocket() + answer + } + val ref = (r.repo.createChat("research") as CreateOutcome.Created).ref + r.awaitState(ref, "attached on the new socket") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals("The runtime of the old socket was not trusted on the new one: the chat resumed by its stored ID", 1, r.host.count("session.resume")) + assertTrue(r.repo.send(ref, "hello").let { it is SendResult.Admitted }) + } +} + +internal fun ChatRig.scopeOf(ref: ConversationRef) = ConversationScope(ChatTestData.host, ref.profile, ref.anchor) diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/EventOverflowTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/EventOverflowTest.kt new file mode 100644 index 00000000..19289718 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/EventOverflowTest.kt @@ -0,0 +1,92 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.CompletableDeferred +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The gateway drops the stream of a collector that falls too far behind, and the dropped events are gone. Every chat + * then has a hole in its transcript that no later event announces, so each must close admission and cover itself again. + */ +class EventOverflowTest : ChatTestBase() { + @Test fun anOverflowedEventStreamClosesEveryChatAndRecoversEachOneBeforeSendingAgain() = run { + val r = rig() + val first = r.savedChat(pairs = 1) + val second = r.newChat("scratch") + val gate = CompletableDeferred() + val reached = CompletableDeferred() + r.host.once("session.resume") { p -> reached.complete(Unit); gate.await(); r.host.defaultHandle("session.resume", p) } + val resumes = r.host.count("session.resume") + val activations = r.host.count("session.activate") + val since = r.host.count("session.events.since") + + r.host.overflowEvents() + reached.awaitWithin("the first chat to be attached again") + + // Nothing is shown as open while the holes are being covered, and nothing can be sent. + for (ref in listOf(first, second)) { + r.awaitState(ref, "admission closed") { it.sendBlock != null } + assertTrue(r.repo.send(ref, "into a hole") is SendResult.NotSent) + } + assertEquals(0, r.host.count("prompt.submit")) + + gate.complete(Unit) + for (ref in listOf(first, second)) r.awaitState(ref, "covered again") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals("Each chat was attached again by its stored ID", resumes + 2, r.host.count("session.resume")) + assertEquals("and ran its recovery bracket once", activations + 2, r.host.count("session.activate")) + assertEquals(since + 4, r.host.count("session.events.since")) + + // The new subscription carries events again. + val rt = r.runtimeOf(first) + r.host.emit(rt, "message.start") + r.host.emit(rt, "message.delta", """{"text":"after the overflow"}""") + r.host.flush() + r.eventually(message = "live events apply after the recovery") { + r.state(first).items.any { it is MessageItem && it.text == "after the overflow" } + } + assertTrue(r.repo.send(second, "now it is open") is SendResult.Admitted) + } + + @Test fun anOpenQuestionSurvivesAnOverflowBecauseItsSocketDid() = run { + val r = rig() + val ref = r.newChat() + val rt = r.runtimeOf(ref) + val params = """{"session_id":"${rt.id}","request_id":"domain-1","command":"ls","choices":["once","deny"]}""" + val asked = r.host.serverRequest(r.scope, "approval", params, id = "wire-1") + r.eventually(message = "prompt shown") { r.repo.prompts.value.any { it.wireId == "wire-1" } } + val resumes = r.host.count("session.resume") + + r.host.overflowEvents() + r.eventually(message = "the chat was attached again") { r.host.count("session.resume") == resumes + 1 } + r.awaitState(ref, "covered again") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + + assertTrue("The host is still waiting on that socket, so the question is still there", !asked.isCompleted) + val prompt = r.repo.prompts.value.single { it.wireId == "wire-1" } + assertEquals(PromptResult.Answered, r.repo.answerPrompt(prompt.id, PromptAnswer.Approve(ApprovalChoice.Once))) + assertEquals("once", ((asked.awaitWithin("the answer") as app.bighelp.hermes.ServerResponse.Result).value as kotlinx.serialization.json.JsonObject)["choice"].asString) + } + + @Test fun anAttachAlreadyUnderWayWhenEventsAreDroppedIsReplacedNotJoined() = run { + val r = rig() + val ref = r.savedChat(pairs = 1) + val reached = CompletableDeferred() + val gate = CompletableDeferred() + r.host.once("session.resume") { p -> reached.complete(Unit); gate.await(); r.host.defaultHandle("session.resume", p) } + val resumes = r.host.count("session.resume") + val activations = r.host.count("session.activate") + + r.host.dropConnection() + r.host.newSocket() + reached.awaitWithin("the socket's attach to reach session.resume") + // Events are dropped while that attach is still waiting: whatever it reads next cannot vouch for them. + r.host.overflowEvents() + r.eventually(message = "a second attach resumed the chat") { r.host.count("session.resume") == resumes + 2 } + gate.complete(Unit) + + r.awaitState(ref, "covered again") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + r.host.flush() + assertEquals("The held attach stood down; only the second one ran a recovery bracket", activations + 1, r.host.count("session.activate")) + assertTrue(r.repo.send(ref, "open again") is SendResult.Admitted) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt new file mode 100644 index 00000000..d63f7e7d --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt @@ -0,0 +1,662 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.ConnectionOwner +import app.bighelp.hermes.DispatchOutcome +import app.bighelp.hermes.RequestCancelledException +import app.bighelp.hermes.GatewayCapabilities +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.GatewayEvent +import app.bighelp.hermes.GatewaySocket +import app.bighelp.hermes.GatewayState +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.IncomingServerRequest +import app.bighelp.hermes.ServerRequestHandler +import app.bighelp.hermes.ServerResponse +import app.bighelp.hermes.WireMessage +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicLong +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * A scripted Hermes for the chat tests: a small model of the real host (profiles, stored sessions with physical + * history rows, runtimes with a replay ring, idempotent create) behind the same seams the repository uses. It is + * not Hermes; it follows the documented contract, including the facts that make the client's rules necessary: + * `prompt.submit` answers `streaming` (never `queued` for an idle chat) and the reply arrives later as events, + * a lost receipt still applies the mutation, and a compaction successor shows up only on resume or in history. + */ +internal class FakeHermesHost : ChatGateway, ChatRest { + /** [fence] is the socket generation the caller asked to be fenced to (null: not fenced). */ + class Recorded(val method: String, val params: JsonObject, val generation: Long, val fence: Long? = null) + class RestRecorded(val route: String, val query: List>) + + inner class Session(val id: String, val profile: String) { + var title = "" + var archived = false + var autoArchived = false + var hidden = false + var pinned = false + var cwd: String? = null + var source = "bighelp" + var model = "stub-model" + var provider = "stub-provider" + var reasoning = "medium" + var tier = "normal" + var startedAt = 1_792_000_000.0 + sessions.size + var lastActive = startedAt + var lineage: List? = null + var lineageRoot: String? = null + val rows = ArrayList() + + fun addRow(role: String, content: String?, extra: Map = emptyMap()): Long { + val rowId = nextRowId.getAndIncrement() + rows += buildJsonObject { + put("id", rowId); put("session_id", id); put("role", role) + put("content", content); put("timestamp", startedAt + rows.size) + extra.forEach { (k, v) -> put(k, v) } + } + lastActive = startedAt + rows.size + return rowId + } + } + + inner class Runtime(val id: String, var stored: String, val profile: String) { + var running = false + var seq = 0L + var lazy = true + val ring = ArrayList() + val openRequests = ArrayList() + var interruptRequested = false + val steers = ArrayList() + } + + // ---- connection + + private val nextRowId = AtomicLong(100) + var generation = 1L + private set + var exclusiveSubmit: Boolean? = true + var epoch = "epoch-1" + var heartbeat = true + + override val state: MutableStateFlow = MutableStateFlow(connectedState()) + @Volatile private var delivery = Channel(Channel.RENDEZVOUS) + override val events: Flow = flow { for (event in delivery) emit(event) } + + /** + * The collector fell too far behind: the stream the client is reading fails with the gateway's own overflow + * error (events are lost), and the next subscription starts on a fresh stream, as the real client's does. + */ + fun overflowEvents() { + val old = delivery + delivery = Channel(Channel.RENDEZVOUS) + old.close(HermesException(HermesException.Kind.TooManyRequests)) + } + + private fun owner(gen: Long) = ConnectionOwner("http://fake.test", "dashboard-session", gen) + + private fun connectedState(): GatewayState { + val ready = WireMessage.Event("gateway.ready", null, buildJsonObject { put("replay_epoch", epoch); put("heartbeat", heartbeat) }, null) + var socket = GatewaySocket.opening(owner(generation)).upgraded().receive(ready) + exclusiveSubmit?.let { socket = socket.discovered(GatewayCapabilities(it)) } + return GatewayState(GatewayConnection.Connected, generation, owner(generation), socket, epoch, heartbeat, null) + } + + /** The host's guarantee changes (for example it reports false): the current socket's capabilities are republished. */ + fun changeExclusiveSubmit(value: Boolean?) { + exclusiveSubmit = value + state.value = connectedState() + } + + /** The socket ends without an automatic recovery: the client is Idle and every pending request fails. */ + fun dropConnection() { + state.value = GatewayState(GatewayConnection.Idle, generation, null, null, null, false, + HermesException(HermesException.Kind.Disconnected)) + } + + /** A replacement socket becomes ready: a new generation, and `gateway.ready` is the first event on it. */ + suspend fun newSocket(newEpoch: String = epoch) { + generation += 1 + epoch = newEpoch + state.value = connectedState() + deliver(WireMessage.Event("gateway.ready", null, buildJsonObject { put("replay_epoch", epoch); put("heartbeat", heartbeat) }, null)) + // Return only once the client has fully processed the ready event (it closes admission synchronously there). + flush() + } + + // ---- recording and scripting + + val requests = CopyOnWriteArrayList() + val restRequests = CopyOnWriteArrayList() + fun calls(method: String) = requests.filter { it.method == method } + fun count(method: String) = calls(method).size + + private val overrides = HashMap JsonElement>>() + + /** Replaces the next call of [method] with [behavior]. It may call [defaultHandle] itself to apply the real effect first. */ + fun once(method: String, behavior: suspend (JsonObject) -> JsonElement) { + overrides.getOrPut(method) { ArrayDeque() }.addLast(behavior) + } + + fun rejectOnce(method: String, code: Long, reason: String? = null) = once(method) { + throw HermesException( + if (code == 4090L && reason == "MAX_CONCURRENT_SESSIONS") HermesException.Kind.ActiveSessionLimit else HermesException.Kind.RpcRejected, + code = code, reason = reason, + ) + } + + /** The host applies [method] and the connection dies before the receipt: the client sees an unknown outcome. */ + fun loseReplyOnce(method: String, dropSocket: Boolean = true) = once(method) { params -> + defaultHandle(method, params) + if (dropSocket) dropConnection() + throw HermesException(HermesException.Kind.Disconnected, outcomeUnknown = true) + } + + fun timeOutOnce(method: String, applyFirst: Boolean = true) = once(method) { params -> + if (applyFirst) defaultHandle(method, params) + throw HermesException(HermesException.Kind.TimedOut, outcomeUnknown = true) + } + + var rejectCwdExplicit = false + var ignoreRequestedModel = false + var failRest: ((String) -> Boolean)? = null + + // ---- model of the host + + val profiles = LinkedHashMap() + val sessions = LinkedHashMap() + val runtimes = LinkedHashMap() + private val idempotency = HashMap() + private val successors = HashMap() + private var counter = 0 + val canonicalIds = HashMap() + + init { + addProfile("research", "Research Bot") + addProfile("scratch") + } + + fun addProfile(name: String, display: String? = null) { + profiles[name] = buildJsonObject { put("name", name); if (display != null) put("display_name", display) } + } + + fun addSession(profile: String, id: String = "saved-${++counter}", title: String = "Chat $id", build: Session.() -> Unit = {}): Session = + Session(id, profile).also { it.title = title; it.build(); sessions[id] = it } + + /** Marks [session] as the profile's canonical Bot Chat (hidden from the list; named by the registry). */ + fun makeCanonical(session: Session) { + session.hidden = true + session.title = "Bot Chat" + canonicalIds[session.profile] = session.id + } + + /** The host compacts [oldId]: its transcript continues under [newId], and resume of the old ID resolves to the new one. */ + fun compact(oldId: String, newId: String) { + val old = sessions.getValue(oldId) + val next = addSession(old.profile, newId, old.title) { + rows += old.rows.map { JsonObject(it + ("session_id" to JsonPrimitive(newId))) } + lineageRoot = old.lineageRoot ?: oldId + lineage = (old.lineage ?: listOf(oldId)) + newId + } + old.archived = false + successors[oldId] = newId + runtimes.values.filter { it.stored == oldId }.forEach { it.stored = newId } + sessions.remove(oldId)?.also { sessions[oldId] = it } + next.lastActive = old.lastActive + } + + private fun tip(id: String): String { var t = id; while (successors.containsKey(t)) t = successors.getValue(t); return t } + + fun runtimeFor(stored: String): Runtime? = runtimes.values.lastOrNull { it.stored == tip(stored) } + + // ---- events + + private suspend fun deliver(event: WireMessage.Event, gen: Long = generation) { delivery.send(GatewayEvent(gen, event)) } + + /** Emits one runtime event with the next sequence number and keeps it in the replay ring. */ + suspend fun emit(runtime: Runtime, type: String, payload: String = "{}", gen: Long = generation) { + val params = emitParams(runtime, type, payload) + deliver(WireMessage.Event(type, runtime.id, params["payload"] as JsonObject, params["seq"].asLong, params), gen) + } + + /** Records an event as the host ring would, without delivering it (the client missed it). */ + fun emitSilently(runtime: Runtime, type: String, payload: String = "{}") { emitParams(runtime, type, payload) } + + private fun emitParams(runtime: Runtime, type: String, payload: String): JsonObject { + runtime.seq += 1 + val params = buildJsonObject { + put("type", type); put("session_id", runtime.id); put("seq", runtime.seq) + put("payload", jsonObject(payload)) + } + runtime.ring += params + return params + } + + /** Waits until the client has fully processed everything emitted before this call. */ + suspend fun flush() { + repeat(2) { deliver(WireMessage.Event("test.flush", null, JsonObject(emptyMap()), null)) } + } + + /** A complete streamed turn: start, deltas, final, row persistence, `running:false`. */ + suspend fun streamReply(runtime: Runtime, text: String, userRowId: Long? = null, deltas: List = listOf(text)) { + val session = sessions.getValue(runtime.stored) + runtime.running = true + emit(runtime, "message.start") + deltas.forEach { emit(runtime, "message.delta", """{"text":${JsonPrimitive(it)}}""") } + val assistant = session.addRow("assistant", text) + val payload = buildJsonObject { + put("text", text) + put("persisted_turn", buildJsonObject { userRowId?.let { put("user_row_id", it) }; put("final_assistant_row_id", assistant) }) + } + emit(runtime, "message.complete", payload.toString()) + runtime.running = false + emit(runtime, "session.info", """{"running":false}""") + } + + // ---- server requests + + val handlers = HashMap() + private val serverCounter = AtomicLong() + + /** The host asks the client something. The returned deferred completes with the client's response. */ + fun serverRequest(scope: CoroutineScope, method: String, params: String, id: String = "server-${serverCounter.incrementAndGet()}", gen: Long = generation): Deferred { + val handler = handlers[method] + return scope.async { + handler?.handle(IncomingServerRequest(gen, id, method, jsonObject(params))) + ?: ServerResponse.Failure(-32601, "Method not supported by this client") + } + } + + // ---- ChatGateway + + /** A request held before its frame is written: cancelling the caller then is cancelling an unsent request. */ + class Hold { val reached = CompletableDeferred(); val release = CompletableDeferred() } + private val writeHolds = HashMap>() + fun holdBeforeWrite(method: String): Hold = Hold().also { writeHolds.getOrPut(method) { ArrayDeque() }.addLast(it) } + + override suspend fun request(method: String, params: JsonObject, timeoutMillis: Long?, generation: Long?): JsonElement { + // Like the real client, a cancelled caller learns whether its frame had been handed to the socket. + var written = false + try { + writeHolds[method]?.removeFirstOrNull()?.let { it.reached.complete(Unit); it.release.await() } + val live = state.value + if (live.connection != GatewayConnection.Connected) throw HermesException(HermesException.Kind.NotConnected) + // The real client compares the fence with the socket it queues on: a mismatch writes nothing. + if (generation != null && live.generation != generation) throw HermesException(HermesException.Kind.NotConnected) + requests += Recorded(method, params, live.generation, generation) + written = true + overrides[method]?.removeFirstOrNull()?.let { return it(params) } + return defaultHandle(method, params) + } catch (e: CancellationException) { + if (e is RequestCancelledException) throw e + throw RequestCancelledException(if (written) DispatchOutcome.MayHaveBeenSent else DispatchOutcome.NotSent).also { it.initCause(e) } + } + } + + var admissionPreparations = 0 + var failNextAdmission: HermesException? = null + override suspend fun prepareForAdmission() { + admissionPreparations += 1 + failNextAdmission?.let { failNextAdmission = null; throw it } + if (state.value.connection != GatewayConnection.Connected) throw HermesException(HermesException.Kind.NotConnected) + } + + override suspend fun verifyLiveness() = Unit + override suspend fun reconnect(): GatewayState = state.value + val adopted = CopyOnWriteArrayList>() + override suspend fun adoptOpenRequests(rows: JsonElement, runtimeId: String, generation: Long) { adopted += Triple(rows, runtimeId, generation) } + override fun setServerRequestHandler(method: String, handler: ServerRequestHandler?) { + if (handler == null) handlers.remove(method) else handlers[method] = handler + } + + // ---- RPC behavior + + suspend fun defaultHandle(method: String, p: JsonObject): JsonElement = when (method) { + "gateway.ping", "client.capabilities" -> JsonObject(emptyMap()) + "profiles.list" -> buildJsonObject { + put("profiles", buildJsonArray { + profiles.values.forEach { row -> + val name = row["name"].asString!! + add(JsonObject(row + (canonicalIds[name]?.let { id -> + mapOf("canonical_session" to buildJsonObject { put("id", id); sessions[id]?.let { put("resolved_id", tip(id)) } }) + } ?: emptyMap()))) + } + }) + } + "session.create" -> create(p) + "session.resume" -> resume(p) + "session.activate" -> activate(p) + "session.events.since" -> eventsSince(p) + "prompt.submit" -> submit(p) + "session.steer" -> steer(p) + "session.interrupt" -> { runtime(p).interruptRequested = true; buildJsonObject { put("status", "interrupted") } } + "session.title" -> { + val rt = runtime(p) + val title = p["title"].asString!! + if (sessions.values.any { it.id != rt.stored && it.title == title && it.hidden && title == "Bot Chat" }) throw HermesException(HermesException.Kind.RpcRejected, code = 4022) + val session = sessions.getValue(rt.stored) + session.title = title + // A hidden chat titled "Bot Chat" becomes the profile's registry chat, as on the real host. + if (title == "Bot Chat" && session.hidden) canonicalIds.putIfAbsent(session.profile, session.id) + buildJsonObject { put("pending", false); put("title", title) } + } + "commands.catalog" -> commandCatalog + "slash.exec" -> slashExec(p) + "command.dispatch" -> dispatch(p) + "model.options" -> modelOptions(p) + "config.set" -> configSet(p) + "config.get" -> configGet(p) + "session.archive" -> archive(p, "archived") + "session.set_hidden" -> archive(p, "hidden") + "session.delete" -> delete(p) + "session.branch" -> branch(p) + "session.compress" -> buildJsonObject { put("status", "compressed"); put("removed", 4); put("before_tokens", 1000); put("after_tokens", 400) } + else -> throw HermesException(HermesException.Kind.RpcRejected, code = -32601) + } + + private fun runtime(p: JsonObject): Runtime { + val id = p["session_id"].asString ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + return runtimes[id] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4001) + } + + private fun info(rt: Runtime): JsonObject { + val s = sessions.getValue(rt.stored) + return buildJsonObject { + put("profile_name", rt.profile); put("stored_session_id", rt.stored); put("model", s.model); put("provider", s.provider) + put("reasoning_effort", s.reasoning); put("service_tier", s.tier); s.cwd?.let { put("cwd", it) }; put("lazy", rt.lazy) + } + } + + private var runtimeCounter = 0 + private fun nextRuntimeId() = "rt-${++runtimeCounter}" + private var createCounter = 0 + private fun create(p: JsonObject): JsonElement { + val profile = p["profile"].asString ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + if (!profiles.containsKey(profile)) throw HermesException(HermesException.Kind.RpcRejected, code = 4007) + if (p["source"].asString != "bighelp") throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + if (rejectCwdExplicit && p.containsKey("cwd_explicit")) throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + val key = p["idempotency_key"].asString + key?.let { existing -> idempotency[existing]?.let { stored -> return created(runtimes.values.last { it.stored == stored }, p) } } + val session = addSession(profile, "saved-c${++createCounter}", p["title"].asString ?: "") { + hidden = p["hidden"].asBool == true + cwd = p["cwd"].asString + if (!ignoreRequestedModel) p["model"].asString?.let { model = it } + p["provider"].asString?.let { provider = it } + p["reasoning_effort"].asString?.let { reasoning = it } + } + val rt = Runtime(nextRuntimeId(), session.id, profile).also { runtimes[it.id] = it } + key?.let { idempotency[it] = session.id } + return created(rt, p) + } + + private fun created(rt: Runtime, p: JsonObject) = buildJsonObject { + put("session_id", rt.id); put("stored_session_id", rt.stored); put("session_key", rt.stored) + put("message_count", 0); put("messages", JsonArray(emptyList())); put("running", false) + put("info", info(rt)) + } + + private fun resume(p: JsonObject): JsonElement { + val requested = p["session_id"].asString ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + if (p["source"].asString != "bighelp") throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + val stored = tip(requested) + val session = sessions[stored] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4007) + if (p["profile"].asString != session.profile) throw HermesException(HermesException.Kind.RpcRejected, code = 4007) + val rt = runtimes.values.lastOrNull { it.stored == stored } ?: Runtime(nextRuntimeId(), stored, session.profile).also { runtimes[it.id] = it } + return buildJsonObject { + put("session_id", rt.id); put("stored_session_id", stored); put("session_key", stored); put("resumed", stored) + put("running", rt.running); put("messages", JsonArray(emptyList())); put("messages_omitted", true) + put("info", info(rt)) + } + } + + private fun activate(p: JsonObject): JsonElement { + val rt = runtime(p) + return buildJsonObject { + put("session_id", rt.id); put("session_key", rt.stored); put("running", rt.running) + put("messages", JsonArray(emptyList())); put("messages_omitted", true); put("info", info(rt)) + put("pending_connection", JsonNull) + } + } + + var legacyPrompts = false + var truncateReplay = false + private fun eventsSince(p: JsonObject): JsonElement { + val id = p["session_id"].asString.orEmpty() + val last = p["last_seen"].asLong ?: 0 + if (id.isEmpty()) return buildJsonObject { + put("epoch", epoch); put("latest_seq", 0); put("truncated", false); put("count", 0) + put("events", JsonArray(emptyList())); put("open_requests", JsonArray(emptyList())) + } + val rt = runtimes[id] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4001) + return buildJsonObject { + put("epoch", epoch); put("latest_seq", rt.seq); put("truncated", truncateReplay) + put("events", JsonArray(if (truncateReplay) emptyList() else rt.ring.filter { it["seq"].asLong!! > last })) + if (!legacyPrompts) put("open_requests", JsonArray(rt.openRequests.toList())) + } + } + + var autoReply: String? = null + var beforeReceipt: (suspend (Runtime) -> Unit)? = null + private suspend fun submit(p: JsonObject): JsonElement { + val rt = runtime(p) + val session = sessions.getValue(rt.stored) + val text = p["text"].asString ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + if (rt.running) { + return if (p["queued"].asBool == true) buildJsonObject { put("status", "queued") } else buildJsonObject { put("status", "steered") } + } + val userRow = session.addRow("user", text) + rt.lazy = false + rt.running = true + beforeReceipt?.invoke(rt) + return buildJsonObject { put("status", "streaming"); put("user_row_id", userRow) } + } + + private fun steer(p: JsonObject): JsonElement { + val rt = runtime(p) + if (!rt.running) return buildJsonObject { put("status", "rejected") } + rt.steers += p["text"].asString.orEmpty() + return buildJsonObject { put("status", "queued") } + } + + val commandCatalog: JsonObject = jsonObject( + """{"pairs":[["/help","Show help"],["/plan","Plan first"],["/deploy-skill","Run the deploy skill"],["/model","Pick a model"]], + "canon":{"/h":"/help"},"skills":{"deploy-skill":{}}, + "categories":[{"name":"Plugin Commands","pairs":[["/model","Pick a model"]]}], + "commands":{"/plan":{"argument_mode":"text"}}}""", + ) + val slashOutputs = HashMap() + val dispatchResults = HashMap() + private suspend fun slashExec(p: JsonObject): JsonElement { + runtime(p) + val command = p["command"].asString.orEmpty() + val name = command.trim().removePrefix("/").substringBefore(' ').lowercase() + if (name == "deploy-skill") throw HermesException(HermesException.Kind.RpcRejected, code = 4018) + return slashOutputs[name] ?: buildJsonObject { put("output", "ran $name") } + } + + private suspend fun dispatch(p: JsonObject): JsonElement { + runtime(p) + val name = p["name"].asString.orEmpty() + return dispatchResults[name] ?: buildJsonObject { put("type", "skill"); put("message", "EXPANDED(${p["arg"].asString.orEmpty()})") } + } + + var modelOptionRows: JsonObject = jsonObject( + """{"model":"stub-model","providers":[{"slug":"stub-provider","name":"Stub","is_current":true,"models":["stub-model","big-model"]}, + {"slug":"other-provider","name":"Other","models":["other-model"]}]}""", + ) + private fun modelOptions(p: JsonObject): JsonElement = modelOptionRows + + var deferModelChange = false + var requireModelConfirmation = false + private fun configSet(p: JsonObject): JsonElement { + val rt = runtime(p) + val session = sessions.getValue(rt.stored) + val key = p["key"].asString + val value = p["value"].asString.orEmpty() + return when (key) { + "model" -> { + val model = value.substringBefore(" --provider ") + val provider = value.substringAfter(" --provider ").substringBefore(" --session") + if (requireModelConfirmation && p["confirm_expensive_model"].asBool != true) { + return buildJsonObject { put("key", "model"); put("scope", "session"); put("value", model); put("confirm_required", true); put("confirm_message", "That model is expensive. Continue?") } + } + if (!deferModelChange) { session.model = model; session.provider = provider } + buildJsonObject { + put("key", "model"); put("scope", "session"); put("value", model); put("confirm_required", false) + if (deferModelChange) put("deferred", true) + } + } + "reasoning" -> { session.reasoning = value; buildJsonObject { put("key", "reasoning"); put("value", value) } } + "fast" -> { session.tier = value; buildJsonObject { put("key", "fast"); put("value", value) } } + "yolo" -> buildJsonObject { put("key", "yolo"); put("value", if (value == "on") "1" else "0") } + else -> throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + } + } + + private fun configGet(p: JsonObject): JsonElement { + val session = sessions.getValue(runtime(p).stored) + val key = p["key"].asString + return buildJsonObject { + put("key", key) + put("value", when (key) { "reasoning" -> session.reasoning; "fast" -> session.tier; else -> "" }) + } + } + + private fun archive(p: JsonObject, field: String): JsonElement { + val id = p["session_id"].asString ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + val session = sessions[tip(id)] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4007) + val value = p[field].asBool ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + if (field == "archived") { session.archived = value; session.autoArchived = false } else session.hidden = value + return buildJsonObject { put(field, value); put("session_key", session.id) } + } + + private fun delete(p: JsonObject): JsonElement { + val id = p["session_id"].asString ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4000) + val session = sessions[id] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 4007) + if (runtimes.values.any { it.stored == session.id && it.running }) throw HermesException(HermesException.Kind.RpcRejected, code = 4009) + sessions.remove(id) + return buildJsonObject { put("deleted", id) } + } + + private fun branch(p: JsonObject): JsonElement { + val rt = runtime(p) + val parent = sessions.getValue(rt.stored) + val count = p["count"].asInt ?: parent.rows.size + val name = p["name"].asString ?: "${parent.title} · Fork" + val child = addSession(parent.profile, "saved-b${++counter}", name) { + // Like the real host, the child's rows are numbered afresh. + parent.rows.take(count).forEach { addRow(it["role"].asString!!, it["content"].asString) } + } + val childRuntime = Runtime(nextRuntimeId(), child.id, parent.profile).also { runtimes[it.id] = it } + return buildJsonObject { + put("session_id", childRuntime.id); put("stored_session_id", child.id); put("title", name); put("parent", parent.id) + put("message_count", count) + put("messages", buildJsonArray { + child.rows.forEach { row -> + add(buildJsonObject { put("role", row["role"].asString); put("text", row["content"].asString.orEmpty()); put("row_id", row["id"].asLong) }) + } + }) + put("info", JsonObject(info(childRuntime) + ("running" to JsonPrimitive(false)))) + } + } + + // ---- REST + + override suspend fun get(route: String, query: List>): JsonElement { + restRequests += RestRecorded(route, query) + if (failRest?.invoke(route) == true) throw HermesException(HermesException.Kind.ServerUnavailable) + fun q(name: String) = query.firstOrNull { it.first == name }?.second + val result = when { + route == "/api/sessions" -> listSessions(q("profile")!!, q("offset")!!.toInt(), q("limit")!!.toInt(), q("archived"), q("exclude_sources")) + route == "/api/sessions/search" -> search(q("profile")!!, q("q")!!, q("limit")!!.toInt()) + route.startsWith("/api/sessions/") && route.endsWith("/messages") -> messages(route.removePrefix("/api/sessions/").removeSuffix("/messages"), q("profile")!!, q("offset")!!.toInt(), q("limit")!!.toInt(), q("order")!!) + route.startsWith("/api/sessions/") -> detail(route.removePrefix("/api/sessions/"), q("profile")) + else -> throw HermesException(HermesException.Kind.InvalidResponse) + } + // The answer was fixed when the request arrived; a held read delivers that older picture late. + if (route.endsWith("/messages")) holdMessages?.await() + return result + } + + /** When set, history reads answer as if the rows belonged to this other session ID. */ + @Volatile var historySessionOverride: String? = null + + /** When set, history reads answer only after this completes (they keep the data they saw on arrival). */ + @Volatile var holdMessages: kotlinx.coroutines.CompletableDeferred? = null + + var legacyListEnvelope = false + private fun rowOf(s: Session) = buildJsonObject { + put("id", s.id); put("profile", s.profile); put("title", s.title); put("started_at", s.startedAt); put("last_active", s.lastActive) + put("message_count", s.rows.size); put("source", s.source); put("pinned", s.pinned) + if (s.archived) put("archived", true); if (s.autoArchived) put("auto_archived", true) + s.cwd?.let { put("cwd", it) } + s.lineageRoot?.let { put("_lineage_root_id", it) } + s.lineage?.let { ids -> put("_lineage_ids", buildJsonArray { ids.forEach { add(JsonPrimitive(it)) } }) } + put("preview", s.rows.firstOrNull { it["role"].asString == "user" }?.get("content").asString.orEmpty()) + } + + /** Profiles whose list answers 503, as a real profile with no session store yet does. */ + val unavailableLists = HashSet() + + private fun listSessions(profile: String, offset: Int, limit: Int, archived: String?, excluded: String?): JsonElement { + if (profile in unavailableLists) throw HermesException(HermesException.Kind.ServerUnavailable) + val hiddenSources = excluded?.split(',').orEmpty() + val all = sessions.values.filter { s -> + s.profile == profile && !s.hidden && s.source !in hiddenSources && tip(s.id) == s.id && + (archived == "include" || (archived == "only") == s.archived) + }.sortedByDescending { it.startedAt } + val page = all.drop(offset).take(limit) + return if (legacyListEnvelope) buildJsonObject { + put("sessions", buildJsonArray { page.forEach { add(rowOf(it)) } }); put("total", all.size); put("limit", limit); put("offset", offset) + } else buildJsonObject { + put("object", "list"); put("data", buildJsonArray { page.forEach { add(rowOf(it)) } }) + put("has_more", offset + page.size < all.size); put("limit", limit); put("offset", offset) + } + } + + private fun search(profile: String, needle: String, limit: Int): JsonElement = buildJsonObject { + put("results", buildJsonArray { + sessions.values.filter { it.profile == profile && !it.hidden && (it.title.contains(needle, true) || it.rows.any { r -> r["content"].asString.orEmpty().contains(needle, true) }) } + .take(limit).forEach { s -> + add(JsonObject(rowOf(s) + ("snippet" to JsonPrimitive(s.rows.firstOrNull { r -> r["content"].asString.orEmpty().contains(needle, true) }?.get("content").asString.orEmpty())))) + } + }) + } + + private fun messages(id: String, profile: String, offset: Int, limit: Int, order: String): JsonElement { + val stored = tip(id) + val session = sessions[stored] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 404) + if (session.profile != profile) throw HermesException(HermesException.Kind.RpcRejected, code = 404) + val ordered = session.rows + val page = if (order == "latest") ordered.reversed().drop(offset).take(limit).reversed() else ordered.drop(offset).take(limit) + val answerAs = historySessionOverride ?: stored + val rows = if (answerAs == stored) page else page.map { JsonObject(it + ("session_id" to JsonPrimitive(answerAs))) } + return historyEnvelope(rows, offset, limit, order, session = answerAs, profile = profile) + } + + private fun detail(id: String, profile: String?): JsonElement { + val s = sessions[tip(id)] ?: throw HermesException(HermesException.Kind.RpcRejected, code = 404) + return buildJsonObject { put("object", "hermes.session"); put("session", rowOf(s)) } + } + + // ---- convenience for tests + + /** Rows of a stored session as ids, for assertions. */ + fun rowIds(stored: String) = sessions.getValue(stored).rows.map { it["id"].asLong!! } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FileSnapshotChatStore.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FileSnapshotChatStore.kt new file mode 100644 index 00000000..a1cac327 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FileSnapshotChatStore.kt @@ -0,0 +1,78 @@ +package app.bighelp.hermes.chat + +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardCopyOption + +/** + * A reopenable, file-backed [ChatStore] for tests: every commit rewrites one snapshot file through a temp file + * and an atomic move, so a crash (or an injected failure) leaves either the old or the new snapshot, never a mix. + * A second instance over the same file is the "process restarted" store. Cache records are not persisted: + * a store may drop them at any time, and a reopen does. + */ +class FileSnapshotChatStore(private val file: File) : MemoryChatStore() { + /** When non-null the next commit fails with this and applies nothing (a full disk, a revoked directory). */ + @Volatile var failNextCommit: ChatStoreException? = null + + /** Commits that reached [beforeApply] successfully. */ + @Volatile var commits = 0 + private set + + init { + if (file.exists()) load() + } + + override fun beforeApply(ops: List) { + failNextCommit?.let { failNextCommit = null; throw it } + // Build the next snapshot first and write it; only after the move succeeds does memory change. + val next = LinkedHashMap(records.filterKeys { it.kind.durable }) + for (op in ops) when (op) { + is StoreOp.Put -> next[op.key] = op.bytes.copyOf() + is StoreOp.Delete -> next.remove(op.key) + } + write(next) + commits++ + } + + /** Drops every cache record, as a storage-pressure pass may. Durable records stay. */ + fun evictCaches() { + records.keys.removeAll { !it.kind.durable } + } + + private fun write(snapshot: Map) { + val temp = File(file.parentFile, file.name + ".tmp") + try { + DataOutputStream(temp.outputStream().buffered()).use { out -> + out.writeInt(snapshot.size) + for ((key, bytes) in snapshot) { + out.writeInt(key.kind.ordinal) + out.writeUTF(key.host.computerId); out.writeUTF(key.host.endpoint); out.writeUTF(key.host.principal) + for (part in listOf(key.profile, key.anchor, key.entry)) { + out.writeBoolean(part != null) + if (part != null) out.writeUTF(part) + } + out.writeInt(bytes.size); out.write(bytes) + } + } + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + } catch (e: IOException) { + temp.delete() + throw ChatStoreException(ChatStoreException.Kind.Unavailable, e) + } + } + + private fun load() { + DataInputStream(file.inputStream().buffered()).use { input -> + repeat(input.readInt()) { + val kind = RecordKind.entries[input.readInt()] + val host = HostScope(input.readUTF(), input.readUTF(), input.readUTF()) + val parts = List(3) { if (input.readBoolean()) input.readUTF() else null } + val bytes = ByteArray(input.readInt()).also { input.readFully(it) } + records[RecordKey.of(kind, host, parts[0], parts[1], parts[2])] = bytes + } + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatedChatStore.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatedChatStore.kt new file mode 100644 index 00000000..1d48f252 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatedChatStore.kt @@ -0,0 +1,27 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.CompletableDeferred + +/** + * A store whose next journal write waits for the test. It holds the sender between its ownership check and the + * request, which is the window in which the socket (or the caller) can change under it. + */ +internal class GatedChatStore : MemoryChatStore() { + @Volatile private var armed = false + val reached = CompletableDeferred() + private val release = CompletableDeferred() + + /** The next commit that writes a journal entry stops before it is applied. */ + fun holdNextJournalWrite() { armed = true } + + fun open() { release.complete(Unit) } + + override suspend fun commit(ops: List) { + if (armed && ops.any { it is StoreOp.Put && it.key.kind == RecordKind.Journal }) { + armed = false + reached.complete(Unit) + release.await() + } + super.commit(ops) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt new file mode 100644 index 00000000..c956bef9 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt @@ -0,0 +1,170 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.GatewayClient +import app.bighelp.hermes.GatewayTestSupport +import app.bighelp.hermes.ScriptedGateway +import app.bighelp.hermes.ScriptedHost +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The repository on the real [GatewayClient]: real WebSocket frames from a scripted loopback gateway. This shows + * what the in-memory fake cannot: that the handlers are registered before the first socket's advertisement, that + * server requests and their cancellation are matched by the transport, and that a lost receipt on a real socket + * is never resent across a reconnect. + */ +class GatewayChatIntegrationTest : GatewayTestSupport() { + private val chatScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val ref = ConversationRef("research", "saved-1") + private val dropOnSubmit = AtomicBoolean(false) + + @After fun stopChat() { chatScope.cancel() } + + private fun info(): String = """{"profile_name":"research","stored_session_id":"saved-1","model":"m","provider":"p","reasoning_effort":"medium","lazy":false}""" + + private fun wireUpHost() { + gateway.responder = { conn, frame -> + val id = frame["id"]?.jsonPrimitive?.content + when (frame["method"]?.jsonPrimitive?.content) { + "session.resume" -> conn.result(id!!, """{"session_id":"rt-live","stored_session_id":"saved-1","session_key":"saved-1","resumed":"saved-1","running":false,"messages":[],"messages_omitted":true,"info":${info()}}""") + "session.activate" -> conn.result(id!!, """{"session_id":"rt-live","session_key":"saved-1","running":false,"messages":[],"messages_omitted":true,"info":${info()}}""") + "session.events.since" -> conn.result(id!!, """{"epoch":"epoch-1","latest_seq":0,"truncated":false,"events":[],"open_requests":[]}""") + "prompt.submit" -> if (dropOnSubmit.get()) conn.drop() else conn.result(id!!, """{"status":"streaming","user_row_id":7}""") + else -> gateway.defaultResponse(conn, frame) + } + } + gateway.host.on("GET", "/api/sessions/saved-1/messages") { + ScriptedHost.json("""{"session_id":"saved-1","profile":"research","messages":[],"pagination":{"offset":0,"limit":200,"order":"latest","returned":0}}""") + } + } + + private suspend fun awaitUntil(message: String, timeoutMillis: Long = 8_000, condition: () -> Boolean) { + eventually(timeoutMillis, condition) + } + + private fun ScriptedGateway.Conn.responseTo(id: String): JsonObject? = + allFrames.map { Json.parseToJsonElement(it).jsonObject }.firstOrNull { it["method"] == null && it["id"]?.jsonPrimitive?.content == id } + + @Test fun aRepositoryBuiltBeforeConnectBacksTheFirstAdvertisementAndMatchesCancellationByIdAndMethod() = runBlocking { + wireUpHost() + val authenticator = authenticator() + val client = GatewayClient(authenticator, chatScope, fast) + val repo = HermesChatRepository(client, authenticator, chatScope, ChatTestData.host, MemoryChatStore()) + client.connect() + val conn = gateway.awaitConnection() + assertEquals("Handlers existed before the socket, so the host's first advertisement was honest", 1, conn.framesWithMethod("client.capabilities").size) + + repo.open(ref) + awaitUntil("ready") { repo.conversations.value[ref]?.phase == ConversationPhase.Ready && repo.conversations.value[ref]?.sendBlock == null } + + conn.send(ScriptedGateway.requestLine("wire-A", "approval", """{"session_id":"rt-live","request_id":"domain-1","choices":["once","deny"]}""")) + awaitUntil("prompt shown") { repo.prompts.value.size == 1 } + val prompt = repo.prompts.value.single() + assertEquals("wire-A", prompt.wireId) + assertEquals("domain-1", prompt.domainRequestId) + + // A cancel naming the right ID but another method retires nothing. + conn.event("request.cancel", """{"id":"wire-A","method":"clarify","reason":"expired"}""") + delay(300) + assertEquals(1, repo.prompts.value.size) + // Answering writes the response with the original wire ID, once. + assertEquals(PromptResult.Answered, repo.answerPrompt(prompt.id, PromptAnswer.Approve(ApprovalChoice.Once))) + awaitUntil("response written") { conn.responseTo("wire-A") != null } + assertEquals("""{"jsonrpc":"2.0","id":"wire-A","result":{"choice":"once","all":false}}""", conn.responseTo("wire-A").toString()) + + // The exact ID and method retire the prompt, and no response is ever written for it. + conn.send(ScriptedGateway.requestLine("wire-B", "approval", """{"session_id":"rt-live","request_id":"domain-2","choices":["once"]}""")) + awaitUntil("second prompt") { repo.prompts.value.size == 1 } + conn.event("request.cancel", """{"id":"wire-B","method":"approval","reason":"expired"}""") + awaitUntil("second prompt retired") { repo.prompts.value.isEmpty() } + delay(200) + assertEquals(null, conn.responseTo("wire-B")) + + // A request for a runtime this repository does not hold fails explicitly with -32602. + conn.send(ScriptedGateway.requestLine("wire-C", "approval", """{"session_id":"nobody","request_id":"d3","choices":["once"]}""")) + awaitUntil("explicit failure") { conn.responseTo("wire-C") != null } + assertEquals(-32602L, conn.responseTo("wire-C")!!["error"]!!.jsonObject["code"]!!.jsonPrimitive.content.toLong()) + // An unknown method is the transport's -32601. + conn.send(ScriptedGateway.requestLine("wire-D", "mcp.setup", """{"session_id":"rt-live"}""")) + awaitUntil("method not supported") { conn.responseTo("wire-D") != null } + assertEquals(-32601L, conn.responseTo("wire-D")!!["error"]!!.jsonObject["code"]!!.jsonPrimitive.content.toLong()) + repo.close() + client.disconnect() + } + + @Test fun aLostReceiptOnARealSocketIsUncertainAndNeverResentAcrossTheReconnect() = runBlocking { + wireUpHost() + val authenticator = authenticator() + val client = GatewayClient(authenticator, chatScope, fast) + val repo = HermesChatRepository(client, authenticator, chatScope, ChatTestData.host, MemoryChatStore()) + client.connect() + val first = gateway.awaitConnection() + repo.open(ref) + awaitUntil("ready") { repo.conversations.value[ref]?.sendBlock == null && repo.conversations.value[ref]?.phase == ConversationPhase.Ready } + + dropOnSubmit.set(true) + val result = repo.send(ref, "please do the thing") + assertTrue("$result", result is SendResult.Uncertain) + assertEquals("The journaled entry is the only record of it", 1, repo.conversations.value.getValue(ref).unresolved.size) + + // The client does not reconnect after an uncertain mutation; the owner asks, and nothing is replayed. + dropOnSubmit.set(false) + repo.reconnect() + val second = gateway.awaitConnection() + awaitUntil("reattached on the new socket") { repo.conversations.value[ref]?.phase == ConversationPhase.Ready && repo.conversations.value[ref]?.sendBlock == null } + val submits = (first.framesWithMethod("prompt.submit") + second.framesWithMethod("prompt.submit")) + assertEquals("Exactly one prompt.submit ever left the device", 1, submits.size) + assertEquals(1, second.framesWithMethod("session.resume").size) + assertEquals("The new socket advertised again with the handlers re-registered", 1, second.framesWithMethod("client.capabilities").size) + assertFalse(repo.conversations.value.getValue(ref).unresolved.isEmpty()) + repo.close() + client.disconnect() + } + + @Test fun aSocketReplacedDuringTheJournalWriteNeverCarriesTheOldRuntimeIdToTheNewSocket() = runBlocking { + wireUpHost() + val authenticator = authenticator() + val client = GatewayClient(authenticator, chatScope, fast) + val store = GatedChatStore() + val repo = HermesChatRepository(client, authenticator, chatScope, ChatTestData.host, store) + client.connect() + val first = gateway.awaitConnection() + repo.open(ref) + awaitUntil("ready") { repo.conversations.value[ref]?.phase == ConversationPhase.Ready && repo.conversations.value[ref]?.sendBlock == null } + + store.holdNextJournalWrite() + val sending = chatScope.async { repo.send(ref, "planned on socket one") } + store.reached.awaitWithin("the journal write to be held") + first.drop() + val second = gateway.awaitConnection() + awaitUntil("recovered on the new socket") { + second.framesWithMethod("session.activate").isNotEmpty() && + repo.conversations.value[ref]?.phase == ConversationPhase.Ready && repo.conversations.value[ref]?.sendBlock == null + } + store.open() + + val result = sending.await() + delay(300) + assertEquals("The old socket never saw the send either", 0, first.framesWithMethod("prompt.submit").size) + assertEquals("No frame naming the old runtime reached the new socket", 0, second.framesWithMethod("prompt.submit").size) + assertTrue("$result", result is SendResult.NotSent) + assertEquals("planned on socket one", repo.conversations.value.getValue(ref).draft) + repo.close() + client.disconnect() + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt new file mode 100644 index 00000000..ceafb791 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt @@ -0,0 +1,155 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.async +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class HistoryRepositoryTest : ChatTestBase() { + private val host = ChatTestData.host + + private fun ChatRig.rows(ref: ConversationRef) = state(ref).items.filterIsInstance() + + @Test fun openReadsTheNewestPhysicalPageWithTheDocumentedParametersAndOffersOlderRows() = run { + val r = rig(config = ChatConfig(turnLimit = 1)) + val ref = r.savedChat(pairs = 30) + val request = r.host.restRequests.last { it.route.endsWith("/messages") } + val q = request.query.toMap() + assertEquals("research", q["profile"]) + assertEquals("40", q["limit"]) + assertEquals("0", q["offset"]) + assertEquals("latest", q["order"]) + assertEquals("true", q["include_compacted"]) + val state = r.awaitState(ref) { it.items.size == 40 } + assertEquals("Rows keep the host's order", "question 10", (state.items.first() as MessageItem).text) + assertTrue(state.history.hasOlder) + assertEquals("Row IDs are the host's physical IDs", true, r.rows(ref).all { it.rowId != null && it.origin == ItemOrigin.Saved }) + } + + @Test fun olderPagesOverlapByOneRowAndStopAtTheStartOfTheChat() = run { + val r = rig(config = ChatConfig(turnLimit = 1)) + val ref = r.savedChat(pairs = 30) // 60 rows + r.awaitState(ref) { it.items.size == 40 } + val loaded = r.repo.loadOlder(ref) as HistoryLoad.Loaded + assertEquals(20, loaded.addedRows) + assertFalse(loaded.hasOlder) + val request = r.host.restRequests.last { it.route.endsWith("/messages") }.query.toMap() + assertEquals("One overlap row: offset - 1, limit + 1", "39", request["offset"]) + assertEquals("41", request["limit"]) + assertEquals(60, r.state(ref).items.size) + assertEquals((r.rows(ref).map { it.rowId }), r.rows(ref).map { it.rowId }.sortedBy { it!! }) + assertEquals(HistoryLoad.NothingOlder, r.repo.loadOlder(ref)) + } + + @Test fun aRewrittenOverlapRowRefusesTheMergeAndReloadsTheNewestPage() = run { + val r = rig(config = ChatConfig(turnLimit = 1)) + val ref = r.savedChat(pairs = 30) + r.awaitState(ref) { it.items.size == 40 } + val session = r.host.sessions.getValue(ref.anchor) + // The host rewrites the row the older page will overlap. + val index = session.rows.size - 40 + session.rows[index] = kotlinx.serialization.json.JsonObject(session.rows[index] + ("content" to kotlinx.serialization.json.JsonPrimitive("REWRITTEN"))) + val result = r.repo.loadOlder(ref) + assertEquals(ChatError.Kind.HistoryChanged, (result as HistoryLoad.Failed).error.kind) + r.awaitState(ref, "reloaded") { it.items.size == 40 && it.items.filterIsInstance().any { m -> m.text == "REWRITTEN" } } + assertFalse("Nothing from the failed older page was merged", r.rows(ref).any { it.text == "question 9" }) + } + + @Test fun aWindowThatDoesNotLineUpIsNeverCombined() = run { + val r = rig(config = ChatConfig(turnLimit = 1)) + val ref = r.savedChat(pairs = 30) + r.awaitState(ref) { it.items.size == 40 } + // The host answers the older page with a different session's ID (not in the chat's lineage): refused. + r.host.failRest = null + val other = r.host.addSession("research", "stranger") { repeat(60) { addRow("user", "x$it") } } + r.host.sessions.getValue(ref.anchor).rows.clear() + r.host.sessions.getValue(ref.anchor).rows += other.rows.map { kotlinx.serialization.json.JsonObject(it + ("session_id" to kotlinx.serialization.json.JsonPrimitive(ref.anchor))) } + val result = r.repo.loadOlder(ref) + assertTrue("$result", result is HistoryLoad.Failed) + } + + @Test fun aStaleCachedSeedIsReplacedByTheCanonicalPageNotDuplicatedOrMerged() = run { + val store = MemoryChatStore() + val host = FakeHermesHost() + val session = host.addSession("research", "s1") { addRow("user", "one"); addRow("assistant", "two"); addRow("user", "three"); addRow("assistant", "four") } + // A cache from earlier holds only the first two rows. + val cached = HistoryWindow.fresh(HistoryPage.parse(historyEnvelope(session.rows.take(2), 0, 40, "latest", session = "s1"), "research", 0, 40, "latest")) + val scope = ConversationScope(ChatTestData.host, "research", "s1") + store.putCache(RecordKey.history(scope), HistoryCacheCodec.encode(cached, scope)) + val r = rig(host = host, store = store) + val ref = ConversationRef("research", "s1") + r.repo.open(ref) + val state = r.awaitState(ref) { it.phase == ConversationPhase.Ready && it.items.size == 4 } + assertEquals(listOf("one", "two", "three", "four"), r.rows(ref).map { it.text }) + assertEquals(4, state.history.retainedRows) + } + + @Test fun savedHistoryNeverReplacesRicherLiveRowsAndTakesOverOnlyOnceItHasCaughtUp() = run { + val r = rig() + val ref = r.savedChat(pairs = 1) + assertTrue(r.repo.send(ref, "stream please") is SendResult.Admitted) + val rt = r.runtimeOf(ref) + r.host.emit(rt, "message.start") + r.host.emit(rt, "message.delta", """{"text":"partial answer"}""") + r.host.flush() + r.awaitState(ref) { s -> s.items.any { it is MessageItem && it.text == "partial answer" } } + // A history read while the turn runs cannot replace the live rows. + r.repo.reloadHistory(ref) + assertTrue(r.rows(ref).any { it.text == "partial answer" && it.origin == ItemOrigin.Live }) + + // The turn ends but the host has not persisted its reply yet: the live row is kept. + r.host.emit(rt, "message.complete", """{"text":"final answer"}""") + r.host.emit(rt, "session.info", """{"running":false}""") + r.host.flush() + r.eventually(message = "retired") { r.state(ref).unresolved.isEmpty() } + r.repo.reloadHistory(ref) + assertTrue("Saved history lacks the reply, so the live row stays", r.rows(ref).any { it.text == "final answer" }) + + // Once the host has saved it, the saved rows take over and nothing is shown twice. + r.host.sessions.getValue(rt.stored).addRow("assistant", "final answer") + r.repo.reloadHistory(ref) + r.eventually(message = "saved rows take over") { r.rows(ref).none { it.origin != ItemOrigin.Saved } } + assertEquals(1, r.rows(ref).count { it.text == "final answer" }) + } + + @Test fun aHistoryAnswerForAnUnrelatedSessionIsRefusedAndNeverRebindsTheChat() = run { + val r = rig() + val ref = r.savedChat(pairs = 2) + val tip = r.state(ref).identity.storedTip + r.host.historySessionOverride = "an-unrelated-session" + val failure = runCatching { r.repo.reloadHistory(ref) }.exceptionOrNull() as ChatException + assertEquals(ChatError.Kind.HistoryChanged, failure.error.kind) + assertEquals("The tip moved only on first-hand proof, never on a history read", tip, r.state(ref).identity.storedTip) + assertEquals(4, r.rows(ref).size) + } + + @Test fun aHistoryCacheFileOfAnotherConversationIsNeverShownAsThisOnes() = run { + val store = MemoryChatStore() + val hostA = FakeHermesHost().also { it.addSession("research", "chat-a") { addRow("user", "secret from chat A"); addRow("assistant", "reply A") } } + val first = rig(host = hostA, store = store) + val refA = ConversationRef("research", "chat-a") + first.repo.open(refA) + first.awaitState(refA) { it.phase == ConversationPhase.Ready && it.items.size == 2 } + val scopeA = ConversationScope(ChatTestData.host, "research", "chat-a") + first.eventually(message = "chat A's cache written") { store.read(RecordKey.history(scopeA)) != null } + val foreign = store.read(RecordKey.history(scopeA))!! + first.close() + + // A mis-addressed file: chat A's rows sit under chat B's key. + val hostB = FakeHermesHost().also { it.addSession("research", "chat-b") { addRow("user", "hello B"); addRow("assistant", "reply B") } } + val scopeB = ConversationScope(ChatTestData.host, "research", "chat-b") + store.putCache(RecordKey.history(scopeB), foreign) + val hold = kotlinx.coroutines.CompletableDeferred() + hostB.holdMessages = hold + val second = rig(host = hostB, store = store) + val refB = ConversationRef("research", "chat-b") + val opening = second.scope.async { second.repo.open(refB) } + second.awaitState(refB, "attached while the page read is held") { it.phase == ConversationPhase.Ready } + assertTrue("Chat A's text was shown in chat B", second.rows(refB).none { it.text.contains("secret from chat A") }) + hold.complete(Unit) + opening.await() + second.awaitState(refB) { it.items.size == 2 } + assertEquals(listOf("hello B", "reply B"), second.rows(refB).map { it.text }) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryTest.kt new file mode 100644 index 00000000..0da2ee29 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryTest.kt @@ -0,0 +1,223 @@ +package app.bighelp.hermes.chat + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import app.bighelp.hermes.HermesException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +internal fun json(text: String): JsonElement = Json.parseToJsonElement(text) +internal fun jsonObject(text: String): JsonObject = json(text) as JsonObject + +/** A history row as the host sends it. */ +internal fun historyRow(id: Long, role: String, content: String?, session: String = "saved-a", extra: String = ""): JsonObject = + jsonObject( + """{"id":$id,"session_id":"$session","role":"$role","content":${content?.let { Json.encodeToString(kotlinx.serialization.serializer(), it) } ?: "null"}$extra}""", + ) + +internal fun historyEnvelope(rows: List, offset: Int, limit: Int, order: String, session: String = "saved-a", profile: String? = "research", key: String = "messages"): JsonObject = + buildJsonObject { + put("session_id", session) + if (profile != null) put("profile", profile) + put(key, JsonArray(rows)) + put("pagination", buildJsonObject { put("offset", offset); put("limit", limit); put("order", order); put("returned", rows.size) }) + } + +class HistoryTest { + private fun parsed(vararg rows: JsonObject, offset: Int = 0, limit: Int = 40, order: String = "latest") = + HistoryPage.parse(historyEnvelope(rows.toList(), offset, limit, order), "research", offset, limit, order) + + private fun invalid(block: () -> Unit) { + val e = runCatching(block).exceptionOrNull() + assertTrue("Expected InvalidResponse but got $e", e is HermesException && e.kind == HermesException.Kind.InvalidResponse) + } + + @Test fun rowsNeedAStrictPositiveIdTheExactSessionAndARole() { + listOf(0L, -1L, 9_007_199_254_740_992L).forEach { bad -> invalid { HistoryRow.parse(historyRow(bad, "user", "x"), "saved-a") } } + invalid { HistoryRow.parse(jsonObject("""{"id":"7","session_id":"saved-a","role":"user","content":"x"}"""), "saved-a") } + invalid { HistoryRow.parse(jsonObject("""{"id":7.0,"session_id":"saved-a","role":"user","content":"x"}"""), "saved-a") } + invalid { HistoryRow.parse(historyRow(7, "user", "x", session = "other"), "saved-a") } + invalid { HistoryRow.parse(jsonObject("""{"id":7,"session_id":"saved-a","content":"x"}"""), "saved-a") } + assertEquals(9_007_199_254_740_991L, HistoryRow.parse(historyRow(9_007_199_254_740_991L, "user", "x"), "saved-a").id) + } + + @Test fun contentIsKeptRawStringArrayPartsJoinAndOtherPartsAreFlaggedNotInvented() { + assertEquals("verbatim text", HistoryRow.parse(historyRow(1, "user", "verbatim text"), "saved-a").text) + assertEquals("", HistoryRow.parse(historyRow(2, "assistant", null), "saved-a").text) + val parts = HistoryRow.parse(jsonObject( + """{"id":3,"session_id":"saved-a","role":"user","content":[{"type":"text","text":"a"},{"type":"input_image","image_url":"x"},{"type":"output_text","text":"b"}]}"""), "saved-a") + assertEquals("a\nb", parts.text) + assertTrue(parts.hasUnsupportedContent) + val number = HistoryRow.parse(jsonObject("""{"id":4,"session_id":"saved-a","role":"user","content":42}"""), "saved-a") + assertEquals("", number.text) + assertTrue(number.hasUnsupportedContent) + // display_content overrides what is rendered but the physical content is retained. + val shown = HistoryRow.parse(historyRow(5, "user", "raw wire text", extra = ""","display_content":"what the person typed""""), "saved-a") + assertEquals("what the person typed", shown.text) + assertEquals("raw wire text", (shown.content as kotlinx.serialization.json.JsonPrimitive).content) + } + + @Test fun hiddenAndInternalKindsAreNotVisibleAndReasoningAliasesAreRead() { + assertFalse(HistoryRow.parse(historyRow(1, "user", "x", extra = ""","display_kind":"hidden""""), "saved-a").isVisible) + assertFalse(HistoryRow.parse(historyRow(2, "user", "x", extra = ""","display_kind":"internal_notification""""), "saved-a").isVisible) + assertTrue(HistoryRow.parse(historyRow(3, "user", "x", extra = ""","display_kind":"model_switch""""), "saved-a").isVisible) + assertEquals("because", HistoryRow.parse(historyRow(4, "assistant", "y", extra = ""","reasoning":"because""""), "saved-a").reasoning) + assertEquals("first", HistoryRow.parse(historyRow(5, "assistant", "y", extra = ""","reasoning_content":"first","reasoning":"second""""), "saved-a").reasoning) + invalid { HistoryRow.parse(historyRow(6, "assistant", "y", extra = ""","reasoning":7"""), "saved-a") } + } + + @Test fun timestampsAreFiniteEpochSecondsAndABadDurationNeverHidesTheRow() { + assertEquals(1_792_000_000.5, HistoryRow.parse(historyRow(1, "user", "x", extra = ""","timestamp":1792000000.5"""), "saved-a").timestamp!!, 0.0) + invalid { HistoryRow.parse(historyRow(2, "user", "x", extra = ""","timestamp":-1"""), "saved-a") } + invalid { HistoryRow.parse(historyRow(3, "user", "x", extra = ""","timestamp":253402300800"""), "saved-a") } + assertNull(HistoryRow.parse(historyRow(4, "assistant", "x", extra = ""","turn_duration_ms":-5"""), "saved-a").turnDurationMillis) + assertEquals(1200, HistoryRow.parse(historyRow(5, "assistant", "x", extra = ""","turn_duration_ms":1200"""), "saved-a").turnDurationMillis) + } + + @Test fun aPageMustEchoOffsetLimitOrderAndReturnedExactly() { + val rows = listOf(historyRow(1, "user", "a"), historyRow(2, "assistant", "b")) + assertEquals(2, HistoryPage.parse(historyEnvelope(rows, 0, 40, "latest"), "research", 0, 40, "latest").rows.size) + invalid { HistoryPage.parse(historyEnvelope(rows, 5, 40, "latest"), "research", 0, 40, "latest") } + invalid { HistoryPage.parse(historyEnvelope(rows, 0, 41, "latest"), "research", 0, 40, "latest") } + invalid { HistoryPage.parse(historyEnvelope(rows, 0, 40, "oldest"), "research", 0, 40, "latest") } + invalid { HistoryPage.parse(historyEnvelope(rows, 0, 40, "latest", profile = "other"), "research", 0, 40, "latest") } + val liar = historyEnvelope(rows, 0, 40, "latest").let { JsonObject(it + ("pagination" to buildJsonObject { put("offset", 0); put("limit", 40); put("order", "latest"); put("returned", 3) })) } + invalid { HistoryPage.parse(liar, "research", 0, 40, "latest") } + // `data` is an accepted alias; a missing profile echo is allowed. + assertEquals(2, HistoryPage.parse(historyEnvelope(rows, 0, 40, "latest", profile = null, key = "data"), "research", 0, 40, "latest").rows.size) + // More rows than the limit are refused even when they are consistent with themselves. + val big = (1L..3L).map { historyRow(it, "user", "x") } + invalid { HistoryPage.parse(historyEnvelope(big, 0, 2, "latest"), "research", 0, 2, "latest") } + } + + @Test fun duplicatePhysicalRowIdsMeanTheHistoryMovedAndAreRefused() { + val dup = listOf(historyRow(1, "user", "a"), historyRow(1, "assistant", "b")) + val e = assertThrows(ChatException::class.java) { HistoryPage.parse(historyEnvelope(dup, 0, 40, "latest"), "research", 0, 40, "latest") } + assertEquals(ChatError.Kind.HistoryChanged, e.error.kind) + } + + private fun page(ids: LongRange, offset: Int = 0, limit: Int = 4, text: (Long) -> String = { "row $it" }) = + parsed(*ids.map { historyRow(it, if (it % 2 == 1L) "user" else "assistant", text(it)) }.toTypedArray(), offset = offset, limit = limit) + + @Test fun aFullFirstPageOffersAnOlderPageAndAShortOneDoesNot() { + assertEquals(4, HistoryWindow.fresh(page(7L..10L)).nextOffset) + assertNull(HistoryWindow.fresh(page(9L..10L)).nextOffset) + } + + @Test fun anOlderPageOverlapsTheOldestHeldRowByteForByteAndPrepends() { + val window = HistoryWindow.fresh(page(7L..10L)) + // offset - 1 with limit + 1: the page ends with the held oldest row. + val older = parsed(*(3L..7L).map { historyRow(it, "user", "row $it") }.toTypedArray(), offset = 3, limit = 5) + val merged = HistoryWindow.prepended(window, older) + assertEquals((3L..10L).toList(), merged.rows.map { it.id }) + assertEquals("A full older page offers another", 8, merged.nextOffset) + } + + @Test fun aShiftedOrRewrittenBoundaryIsRefusedNotMerged() { + val window = HistoryWindow.fresh(page(7L..10L)) + val rewritten = parsed(*(3L..7L).map { historyRow(it, "user", if (it == 7L) "EDITED" else "row $it") }.toTypedArray(), offset = 3, limit = 5) + assertEquals(ChatError.Kind.HistoryChanged, assertThrows(ChatException::class.java) { HistoryWindow.prepended(window, rewritten) }.error.kind) + val shifted = parsed(*(2L..6L).map { historyRow(it, "user", "row $it") }.toTypedArray(), offset = 3, limit = 5) + assertEquals(ChatError.Kind.HistoryChanged, assertThrows(ChatException::class.java) { HistoryWindow.prepended(window, shifted) }.error.kind) + val repeating = parsed(*(listOf(8L) + (4L..7L)).map { historyRow(it, "user", "row $it") }.toTypedArray(), offset = 3, limit = 5) + assertEquals(ChatError.Kind.HistoryChanged, assertThrows(ChatException::class.java) { HistoryWindow.prepended(window, repeating) }.error.kind) + } + + @Test fun aNewestPageRefreshKeepsEarlierHeldPagesWhenItLinesUpAndStartsOverWhenItDoesNot() { + val held = HistoryWindow.prepended(HistoryWindow.fresh(page(7L..10L)), + parsed(*(3L..7L).map { historyRow(it, "user", "row $it") }.toTypedArray(), offset = 3, limit = 5)) + // Two new rows arrived: the newest page now starts inside what is held and its prefix matches the held tail. + val refreshed = HistoryWindow.refreshed(held, page(9L..12L)) + assertEquals((3L..12L).toList(), refreshed.rows.map { it.id }) + // A page that does not start inside the held rows replaces the window. + val unrelated = HistoryWindow.refreshed(held, page(20L..23L)) + assertEquals((20L..23L).toList(), unrelated.rows.map { it.id }) + // A page whose boundary row changed is not aligned either. + val edited = HistoryWindow.refreshed(held, page(9L..12L) { if (it == 9L) "EDITED" else "row $it" }) + assertEquals((9L..12L).toList(), edited.rows.map { it.id }) + } + + @Test fun retainedHistoryIsCappedByRowsAndByBytes() { + val fat = "x".repeat(1_000_000) + val rows = (1L..34L).map { historyRow(it, "assistant", fat) }.toTypedArray() + val e = assertThrows(ChatException::class.java) { HistoryWindow.fresh(parsed(*rows, limit = 400)) } + assertEquals("34 MB of rows exceeds the 32 MiB retained read", ChatError.Kind.TooLarge, e.error.kind) + } + + @Test fun onlyFourWindowsAndSixtyFourMebibytesStayCached() { + val cache = HistoryWindowCache() + val refs = (1..5).map { ConversationRef("research", "a$it") } + refs.forEach { cache.put(it, HistoryWindow.fresh(page(1L..2L))) } + assertEquals(4, cache.size) + assertNull("The oldest window was evicted, with its paging offset", cache[refs[0]]) + assertTrue(cache[refs[4]] != null) + val fat = HistoryWindow.fresh(parsed(*(1L..30L).map { historyRow(it, "assistant", "y".repeat(1_000_000)) }.toTypedArray(), limit = 400)) + val roomy = HistoryWindowCache() + roomy.put(refs[0], fat); roomy.put(refs[1], fat); roomy.put(refs[2], fat) + assertTrue("Three 30 MB windows cannot all fit 64 MiB", roomy.size < 3) + } + + @Test fun theProjectionKeepsHostOrderJoinsOnlyUniqueToolCallsAndNeverInventsOutcomes() { + val rows = listOf( + historyRow(1, "user", "list the files"), + historyRow(2, "assistant", "", extra = ""","reasoning":"I will look","tool_calls":[{"id":"call-1","function":{"name":"ls","arguments":"{\"path\":\".\"}"}}]"""), + historyRow(3, "tool", "a.txt", extra = ""","tool_call_id":"call-1","tool_name":"ls""""), + historyRow(4, "assistant", "There is one file."), + ).map { HistoryRow.parse(it, "saved-a") } + val items = HistoryProjection.project(rows).items + assertEquals(listOf("row:1", "reasoning-row:2", "tool-row:2:0", "row:4"), items.map { it.id }) + val tool = items[2] as ActivityItem + assertEquals("ls", tool.title) + assertEquals("a.txt", tool.result) + assertEquals("""{"path":"."}""", tool.arguments) + assertEquals("History alone never says a tool succeeded", ActivityLifecycle.Recorded, tool.lifecycle) + assertEquals("call-1", tool.toolCallId) + assertEquals("turn:1", tool.turnId) + } + + @Test fun aDuplicateToolCallIdIsNotJoinedAndStaysSeparateEvidence() { + val rows = listOf( + historyRow(1, "assistant", "", extra = ""","tool_calls":[{"id":"dup","function":{"name":"a"}},{"id":"dup","function":{"name":"b"}}]"""), + historyRow(2, "tool", "r1", extra = ""","tool_call_id":"dup""""), + ).map { HistoryRow.parse(it, "saved-a") } + val items = HistoryProjection.project(rows).items.filterIsInstance() + assertEquals(listOf("tool-row:1:0", "tool-row:1:1", "tool-result-row:2"), items.map { it.id }) + assertTrue(items.take(2).all { it.result == null && it.toolCallId == null }) + } + + @Test fun modelSwitchRowsAreSystemMetadataUnknownRolesAreEvidenceAndHiddenRowsAreAbsent() { + val rows = listOf( + historyRow(1, "user", "[switched to model x]", extra = ""","display_kind":"model_switch""""), + historyRow(2, "user", "secret note", extra = ""","display_kind":"hidden""""), + historyRow(3, "narrator", "unusual"), + historyRow(4, "user", "hello", extra = ""","content":[{"type":"input_image"}]"""), + ).map { HistoryRow.parse(it, "saved-a") } + val project = HistoryProjection.project(rows) + val items = project.items.filterIsInstance() + assertEquals(listOf("row:1", "row:3"), items.take(2).map { it.id }) + assertEquals(MessageRole.System, items[0].role) + assertEquals(MessageRole.Unknown, items[1].role) + assertEquals("narrator", items[1].rawRole) + assertFalse(items.any { it.text == "secret note" }) + assertEquals(listOf(4L), project.unsupportedContentRowIds) + } + + @Test fun theMemoryContextHostAddsToAUserTurnIsNotShownAsThePersonsWords() { + val raw = "Fix the bug\n\nremembered: they like tea\n" + assertEquals("Fix the bug", UserMessageDisplay.text(raw)) + assertEquals("Fix it", UserMessageDisplay.text("Fix it\ncut off")) + assertEquals("@image:/tmp/a.png", UserMessageDisplay.text("[Image attached at: /tmp/a.png]\n[screenshot]\nWhat do you see in this image?")) + assertEquals("plain", UserMessageDisplay.text("plain")) + val projected = HistoryProjection.project(listOf(HistoryRow.parse(historyRow(1, "user", raw), "saved-a"))) + assertEquals("Fix the bug", (projected.items.single() as MessageItem).text) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/PromptRepositoryTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/PromptRepositoryTest.kt new file mode 100644 index 00000000..e38c56a6 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/PromptRepositoryTest.kt @@ -0,0 +1,216 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.ServerResponse +import java.io.File +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class PromptRepositoryTest : ChatTestBase() { + private suspend fun Deferred.response(): ServerResponse = withTimeout(5_000) { await() } + + private fun ServerResponse.result(): JsonObject = (this as ServerResponse.Result).value as JsonObject + + private fun ServerResponse.failureCode(): Long = (this as ServerResponse.Failure).code + + private suspend fun ChatRig.ask(ref: ConversationRef, method: String, params: String, id: String = "wire-1"): Deferred { + val runtime = runtimeOf(ref).id + val withSession = JsonObject(mapOf("session_id" to kotlinx.serialization.json.JsonPrimitive(runtime)) + jsonObject(params)).toString() + val deferred = host.serverRequest(scope, method, withSession, id) + eventually(message = "prompt shown or answered") { repo.prompts.value.any { it.wireId == id } || deferred.isCompleted } + return deferred + } + + @Test fun theHandlersAreRegisteredBeforeAnySocketAndAgainBeforeAReconnect() = run { + val r = rig() + assertEquals(setOf("approval", "clarify", "secret", "sudo", "vault.code", "vault.save_login", "vault.unlock_prompt"), r.host.handlers.keys) + r.host.handlers.clear() + r.repo.reconnect() + assertEquals("A connection that ended without recovery forgets handlers; the repository registers them again", 7, r.host.handlers.size) + // A method nobody can fulfil stays unregistered, so the gateway answers it with -32601. + assertFalse("mcp.setup" in r.host.handlers) + } + + @Test fun anApprovalIsBoundToTheConversationAndKeepsTheWireIdSeparateFromTheDomainRequestId() = run { + val r = rig() + val ref = r.newChat() + val deferred = r.ask(ref, "approval", """{"request_id":"approval-domain-a","command":"git status","description":"Inspect","tool_name":"terminal","choices":["once","session","always","deny","bogus","once"]}""", id = "server-approval-a") + val prompt = r.repo.prompts.value.single() + assertEquals("server-approval-a", prompt.wireId) + assertEquals("approval-domain-a", prompt.domainRequestId) + assertNotEquals(prompt.wireId, prompt.domainRequestId) + assertEquals(ref, prompt.ref) + val card = prompt.content as PromptContent.Approval + assertEquals("An unknown or repeated choice is skipped, not fatal", listOf(ApprovalChoice.Once, ApprovalChoice.Session, ApprovalChoice.Always, ApprovalChoice.Deny), card.choices) + assertEquals("git status", card.command) + assertEquals(listOf(prompt.id), r.state(ref).prompts.map { it.id }) + + assertEquals(PromptResult.Answered, r.repo.answerPrompt(prompt.id, PromptAnswer.Approve(ApprovalChoice.Session))) + val result = deferred.response().result() + assertEquals("session", result["choice"].asString) + assertEquals("Always the one scope offered, never a blanket", false, result["all"].asBool) + assertTrue(r.repo.prompts.value.isEmpty()) + assertEquals(PromptResult.NoLongerActive, r.repo.answerPrompt(prompt.id, PromptAnswer.Approve(ApprovalChoice.Once))) + } + + @Test fun anUnofferedChoiceIsInvalidAndLeavesThePromptActionableAndDeclineDenies() = run { + val r = rig() + val ref = r.newChat() + val deferred = r.ask(ref, "approval", """{"request_id":"d1","choices":["once","deny"]}""") + val prompt = r.repo.prompts.value.single() + assertTrue(r.repo.answerPrompt(prompt.id, PromptAnswer.Approve(ApprovalChoice.Always)) is PromptResult.Invalid) + assertEquals(1, r.repo.prompts.value.size) + assertEquals(PromptResult.Answered, r.repo.declinePrompt(prompt.id)) + val result = deferred.response().result() + assertEquals("deny", result["choice"].asString) + assertEquals(false, result["all"].asBool) + } + + @Test fun malformedAndUnboundRequestsFailExplicitlyAndNeverBecomeCards() = run { + val r = rig() + val ref = r.newChat() + assertEquals(-32602L, r.ask(ref, "approval", """{"choices":["once"]}""", "m1").response().failureCode()) + assertEquals(-32602L, r.ask(ref, "approval", """{"request_id":"x","choices":["unknown"]}""", "m2").response().failureCode()) + assertEquals(-32602L, r.ask(ref, "clarify", """{"question":"a","questions":[{"qid":"q","question":"b"}]}""", "m3").response().failureCode()) + assertEquals(-32602L, r.ask(ref, "sudo", """{"extra":1}""", "m4").response().failureCode()) + assertEquals(-32602L, r.ask(ref, "secret", """{"env_var":"K","prompt":"p","surprise":1}""", "m5").response().failureCode()) + val unbound = r.host.serverRequest(r.scope, "approval", """{"session_id":"runtime-nobody","request_id":"x","choices":["once"]}""", "m6") + assertEquals("A request for a runtime this repository does not hold is not actionable", -32602L, unbound.response().failureCode()) + assertTrue(r.repo.prompts.value.isEmpty()) + // A method with no handler is the gateway's -32601, never a card (the fake answers as the gateway would). + assertEquals(-32601L, r.host.serverRequest(r.scope, "mcp.setup", """{"session_id":"x"}""").response().failureCode()) + } + + @Test fun aSingleClarificationAnswersWithAnAnswerStringAndABatchKeepsLockedAnswers() = run { + val r = rig() + val ref = r.newChat() + val single = r.ask(ref, "clarify", """{"question":"Which environment?","choices":["Test","Production"],"multi_select":false}""", "c1") + val one = r.repo.prompts.value.single { it.wireId == "c1" } + val content = one.content as PromptContent.Clarification + assertFalse(content.isBatch) + assertEquals(PromptResult.Answered, r.repo.answerPrompt(one.id, PromptAnswer.Clarify(mapOf(PromptCenter.SINGLE to "Test")))) + assertEquals("Test", single.response().result()["answer"].asString) + + val batch = r.ask(ref, "clarify", """{"questions":[{"qid":"environment","question":"Which environment?","choices":["Test","Production"]},{"qid":"checks","question":"Which checks?","choices":["Unit","UI"],"multi_select":true}],"answers":{"environment":"Test"}}""", "c2") + val two = r.repo.prompts.value.single { it.wireId == "c2" } + val questions = (two.content as PromptContent.Clarification).questions + assertEquals("Test", questions[0].lockedAnswer) + // Missing the second answer: invalid, still actionable. + assertTrue(r.repo.answerPrompt(two.id, PromptAnswer.Clarify(emptyMap())) is PromptResult.Invalid) + // A multi-select answer is JSON array text, with at most one custom string. + assertTrue(r.repo.answerPrompt(two.id, PromptAnswer.Clarify(mapOf("checks" to """["Unit","Other","Another"]"""))) is PromptResult.Invalid) + assertEquals(PromptResult.Answered, r.repo.answerPrompt(two.id, PromptAnswer.Clarify(mapOf("checks" to """["Unit","UI"]""")))) + val answers = batch.response().result()["answers"] as JsonObject + assertEquals("Test", answers["environment"].asString) + assertEquals("""["Unit","UI"]""", answers["checks"].asString) + } + + @Test fun aSecureValueIsOneResponseNeverStoredAndClearedAfterUse() = run { + val store = MemoryChatStore() + val r = rig(store = store) + val ref = r.newChat() + val deferred = r.ask(ref, "secret", """{"env_var":"EXAMPLE_API_KEY","prompt":"Enter the key","metadata":{"source":"agent","label":"Service API key"}}""", "s1") + val prompt = r.repo.prompts.value.single() + val card = prompt.content as PromptContent.SecureInput + assertEquals(SecureKind.Secret, card.kind) + assertEquals("EXAMPLE_API_KEY", card.envVar) + assertEquals("Service API key", card.label) + assertTrue(card.isAgentRequest) + val secret = "synthetic-secret-value".toCharArray() + assertEquals(PromptResult.Answered, r.repo.answerPrompt(prompt.id, PromptAnswer.Secure(secret))) + assertEquals("synthetic-secret-value", deferred.response().result()["value"].asString) + assertTrue("The caller's array was cleared", secret.all { it == '\u0000' }) + assertTrue(r.repo.prompts.value.isEmpty()) + // A second answer is retired without replay, and its array is cleared too. + val again = "another-synthetic".toCharArray() + assertEquals(PromptResult.NoLongerActive, r.repo.answerPrompt(prompt.id, PromptAnswer.Secure(again))) + assertTrue(again.all { it == '\u0000' }) + // Nothing durable or observable ever held it. + val blob = r.store.keys(ChatTestData.host, RecordKind.Journal).size + r.store.keys(ChatTestData.host, RecordKind.Draft).size + assertEquals(0, blob) + assertFalse(r.state(ref).toString().contains("synthetic-secret-value") || r.repo.prompts.value.toString().contains("synthetic-secret-value")) + } + + @Test fun declineAndTheOtherSecureKindsRespondWithTheirDocumentedShapes() = run { + val r = rig() + val ref = r.newChat() + val sudo = r.ask(ref, "sudo", "{}", "u1") + r.repo.declinePrompt(r.repo.prompts.value.single { it.wireId == "u1" }.id) + assertEquals("", sudo.response().result()["value"].asString) + + val code = r.ask(ref, "vault.code", """{"site":"example.org","hint":"six digits"}""", "u2") + val codePrompt = r.repo.prompts.value.single { it.wireId == "u2" } + assertTrue(r.repo.answerPrompt(codePrompt.id, PromptAnswer.Secure("12 34-56 !".toCharArray())) is PromptResult.Invalid) + assertEquals(PromptResult.Answered, r.repo.answerPrompt(codePrompt.id, PromptAnswer.Secure("12 34-56".toCharArray()))) + assertEquals("123456", code.response().result()["value"].asString) + + val login = r.ask(ref, "vault.save_login", """{"origin":"https://example.org","site":"Example"}""", "u3") + val loginPrompt = r.repo.prompts.value.single { it.wireId == "u3" } + assertEquals("https://example.org", (loginPrompt.content as PromptContent.SecureInput).site) + assertEquals(PromptResult.Answered, r.repo.answerPrompt(loginPrompt.id, PromptAnswer.SaveLogin(" me@example.org ", "pw".toCharArray()))) + val saved = login.response().result()["value"].asString!! + assertEquals("""{"identifier":"me@example.org","password":"pw"}""", saved) + + val unlock = r.ask(ref, "vault.unlock_prompt", """{"backend":"keychain","display_name":""}""", "u4") + assertEquals("keychain", (r.repo.prompts.value.single { it.wireId == "u4" }.content as PromptContent.SecureInput).backendName) + r.repo.declinePrompt(r.repo.prompts.value.single { it.wireId == "u4" }.id) + assertEquals("", unlock.response().result()["value"].asString) + assertEquals(-32602L, r.ask(ref, "vault.save_login", """{"origin":"ftp://example.org","site":"x"}""", "u5").response().failureCode()) + } + + @Test fun aCancellationRetiresOnlyThePromptItNamesAndTheGatewayDecidesTheMatchByIdAndMethod() = run { + val r = rig() + val ref = r.newChat() + val first = r.ask(ref, "approval", """{"request_id":"d1","choices":["once"]}""", "dup") + val second = r.ask(ref, "clarify", """{"question":"Same wire id, other method?"}""", "dup") + r.eventually(message = "both prompts") { r.repo.prompts.value.size == 2 } + assertEquals("Two methods may share a wire ID bytes; they are two prompts", 2, r.repo.prompts.value.size) + // The gateway cancels exactly the handler whose ID and method match: here the clarify one. + second.cancel() + r.eventually(message = "clarify retired") { r.repo.prompts.value.size == 1 } + assertEquals("approval", r.repo.prompts.value.single().method) + assertFalse(first.isCompleted) + val remaining = r.repo.prompts.value.single() + assertEquals(PromptResult.Answered, r.repo.answerPrompt(remaining.id, PromptAnswer.Approve(ApprovalChoice.Once))) + } + + @Test fun promptsEndWithTheirSocketAndAreNeverRestoredFromAStoredResponse() = run { + val r = rig() + val ref = r.newChat() + val deferred = r.ask(ref, "approval", """{"request_id":"d1","choices":["once"]}""", "gone") + r.host.dropConnection() + r.eventually(message = "prompt retired with the socket") { r.repo.prompts.value.isEmpty() } + assertEquals("Retired: its response is an error that is never written", -32000L, deferred.response().failureCode()) + assertEquals(emptyList(), r.state(ref).prompts) + } + + @Test fun openRequestsOfTheFinalRecoveryAreRestoredThroughTheOrdinaryHandlerPath() = run { + val r = rig() + val ref = r.newChat() + val rt = r.runtimeOf(ref) + rt.openRequests += jsonObject("""{"id":"server-question-a","method":"clarify","params":{"session_id":"${rt.id}","question":"Continue?"}}""") + r.host.dropConnection() + r.host.newSocket() + r.awaitState(ref, "recovered") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + val adopted = r.host.adopted.last() + assertEquals(rt.id, adopted.second) + assertEquals("Adopted for the new socket generation", r.host.generation, adopted.third) + assertEquals(1, (adopted.first as kotlinx.serialization.json.JsonArray).size) + assertFalse(r.state(ref).legacyPromptHost) + } + + @Test fun aHostWithoutOpenRequestsIsMarkedLegacyAndOffersNoCards() = run { + val r = rig() + r.host.legacyPrompts = true + val ref = r.newChat() + assertTrue(r.state(ref).legacyPromptHost) + assertEquals("No adoption is attempted without the modern field", 0, r.host.adopted.size) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RealHostChatTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RealHostChatTest.kt new file mode 100644 index 00000000..673f189e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RealHostChatTest.kt @@ -0,0 +1,199 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.GatewayClient +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.HermesAuthenticator +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.InMemoryCredentialStore +import app.bighelp.hermes.OkHttpHermesHttp +import app.bighelp.hermes.SignInInput +import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.Timeout + +/** + * The repository against a real stock Hermes with a scripted local model (the disposable open host; no AI spend). + * Skipped unless `BIGHELP_E2E_CREDENTIALS` names the private credentials file, which is read at run time and never + * printed. Only the open host is used, so the password host's pending-authorization quota is untouched. + * + * This is protocol-level JVM evidence: not Android, not an emulator or device, not real inference. + */ +class RealHostChatTest { + @get:Rule val timeout: Timeout = Timeout.seconds(180) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val closeables = mutableListOf() + private val clients = mutableListOf() + private val repositories = mutableListOf() + private lateinit var origin: String + private lateinit var project: String + private val computer = ChatTestData.host.computerId + + @Before fun requireHost() { + val path = System.getenv("BIGHELP_E2E_CREDENTIALS") + assumeTrue("Set BIGHELP_E2E_CREDENTIALS to run against the disposable hosts", path != null && File(path).isFile) + val open = Json.parseToJsonElement(File(path!!).readText()).jsonObject["hosts"]!!.jsonObject["open"]!!.jsonObject + origin = open["proxy_origin"]!!.jsonPrimitive.content + project = open["project"]!!.jsonPrimitive.content + } + + @After fun cleanup() = runBlocking { + repositories.forEach { runCatching { it.close() } } + clients.forEach { runCatching { it.disconnect() } } + scope.cancel() + closeables.forEach { runCatching { it.close() } } + } + + /** One owner as the app builds it: authenticator, client, repository first, then connect. */ + private suspend fun owner(store: ChatStore = MemoryChatStore()): HermesChatRepository { + val endpoint = HermesEndpoint.parse(origin, allowPrivateHttp = true) + val authenticator = HermesAuthenticator(endpoint, OkHttpHermesHttp(endpoint), InMemoryCredentialStore()).also { closeables += it } + authenticator.signIn(SignInInput.Dashboard) + val client = GatewayClient(authenticator, scope).also { clients += it } + val host = HostScope(computer, endpoint.canonical, authenticator.savedConnection!!.principal) + val repo = HermesChatRepository(client, authenticator, scope, host, store).also { repositories += it } + assertEquals(GatewayConnection.Connected, client.connect().connection) + authenticator.commit() + return repo + } + + private suspend fun eventually(message: String, timeoutMillis: Long = 60_000, condition: () -> Boolean) { + try { withTimeout(timeoutMillis) { while (!condition()) delay(100) } } catch (e: kotlinx.coroutines.TimeoutCancellationException) { throw AssertionError("Timed out waiting for $message") } + } + + private suspend fun HermesChatRepository.newChat(title: String): ConversationRef { + val outcome = createChat("default", CreateRequest(cwd = project, title = title)) + val ref = (outcome as? CreateOutcome.Created)?.ref ?: throw AssertionError("create failed: $outcome") + eventually("ready") { conversations.value[ref]?.phase == ConversationPhase.Ready } + return ref + } + + private fun HermesChatRepository.texts(ref: ConversationRef) = conversations.value.getValue(ref).items.filterIsInstance().map { it.text } + + @Test fun createSendStreamPersistAndReopenOnAFreshSocketAgainstARealHost() = runBlocking { + val repo = owner() + val catalog = repo.refreshCatalog() + assertNull(catalog.error) + assertTrue(catalog.agents.map { it.id }.containsAll(listOf("default", "moss", "cobalt"))) + // A profile with no session store yet answers 503; that must not hide the others. + assertFalse("default" in catalog.agentErrors) + println("REAL-HOST catalog: agents=${catalog.agents.size} agentErrors=${catalog.agentErrors.mapValues { it.value.kind }}") + + val ref = repo.newChat("Synthetic repository check") + val result = repo.send(ref, "hello from the Android chat repository") + assertEquals(Admission.Streaming, (result as SendResult.Admitted).admission) + eventually("the owned terminal retires the journal entry") { repo.conversations.value.getValue(ref).unresolved.isEmpty() } + eventually("the final reply, once") { repo.texts(ref).count { it.contains("Direct streaming fixture complete.") } == 1 } + eventually("saved rows take over from the live ones") { + val items = repo.conversations.value.getValue(ref).items.filterIsInstance() + items.size == 2 && items.all { it.origin == ItemOrigin.Saved && it.rowId != null } + } + assertEquals("hello from the Android chat repository", repo.texts(ref).first()) + val state = repo.conversations.value.getValue(ref) + assertFalse(state.running) + assertNull(state.sendBlock) + println("REAL-HOST chat: legacyPromptHost=${state.legacyPromptHost} runtimeModelKnown=${state.runtime.model != null} items=${state.items.map { it::class.simpleName }}") + + // A second owner on a new socket opens the same stored chat: resume by stored ID, the recovery bracket, saved history. + val second = owner() + val reopened = second.open(ref) + eventually("reopened chat ready") { second.conversations.value[ref]?.phase == ConversationPhase.Ready && second.conversations.value[ref]?.sendBlock == null } + eventually("reopened history") { second.texts(ref).size == 2 } + assertEquals(repo.texts(ref), second.texts(ref)) + assertNull(second.conversations.value.getValue(ref).lastError) + println("REAL-HOST reopen: phase=${second.conversations.value.getValue(ref).phase} rows=${second.texts(ref).size} initialPhase=${reopened.phase}") + } + + @Test fun clarifyApprovalAndSecureInputReachTheRepositoryAndAreAnsweredOrDeclined() = runBlocking { + val repo = owner() + + val question = repo.newChat("Synthetic question") + assertTrue(repo.send(question, "question test") is SendResult.Admitted) + eventually("clarify prompt") { repo.prompts.value.any { it.method == "clarify" } } + val clarify = repo.prompts.value.first { it.method == "clarify" } + val questions = (clarify.content as PromptContent.Clarification).questions + assertEquals(PromptResult.Answered, repo.answerPrompt(clarify.id, PromptAnswer.Clarify(questions.associate { it.id to "Alpha" }))) + eventually("question turn ends") { repo.conversations.value.getValue(question).unresolved.isEmpty() && repo.prompts.value.isEmpty() } + + val approval = repo.newChat("Synthetic approval") + assertTrue(repo.send(approval, "approval test") is SendResult.Admitted) + eventually("approval prompt") { repo.prompts.value.any { it.method == "approval" } } + val card = repo.prompts.value.first { it.method == "approval" } + assertTrue((card.content as PromptContent.Approval).choices.contains(ApprovalChoice.Deny)) + assertTrue(card.domainRequestId != null && card.domainRequestId != card.wireId) + assertEquals(PromptResult.Answered, repo.declinePrompt(card.id)) + eventually("approval turn ends") { repo.conversations.value.getValue(approval).unresolved.isEmpty() && repo.prompts.value.isEmpty() } + assertTrue("The denied approval left the disposable directory in place", File(project, "approval-only-delete").isDirectory) + + // A numbered fixture no earlier run can have answered; it is declined, so nothing is ever stored. + val secure = repo.newChat("Synthetic secure input") + assertTrue(repo.send(secure, "secure input test 3") is SendResult.Admitted) + eventually("secure prompt") { repo.prompts.value.any { it.method == "secret" } } + val secret = repo.prompts.value.first { it.method == "secret" } + assertEquals("SECURE_INPUT_FIXTURE_3", (secret.content as PromptContent.SecureInput).envVar) + assertEquals(PromptResult.Answered, repo.declinePrompt(secret.id)) + eventually("secure turn ends") { repo.conversations.value.getValue(secure).unresolved.isEmpty() && repo.prompts.value.isEmpty() } + println("REAL-HOST prompts: clarify, approval and secret raised, answered over the wire; secret declined") + } + + @Test fun anActiveTurnSteersAndTheFinalReplyShowsTheCorrection() = runBlocking { + val repo = owner() + val ref = repo.newChat("Synthetic steer") + assertTrue(repo.send(ref, "long tool test") is SendResult.Admitted) + eventually("the turn is observed running") { repo.conversations.value.getValue(ref).running } + val steer = repo.send(ref, "A synthetic steer") + assertEquals(Admission.Steered, (steer as SendResult.Admitted).admission) + eventually("the turn ends and its entries retire") { !repo.conversations.value.getValue(ref).running && repo.conversations.value.getValue(ref).unresolved.isEmpty() } + eventually("the reply reflects the steer") { repo.texts(ref).any { it.contains("A synthetic steer") && it != "A synthetic steer" } } + } + + @Test fun renameArchiveRestoreForkSearchAndModelOptionsAgainstTheRealHost() = runBlocking { + val repo = owner() + val ref = repo.newChat("Synthetic edits") + assertTrue(repo.send(ref, "hello for the catalog") is SendResult.Admitted) + eventually("turn ends") { repo.conversations.value.getValue(ref).unresolved.isEmpty() && !repo.conversations.value.getValue(ref).running } + repo.refreshCatalog() + assertTrue(repo.catalog.value.sessions.any { it.ref == ref || it.storedId == ref.anchor }) + // Hermes keeps titles unique, so each run names its chat afresh. + val title = "Synthetic renamed ${java.util.UUID.randomUUID()}" + repo.rename(ref, title) + assertEquals(title, repo.conversations.value.getValue(ref).title) + val found = repo.search("default", "catalog") + println("REAL-HOST search: results=${found.size}") + val modelResult = runCatching { repo.modelOptions(ref) } + println("REAL-HOST modelOptions: ${modelResult.map { "ok providers=${it.providers.size}" }.getOrElse { "failed ${(it as? ChatException)?.error ?: it::class.simpleName}" }}") + repo.archive(ref) + assertTrue(repo.archivedChats().any { it.storedId == ref.anchor || it.ref == ref }) + repo.restore(ref) + assertTrue(repo.catalog.value.sessions.any { it.storedId == ref.anchor || it.ref == ref }) + + // Fork through the assistant's reply: the whole transcript is read, the host's count and messages are checked. + val through = repo.conversations.value.getValue(ref).items.filterIsInstance().last().rowId!! + val child = repo.fork(ref, through) + eventually("the fork is open") { repo.conversations.value[child]?.phase == ConversationPhase.Ready } + assertTrue(child.anchor != ref.anchor) + + // Hermes refuses to delete a chat that is open on its gateway; nothing is forgotten locally when it does. + val refused = runCatching { repo.delete(ref) }.exceptionOrNull() as ChatException + assertEquals(ChatError.Kind.Rejected, refused.error.kind) + println("REAL-HOST delete while open: code=${refused.error.code}") + assertTrue(repo.conversations.value[ref] != null) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RecoveryTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RecoveryTest.kt new file mode 100644 index 00000000..e1dc5b12 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RecoveryTest.kt @@ -0,0 +1,210 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.CompletableDeferred +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RecoveryTest : ChatTestBase() { + private fun ChatRig.messages(ref: ConversationRef) = state(ref).items.filterIsInstance() + + /** A sent message whose turn is running, with some text streamed (the client has seen sequence 2). */ + private suspend fun ChatRig.streaming(ref: ConversationRef, text: String = "Hello"): FakeHermesHost.Runtime { + assertTrue(repo.send(ref, "go") is SendResult.Admitted) + val rt = runtimeOf(ref) + host.emit(rt, "message.start") + host.emit(rt, "message.delta", """{"text":"$text"}""") + host.flush() + awaitState(ref) { s -> s.items.any { it is MessageItem && it.text == text } } + return rt + } + + @Test fun aNewSocketClosesAdmissionAtOnceThenResumesByStoredIdAndRecoversInTheDocumentedOrder() = run { + val r = rig() + val ref = r.savedChat() + val gate = CompletableDeferred() + r.host.once("session.resume") { p -> gate.await(); r.host.defaultHandle("session.resume", p) } + val before = r.host.requests.size + r.host.dropConnection() + r.host.newSocket() + r.host.flush() + // The socket is ready but the chat has no coverage yet: no send is admitted. + val blocked = r.state(ref) + assertTrue("Admission is closed while recovering: ${blocked.sendBlock}", blocked.sendBlock != null) + val refused = r.repo.send(ref, "too early") + assertTrue(refused is SendResult.NotSent) + assertEquals(0, r.host.count("prompt.submit")) + gate.complete(Unit) + r.awaitState(ref, "ready again") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + val after = r.host.requests.drop(before).map { it.method + "@" + it.generation } + assertEquals(listOf("session.resume@2", "session.events.since@2", "session.activate@2", "session.events.since@2"), after.filter { !it.startsWith("gateway") && !it.startsWith("client") }.take(4)) + assertEquals("Never a create as a reconnect fallback", 0, r.host.count("session.create")) + } + + @Test fun anExactReplayRestoresWhatWasMissedOnceAndSettlesAConfirmedAdmissionByItsOwnTerminal() = run { + val r = rig() + val ref = r.newChat() + val rt = r.streaming(ref) + assertEquals(1, r.state(ref).unresolved.size) + r.host.dropConnection() + // While away the host finished the turn; the client saw none of it. + r.host.emitSilently(rt, "message.delta", """{"text":" there"}""") + r.host.sessions.getValue(rt.stored).addRow("assistant", "Hello there") + r.host.emitSilently(rt, "message.complete", """{"text":"Hello there"}""") + rt.running = false + r.host.emitSilently(rt, "session.info", """{"running":false}""") + r.host.newSocket() + r.awaitState(ref, "recovered") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + r.eventually(message = "reply appears exactly once") { r.messages(ref).count { it.text == "Hello there" } == 1 } + assertEquals("The exact same-epoch terminal replay settles the admitted send", 0, r.state(ref).unresolved.size) + assertEquals(1, r.host.count("prompt.submit")) + } + + @Test fun anIdleSnapshotWithoutReplayCannotSettleASendWhoseAdmissionWasNeverConfirmed() = run { + val r = rig() + val ref = r.newChat() + r.host.loseReplyOnce("prompt.submit", dropSocket = true) + assertTrue(r.repo.send(ref, "maybe") is SendResult.Uncertain) + val rt = r.runtimeOf(ref) + rt.running = false // the host went idle without any evidence about our message + r.host.newSocket() + r.awaitState(ref) { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals("An idle snapshot is not proof either way", 1, r.state(ref).unresolved.size) + assertEquals(1, r.host.count("prompt.submit")) + } + + @Test fun aGapInTheLiveEventsKeepsAdmissionClosedInsteadOfGuessing() = run { + val r = rig() + val ref = r.newChat() + val rt = r.runtimeOf(ref) + r.host.dropConnection() + var tails = 0 + repeat(2) { + r.host.once("session.events.since") { p -> + val reply = r.host.defaultHandle("session.events.since", p) + if (++tails == 2) { + // A live event is lost (never delivered) and the next one arrives while the chat is catching up. + r.host.emitSilently(rt, "message.delta", """{"text":"lost"}""") + r.host.emit(rt, "message.delta", """{"text":"after the gap"}""") + // Wait until the client has taken the event in (held, because recovery is still running). + r.host.flush() + } + reply + } + } + r.host.newSocket() + val failed = r.awaitState(ref, "recovery refused the gap") { it.lastError != null } + assertTrue(failed.sendBlock != null) + assertTrue(failed.phase != ConversationPhase.Ready) + assertEquals(0, r.host.count("prompt.submit")) + assertFalse("Nothing from the uncovered span is shown", r.messages(ref).any { it.text.contains("after the gap") }) + // Opening again recovers from a clean cursor. + r.repo.open(ref) + r.awaitState(ref, "ready again") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + } + + @Test fun aChangedEpochKeepsTheRichRowsAndRestartsTheCursorFromTheFinalReplay() = run { + val r = rig() + val ref = r.newChat() + val rt = r.streaming(ref, "partial") + r.host.dropConnection() + r.host.newSocket("epoch-2") + r.awaitState(ref, "recovered") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals("The live row survives the epoch change", "partial", r.messages(ref).last { it.role == MessageRole.Assistant }.text) + // The cursor now follows the new epoch's sequence: the next event continues the same row. + r.host.emit(rt, "message.delta", """{"text":" more"}""") + r.host.flush() + r.eventually(message = "continued") { r.messages(ref).last { it.role == MessageRole.Assistant }.text == "partial more" } + } + + @Test fun eventsFromAnOlderSocketNeverApplyToANewerOne() = run { + val r = rig() + val ref = r.newChat() + val rt = r.streaming(ref) + r.host.dropConnection() + r.host.newSocket() + r.awaitState(ref) { it.phase == ConversationPhase.Ready && it.sendBlock == null } + r.host.emit(rt, "message.delta", """{"text":" STALE"}""", gen = 1) + r.host.flush() + assertFalse(r.messages(ref).any { it.text.contains("STALE") }) + } + + @Test fun aReapedRuntimeIsResumedByStoredIdAndItsCursorStartsOver() = run { + val r = rig() + val ref = r.newChat() + val old = r.streaming(ref) + r.host.dropConnection() + r.host.runtimes.remove(old.id) // Hermes reaped the app's runtime after the socket went + r.host.newSocket() + r.awaitState(ref, "reattached") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + val fresh = r.runtimeOf(ref) + assertNotEquals("A new runtime ID is a new coordinate", old.id, fresh.id) + r.host.emit(fresh, "message.start") + r.host.emit(fresh, "message.delta", """{"text":"new runtime"}""") + r.host.flush() + r.eventually(message = "events of the new runtime apply from sequence one") { r.messages(ref).any { it.text == "new runtime" } } + } + + @Test fun aReclaimRevokesTheWriterAtOnceButOnlyForTheExactOwner() = run { + val r = rig() + val ref = r.newChat() + val creates = r.host.count("session.create") + val rt = r.runtimeOf(ref) + val tip = r.state(ref).identity.storedTip + // Wrong stored ID, wrong outer session: not this chat. + r.host.emit(rt, "session.reclaimed", """{"session_id":"${rt.id}","stored_session_id":"someone-else","reason":"idle"}""") + r.host.flush() + assertEquals(ConversationPhase.Ready, r.state(ref).phase) + r.host.emit(rt, "session.reclaimed", """{"session_id":"${rt.id}","stored_session_id":"$tip","reason":"idle"}""") + r.host.flush() + val revoked = r.awaitState(ref) { it.phase == ConversationPhase.Suspended } + assertEquals(SendBlock.NoLiveSession, revoked.sendBlock) + assertEquals(ChatError.Kind.NotConnected, (r.repo.send(ref, "hi") as SendResult.NotSent).error.kind) + // Opening again reattaches by the stored ID. + r.repo.open(ref) + r.awaitState(ref, "reattached") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals(creates, r.host.count("session.create")) + } + + @Test fun aLostSocketSuspendsEveryChatAndKeepsTheirTranscripts() = run { + val r = rig() + val a = r.savedChat(pairs = 1) + val b = r.newChat("scratch") + val items = r.state(a).items + r.host.dropConnection() + r.eventually(message = "suspended") { r.state(a).phase == ConversationPhase.Suspended && r.state(b).phase == ConversationPhase.Suspended } + assertEquals(items, r.state(a).items) + assertEquals(SendBlock.NotConnected, r.state(a).sendBlock) + r.host.newSocket() + r.awaitState(a) { it.phase == ConversationPhase.Ready } + r.awaitState(b) { it.phase == ConversationPhase.Ready } + } + + @Test fun aLateFailureOfAnOldSocketsRecoveryNeverClosesAdmissionOfTheNewOwner() = run { + val r = rig() + val ref = r.newChat() + val gate = CompletableDeferred() + val entered = CompletableDeferred() + // The recovery that follows a lost send starts on socket 1 and stalls in its first replay request. + r.host.timeOutOnce("prompt.submit") + r.host.once("session.events.since") { _ -> + entered.complete(Unit) + gate.await() + throw app.bighelp.hermes.HermesException(app.bighelp.hermes.HermesException.Kind.TimedOut) + } + assertTrue(r.repo.send(ref, "stalls the old recovery") is SendResult.Uncertain) + entered.await() + r.host.dropConnection() + r.host.newSocket() + r.awaitState(ref, "ready on the new socket") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + gate.complete(Unit) // the old recovery now fails, late + kotlinx.coroutines.delay(400) + val state = r.state(ref) + assertEquals(ConversationPhase.Ready, state.phase) + assertEquals("The new owner is still open for input", null, state.sendBlock) + // Not just the published snapshot: admission itself is still open. + assertTrue(r.repo.send(ref, "the new owner still works") is SendResult.Admitted) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RuntimeControlsTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RuntimeControlsTest.kt new file mode 100644 index 00000000..868a0867 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RuntimeControlsTest.kt @@ -0,0 +1,156 @@ +package app.bighelp.hermes.chat + +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RuntimeControlsTest : ChatTestBase() { + private fun ChatRig.configSets() = host.calls("config.set").map { it.params } + + @Test fun optionsAreReadFromTheLiveRuntimeNotInferredAndCarryTheHostCatalog() = run { + val r = rig() + val ref = r.savedChat() + val options = r.repo.modelOptions(ref) + assertEquals("stub-model", options.model) + assertEquals("stub-provider", options.provider) + assertEquals("medium", options.reasoningEffort) + assertEquals(listOf("stub-provider", "other-provider"), options.providers.map { it.id }) + assertTrue(options.providers.first().isCurrent) + assertEquals(false, options.isFast) + assertEquals("The proof came from activation of this very runtime", r.runtimeOf(ref).id, r.host.calls("session.activate").last().params["session_id"].asString) + } + + @Test fun aModelChangeIsSessionScopedKeepsReasoningAndIsConfirmedByReadback() = run { + val r = rig() + val ref = r.savedChat() + val change = r.repo.setModel(ref, "big-model", "stub-provider") + assertEquals(ModelChange.Confirmed("big-model", "stub-provider"), change) + val sets = r.configSets() + val model = sets.first { it["key"].asString == "model" } + assertEquals("big-model --provider stub-provider --session", model["value"].asString) + assertEquals(r.runtimeOf(ref).id, model["session_id"].asString) + assertEquals("research", model["profile"].asString) + // The previous reasoning level is written back for this session only, then read back. + val reasoning = sets.first { it["key"].asString == "reasoning" } + assertEquals("medium", reasoning["value"].asString) + assertEquals("session", reasoning["scope"].asString) + assertEquals(1, r.host.calls("config.get").size) + // No call may touch a profile default: every config.set names this runtime. + assertTrue(sets.all { it["session_id"].asString == r.runtimeOf(ref).id }) + assertEquals("big-model", r.state(ref).runtime.model) + assertEquals("big-model", r.host.sessions.getValue(ref.anchor).model) + } + + @Test fun anAlreadyCurrentModelIsConfirmedWithoutAWrite() = run { + val r = rig() + val ref = r.savedChat() + assertEquals(ModelChange.Confirmed("stub-model", "stub-provider"), r.repo.setModel(ref, "stub-model", "stub-provider")) + assertEquals(0, r.host.count("config.set")) + } + + @Test fun aDeferredChangeIsNeverReportedAsChangedAndLeavesTheCurrentModelAlone() = run { + val r = rig() + val ref = r.savedChat() + r.host.deferModelChange = true + val change = r.repo.setModel(ref, "big-model", "stub-provider") + assertTrue(change is ModelChange.Deferred) + assertEquals("stub-model", r.host.sessions.getValue(ref.anchor).model) + assertEquals("No reasoning rewrite on an unconfirmed change", 1, r.configSets().size) + assertEquals("stub-model", r.repo.modelOptions(ref).model) + } + + @Test fun anExpensiveModelNeedsAnExplicitYesAndNothingChangedBeforeIt() = run { + val r = rig() + val ref = r.savedChat() + r.host.requireModelConfirmation = true + val first = r.repo.setModel(ref, "big-model", "stub-provider") + assertTrue(first is ModelChange.NeedsConfirmation) + assertEquals("stub-model", r.host.sessions.getValue(ref.anchor).model) + assertNull(r.configSets().first()["confirm_expensive_model"]) + val confirmed = r.repo.setModel(ref, "big-model", "stub-provider", confirmed = true) + assertEquals(ModelChange.Confirmed("big-model", "stub-provider"), confirmed) + assertEquals(true, r.configSets().last { it["key"].asString == "model" }["confirm_expensive_model"].asBool) + } + + @Test fun aHostThatReportsAnotherModelAfterTheChangeIsNotConfirmed() = run { + val r = rig() + val ref = r.savedChat() + r.host.once("config.set") { p -> + // The host accepts the call but the session keeps its model. + kotlinx.serialization.json.JsonObject(mapOf( + "key" to kotlinx.serialization.json.JsonPrimitive("model"), "scope" to kotlinx.serialization.json.JsonPrimitive("session"), + "value" to kotlinx.serialization.json.JsonPrimitive("big-model"), "confirm_required" to kotlinx.serialization.json.JsonPrimitive(false), + )) + } + assertThrowsChat(ChatError.Kind.ModelNotConfirmed) { r.repo.setModel(ref, "big-model", "stub-provider") } + assertEquals("stub-model", r.host.sessions.getValue(ref.anchor).model) + } + + @Test fun reasoningIsWrittenForTheSessionAndVerifiedByAReadBack() = run { + val r = rig() + val ref = r.savedChat() + r.repo.setReasoning(ref, "high") + val set = r.configSets().single() + assertEquals("reasoning", set["key"].asString) + assertEquals("high", set["value"].asString) + assertEquals("session", set["scope"].asString) + assertEquals(r.runtimeOf(ref).id, set["session_id"].asString) + assertEquals("high", r.state(ref).runtime.reasoningEffort) + assertThrowsChat(ChatError.Kind.InvalidInput) { r.repo.setReasoning(ref, "turbo") } + // A readback that disagrees is an unknown outcome. + r.host.once("config.get") { JsonObject(mapOf("key" to kotlinx.serialization.json.JsonPrimitive("reasoning"), "value" to kotlinx.serialization.json.JsonPrimitive("low"))) } + assertThrowsChat(ChatError.Kind.OutcomeUnknown) { r.repo.setReasoning(ref, "max") } + } + + @Test fun fastModeNeedsAnIdleRuntimeAndAModelTheHostSaysSupportsIt() = run { + val r = rig() + val ref = r.savedChat() + assertThrowsChat(ChatError.Kind.Unsupported) { r.repo.setFast(ref, true) } + assertEquals(0, r.host.count("config.set")) + r.host.modelOptionRows = jsonObject("""{"model":"stub-model","providers":[{"slug":"stub-provider","name":"Stub","is_current":true,"models":["stub-model"],"capabilities":{"stub-model":{"fast":true}}}]}""") + r.repo.setFast(ref, true) + val set = r.configSets().single() + assertEquals("fast", set["key"].asString) + assertEquals("fast", set["value"].asString) + assertEquals("session", set["scope"].asString) + assertEquals(true, r.repo.modelOptions(ref).isFast) + // A running turn blocks it. + assertTrue(r.repo.send(ref, "work") is SendResult.Admitted) + assertThrowsChat(ChatError.Kind.Conflict) { r.repo.setFast(ref, false) } + } + + @Test fun yoloIsConfirmedByTheHostsOneOrZero() = run { + val r = rig() + val ref = r.newChat() + r.repo.setYolo(ref, true) + val set = r.configSets().single() + assertEquals("yolo", set["key"].asString) + assertEquals("on", set["value"].asString) + assertEquals("session", set["scope"].asString) + r.host.once("config.set") { JsonObject(mapOf("key" to kotlinx.serialization.json.JsonPrimitive("yolo"), "value" to kotlinx.serialization.json.JsonPrimitive("1"))) } + assertThrowsChat(ChatError.Kind.OutcomeUnknown) { r.repo.setYolo(ref, false) } + } + + @Test fun aControlNeedsALiveRuntimeAndAnOwnerThatIsStillCurrent() = run { + val r = rig() + val ref = r.savedChat() + r.host.dropConnection() + r.eventually { r.state(ref).phase == ConversationPhase.Suspended } + assertThrowsChat(ChatError.Kind.NotConnected) { r.repo.setReasoning(ref, "high") } + assertEquals("Nothing was written", 0, r.host.count("config.set")) + r.host.newSocket() + r.awaitState(ref) { it.phase == ConversationPhase.Ready && it.sendBlock == null } + // The socket changes while the change is in flight: the late answer is not applied to the new owner. + r.host.once("config.set") { p -> + val reply = r.host.defaultHandle("config.set", p) + r.host.dropConnection() + r.host.newSocket() + reply + } + // The answer arrived on the replaced socket's watch: it is not applied (the new socket's own recovery reads the host's truth). + assertThrowsChat(ChatError.Kind.NotConnected) { r.repo.setReasoning(ref, "high") } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendCancellationTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendCancellationTest.kt new file mode 100644 index 00000000..19e8a5aa --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendCancellationTest.kt @@ -0,0 +1,109 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A screen-scoped caller of `send` is cancelled while its request is in flight (the person leaves the chat). Whatever + * stage the request had reached, the chat must come out usable: no stuck admission slot, no duplicate bubble, the text + * reviewable or back in the composer, and one recovery for a send that may have gone out. + */ +class SendCancellationTest : ChatTestBase() { + private val screens = ArrayList() + private fun screen() = CoroutineScope(Job() + Dispatchers.Default).also { screens += it } + @After fun leaveScreens() { screens.forEach { it.cancel() } } + + private fun ChatRig.localRows(ref: ConversationRef) = state(ref).items.filterIsInstance().filter { it.origin == ItemOrigin.Local } + + @Test fun cancellingASendAfterTheFrameWasWrittenKeepsTheEntryReviewableAndRunsOneRecovery() = run { + val r = rig() + val ref = r.newChat() + val reached = CompletableDeferred() + val never = CompletableDeferred() + r.host.once("prompt.submit") { _ -> reached.complete(Unit); never.await(); throw AssertionError("The receipt never comes") } + val activations = r.host.count("session.activate") + val sending = screen().async { r.repo.send(ref, "leave the screen") } + reached.awaitWithin("the receipt to be awaited") + r.eventually(message = "optimistic row shown") { r.localRows(ref).size == 1 } + + sending.cancel() + sending.join() + assertTrue("The caller's cancellation is passed on, not turned into a result", sending.isCancelled) + + val settled = r.awaitState(ref, "recovered after the cancelled send") { it.sendBlock == null && it.phase == ConversationPhase.Ready } + assertEquals("The entry is the only representation of the send", 1, settled.unresolved.size) + assertTrue("No duplicate optimistic bubble next to the entry", r.localRows(ref).isEmpty()) + assertEquals("Exactly one exact-owner recovery ran", activations + 1, r.host.count("session.activate")) + assertEquals("Nothing is ever resent", 1, r.host.count("prompt.submit")) + + val entry = settled.unresolved.single() + assertEquals("leave the screen", entry.composerText) + assertEquals(ReviewResult.Done, r.repo.resolveUnresolved(ref, entry.id, ReviewDecision.RestoreToComposer)) + assertEquals("leave the screen", r.state(ref).draft) + assertTrue(r.store.keys(ChatTestData.host, RecordKind.Journal, ref.profile, ref.anchor).isEmpty()) + assertTrue("A second send works", r.repo.send(ref, "again") is SendResult.Admitted) + } + + @Test fun cancellingASendBeforeTheFrameWasWrittenSendsNothingAndGivesTheTextBack() = run { + val r = rig() + val ref = r.newChat() + val hold = r.host.holdBeforeWrite("prompt.submit") + val sending = screen().async { r.repo.send(ref, "never leaves the phone") } + hold.reached.awaitWithin("the request to be held") + + sending.cancel() + sending.join() + assertTrue(sending.isCancelled) + + val settled = r.awaitState(ref, "slot freed") { it.sendBlock == null } + assertEquals("Nothing reached the host", 0, r.host.count("prompt.submit")) + assertTrue("The optimistic row is gone", r.localRows(ref).isEmpty()) + assertEquals("Nothing was sent, so the text is back where the person typed it", "never leaves the phone", settled.draft) + assertTrue(settled.unresolved.isEmpty()) + assertTrue(r.store.keys(ChatTestData.host, RecordKind.Journal, ref.profile, ref.anchor).isEmpty()) + assertTrue("A second send works", r.repo.send(ref, "again") is SendResult.Admitted) + } + + @Test fun anUnsentCancelledSendNeverOverwritesANewerDraftAndStaysReviewable() = run { + val r = rig() + val ref = r.newChat() + val hold = r.host.holdBeforeWrite("prompt.submit") + val sending = screen().async { r.repo.send(ref, "older words") } + hold.reached.awaitWithin("the request to be held") + r.repo.updateDraft(ref, "newer words") + + sending.cancel() + sending.join() + + val settled = r.awaitState(ref, "slot freed") { it.sendBlock == null } + assertEquals("newer words", settled.draft) + assertEquals("The unsent text is kept for review instead", "older words", settled.unresolved.single().composerText) + assertTrue(r.localRows(ref).isEmpty()) + assertEquals(0, r.host.count("prompt.submit")) + } + + @Test fun cancellingWhileTheJournalIsBeingWrittenFreesTheSlotAndSendsNothing() = run { + val store = GatedChatStore() + val r = rig(store = store) + val ref = r.newChat() + store.holdNextJournalWrite() + val sending = screen().async { r.repo.send(ref, "stalled disk") } + store.reached.awaitWithin("the journal write to be held") + + sending.cancel() + sending.join() + store.open() + + r.awaitState(ref, "slot freed") { it.sendBlock == null } + assertEquals(0, r.host.count("prompt.submit")) + assertTrue("A second send works", r.repo.send(ref, "again") is SendResult.Admitted) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt new file mode 100644 index 00000000..be596c28 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt @@ -0,0 +1,394 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import java.io.File +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SendFlowTest : ChatTestBase() { + private val hostScope = ChatTestData.host + + private suspend fun ChatRig.journalKeys(ref: ConversationRef) = store.keys(hostScope, RecordKind.Journal, ref.profile, ref.anchor) + + private fun ChatRig.messages(ref: ConversationRef) = state(ref).items.filterIsInstance() + + /** Starts a turn and makes the client observe it running (the reply is not finished). */ + private suspend fun ChatRig.startRunning(ref: ConversationRef, text: String = "go"): FakeHermesHost.Runtime { + assertTrue(repo.send(ref, text) is SendResult.Admitted) + val rt = runtimeOf(ref) + host.emit(rt, "message.start") + host.flush() + awaitState(ref, "running") { it.running } + return rt + } + + @Test fun theExactBytesAreJournaledBeforeDispatchAndTheStreamingReceiptStaysPendingUntilTheOwnedTerminal() = run { + val r = rig() + val ref = r.newChat() + var journaledDuringDispatch = -1 + r.host.once("prompt.submit") { params -> + journaledDuringDispatch = r.journalKeys(ref).size + r.host.defaultHandle("prompt.submit", params) + } + val result = r.repo.send(ref, "hello world") + assertEquals(Admission.Streaming, (result as SendResult.Admitted).admission) + assertEquals("The entry was on disk when the method was dispatched", 1, journaledDuringDispatch) + val sent = r.host.calls("prompt.submit").single().params + assertEquals("hello world", sent["text"].asString) + assertEquals(true, sent["queued"].asBool) + assertEquals("research", sent["profile"].asString) + assertEquals(r.runtimeOf(ref).id, sent["session_id"].asString) + assertEquals("The local UUID is never sent to Hermes", setOf("session_id", "profile", "text", "queued"), sent.keys) + + // The receipt proved admission only: the entry stays, and a second ordinary send is closed. + assertEquals(1, r.state(ref).unresolved.size) + assertEquals(SendBlock.PendingAdmission, r.state(ref).sendBlock) + + val rt = r.runtimeOf(ref) + val userRow = r.host.sessions.getValue(rt.stored).rows.last()["id"].asLong!! + r.host.emit(rt, "message.start") + r.host.emit(rt, "message.delta", """{"text":"Hi "}""") + r.host.emit(rt, "message.delta", """{"text":"there."}""") + val assistant = r.host.sessions.getValue(rt.stored).addRow("assistant", "Hi there.") + r.host.emit(rt, "message.complete", """{"text":"Hi there.","persisted_turn":{"user_row_id":$userRow,"final_assistant_row_id":$assistant}}""") + r.host.flush() + val mid = r.awaitState(ref) { it.items.any { item -> item is MessageItem && item.text == "Hi there." } } + assertEquals("A segment final is not the end of the turn: the entry is still held", 1, mid.unresolved.size) + assertTrue(mid.running) + + r.host.emit(rt, "session.info", """{"running":false}""") + r.host.flush() + r.eventually(message = "entry retired at the terminal") { r.state(ref).unresolved.isEmpty() && r.journalKeys(ref).isEmpty() } + // The submit's return value is never appended as a second reply; saved history takes over from the live rows. + r.eventually(message = "history caught up") { r.messages(ref).all { it.origin == ItemOrigin.Saved } && r.messages(ref).size == 2 } + assertEquals(listOf("hello world", "Hi there."), r.messages(ref).map { it.text }) + assertNull(r.state(ref).sendBlock) + } + + @Test fun aFailedJournalWriteSendsNothingAndLeavesTheComposerAlone() = run { + val store = FileSnapshotChatStore(File(directory, "s.bin")) + val r = rig(store = store) + val ref = r.newChat() + r.repo.updateDraft(ref, "important words") + store.failNextCommit = ChatStoreException(ChatStoreException.Kind.QuotaExceeded) + val result = r.repo.send(ref, "important words") + assertEquals(ChatError.Kind.PersistenceFailed, (result as SendResult.NotSent).error.kind) + assertEquals("Nothing reached the socket", 0, r.host.count("prompt.submit")) + assertEquals("important words", r.state(ref).draft) + assertNull("The slot is free again", r.state(ref).sendBlock) + assertTrue(r.repo.send(ref, "important words") is SendResult.Admitted) + } + + @Test fun eventsThatBeatTheReceiptStillSettleTheRightTurn() = run { + val r = rig() + val ref = r.newChat() + r.host.beforeReceipt = { rt -> + r.host.emit(rt, "message.start") + r.host.emit(rt, "message.delta", """{"text":"early"}""") + r.host.flush() + } + assertTrue(r.repo.send(ref, "hi") is SendResult.Admitted) + val rt = r.runtimeOf(ref) + assertEquals("early", r.messages(ref).last { it.role == MessageRole.Assistant }.text) + assertEquals(1, r.state(ref).unresolved.size) + r.host.emit(rt, "session.info", """{"running":false}""") + r.host.flush() + r.eventually(message = "retired") { r.state(ref).unresolved.isEmpty() } + } + + @Test fun twoOverlappingStartsKeepTheEntryForReviewInsteadOfGuessingWhichTurnWasOurs() = run { + val r = rig() + val ref = r.newChat() + r.host.beforeReceipt = { rt -> + r.host.emit(rt, "message.start") + r.host.emit(rt, "session.info", """{"running":false}""") + r.host.emit(rt, "message.start") + r.host.flush() + } + assertTrue(r.repo.send(ref, "hi") is SendResult.Admitted) + val rt = r.runtimeOf(ref) + r.host.emit(rt, "session.info", """{"running":false}""") + r.host.flush() + r.eventually(message = "recovery after the ambiguous overlap") { r.state(ref).sendBlock == null } + assertEquals("Ambiguous: the entry is kept, not retired by a stranger's final", 1, r.state(ref).unresolved.size) + } + + @Test fun aSendWhileATurnRunsSteersByDefaultAndQueueUsesThePromptSubmitPath() = run { + val r = rig() + val ref = r.newChat() + val rt = r.startRunning(ref) + val steer = r.repo.send(ref, "also check the tests") + assertEquals(Admission.Steered, (steer as SendResult.Admitted).admission) + val steerCall = r.host.calls("session.steer").single().params + assertEquals("also check the tests", steerCall["text"].asString) + assertEquals(rt.id, steerCall["session_id"].asString) + assertEquals(listOf("also check the tests"), rt.steers) + r.eventually(message = "steer receipt retired its entry") { r.state(ref).unresolved.size == 1 } + + val queued = r.repo.send(ref, "then this", mode = SendMode.Queue) + assertEquals(Admission.Queued, (queued as SendResult.Admitted).admission) + val queueCall = r.host.calls("prompt.submit").last().params + assertEquals("then this", queueCall["text"].asString) + assertEquals(true, queueCall["queued"].asBool) + assertEquals(1, r.host.count("session.steer")) + } + + @Test fun steerNeedsAnObservedRunningTurnAndNeverBecomesANewOne() = run { + val r = rig() + val ref = r.newChat() + val result = r.repo.send(ref, "late correction", mode = SendMode.Steer) + assertEquals(ChatError.Kind.NoActiveTurn, (result as SendResult.NotSent).error.kind) + assertEquals(0, r.host.count("session.steer") + r.host.count("prompt.submit")) + assertTrue(r.journalKeys(ref).isEmpty()) + } + + @Test fun aRejectedSteerIsADefiniteRefusalAndTheTextComesBack() = run { + val r = rig() + val ref = r.newChat() + r.startRunning(ref) + r.host.once("session.steer") { buildJsonObject { put("status", "rejected") } } + val result = r.repo.send(ref, "nope") + assertTrue(result is SendResult.Refused) + assertEquals("nope", r.state(ref).draft) + assertEquals("Only the first send's entry remains", 1, r.state(ref).unresolved.size) + } + + @Test fun stopNeedsTheInterruptedReceiptAndTheTurnEndsOnlyWhenTheHostSaysSo() = run { + val r = rig() + val ref = r.newChat() + val rt = r.startRunning(ref) + assertEquals(StopResult.Requested, r.repo.stop(ref)) + assertTrue(r.host.runtimes.getValue(rt.id).interruptRequested) + val stopped = r.awaitState(ref) { it.stopRequested } + assertTrue("Still running until running:false arrives", stopped.running) + r.host.emit(rt, "session.info", """{"running":false}""") + r.host.flush() + val ended = r.awaitState(ref) { !it.running } + assertFalse(ended.stopRequested) + + r.startRunning(ref, "again") + r.host.once("session.interrupt") { buildJsonObject { put("status", "nothing") } } + assertTrue(r.repo.stop(ref) is StopResult.Uncertain) + } + + @Test fun interruptAndSendQueuesOnlyAfterTheStopReceiptAndNeverRetriesALostStop() = run { + val r = rig() + val ref = r.newChat() + r.startRunning(ref) + var methodWhenQueued: String? = null + r.host.once("prompt.submit") { params -> + methodWhenQueued = r.journalKeys(ref).map { key -> JournalEntry.decode(r.scopeOf(ref), key.entry!!, r.store.read(key)!!) } + .single { it.text == "replace the plan" }.method + r.host.defaultHandle("prompt.submit", params) + } + val done = r.repo.send(ref, "replace the plan", mode = SendMode.InterruptAndSend) + assertTrue(done is SendResult.Admitted) + assertEquals(listOf("session.interrupt", "prompt.submit"), r.host.requests.map { it.method }.filter { it == "session.interrupt" || it == "prompt.submit" }.takeLast(2)) + assertEquals("The journal's method moved to prompt.submit before it was sent", "prompt.submit", methodWhenQueued) + + // A lost stop receipt stops the sequence: the message is not queued and nothing is retried. + val other = r.newChat("scratch") + r.startRunning(other, "work") + r.host.timeOutOnce("session.interrupt") + val submitsBefore = r.host.count("prompt.submit") + val lost = r.repo.send(other, "next", mode = SendMode.InterruptAndSend) + assertTrue(lost is SendResult.Uncertain) + assertEquals(submitsBefore, r.host.count("prompt.submit")) + assertEquals("session.interrupt", r.state(other).unresolved.single { it.composerText == "next" }.method) + } + + @Test fun aLostReceiptKeepsTheEntryNeverResendsAndTheReplyStillArrives() = run { + val r = rig() + val ref = r.newChat() + r.host.loseReplyOnce("prompt.submit", dropSocket = true) + val result = r.repo.send(ref, "please help") + val entryId = (result as SendResult.Uncertain).entryId + assertEquals(1, r.state(ref).unresolved.size) + + r.host.newSocket() + r.awaitState(ref, "recovered after reconnect") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + val rt = r.runtimeOf(ref) + r.host.streamReply(rt, "Of course.") + r.host.flush() + r.eventually(message = "reply visible") { r.messages(ref).any { it.text == "Of course." } } + + assertEquals("The send is never repeated, on any socket", 1, r.host.count("prompt.submit")) + val unresolved = r.state(ref).unresolved + assertEquals("Neither an idle snapshot, a reply nor the same text in saved history proves it was admitted", listOf(entryId), unresolved.map { it.id }) + assertEquals("please help", unresolved.single().composerText) + assertNull("Independent input is possible again", r.state(ref).sendBlock) + assertEquals(ReviewResult.Done, r.repo.resolveUnresolved(ref, entryId, ReviewDecision.Discard)) + assertTrue(r.journalKeys(ref).isEmpty()) + assertEquals("Reviewing is not sending", 1, r.host.count("prompt.submit")) + } + + @Test fun anUnknownSteerNeverDisablesIndependentInput() = run { + val r = rig() + val ref = r.newChat() + r.startRunning(ref) + r.host.timeOutOnce("session.steer") + assertTrue(r.repo.send(ref, "steer me") is SendResult.Uncertain) + r.eventually(message = "recovery") { r.state(ref).sendBlock == null } + assertEquals(1, r.host.count("session.steer")) + val queued = r.repo.send(ref, "independent", mode = SendMode.Queue) + assertTrue("$queued", queued is SendResult.Admitted) + } + + @Test fun explicitRefusalsKeepTheTextUnsentWithTheirCode() = run { + val r = rig() + val ref = r.newChat() + r.host.rejectOnce("prompt.submit", 4001) + val stale = r.repo.send(ref, "first") + assertEquals(4001, (stale as SendResult.Refused).rejectionCode) + assertEquals(4001, r.state(ref).unresolved.single().rejectionCode) + assertEquals("A stale runtime closes sending until the chat is reattached", SendBlock.NoLiveSession, r.state(ref).sendBlock) + r.repo.open(ref) + r.awaitState(ref, "reattached") { it.sendBlock == null } + + r.host.rejectOnce("prompt.submit", 4090, "MAX_CONCURRENT_SESSIONS") + val full = r.repo.send(ref, "second") as SendResult.Refused + assertTrue(full.reachedSessionLimit) + assertEquals(4090, full.rejectionCode) + r.host.rejectOnce("prompt.submit", 4090) + val owned = r.repo.send(ref, "third") as SendResult.Refused + assertFalse("4090 without the reason is another process owning the chat", owned.reachedSessionLimit) + assertEquals(3, r.state(ref).unresolved.count { it.rejectionCode != null }) + } + + @Test fun aProvenInputRejectionRestoresTheTextAndANewerDraftIsNeverOverwritten() = run { + val r = rig() + val ref = r.newChat() + r.host.rejectOnce("prompt.submit", 4002) + val refused = r.repo.send(ref, "bad input") + assertEquals(4002, (refused as SendResult.Refused).rejectionCode) + assertEquals("The empty composer got its text back", "bad input", r.state(ref).draft) + assertTrue("and no entry lingers", r.state(ref).unresolved.isEmpty()) + + // The person kept typing while the send was in flight: that newer text wins, the older one is kept unsent. + r.repo.updateDraft(ref, "A") + r.host.once("prompt.submit") { _ -> + r.repo.updateDraft(ref, "B, typed meanwhile") + throw HermesException(HermesException.Kind.RpcRejected, code = 4002) + } + r.repo.send(ref, "A") + val state = r.state(ref) + assertEquals("B, typed meanwhile", state.draft) + assertEquals("A", state.unresolved.single().composerText) + assertEquals(4002, state.unresolved.single().rejectionCode) + } + + @Test fun aNewerDraftSurvivesTheRetirementOfAnOlderSend() = run { + val r = rig() + val ref = r.newChat() + r.repo.updateDraft(ref, "send me") + assertTrue(r.repo.send(ref, "send me") is SendResult.Admitted) + assertEquals("The sent text left the composer atomically with the journal write", "", r.state(ref).draft) + r.repo.updateDraft(ref, "next thought") + val rt = r.runtimeOf(ref) + r.host.streamReply(rt, "Done.") + r.host.flush() + r.eventually(message = "retired") { r.state(ref).unresolved.isEmpty() } + assertEquals("next thought", r.state(ref).draft) + assertEquals("next thought", DraftRecord.decode(r.scopeOf(ref), r.store.read(RecordKey.draft(r.scopeOf(ref)))!!).text) + } + + @Test fun anUncertainSendSurvivesAProcessRestartAndCanBeRestoredToTheComposer() = run { + val file = File(directory, "s.bin") + val first = rig(store = FileSnapshotChatStore(file)) + val ref = first.newChat() + first.host.loseReplyOnce("prompt.submit", dropSocket = true) + val entryId = (first.repo.send(ref, "do the thing") as SendResult.Uncertain).entryId + first.close() + + val second = rig(host = FakeHermesHost().also { it.addSession("research", ref.anchor) }, store = FileSnapshotChatStore(file)) + second.repo.open(ref) + val reopened = second.awaitState(ref, "entry loaded after restart") { it.unresolved.isNotEmpty() } + assertEquals(entryId, reopened.unresolved.single().id) + assertEquals("prompt.submit", reopened.unresolved.single().method) + assertEquals("do the thing", reopened.unresolved.single().composerText) + second.awaitState(ref) { it.phase == ConversationPhase.Ready } + assertEquals(ReviewResult.Done, second.repo.resolveUnresolved(ref, entryId, ReviewDecision.RestoreToComposer)) + assertEquals("do the thing", second.state(ref).draft) + assertEquals("Reviewing is not resending", 0, second.host.count("prompt.submit")) + assertTrue(second.journalKeys(ref).isEmpty()) + } + + @Test fun restoringNeverOverwritesANewerDraft() = run { + val r = rig() + val ref = r.newChat() + r.host.timeOutOnce("prompt.submit") + val entry = (r.repo.send(ref, "old words") as SendResult.Uncertain).entryId + r.repo.updateDraft(ref, "new words") + assertEquals(ReviewResult.ComposerNotEmpty, r.repo.resolveUnresolved(ref, entry, ReviewDecision.RestoreToComposer)) + assertEquals("new words", r.state(ref).draft) + assertEquals(1, r.state(ref).unresolved.size) + } + + @Test fun aReceiptThatOutlivesItsSocketIsNotAttributedToTheNewOne() = run { + val r = rig() + val ref = r.newChat() + r.host.once("prompt.submit") { params -> + val receipt = r.host.defaultHandle("prompt.submit", params) + r.host.dropConnection() + r.host.newSocket() + r.host.flush() + receipt + } + val result = r.repo.send(ref, "hello") + assertTrue("$result", result is SendResult.Uncertain) + assertEquals("The entry stays reviewable", 1, r.state(ref).unresolved.size) + r.awaitState(ref, "recovered") { it.phase == ConversationPhase.Ready } + assertEquals(1, r.host.count("prompt.submit")) + } + + @Test fun anUnsendableMessageIsRefusedBeforeAnythingIsJournaled() = run { + val r = rig() + val ref = r.newChat() + assertEquals(ChatError.Kind.InvalidInput, (r.repo.send(ref, " ") as SendResult.NotSent).error.kind) + assertEquals(ChatError.Kind.TooLarge, (r.repo.send(ref, "x".repeat(ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES + 1)) as SendResult.NotSent).error.kind) + // Valid UTF-8 size but escapes beyond one frame. + assertEquals(ChatError.Kind.TooLarge, (r.repo.send(ref, "\u0001".repeat(400_000)) as SendResult.NotSent).error.kind) + assertEquals(ChatError.Kind.NotOpen, (r.repo.send(ConversationRef("research", "nothing"), "hi") as SendResult.NotSent).error.kind) + assertTrue(r.journalKeys(ref).isEmpty()) + assertEquals(0, r.host.count("prompt.submit")) + } + + @Test fun aHostWithoutTheExclusiveSubmitGuaranteeNeverAdmitsATurn() = run { + val r = rig() + val ref = r.newChat() + r.host.changeExclusiveSubmit(false) + r.eventually { r.state(ref).sendBlock == SendBlock.HostLacksExclusiveSubmit } + val result = r.repo.send(ref, "hi") + assertEquals(SendBlock.HostLacksExclusiveSubmit, (result as SendResult.NotSent).block) + assertEquals(0, r.host.count("prompt.submit")) + assertTrue(r.journalKeys(ref).isEmpty()) + } + + @Test fun steeringAndStoppingStayOpenWhenTheHostLacksTheExclusiveSubmitGuaranteeButNewTurnsDoNot() = run { + val r = rig() + val ref = r.newChat() + r.startRunning(ref) + r.host.changeExclusiveSubmit(false) + + val steer = r.repo.send(ref, "steer under false") + assertTrue("A correction is not a submission: $steer", steer is SendResult.Admitted) + assertEquals(Admission.Steered, (steer as SendResult.Admitted).admission) + assertEquals(1, r.host.count("session.steer")) + + val queued = r.repo.send(ref, "queued", mode = SendMode.Queue) + assertEquals(SendBlock.HostLacksExclusiveSubmit, (queued as SendResult.NotSent).block) + val replaced = r.repo.send(ref, "replace", mode = SendMode.InterruptAndSend) + assertEquals("Nothing is interrupted for a message that could not be queued", SendBlock.HostLacksExclusiveSubmit, (replaced as SendResult.NotSent).block) + assertEquals(0, r.host.count("session.interrupt")) + assertEquals("Only the first send was ever submitted", 1, r.host.count("prompt.submit")) + + assertEquals(StopResult.Requested, r.repo.stop(ref)) + assertEquals(1, r.host.count("session.interrupt")) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SessionOperationsTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SessionOperationsTest.kt new file mode 100644 index 00000000..878c4900 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SessionOperationsTest.kt @@ -0,0 +1,166 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.launch +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SessionOperationsTest : ChatTestBase() { + private fun ChatRig.messages(ref: ConversationRef) = state(ref).items.filterIsInstance() + + @Test fun renameTitlesTheLiveRuntimeAndReadsTheTitleBack() = run { + val r = rig() + val ref = r.savedChat() + r.repo.rename(ref, " Garden plan ") + val call = r.host.calls("session.title").single().params + assertEquals("Garden plan", call["title"].asString) + assertEquals(r.runtimeOf(ref).id, call["session_id"].asString) + assertEquals("Garden plan", r.state(ref).title) + assertEquals("Garden plan", r.host.sessions.getValue(ref.anchor).title) + assertThrowsChat(ChatError.Kind.InvalidInput) { r.repo.rename(ref, " ") } + assertThrowsChat(ChatError.Kind.InvalidInput) { r.repo.rename(ref, "x".repeat(241)) } + // A title the host does not confirm is an unknown outcome, never a quiet success. + r.host.once("session.title") { kotlinx.serialization.json.JsonObject(mapOf("pending" to kotlinx.serialization.json.JsonPrimitive(true), "title" to kotlinx.serialization.json.JsonPrimitive("Other"))) } + assertThrowsChat(ChatError.Kind.OutcomeUnknown) { r.repo.rename(ref, "Another") } + } + + @Test fun theBotChatIsUnhiddenBeforeItIsRenamedBecauseHermesRefusesAHiddenOne() = run { + val r = rig() + val bot = r.host.addSession("research", "bot-1") { addRow("user", "hello") } + r.host.makeCanonical(bot) + val opened = r.repo.openBotChat("research") as BotChatOutcome.Opened + r.awaitState(opened.ref) { it.phase == ConversationPhase.Ready } + r.repo.rename(opened.ref, "Our projects") + val hide = r.host.calls("session.set_hidden").single().params + assertEquals("bot-1", hide["session_id"].asString) + assertEquals(false, hide["hidden"].asBool) + assertEquals(listOf("session.set_hidden", "session.title"), r.host.requests.map { it.method }.filter { it == "session.set_hidden" || it == "session.title" }) + } + + @Test fun archiveAndRestoreUseTheLineageRootAndReadTheFlagBack() = run { + val r = rig() + r.host.addSession("research", "root-1", "Plan") { addRow("user", "x") } + r.host.compact("root-1", "tip-2") + r.repo.refreshCatalog() + val row = r.repo.catalog.value.sessions.single() + assertEquals("root-1", row.ref.anchor) + r.repo.open(row.ref) + r.awaitState(row.ref) { it.phase == ConversationPhase.Ready } + r.repo.archive(row.ref) + assertEquals("The edit targets the lineage root, not the current tip", "root-1", r.host.calls("session.archive").single().params["session_id"].asString) + assertTrue(r.repo.catalog.value.sessions.isEmpty()) + assertEquals(listOf("root-1"), r.repo.archivedChats().map { it.ref.anchor }) + r.repo.restore(row.ref) + assertEquals(false, r.host.calls("session.archive").last().params["archived"].asBool) + assertEquals(1, r.repo.catalog.value.sessions.size) + } + + @Test fun anArchiveTheHostDidNotApplyIsAConflictNotASuccess() = run { + val r = rig() + val ref = r.savedChat() + r.host.once("session.archive") { p -> + // The host says archived:true but its row never changed (a quiet no-op). + kotlinx.serialization.json.JsonObject(mapOf("archived" to kotlinx.serialization.json.JsonPrimitive(true), "session_key" to kotlinx.serialization.json.JsonPrimitive(ref.anchor))) + } + assertThrowsChat(ChatError.Kind.Conflict) { r.repo.archive(ref) } + } + + @Test fun deleteFindsTheHostRowDeletesItAndClearsEverythingKeptForThatChat() = run { + val r = rig() + val ref = r.savedChat() + r.repo.updateDraft(ref, "leftover draft") + r.host.timeOutOnce("prompt.submit") + r.repo.send(ref, "an uncertain one") + r.repo.refreshCatalog() + r.runtimeOf(ref).running = false // the host finished with it; an active chat cannot be deleted + r.repo.delete(ref) + assertEquals(ref.anchor, r.host.calls("session.delete").single().params["session_id"].asString) + assertFalse(r.host.sessions.containsKey(ref.anchor)) + assertTrue(r.repo.conversations.value[ref] == null) + val scope = r.scopeOf(ref) + assertNull(r.store.read(RecordKey.draft(scope))) + assertTrue(r.store.keys(ChatTestData.host, RecordKind.Journal, ref.profile, ref.anchor).isEmpty()) + assertTrue(r.repo.catalog.value.sessions.none { it.ref == ref }) + } + + @Test fun deletingAnActiveChatIsRefusedByHermesAndAnAlreadyGoneChatCountsAsDeleted() = run { + val r = rig() + val ref = r.savedChat() + r.host.rejectOnce("session.delete", 4009) + assertThrowsChat(ChatError.Kind.Rejected) { r.repo.delete(ref) } + assertTrue("Nothing was forgotten locally", r.repo.conversations.value[ref] != null) + r.host.rejectOnce("session.delete", 4007) + r.repo.delete(ref) + assertTrue(r.repo.conversations.value[ref] == null) + } + + @Test fun forkReadsTheWholeTranscriptCountsVisibleMessagesAndValidatesTheBranch() = run { + val r = rig() + // 130 pairs = 260 rows, more than one 200-row hydration page, so the one-row overlap is exercised. + val ref = r.savedChat(pairs = 130) + val through = r.host.sessions.getValue(ref.anchor).rows[201]["id"].asLong!! + val child = r.repo.fork(ref, through) + val hydration = r.host.restRequests.filter { it.route.endsWith("/messages") && it.query.toMap()["order"] == "oldest" } + assertEquals(listOf("0", "199"), hydration.map { it.query.toMap()["offset"] }) + assertEquals(listOf("200", "201"), hydration.map { it.query.toMap()["limit"] }) + val branch = r.host.calls("session.branch").single().params + assertEquals("Visible messages through the checkpoint", 202, branch["count"].asInt) + assertEquals("${r.state(ref).title} · Fork", branch["name"].asString) + assertNotNull(r.repo.conversations.value[child]) + assertTrue(child.anchor != ref.anchor) + r.awaitState(child) { it.phase == ConversationPhase.Ready } + } + + @Test fun aForkTheHostAnswersWithTheWrongMessagesIsRefused() = run { + val r = rig() + val ref = r.savedChat(pairs = 3) + val through = r.host.sessions.getValue(ref.anchor).rows[3]["id"].asLong!! + r.host.once("session.branch") { p -> + val reply = r.host.defaultHandle("session.branch", p) as kotlinx.serialization.json.JsonObject + kotlinx.serialization.json.JsonObject(reply + ("message_count" to kotlinx.serialization.json.JsonPrimitive(99))) + } + val failure = runCatching { kotlinx.coroutines.runBlocking { r.repo.fork(ref, through) } }.exceptionOrNull() + assertTrue("$failure", failure is HermesException || failure is ChatException) + assertThrowsChat(ChatError.Kind.InvalidInput) { r.repo.fork(ref, 424242) } + } + + @Test fun aTipReportedByTheRuntimeIsAdoptedWithItsOldIdKeptAsARoutingAlias() = run { + val r = rig() + val ref = r.savedChat() + val rt = r.runtimeOf(ref) + val old = r.state(ref).identity.storedTip + r.host.emit(rt, "session.info", """{"stored_session_id":"compacted-tip"}""") + r.host.flush() + val state = r.awaitState(ref) { it.identity.storedTip == "compacted-tip" } + assertEquals(ref, state.ref) + assertTrue(state.identity.knows(old)) + r.eventually(message = "alias persisted") { + r.store.read(RecordKey.identity(r.scopeOf(ref)))?.let { IdentityRecord.decode(r.scopeOf(ref), it).knows(old) } == true + } + r.host.emit(rt, "status.update", """{"kind":"compacted","text":"Done"}""") + r.host.flush() + r.awaitState(ref) { it.status == "Compacted" } + } + + @Test fun aReadForAChatThatWasReleasedAndOpenedAgainNeverAppliesToTheNewOne() = run { + val r = rig() + val ref = r.savedChat(pairs = 2) + val gate = CompletableDeferred() + r.host.holdMessages = gate + val late = r.scope.launch { runCatching { r.repo.reloadHistory(ref) } } + r.eventually(message = "request in flight") { r.host.restRequests.count { it.route.endsWith("/messages") } >= 2 } + r.repo.release(ref) + r.host.holdMessages = null + r.host.sessions.getValue(ref.anchor).addRow("user", "added while the old read was in flight") + r.repo.open(ref) + r.awaitState(ref) { it.phase == ConversationPhase.Ready && it.items.size == 5 } + gate.complete(Unit) + late.join() + assertEquals("The old read could not shrink or replace the new owner's rows", 5, r.state(ref).items.size) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SingleFlightAttachTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SingleFlightAttachTest.kt new file mode 100644 index 00000000..e7e7c43e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SingleFlightAttachTest.kt @@ -0,0 +1,80 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** One conversation is attached and recovered by at most one flight per socket, however many screens ask. */ +class SingleFlightAttachTest : ChatTestBase() { + @Test fun openingARecoveringChatTwiceJoinsTheAttachThatIsAlreadyRunning() = run { + val r = rig() + val ref = r.savedChat(pairs = 1) + val reached = CompletableDeferred() + val gate = CompletableDeferred() + r.host.once("session.resume") { p -> reached.complete(Unit); gate.await(); r.host.defaultHandle("session.resume", p) } + val resumes = r.host.count("session.resume") + val activations = r.host.count("session.activate") + val since = r.host.count("session.events.since") + + r.host.dropConnection() + r.host.newSocket() + reached.awaitWithin("the socket's own attach to reach session.resume") + val screens = listOf(r.scope.async { r.repo.open(ref) }, r.scope.async { r.repo.open(ref) }) + kotlinx.coroutines.delay(150) // time for a second and third attach to start, if they are going to + gate.complete(Unit) + screens.awaitAll() + + r.awaitState(ref, "ready again") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals("One resume for the new socket", resumes + 1, r.host.count("session.resume")) + assertEquals("One activation", activations + 1, r.host.count("session.activate")) + assertEquals("One recovery bracket (two replay reads)", since + 2, r.host.count("session.events.since")) + assertTrue(r.repo.send(ref, "works").let { it is SendResult.Admitted }) + } + + @Test fun anAttachForAnOlderSocketIsNeverJoinedByAnOpenOnTheNewerOne() = run { + val r = rig() + val ref = r.savedChat(pairs = 1) + val reached = CompletableDeferred() + val gate = CompletableDeferred() + r.host.once("session.resume") { p -> reached.complete(Unit); gate.await(); r.host.defaultHandle("session.resume", p) } + r.host.dropConnection() + r.host.newSocket() + reached.awaitWithin("the first socket's attach to reach session.resume") + // The socket moves on before the held attach answers. + r.host.dropConnection() + r.host.newSocket() + val opened = r.scope.async { r.repo.open(ref) } + gate.complete(Unit) + opened.await() + val ready = r.awaitState(ref, "ready on the newest socket") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals(ConversationPhase.Ready, ready.phase) + assertTrue("The chat is bound to the newest socket and can send", r.repo.send(ref, "on the third").let { it is SendResult.Admitted }) + assertEquals(3, r.host.calls("prompt.submit").single().generation) + } + + @Test fun aReopenWhileTheRecoveryAfterALostSendRunsJoinsThatBracket() = run { + val r = rig() + val ref = r.newChat() + val reached = CompletableDeferred() + val gate = CompletableDeferred() + r.host.timeOutOnce("prompt.submit") + r.host.once("session.events.since") { p -> reached.complete(Unit); gate.await(); r.host.defaultHandle("session.events.since", p) } + val resumes = r.host.count("session.resume") + val activations = r.host.count("session.activate") + + assertTrue(r.repo.send(ref, "lost receipt") is SendResult.Uncertain) + reached.awaitWithin("the recovery after the lost send to start") + val reopened = r.scope.async { r.repo.open(ref) } + kotlinx.coroutines.delay(150) // time for a second bracket to start, if it is going to + gate.complete(Unit) + reopened.await() + + r.awaitState(ref, "covered") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + assertEquals("The reopen resumed the chat once", resumes + 1, r.host.count("session.resume")) + assertEquals("and the two callers shared one recovery bracket", activations + 1, r.host.count("session.activate")) + assertEquals("The lost send was never repeated", 1, r.host.count("prompt.submit")) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SocketFenceTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SocketFenceTest.kt new file mode 100644 index 00000000..3368b8f9 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SocketFenceTest.kt @@ -0,0 +1,70 @@ +package app.bighelp.hermes.chat + +import kotlinx.coroutines.async +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A request that names a runtime ID is only valid on the socket that runtime was proved on. The chat plans a send on + * one socket, awaits a durable write, and only then writes the frame: the socket may have been replaced in between, + * and the frame must then not leave at all. + */ +class SocketFenceTest : ChatTestBase() { + @Test fun aSocketReplacedDuringTheJournalWriteSendsNothingAndGivesTheTextBack() = run { + val store = GatedChatStore() + val r = rig(store = store) + val ref = r.newChat() + store.holdNextJournalWrite() + val sending = r.scope.async { r.repo.send(ref, "planned on socket one") } + store.reached.awaitWithin("the journal write to be held") + + r.host.dropConnection() + r.host.newSocket() + r.awaitState(ref, "recovered on socket two") { it.phase == ConversationPhase.Ready && it.sendBlock == null } + store.open() + + val result = sending.await() + assertEquals("No frame carrying a socket-one runtime ID reached socket two", 0, r.host.count("prompt.submit")) + assertTrue("$result", result is SendResult.NotSent) + val state = r.awaitState(ref, "text returned") { it.sendBlock == null } + assertEquals("planned on socket one", state.draft) + assertTrue(state.unresolved.isEmpty()) + assertTrue("The chat still works on the new socket", r.repo.send(ref, "again") is SendResult.Admitted) + assertEquals(2, r.host.calls("prompt.submit").single().generation) + } + + @Test fun everyRuntimeAddressedCallIsFencedToTheSocketItWasPlannedOn() = run { + val r = rig() + val ref = r.savedChat(pairs = 2) + val generation = r.host.generation + // Controls and session edits. + r.repo.modelOptions(ref) + r.repo.setModel(ref, "big-model", "stub-provider") + r.repo.setReasoning(ref, "high") + r.repo.setYolo(ref, true) + r.repo.commands(ref) + r.repo.rename(ref, "Fenced") + r.repo.fork(ref, r.host.rowIds(ref.anchor).last()) + r.repo.openBotChat("scratch", createIfMissing = true) + // Commands, then a turn that is steered and stopped. + assertTrue(r.repo.send(ref, "/help") is SendResult.Admitted) + assertTrue(r.repo.send(ref, "/deploy-skill go") is SendResult.Admitted) + val rt = r.runtimeOf(ref) + r.host.emit(rt, "message.start") + r.host.flush() + r.awaitState(ref, "running") { it.running } + assertTrue(r.repo.send(ref, "also") is SendResult.Admitted) + assertEquals(StopResult.Requested, r.repo.stop(ref)) + + val addressed = setOf( + "session.resume", "session.create", "session.activate", "session.events.since", "prompt.submit", "slash.exec", "command.dispatch", + "session.steer", "session.interrupt", "config.set", "config.get", "model.options", "commands.catalog", "session.title", "session.branch", + ) + val seen = r.host.requests.map { it.method }.toSet() + assertTrue("Every kind of call was exercised: ${addressed - seen}", seen.containsAll(addressed)) + val unfenced = r.host.requests.filter { it.method in addressed && it.fence == null }.map { it.method }.distinct() + assertEquals("Calls sent without a socket fence", emptyList(), unfenced) + assertTrue(r.host.requests.filter { it.method in addressed }.all { it.fence == generation && it.generation == generation }) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt new file mode 100644 index 00000000..505fca8a --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt @@ -0,0 +1,283 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.WireMessage +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TurnReducerTest { + private val runtime = "runtime-a" + private var seq = 0L + + private fun event(type: String, payload: String = "{}", sequence: Long? = ++seq): WireMessage.Event = + WireMessage.Event(type, runtime, jsonObject(payload), sequence) + + private fun TurnReducer.feed(type: String, payload: String = "{}", sequence: Long? = ++seq) = accept(event(type, payload, sequence)) + + private fun reducer() = TurnReducer("epoch-1") + + private fun TurnReducer.messages() = items.filterIsInstance() + private fun TurnReducer.activities() = items.filterIsInstance() + + @Test fun deltasBuildOneStreamingAssistantRowThatTheFinalReplaces() { + val r = reducer() + r.feed("message.start") + assertTrue(r.running) + r.feed("message.delta", """{"text":"Hel"}""") + r.feed("message.delta", """{"text":"lo"}""") + val streaming = r.messages().single() + assertEquals("Hello", streaming.text) + assertFalse(streaming.complete) + assertEquals(ItemOrigin.Live, streaming.origin) + r.feed("message.complete", """{"text":"Hello there."}""") + val final = r.messages().single() + assertEquals("The final text replaces the accumulated deltas", "Hello there.", final.text) + assertTrue(final.complete) + assertEquals("A segment keeps one stable ID", streaming.id, final.id) + } + + @Test fun aMessageCompleteIsASegmentFinalAndOnlyRunningFalseEndsTheTurn() { + val r = reducer() + r.feed("message.start") + r.feed("message.delta", """{"text":"x"}""") + val complete = r.feed("message.complete", """{"text":"x"}""") + assertFalse("A segment final does not end the turn", complete.terminal) + assertTrue(r.running) + val ended = r.feed("session.info", """{"running":false}""") + assertTrue(ended.terminal) + assertFalse(r.running) + val again = r.feed("session.info", """{"running":false}""") + assertFalse("running false after not running is not a second terminal", again.terminal) + } + + @Test fun anInterimSealsOneSegmentAndTheNextTextStartsAnother() { + val r = reducer() + r.feed("message.start") + r.feed("message.delta", """{"text":"Let me check."}""") + r.feed("message.interim", """{"text":"Let me check."}""") + r.feed("message.delta", """{"text":"Done."}""") + val rows = r.messages() + assertEquals(listOf("Let me check.", "Done."), rows.map { it.text }) + assertEquals(listOf(true, false), rows.map { it.complete }) + assertEquals(2, rows.map { it.id }.toSet().size) + assertTrue("Both stay inside the same running turn", r.running) + } + + @Test fun reasoningIsAnActivityThatTextSealsAndALaterPhaseIsANewOne() { + val r = reducer() + r.feed("message.start") + r.feed("reasoning.delta", """{"text":"think "}""") + r.feed("reasoning.delta", """{"text":"more"}""") + val first = r.activities().single() + assertEquals(ActivityKind.Reasoning, first.kind) + assertEquals("think more", first.detail) + assertEquals(ActivityLifecycle.Running, first.lifecycle) + r.feed("message.delta", """{"text":"answer"}""") + assertEquals(ActivityLifecycle.Succeeded, r.activities().single().lifecycle) + r.feed("reasoning.delta", """{"text":"second thought"}""") + val phases = r.activities() + assertEquals(2, phases.size) + assertEquals("second thought", phases[1].detail) + // reasoning.available is the assistant body preview, not model reasoning. + r.feed("reasoning.available", """{"text":"preview"}""") + assertEquals(2, r.activities().size) + } + + @Test fun spinnerAndPreannouncementAreStatusOnlyAndMakeNoRows() { + val r = reducer() + r.feed("message.start") + val thinking = r.feed("thinking.delta", """{"text":" pondering ","rendered":null,"verbose":false}""") + assertEquals("pondering", thinking.status) + val generating = r.feed("tool.generating", """{"name":"terminal"}""") + assertEquals("Preparing terminal", generating.status) + assertTrue(r.items.isEmpty()) + // An extra key makes the typed auxiliary payload malformed: ignored, never a row. + val bad = r.feed("thinking.delta", """{"text":"x","surprise":1}""") + assertNull(bad.status) + assertTrue(r.items.isEmpty()) + } + + @Test fun toolsUpsertByIdKeepTheirOriginalArgumentsAndMapExplicitFailure() { + val r = reducer() + r.feed("message.start") + r.feed("tool.start", """{"tool_id":"t1","name":"terminal","context":"ls","args":{"command":"ls"}}""") + assertEquals(ActivityLifecycle.Running, r.activities().single().lifecycle) + r.feed("tool.progress", """{"tool_id":"t1","summary":"working"}""") + r.feed("tool.complete", """{"tool_id":"t1","result":{"files":["a"]},"duration_s":1.5}""") + val done = r.activities().single() + assertEquals(ActivityLifecycle.Succeeded, done.lifecycle) + assertEquals("terminal", done.title) + assertEquals("""{"command":"ls"}""", done.arguments) + assertEquals("""{"files":["a"]}""", done.result) + r.feed("tool.start", """{"tool_id":"t2","name":"x"}""") + r.feed("tool.complete", """{"tool_id":"t2","status":"error"}""") + assertEquals(ActivityLifecycle.Failed, r.activities()[1].lifecycle) + r.feed("tool.start", """{"tool_id":"t3"}""") + r.feed("tool.complete", """{"tool_id":"t3","status":"cancelled"}""") + assertEquals(ActivityLifecycle.Cancelled, r.activities()[2].lifecycle) + // No tool_id: not joinable to a later call, so it is ignored. + val before = r.activities().size + r.feed("tool.start", """{"name":"anonymous"}""") + assertEquals(before, r.activities().size) + } + + @Test fun aTurnEndSettlesAnUnfinishedToolAsRecordedNotSuccessful() { + val r = reducer() + r.feed("message.start") + r.feed("tool.start", """{"tool_id":"t1","name":"terminal"}""") + val end = r.feed("session.info", """{"running":false}""") + assertTrue(end.terminal) + assertEquals(ActivityLifecycle.Recorded, r.activities().single().lifecycle) + } + + @Test fun staleAndDuplicateSequencesAreIgnoredAndTheCursorAdvancesFirst() { + val r = reducer() + r.feed("message.start", sequence = 10) + r.feed("message.delta", """{"text":"a"}""", sequence = 11) + assertEquals(11, r.lastSequence) + val stale = r.feed("message.delta", """{"text":"STALE"}""", sequence = 11) + assertTrue(stale.ignored) + val older = r.feed("message.delta", """{"text":"OLDER"}""", sequence = 3) + assertTrue(older.ignored) + assertEquals("a", r.messages().single().text) + // An event without a sequence is applied and leaves the cursor alone. + r.feed("message.delta", """{"text":"b"}""", sequence = null) + assertEquals("ab", r.messages().single().text) + assertEquals(11, r.lastSequence) + } + + @Test fun theTurnIdentityIsTheEpochAndTheSequenceOfItsStart() { + val r = reducer() + r.feed("message.start", sequence = 21) + assertEquals("epoch-1:21", r.turnId) + r.feed("session.info", """{"running":false}""", sequence = 22) + r.feed("message.start", sequence = 40) + assertEquals("epoch-1:40", r.turnId) + } + + @Test fun aFailedFinalBeforeAnyStartIsItsOwnFailedTurnAndNotTheLastOnesReply() { + val r = reducer() + r.feed("message.start") + r.feed("message.delta", """{"text":"earlier answer"}""") + r.feed("session.info", """{"running":false}""") + val earlier = r.turnId + val failed = r.feed("message.complete", """{"status":"error","text":"The provider is busy.","failure_reason":"overloaded","error_surface":{"layer":"provider","code":"overloaded","retryable":true,"provider_label":"Example Provider"}}""") + assertTrue(failed.failedBeforeStart) + assertTrue(failed.terminal) + assertTrue(r.turnId != earlier) + assertEquals("overloaded", failed.turnFailure!!.code) + assertEquals("Example Provider", failed.turnFailure!!.providerLabel) + assertTrue(failed.turnFailure!!.retryable) + assertEquals(r.turnId, r.failedTurnId) + assertEquals("earlier answer", r.messages().first().text) + assertEquals("The provider is busy.", r.messages().last().text) + } + + @Test fun aReusedFinalSettlesTheSealedAnswerInsteadOfPaintingACopy() { + val r = reducer() + r.feed("message.start") + r.feed("message.delta", """{"text":"All done."}""") + r.feed("message.interim", """{"text":"All done."}""") + r.feed("tool.start", """{"tool_id":"t","name":"memory"}""") + r.feed("tool.complete", """{"tool_id":"t"}""") + val settled = r.feed("message.complete", """{"text":"All done.","response_reused":true}""") + assertEquals("The reused final adds no second copy", 1, r.messages().size) + assertTrue(settled.settledAnswer) + assertTrue(r.messages().single().complete) + } + + @Test fun theHostsSavedRowIdsBindOptimisticRowsNeverByText() { + val r = reducer() + r.addLocalUser("local-1", "hello") + r.feed("message.start") + r.feed("message.delta", """{"text":"hi"}""") + val change = r.feed("message.complete", """{"text":"hi","persisted_turn":{"user_row_id":101,"final_assistant_row_id":102}}""") + assertEquals(101L, change.persistedTurn!!.userRowId) + assertEquals(102L, change.persistedTurn!!.finalAssistantRowId) + r.bindRows(change.persistedTurn!!) + val rows = r.messages() + assertEquals(listOf(101L, 102L), rows.map { it.rowId }) + assertEquals(listOf(ItemOrigin.Local, ItemOrigin.Live), rows.map { it.origin }) + // A second binding for the same rows changes nothing. + r.bindRows(change.persistedTurn!!) + assertEquals(listOf(101L, 102L), r.messages().map { it.rowId }) + } + + @Test fun sessionInfoReportsTheStoredTipTheModelTheTitleAndTheServiceTier() { + val r = reducer() + val info = r.feed("session.info", """{"running":true,"stored_session_id":"tip-2","model":"m","provider":"p","reasoning_effort":"high","service_tier":"fast","title":"A title","cwd":"/work"}""") + assertEquals("tip-2", info.storedIdReport) + assertEquals("m", info.runtime!!.model) + assertEquals("p", info.runtime!!.provider) + assertEquals("high", info.runtime!!.reasoningEffort) + assertEquals("fast", info.runtime!!.serviceTier) + assertEquals("/work", info.runtime!!.cwd) + assertEquals("A title", info.title) + assertTrue("running:true starts a turn the reducer did not see start", r.running) + assertEquals("Renamed", r.feed("session.title", """{"title":"Renamed"}""").title) + } + + @Test fun compactionIsReadFromTheHostsStatusKindsOnly() { + val r = reducer() + assertEquals(CompactionSignal.Compressing, r.feed("status.update", """{"kind":"compressing","text":"Compressing…"}""").compaction) + assertEquals(CompactionSignal.Compacting, r.feed("status.update", """{"kind":"compacting","text":"Compacting"}""").compaction) + assertEquals(CompactionSignal.Compacted, r.feed("status.update", """{"kind":"compacted","text":"Done"}""").compaction) + assertNull(r.feed("status.update", """{"kind":"other","text":"x"}""").compaction) + assertNull("A malformed status update is ignored", r.feed("status.update", """{"kind":"compacted"}""").compaction) + } + + @Test fun anEpochChangeRestartsTheCursorWithoutDroppingTheRichRows() { + val r = reducer() + r.feed("message.start", sequence = 5) + r.feed("message.delta", """{"text":"kept"}""", sequence = 6) + r.resetCursor("epoch-2", 0) + assertEquals("epoch-2", r.epoch) + assertEquals(0, r.lastSequence) + assertEquals("kept", r.messages().single().text) + r.feed("message.delta", """{"text":"!"}""", sequence = 1) + assertEquals("kept!", r.messages().single().text) + } + + @Test fun turnIdsStayUniqueWhenAnotherRuntimeOfTheSameEpochRestartsItsSequence() { + val r = reducer() + r.feed("message.start", sequence = 1) + val first = r.turnId + r.feed("message.delta", """{"text":"old answer"}""", sequence = 2) + // Reattached to a new runtime of the same host epoch: its sequence numbers start over at one. + r.resetCursor("epoch-1", 0) + r.feed("message.start", sequence = 1) + assertFalse("A turn of another runtime never reuses an older turn's ID", first == r.turnId) + r.feed("message.delta", """{"text":"new answer"}""", sequence = 2) + assertEquals(listOf("old answer", "new answer"), r.messages().map { it.text }) + } + + @Test fun anErrorEventMarksTheTurnFailedWithoutEndingIt() { + val r = reducer() + r.feed("message.start") + val error = r.feed("error", """{"message":"oops"}""") + assertTrue(error.errorEvent) + assertTrue(r.running) + } + + @Test fun subagentEventsNeedARealSubagentOrChildSessionId() { + val r = reducer() + r.feed("message.start") + r.feed("subagent.start", """{"goal":"search"}""") + assertTrue(r.items.isEmpty()) + r.feed("subagent.start", """{"subagent_id":"s1","goal":"search"}""") + r.feed("subagent.text", """{"subagent_id":"s1","text":"found "}""") + r.feed("subagent.text", """{"subagent_id":"s1","text":"it"}""") + val running = r.activities().single() + assertEquals(ActivityKind.Subagent, running.kind) + assertEquals("search", running.title) + assertEquals("found it", running.detail) + r.feed("subagent.complete", """{"subagent_id":"s1","summary":"done"}""") + assertEquals(ActivityLifecycle.Succeeded, r.activities().single().lifecycle) + // A turn end does not settle a subagent: it keeps its own lifecycle. + r.feed("subagent.start", """{"subagent_id":"s2"}""") + r.feed("session.info", """{"running":false}""") + assertEquals(ActivityLifecycle.Running, r.activities().last().lifecycle) + } +} diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 00000000..54521a73 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "bighelp-android" +include(":hermes") +include(":app") diff --git a/docs/ANDROID_PARITY.md b/docs/ANDROID_PARITY.md new file mode 100644 index 00000000..e58e3512 --- /dev/null +++ b/docs/ANDROID_PARITY.md @@ -0,0 +1,52 @@ +# Android parity acceptance matrix + +Target: a functioning Android application close to bighelp's everyday Apple workflows. The discovery/demo foundation is not acceptance of the target. Current Apple source and the [transport contract](NATIVE_TRANSPORT.md) define behavior. The implementation plan is [Android end-to-end parity](superpowers/plans/2026-10-27-android-parity.md). + +Status is updated from source and executed evidence. **Not started** and **pending** are incomplete. Host capability absence is a runtime state, not proof that the Android implementation exists. Tests of a policy type do not establish live behavior. Apple-only platform surfaces and store-distribution gates have separate dispositions. + +Contract references below name chapters under `docs/hermes/`, with product references relative to the repository root. Exact source implementations are linked from those chapters. + +| Workflow | Required behavior | Authority | Implementation | Evidence | +|---|---|---|---|---| +| Authentication | Automatic dashboard, session/access token, password PKCE, loopback browser PKCE; restore and rotation | CONNECTION.md §§3–7 | In progress: Task 1 | Pending | +| Proxy access | Independent proxy headers, private HTTP consent and prefix-safe paths | CONNECTION.md §§1–2 | In progress: Task 1 | Endpoint tests exist; full proxy pending | +| Gateway | Ready deadline, ticket subprotocol, ordered RPC/events, heartbeat and reconnect | CONNECTION.md §§7–10 | In progress: Task 1 | Pending | +| Prompts | Questions, approval, secret/sudo and exact cancellation ownership | CHAT.md §§8–9 | Not started | Pending | +| Saved computers | Encrypted credentials, add/select/remove, restore exact principal | CONNECTION.md §6 | In progress: verified Keystore backing; live composition pending | 22 storage JVM cases and 5 API36 instrumentation cases pass | +| Agents and Bots | Real directory and canonical Bot Chats; edit instructions, model, appearance | REFERENCE.md §Profiles | Not started | Pending | +| Sessions | Catalog, create/resume, search, rename, archive/restore/delete/fork | CHAT.md §§1–3,11 | Not started | Pending | +| Live chat | Streaming, tools, segment finals and authoritative turn terminal | CHAT.md §§4,7 | Not started | Pending | +| Active-turn controls | Steer default, queue, stop and slash/model/reasoning controls | CHAT.md §§4,6,12 | Not started | Pending | +| Durable recovery | Draft/journal before dispatch, no uncertain replay, replay/history after restart | CHAT.md §§5,10–11 | Not started | Pending | +| Reader and input | Stable history anchor, paging, Latest, keyboard, rotation and background recovery | ../CHAT_INTERACTION_CONTRACT.md | Demo only | Live verification pending | +| Rich transcript | Markdown, tools, reasoning and supported cards with inert invalid fallback | EXTENSIONS.md §§Card documents,Agent deliveries | Not started | Pending | +| Outgoing attachments | Image/PDF/file admission and uncertainty, real picker/share | EXTENSIONS.md §Outgoing chat attachments | Not started | Pending | +| Incoming media | Resolved chunked downloads, digest/cache, image/audio/video/file viewer | EXTENSIONS.md §§Incoming attachment resolution,Managed transfers | Not started | Pending | +| Files | Agent workspace scope, browse/read/upload/download/edit with conflict handling | EXTENSIONS.md §Configured workspace; REFERENCE.md §Stock files | Not started | Pending | +| Feed, Ideas, Goals | Per-agent content, details, feedback and state changes; empty by default | EXTENSIONS.md §Board | Not started | Pending | +| Projects | Real catalog/folders/active pointer and exact session workspace binding | REFERENCE.md §Projects | Not started | Pending | +| Code | Project/branch/worktree launch, Changes, supported Ship and staged jobs | REFERENCE.md §Stock Git; AGENTS.md Code mode | Not started | Pending | +| Kanban | Boards, task CRUD/move/comments, attachments and ordered event updates | EXTENSIONS.md §Independent Hermes Kanban plugin | Not started | Pending | +| Workflows and Dev Factory | Recipes/runs/editor/actions, exact sign-off and verified artifacts | EXTENSIONS.md §Workflows | Not started | Pending | +| Scheduled tasks | List/detail/runs, capability-gated friendly editing and run actions | REFERENCE.md §Scheduled tasks | Not started | Pending | +| Usage | Host analytics and provider limits, unknown values remain unknown | REFERENCE.md §Usage; EXTENSIONS.md §Usage | Not started | Pending | +| Apps | Native connection cards, Composio/MCP connection and account management | GROUPS_AND_DEVICE_TOOLS.md §App connection cards; EXTENSIONS.md §Composio | Not started | Pending | +| Groups | Hosted rooms, durable send/log, pending actions and stop; both host paths | GROUPS_AND_DEVICE_TOOLS.md §§1–8 | Not started | Pending | +| Voice | Transcription/speech and supported real live call delegation | EXTENSIONS.md §Voice protocols | Not started | Pending | +| Bot Screen | Authenticated display bridge, bounded RFB viewer and control handoff | GROUPS_AND_DEVICE_TOOLS.md §Display transport | Not started | Pending | +| Android tools | Applicable device tools, explicit grants, OS permission and revocation | GROUPS_AND_DEVICE_TOOLS.md §§9–10 | Not started | Pending | +| Notifications | Foreground alerts and exact-chat routing; background delivery needs real Android adapter | NATIVE_TRANSPORT.md; Android delivery adapter | Not started | No FCM server contract established | +| Settings and navigation | One menu/Settings, appearance/layout/mode, identity, computers and Nerd Mode | ../../DESIGN.md; ../../AGENTS.md | Demo subset | Live acceptance pending | +| Accessibility | TalkBack, focus, font scale, contrast and reduced motion | ../../DESIGN.md | Not started | Pending | +| Apple-only surfaces | Watch, CarPlay, visionOS, Live Activities, Shortcuts, Health/Focus/AlarmKit | PORTING.md §Android and Expo boundaries | Platform boundary | No Android support claim | +| Store distribution | Permanent ID/signing, identity and physical-device checks, Play testing | ../../android/README.md | Account created; verification deferred | Distribution gate, separate from app implementation | + +## Evidence classes + +- JVM/scripted: deterministic HTTP/WebSocket, persistence, reducers and failure injection. +- Demo emulator: UI controls with explicitly invented data, no Hermes compatibility claim. +- Disposable Hermes: actual isolated host/plugin at recorded revisions, synthetic model and made-up workspace. +- Android emulator/device: installed-file identity and exercised real controls/lifecycle; emulator evidence does not establish physical-device behavior. +- Live services: only explicitly authorized services; no inference from fixtures or an Apple client. + +The full goal remains open while required everyday workflows lack implementation or appropriate end-to-end evidence. Each accepted row records exact source/build and evidence; no placeholder control or generic raw-data page counts as implementation. diff --git a/docs/hermes/CONNECTION.md b/docs/hermes/CONNECTION.md index 58bb6309..c638564f 100644 --- a/docs/hermes/CONNECTION.md +++ b/docs/hermes/CONNECTION.md @@ -291,12 +291,12 @@ read current credential and exact principal POST /auth/native/refresh (the saved credential keeps its refresh token) on 2xx: validate minted session and unchanged principal compare-and-replace the old record with the new credential -on 401: compare-and-replace the record with one that has no refresh token; require a new sign-in +on 401 without WWW-Authenticate: require a new sign-in; do not write or erase the stored record on anything else (503, 429, a proxy 5xx, a network error, a timeout, cancellation): change nothing; the next attempt sends the same refresh token again ``` -The refresh token is dropped only when Hermes answers 401. Hermes coalesces repeat refreshes for 30 seconds (the same token gets the same answer), and after a lost answer a resend cannot do worse than the sign-out that dropping the token would force; Hermes Desktop keeps its token the same way. A resend may come from the same authenticator, a new one after a reconnect, or the next launch. A stale authenticator never overwrites a newer record: the compare-and-replace fails first, whatever the host answered. +Only Hermes' own 401 requires a new sign-in; it does not erase the saved credential. Another authenticator may be saving a newer sign-in, and the rejected authenticator must not overwrite it. Hermes coalesces repeat refreshes for 30 seconds (the same token gets the same answer). After a lost answer, the saved refresh token remains available to the same authenticator, a reconnect or the next launch. A stale authenticator never overwrites a newer record: the compare-and-replace fails first, whatever the host answered. This matches `performRefresh` and `aRejectedRenewalAsksForANewSignIn` in the linked source and renewal tests. Authenticated JSON HTTP performs one narrowly defined retry: on HTTP 401 **without** `WWW-Authenticate`, renew the Bearer token, or rebootstrap an automatic dashboard token that changed, and resend once. If another concurrent request already installed a new credential, use that one. This relies on the Hermes contract that auth refusal happens before route execution. A 401 with `WWW-Authenticate` is a proxy challenge, not this retry path. Other HTTP failures are not retried here. Dedicated multipart/binary transfers do not inherit this generic JSON retry loop. diff --git a/docs/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md new file mode 100644 index 00000000..03e343f4 --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -0,0 +1,66 @@ +# Android Foundation Implementation Plan + +> **For agentic workers:** Use focused implementation tasks with independent review. Steps use checkbox syntax for tracking. + +**Goal:** Establish a buildable native Android app and a tested portable Hermes foundation. + +**Architecture:** A Kotlin/JVM `hermes` module owns the bounded protocol and connection policy. A Compose `app` module owns consent, local preferences and UI. Demo fixtures exercise screens without a host. + +**Tech Stack:** Kotlin, Gradle, Jetpack Compose, OkHttp, kotlinx.serialization, coroutines, JUnit. + +**Spec:** `docs/superpowers/specs/2026-10-27-android-foundation-design.md` + +## Global Constraints + +- Minimum Android API is 26; compile and target API are 36. +- Use `app.bighelp.android` as the development application ID, with `.debug` on debug builds. +- No host request is sent before consent. +- No credentialed redirects or ambient cookies. +- A dispatched mutation without a receipt is uncertain, not failed, and is never automatically repeated. +- Personal information and real host data never enter this public repository. + +## Review Focus + +- A malformed trailing frame publishes no earlier message from the same WebSocket message. +- UTF-8 byte boundaries and deeply nested JSON fail before unbounded parsing. +- A deployment prefix remains part of endpoint identity and every route. +- Switching owner or closing a connection retires late responses. +- Demo responses remain labeled examples; unsupported live behavior is unavailable. + +### Task 1: Reproducible build and portable protocol + +**Files:** `android/settings.gradle.kts`, `android/build.gradle.kts`, `android/gradle/`, `android/hermes/`. + +**Interfaces:** `HermesEndpoint.parse(input, allowPrivateHttp)` produces a canonical endpoint with prefix preserving route construction. `HermesWire.decode(bytes)` returns an ordered list of typed frames or a typed rejection, atomically. + +- [x] Add the Gradle wrapper, pinned build dependencies and JVM test harness. +- [x] Write failing vector and endpoint tests; capture the failure. +- [x] Implement the decoder and endpoint rules from `CONNECTION.md` and Swift source. +- [x] Run all vectors and generated limit tests; independently review trust boundaries. + +### Task 2: App shell and public host discovery + +**Files:** `android/app/`, `android/README.md`. + +**Interfaces:** App state owns consent and discovery generation; screens observe state and invoke explicit actions. `HostChecker` separates discovery from the state model. Demo chat has no live repository or invented host success. + +- [x] Add Compose app, manifest and local consent preferences with backup exclusions; introduce Keystore storage with authenticated sign-in in the next milestone. +- [x] Add consent, connection setup, demo sessions/chat, agents and one Settings surface. +- [x] Add consent-gated public host discovery through `HostDiscovery.check(endpoint, consentGranted): DiscoveryResult`; do not label discovery as a connection or collect credentials. +- [x] Test consent, failed setup, draft preservation and demo control behavior. + +### Task 3: Verify, review and record evidence + +**Files:** `android/README.md`, Android CI workflow, issue/PR. + +- [x] Run JVM tests, Android unit checks, lint and debug assemble. +- [x] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. +- [x] Review the full diff, fix concrete findings and repeat affected verification. +- [x] Document remaining acceptance gaps, commit changes and open a pull request linked to its issue. + +Preview implementation: [PR #647](https://github.com/promptclickrun/bighelp/pull/647), closing [#644](https://github.com/promptclickrun/bighelp/issues/644). Executed verification and remaining acceptance gaps are recorded in [the Android README](../../../android/README.md#verified-preview-snapshot-2026-10-27). Authenticated live chat and Play release are subsequent milestones. + +### Parallel account preparation + +- [x] Use Terra/max for browser work to prepare personal Play Console registration. +- [x] Leave identity, verification and any required direct checkout with the maintainer; report the exact remaining steps. diff --git a/docs/superpowers/plans/2026-10-27-android-parity.md b/docs/superpowers/plans/2026-10-27-android-parity.md new file mode 100644 index 00000000..b83fb625 --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-android-parity.md @@ -0,0 +1,95 @@ +# Android End-to-End Parity Implementation Plan + +> **For agentic workers:** Use superpowers:subagent-driven-development. Continue all tasks; the user explicitly requires a functioning close-parity app, not a preview checkpoint. Steps use checkbox syntax for tracking. + +**Goal:** Deliver a functioning Android app with real Hermes conversations and the current app's everyday workflows. + +**Architecture:** Retain Kotlin/JVM protocol and domain clients in `android/hermes`; Android adapters and Compose live/demo presentation live in `android/app`. One authenticated authority owns each client, cache, journal and pending prompt. Platform integration follows verified domain behavior. + +**Tech Stack:** Existing pinned Kotlin, coroutines, kotlinx JSON, OkHttp, Compose, Android Keystore and protected atomic files. + +**Spec:** `docs/superpowers/specs/2026-10-27-android-parity-design.md`. + +## Global Constraints + +- Minimum API 26, compile/target 36. Existing pinned dependencies unless necessary. +- Real host data only on the live path; labeled synthetic demo remains separate. No fake progress or default AI spending. +- Consent precedes every host access; secure credentials never enter ordinary preferences, logs, public artifacts or backups. +- Validated canonical endpoints retain deployment prefixes; TLS stays enabled; private HTTP needs explicit opt-in. No ambient cookies, credentialed redirects or automatic mutation replay. +- Actual capabilities gate behavior, never release versions. Register handlers before server-request advertisement on every ready socket. +- Journal before mutation dispatch; original uncertain bytes stay reviewable and never automatically resend. Separate principal/owner/socket/profile/runtime/stored/epoch coordinates. +- Every async callback and persistence replacement checks its original owner. Protect reader-controlled chat scroll, drafts, input and history. +- Only isolated disposable Hermes clones/homes with synthetic data/models for live verification. No maintainer hosts, shared gateway restarts, production services, merges or releases. +- User-selected workers: Claude Sonnet 5.5 / Xhigh implementation and review; GPT-6.1 Terra / max device/browser. + +## Review Focus + +- A late reply/refresh/prompt from a retired host never publishes or rewrites a replacement sign-in. +- Socket upgrade without readiness and an absent/false exclusive-submit guarantee never admit a turn. +- Lost submit/create/refresh receipts follow their distinct reconciliation contracts, including process death. +- Streaming, paging, keyboard, background/reconnect and active-turn sends preserve reader/input ownership and never duplicate an answer. +- Missing plugin features, newer/older optional fields and per-agent context differences disable only the relevant operation without fabricating data. + +### Task 1: Real authentication, bounded HTTP and ordered gateway + +**Files:** New `android/hermes/src/{main,test}/kotlin/app/bighelp/hermes/` authentication/HTTP/gateway classes; `android/hermes/build.gradle.kts` dependencies. Existing endpoint/wire/policy files only where required; preserve all existing tests. + +**Interfaces:** Provide public JVM types for auth status/providers, saved credentials, sign-in input, a compare-and-replace credential store, bounded authenticated HTTP, and an ordered gateway interface. Publish exact signatures in the report for later tasks. Store authority is canonical endpoint plus exact principal. Android browser composition uses a supplied browser-launch callback and a real device-local loopback listener; no invented app-scheme callback. RPC consumers need connect/close, request/result/failure, ordered event and server-request streams, exact-owned server replies, generation and current capability/readiness state. + +- [ ] Write failing tests for bootstrap extraction, dashboard versus bearer headers, password/native browser PKCE query/cookie/state/code validation, token identity/expiry, single-flight rotating refresh with durable CAS and a 401 requiring new sign-in without overwriting the vault, mode/principal changes, response bounds, no redirects/cookies/retries and cancellation. +- [ ] Write failing scripted WebSocket tests: no outbound before ready, 20-second ready deadline, fresh bearer ticket per connection, heartbeat, strict atomic ordered frames, RPC correlation, separate inbound/outbound ID namespaces, 64-entry prompt table, duplicates, wrong-method cancellation, late replies, unknown request `-32601`, close during mutation, false/malformed exclusive-submit and reconnect re-advertisement. +- [ ] Observe RED, implement actual contract in `docs/hermes/CONNECTION.md`, then run all Hermes JVM tests and document GREEN. No speculative retries; expose typed uncertain outcome after possible dispatch. +- [ ] Publish the exact API and focused evidence; independent scoped review before dependent code. + +### Task 2: Durable conversations, catalog, prompts and recovery + +**Files:** New JVM chat/catalog/history/journal models and tests in `android/hermes`; consume Task 1's published API. + +**Interfaces:** A screen-facing live workspace/chat repository exposes state flows for agents, sessions, transcript, real activity, prompts, connectivity, retained intents and drafts. Actions cover load/search/page/create/open, send/steer/queue/stop, answer/cancel prompts, rename/archive/restore/delete/fork, model/reasoning/slash controls and reconnect. A platform-neutral durable store supports atomic scoped cache/draft/journal transactions; persistence failure prevents dispatch. Publish exact API for Android composition. + +- [ ] Write failing cases for `source:bighelp`, persistent create key, distinct runtime/stored IDs, canonical Bot Chat merge, archived catalog and physical history pagination. +- [ ] Write failing reducer/admission cases for streaming before receipt, `streaming` admission versus `session.info running:false` terminal, tools and interims, active-turn steer, queued receipt, exact prompt ownership, unknown secure methods and cancellation. +- [ ] Write failing process-death/reconnect cases: journal before write, lost ACK never resend, create retry same key, canonical history/replay fallback, compaction successor, stale runtime/epoch, draft edits newer than sent intent, failed disk writes and explicit uncertainty review. +- [ ] Implement from `docs/hermes/CHAT.md` and current Swift domain code; run full JVM suite GREEN. Review focused diff; publish usable repository APIs, not just policy types. + +### Task 3: Everyday feature clients and capability discovery + +**Files:** JVM typed stock/plugin feature clients and tests under `android/hermes`; consume Task 1 HTTP/gateway and Task 2 identities. + +**Interfaces:** Typed models/actions for agents and instructions/avatar/model, workspace files and attachment transfer, Feed/Ideas/Goals and feedback, Projects/stock Git/Code, Kanban, scheduled tasks, Workflows/Dev Factory, Usage, Apps/connections, groups and supported voice control. Native extension context is per owner with feature gate, ETag and exact request-ID echo; optional absence is distinct from error. + +- [ ] Turn the inventory in `/tmp/bighelp-android-parity-inventory.md` into a durable parity matrix with actual call/decoder/acceptance references. Do not silently defer ordinary app features. +- [ ] Write failing request/response and ownership tests for every family used by the UI; cover native context normalization/correlation/conflict, missing feature, bounded payloads and unknown mutation readback. +- [ ] Implement documented everyday list/detail/write flows from `REFERENCE.md`, `EXTENSIONS.md`, `GROUPS_AND_DEVICE_TOOLS.md` and current Swift typed clients. Scope all file/agent/session/project/room IDs correctly. Readback validates mutations where contracted; no generic replay. +- [ ] Verify upload/download offsets/size/digest, edited-file conflict and stock Git project-worktree restrictions, groups durable event/idempotency/pending-action variants and voice allocation/result uncertainty. +- [ ] Full JVM GREEN, scoped review, published API and matrix dispositions. Missing host feature never becomes a fake success. + +### Task 4: Android secure persistence and complete live UI + +**Files:** `android/app/src/main/`, app tests, manifest/build dependencies as needed. Preserve demo behavior and shared design components. + +**Interfaces:** Android Keystore AES-GCM credential store implements Task 1 CAS and verifies readback; app-private atomic history/journal/draft store implements Task 2. A lifecycle ViewModel composes live repositories and shared menu/settings/navigation. Browser launch uses system browser with owned loopback callback. All UI actions call real typed clients. + +- [ ] Write failing state/storage tests for consent, add/select/remove/restore computers, cancelled sign-in owner, process-death drafts/journal, private HTTP, credential rotation and feature availability. +- [ ] Implement sign-in and saved hosts, real agent/Bot/session list, chat streaming/tools/prompts/secure input, slash/model/reasoning controls, active-turn controls, history paging/search and uncertainty review. +- [ ] Implement everyday feature screens from Task 3 with real list/detail/edit controls: agents/instructions, files/transfers/text editing, content/feedback, projects/Code/changes, Kanban, tasks/workflows, Usage and Apps. Keep unsupported rows truthful, host admin behind Nerd Mode, one menu and Settings. +- [ ] Add appearance/layout/mode and user identity preferences; readable Markdown, selectable output, stable reader position and keyboard behavior. Demo uses the same presentational components with labeled fixtures. +- [ ] Full app/core JVM checks, lint, debug/release assembly, focused source review and Terra actual-control verification before accepting the slice. + +### Task 5: Android media, groups, lifecycle and granted tools + +**Files:** Focused platform adapters/screens/tests under `android/app`, domain refinements only when required by observed integration. + +- [ ] Add file picker/share/open and incoming attachment/image presentation, bounded caches and permission handling. +- [ ] Add microphone permission/audio focus/recording/playback and real supported voice flows. Keep a lost voice result append uncertain, not replayed. Implement hosted group membership/chat/pending actions via actual advertised path; never fan out normal chats to fake a group. +- [ ] Add applicable Android device tools behind explicit persistent off-by-default grants and OS permissions; advertise only implemented operations. Keep Apple-only tools unavailable. Add supported Android notification delivery only with a proven server adapter; no APNs/FCM substitution. +- [ ] Verify lifecycle foreground recovery, stopped process restoration, sign-in preservation, host switching, cancelled prompts and media transfers. Test and review each affected boundary. + +### Task 6: Integrated parity acceptance and delivery + +**Files:** Android README, parity matrix, test fixtures/probes, existing PR/issue and final evidence records. + +- [ ] Use isolated real Hermes/plugin hosts from `/tmp/bighelp-android-disposable-host.md`, recorded source revisions and synthetic model. Never shared Hermes launchers or actual maintainer hosts. +- [ ] Terra/max installs exact APK and exercises open/password/browser/token sign-in, saved restore, create/resume/send/stream/steer/stop/prompts, history/restart/reconnect and host switch, files and all implemented everyday feature controls in light/dark. Record fixture versus actual-host boundaries and exact receipts. +- [ ] Run integrated checks, fix reproduced failures, one whole-branch review with scoped fix follow-up, repeat affected verification and reconcile every parity-matrix row. Unfinished ordinary workflows keep this task open. +- [ ] Update real PR title/body around the final application, source/evidence/limitations and model/harness footer. Commit and push logical changes, keep PR linked and maintainer merge/release authority. Stop owned temporary servers/emulator runtime; retain exact artifacts and installed toolchain. diff --git a/docs/superpowers/specs/2026-10-27-android-foundation-design.md b/docs/superpowers/specs/2026-10-27-android-foundation-design.md new file mode 100644 index 00000000..d4589b73 --- /dev/null +++ b/docs/superpowers/specs/2026-10-27-android-foundation-design.md @@ -0,0 +1,21 @@ +# Android foundation + +The Android app lives in `android/` in this repository, written in Kotlin with Jetpack Compose. It talks directly to the selected Hermes dashboard, using `docs/NATIVE_TRANSPORT.md` and its chapters as the integration contract. The Apple targets and notification services remain independently buildable. + +## First milestone + +Build a reproducible Android debug APK and a pure JVM Hermes module. The module owns endpoint validation, bounded atomic wire decoding, explicit connection ownership, readiness and capability gates. Its tests consume the repository's shared wire vectors directly. The app provides the AI data agreement, connection setup, a sessions list, agents, short Settings and an explicitly labeled demo mode. Live operations are offered only as their implementation and acceptance tests become available. Unsupported sign-in methods and uncertain outcomes stay visible and never trigger fallback or mutation replay. + +Use `app.bighelp.android` as the development application ID, with `.debug` on debug builds. This reserves nothing on Google Play; confirm the release identity before the first upload. Minimum Android API is 26; compile and target API are 36. Credentials belong in Android Keystore protected storage, excluded from backups and logs. No host request is sent before consent. HTTPS uses ordinary certificate validation; private HTTP requires explicit opt-in and endpoint validation. No credentialed redirects or ambient cookies. + +The first app milestone checks only public `/api/status` discovery. It does not collect credentials, save a sign-in, open a gateway or send a live turn. A discovered host is labeled as found, never connected. Keystore persistence arrives with authenticated connection support; the first milestone persists only consent and nonsecret preview preferences. + +## Boundaries + +`android/hermes` is Kotlin/JVM and owns protocol policy without Android dependencies. `android/app` owns platform storage, lifecycle, screens and demo composition. The pure module exposes typed endpoint and frame models. Readiness, authenticated health and exclusive submission are separate facts. A dispatched mutation without a receipt is uncertain, not failed, and is never automatically repeated. Session runtime IDs and durable stored IDs remain separate. + +The initial foundation is not full Android parity. Browser PKCE, reconnect/replay, durable submit recovery, attachments, live voice, groups, phone tools, FCM, Code mode and store release each require their own acceptance evidence. There are no default agent jobs, cloud sign-up dependency or production service deployments. + +## Evidence + +Run all 55 shared wire vectors and generated byte/count/depth boundaries, endpoint trust tests and scripted readiness/ownership tests. Build the APK and exercise demo controls in light and dark on a dedicated Android emulator if the platform is available. Record JVM, scripted HTTP/WebSocket, emulator, disposable Hermes host and physical-device evidence separately. Account registration may require the maintainer's direct sign-in, identity verification and payment; private information never enters this public repository. diff --git a/docs/superpowers/specs/2026-10-27-android-parity-design.md b/docs/superpowers/specs/2026-10-27-android-parity-design.md new file mode 100644 index 00000000..ba021fd3 --- /dev/null +++ b/docs/superpowers/specs/2026-10-27-android-parity-design.md @@ -0,0 +1,44 @@ +# Functioning Android app with everyday bighelp parity + +## Outcome and authority + +The requested outcome is a functioning end-to-end Android application close to the current Apple app, not another discovery-only preview. Continue the existing Kotlin/Jetpack Compose implementation in `android/`. Current Apple behavior, `DESIGN.md`, `docs/CHAT_INTERACTION_CONTRACT.md`, `docs/NATIVE_TRANSPORT.md` and its chapters are the reference. The earlier foundation is the starting point and remains a clearly labeled optional demo. + +The user has directed implementation and supplied the platform/model choices. Preserve those choices and the existing Ink direction; do not introduce another design selection gate or stop at an intermediate milestone. A checkpoint or PR is progress, not acceptance of a partial application. + +## Architecture + +`android/hermes` remains JVM-testable and owns authentication, ordered transport, domain clients, durable intent/recovery rules and feature decoding. `android/app` supplies Android Keystore encryption, protected atomic local storage, browser/audio/files/permissions/lifecycle adapters, observable app state and Compose presentation. Network results and persistence are bound to endpoint, exact principal and owner generation. Demo and live repositories implement the same screen-facing interfaces, while demo provenance remains explicit. + +Build on the already selected native Kotlin approach rather than changing frameworks or embedding the dashboard. Screens follow existing bighelp navigation and plain language. One menu, one Settings, searchable lists, readable chat and stable input take precedence over copying Apple-only visual effects. + +## Required workflows + +1. Add, save, select, reconnect and remove computers. Discover the advertised authentication mode. Support automatic dashboard bootstrap, explicit session/access tokens, password PKCE and browser PKCE without collecting browser cookies. Save credentials with Android Keystore encryption and verify rotating sign-in identity with single-flight compare-and-replace. Consent precedes all host access. +2. Load agents and durable sessions from the host, including canonical Bot Chats and archived sessions. Start and resume the exact agent/chat with `source: "bighelp"`, preserving runtime and stored identifiers independently. Search, rename, archive, restore, delete and select models/reasoning through real supported operations. +3. Send and stream real turns, display tools and terminal states, steer by default during active work, queue or stop when available, and show questions, approvals and secure requests. Register handlers before advertising them on every socket. Unknown requests fail explicitly. Acknowledgement means admission, not completion. +4. Preserve drafts, cached history and uncertainty across process death. Page canonical history, replay/catch up after interruption, keep reading position and composer stable, and never automatically resend an uncertain mutation. A refused send remains editable; a lost receipt remains reviewable. +5. Offer agents/Bots, configured workspace files and attachments, Feed/Ideas/Goals, Projects, Kanban, Workflows/Dev Factory, scheduled tasks, Usage and connected Apps using their real documented stock/plugin APIs. Implement everyday read/write/detail interactions and truthful supported/unsupported states; do not substitute raw JSON viewers for the product. Optional plugin capabilities are discovered from context and protected with its ETag/request-ID envelope. +6. Offer Code workflows for project/branch/worktree selection, launching chats in the exact folder, inspecting Changes and the supported Ship actions. Preserve ownership and confirmation semantics of the Apple client. +7. Add Android file picking/sharing, rendered incoming media, turn-based voice and supported live voice, hosted groups, permissions and applicable device tools with explicit grants. Android lifecycle recovery must work across background/foreground. Advertise only actually implemented platform capabilities. +8. Settings cover saved computers, appearance/layout/mode, identity, device access and advanced host tools under Nerd Mode. No cloud bighelp account or retired Link pairing. + +Platform-specific Apple surfaces (Watch, CarPlay, visionOS, Live Activities, Shortcuts, Health/Focus/AlarmKit) require honest Android equivalents or explicit platform boundaries. They do not justify omitting ordinary Android app workflows. Android push needs a real supported delivery adapter; never claim APNs registration works with an FCM token. Store verification remains a distribution gate and does not pause application implementation. + +## Invariants + +- Minimum API 26, target/compile 36; keep existing pinned toolchain unless a necessary change is justified. +- No host access before consent, credentials in URLs/logs/preferences, ambient cookies, credentialed redirects, disabled TLS checks or automatic mutation replay. +- Preserve deployment prefixes and independent proxy credentials. Public HTTP remains prohibited; private HTTP is explicit and typed. +- Wait for `gateway.ready`, authenticated health and actual exclusive-submit capability. No version allowlist. +- Strict bounded atomic frame decoding; ordered reader/writer, distinct inbound/outbound IDs, stale-owner fences, bounded prompt table and secure cancellation. +- Journal before dispatch; persistence failure prevents send. Same text is not proof of acceptance. Create retries retain the creation key; ordinary submits have no invented idempotency guarantee. +- Native extensions require advertised feature, current context and exact response correlation. Missing fields are tolerated as documented; unknown fields never break unrelated screens. +- Real data only outside labeled demo. No invented progress, fake tools or canned replies on the live path. No AI spending from default jobs. +- Public repository artifacts contain synthetic data only. Use isolated disposable Hermes clones/homes and synthetic models for verification. Never contact maintainer hosts or restart shared gateways. + +## Verification and completion + +Each independently testable task gets meaningful failing-before/fixed-after tests and a focused independent review. Build and lint the integrated app. Exercise real controls in light/dark on Android with exact installed APK identity, including connection, live send/stream, active-turn controls, prompts, files, navigation, restart/background and recovery. Run isolated stock Hermes/plugin processes with recorded source revisions and synthetic model responses, distinguishing those from scripted socket tests and demo data. Retain screenshots and receipts outside the public repository. + +Maintain an explicit parity/acceptance matrix through implementation. A row is complete only when its implementation and appropriate evidence exist; capability absence and platform boundaries are separate dispositions. Do not label the outcome complete merely because the initial chat works, tests pass or the preview builds. Publish logical commits and a real linked PR; the maintainer merges and controls release. Identity documents/payment remain directly in Google.