From 756833d2ebd3a389573d7f4c7bdd4f3308be5811 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:28:14 -0500 Subject: [PATCH 01/18] Start the native Android preview with tested Hermes framing --- .github/workflows/android.yml | 42 ++ README.md | 2 + android/.gitattributes | 2 + android/.gitignore | 7 + android/README.md | 50 +++ android/app/build.gradle.kts | 57 +++ android/app/src/main/AndroidManifest.xml | 23 ++ .../app/bighelp/android/AgentsScreen.kt | 75 ++++ .../kotlin/app/bighelp/android/AppState.kt | 81 ++++ .../kotlin/app/bighelp/android/BighelpApp.kt | 83 ++++ .../app/bighelp/android/BighelpAppModel.kt | 233 +++++++++++ .../app/bighelp/android/BighelpTheme.kt | 104 +++++ .../kotlin/app/bighelp/android/ChatScreen.kt | 291 ++++++++++++++ .../kotlin/app/bighelp/android/Components.kt | 215 +++++++++++ .../kotlin/app/bighelp/android/DemoContent.kt | 90 +++++ .../app/bighelp/android/HostDiscovery.kt | 109 ++++++ .../kotlin/app/bighelp/android/HostStatus.kt | 125 ++++++ .../app/bighelp/android/MainActivity.kt | 54 +++ .../kotlin/app/bighelp/android/NoodleMark.kt | 39 ++ .../kotlin/app/bighelp/android/PlacesMenu.kt | 50 +++ .../app/bighelp/android/PreviewPreferences.kt | 34 ++ .../app/bighelp/android/SessionsScreen.kt | 130 +++++++ .../app/bighelp/android/SettingsScreen.kt | 109 ++++++ .../kotlin/app/bighelp/android/SetupScreen.kt | 205 ++++++++++ .../app/bighelp/android/WelcomeScreens.kt | 95 +++++ .../res/drawable/ic_launcher_foreground.xml | 20 + .../main/res/mipmap-anydpi/ic_launcher.xml | 6 + .../app/src/main/res/values-night/styles.xml | 9 + android/app/src/main/res/values/colors.xml | 5 + android/app/src/main/res/values/styles.xml | 9 + .../main/res/xml/data_extraction_rules.xml | 18 + .../main/res/xml/network_security_config.xml | 16 + .../app/bighelp/android/AppModelTest.kt | 361 ++++++++++++++++++ .../app/bighelp/android/HostDiscoveryTest.kt | 63 +++ .../app/bighelp/android/HostStatusTest.kt | 76 ++++ android/build.gradle.kts | 6 + android/gradle.properties | 3 + android/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43705 bytes .../gradle/wrapper/gradle-wrapper.properties | 8 + android/gradlew | 251 ++++++++++++ android/gradlew.bat | 94 +++++ android/hermes/build.gradle.kts | 16 + .../app/bighelp/hermes/HermesAddress.kt | 94 +++++ .../app/bighelp/hermes/HermesConnection.kt | 194 ++++++++++ .../app/bighelp/hermes/HermesEndpoint.kt | 158 ++++++++ .../kotlin/app/bighelp/hermes/HermesWire.kt | 272 +++++++++++++ .../kotlin/app/bighelp/hermes/StrictJson.kt | 209 ++++++++++ .../bighelp/hermes/HermesConnectionTest.kt | 202 ++++++++++ .../hermes/HermesEndpointContractTest.kt | 191 +++++++++ .../app/bighelp/hermes/HermesEndpointTest.kt | 39 ++ .../bighelp/hermes/HermesWireLimitsTest.kt | 191 +++++++++ .../hermes/HermesWireStrictnessTest.kt | 165 ++++++++ .../app/bighelp/hermes/HermesWireTest.kt | 58 +++ .../app/bighelp/hermes/StrictJsonTest.kt | 30 ++ android/settings.gradle.kts | 17 + .../plans/2026-10-27-android-foundation.md | 64 ++++ .../2026-10-27-android-foundation-design.md | 21 + 57 files changed, 5171 insertions(+) create mode 100644 .github/workflows/android.yml create mode 100644 android/.gitattributes create mode 100644 android/.gitignore create mode 100644 android/README.md create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/kotlin/app/bighelp/android/AgentsScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/AppState.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/BighelpTheme.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/Components.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/DemoContent.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/HostStatus.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/NoodleMark.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/PlacesMenu.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt create mode 100644 android/app/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 android/app/src/main/res/mipmap-anydpi/ic_launcher.xml create mode 100644 android/app/src/main/res/values-night/styles.xml create mode 100644 android/app/src/main/res/values/colors.xml create mode 100644 android/app/src/main/res/values/styles.xml create mode 100644 android/app/src/main/res/xml/data_extraction_rules.xml create mode 100644 android/app/src/main/res/xml/network_security_config.xml create mode 100644 android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/HostStatusTest.kt create mode 100644 android/build.gradle.kts create mode 100644 android/gradle.properties create mode 100644 android/gradle/wrapper/gradle-wrapper.jar create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100755 android/gradlew create mode 100644 android/gradlew.bat create mode 100644 android/hermes/build.gradle.kts create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesConnection.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt create mode 100644 android/settings.gradle.kts create mode 100644 docs/superpowers/plans/2026-10-27-android-foundation.md create mode 100644 docs/superpowers/specs/2026-10-27-android-foundation-design.md diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 00000000..4860e921 --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,42 @@ +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-latest + defaults: + run: + working-directory: android + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: android-actions/setup-android@v3 + - uses: gradle/actions/setup-gradle@v4 + - 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..e5abaf5b --- /dev/null +++ b/android/README.md @@ -0,0 +1,50 @@ +# 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. HTTPS uses the platform's certificate checks. + +### 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: no credentials, no redirect, malformed and oversized bodies). 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. + +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..8ce2ef7a --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,57 @@ +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") +} 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/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..6684ee00 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/AppState.kt @@ -0,0 +1,81 @@ +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 + data class Chat(val sessionId: 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 + 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, +) + +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, +) { + 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..01a626be --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt @@ -0,0 +1,83 @@ +package app.bighelp.android + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.lifecycle.compose.collectAsStateWithLifecycle + +/** + * 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. + */ +@OptIn(ExperimentalComposeUiApi::class) +@Composable +fun BighelpApp( + model: BighelpAppModel, + versionName: String, + onOpenPrivacyPolicy: () -> Unit, +) { + val state by model.state.collectAsStateWithLifecycle() + val dark = when (state.appearance) { + Appearance.Automatic -> isSystemInDarkTheme() + Appearance.Light -> false + Appearance.Dark -> true + } + 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() } + val demo = state.demo + when (val route = state.route) { + Route.Welcome -> WelcomeScreen(onTryDemo = model::tryDemo, onConnect = model::connectComputer) + 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, + ) + // The demo places exist only while the demo does. + Route.Sessions -> demo?.let { + SessionsScreen(it, model::setSearch, model::openChat, model::startNewChat, model::openPlace) + } + Route.Agents -> demo?.let { AgentsScreen(it, model::selectAgent, model::startNewChat, model::openPlace) } + Route.Settings -> SettingsScreen( + appearance = state.appearance, + consentGranted = state.consentGranted, + versionName = versionName, + onAppearance = model::setAppearance, + onPrivacyPolicy = onOpenPrivacyPolicy, + onLeaveDemo = model::leaveDemo, + onOpenPlace = model::openPlace, + ) + 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) }, + ) + } + } + } + } +} 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..03899b28 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt @@ -0,0 +1,233 @@ +package app.bighelp.android + +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesEndpointException +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.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. + */ +class BighelpAppModel( + private val preferences: PreviewPreferences, + private val hostChecker: HostChecker, + private val scope: CoroutineScope, +) { + private val mutableState = MutableStateFlow( + AppState(consentGranted = preferences.aiDataAgreed, appearance = preferences.appearance), + ) + val state: StateFlow = mutableState.asStateFlow() + + private var checkJob: Job? = null + private var checkGeneration = 0 + + // -- 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 + if (stack.last() == Route.Setup) dropCheck() + 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) { + if (mutableState.value.demo == null) return + if (place != Route.Sessions && place != Route.Agents && place != Route.Settings) return + 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 + mutableState.update { 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 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 + } + + 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() + + 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) 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() + return if (line.length <= MAXIMUM_TITLE) line else line.take(MAXIMUM_TITLE).trimEnd() + "…" + } + + // -- settings ----------------------------------------------------------------------------- + + fun setAppearance(appearance: Appearance) { + preferences.appearance = appearance + mutableState.update { it.copy(appearance = appearance) } + } + + companion object { + const val NEW_CHAT_TITLE = "New chat" + private const val MAXIMUM_TITLE = 40 + } +} 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..d3e8d541 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt @@ -0,0 +1,291 @@ +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 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 reader owns the scroll position: nothing moves it while they read history, Send always + * brings the newest message into view, and a Latest button appears whenever they are away from the end. + * 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) + val messages = session.messages + val scope = rememberCoroutineScope() + val listState = rememberLazyListState(initialFirstVisibleItemIndex = messages.lastIndex.coerceAtLeast(0)) + val lastIndex by rememberUpdatedState(messages.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 + } + } + // Sending (the only way this list grows) always shows the new messages, even from older history. + val lastId = messages.lastOrNull()?.id + var shownLastId by rememberSaveable { mutableStateOf(lastId) } + LaunchedEffect(lastId) { + if (lastId != shownLastId) { + shownLastId = lastId + followTail = true + listState.scrollToLatest(lastIndex, animated = ValueAnimator.areAnimatorsEnabled()) + } + } + // Keep the end in view when the keyboard opens or closes, but only for a reader who is at the end. + LaunchedEffect(listState) { + snapshotFlow { listState.layoutInfo.viewportSize.height }.collect { + if (followTail && lastIndex >= 0) listState.scrollToLatest(lastIndex, animated = false) + } + } + val awayFromLatest by remember { derivedStateOf { listState.canScrollForward } } + + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.chat")) { + ChatHeader(session.title, agent, onBack) + Box(Modifier.weight(1f).fillMaxWidth()) { + LazyColumn( + state = listState, + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxSize().testTag("chat.messages"), + ) { + if (messages.isEmpty()) { + item(key = "empty") { EmptyChatNote(agent) } + } + items(messages, key = { it.id }) { message -> MessageRow(message) } + } + if (awayFromLatest) { + JumpToLatest( + onClick = { + followTail = true + scope.launch { listState.scrollToLatest(lastIndex, animated = ValueAnimator.areAnimatorsEnabled()) } + }, + modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp), + ) + } + } + // Keyed by chat, so a draft is read once when the chat opens and then owned by the box while typing. + Composer( + key = session.id, + initialDraft = demo.drafts[session.id].orEmpty(), + agentName = agent.name, + onDraft = onDraft, + onSend = onSend, + ) + } +} + +/** 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) { + val fromUser = message.fromUser + Row( + Modifier.fillMaxWidth().testTag("chat.message.${message.id}"), + 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 (message.isExample) { + Text( + "Example reply, not from an agent", + 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 { + Text(message.text, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) + } + } + } + } +} + +@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..da70b8e0 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt @@ -0,0 +1,109 @@ +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. 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") + .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/MainActivity.kt b/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt new file mode 100644 index 00000000..3379e641 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt @@ -0,0 +1,54 @@ +package app.bighelp.android + +import android.content.ActivityNotFoundException +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 + +/** Keeps the app's state across rotation. The model itself is plain Kotlin, tested without Android. */ +class BighelpViewModel(preferences: PreviewPreferences, hostChecker: HostChecker) : ViewModel() { + val model = BighelpAppModel(preferences, hostChecker, viewModelScope) +} + +class MainActivity : ComponentActivity() { + private val viewModel: BighelpViewModel by viewModels { + object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class, extras: CreationExtras): T = + BighelpViewModel(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/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..aeed3277 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt @@ -0,0 +1,34 @@ +package app.bighelp.android + +import android.content.Context +import androidx.core.content.edit + +/** + * The only things this milestone keeps on the device: the one-time AI data agreement and the look. No + * credential, address or chat is stored. Backup and device transfer are excluded in the manifest. + */ +interface PreviewPreferences { + var aiDataAgreed: Boolean + var appearance: Appearance +} + +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) } + + 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" + } +} 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..3c033d4f --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt @@ -0,0 +1,130 @@ +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) + val preview = when { + draft != null -> "Draft: ${draft.trim().replace('\n', ' ')}" + session.messages.isEmpty() -> "No messages yet" + else -> session.messages.last().text.replace('\n', ' ') + } + Text( + preview, + style = MaterialTheme.typography.bodyMedium, + color = if (draft != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = if (draft != null) 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..8c75cbc9 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt @@ -0,0 +1,109 @@ +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.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: look, data agreement, the demo, and what this build is. */ +@Composable +fun SettingsScreen( + appearance: Appearance, + consentGranted: Boolean, + versionName: String, + onAppearance: (Appearance) -> Unit, + onPrivacyPolicy: () -> Unit, + onLeaveDemo: () -> Unit, + onOpenPlace: (Route) -> Unit, +) { + Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.settings")) { + ScreenHeader("Settings", leading = { PlacesMenu(current = Route.Settings, onOpen = onOpenPlace) }) + 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), + ) { + 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 asked 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") + } + + 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. This preview has the demo and a check that a Hermes " + + "computer answers. Signing in and chatting with your computer come next.", + 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..8cf1493c --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt @@ -0,0 +1,205 @@ +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.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.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.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.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import app.bighelp.hermes.HermesEndpointException + +/** + * Asks a typed address whether a Hermes computer answers. The result says "found", never "connected": + * this milestone collects no password or token and opens no chat. + */ +@Composable +fun SetupScreen( + setup: SetupState, + onBack: () -> Unit, + onAddress: (String) -> Unit, + onAllowPrivateHttp: (Boolean) -> Unit, + onCheck: () -> Unit, + onCancel: () -> Unit, + onTryDemo: () -> 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 (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, onCheck = onCheck, onTryDemo = onTryDemo) + 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, onCheck: () -> Unit, onTryDemo: () -> Unit) { + when (discovery) { + DiscoveryState.Idle, DiscoveryState.Checking -> Unit + + is DiscoveryState.AddressProblem -> ResultCard( + title = "That address can't be used", + body = when (discovery.reason) { + HermesEndpointException.Reason.PlaintextNotAllowed -> + "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.") + } + append("\n\nThis is not a connection. Signing in and chatting come in a later update; ") + append("this preview sent no password or chat.") + }, + tag = "setup.result.found", + ) { + InkOutlinedButton("Check again", onCheck, tag = "setup.check-again") + 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), + modifier = Modifier.fillMaxWidth().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() + } + } +} 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..5e62dc7a --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt @@ -0,0 +1,95 @@ +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 checks a real computer. */ +@Composable +fun WelcomeScreen(onTryDemo: () -> Unit, onConnect: () -> 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(40.dp)) + 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( + "Check that your Hermes computer answers. Chatting with it comes in a later update.", + 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( + "Right now bighelp only asks whether your computer answers. It sends no password and no chat.", + 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/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/AppModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt new file mode 100644 index 00000000..93ac7e16 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt @@ -0,0 +1,361 @@ +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 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..d6afb80b --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt @@ -0,0 +1,63 @@ +package app.bighelp.android + +import app.bighelp.hermes.HermesEndpoint +import kotlinx.coroutines.test.runTest +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +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("/hermes/api/status", request.path) + 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 malformedOversizedOrNonJsonResponsesStayUnavailable() = runTest { + listOf( + json("""{"auth_required":"false"}"""), + json("""{"auth_required":false,"auth_flows":["native_pkce","native_pkce"]}"""), + json("""{"auth_required":false,"auth_flows":null}""" + "x".repeat(16_384)), + MockResponse().setHeader("Content-Type", "text/html").setBody("Private proxy diagnostic"), + ).forEach { response -> + host.enqueue(response) + 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) + } + + private fun json(body: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(body) +} 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/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 0000000000000000000000000000000000000000..9bbc975c742b298b441bfb90dbc124400a3751b9 GIT binary patch literal 43705 zcma&Obx`DOvL%eWOXJW;V64viP??$)@wHcsJ68)>bJS6*&iHnskXE8MjvIPVl|FrmV}Npeql07fCw6`pw`0s zGauF(<*@v{3t!qoUU*=j)6;|-(yg@jvDx&fV^trtZt27?4Tkn729qrItVh@PMwG5$ z+oXHSPM??iHZ!cVP~gYact-CwV`}~Q+R}PPNRy+T-geK+>fHrijpllon_F4N{@b-} z1M0=a!VbVmJM8Xk@NRv)m&aRYN}FSJ{LS;}2ArQ5baSjfy40l@T5)1r-^0fAU6f_} zzScst%$Nd-^ElV~H0TetQhMc%S{}Q4lssln=|;LG?Ulo}*mhg8YvBAUY7YFdXs~vv zv~{duzVw%C#GxkBwX=TYp1Dh*Uaum2?RmsvPaLlzO^fIJ`L?&OV?Y&kKj~^kWC`Ly zfL-}J^4a0Ojuz9O{jUbIS;^JatJ5+YNNHe}6nG9Yd6P-lJiK2ms)A^xq^H2fKrTF) zp!6=`Ece~57>^9(RA4OB9;f1FAhV%zVss%#rDq$9ZW3N2cXC7dMz;|UcRFecBm`DA z1pCO!#6zKp#@mx{2>Qcme8y$Qg_gnA%(`Vtg3ccwgb~D(&@y8#Jg8nNYW*-P{_M#E zZ|wCsQoO1(iIKd-2B9xzI}?l#Q@G5d$m1Lfh0q;iS5FDQ&9_2X-H)VDKA*fa{b(sV zL--krNCXibi1+*C2;4qVjb0KWUVGjjRT{A}Q*!cFmj0tRip2ra>WYJ>ZK4C|V~RYs z6;~+*)5F^x^aQqk9tjh)L;DOLlD8j+0<>kHc8MN|68PxQV`tJFbgxSfq-}b(_h`luA0&;Vk<@51i0 z_cu6{_*=vlvYbKjDawLw+t^H?OV00_73Cn3goU5?})UYFuoSX6Xqw;TKcrsc|r# z$sMWYl@cs#SVopO$hpHZ)cdU-+Ui%z&Sa#lMI~zWW@vE%QDh@bTe0&V9nL>4Et9`N zGT8(X{l@A~loDx}BDz`m6@tLv@$mTlVJ;4MGuj!;9Y=%;;_kj#o8n5tX%@M)2I@}u z_{I!^7N1BxW9`g&Z+K#lZ@7_dXdsqp{W9_`)zgZ=sD~%WS5s$`7z#XR!Lfy(4se(m zR@a3twgMs19!-c4jh`PfpJOSU;vShBKD|I0@rmv_x|+ogqslnLLOepJpPMOxhRb*i zGHkwf#?ylQ@k9QJL?!}MY4i7joSzMcEhrDKJH&?2v{-tgCqJe+Y0njl7HYff z{&~M;JUXVR$qM1FPucIEY(IBAuCHC@^~QG6O!dAjzQBxDOR~lJEr4KS9R*idQ^p{D zS#%NQADGbAH~6wAt}(1=Uff-1O#ITe)31zCL$e9~{w)gx)g>?zFE{Bc9nJT6xR!i8 z)l)~9&~zSZTHk{?iQL^MQo$wLi}`B*qnvUy+Y*jEraZMnEhuj`Fu+>b5xD1_Tp z)8|wedv42#3AZUL7x&G@p@&zcUvPkvg=YJS6?1B7ZEXr4b>M+9Gli$gK-Sgh{O@>q7TUg+H zNJj`6q#O@>4HpPJEHvNij`sYW&u%#=215HKNg;C!0#hH1vlO5+dFq9& zS)8{5_%hz?#D#wn&nm@aB?1_|@kpA@{%jYcs{K%$a4W{k@F zPyTav?jb;F(|GaZhm6&M#g|`ckO+|mCtAU)5_(hn&Ogd z9Ku}orOMu@K^Ac>eRh3+0-y^F`j^noa*OkS3p^tLV`TY$F$cPXZJ48!xz1d7%vfA( zUx2+sDPqHfiD-_wJDb38K^LtpN2B0w=$A10z%F9f_P2aDX63w7zDG5CekVQJGy18I zB!tI`6rZr7TK10L(8bpiaQ>S@b7r_u@lh^vakd0e6USWw7W%d_Ob%M!a`K>#I3r-w zo2^+9Y)Sb?P9)x0iA#^ns+Kp{JFF|$09jb6ZS2}_<-=$?^#IUo5;g`4ICZknr!_aJ zd73%QP^e-$%Xjt|28xM}ftD|V@76V_qvNu#?Mt*A-OV{E4_zC4Ymo|(cb+w^`Wv== z>)c%_U0w`d$^`lZQp@midD89ta_qTJW~5lRrIVwjRG_9aRiQGug%f3p@;*%Y@J5uQ|#dJ+P{Omc`d2VR)DXM*=ukjVqIpkb<9gn9{*+&#p)Ek zN=4zwNWHF~=GqcLkd!q0p(S2_K=Q`$whZ}r@ec_cb9hhg9a z6CE=1n8Q;hC?;ujo0numJBSYY6)GTq^=kB~`-qE*h%*V6-ip=c4+Yqs*7C@@b4YAi zuLjsmD!5M7r7d5ZPe>4$;iv|zq=9=;B$lI|xuAJwi~j~^Wuv!Qj2iEPWjh9Z&#+G>lZQpZ@(xfBrhc{rlLwOC;optJZDj4Xfu3$u6rt_=YY0~lxoy~fq=*L_&RmD7dZWBUmY&12S;(Ui^y zBpHR0?Gk|`U&CooNm_(kkO~pK+cC%uVh^cnNn)MZjF@l{_bvn4`Jc}8QwC5_)k$zs zM2qW1Zda%bIgY^3NcfL)9ug`05r5c%8ck)J6{fluBQhVE>h+IA&Kb}~$55m-^c1S3 zJMXGlOk+01qTQUFlh5Jc3xq|7McY$nCs$5=`8Y;|il#Ypb{O9}GJZD8!kYh{TKqs@ z-mQn1K4q$yGeyMcryHQgD6Ra<6^5V(>6_qg`3uxbl|T&cJVA*M_+OC#>w(xL`RoPQ zf1ZCI3G%;o-x>RzO!mc}K!XX{1rih0$~9XeczHgHdPfL}4IPi~5EV#ZcT9 zdgkB3+NPbybS-d;{8%bZW^U+x@Ak+uw;a5JrZH!WbNvl!b~r4*vs#he^bqz`W93PkZna2oYO9dBrKh2QCWt{dGOw)%Su%1bIjtp4dKjZ^ zWfhb$M0MQiDa4)9rkip9DaH0_tv=XxNm>6MKeWv>`KNk@QVkp$Lhq_~>M6S$oliq2 zU6i7bK;TY)m>-}X7hDTie>cc$J|`*}t=MAMfWIALRh2=O{L57{#fA_9LMnrV(HrN6 zG0K_P5^#$eKt{J|#l~U0WN_3)p^LLY(XEqes0OvI?3)GTNY&S13X+9`6PLVFRf8K) z9x@c|2T72+-KOm|kZ@j4EDDec>03FdgQlJ!&FbUQQH+nU^=U3Jyrgu97&#-W4C*;_ z(WacjhBDp@&Yon<9(BWPb;Q?Kc0gR5ZH~aRNkPAWbDY!FiYVSu!~Ss^9067|JCrZk z-{Rn2KEBR|Wti_iy) zXnh2wiU5Yz2L!W{{_#LwNWXeNPHkF=jjXmHC@n*oiz zIoM~Wvo^T@@t!QQW?Ujql-GBOlnB|HjN@x~K8z)c(X}%%5Zcux09vC8=@tvgY>czq z3D(U&FiETaN9aP}FDP3ZSIXIffq>M3{~eTB{uauL07oYiM=~K(XA{SN!rJLyXeC+Y zOdeebgHOc2aCIgC=8>-Q>zfuXV*=a&gp{l#E@K|{qft@YtO>xaF>O7sZz%8);e86? z+jJlFB{0fu6%8ew^_<+v>>%6eB8|t*_v7gb{x=vLLQYJKo;p7^o9!9A1)fZZ8i#ZU z<|E?bZakjkEV8xGi?n+{Xh3EgFKdM^;4D;5fHmc04PI>6oU>>WuLy6jgpPhf8$K4M zjJo*MbN0rZbZ!5DmoC^@hbqXiP^1l7I5;Wtp2i9Jkh+KtDJoXP0O8qmN;Sp(+%upX zAxXs*qlr(ck+-QG_mMx?hQNXVV~LT{$Q$ShX+&x?Q7v z@8t|UDylH6@RZ?WsMVd3B0z5zf50BP6U<&X_}+y3uJ0c5OD}+J&2T8}A%2Hu#Nt_4 zoOoTI$A!hQ<2pk5wfZDv+7Z{yo+Etqry=$!*pvYyS+kA4xnJ~3b~TBmA8Qd){w_bE zqDaLIjnU8m$wG#&T!}{e0qmHHipA{$j`%KN{&#_Kmjd&#X-hQN+ju$5Ms$iHj4r?) z&5m8tI}L$ih&95AjQ9EDfPKSmMj-@j?Q+h~C3<|Lg2zVtfKz=ft{YaQ1i6Om&EMll zzov%MsjSg=u^%EfnO+W}@)O6u0LwoX709h3Cxdc2Rwgjd%LLTChQvHZ+y<1q6kbJXj3_pq1&MBE{8 zd;aFotyW>4WHB{JSD8Z9M@jBitC1RF;!B8;Rf-B4nOiVbGlh9w51(8WjL&e{_iXN( zAvuMDIm_>L?rJPxc>S`bqC|W$njA0MKWa?V$u6mN@PLKYqak!bR!b%c^ze(M`ec(x zv500337YCT4gO3+9>oVIJLv$pkf`01S(DUM+4u!HQob|IFHJHm#>eb#eB1X5;bMc| z>QA4Zv}$S?fWg~31?Lr(C>MKhZg>gplRm`2WZ--iw%&&YlneQYY|PXl;_4*>vkp;I z$VYTZq|B*(3(y17#@ud@o)XUZPYN*rStQg5U1Sm2gM}7hf_G<>*T%6ebK*tF(kbJc zNPH4*xMnJNgw!ff{YXrhL&V$6`ylY={qT_xg9znQWw9>PlG~IbhnpsG_94Kk_(V-o&v7#F znra%uD-}KOX2dkak**hJnZZQyp#ERyyV^lNe!Qrg=VHiyr7*%j#PMvZMuYNE8o;JM zGrnDWmGGy)(UX{rLzJ*QEBd(VwMBXnJ@>*F8eOFy|FK*Vi0tYDw;#E zu#6eS;%Nm2KY+7dHGT3m{TM7sl=z8|V0e!DzEkY-RG8vTWDdSQFE|?+&FYA146@|y zV(JP>LWL;TSL6rao@W5fWqM1-xr$gRci#RQV2DX-x4@`w{uEUgoH4G|`J%H!N?*Qn zy~rjzuf(E7E!A9R2bSF|{{U(zO+;e29K_dGmC^p7MCP!=Bzq@}&AdF5=rtCwka zTT1A?5o}i*sXCsRXBt)`?nOL$zxuP3i*rm3Gmbmr6}9HCLvL*45d|(zP;q&(v%}S5yBmRVdYQQ24zh z6qL2<2>StU$_Ft29IyF!6=!@;tW=o8vNzVy*hh}XhZhUbxa&;9~woye<_YmkUZ)S?PW{7t; zmr%({tBlRLx=ffLd60`e{PQR3NUniWN2W^~7Sy~MPJ>A#!6PLnlw7O0(`=PgA}JLZ ztqhiNcKvobCcBel2 z-N82?4-()eGOisnWcQ9Wp23|ybG?*g!2j#>m3~0__IX1o%dG4b;VF@^B+mRgKx|ij zWr5G4jiRy}5n*(qu!W`y54Y*t8g`$YrjSunUmOsqykYB4-D(*(A~?QpuFWh;)A;5= zPl|=x+-w&H9B7EZGjUMqXT}MkcSfF}bHeRFLttu!vHD{Aq)3HVhvtZY^&-lxYb2%` zDXk7>V#WzPfJs6u{?ZhXpsMdm3kZscOc<^P&e&684Rc1-d=+=VOB)NR;{?0NjTl~D z1MXak$#X4{VNJyD$b;U~Q@;zlGoPc@ny!u7Pe;N2l4;i8Q=8>R3H{>HU(z z%hV2?rSinAg6&wuv1DmXok`5@a3@H0BrqsF~L$pRYHNEXXuRIWom0l zR9hrZpn1LoYc+G@q@VsFyMDNX;>_Vf%4>6$Y@j;KSK#g)TZRmjJxB!_NmUMTY(cAV zmewn7H{z`M3^Z& z2O$pWlDuZHAQJ{xjA}B;fuojAj8WxhO}_9>qd0|p0nBXS6IIRMX|8Qa!YDD{9NYYK z%JZrk2!Ss(Ra@NRW<7U#%8SZdWMFDU@;q<}%F{|6n#Y|?FaBgV$7!@|=NSVoxlJI4G-G(rn}bh|?mKkaBF$-Yr zA;t0r?^5Nz;u6gwxURapQ0$(-su(S+24Ffmx-aP(@8d>GhMtC5x*iEXIKthE*mk$` zOj!Uri|EAb4>03C1xaC#(q_I<;t}U7;1JqISVHz3tO{) zD(Yu@=>I9FDmDtUiWt81;BeaU{_=es^#QI7>uYl@e$$lGeZ~Q(f$?^3>$<<{n`Bn$ zn8bamZlL@6r^RZHV_c5WV7m2(G6X|OI!+04eAnNA5=0v1Z3lxml2#p~Zo57ri;4>;#16sSXXEK#QlH>=b$inEH0`G#<_ zvp;{+iY)BgX$R!`HmB{S&1TrS=V;*5SB$7*&%4rf_2wQS2ed2E%Wtz@y$4ecq4w<) z-?1vz_&u>s?BMrCQG6t9;t&gvYz;@K@$k!Zi=`tgpw*v-#U1Pxy%S9%52`uf$XMv~ zU}7FR5L4F<#9i%$P=t29nX9VBVv)-y7S$ZW;gmMVBvT$BT8d}B#XV^@;wXErJ-W2A zA=JftQRL>vNO(!n4mcd3O27bHYZD!a0kI)6b4hzzL9)l-OqWn)a~{VP;=Uo|D~?AY z#8grAAASNOkFMbRDdlqVUfB;GIS-B-_YXNlT_8~a|LvRMVXf!<^uy;)d$^OR(u)!) zHHH=FqJF-*BXif9uP~`SXlt0pYx|W&7jQnCbjy|8b-i>NWb@!6bx;1L&$v&+!%9BZ z0nN-l`&}xvv|wwxmC-ZmoFT_B#BzgQZxtm|4N+|;+(YW&Jtj^g!)iqPG++Z%x0LmqnF875%Ry&2QcCamx!T@FgE@H zN39P6e#I5y6Yl&K4eUP{^biV`u9{&CiCG#U6xgGRQr)zew;Z%x+ z-gC>y%gvx|dM=OrO`N@P+h2klPtbYvjS!mNnk4yE0+I&YrSRi?F^plh}hIp_+OKd#o7ID;b;%*c0ES z!J))9D&YufGIvNVwT|qsGWiZAwFODugFQ$VsNS%gMi8OJ#i${a4!E3<-4Jj<9SdSY z&xe|D0V1c`dZv+$8>(}RE|zL{E3 z-$5Anhp#7}oO(xm#}tF+W=KE*3(xxKxhBt-uuJP}`_K#0A< zE%rhMg?=b$ot^i@BhE3&)bNBpt1V*O`g?8hhcsV-n#=|9wGCOYt8`^#T&H7{U`yt2 z{l9Xl5CVsE=`)w4A^%PbIR6uG_5Ww9k`=q<@t9Bu662;o{8PTjDBzzbY#tL;$wrpjONqZ{^Ds4oanFm~uyPm#y1Ll3(H57YDWk9TlC zq;kebC!e=`FU&q2ojmz~GeLxaJHfs0#F%c(i+~gg$#$XOHIi@1mA72g2pFEdZSvp}m0zgQb5u2?tSRp#oo!bp`FP}< zaK4iuMpH+Jg{bb7n9N6eR*NZfgL7QiLxI zk6{uKr>xxJ42sR%bJ%m8QgrL|fzo9@?9eQiMW8O`j3teoO_R8cXPe_XiLnlYkE3U4 zN!^F)Z4ZWcA8gekEPLtFqX-Q~)te`LZnJK_pgdKs)Dp50 zdUq)JjlJeELskKg^6KY!sIou-HUnSFRsqG^lsHuRs`Z{f(Ti9eyd3cwu*Kxp?Ws7l z3cN>hGPXTnQK@qBgqz(n*qdJ2wbafELi?b90fK~+#XIkFGU4+HihnWq;{{)1J zv*Txl@GlnIMOjzjA1z%g?GsB2(6Zb-8fooT*8b0KF2CdsIw}~Hir$d3TdVHRx1m3c z4C3#h@1Xi@{t4zge-#B6jo*ChO%s-R%+9%-E|y<*4;L>$766RiygaLR?X%izyqMXA zb|N=Z-0PSFeH;W6aQ3(5VZWVC>5Ibgi&cj*c%_3=o#VyUJv* zM&bjyFOzlaFq;ZW(q?|yyi|_zS%oIuH^T*MZ6NNXBj;&yM3eQ7!CqXY?`7+*+GN47 zNR#%*ZH<^x{(0@hS8l{seisY~IE*)BD+R6^OJX}<2HRzo^fC$n>#yTOAZbk4%=Bei=JEe=o$jm`or0YDw*G?d> z=i$eEL7^}_?UI^9$;1Tn9b>$KOM@NAnvWrcru)r`?LodV%lz55O3y(%FqN;cKgj7t zlJ7BmLTQ*NDX#uelGbCY>k+&H*iSK?x-{w;f5G%%!^e4QT9z<_0vHbXW^MLR} zeC*jezrU|{*_F`I0mi)9=sUj^G03i@MjXx@ePv@(Udt2CCXVOJhRh4yp~fpn>ssHZ z?k(C>2uOMWKW5FVsBo#Nk!oqYbL`?#i~#!{3w^qmCto05uS|hKkT+iPrC-}hU_nbL zO622#mJupB21nChpime}&M1+whF2XM?prT-Vv)|EjWYK(yGYwJLRRMCkx;nMSpu?0 zNwa*{0n+Yg6=SR3-S&;vq=-lRqN`s9~#)OOaIcy3GZ&~l4g@2h| zThAN#=dh{3UN7Xil;nb8@%)wx5t!l z0RSe_yJQ+_y#qEYy$B)m2yDlul^|m9V2Ia$1CKi6Q19~GTbzqk*{y4;ew=_B4V8zw zScDH&QedBl&M*-S+bH}@IZUSkUfleyM45G>CnYY{hx8J9q}ME?Iv%XK`#DJRNmAYt zk2uY?A*uyBA=nlYjkcNPMGi*552=*Q>%l?gDK_XYh*Rya_c)ve{=ps`QYE0n!n!)_$TrGi_}J|>1v}(VE7I~aP-wns#?>Y zu+O7`5kq32zM4mAQpJ50vJsUDT_^s&^k-llQMy9!@wRnxw@~kXV6{;z_wLu3i=F3m z&eVsJmuauY)8(<=pNUM5!!fQ4uA6hBkJoElL1asWNkYE#qaP?a+biwWw~vB48PRS7 zY;DSHvgbIB$)!uJU)xA!yLE*kP0owzYo`v@wfdux#~f!dv#uNc_$SF@Qq9#3q5R zfuQnPPN_(z;#X#nRHTV>TWL_Q%}5N-a=PhkQ^GL+$=QYfoDr2JO-zo#j;mCsZVUQ) zJ96e^OqdLW6b-T@CW@eQg)EgIS9*k`xr$1yDa1NWqQ|gF^2pn#dP}3NjfRYx$pTrb zwGrf8=bQAjXx*8?du*?rlH2x~^pXjiEmj^XwQo{`NMonBN=Q@Y21!H)D( zA~%|VhiTjaRQ%|#Q9d*K4j~JDXOa4wmHb0L)hn*;Eq#*GI}@#ux4}bt+olS(M4$>c z=v8x74V_5~xH$sP+LZCTrMxi)VC%(Dg!2)KvW|Wwj@pwmH6%8zd*x0rUUe$e(Z%AW z@Q{4LL9#(A-9QaY2*+q8Yq2P`pbk3!V3mJkh3uH~uN)+p?67d(r|Vo0CebgR#u}i? zBxa^w%U|7QytN%L9bKaeYhwdg7(z=AoMeP0)M3XZA)NnyqL%D_x-(jXp&tp*`%Qsx z6}=lGr;^m1<{;e=QQZ!FNxvLcvJVGPkJ63at5%*`W?46!6|5FHYV0qhizSMT>Zoe8 zsJ48kb2@=*txGRe;?~KhZgr-ZZ&c0rNV7eK+h$I-UvQ=552@psVrvj#Ys@EU4p8`3 zsNqJu-o=#@9N!Pq`}<=|((u)>^r0k^*%r<{YTMm+mOPL>EoSREuQc-e2~C#ZQ&Xve zZ}OUzmE4{N-7cqhJiUoO_V#(nHX11fdfVZJT>|6CJGX5RQ+Ng$Nq9xs-C86-)~`>p zW--X53J`O~vS{WWjsAuGq{K#8f#2iz` zzSSNIf6;?5sXrHig%X(}0q^Y=eYwvh{TWK-fT>($8Ex>!vo_oGFw#ncr{vmERi^m7lRi%8Imph})ZopLoIWt*eFWSPuBK zu>;Pu2B#+e_W|IZ0_Q9E9(s@0>C*1ft`V{*UWz^K<0Ispxi@4umgGXW!j%7n+NC~* zBDhZ~k6sS44(G}*zg||X#9Weto;u*Ty;fP!+v*7be%cYG|yEOBomch#m8Np!Sw`L)q+T` zmrTMf2^}7j=RPwgpO9@eXfb{Q>GW#{X=+xt`AwTl!=TgYm)aS2x5*`FSUaaP_I{Xi zA#irF%G33Bw>t?^1YqX%czv|JF0+@Pzi%!KJ?z!u$A`Catug*tYPO`_Zho5iip0@! z;`rR0-|Ao!YUO3yaujlSQ+j-@*{m9dHLtve!sY1Xq_T2L3&=8N;n!!Eb8P0Z^p4PL zQDdZ?An2uzbIakOpC|d@=xEA}v-srucnX3Ym{~I#Ghl~JZU(a~Ppo9Gy1oZH&Wh%y zI=KH_s!Lm%lAY&`_KGm*Ht)j*C{-t}Nn71drvS!o|I|g>ZKjE3&Mq0TCs6}W;p>%M zQ(e!h*U~b;rsZ1OPigud>ej=&hRzs@b>>sq6@Yjhnw?M26YLnDH_Wt#*7S$-BtL08 zVyIKBm$}^vp?ILpIJetMkW1VtIc&7P3z0M|{y5gA!Yi5x4}UNz5C0Wdh02!h zNS>923}vrkzl07CX`hi)nj-B?#n?BJ2Vk0zOGsF<~{Fo7OMCN_85daxhk*pO}x_8;-h>}pcw26V6CqR-=x2vRL?GB#y%tYqi;J}kvxaz}*iFO6YO0ha6!fHU9#UI2Nv z_(`F#QU1B+P;E!t#Lb)^KaQYYSewj4L!_w$RH%@IL-M($?DV@lGj%3ZgVdHe^q>n(x zyd5PDpGbvR-&p*eU9$#e5#g3-W_Z@loCSz}f~{94>k6VRG`e5lI=SE0AJ7Z_+=nnE zTuHEW)W|a8{fJS>2TaX zuRoa=LCP~kP)kx4L+OqTjtJOtXiF=y;*eUFgCn^Y@`gtyp?n14PvWF=zhNGGsM{R- z^DsGxtoDtx+g^hZi@E2Y(msb-hm{dWiHdoQvdX88EdM>^DS#f}&kCGpPFDu*KjEpv$FZtLpeT>@)mf|z#ZWEsueeW~hF78Hu zfY9a+Gp?<)s{Poh_qdcSATV2oZJo$OH~K@QzE2kCADZ@xX(; z)0i=kcAi%nvlsYagvUp(z0>3`39iKG9WBDu3z)h38p|hLGdD+Khk394PF3qkX!02H z#rNE`T~P9vwNQ_pNe0toMCRCBHuJUmNUl)KFn6Gu2je+p>{<9^oZ4Gfb!)rLZ3CR3 z-o&b;Bh>51JOt=)$-9+Z!P}c@cKev_4F1ZZGs$I(A{*PoK!6j@ZJrAt zv2LxN#p1z2_0Ox|Q8PVblp9N${kXkpsNVa^tNWhof)8x8&VxywcJz#7&P&d8vvxn` zt75mu>yV=Dl#SuiV!^1BPh5R)`}k@Nr2+s8VGp?%Le>+fa{3&(XYi~{k{ z-u4#CgYIdhp~GxLC+_wT%I*)tm4=w;ErgmAt<5i6c~)7JD2olIaK8by{u-!tZWT#RQddptXRfEZxmfpt|@bs<*uh?Y_< zD>W09Iy4iM@@80&!e^~gj!N`3lZwosC!!ydvJtc0nH==K)v#ta_I}4Tar|;TLb|+) zSF(;=?$Z0?ZFdG6>Qz)6oPM}y1&zx_Mf`A&chb znSERvt9%wdPDBIU(07X+CY74u`J{@SSgesGy~)!Mqr#yV6$=w-dO;C`JDmv=YciTH zvcrN1kVvq|(3O)NNdth>X?ftc`W2X|FGnWV%s})+uV*bw>aoJ#0|$pIqK6K0Lw!@- z3pkPbzd`ljS=H2Bt0NYe)u+%kU%DWwWa>^vKo=lzDZHr>ruL5Ky&#q7davj-_$C6J z>V8D-XJ}0cL$8}Xud{T_{19#W5y}D9HT~$&YY-@=Th219U+#nT{tu=d|B)3K`pL53 zf7`I*|L@^dPEIDJkI3_oA9vsH7n7O}JaR{G~8 zfi$?kmKvu20(l`dV7=0S43VwVKvtF!7njv1Q{Ju#ysj=|dASq&iTE8ZTbd-iiu|2& zmll%Ee1|M?n9pf~?_tdQ<7%JA53!ulo1b^h#s|Su2S4r{TH7BRB3iIOiX5|vc^;5( zKfE1+ah18YA9o1EPT(AhBtve5(%GMbspXV)|1wf5VdvzeYt8GVGt0e*3|ELBhwRaO zE|yMhl;Bm?8Ju3-;DNnxM3Roelg`^!S%e({t)jvYtJCKPqN`LmMg^V&S z$9OIFLF$%Py~{l?#ReyMzpWixvm(n(Y^Am*#>atEZ8#YD&?>NUU=zLxOdSh0m6mL? z_twklB0SjM!3+7U^>-vV=KyQZI-6<(EZiwmNBzGy;Sjc#hQk%D;bay$v#zczt%mFCHL*817X4R;E$~N5(N$1Tv{VZh7d4mhu?HgkE>O+^-C*R@ zR0ima8PsEV*WFvz`NaB+lhX3&LUZcWWJJrG7ZjQrOWD%_jxv=)`cbCk zMgelcftZ%1-p9u!I-Zf_LLz{hcn5NRbxkWby@sj2XmYfAV?iw^0?hM<$&ZDctdC`; zsL|C-7d;w$z2Gt0@hsltNlytoPnK&$>ksr(=>!7}Vk#;)Hp)LuA7(2(Hh(y3LcxRY zim!`~j6`~B+sRBv4 z<#B{@38kH;sLB4eH2+8IPWklhd25r5j2VR}YK$lpZ%7eVF5CBr#~=kUp`i zlb+>Z%i%BJH}5dmfg1>h7U5Q(-F{1d=aHDbMv9TugohX5lq#szPAvPE|HaokMQIi_ zTcTNsO53(oX=hg2w!XA&+qP}nwr$(C)pgG8emS@Mf7m0&*kiA!wPLS`88c=aD$niJ zp?3j%NI^uy|5*MzF`k4hFbsyQZ@wu!*IY+U&&9PwumdmyfL(S0#!2RFfmtzD3m9V7 zsNOw9RQofl-XBfKBF^~~{oUVouka#r3EqRf=SnleD=r1Hm@~`y8U7R)w16fgHvK-6?-TFth)f3WlklbZh+}0 zx*}7oDF4U^1tX4^$qd%987I}g;+o0*$Gsd=J>~Uae~XY6UtbdF)J8TzJXoSrqHVC) zJ@pMgE#;zmuz?N2MIC+{&)tx=7A%$yq-{GAzyz zLzZLf=%2Jqy8wGHD;>^x57VG)sDZxU+EMfe0L{@1DtxrFOp)=zKY1i%HUf~Dro#8} zUw_Mj10K7iDsX}+fThqhb@&GI7PwONx!5z;`yLmB_92z0sBd#HiqTzDvAsTdx+%W{ z2YL#U=9r!@3pNXMp_nvximh+@HV3psUaVa-lOBekVuMf1RUd26~P*|MLouQrb}XM-bEw(UgQxMI6M&l3Nha z{MBcV=tl(b_4}oFdAo}WX$~$Mj-z70FowdoB{TN|h2BdYs?$imcj{IQpEf9q z)rzpttc0?iwopSmEoB&V!1aoZqEWEeO-MKMx(4iK7&Fhc(94c zdy}SOnSCOHX+A8q@i>gB@mQ~Anv|yiUsW!bO9hb&5JqTfDit9X6xDEz*mQEiNu$ay zwqkTV%WLat|Ar+xCOfYs0UQNM`sdsnn*zJr>5T=qOU4#Z(d90!IL76DaHIZeWKyE1 zqwN%9+~lPf2d7)vN2*Q?En?DEPcM+GQwvA<#;X3v=fqsxmjYtLJpc3)A8~*g(KqFx zZEnqqruFDnEagXUM>TC7ngwKMjc2Gx%#Ll#=N4qkOuK|;>4%=0Xl7k`E69@QJ-*Vq zk9p5!+Ek#bjuPa<@Xv7ku4uiWo|_wy)6tIr`aO!)h>m5zaMS-@{HGIXJ0UilA7*I} z?|NZ!Tp8@o-lnyde*H+@8IHME8VTQOGh96&XX3E+}OB zA>VLAGW+urF&J{H{9Gj3&u+Gyn?JAVW84_XBeGs1;mm?2SQm9^!3UE@(_FiMwgkJI zZ*caE={wMm`7>9R?z3Ewg!{PdFDrbzCmz=RF<@(yQJ_A6?PCd_MdUf5vv6G#9Mf)i#G z($OxDT~8RNZ>1R-vw|nN699a}MQN4gJE_9gA-0%>a?Q<9;f3ymgoi$OI!=aE6Elw z2I`l!qe-1J$T$X&x9Zz#;3!P$I);jdOgYY1nqny-k=4|Q4F!mkqACSN`blRji>z1` zc8M57`~1lgL+Ha%@V9_G($HFBXH%k;Swyr>EsQvg%6rNi){Tr&+NAMga2;@85531V z_h+h{jdB&-l+%aY{$oy2hQfx`d{&?#psJ78iXrhrO)McOFt-o80(W^LKM{Zw93O}m z;}G!51qE?hi=Gk2VRUL2kYOBRuAzktql%_KYF4>944&lJKfbr+uo@)hklCHkC=i)E zE*%WbWr@9zoNjumq|kT<9Hm*%&ahcQ)|TCjp@uymEU!&mqqgS;d|v)QlBsE0Jw|+^ zFi9xty2hOk?rlGYT3)Q7i4k65@$RJ-d<38o<`}3KsOR}t8sAShiVWevR8z^Si4>dS z)$&ILfZ9?H#H&lumngpj7`|rKQQ`|tmMmFR+y-9PP`;-425w+#PRKKnx7o-Rw8;}*Ctyw zKh~1oJ5+0hNZ79!1fb(t7IqD8*O1I_hM;o*V~vd_LKqu7c_thyLalEF8Y3oAV=ODv z$F_m(Z>ucO(@?+g_vZ`S9+=~Msu6W-V5I-V6h7->50nQ@+TELlpl{SIfYYNvS6T6D z`9cq=at#zEZUmTfTiM3*vUamr!OB~g$#?9$&QiwDMbSaEmciWf3O2E8?oE0ApScg38hb&iN%K+kvRt#d))-tr^ zD+%!d`i!OOE3in0Q_HzNXE!JcZ<0;cu6P_@;_TIyMZ@Wv!J z)HSXAYKE%-oBk`Ye@W3ShYu-bfCAZ}1|J16hFnLy z?Bmg2_kLhlZ*?`5R8(1%Y?{O?xT)IMv{-)VWa9#1pKH|oVRm4!lLmls=u}Lxs44@g^Zwa0Z_h>Rk<(_mHN47=Id4oba zQ-=qXGz^cNX(b*=NT0<^23+hpS&#OXzzVO@$Z2)D`@oS=#(s+eQ@+FSQcpXD@9npp zlxNC&q-PFU6|!;RiM`?o&Sj&)<4xG3#ozRyQxcW4=EE;E)wcZ&zUG*5elg;{9!j}I z9slay#_bb<)N!IKO16`n3^@w=Y%duKA-{8q``*!w9SW|SRbxcNl50{k&CsV@b`5Xg zWGZ1lX)zs_M65Yt&lO%mG0^IFxzE_CL_6$rDFc&#xX5EXEKbV8E2FOAt>Ka@e0aHQ zMBf>J$FLrCGL@$VgPKSbRkkqo>sOXmU!Yx+Dp7E3SRfT`v~!mjU3qj-*!!YjgI*^) z+*05x78FVnVwSGKr^A|FW*0B|HYgc{c;e3Ld}z4rMI7hVBKaiJRL_e$rxDW^8!nGLdJ<7ex9dFoyj|EkODflJ#Xl`j&bTO%=$v)c+gJsLK_%H3}A_} z6%rfG?a7+k7Bl(HW;wQ7BwY=YFMSR3J43?!;#~E&)-RV_L!|S%XEPYl&#`s!LcF>l zn&K8eemu&CJp2hOHJKaYU#hxEutr+O161ze&=j3w12)UKS%+LAwbjqR8sDoZHnD=m0(p62!zg zxt!Sj65S?6WPmm zL&U9c`6G}T`irf=NcOiZ!V)qhnvMNOPjVkyO2^CGJ+dKTnNAPa?!AxZEpO7yL_LkB zWpolpaDfSaO-&Uv=dj7`03^BT3_HJOAjn~X;wz-}03kNs@D^()_{*BD|0mII!J>5p z1h06PTyM#3BWzAz1FPewjtrQfvecWhkRR=^gKeFDe$rmaYAo!np6iuio3>$w?az$E zwGH|zy@OgvuXok}C)o1_&N6B3P7ZX&-yimXc1hAbXr!K&vclCL%hjVF$yHpK6i_Wa z*CMg1RAH1(EuuA01@lA$sMfe*s@9- z$jNWqM;a%d3?(>Hzp*MiOUM*?8eJ$=(0fYFis!YA;0m8s^Q=M0Hx4ai3eLn%CBm14 zOb8lfI!^UAu_RkuHmKA-8gx8Z;##oCpZV{{NlNSe<i;9!MfIN!&;JI-{|n{(A19|s z9oiGesENcLf@NN^9R0uIrgg(46r%kjR{0SbnjBqPq()wDJ@LC2{kUu_j$VR=l`#RdaRe zxx;b7bu+@IntWaV$si1_nrQpo*IWGLBhhMS13qH zTy4NpK<-3aVc;M)5v(8JeksSAGQJ%6(PXGnQ-g^GQPh|xCop?zVXlFz>42%rbP@jg z)n)% zM9anq5(R=uo4tq~W7wES$g|Ko z1iNIw@-{x@xKxSXAuTx@SEcw(%E49+JJCpT(y=d+n9PO0Gv1SmHkYbcxPgDHF}4iY zkXU4rkqkwVBz<{mcv~A0K|{zpX}aJcty9s(u-$je2&=1u(e#Q~UA{gA!f;0EAaDzdQ=}x7g(9gWrWYe~ zV98=VkHbI!5Rr;+SM;*#tOgYNlfr7;nLU~MD^jSdSpn@gYOa$TQPv+e8DyJ&>aInB zDk>JmjH=}<4H4N4z&QeFx>1VPY8GU&^1c&71T*@2#dINft%ibtY(bAm%<2YwPL?J0Mt{ z7l7BR718o5=v|jB!<7PDBafdL>?cCdVmKC;)MCOobo5edt%RTWiReAMaIU5X9h`@El0sR&Z z7Ed+FiyA+QAyWn zf7=%(8XpcS*C4^-L24TBUu%0;@s!Nzy{e95qjgkzElf0#ou`sYng<}wG1M|L? zKl6ITA1X9mt6o@S(#R3B{uwJI8O$&<3{+A?T~t>Kapx6#QJDol6%?i-{b1aRu?&9B z*W@$T*o&IQ&5Kc*4LK_)MK-f&Ys^OJ9FfE?0SDbAPd(RB)Oju#S(LK)?EVandS1qb#KR;OP|86J?;TqI%E8`vszd&-kS%&~;1Als=NaLzRNnj4q=+ zu5H#z)BDKHo1EJTC?Cd_oq0qEqNAF8PwU7fK!-WwVEp4~4g z3SEmE3-$ddli))xY9KN$lxEIfyLzup@utHn=Q{OCoz9?>u%L^JjClW$M8OB`txg4r6Q-6UlVx3tR%%Z!VMb6#|BKRL`I))#g zij8#9gk|p&Iwv+4s+=XRDW7VQrI(+9>DikEq!_6vIX8$>poDjSYIPcju%=qluSS&j zI-~+ztl1f71O-B+s7Hf>AZ#}DNSf`7C7*)%(Xzf|ps6Dr7IOGSR417xsU=Rxb z1pgk9vv${17h7mZ{)*R{mc%R=!i}8EFV9pl8V=nXCZruBff`$cqN3tpB&RK^$yH!A8RL zJ5KltH$&5%xC7pLZD}6wjD2-uq3&XL8CM$@V9jqalF{mvZ)c4Vn?xXbvkB(q%xbSdjoXJXanVN@I;8I`)XlBX@6BjuQKD28Jrg05} z^ImmK-Ux*QMn_A|1ionE#AurP8Vi?x)7jG?v#YyVe_9^up@6^t_Zy^T1yKW*t* z&Z0+0Eo(==98ig=^`he&G^K$I!F~1l~gq}%o5#pR6?T+ zLmZu&_ekx%^nys<^tC@)s$kD`^r8)1^tUazRkWEYPw0P)=%cqnyeFo3nW zyV$^0DXPKn5^QiOtOi4MIX^#3wBPJjenU#2OIAgCHPKXv$OY=e;yf7+_vI7KcjKq% z?RVzC24ekYp2lEhIE^J$l&wNX0<}1Poir8PjM`m#zwk-AL0w6WvltT}*JN8WFmtP_ z6#rK7$6S!nS!}PSFTG6AF7giGJw5%A%14ECde3x95(%>&W3zUF!8x5%*h-zk8b@Bz zh`7@ixoCVCZ&$$*YUJpur90Yg0X-P82>c~NMzDy7@Ed|6(#`;{)%t7#Yb>*DBiXC3 zUFq(UDFjrgOsc%0KJ_L;WQKF0q!MINpQzSsqwv?#Wg+-NO; z84#4nk$+3C{2f#}TrRhin=Erdfs77TqBSvmxm0P?01Tn@V(}gI_ltHRzQKPyvQ2=M zX#i1-a(>FPaESNx+wZ6J{^m_q3i})1n~JG80c<%-Ky!ZdTs8cn{qWY%x%X^27-Or_ z`KjiUE$OG9K4lWS16+?aak__C*)XA{ z6HmS*8#t_3dl}4;7ZZgn4|Tyy1lOEM1~6Qgl(|BgfQF{Mfjktch zB5kc~4NeehRYO%)3Z!FFHhUVVcV@uEX$eft5Qn&V3g;}hScW_d)K_h5i)vxjKCxcf zL>XlZ^*pQNuX*RJQn)b6;blT3<7@Ap)55)aK3n-H08GIx65W zO9B%gE%`!fyT`)hKjm-&=on)l&!i-QH+mXQ&lbXg0d|F{Ac#U;6b$pqQcpqWSgAPo zmr$gOoE*0r#7J=cu1$5YZE%uylM!i3L{;GW{ae9uy)+EaV>GqW6QJ)*B2)-W`|kLL z)EeeBtpgm;79U_1;Ni5!c^0RbG8yZ0W98JiG~TC8rjFRjGc6Zi8BtoC);q1@8h7UV zFa&LRzYsq%6d!o5-yrqyjXi>jg&c8bu}{Bz9F2D(B%nnuVAz74zmBGv)PAdFXS2(A z=Z?uupM2f-ar0!A)C6l2o8a|+uT*~huH)!h3i!&$ zr>76mt|lwexD(W_+5R{e@2SwR15lGxsnEy|gbS-s5?U}l*kcfQlfnQKo5=LZXizrL zM=0ty+$#f_qGGri-*t@LfGS?%7&LigUIU#JXvwEdJZvIgPCWFBTPT`@Re5z%%tRDO zkMlJCoqf2A=hkU7Ih=IxmPF~fEL90)u76nfFRQwe{m7b&Ww$pnk~$4Lx#s9|($Cvt ze|p{Xozhb^g1MNh-PqS_dLY|Fex4|rhM#lmzq&mhebD$5P>M$eqLoV|z=VQY{)7&sR#tW zl(S1i!!Rrg7kv+V@EL51PGpm511he%MbX2-Jl+DtyYA(0gZyZQjPZP@`SAH{n&25@ zd)emg(p2T3$A!Nmzo|%=z%AhLX)W4hsZNFhmd4<1l6?b3&Fg)G(Zh%J{Cf8Q;?_++ zgO7O<(-)H|Es@QqUgcXNJEfC-BCB~#dhi6ADVZtL!)Mx|u7>ukD052z!QZ5UC-+rd zYXWNRpCmdM{&?M9OMa;OiN{Y#0+F>lBQ=W@M;OXq;-7v3niC$pM8p!agNmq7F04;| z@s-_98JJB&s`Pr6o$KZ=8}qO*7m6SMp7kVmmh$jfnG{r@O(auI7Z^jj!x}NTLS9>k zdo}&Qc2m4Ws3)5qFw#<$h=g%+QUKiYog33bE)e4*H~6tfd42q+|FT5+vmr6Y$6HGC zV!!q>B`1Ho|6E|D<2tYE;4`8WRfm2#AVBBn%_W)mi(~x@g;uyQV3_)~!#A6kmFy0p zY~#!R1%h5E{5;rehP%-#kjMLt*{g((o@0-9*8lKVu+t~CtnOxuaMgo2ssI6@kX09{ zkn~q8Gx<6T)l}7tWYS#q0&~x|-3ho@l}qIr79qOJQcm&Kfr7H54=BQto0)vd1A_*V z)8b2{xa5O^u95~TS=HcJF5b9gMV%&M6uaj<>E zPNM~qGjJ~xbg%QTy#(hPtfc46^nN=Y_GmPYY_hTL{q`W3NedZyRL^kgU@Q$_KMAjEzz*eip`3u6AhPDcWXzR=Io5EtZRPme>#K9 z4lN&87i%YYjoCKN_z9YK+{fJu{yrriba#oGM|2l$ir017UH86Eoig3x+;bz32R*;n zt)Eyg#PhQbbGr^naCv0?H<=@+Poz)Xw*3Gn00qdSL|zGiyYKOA0CP%qk=rBAlt~hr zEvd3Z4nfW%g|c`_sfK$z8fWsXTQm@@eI-FpLGrW<^PIjYw)XC-xFk+M<6>MfG;WJr zuN}7b;p^`uc0j(73^=XJcw;|D4B(`)Flm|qEbB?>qBBv2V?`mWA?Q3yRdLkK7b}y& z+!3!JBI{+&`~;%Pj#n&&y+<;IQzw5SvqlbC+V=kLZLAHOQb zS{{8E&JXy1p|B&$K!T*GKtSV^{|Uk;`oE*F;?@q1dX|>|KWb@|Dy*lbGV0Gx;gpA$ z*N16`v*gQ?6Skw(f^|SL;;^ox6jf2AQ$Zl?gvEV&H|-ep*hIS@0TmGu1X1ZmEPY&f zKCrV{UgRAiNU*=+Uw%gjIQhTAC@67m)6(_D+N>)(^gK74F%M2NUpWpho}aq|Kxh$3 zz#DWOmQV4Lg&}`XTU41Z|P~5;wN2c?2L{a=)Xi~!m#*=22c~&AW zgG#yc!_p##fI&E{xQD9l#^x|9`wSyCMxXe<3^kDIkS0N>=oAz7b`@M>aT?e$IGZR; zS;I{gnr4cS^u$#>D(sjkh^T6_$s=*o%vNLC5+6J=HA$&0v6(Y1lm|RDn&v|^CTV{= zjVrg_S}WZ|k=zzp>DX08AtfT@LhW&}!rv^);ds7|mKc5^zge_Li>FTNFoA8dbk@K$ zuuzmDQRL1leikp%m}2_`A7*7=1p2!HBlj0KjPC|WT?5{_aa%}rQ+9MqcfXI0NtjvXz1U)|H>0{6^JpHspI4MfXjV%1Tc1O!tdvd{!IpO+@ z!nh()i-J3`AXow^MP!oVLVhVW&!CDaQxlD9b|Zsc%IzsZ@d~OfMvTFXoEQg9Nj|_L zI+^=(GK9!FGck+y8!KF!nzw8ZCX>?kQr=p@7EL_^;2Mlu1e7@ixfZQ#pqpyCJ```(m;la2NpJNoLQR};i4E;hd+|QBL@GdQy(Cc zTSgZ)4O~hXj86x<7&ho5ePzDrVD`XL7{7PjjNM1|6d5>*1hFPY!E(XDMA+AS;_%E~ z(dOs)vy29&I`5_yEw0x{8Adg%wvmoW&Q;x?5`HJFB@KtmS+o0ZFkE@f)v>YYh-z&m z#>ze?@JK4oE7kFRFD%MPC@x$^p{aW}*CH9Y_(oJ~St#(2)4e-b34D>VG6giMGFA83 zpZTHM2I*c8HE}5G;?Y7RXMA2k{Y?RxHb2 zZFQv?!*Kr_q;jt3`{?B5Wf}_a7`roT&m1BN9{;5Vqo6JPh*gnN(gj}#=A$-F(SRJj zUih_ce0f%K19VLXi5(VBGOFbc(YF zLvvOJl+W<}>_6_4O?LhD>MRGlrk;~J{S#Q;Q9F^;Cu@>EgZAH=-5fp02(VND(v#7n zK-`CfxEdonk!!65?3Ry(s$=|CvNV}u$5YpUf?9kZl8h@M!AMR7RG<9#=`_@qF@})d ztJDH>=F!5I+h!4#^DN6C$pd6^)_;0Bz7|#^edb9_qFg&eI}x{Roovml5^Yf5;=ehZ zGqz-x{I`J$ejkmGTFipKrUbv-+1S_Yga=)I2ZsO16_ye@!%&Op^6;#*Bm;=I^#F;? z27Sz-pXm4x-ykSW*3`)y4$89wy6dNOP$(@VYuPfb97XPDTY2FE{Z+{6=}LLA23mAc zskjZJ05>b)I7^SfVc)LnKW(&*(kP*jBnj>jtph`ZD@&30362cnQpZW8juUWcDnghc zy|tN1T6m?R7E8iyrL%)53`ymXX~_;#r${G`4Q(&7=m7b#jN%wdLlS0lb~r9RMdSuU zJ{~>>zGA5N`^QmrzaqDJ(=9y*?@HZyE!yLFONJO!8q5Up#2v>fR6CkquE$PEcvw5q zC8FZX!15JgSn{Gqft&>A9r0e#be^C<%)psE*nyW^e>tsc8s4Q}OIm})rOhuc{3o)g1r>Q^w5mas) zDlZQyjQefhl0PmH%cK05*&v{-M1QCiK=rAP%c#pdCq_StgDW}mmw$S&K6ASE=`u4+ z5wcmtrP27nAlQCc4qazffZoFV7*l2=Va}SVJD6CgRY^=5Ul=VYLGqR7H^LHA;H^1g}ekn=4K8SPRCT+pel*@jUXnLz+AIePjz@mUsslCN2 z({jl?BWf&DS+FlE5Xwp%5zXC7{!C=k9oQLP5B;sLQxd`pg+B@qPRqZ6FU(k~QkQu{ zF~5P=kLhs+D}8qqa|CQo2=cv$wkqAzBRmz_HL9(HRBj&73T@+B{(zZahlkkJ>EQmQ zenp59dy+L;sSWYde!z_W+I~-+2Xnm;c;wI_wH=RTgxpMlCW@;Us*0}L74J#E z8XbDWJGpBscw?W$&ZxZNxUq(*DKDwNzW7_}AIw$HF6Ix|;AJ3t6lN=v(c9=?n9;Y0 zK9A0uW4Ib9|Mp-itnzS#5in=Ny+XhGO8#(1_H4%Z6yEBciBiHfn*h;^r9gWb^$UB4 zJtN8^++GfT`1!WfQt#3sXGi-p<~gIVdMM<#ZZ0e_kdPG%Q5s20NNt3Jj^t$(?5cJ$ zGZ#FT(Lt>-0fP4b5V3az4_byF12k%}Spc$WsRydi&H|9H5u1RbfPC#lq=z#a9W(r1 z!*}KST!Yhsem0tO#r!z`znSL-=NnP~f(pw-sE+Z$e7i7t9nBP^5ts1~WFmW+j+<@7 zIh@^zKO{1%Lpx^$w8-S+T_59v;%N;EZtJzcfN%&@(Ux5 z@YzX^MwbbXESD*d(&qT7-eOHD6iaH-^N>p2sVdq&(`C$;?#mgBANIc5$r| z^A$r)@c{Z}N%sbfo?T`tTHz9-YpiMW?6>kr&W9t$Cuk{q^g1<$I~L zo++o2!!$;|U93cI#p4hyc!_Mv2QKXxv419}Ej#w#%N+YIBDdnn8;35!f2QZkUG?8O zpP47Wf9rnoI^^!9!dy~XsZ&!DU4bVTAi3Fc<9$_krGR&3TI=Az9uMgYU5dd~ksx+} zP+bs9y+NgEL>c@l>H1R%@>5SWg2k&@QZL(qNUI4XwDl6(=!Q^U%o984{|0e|mR$p+ z9BcwttR#7?As?@Q{+j?K6H7R71PuiA^Dl$=f47nUKL|koCwutc_P<-m{|Al3C~o7w z=4S=}s5LcJFT1zjS)+10X_r$74`K78pz!nGGH%JV%w75!YSIt#hT7}}K>+@{{a+Im z5p#6%^X*txY?}|T17xWW*sa^?G2QHt#@tlcw0GIcy;|NR2vaCBDvn=`h)1il7E5Rx z%)mA4$`$OZx)NF5vXZnaJ1)*cA6ryx6Ll~t!LzhxvcTedxT;>JS&e=?-&DXUPaQ2~ zH*69ezE`hgV{K-|0z|m~ld}=X^-Ob={wpex&}*+Rz{gx)G}gn!C_VN{UN=>^EV=Xc zr$-HO09cW&p4^M}V3yBjTP_xrVcc8iU_^Y-JD~(bgw*@GXGB1gYKz5DWO+O`>})|N zWrC)MR93yA)3{&27-M)TJB6Ml3~?zZg#mYsF=#OSTaw&K z@hBftpt+2l@)YK@|3DvTjl(8wZtpLp9Ik!6G$CSL_idZ$Ti?R)4toe8bb)l|)lNb}?K;O2K9vyn1QG zd=v#y-Ld49UVkmfRU>Egc+(Y$^-;6vW;3Lcu*6~etz}0|@+b|+!UCal)DEYGLbHWJ zll5Wi^$Y<6@S%^y%hdjRh6&{!z1Py|lZ|q&Wub3l41uN2zEF8E&5H5?PL*&V}?*a}Lp% zCYi{ghjpRNT^^B+_U59No50Ghih5qn(W5`RkrsDWr{~A1dgtv{sRkH4RU2^A{jb&0 zxVRnrm|u<;$iI;M6A>$POP)TWGU-gSjAERk*EGmVT(aw$!XUSe~7Ql-oRA54^4V(JWS6Q1mG?!vZ zx+pE!FEtvqr|Xrcb3oR`%LHFLmU_&{=p%mGy6MRe2Yz_5WJ8p@IgU2 zdVvvhhQtiQkChK%*&PsiPCBL9oDOoJX8!$S(V>R}+1M}wzK*U*A{KJ`r=lM;mPrKU zQDqqN(W*u-5-?$(SIk<6A0E}34y&@-IVC%S!a1F4kz<3bIKjlyD)ooO_7ftl%S_(6w`!vX&1PZ!K`@D@L6JR)6zO@Dl!YF{RY}d3HZ7?Q5E>w=$ ze)H_)48Ds*Ov4?zoGb2fe3}{!5Ooc|KCIni1o)(Gj+CO?`*7jsV`hIv@8J(22o4Q? zu?Bvi)zDG(me?7XKeL|iF9ZRgZdT*}Ffsl62Cu;{Gv9j6dO zPt*H2GqC)-C`V`ceuu=tM{7!2yTEj=*5+T~5DYiZ)Hy)*PARYI6R2lZXoOj;v8M4W z*O-NX(7_~Q&A3>Oaw&1lBH_H%SwmISX-i3)HfHvBOeVwTT{LUM3}ZuZmg<(>)KE;d zbs2!0v6>J;1nQ0UJkUxnkE@Ibi~Q}M=-=Rk;hcOnxO$luOKEVxZc|!XECgex(2`}T z3Y;Q_6rL)e+SrOZhQj5_e}Lv>w7n*Pep$yWZNQl>ubBgb_NIWWDn3kNpn+MPQXV;8 zV|_Ba5jsQ(w&Ey^IM|@|y!AqcJ#3m0#Q6_qvgCG~eoF#mnGmbO(;DP+bW%_aOs1R_ z@9p#7X2UA^--#Nwx_Hvk2l1`eO{P*#j@q2UELtH|Uh6hxR`h_847wIJo0=5CQQ`6it|%a-I$^&a@we1rc&*;QIu5Ck^?) zx*5eSd*mG#=6Hi(5!;5uUi&{HfnT1S8X-)?gE5CZ6KWoqM5|CyrULmuFBKOU8SOp* z{IB1$OCcq`S-k*xs;4fmhKsIGZ;GYAY*%(@875NxhMq|j*m4CNLI(Vho|N|F);!E0cS5y^$H^Izje?z}oTgyr`9x9G&rlJZw&uqIoBMtz zzhU0(9;w02?m#0!)cFi*r+8YvooQ;(s2lLVvyLqAE%Xqe!vtWbIs!l1Bpp(FIht-Z zPn#CN-2C|J*GhA2fuHqYQ2mJiXlGTzD}mkr2;ia8Wp}h^;OS7+N^Mw|en!1${vN6 z-x{8N*4UekA~`IV2&K-GzhAqau|}d*pEQ$1MH$cFi03OG^1NetZ_jW^STaEzr&Xho zB452St%v3ez2#TFm~`gZh$vi=in+y2d!z<{OZ~Kty-5bQ;0O=k_ESi8Nx9{*T`LJy6jqR>&|+>OZ;+=0hA04 zE25t^sE9HG)3^KKR_A5WDkqispweP9!I-@dCO&N!JrD@i{WBHnfQ z95o8;d$`AFnca3;N-0iX-CmbbAp5yQ!GoH;h7Cn?m{ammZJI8igP{U73lFnl2&gCs zqJ4(Vo~^j`{zOAzScL5B_Sm?Mjtek1d(A6X5ObcZi$;aOYy|g$}BY z$GEP3#i60Ju_&3SHzryH!gUFwC9-295u??cf+aYRQ1$+!rc#42YNattd6mZEFI@?C zqFM>6+zxEunIHDZ>{Z15u##>N(28Dw!>G(k*dB{NHvip@aP}f`@=Q;!o;zRMWo{Cx zo?kyzh8n7#f1g0&g>Cd>O-2g?uPwy8sy8hZbHSsXPmU;@l=HL=zm7mN(=@*|D$i+u zs~TllkCTvD$f&-#b9B?}#Lg*-ibK13R_a$RyoN3m5`10tdhAq{+VW)K#Bht-ra1*J z+n$N%V>u0rVtx`aKJDwXXrxaD7nS<>$=c82v7@KVx^S@vT;h=SZE37K>iahpx3;VDzEr9GY=2(%uaqM;^76eSP0QLzo4sI z>p_Eei*T$K;|qK`sq;?Hesp}(@VvX2Q4sAMYAJ}b&d$htDMC{FG-$o4k9ApECi1$a zXdamjiOGKHBh(4M<3(2x6n-CrmZMCknkQxdSS!qlis#I}btfX;J`JU3RlvtLdrymP zG0ZzrsGXVFiq+Wk1=BFay&9ZiCE#(`h~CL+c-Hs@iGTU@YxM%vlg;)`Tf~IknA^02 zXkN#Txo6aR{j$wP5T#|UH#5AP2{rSY8p?jKFv zG3kn3y`FaV!*Jq%m39_TQEhD>M@l*bhEPGe1{ft3q#K5AknT=F2_=T^l#ou5ln@D# z5Tzs(kRG@qNDa~HLNvfv7Z0g=bSlb?`QAx|Gfoni|iHJ%K0cy z;~Nsaa+{8HP_qrb{nj+xzkdYhSI@W4N_1`z(eSGIkbDP)!Ko|M%}Rqp(~KI2hl~eE zvJ!j4m6iwMgKy>fkCLC)`M$z9EV}B+sq1}}kVf$(ig0pWTY?rHz1Sm=4srTGNb^JG z=2$9wz-C@aZZZ2!HY#HNejqZRmE=pN(D$Kui$NpfhU`!y_s{@MIxiJdHb1|{6xb`> zE74_@QtgtG{4=3P1$^vn&m}7Aw8!1DnT$2thO#~44wl(N#ao8S0@t@m+Z!KD2CfK; z)n5DAPKV_etmH1aLDK$?`;sL91iVt$D z*SG}=-LIAg(*+JON!-5ivqOMQ1S!OQUgHglDsKik&Mwg;vva523`JwQH6SRz9eTY# zTIi23145~kc3r1mSWC_RzD%hs$S#!pkI9!BU80jJCJcwo*FZolQG$q`8C1d9pP@ND zG^&-ZraIvhg_FDVSfKGwkcI=avIan%2sK4coUs~Nr8jC*&!G0#?}_^s3r-c}-uAqi zM-Lw>Y}I``T;IS%Y|qH;s{F*ZefM!4{I5awr!K+T@uPd*Vu*iPWI}>(-D{zxsN>LG z=@747a_Rb2>q?y8xYf?dq2HM5tFO8Y5e4N;Y=xy8yAhI zsm>oy%R5;7)7T3V_b2%`aH^tNlsQpFxIFW#iV#8?{6{^cGr{A0@1bA)|K z>MMTuZD(pd2t|7vmHtywGXb%%=)S<`OG~}U+jm#xd%H8 z$v8-C%F?ah3$;hn?{G3(LT!SgvCVi$vwsZssAQvUwT`Q%qSw!LSd!(I!64w1=%Sc1Mck)q1@pZ@)=SY zoX}d+L3-RA|c?G3_BQNm&( z!i$AZ7cI(z7q|e9VM##6T3Xorj1JG(9os$;(I$y%mBy(#8{|3l4|x*oBAQL^XhZ0g zy1FR1teRrpKq{uLAibTLx#n({qwjlkOvR{OdSAeT5ah4-sNN)n4Clg1T9lzF)&yj; zyal1%+s4n1IG;^VPWJ;#olpk8Z42Gj-tjFeQ&PlxB)`oCNoUYKj4U$AeG8rYiD{pK zndDf&2;2;)D|KvOZP+e7fcPU9k4M2sfhr@vC~Ly0?S-4dz)ZGAYpCsAhChgbxLd4g zhTrbIPkO5SEp_kD>Ha0m12h5n3s;mE8kn515&nzSf+^D= zyE{JnJ;43l&BH55CL<=W%CF;6iUI)V5C*6!`**KqvzR2=Fj*3Y4`HYwx}TYD445(K z-QtXwtL?m*(F=LVH*H4oM>dXHBW=38q_dZ-_Vr&qpEPxd9Fs95P5W~@Z|Rt+WZP6l zPSQ}~Dh4V?Pp1g&Hk*Px?lm16C@X6M29Vrk%Rw@E||E-v~$ zb_E~{z<}#8i`Mx9mkqtd#Z1lZ-E_J8I+2oumc#x1)jdvh{W76NKm6x-RYpM~v!P8$ zw3e|YVf|}Hse9~oC@N7^j}Fi$hNpyaYnu1}bdXsD=^oI*%WKvbme|BI}$G3>smu#6y)ls|j? zF7Bhu9Z)j)C;3cZb+I>0stSK^WLOYV^U{pUYkgv>?+Nt^5j*CUB=eGw-CvU&40>y~ zGoHLXxY^7k5Xgv62{iQy|5jJQuq0|LU`}lE@flQ2Z*Zn*VWcQjm4FTb>LSVox^S4q zLn`LfS@mrjKCmg$nb^af?d?0&$aX6#2u(JyzIJvuJ*lwPrh|0~aEnSACCTezSdG%h zmSQg`17j@$Iq)r1&?+eR@1nlX|H`<}_!?BQSF&N+QQnvEAqZe+mIFui!0V49R?|9*$ zv!K1A01{8xq;L()Tv*Qk0-$Oj6+vCT*TUD{HvxO@3JjxBwM!4g3ydy&eaJw4CoQBF zJtULJ!YxgNR7_Ls%LmogyI7uIs=!B&?=MYY^yX+v;j@D_xGeZg>eZk0C;4e|HRNSi z6KlD9>q=3v-$4Zik&^ZDhNm1X)+7LCH1k!s+T3tn zUn@={1U&NJLq@K?~w|(=Y<4W{ucX}FdRr6pLw(l2$iK)At%t3gYBMlJz#(K0Nqm;=KAML!&MMSNz=%k=j*zh77r34Rs37iCY` z=_kva_41bdrj(b=4Wc5MO0~q^z#pIWJ>)vDSgIQF=3JVJe1iDy%h)8oNy{s_r&;m` zL{DYKSB_5xRb9xKNOS{qAY3qv5sSXVrrf%~*q5HO|CQ&lbKMePa$M5D{vlJcoGrCZ zD?fKbZN$6rWwz)w7`9h4DAmh1ij2}EO|bO#A9L0_RW6l*$sPPUJrUbhLC75L9%W5iO$Iw5~Yut-qBeu~hF|xD7-eQ%l z412vpq_;t%^F*pYDk%Q35c-erK|6Ve=FxQbAv~ikZ4c9$Y4;ee#ciOD9{yRqf55Qk zumv}#+JciT|Gj$uFOxBUze)=?l{B}qaC0_7m`t82<$K53!4Xvi9Tr)ADp3Off?O8o zVDG0Yx|tfn@r((m?Nxrh(b0DGjg)$;DfO&$6uY;4&F!4jnxkhP}Y3x zS?WFFt>=HWzqlQhffVfvM$Ta8Sg*r3j!Eo&rUOW7SCL2~lG7<+XZ;+{&8h5g8ElI+P>>yR2U%S93NN!Xhm|C682t6ysH-=o1=Bd*N*VlnG%l+KZFtjG`UkL;%65qn0UYQ`h zh0{9jDQx(`aBe7J0Aj3Z)4}`A|4OMM0a;?{j}qkYwi)~O8$9D}ITiMH2buiU>ixYp zhL${nwj6X($*OwmpVG`y5b6v45tX*J8?og}Qju6eJ9H}`X87iEd%BUo7<`2q(HJx+ zMR}d-J4oAf{V1W^a2~`M-YAdZ81dd4o6NPO{cmZaAS@RS4ir#Sr zfFZO-VIL|VN<%nEXr2` z$0FK2L#8O_f1w~c@G70JrB@N}r(gJ!Vmkk6{r68w!o$qO?HrFcjeU0_3F5;*!E2%( zTx>4?gP8w z1B?3UVZmz^%d_dIps>>0{cB~mp3{9UoPR6uQFecVq&} zY{ebB?AlPAD_}(ll{fK99;Wh1cgRbnw)maD^F>*J!R}eHM*W0VYN1TADWMy9H=$00 z5bHY${oDgwX7(W9LZw?}{!8(_{JB~Xkje6{0x4fgC4kUmpfJ+LT1DYD*TWu4#h{Y7 zFLronmc=hS=W=j1ar3r1JNjQoWo2hMWsqW*e?TF%#&{GpsaLp}iN~$)ar+7Ti}E&X z-nq~+Gkp(`qF0F_4A22>VZn-x>I$?PDZSeG8h_ifoWf^DxIb5%T7UytYo3}F|4#RC zUHpg$=)qVqD~=m(!~?XwocuxU1u}9qhhM7d^eqmJPi_e-!IO`*{u7A zbu*?L$Mbj-X9n3G2>+Kc#l`@d8}Xb9{l*IN{#M*d;s+3Pdr8FO$EBELR=8{ zd?LJbSv9fI`{OqTH)5{b?WulgMb)psp+W|@cSp=jtl-&5C}9lw@*0H+gEW(}mAWNz zf{~U;;N}|wdSaphgqnH{FWUy!{y3^=AC*c?RJ5Eb<^ zCgH_v7^axIUVmHSFL^zlj2R$zow$|y#7>%#U7d#Vp_ezcp3lefMyd5ES=q$>4pWyA zp_Zso^^NP~lu2=S6nD(3Z5u=Uy&B&F1i$J*3;3KhEkD_lgscHGR*;T;U!9vgQa(hI}oh9IzEf_PU_8F+i77t-~gDX z490Sb)LyVZmf18N6w{+37$aO<2!Av0 ztLaPOv^J<2@p{WnMiDudoghX_`luFZt_4eNU}*~cF5i%eEcNLs;D>QVIwr8mH;=dc z09`}JV;aaF;13@&iS(w>Jc=k~|d_1hcpM(l|O zu>!@}me%isTT$xT#hNUvh(ATd0wT4fbv=6htcHNEZIw9%E6wlYmwfu2{j0kh1y=$;Yf!|NldgB9ul zB{dbE&LfRnr8ITm@;-68wo#VV?8lG3ed&9k1}QBS3}WGV9%26?A1rBkkDR9Z3o+g+ z)eQg8BY3y(Dh5&z?VLLNdDV`C=muUvCPpGg!oYxIgOI3^%4>5d7jTh~ni!Fg2;fhx z(*c%H6Je84kmQh;5tC3*l~7khLxK-e|Cz?FLh!yYe7g|*LwqU?2wv^_ZyKT$fYVkGJo@AK0$+ml?}zJeB~deT2WL1vz}dxB z)y??t!}%M@)u$_IyW~)6u1SttJ!awd6N5lx|xBrmyrBh>tb&D*=C+Z3nPfq$1%WgY0bY*?PZ#Hk|=xn zGM#0*w4CaB^y0G(J4q=;5NeM@m-P}#mv7QZNF)M!dK^w{mk_!n0`+Y3PQutu-%NBt zzgPXug?JLEbUL{e_dk;Vd896&yPe(hliVK!lj%5+@BKdcrEZ2Nc_*i@ve*2lB>u~{ zFozd2FM|_0+nAGR4TLNHanQn_Oeb!JrUcvzJ?7p9TTNB}ocO3j$7ij!li8#k6 z@2tSd1>K03K9A#_-MIq)S;T#oE^;>U$)&}okIvDf3lm?kI{d80$>~xKUoS!%q1Pi?WpsUUt(tI ztjNjY*y&Rm9(S(DC2GuPHBJs@5M{RGm`c1z<6nwyN^)rMo-AS{M2$oM9|y%fM|}G~ DHx0+F literal 0 HcmV?d00001 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..9123188d --- /dev/null +++ b/android/hermes/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { + kotlin("jvm") +} +kotlin { + jvmToolchain(17) +} +dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + testImplementation("junit:junit:4.13.2") +} +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/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/HermesConnection.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesConnection.kt new file mode 100644 index 00000000..97ff187b --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesConnection.kt @@ -0,0 +1,194 @@ +package app.bighelp.hermes + +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull + +// Pure, immutable policy for who owns a connection and what it may do. It performs no I/O: a transport +// feeds it facts (upgraded, a decoded message, a capability result) and asks before acting. It is not a +// client; nothing here opens a socket, sends a frame or reconnects. + +/** + * Who a socket, request or result belongs to. [generation] changes on every new connection, even to the + * same endpoint and principal, so an older answer can never be mistaken for the current one. + */ +data class ConnectionOwner(val endpoint: String, val principal: String, val generation: Long) + +/** + * The one current owner, or none while disconnected. Hold it in a single atomic holder and check + * [accepts] on the same context that applies the result: a retired owner can never publish. + */ +class OwnerState private constructor(val current: ConnectionOwner?, private val lastGeneration: Long) { + /** Supersedes any current owner. Generations only grow, also across [disconnect]. */ + fun connect(endpoint: HermesEndpoint, principal: String): OwnerState { + val owner = ConnectionOwner(endpoint.canonical, principal, lastGeneration + 1) + return OwnerState(owner, owner.generation) + } + + fun disconnect(): OwnerState = OwnerState(null, lastGeneration) + + /** True only for the exact current owner: same endpoint, same principal, same generation. */ + fun accepts(owner: ConnectionOwner): Boolean = owner == current + + companion object { + val none = OwnerState(null, 0) + } +} + +/** Host-advertised `gateway.capabilities`. Unknown keys are ignored; the one Boolean is required. */ +data class GatewayCapabilities(val perSessionExclusiveSubmit: Boolean) { + companion object { + /** + * @throws WireException unless [result] is an object whose `per_session_exclusive_submit` is a JSON + * Boolean. Missing, `"true"` or any other shape fails discovery; never infer it from a version. + */ + fun decode(result: JsonElement): GatewayCapabilities { + val flag = (result as? JsonObject)?.get("per_session_exclusive_submit") as? JsonPrimitive + val value = flag?.takeIf { !it.isString }?.booleanOrNull + ?: throw WireException(WireException.Kind.InvalidResponse) + return GatewayCapabilities(value) + } + } +} + +enum class SocketPhase { + /** The upgrade request is under way. */ + Connecting, + + /** The WebSocket opened (HTTP 101) but Hermes has not said `gateway.ready`. Not usable. */ + Upgraded, + + /** `gateway.ready` arrived. Only now may the application write. */ + Ready, + + Closed, +} + +/** What a request needs from the connection. */ +enum class GatewayOperation { + /** Reads such as listing sessions. */ + Read, + + /** Prompt answers, stop, steer and other session controls that do not submit a new turn. */ + Control, + + /** Starting a turn: chat send, queue and slash commands. Needs the exclusive-submit guarantee. */ + Submission, +} + +enum class Refusal { + /** The owner was superseded or disconnected. */ + StaleOwner, + + /** The socket is not past `gateway.ready`; an upgrade alone allows no application writes. */ + NotReady, + + /** Capabilities have not been discovered on this socket yet. */ + CapabilitiesUnknown, + + /** The host did not guarantee serialized submitters, so starting a turn stays off. */ + ExclusiveSubmitUnavailable, +} + +sealed interface Admission { + data object Admitted : Admission + data class Refused(val reason: Refusal) : Admission +} + +/** + * One socket generation's readiness and capabilities. Readiness is a separate fact from the upgrade and + * from capability discovery; every transition returns a new value. + */ +class GatewaySocket private constructor( + val owner: ConnectionOwner, + val phase: SocketPhase, + /** Null until discovered on this ready socket. Capabilities belong to one socket and are never carried over. */ + val capabilities: GatewayCapabilities?, + /** The retained initial `gateway.ready`, so a late consumer still sees its epoch and heartbeat hint. */ + val ready: WireMessage.Event?, +) { + fun upgraded(): GatewaySocket = + if (phase == SocketPhase.Connecting) GatewaySocket(owner, SocketPhase.Upgraded, null, null) else this + + /** + * Feeds one decoded message. The first `gateway.ready` on an upgraded socket makes it ready; a second + * one on an already ready socket is invalid and closes it. Everything else changes nothing. + */ + fun receive(message: WireMessage): GatewaySocket { + if (message !is WireMessage.Event || message.type != GATEWAY_READY) return this + return when (phase) { + SocketPhase.Upgraded -> GatewaySocket(owner, SocketPhase.Ready, null, message) + SocketPhase.Ready -> closed() + else -> this + } + } + + /** @throws IllegalStateException unless the socket is ready: capabilities are asked after `gateway.ready`. */ + fun discovered(capabilities: GatewayCapabilities): GatewaySocket { + check(phase == SocketPhase.Ready) { "Capabilities are only discovered on a ready socket." } + return GatewaySocket(owner, phase, capabilities, ready) + } + + fun closed(): GatewaySocket = GatewaySocket(owner, SocketPhase.Closed, null, ready) + + /** Server requests may arrive early, but their responses and every client frame wait for this. */ + val canWriteApplicationFrames: Boolean get() = phase == SocketPhase.Ready + + fun admit(operation: GatewayOperation, owners: OwnerState): Admission { + if (!owners.accepts(owner)) return Admission.Refused(Refusal.StaleOwner) + if (!canWriteApplicationFrames) return Admission.Refused(Refusal.NotReady) + if (operation == GatewayOperation.Submission) { + val known = capabilities ?: return Admission.Refused(Refusal.CapabilitiesUnknown) + if (!known.perSessionExclusiveSubmit) return Admission.Refused(Refusal.ExclusiveSubmitUnavailable) + } + return Admission.Admitted + } + + companion object { + const val GATEWAY_READY = "gateway.ready" + + fun opening(owner: ConnectionOwner) = GatewaySocket(owner, SocketPhase.Connecting, null, null) + } +} + +/** How far one outgoing RPC got. Mark [MayHaveBeenSent] before awaiting the socket send, not after. */ +enum class DispatchOutcome { + /** Nothing left the device. */ + NotSent, + + /** Bytes may have reached the host. A failed send call does not prove otherwise. */ + MayHaveBeenSent, + + ConfirmedResult, + ConfirmedRefusal, +} + +object DispatchPolicy { + /** The current client's conservative read-only allowlist. Anything else counts as a mutation. */ + val readOnlyMethods: Set = setOf( + "gateway.ping", "session.list", "session.active_list", "session.history", + "session.status", "session.usage", "session.events.since", "commands.catalog", + "config.get", "delegation.status", "spawn_tree.list", + "profiles.list", "profiles.describe", "profiles.get_asset", "model.options", + "projects.list", "projects.get", "subagent.list", "subagent.tail", "client.capabilities", + "groups.capabilities", "groups.list", "groups.state", "groups.log", "pet.gallery", "pet.thumb", + ) + + fun isReadOnly(method: String): Boolean = method in readOnlyMethods + + /** A mutation that may have been sent has an unknown outcome: show it as uncertain, never as failed. */ + fun isUncertain(method: String, outcome: DispatchOutcome): Boolean = + outcome == DispatchOutcome.MayHaveBeenSent && !isReadOnly(method) + + /** + * Whether the owning layer may issue a fresh request after a lost connection. This is never a license + * to copy the old frame to a new socket, and a mutation with an uncertain outcome is never retried by + * the transport: an operation-specific recovery contract has to reconcile host state first. + */ + fun mayRetry(method: String, outcome: DispatchOutcome): Boolean = when (outcome) { + DispatchOutcome.NotSent -> true + DispatchOutcome.MayHaveBeenSent -> isReadOnly(method) + DispatchOutcome.ConfirmedResult, DispatchOutcome.ConfirmedRefusal -> false + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt new file mode 100644 index 00000000..1b8d5a95 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt @@ -0,0 +1,158 @@ +package app.bighelp.hermes + +import java.net.URI +import java.net.URISyntaxException + +/** Why an address or route was refused. Callers show plain words per reason and never echo the input. */ +class HermesEndpointException(val reason: Reason) : IllegalArgumentException(reason.name) { + enum class Reason { InvalidEndpoint, PlaintextNotAllowed, InvalidRoute } +} + +/** + * A validated Hermes dashboard base address, including an optional deployment prefix. [canonical] is the + * endpoint's identity: scheme, effective port and prefix are all part of it, so credentials for + * `/hermes-a` are never credentials for `/hermes-b`. Saved endpoints must go through [parse] again. + * + * Plain HTTP needs both the caller's explicit private-network opt-in and a host that is private by its + * syntax alone. No name is ever resolved, so DNS cannot authorize plaintext. + */ +class HermesEndpoint private constructor( + val isSecure: Boolean, + /** Lowercase host without IPv6 brackets. */ + val host: String, + /** The explicit port, or null when it is the scheme's default. */ + val port: Int?, + /** Deployment prefix: empty, or `/a/b` with no trailing slash. */ + val prefix: String, + val allowPrivateHttp: Boolean, +) { + private val authority: String = + (if (':' in host) "[$host]" else host) + (port?.let { ":$it" } ?: "") + + val canonical: String = "${if (isSecure) "https" else "http"}://$authority$prefix" + + /** The gateway socket, `wss` for HTTPS and `ws` for HTTP. The prefix is kept. */ + val webSocketUrl: String = "${if (isSecure) "wss" else "ws"}://$authority$prefix/api/ws" + + /** + * Appends an application-owned [route] to the prefix. Caller-supplied absolute URLs, queries and + * traversal never pass; add query values separately with a real query encoder. + */ + fun httpUrl(route: String): URI { + if (!route.startsWith("/") || "//" in route || route.any { it.code !in 0x21..0x7e || it in "?#%\\" } || + route.split('/').any { it == "." || it == ".." } + ) throw HermesEndpointException(HermesEndpointException.Reason.InvalidRoute) + return try { + URI("$canonical$route") + } catch (_: URISyntaxException) { + throw HermesEndpointException(HermesEndpointException.Reason.InvalidRoute) + } + } + + override fun equals(other: Any?): Boolean = + other is HermesEndpoint && canonical == other.canonical && allowPrivateHttp == other.allowPrivateHttp + + override fun hashCode(): Int = 31 * canonical.hashCode() + allowPrivateHttp.hashCode() + + override fun toString(): String = canonical + + companion object { + private const val MAXIMUM_INPUT_BYTES = 2_048 + private const val PREFIX_CHARACTERS = + "/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" + + /** + * @throws HermesEndpointException (an [IllegalArgumentException]) for anything the contract refuses: + * whitespace, credentials, query, fragment, percent escapes, traversal, numeric host aliases, ports + * outside 1–65535, an unsupported scheme, or plain HTTP that is not both opted in and private. + */ + fun parse(input: String, allowPrivateHttp: Boolean = false): HermesEndpoint { + // The only characters any valid endpoint holds are ASCII, so non-ASCII can never be accepted. + if (input.isEmpty() || input.length > MAXIMUM_INPUT_BYTES || + input.any { it.code !in 0x21..0x7e } || '\\' in input + ) throw invalidEndpoint() + + val separator = input.indexOf("://") + val explicitScheme = if (separator >= 0) input.substring(0, separator).lowercase() else null + val rest = when { + separator >= 0 -> input.substring(separator + 3) + // An unbracketed IPv6 literal with no path or port is unambiguous. + HermesAddress.parseIPv6(input) != null -> "[$input]" + else -> input + } + val secure = when (explicitScheme) { + null, "https" -> true + "http" -> false + else -> throw invalidEndpoint() + } + // Credentials, query and fragment never belong in an endpoint, even when empty. + if (rest.any { it == '@' || it == '?' || it == '#' }) throw invalidEndpoint() + + val slash = rest.indexOf('/') + val authority = if (slash >= 0) rest.substring(0, slash) else rest + val path = if (slash >= 0) rest.substring(slash) else "" + if ('%' in authority) throw invalidEndpoint() // zone IDs and escaped hosts + + val (host, portText) = splitAuthority(authority) + val port = portText?.let { parsePort(it) } + if (!validHost(host)) throw invalidEndpoint() + + if (path.any { it !in PREFIX_CHARACTERS } || "//" in path || + path.split('/').any { it == "." || it == ".." } + ) throw invalidEndpoint() + + if (!secure && !(allowPrivateHttp && HermesAddress.isPrivateNetworkHost(host))) { + throw HermesEndpointException(HermesEndpointException.Reason.PlaintextNotAllowed) + } + val defaultPort = if (secure) 443 else 80 + return HermesEndpoint( + isSecure = secure, + host = host, + port = port?.takeIf { it != defaultPort }, + prefix = path.removeSuffix("/"), + allowPrivateHttp = allowPrivateHttp, + ) + } + + /** Host (lowercase, no brackets) and the raw port digits, when a port is present. */ + private fun splitAuthority(authority: String): Pair { + if (authority.startsWith("[")) { + val close = authority.indexOf(']') + if (close < 0) throw invalidEndpoint() + val literal = authority.substring(1, close).lowercase() + if (HermesAddress.parseIPv6(literal) == null) throw invalidEndpoint() + val after = authority.substring(close + 1) + return when { + after.isEmpty() -> literal to null + after.startsWith(":") -> literal to after.substring(1) + else -> throw invalidEndpoint() + } + } + // An unbracketed host never holds ':' except before its port. + val colon = authority.indexOf(':') + if (colon < 0) return authority.lowercase() to null + if (authority.indexOf(':', colon + 1) >= 0) throw invalidEndpoint() + return authority.substring(0, colon).lowercase() to authority.substring(colon + 1) + } + + private fun parsePort(text: String): Int { + // An empty port ("host:") is refused rather than read as the default. + if (text.isEmpty() || text.length > 5 || !text.all { it in '0'..'9' }) throw invalidEndpoint() + return text.toInt().also { if (it !in 1..65_535) throw invalidEndpoint() } + } + + private fun validHost(host: String): Boolean { + if (host.isEmpty()) return false + if (':' in host) return HermesAddress.parseIPv6(host) != null // bracketed literal, already checked + if (HermesAddress.parseIPv4(host) != null) return true + // Refuse numeric aliases (127.1, integer and hex IPv4) and ambiguous DNS. + if (host.length > 253 || host.all { it in '0'..'9' || it == '.' } || host.startsWith("0x")) return false + return host.split('.').all { label -> + label.length in 1..63 && label.first() != '-' && label.last() != '-' && + label.all { it in 'a'..'z' || it in '0'..'9' || it == '-' } + } + } + + private fun invalidEndpoint() = HermesEndpointException(HermesEndpointException.Reason.InvalidEndpoint) + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt new file mode 100644 index 00000000..27a855c3 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt @@ -0,0 +1,272 @@ +package app.bighelp.hermes + +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** A frame that must not be applied. Carries only a category, never frame text. */ +class WireException(val kind: Kind) : Exception(kind.category) { + enum class Kind(val category: String) { + InvalidResponse("invalidResponse"), + MessageTooLarge("messageTooLarge"), + } + + /** The shared vectors' name for [kind]. */ + val category: String get() = kind.category +} + +/** + * One decoded gateway entry. IDs are the exact decoded strings: never trimmed, normalized or replaced, + * so canonically equivalent but byte-distinct IDs stay distinct. + */ +sealed interface WireMessage { + /** `event:`, `request:`, `result:` or `failure:`, as in the shared vectors. */ + val classification: String + + /** `parameters` is the complete original `params`, including future envelope metadata. */ + data class Event( + val type: String, + val sessionID: String?, + val payload: JsonObject, + val sequence: Long?, + val parameters: JsonObject = JsonObject(emptyMap()), + ) : WireMessage { + override val classification get() = "event:$type" + } + + /** A live server request, answered with the same [id]. Absent or null `params` become `{}`. */ + data class Request(val id: String, val method: String, val params: JsonObject) : WireMessage { + override val classification get() = "request:$method" + } + + data class Result(val id: String, val value: JsonElement) : WireMessage { + override val classification get() = "result:$id" + } + + /** `reason` is `error.data.reason`; `message` is Hermes' words flattened for display, never a decision input. */ + data class Failure(val id: String, val code: Long, val reason: String?, val message: String?) : WireMessage { + override val classification get() = "failure:$id" + } +} + +/** Exact payload of a `request.cancel` event. */ +data class RequestCancellation(val id: String, val method: String, val reason: String) + +/** + * The gateway's framing seam. [decode] validates a whole WebSocket message before returning anything, so a + * caller either gets every entry in wire order or a [WireException] and nothing: a good first line followed + * by a bad one never publishes the first. + */ +object HermesWire { + const val MAXIMUM_MESSAGE_BYTES = 4 * 1_024 * 1_024 + const val MAXIMUM_BATCH_COUNT = 4_096 + const val MAXIMUM_METHOD_BYTES = 256 + const val MAXIMUM_REQUEST_ID_BYTES = 1_024 + const val MAXIMUM_CANCELLATION_REASON_BYTES = 4_096 + const val MAXIMUM_NESTING = StrictJson.MAXIMUM_DEPTH + const val MAXIMUM_REFUSAL_CHARACTERS = 280 + + private const val NEWLINE = 0x0a.toByte() + private val CANCELLATION_KEYS = setOf("id", "method", "reason") + + /** Lines are checked in order, like the iOS decoder, so the first violation decides the category. */ + fun decode(bytes: ByteArray): List { + if (bytes.size > MAXIMUM_MESSAGE_BYTES) throw tooLarge() + val messages = ArrayList() + var start = 0 + while (start < bytes.size) { + var end = start + while (end < bytes.size && bytes[end] != NEWLINE) end++ + if (!isBlank(bytes, start, end)) { + if (messages.size >= MAXIMUM_BATCH_COUNT) throw tooLarge() + validateNesting(bytes, start, end) + messages += decodeLine(bytes, start, end) + } + start = end + 1 + } + if (messages.isEmpty()) throw invalid() + return messages + } + + fun isValidMethod(method: String): Boolean = + method.length in 1..MAXIMUM_METHOD_BYTES && method.all { it.code in 33..126 } + + fun isValidRequestID(id: String): Boolean = utf8Length(id) <= MAXIMUM_REQUEST_ID_BYTES + + /** + * The documented cancellation is exact: only `id`, `method` and `reason`. Matching both ID and method + * stops a malformed cancel from retiring another prompt. + * @throws WireException if [event] is not a well-formed `request.cancel`. + */ + fun cancellation(event: WireMessage.Event): RequestCancellation { + val payload = event.payload + val id = payload["id"].string + val method = payload["method"].string + val reason = payload["reason"].string + if (event.type != "request.cancel" || payload.keys != CANCELLATION_KEYS || + id == null || !isValidRequestID(id) || + method == null || !isValidMethod(method) || + reason == null || utf8Length(reason) > MAXIMUM_CANCELLATION_REASON_BYTES + ) throw invalid() + return RequestCancellation(id, method, reason) + } + + private fun decodeLine(bytes: ByteArray, start: Int, end: Int): WireMessage { + val text = try { + Charsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes, start, end - start)) + .toString() + } catch (_: CharacterCodingException) { + throw invalid() + } + val root = try { + StrictJson.parse(text) + } catch (_: StrictJson.Malformed) { + throw invalid() + } + val envelope = root as? JsonObject ?: throw invalid() + if (envelope["jsonrpc"].string != "2.0") throw invalid() + + val method = envelope["method"] + val hasResponse = "result" in envelope || "error" in envelope + if (method != null) { + val name = method.string?.takeIf(::isValidMethod) ?: throw invalid() + if (hasResponse) throw invalid() + return if (name == "event") event(envelope) else request(envelope, name) + } + return response(envelope) + } + + private fun event(envelope: JsonObject): WireMessage { + if ("id" in envelope) throw invalid() + val params = envelope["params"] as? JsonObject ?: throw invalid() + val type = params["type"].string?.takeIf { it.isNotEmpty() && utf8Length(it) <= MAXIMUM_METHOD_BYTES } + ?: throw invalid() + val payload = params["payload"] + if (payload != null && payload !is JsonObject) throw invalid() + val session = params["session_id"] + if (session != null && session !is JsonNull && session.string == null) throw invalid() + val seq = params["seq"] + if (seq != null && seq.integer == null) throw invalid() + val event = WireMessage.Event( + type = type, + sessionID = session.string, + payload = payload as? JsonObject ?: JsonObject(emptyMap()), + sequence = seq.integer, + parameters = params, + ) + if (type == "request.cancel") cancellation(event) + return event + } + + private fun request(envelope: JsonObject, method: String): WireMessage { + // Backend notifications use method "event"; any other method needs a string ID to be a request. + val id = envelope["id"].string?.takeIf(::isValidRequestID) ?: throw invalid() + val params = when (val raw = envelope["params"]) { + null, JsonNull -> JsonObject(emptyMap()) + is JsonObject -> raw + else -> throw invalid() + } + return WireMessage.Request(id, method, params) + } + + private fun response(envelope: JsonObject): WireMessage { + // This client uses string IDs only; a numeric, null or absent ID is never reinterpreted. + val id = envelope["id"].string?.takeIf(::isValidRequestID) ?: throw invalid() + if ("params" in envelope) throw invalid() + val error = envelope["error"] as? JsonObject + val code = error?.get("code").integer + val result = envelope["result"] + return when { + error != null && code != null -> { + if (result != null) throw invalid() + val data = error["data"] as? JsonObject + WireMessage.Failure(id, code, data?.get("reason").string, refusalText(error["message"].string)) + } + result != null && "error" !in envelope -> WireMessage.Result(id, result) + else -> throw invalid() + } + } + + /** Counts `{`/`[` depth outside strings before any parsing, so hostile nesting never reaches the parser. */ + private fun validateNesting(bytes: ByteArray, start: Int, end: Int) { + var depth = 0 + var quoted = false + var escaped = false + for (index in start until end) { + val byte = bytes[index].toInt() + if (quoted) { + if (escaped) escaped = false + else if (byte == 0x5c) escaped = true + else if (byte == 0x22) quoted = false + } else if (byte == 0x22) quoted = true + else if (byte == 0x7b || byte == 0x5b) { + depth++ + if (depth > MAXIMUM_NESTING) throw tooLarge() + } else if (byte == 0x7d || byte == 0x5d) depth-- + } + } + + private fun isBlank(bytes: ByteArray, start: Int, end: Int): Boolean { + for (index in start until end) { + val byte = bytes[index].toInt() + if (byte != 0x20 && byte != 0x0d && byte != 0x09) return false + } + return true + } + + /** Hermes' refusal words as one short line of plain text: breaks, control and format characters become spaces. */ + private fun refusalText(raw: String?): String? { + if (raw.isNullOrEmpty()) return null + val words = ArrayList() + val word = StringBuilder() + var index = 0 + while (index < raw.length) { + val point = raw.codePointAt(index) + index += Character.charCount(point) + val separator = Character.isWhitespace(point) || Character.isSpaceChar(point) || + Character.getType(point).let { it == Character.CONTROL.toInt() || it == Character.FORMAT.toInt() } + if (separator) { + if (word.isNotEmpty()) { words += word.toString(); word.setLength(0) } + } else word.appendCodePoint(point) + } + if (word.isNotEmpty()) words += word.toString() + val line = words.joinToString(" ") + if (line.isEmpty()) return null + if (line.codePointCount(0, line.length) <= MAXIMUM_REFUSAL_CHARACTERS) return line + return line.substring(0, line.offsetByCodePoints(0, MAXIMUM_REFUSAL_CHARACTERS - 1)) + "…" + } + + private fun invalid() = WireException(WireException.Kind.InvalidResponse) + private fun tooLarge() = WireException(WireException.Kind.MessageTooLarge) + + private val JsonElement?.string: String? + get() = (this as? JsonPrimitive)?.takeIf { it.isString }?.content + + /** Only a JSON integer literal that fits 64 bits; `1.0`, `1e2`, strings and null are not integers. */ + private val JsonElement?.integer: Long? + get() = (this as? JsonPrimitive)?.takeIf { !it.isString && this !is JsonNull }?.content?.toLongOrNull() +} + +/** UTF-8 byte length of a string that holds no unpaired surrogate (the parser never produces one). */ +internal fun utf8Length(text: String): Int { + var bytes = 0 + var index = 0 + while (index < text.length) { + val unit = text[index] + bytes += when { + unit.code < 0x80 -> 1 + unit.code < 0x800 -> 2 + unit.isHighSurrogate() -> { index++; 4 } + else -> 3 + } + index++ + } + return bytes +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt new file mode 100644 index 00000000..5c4944a0 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt @@ -0,0 +1,209 @@ +package app.bighelp.hermes + +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 + +/** + * RFC 8259 parser for one gateway line. Trailing commas, comments, leading zeros, non-finite numbers, + * duplicate object keys and unpaired surrogate escapes are all rejected: the wire layer treats any of + * them as an invalid frame instead of guessing which value a host meant. + * + * Integers that fit a signed 64-bit value stay [Long]; every other number must be a finite [Double], so + * `1.0` is deliberately not an integer cursor. + */ +internal class StrictJson private constructor(private val text: String) { + private var position = 0 + + class Malformed : Exception() { + // A parse failure carries no frame text and no stack: it only means "reject the frame". + override fun fillInStackTrace(): Throwable = this + } + + companion object { + const val MAXIMUM_DEPTH = 64 + + /** @throws Malformed for any grammar violation or nesting beyond [MAXIMUM_DEPTH]. */ + fun parse(text: String): JsonElement { + val parser = StrictJson(text) + parser.skipWhitespace() + val value = parser.value(depth = 0) + parser.skipWhitespace() + if (parser.position != text.length) throw Malformed() + return value + } + } + + private fun value(depth: Int): JsonElement { + if (position >= text.length) throw Malformed() + return when (val c = text[position]) { + '{' -> obj(depth + 1) + '[' -> array(depth + 1) + '"' -> JsonPrimitive(string()) + 't' -> literal("true", JsonPrimitive(true)) + 'f' -> literal("false", JsonPrimitive(false)) + 'n' -> literal("null", JsonNull) + else -> if (c == '-' || c in '0'..'9') number() else throw Malformed() + } + } + + private fun obj(depth: Int): JsonElement { + if (depth > MAXIMUM_DEPTH) throw Malformed() + position++ // { + val members = LinkedHashMap() + skipWhitespace() + if (peek() == '}') { position++; return JsonObject(members) } + while (true) { + skipWhitespace() + if (peek() != '"') throw Malformed() + val key = string() + skipWhitespace() + if (peek() != ':') throw Malformed() + position++ + skipWhitespace() + val member = value(depth) + // First-wins (Foundation) and last-wins (most others) disagree; a duplicate is never legitimate. + if (members.put(key, member) != null) throw Malformed() + skipWhitespace() + when (peek()) { + ',' -> position++ + '}' -> { position++; return JsonObject(members) } + else -> throw Malformed() + } + } + } + + private fun array(depth: Int): JsonElement { + if (depth > MAXIMUM_DEPTH) throw Malformed() + position++ // [ + val elements = ArrayList() + skipWhitespace() + if (peek() == ']') { position++; return JsonArray(elements) } + while (true) { + skipWhitespace() + elements += value(depth) + skipWhitespace() + when (peek()) { + ',' -> position++ + ']' -> { position++; return JsonArray(elements) } + else -> throw Malformed() + } + } + } + + private fun string(): String { + position++ // opening quote + val out = StringBuilder() + while (true) { + if (position >= text.length) throw Malformed() + val c = text[position++] + when { + c == '"' -> return out.toString() + c < ' ' -> throw Malformed() // raw control characters must be escaped + c == '\\' -> { + if (position >= text.length) throw Malformed() + when (text[position++]) { + '"' -> out.append('"') + '\\' -> out.append('\\') + '/' -> out.append('/') + 'b' -> out.append('\b') + 'f' -> out.append('\u000c') + 'n' -> out.append('\n') + 'r' -> out.append('\r') + 't' -> out.append('\t') + 'u' -> out.append(unicodeEscape()) + else -> throw Malformed() + } + } + // An unpaired surrogate cannot be echoed back as the same UTF-8 bytes. Valid pairs are + // consumed together, so any surrogate seen on its own is a lone one. + c.isHighSurrogate() -> { + if (position >= text.length || !text[position].isLowSurrogate()) throw Malformed() + out.append(c).append(text[position++]) + } + c.isLowSurrogate() -> throw Malformed() + else -> out.append(c) + } + } + } + + private fun unicodeEscape(): String { + val first = hex4() + val unit = first.toChar() + return when { + unit.isHighSurrogate() -> { + if (position + 1 >= text.length || text[position] != '\\' || text[position + 1] != 'u') throw Malformed() + position += 2 + val low = hex4().toChar() + if (!low.isLowSurrogate()) throw Malformed() + String(charArrayOf(unit, low)) + } + unit.isLowSurrogate() -> throw Malformed() + else -> unit.toString() + } + } + + private fun hex4(): Int { + if (position + 4 > text.length) throw Malformed() + var result = 0 + repeat(4) { + val digit = Character.digit(text[position++], 16) + // Character.digit also accepts fullwidth and other non-ASCII digits. + if (digit < 0 || text[position - 1].code > 0x7f) throw Malformed() + result = result * 16 + digit + } + return result + } + + private fun number(): JsonElement { + val start = position + if (peek() == '-') position++ + when (peek()) { + '0' -> position++ + in '1'..'9' -> digits() + else -> throw Malformed() + } + var integral = true + if (peek() == '.') { + integral = false + position++ + if (peek() !in '0'..'9') throw Malformed() + digits() + } + if (peek() == 'e' || peek() == 'E') { + integral = false + position++ + if (peek() == '+' || peek() == '-') position++ + if (peek() !in '0'..'9') throw Malformed() + digits() + } + val raw = text.substring(start, position) + if (integral) raw.toLongOrNull()?.let { return JsonPrimitive(it) } + val double = raw.toDouble() + if (!double.isFinite()) throw Malformed() + return JsonPrimitive(double) + } + + private fun digits() { + while (peek() in '0'..'9') position++ + } + + private fun literal(word: String, value: JsonElement): JsonElement { + if (!text.startsWith(word, position)) throw Malformed() + position += word.length + return value + } + + private fun peek(): Char = if (position < text.length) text[position] else '\u0000' + + private fun skipWhitespace() { + while (position < text.length) { + when (text[position]) { + ' ', '\t', '\n', '\r' -> position++ + else -> return + } + } + } +} 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/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/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/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md new file mode 100644 index 00000000..6b9cd83c --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -0,0 +1,64 @@ +# 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, secure platform persistence 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. + +- [ ] Add the Gradle wrapper, pinned build dependencies and JVM test harness. +- [ ] Write failing vector and endpoint tests; capture the failure. +- [ ] Implement the decoder and endpoint rules from `CONNECTION.md` and Swift source. +- [ ] Run all vectors and generated limit tests; independently review trust boundaries. + +### Task 2: App shell and explicitly scoped live connection + +**Files:** `android/app/`, `android/README.md`. + +**Interfaces:** App state owns consent and connection generation; screens observe state and invoke explicit actions. Demo and live repositories implement the same UI model without invented host success. + +- [ ] Add Compose app, manifest and local consent preferences with backup exclusions; introduce Keystore storage with authenticated sign-in in the next milestone. +- [ ] Add consent, connection setup, demo sessions/chat, agents and one Settings surface. +- [ ] Add consent-gated public host discovery through `HostDiscovery.check(endpoint, consentGranted): DiscoveryResult`; do not label discovery as a connection or collect credentials. +- [ ] 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. + +- [ ] Run JVM tests, Android unit checks, lint and debug assemble. +- [ ] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. +- [ ] Review the full diff, fix concrete findings and repeat affected verification. +- [ ] Document remaining acceptance gaps, commit changes and open a draft PR linked to its issue. + +### Parallel account preparation + +- [ ] Use Terra/max for browser work to prepare personal Play Console registration. +- [ ] Leave identity, verification and any required direct checkout with the maintainer; report the exact remaining steps. 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. From c0c285c51be7cb019b50cccc5781bbb4915b268f Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:05:50 -0500 Subject: [PATCH 02/18] Keep Android history clear and clarify setup feedback --- android/README.md | 4 +- .../app/bighelp/android/BighelpAppModel.kt | 5 +- .../kotlin/app/bighelp/android/ChatScreen.kt | 39 +++++----- .../app/bighelp/android/SessionsScreen.kt | 9 ++- .../app/bighelp/android/SettingsScreen.kt | 2 +- .../kotlin/app/bighelp/android/SetupScreen.kt | 25 +++++-- .../app/bighelp/android/AppModelTest.kt | 16 +++++ .../app/bighelp/android/HostDiscoveryTest.kt | 71 ++++++++++++++++++- .../plans/2026-10-27-android-foundation.md | 32 ++++----- 9 files changed, 157 insertions(+), 46 deletions(-) diff --git a/android/README.md b/android/README.md index e5abaf5b..2b7a1151 100644 --- a/android/README.md +++ b/android/README.md @@ -35,7 +35,7 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco - **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. HTTPS uses the platform's certificate checks. +- Discovery sends no cookies, tokens or custom headers, follows no redirect, reads at most 16,384 decoded bytes, and keeps no response text. 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 @@ -43,7 +43,7 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco ### 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: no credentials, no redirect, malformed and oversized bodies). 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. +`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, and a cancelled check cancelling the real call). 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. 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. diff --git a/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt index 03899b28..22874076 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt @@ -216,7 +216,10 @@ class BighelpAppModel( private fun titleFrom(message: String): String { val line = message.lineSequence().first().trim() - return if (line.length <= MAXIMUM_TITLE) line else line.take(MAXIMUM_TITLE).trimEnd() + "…" + 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 ----------------------------------------------------------------------------- diff --git a/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt index d3e8d541..491b2888 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt @@ -57,7 +57,8 @@ import kotlinx.coroutines.launch /** * A demo chat. The reader owns the scroll position: nothing moves it while they read history, Send always - * brings the newest message into view, and a Latest button appears whenever they are away from the end. + * brings the newest message into view, and a Latest button appears, in its own row above the message box, + * whenever they are away from the end. * Rows are keyed by message ID, so a row's identity survives every change to the list. */ @Composable @@ -101,34 +102,40 @@ fun ChatScreen( } } // 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 && lastIndex >= 0) listState.scrollToLatest(lastIndex, animated = false) + if (followTail && !listState.isScrollInProgress && lastIndex >= 0) { + listState.scrollToLatest(lastIndex, animated = false) + } } } - val awayFromLatest by remember { derivedStateOf { listState.canScrollForward } } + // 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")) { ChatHeader(session.title, agent, onBack) - Box(Modifier.weight(1f).fillMaxWidth()) { - LazyColumn( - state = listState, - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxSize().testTag("chat.messages"), - ) { - if (messages.isEmpty()) { - item(key = "empty") { EmptyChatNote(agent) } - } - items(messages, key = { it.id }) { message -> MessageRow(message) } + 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 (messages.isEmpty()) { + item(key = "empty") { EmptyChatNote(agent) } } - if (awayFromLatest) { + items(messages, key = { it.id }) { message -> MessageRow(message) } + } + 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()) } }, - modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp), ) } } diff --git a/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt index 3c033d4f..67cce8d2 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt @@ -112,16 +112,19 @@ private fun SessionRow(session: DemoSession, agent: DemoAgent, draft: String?, o 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 { - draft != null -> "Draft: ${draft.trim().replace('\n', ' ')}" + 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 (draft != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, - fontWeight = if (draft != null) FontWeight.Medium else FontWeight.Normal, + 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 index 8c75cbc9..840b0bf1 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt @@ -73,7 +73,7 @@ fun SettingsScreen( SectionLabel("Your data and AI") Text( if (consentGranted) "You agreed to share chat data with your computer and its AI providers." - else "Not asked yet. bighelp asks before it connects to a computer.", + 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"), diff --git a/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt index 8cf1493c..7afb2fee 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt @@ -28,7 +28,10 @@ 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 @@ -93,7 +96,7 @@ fun SetupScreen( InkButton("Check computer", onCheck, tag = "setup.check", enabled = setup.address.isNotBlank()) } - DiscoveryResultCard(setup.discovery, onCheck = onCheck, onTryDemo = onTryDemo) + DiscoveryResultCard(setup.discovery, setup.allowPrivateHttp, onCheck = onCheck, onTryDemo = onTryDemo) Spacer(Modifier.height(8.dp)) } } @@ -139,16 +142,27 @@ private fun PrivateHttpRow(checked: Boolean, enabled: Boolean, onChange: (Boolea } @Composable -private fun DiscoveryResultCard(discovery: DiscoveryState, onCheck: () -> Unit, onTryDemo: () -> Unit) { +private fun DiscoveryResultCard( + discovery: DiscoveryState, + allowPrivateHttp: Boolean, + onCheck: () -> Unit, + onTryDemo: () -> Unit, +) { when (discovery) { DiscoveryState.Idle, DiscoveryState.Checking -> Unit 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 -> - "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://." + 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." @@ -194,7 +208,8 @@ private fun ResultCard( Surface( color = MaterialTheme.colorScheme.surfaceContainerHigh, shape = RoundedCornerShape(16.dp), - modifier = Modifier.fillMaxWidth().testTag(tag), + // 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) diff --git a/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt index 93ac7e16..d1f2855e 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt @@ -264,6 +264,22 @@ class AppModelTest { 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() diff --git a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt index d6afb80b..d75b7059 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt @@ -1,9 +1,19 @@ package app.bighelp.android import app.bighelp.hermes.HermesEndpoint +import java.util.concurrent.TimeUnit +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 @@ -27,7 +37,10 @@ class HostDiscoveryTest { 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")) assertNull(request.getHeader("Authorization")) assertNull(request.getHeader("Cookie")) assertNull(request.getHeader("X-Hermes-Session-Token")) @@ -40,11 +53,18 @@ class HostDiscoveryTest { assertEquals(1, host.requestCount) } - @Test fun malformedOversizedOrNonJsonResponsesStayUnavailable() = runTest { + @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"]}"""), - json("""{"auth_required":false,"auth_flows":null}""" + "x".repeat(16_384)), MockResponse().setHeader("Content-Type", "text/html").setBody("Private proxy diagnostic"), ).forEach { response -> host.enqueue(response) @@ -52,6 +72,28 @@ class HostDiscoveryTest { } } + // 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)) @@ -59,5 +101,30 @@ class HostDiscoveryTest { 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() + } + + 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/docs/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md index 6b9cd83c..d2c3d5ee 100644 --- a/docs/superpowers/plans/2026-10-27-android-foundation.md +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -4,7 +4,7 @@ **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, secure platform persistence and UI. Demo fixtures exercise screens without a host. +**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. @@ -33,32 +33,32 @@ **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. -- [ ] Add the Gradle wrapper, pinned build dependencies and JVM test harness. -- [ ] Write failing vector and endpoint tests; capture the failure. -- [ ] Implement the decoder and endpoint rules from `CONNECTION.md` and Swift source. -- [ ] Run all vectors and generated limit tests; independently review trust boundaries. +- [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 explicitly scoped live connection +### Task 2: App shell and public host discovery **Files:** `android/app/`, `android/README.md`. -**Interfaces:** App state owns consent and connection generation; screens observe state and invoke explicit actions. Demo and live repositories implement the same UI model without invented host success. +**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. -- [ ] Add Compose app, manifest and local consent preferences with backup exclusions; introduce Keystore storage with authenticated sign-in in the next milestone. -- [ ] Add consent, connection setup, demo sessions/chat, agents and one Settings surface. -- [ ] Add consent-gated public host discovery through `HostDiscovery.check(endpoint, consentGranted): DiscoveryResult`; do not label discovery as a connection or collect credentials. -- [ ] Test consent, failed setup, draft preservation and demo control behavior. +- [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. -- [ ] Run JVM tests, Android unit checks, lint and debug assemble. -- [ ] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. +- [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. - [ ] Review the full diff, fix concrete findings and repeat affected verification. -- [ ] Document remaining acceptance gaps, commit changes and open a draft PR linked to its issue. +- [ ] Document remaining acceptance gaps, commit changes and open a pull request linked to its issue. ### Parallel account preparation -- [ ] Use Terra/max for browser work to prepare personal Play Console registration. -- [ ] Leave identity, verification and any required direct checkout with the maintainer; report the exact remaining steps. +- [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. From 03530e8b4f1baf73b8be27f133b030964d4601c9 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:26:39 -0500 Subject: [PATCH 03/18] Run Android CI within the repository action policy --- .github/workflows/android.yml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 4860e921..e2bda802 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -22,7 +22,7 @@ concurrency: jobs: build: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 defaults: run: working-directory: android @@ -32,8 +32,17 @@ jobs: with: distribution: temurin java-version: '17' - - uses: android-actions/setup-android@v3 - - uses: gradle/actions/setup-gradle@v4 + 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 From 591c44dba80477f135f9b3e191b93dd6edc26b0e Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:37:46 -0500 Subject: [PATCH 04/18] Avoid stale pooled sockets during Android host discovery --- .../app/bighelp/android/HostDiscovery.kt | 8 +- .../app/bighelp/android/HostDiscoveryTest.kt | 76 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt index da70b8e0..4e4e5a80 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt @@ -37,7 +37,9 @@ fun interface HostChecker { * 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. The decoded body is capped at + * 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]. @@ -50,6 +52,10 @@ class HostDiscovery(private val client: OkHttpClient = defaultClient) : HostChec .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 diff --git a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt index d75b7059..c4fdc18e 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt @@ -1,7 +1,13 @@ 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 @@ -41,6 +47,7 @@ class HostDiscoveryTest { 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")) @@ -118,6 +125,75 @@ class HostDiscoveryTest { 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) From 6f721ffbc351c1ace751d6eabc9388f151f1d660 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:49:17 -0500 Subject: [PATCH 05/18] Record Android preview verification and remaining milestones --- android/README.md | 12 ++++++++++-- .../plans/2026-10-27-android-foundation.md | 6 ++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/android/README.md b/android/README.md index 2b7a1151..6798e861 100644 --- a/android/README.md +++ b/android/README.md @@ -35,7 +35,7 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco - **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. 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. +- 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 @@ -43,7 +43,15 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco ### 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, and a cancelled check cancelling the real call). 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. +`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. diff --git a/docs/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md index d2c3d5ee..03e343f4 100644 --- a/docs/superpowers/plans/2026-10-27-android-foundation.md +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -55,8 +55,10 @@ - [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. -- [ ] Review the full diff, fix concrete findings and repeat affected verification. -- [ ] Document remaining acceptance gaps, commit changes and open a pull request linked to its issue. +- [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 From ac54ff898ed8e66b4442b6c325f9f1ee8fce3543 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:59:58 -0500 Subject: [PATCH 06/18] Plan the functioning Android app and parity acceptance --- .../plans/2026-10-27-android-parity.md | 95 +++++++++++++++++++ .../specs/2026-10-27-android-parity-design.md | 44 +++++++++ 2 files changed, 139 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-27-android-parity.md create mode 100644 docs/superpowers/specs/2026-10-27-android-parity-design.md 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..a18c0be3 --- /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 401-only retirement, 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-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. From c65c476b6d154e96f64c921644a336af0e00614b Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:07:28 -0500 Subject: [PATCH 07/18] Track Android parity and match current refresh rejection behavior --- docs/ANDROID_PARITY.md | 52 +++++++++++++++++++ docs/hermes/CONNECTION.md | 4 +- .../plans/2026-10-27-android-parity.md | 2 +- 3 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 docs/ANDROID_PARITY.md diff --git a/docs/ANDROID_PARITY.md b/docs/ANDROID_PARITY.md new file mode 100644 index 00000000..1e85a113 --- /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 | Not started | Pending | +| 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-parity.md b/docs/superpowers/plans/2026-10-27-android-parity.md index a18c0be3..b83fb625 100644 --- a/docs/superpowers/plans/2026-10-27-android-parity.md +++ b/docs/superpowers/plans/2026-10-27-android-parity.md @@ -36,7 +36,7 @@ **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 401-only retirement, mode/principal changes, response bounds, no redirects/cookies/retries and cancellation. +- [ ] 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. From 97b5db4d230c882e6220f3ad386062f5e9f52179 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:14:43 -0500 Subject: [PATCH 08/18] Add encrypted storage for Android sign-in records --- .../android/storage/AndroidCredentialKey.kt | 28 +++ .../android/storage/ProtectedRecordStore.kt | 100 +++++++++++ .../bighelp/android/storage/RecordCipher.kt | 63 +++++++ .../storage/ProtectedRecordStoreTest.kt | 168 ++++++++++++++++++ 4 files changed, 359 insertions(+) create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt 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..f554baed --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt @@ -0,0 +1,28 @@ +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 + +/** One non-exportable device key. Records remain unavailable if the key is lost or invalidated. */ +object AndroidCredentialKey { + private const val ALIAS = "bighelp.credentials.v1" + + @Synchronized + fun get(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(ALIAS, null) as? SecretKey)?.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..2034ad20 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt @@ -0,0 +1,100 @@ +package app.bighelp.android.storage + +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.nio.channels.FileChannel +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.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(private val directory: File, private val cipher: RecordCipher) { + fun read(key: String): ByteArray? = locked(key) { file -> readRecord(key, file) } + + 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 + } + + private fun readRecord(key: String, file: File): ByteArray? { + if (!file.exists()) return null + val bytes = file.inputStream().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 { + FileOutputStream(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(), ATOMIC_MOVE, REPLACE_EXISTING) + 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 { + require(key.isNotEmpty() && key.toByteArray(Charsets.UTF_8).size <= 8_192) + try { + Files.createDirectories(directory.toPath()) + val digest = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) + .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() + } +} 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..f54da6a1 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -0,0 +1,63 @@ +package app.bighelp.android.storage + +import java.security.GeneralSecurityException +import javax.crypto.AEADBadTagException +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +enum class StorageProblem { CorruptRecord, RecordTooLarge, KeyUnavailable, DiskUnavailable } + +/** Carries a category, never a credential, authority or filesystem path. */ +class RecordStorageException(val problem: StorageProblem) : Exception(problem.name) + +/** The authority is authenticated too: copying ciphertext to another host never adopts its identity. */ +class RecordCipher(private val key: () -> SecretKey) { + fun encrypt(binding: String, plaintext: ByteArray): ByteArray { + if (plaintext.size > MAXIMUM_RECORD_BYTES) throw RecordStorageException(StorageProblem.RecordTooLarge) + val secret = deviceKey() + try { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, secret) + cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + 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) + } + } + + 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 secret = deviceKey() + try { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val nonce = envelope.copyOfRange(MAGIC.size, MAGIC.size + NONCE_BYTES) + cipher.init(Cipher.DECRYPT_MODE, secret, GCMParameterSpec(128, nonce)) + cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + 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) + } + } + + private fun deviceKey(): SecretKey = try { + key() + } 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 + } +} 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..4ea062e7 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -0,0 +1,168 @@ +package app.bighelp.android.storage + +import java.nio.file.Files +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.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) } + } + + @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)) + } + + private fun refuses(problem: StorageProblem, action: () -> Unit) { + try { + action() + fail("Expected $problem") + } catch (failure: RecordStorageException) { + assertEquals(problem, failure.problem) + } + } +} From e2d20f33634b4b31b28f75dbf2f56c2e40106b6b Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:32:08 -0500 Subject: [PATCH 09/18] Handle Android credential key loss and storage failures safely --- android/app/build.gradle.kts | 2 + .../storage/AndroidCredentialStorageTest.kt | 93 ++++++++++++ .../android/storage/AndroidCredentialKey.kt | 19 ++- .../android/storage/ProtectedRecordStore.kt | 57 +++++++- .../bighelp/android/storage/RecordCipher.kt | 64 +++++++-- .../storage/ProtectedRecordStoreTest.kt | 132 ++++++++++++++++++ 6 files changed, 343 insertions(+), 24 deletions(-) create mode 100644 android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8ce2ef7a..29b88468 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -54,4 +54,6 @@ dependencies { 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/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/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt index f554baed..dec2ce25 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt @@ -6,17 +6,24 @@ import java.security.KeyStore import javax.crypto.KeyGenerator import javax.crypto.SecretKey -/** One non-exportable device key. Records remain unavailable if the key is lost or invalidated. */ -object AndroidCredentialKey { - private const val ALIAS = "bighelp.credentials.v1" +/** 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 - fun get(): SecretKey { + override fun existing(): SecretKey? { val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } - (store.getKey(ALIAS, null) as? SecretKey)?.let { return it } + 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) + KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) .setKeySize(256) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) 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 index 2034ad20..415a33fb 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt @@ -4,8 +4,11 @@ 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 @@ -18,9 +21,16 @@ 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(private val directory: File, private val cipher: RecordCipher) { +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) @@ -38,9 +48,28 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco 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? { - if (!file.exists()) return null - val bytes = file.inputStream().use { input -> + 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) { @@ -59,12 +88,12 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco private fun writeRecord(file: File, bytes: ByteArray) { val pending = File.createTempFile(".record-", ".pending", directory) try { - FileOutputStream(pending).use { output -> + 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(), ATOMIC_MOVE, REPLACE_EXISTING) + files.move(pending.toPath(), file.toPath()) syncDirectory() } finally { Files.deleteIfExists(pending.toPath()) @@ -76,10 +105,10 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco } private fun locked(key: String, body: (File) -> T): T { - require(key.isNotEmpty() && key.toByteArray(Charsets.UTF_8).size <= 8_192) + val binding = recordBindingBytes(key) try { Files.createDirectories(directory.toPath()) - val digest = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) + 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() } @@ -98,3 +127,17 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco 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 index f54da6a1..0231b543 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -1,30 +1,52 @@ 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, KeyUnavailable, DiskUnavailable } +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) -/** The authority is authenticated too: copying ciphertext to another host never adopts its identity. */ -class RecordCipher(private val key: () -> SecretKey) { +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") }) + 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 secret = deviceKey() + val bindingBytes = recordBindingBytes(binding) + val secret = deviceKey(create = true) try { - val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val cipher = cipherFactory() cipher.init(Cipher.ENCRYPT_MODE, secret) - cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + 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) } } @@ -33,22 +55,28 @@ class RecordCipher(private val key: () -> SecretKey) { if (envelope.size < OVERHEAD_BYTES || !envelope.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) { throw RecordStorageException(StorageProblem.CorruptRecord) } - val secret = deviceKey() + val bindingBytes = recordBindingBytes(binding) + val secret = deviceKey(create = false) try { - val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val cipher = cipherFactory() val nonce = envelope.copyOfRange(MAGIC.size, MAGIC.size + NONCE_BYTES) cipher.init(Cipher.DECRYPT_MODE, secret, GCMParameterSpec(128, nonce)) - cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + 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(): SecretKey = try { - key() + 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) } @@ -61,3 +89,17 @@ class RecordCipher(private val key: () -> SecretKey) { 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/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt index 4ea062e7..58233947 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -1,12 +1,20 @@ 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 @@ -81,6 +89,10 @@ class ProtectedRecordStoreTest { 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() { @@ -157,6 +169,126 @@ class ProtectedRecordStoreTest { 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")) } + 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() From f421b45e70371ad01610d62f8d74c145b219d08d Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:04:36 -0500 Subject: [PATCH 10/18] Restrict record-key helpers and record verified Android storage --- .../src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt | 2 +- .../app/bighelp/android/storage/ProtectedRecordStoreTest.kt | 1 + docs/ANDROID_PARITY.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) 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 index 0231b543..1e396cd4 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -26,7 +26,7 @@ class RecordCipher internal constructor( private val cipherFactory: () -> Cipher, ) { constructor(keys: RecordKeyProvider) : this(keys, { Cipher.getInstance("AES/GCM/NoPadding") }) - constructor(key: () -> SecretKey) : this(object : RecordKeyProvider { + internal constructor(key: () -> SecretKey) : this(object : RecordKeyProvider { override fun existing() = key() override fun getOrCreate() = key() }) 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 index 58233947..6d8fc053 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -177,6 +177,7 @@ class ProtectedRecordStoreTest { 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)) } diff --git a/docs/ANDROID_PARITY.md b/docs/ANDROID_PARITY.md index 1e85a113..e58e3512 100644 --- a/docs/ANDROID_PARITY.md +++ b/docs/ANDROID_PARITY.md @@ -12,7 +12,7 @@ Contract references below name chapters under `docs/hermes/`, with product refer | 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 | 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 | From 32a6ee9c5b7d7f336c61bdaceb92b1adc0f358c8 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:30:03 -0500 Subject: [PATCH 11/18] Add real Hermes authentication and ordered gateway transport --- android/hermes/build.gradle.kts | 8 +- .../app/bighelp/hermes/BrowserSignIn.kt | 279 ++++++ .../app/bighelp/hermes/GatewayClient.kt | 894 ++++++++++++++++++ .../kotlin/app/bighelp/hermes/GatewayTypes.kt | 98 ++ .../kotlin/app/bighelp/hermes/HermesAccess.kt | 134 +++ .../app/bighelp/hermes/HermesAuthParsers.kt | 231 +++++ .../app/bighelp/hermes/HermesAuthTypes.kt | 84 ++ .../app/bighelp/hermes/HermesAuthenticator.kt | 663 +++++++++++++ .../app/bighelp/hermes/HermesCredentials.kt | 213 +++++ .../app/bighelp/hermes/HermesException.kt | 50 + .../kotlin/app/bighelp/hermes/HermesHttp.kt | 100 ++ .../app/bighelp/hermes/HermesHttpLimits.kt | 105 ++ .../app/bighelp/hermes/HermesSecrets.kt | 27 + .../app/bighelp/hermes/OkHttpHermesHttp.kt | 240 +++++ .../app/bighelp/hermes/ServerRequestTable.kt | 56 ++ .../app/bighelp/hermes/GatewayFramingTest.kt | 144 +++ .../bighelp/hermes/GatewayHandshakeTest.kt | 284 ++++++ .../app/bighelp/hermes/GatewayRecoveryTest.kt | 193 ++++ .../app/bighelp/hermes/GatewayRpcTest.kt | 239 +++++ .../hermes/GatewayServerRequestTest.kt | 266 ++++++ .../app/bighelp/hermes/GatewayTestSupport.kt | 99 ++ .../app/bighelp/hermes/HermesAccessTest.kt | 119 +++ .../bighelp/hermes/HermesAuthParsersTest.kt | 234 +++++ .../hermes/HermesAuthenticatorBrowserTest.kt | 203 ++++ .../hermes/HermesAuthenticatorSessionTest.kt | 521 ++++++++++ .../hermes/HermesAuthenticatorSignInTest.kt | 366 +++++++ .../hermes/LoopbackCallbackListenerTest.kt | 231 +++++ .../bighelp/hermes/OkHttpHermesHttpTest.kt | 399 ++++++++ .../hermes/OkHttpWebSocketNegotiationTest.kt | 77 ++ .../bighelp/hermes/RealHostIntegrationTest.kt | 352 +++++++ .../app/bighelp/hermes/SavedConnectionTest.kt | 139 +++ .../app/bighelp/hermes/ScriptedGateway.kt | 183 ++++ .../kotlin/app/bighelp/hermes/ScriptedHost.kt | 69 ++ 33 files changed, 7299 insertions(+), 1 deletion(-) create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthTypes.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthenticator.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesCredentials.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesException.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesHttp.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesHttpLimits.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesSecrets.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/OkHttpHermesHttp.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/ServerRequestTable.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayFramingTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayHandshakeTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRecoveryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRpcTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayServerRequestTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTestSupport.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAccessTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthParsersTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorBrowserTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSessionTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSignInTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/LoopbackCallbackListenerTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpHermesHttpTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/SavedConnectionTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedGateway.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedHost.kt diff --git a/android/hermes/build.gradle.kts b/android/hermes/build.gradle.kts index 9123188d..a123dbca 100644 --- a/android/hermes/build.gradle.kts +++ b/android/hermes/build.gradle.kts @@ -5,8 +5,14 @@ kotlin { jvmToolchain(17) } dependencies { - implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + // 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 stays an implementation detail: no public signature mentions its types. + 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") } tasks.test { val wireVectors = rootProject.file("../docs/hermes/vectors/wire.json") 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..628aa67a --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt @@ -0,0 +1,894 @@ +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.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 +import okhttp3.Headers +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import okio.ByteString + +/** + * 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. + * + * Known limitation: OkHttp 4.12 assembles an inbound WebSocket message before delivering it, so the 4 MiB + * cap is enforced on arrival rather than while streaming, and a malformed UTF-8 text frame is repaired by + * the platform before [HermesWire] sees it. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class GatewayClient( + private val authenticator: HermesAuthenticator, + private val scope: CoroutineScope, + private val timings: GatewayTimings = GatewayTimings(), +) { + private val serial: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1) + private val okHttp = HermesOkHttp.baseClient().newBuilder() + .callTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) + .readTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) + .writeTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) + .build() + + // 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 + + 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 + } + + private class Outbound(val id: String, val serverMethod: String?, val text: String, val bytes: Int) + 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 webSocket: WebSocket? = 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 queuedServerBytes = 0 + var attachmentId: String? = null + 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() + + val headers = Headers.Builder() + request.headers.forEach { (name, value) -> headers.addUnsafeNonAscii(name, value) } + val upgrade = Request.Builder().url(request.url).headers(headers.build()).build() + created.webSocket = okHttp.newWebSocket(upgrade, listenerFor(created)) + 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 + } + + private fun listenerFor(owner: Link) = object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + owner.inbound.trySendBlocking(Inbound.Opened(response.header("Sec-WebSocket-Protocol"))) + } + + override fun onMessage(webSocket: WebSocket, text: String) { + // Characters never outnumber bytes: anything over the cap in characters is over it in bytes. + val tooLarge = text.length > HermesWire.MAXIMUM_MESSAGE_BYTES + owner.inbound.trySendBlocking( + if (tooLarge) Inbound.Failed(HermesException(HermesException.Kind.MessageTooLarge)) + else Inbound.Message(text.toByteArray(Charsets.UTF_8)), + ) + } + + override fun onMessage(webSocket: WebSocket, bytes: ByteString) { + owner.inbound.trySendBlocking( + if (bytes.size > HermesWire.MAXIMUM_MESSAGE_BYTES) Inbound.Failed(HermesException(HermesException.Kind.MessageTooLarge)) + else Inbound.Message(bytes.toByteArray()), + ) + } + + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + webSocket.close(1000, null) + owner.inbound.trySendBlocking(Inbound.Failed(HermesException(HermesException.Kind.Disconnected))) + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + owner.inbound.trySendBlocking(Inbound.Failed(HermesException(HermesException.Kind.Disconnected))) + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + val status = response?.code + val error = when { + status == 401 || status == 403 -> HermesException(HermesException.Kind.InvalidCredentials) + status != null && status in 300..399 -> HermesException(HermesException.Kind.RedirectRefused) + else -> OkHttpHermesHttp.map(t) + } + 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. + */ + suspend fun request( + method: String, + params: JsonObject = JsonObject(emptyMap()), + timeoutMillis: Long = timings.requestMillis, + operation: GatewayOperation? = null, + maximumFrameBytes: Int = DEFAULT_FRAME_BYTES, + ): JsonElement { + val live = withContext(serial) { link } ?: 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) + if (isAttachment && owner.attachmentId != null) throw HermesException(HermesException.Kind.TooManyRequests) + val queuedLimit = if (isAttachment) ATTACHMENT_FRAME_BYTES else MAXIMUM_QUEUED_BYTES + if (owner.queuedBytes + bytes > queuedLimit) 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)) + 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) owner.queuedBytes -= owner.outbox.removeAt(index).bytes + 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) + } + + /** The single ordered writer. Nothing leaves before ready; each frame is marked sent before the socket call. */ + private fun pump(owner: Link) { + if (owner.closed || owner.socket.phase != SocketPhase.Ready) return + val socket = owner.webSocket ?: return + while (owner.outbox.isNotEmpty()) { + val item = owner.outbox.removeFirst() + owner.queuedBytes -= item.bytes + if (item.serverMethod != null) { + owner.queuedServerBytes -= item.bytes + if (!owner.serverRequests.beginSendingResponse(item.id, item.serverMethod)) continue + } else { + val pending = owner.pending[item.id] ?: continue + pending.sendStarted = true + } + if (!socket.send(item.text)) { + closeLink(owner, HermesException(HermesException.Kind.Disconnected), notify = true) + return + } + } + } + + // 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.queuedBytes += 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) { + val removed = owner.outbox.removeAt(index) + owner.queuedBytes -= removed.bytes + owner.queuedServerBytes -= removed.bytes + } + } + + /** + * 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() + okHttp.dispatcher.executorService.shutdown() + okHttp.connectionPool.evictAll() + } + + 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.webSocket?.let { socket -> + if (orderly) { + socket.close(1001, null) + scope.launch(serial) { delay(1_000); socket.cancel() } + } else { + socket.cancel() + } + } + 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.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 + // 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/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/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/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/OkHttpWebSocketNegotiationTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt new file mode 100644 index 00000000..07ebcfdd --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt @@ -0,0 +1,77 @@ +package app.bighelp.hermes + +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The gated gateway authenticates with `Sec-WebSocket-Protocol: hermes-gateway-v1, hermes-gateway-ticket.` + * and the host answers with the negotiated `hermes-gateway-v1`. These tests prove the platform + * WebSocket (OkHttp) really sends a hand-set two-value header, lets proxy headers ride the upgrade, + * sends no cookies, and exposes the negotiated value, before any client code depends on it. + */ +class OkHttpWebSocketNegotiationTest { + private val server = MockWebServer() + + @After fun stop() = server.shutdown() + + private fun upgrade(negotiated: String?, onOpen: (WebSocket) -> Unit = {}) { + val response = MockResponse() + if (negotiated != null) response.setHeader("Sec-WebSocket-Protocol", negotiated) + server.enqueue(response.withWebSocketUpgrade(object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) = onOpen(webSocket) + })) + server.start() + } + + private fun open(request: Request): Pair { + val opened = CompletableFuture() + val socket = OkHttpClient.Builder().build().newWebSocket(request, object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { opened.complete(response) } + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + opened.completeExceptionally(t) + } + }) + return socket to opened.get(10, TimeUnit.SECONDS) + } + + @Test fun aHandSetTwoValueSubprotocolHeaderReachesTheHostAndTheNegotiatedValueIsReadable() { + upgrade(negotiated = "hermes-gateway-v1") + val offered = "hermes-gateway-v1, hermes-gateway-ticket.synthetic_Ticket-1" + val (socket, response) = open( + Request.Builder().url(server.url("/api/ws")).header("Sec-WebSocket-Protocol", offered).build(), + ) + val received = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("/api/ws", received.path) + assertEquals(offered, received.getHeader("Sec-WebSocket-Protocol")) + assertEquals("hermes-gateway-v1", response.header("Sec-WebSocket-Protocol")) + socket.cancel() + } + + @Test fun proxyHeadersRideTheUpgradeAndNoCookieIsSent() { + upgrade(negotiated = null) + val (socket, response) = open( + Request.Builder().url(server.url("/hermes/api/ws")) + .header("CF-Access-Client-Id", "id").header("X-Session-Gate", "g") + .header("X-Hermes-Session-Token", "dashboard-token").build(), + ) + val received = server.takeRequest(5, TimeUnit.SECONDS)!! + assertEquals("id", received.getHeader("CF-Access-Client-Id")) + assertEquals("g", received.getHeader("X-Session-Gate")) + assertEquals("dashboard-token", received.getHeader("X-Hermes-Session-Token")) + assertNull(received.getHeader("Cookie")) + assertNull("A dashboard upgrade offers no subprotocol", received.getHeader("Sec-WebSocket-Protocol")) + assertNull(response.header("Sec-WebSocket-Protocol")) + socket.cancel() + } +} 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..ffb63b05 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt @@ -0,0 +1,352 @@ +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) + } + + @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") + // Hermes asks only while the fixture variable is unset; an earlier answered run leaves it set. + assumeTrue("The host already holds the fixture secret, so it did not ask", "secret" in prompts.methods()) + val request = prompts.seen.first { it.method == "secret" } + assertEquals("SECURE_INPUT_FIXTURE", request.params["env_var"]?.jsonPrimitive?.content) + assertEquals(runtime, request.params["session_id"]?.jsonPrimitive?.content) + Unit + } + + @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 + assertNotEquals("The access token was renewed", bearer.accessToken, rotatedBearer.accessToken) + assertEquals("Same principal", staged.authority, rotated.authority) + assertTrue((rotatedBearer.expiresAtEpochSeconds ?: 0) > System.currentTimeMillis() / 1_000) + assertEquals(rotated, restoredAuthenticator.savedConnection) + println("REAL-HOST password rotation: accessChanged=${bearer.accessToken != rotatedBearer.accessToken} refreshChanged=${bearer.refreshToken != rotatedBearer.refreshToken}") + + // Two tickets, two sockets: a fresh single-use ticket every attempt. + val first = restoredAuthenticator.socketRequest() + val second = restoredAuthenticator.socketRequest() + assertNotEquals(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) } +} From 3d85e2810e94b8d38ff246d4ab371dbf31c7efd2 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:43:00 -0500 Subject: [PATCH 12/18] Persist Android sign-ins and configured computers securely --- .../live/AndroidCredentialAdapterTest.kt | 45 +++ .../android/live/AndroidCredentialStore.kt | 120 +++++++ .../android/live/SavedComputerStore.kt | 162 ++++++++++ .../live/AndroidCredentialStoreTest.kt | 296 ++++++++++++++++++ .../android/live/SavedComputerStoreTest.kt | 188 +++++++++++ 5 files changed, 811 insertions(+) create mode 100644 android/app/src/androidTest/kotlin/app/bighelp/android/live/AndroidCredentialAdapterTest.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/AndroidCredentialStore.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/SavedComputerStore.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/AndroidCredentialStoreTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/SavedComputerStoreTest.kt 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/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/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/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/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()) + } +} From 1223a15cd43993e8cbd251b685effbdf1315e6db Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:10:04 -0500 Subject: [PATCH 13/18] Android chat connects over a bounded, ordered Hermes WebSocket Co-Authored-By: Claude Sonnet 5.5 --- android/hermes/build.gradle.kts | 11 +- .../app/bighelp/hermes/GatewayClient.kt | 174 +++++---- .../app/bighelp/hermes/GatewayWebSocket.kt | 297 +++++++++++++++ .../app/bighelp/hermes/FakeTransport.kt | 62 ++++ .../app/bighelp/hermes/GatewayLoggingTest.kt | 71 ++++ .../app/bighelp/hermes/GatewayQueueTest.kt | 242 ++++++++++++ .../app/bighelp/hermes/GatewayRawPeerTest.kt | 349 ++++++++++++++++++ .../bighelp/hermes/GatewayTransportTest.kt | 127 +++++++ .../bighelp/hermes/GatewayTransportTlsTest.kt | 140 +++++++ .../hermes/OkHttpWebSocketNegotiationTest.kt | 77 ---- .../test/kotlin/app/bighelp/hermes/RawPeer.kt | 225 +++++++++++ .../bighelp/hermes/RealHostIntegrationTest.kt | 23 +- 12 files changed, 1636 insertions(+), 162 deletions(-) create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayLoggingTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRawPeerTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTlsTest.kt delete mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/RawPeer.kt diff --git a/android/hermes/build.gradle.kts b/android/hermes/build.gradle.kts index a123dbca..95975f45 100644 --- a/android/hermes/build.gradle.kts +++ b/android/hermes/build.gradle.kts @@ -8,11 +8,20 @@ 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 stays an implementation detail: no public signature mentions its types. + // 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") diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt index 628aa67a..17cad7ce 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt @@ -30,12 +30,6 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put -import okhttp3.Headers -import okhttp3.Request -import okhttp3.Response -import okhttp3.WebSocket -import okhttp3.WebSocketListener -import okio.ByteString /** * The ordered Hermes gateway: one authenticated WebSocket at a time, a single ordered reader and a single @@ -64,22 +58,30 @@ import okio.ByteString * 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. * - * Known limitation: OkHttp 4.12 assembles an inbound WebSocket message before delivering it, so the 4 MiB - * cap is enforced on arrival rather than while streaming, and a malformed UTF-8 text frame is repaired by - * the platform before [HermesWire] sees it. + * **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( +class GatewayClient internal constructor( private val authenticator: HermesAuthenticator, private val scope: CoroutineScope, - private val timings: GatewayTimings = GatewayTimings(), + 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) - private val okHttp = HermesOkHttp.baseClient().newBuilder() - .callTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) - .readTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) - .writeTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS) - .build() // Everything below is touched only on [serial], except the concurrent collections. private var terminal = false @@ -120,6 +122,13 @@ class GatewayClient( 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, @@ -131,7 +140,8 @@ class GatewayClient( var timeout: Job? = null } - private class Outbound(val id: String, val serverMethod: String?, val text: String, val bytes: Int) + /** [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 { @@ -142,7 +152,7 @@ class GatewayClient( private inner class Link(val generation: Long, val owner: ConnectionOwner, val request: SocketRequest) { var socket: GatewaySocket = GatewaySocket.opening(owner) - var webSocket: WebSocket? = null + var transport: GatewayTransport? = null val inbound = Channel(INBOUND_BUFFER) var reader: Job? = null var heartbeat: Job? = null @@ -151,8 +161,10 @@ class GatewayClient( 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 @@ -222,10 +234,12 @@ class GatewayClient( link = created publish() - val headers = Headers.Builder() - request.headers.forEach { (name, value) -> headers.addUnsafeNonAscii(name, value) } - val upgrade = Request.Builder().url(request.url).headers(headers.build()).build() - created.webSocket = okHttp.newWebSocket(upgrade, listenerFor(created)) + 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) @@ -234,43 +248,17 @@ class GatewayClient( return created } - private fun listenerFor(owner: Link) = object : WebSocketListener() { - override fun onOpen(webSocket: WebSocket, response: Response) { - owner.inbound.trySendBlocking(Inbound.Opened(response.header("Sec-WebSocket-Protocol"))) - } - - override fun onMessage(webSocket: WebSocket, text: String) { - // Characters never outnumber bytes: anything over the cap in characters is over it in bytes. - val tooLarge = text.length > HermesWire.MAXIMUM_MESSAGE_BYTES - owner.inbound.trySendBlocking( - if (tooLarge) Inbound.Failed(HermesException(HermesException.Kind.MessageTooLarge)) - else Inbound.Message(text.toByteArray(Charsets.UTF_8)), - ) - } - - override fun onMessage(webSocket: WebSocket, bytes: ByteString) { - owner.inbound.trySendBlocking( - if (bytes.size > HermesWire.MAXIMUM_MESSAGE_BYTES) Inbound.Failed(HermesException(HermesException.Kind.MessageTooLarge)) - else Inbound.Message(bytes.toByteArray()), - ) - } - - override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { - webSocket.close(1000, null) - owner.inbound.trySendBlocking(Inbound.Failed(HermesException(HermesException.Kind.Disconnected))) + /** 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 onClosed(webSocket: WebSocket, code: Int, reason: String) { - owner.inbound.trySendBlocking(Inbound.Failed(HermesException(HermesException.Kind.Disconnected))) + override fun message(bytes: ByteArray) { + owner.inbound.trySendBlocking(Inbound.Message(bytes)) } - override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { - val status = response?.code - val error = when { - status == 401 || status == 403 -> HermesException(HermesException.Kind.InvalidCredentials) - status != null && status in 300..399 -> HermesException(HermesException.Kind.RedirectRefused) - else -> OkHttpHermesHttp.map(t) - } + override fun failed(error: HermesException) { owner.inbound.trySendBlocking(Inbound.Failed(error)) } } @@ -497,9 +485,15 @@ class GatewayClient( ) } if (owner.pending.size >= MAXIMUM_PENDING) throw HermesException(HermesException.Kind.TooManyRequests) - if (isAttachment && owner.attachmentId != null) throw HermesException(HermesException.Kind.TooManyRequests) - val queuedLimit = if (isAttachment) ATTACHMENT_FRAME_BYTES else MAXIMUM_QUEUED_BYTES - if (owner.queuedBytes + bytes > queuedLimit) 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 @@ -508,8 +502,8 @@ class GatewayClient( delay(timeoutMillis) expire(owner, id) } - owner.outbox.addLast(Outbound(id, null, text, bytes)) - owner.queuedBytes += bytes + owner.outbox.addLast(Outbound(id, null, text, bytes, isAttachment)) + if (isAttachment) owner.queuedAttachmentBytes += bytes else owner.queuedBytes += bytes pump(owner) return pending } @@ -527,7 +521,7 @@ class GatewayClient( pending.timeout?.cancel() if (owner.attachmentId == id) owner.attachmentId = null val index = owner.outbox.indexOfFirst { it.id == id && it.serverMethod == null } - if (index >= 0) owner.queuedBytes -= owner.outbox.removeAt(index).bytes + if (index >= 0) uncount(owner, owner.outbox.removeAt(index)) return pending } @@ -543,27 +537,58 @@ class GatewayClient( if (pending.sendStarted) closeLink(owner, HermesException(HermesException.Kind.TimedOut), notify = true) } - /** The single ordered writer. Nothing leaves before ready; each frame is marked sent before the socket call. */ + /** 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 socket = owner.webSocket ?: return + val transport = owner.transport ?: return while (owner.outbox.isNotEmpty()) { + if (transport.hasBufferedData) { + drainLater(owner) + return + } val item = owner.outbox.removeFirst() - owner.queuedBytes -= item.bytes + uncount(owner, item) if (item.serverMethod != null) { - owner.queuedServerBytes -= item.bytes if (!owner.serverRequests.beginSendingResponse(item.id, item.serverMethod)) continue } else { val pending = owner.pending[item.id] ?: continue pending.sendStarted = true } - if (!socket.send(item.text)) { + 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. */ + private fun drainLater(owner: Link) { + if (owner.draining) return + owner.draining = true + scope.launch(serial) { + try { + while (!owner.closed && owner.outbox.isNotEmpty()) { + if (owner.transport?.hasBufferedData == true) delay(DRAIN_POLL_MILLIS) else pump(owner) + } + } finally { + owner.draining = false + } + } + } + // Keepalive private fun startHeartbeat(owner: Link) { @@ -671,7 +696,6 @@ class GatewayClient( } if (!owner.serverRequests.stageResponse(id, method)) return owner.outbox.addLast(Outbound(id, method, text, bytes)) - owner.queuedBytes += bytes owner.queuedServerBytes += bytes pump(owner) } @@ -706,9 +730,7 @@ class GatewayClient( owner.serverTasks.remove(cancellation.id)?.job?.cancel() val index = owner.outbox.indexOfFirst { it.id == cancellation.id && it.serverMethod == cancellation.method } if (index >= 0) { - val removed = owner.outbox.removeAt(index) - owner.queuedBytes -= removed.bytes - owner.queuedServerBytes -= removed.bytes + uncount(owner, owner.outbox.removeAt(index)) } } @@ -759,8 +781,6 @@ class GatewayClient( subscribers.clear() } authenticator.settlePendingRenewal() - okHttp.dispatcher.executorService.shutdown() - okHttp.connectionPool.evictAll() } private fun closeLink(owner: Link, reason: HermesException, notify: Boolean, orderly: Boolean = false) { @@ -771,12 +791,12 @@ class GatewayClient( if (link === owner) link = null owner.readyDeadline?.cancel() owner.heartbeat?.cancel() - owner.webSocket?.let { socket -> + owner.transport?.let { transport -> if (orderly) { - socket.close(1001, null) - scope.launch(serial) { delay(1_000); socket.cancel() } + transport.close(orderly = true) + scope.launch(serial) { delay(1_000); transport.close(orderly = false) } } else { - socket.cancel() + transport.close(orderly = false) } } owner.inbound.close() @@ -795,6 +815,7 @@ class GatewayClient( owner.serverRequests.removeAll() owner.outbox.clear() owner.queuedBytes = 0 + owner.queuedAttachmentBytes = 0 owner.queuedServerBytes = 0 owner.attachmentId = null lastFailure = reason @@ -887,6 +908,7 @@ class GatewayClient( 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 // 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/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/test/kotlin/app/bighelp/hermes/FakeTransport.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt new file mode 100644 index 00000000..bb45e644 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt @@ -0,0 +1,62 @@ +package app.bighelp.hermes + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executors +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * An in-memory gateway socket whose "unwritten data" flag the test controls, so sender backpressure is + * deterministic: no kernel buffer sizes, no timing. It answers the connect sequence and records every frame. + */ +internal class FakeTransports : GatewayTransportFactory { + private val replies = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "fake-transport").also { it.isDaemon = true } } + @Volatile var current: Fake? = null + + inner class Fake(val listener: GatewayTransportListener) : GatewayTransport { + val sent = CopyOnWriteArrayList() + @Volatile var buffered = false + + /** When true every frame leaves the socket "unwritten" until the test lets it drain. */ + @Volatile var stallAfterEachSend = false + @Volatile var closed = false + + override val hasBufferedData: Boolean get() = buffered + + override fun send(text: String): Boolean { + if (closed) return false + sent += text + if (stallAfterEachSend) buffered = true + val json = runCatching { Json.parseToJsonElement(text).jsonObject }.getOrNull() ?: return true + val id = json["id"]?.jsonPrimitive?.content ?: return true + val result = when (json["method"]?.jsonPrimitive?.content) { + "client.capabilities", "gateway.ping" -> "{}" + "gateway.capabilities" -> """{"per_session_exclusive_submit":true}""" + else -> return true + } + deliver("""{"jsonrpc":"2.0","id":${ScriptedGateway.quote(id)},"result":$result}""") + return true + } + + override fun close(orderly: Boolean) { closed = true } + + /** Delivers a line as if the host sent it, from another thread (the reader thread of a real socket). */ + fun deliver(line: String) { + replies.execute { runCatching { listener.message(line.toByteArray(Charsets.UTF_8)) } } + } + + fun methods(): List = sent.mapNotNull { runCatching { Json.parseToJsonElement(it).jsonObject["method"]?.jsonPrimitive?.content }.getOrNull() } + fun sentWithMethod(method: String) = sent.filter { it.contains("\"method\":\"$method\"") } + } + + override fun open(request: SocketRequest, listener: GatewayTransportListener): GatewayTransport { + val fake = Fake(listener) + current = fake + replies.execute { + listener.opened(null) + listener.message(ScriptedGateway.eventLine("gateway.ready", """{"heartbeat":false}""").toByteArray()) + } + return fake + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayLoggingTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayLoggingTest.kt new file mode 100644 index 00000000..3993c41b --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayLoggingTest.kt @@ -0,0 +1,71 @@ +package app.bighelp.hermes + +import java.io.ByteArrayOutputStream +import java.io.PrintStream +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import org.java_websocket.drafts.Draft_6455 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.Timeout +import org.slf4j.LoggerFactory + +/** + * The WebSocket library logs frames and handshakes at trace level and errors with their exceptions. SLF4J is + * bound to its no-op provider, so none of that can reach a log, whatever a frame or the socket URL (which + * carries a dashboard token) contains. + */ +class GatewayLoggingTest { + @get:Rule val testTimeout: Timeout = Timeout.seconds(60) + + @Test fun theBoundSlf4jProviderIsTheNoOpOneAndNoLevelIsEnabled() { + assertEquals("org.slf4j.helpers.NOPLoggerFactory", LoggerFactory.getILoggerFactory().javaClass.name) + val library = LoggerFactory.getLogger(Draft_6455::class.java) + assertFalse(library.isTraceEnabled || library.isDebugEnabled || library.isInfoEnabled || library.isWarnEnabled || library.isErrorEnabled) + } + + @Test fun aWholeSocketLifeWithTokensAndRejectedFramesWritesNothingToTheProcessOutput() { + val outBytes = ByteArrayOutputStream() + val errBytes = ByteArrayOutputStream() + val originalOut = System.out + val originalErr = System.err + System.setOut(PrintStream(outBytes, true)) + System.setErr(PrintStream(errBytes, true)) + val peer = RawPeer() + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + try { + val endpoint = HermesEndpoint.parse("http://127.0.0.1:${peer.port}", allowPrivateHttp = true) + val authenticator = HermesAuthenticator(endpoint, OkHttpHermesHttp(endpoint), InMemoryCredentialStore()) + authenticator.adoptForTest(SavedConnection(endpoint, StoredAuth.DashboardSession("secret-dashboard-token", false), null, null), false) + val client = GatewayClient( + authenticator, scope, + GatewayTimings(readyMillis = 3_000, requestMillis = 3_000, heartbeatMillis = 60_000, pingMillis = 60_000, reconnectDelaysMillis = emptyList()), + ) + val connecting = scope.async { client.connect() } + val session = peer.awaitUpgrade() + session.accept() + session.ready() + session.serve() + runBlocking { connecting.await() } + session.frame(0x1, byteArrayOf('{'.code.toByte(), 0xFF.toByte(), '}'.code.toByte())) // rejected: malformed UTF-8 + session.frameHeaderOnly(0x1, 1L shl 40) // and an oversized one, after + Thread.sleep(500) + runBlocking { client.disconnect() } + authenticator.close() + } finally { + System.setOut(originalOut) + System.setErr(originalErr) + scope.cancel() + peer.close() + } + val output = outBytes.toString() + errBytes.toString() + assertTrue("Nothing at all was written: <$output>", output.isEmpty()) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt new file mode 100644 index 00000000..a376fda6 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt @@ -0,0 +1,242 @@ +package app.bighelp.hermes + +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +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.coroutines.withTimeout +import kotlinx.serialization.json.Json +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 org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.Timeout + +/** + * The outbound queue ceilings with a deterministic stalled peer: ordinary requests 8 MiB, one attachment of up + * to 12 MiB counted apart, server replies 4 MiB. The socket's "unwritten data" flag is the test's to flip, so + * no kernel buffer size or timing decides anything. + */ +class GatewayQueueTest { + @get:Rule val testTimeout: Timeout = Timeout.seconds(90) + + private val host = ScriptedHost() + private val transports = FakeTransports() + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val resources = mutableListOf() + private val mebibyte = 1_048_576 + + private val timings = GatewayTimings( + readyMillis = 3_000, advertiseMillis = 2_000, requestMillis = 60_000, heartbeatMillis = 600_000, pingMillis = 600_000, + pingReplyMillis = 5_000, reconnectDelaysMillis = emptyList(), + ) + + @After fun stop() { + scope.cancel() + resources.forEach { runCatching { it.close() } } + host.close() + } + + /** Handlers go in before connecting: the advertisement then happens inside the handshake, not mid-test. */ + private fun connected(register: (GatewayClient) -> Unit = {}): Pair { + host.on("GET", "/api/health", ScriptedHost.json("""{"ok":true,"auth_required":false}""")) + val authenticator = HermesAuthenticator(host.endpoint, OkHttpHermesHttp(host.endpoint), InMemoryCredentialStore()) + resources += authenticator + authenticator.adoptForTest(SavedConnection(host.endpoint, StoredAuth.DashboardSession("dash-token", false), null, null), persisted = false) + val client = GatewayClient(authenticator, scope, timings, transports) + register(client) + runBlocking { client.connect() } + return client to transports.current!! + } + + private suspend fun eventually(timeoutMillis: Long = 10_000, condition: suspend () -> Boolean) { + withTimeout(timeoutMillis) { while (!condition()) delay(5) } + } + + /** Frame bytes of `{"jsonrpc","id","method","params":{"blob":...}}` with a 36-character ID. */ + private fun frameBytes(method: String, blobChars: Int) = utf8Length( + buildJsonObject { + put("jsonrpc", "2.0"); put("id", "0".repeat(36)); put("method", method) + put("params", buildJsonObject { put("blob", "x".repeat(blobChars)) }) + }.toString(), + ) + + private fun blob(method: String, targetFrameBytes: Int): JsonObject { + val chars = targetFrameBytes - frameBytes(method, 0) + require(chars >= 0) + return buildJsonObject { put("blob", "x".repeat(chars)) } + } + + private fun request(client: GatewayClient, method: String, frameBytes: Int, maximum: Int = GatewayClient.DEFAULT_FRAME_BYTES): Deferred> = + scope.async { runCatching { client.request(method, blob(method, frameBytes), maximumFrameBytes = maximum) } } + + private fun kindOf(block: suspend () -> Unit) = assertThrows(HermesException::class.java) { runBlocking { block() } }.kind + + /** Queues [count] ordinary frames of [size] bytes and waits until each is in the queue. */ + private fun fill(client: GatewayClient, count: Int, size: Int): List>> { + val calls = ArrayList>>() + repeat(count) { index -> + calls += request(client, "profiles.list", size) + runBlocking { eventually { client.queueSnapshot().frames == index + 1 } } + } + return calls + } + + @Test fun ordinaryRequestsAreHeldToEightMebibytesExactlyAndReleasedInOrder() = runBlocking { + val (client, socket) = connected() + val before = socket.sent.size + socket.buffered = true // the peer stopped reading + + fill(client, 8, mebibyte - 64) + assertEquals(8 * (mebibyte - 64), client.queueSnapshot().ordinary) + val remaining = 8 * mebibyte - client.queueSnapshot().ordinary // 512 bytes of room + request(client, "profiles.list", remaining) // exactly fills the queue + eventually { client.queueSnapshot().frames == 9 } + assertEquals("Exactly eight mebibytes", 8 * mebibyte, client.queueSnapshot().ordinary) + assertEquals(HermesException.Kind.TooManyRequests, kindOf { client.request("profiles.list") }) + assertEquals("Nothing left the socket while it was stalled", before, socket.sent.size) + + socket.buffered = false + eventually { socket.sentWithMethod("profiles.list").size == 9 } + val frames = socket.sentWithMethod("profiles.list") + assertEquals("The last queued frame went last", remaining, utf8Length(frames.last())) + assertTrue(frames.dropLast(1).all { utf8Length(it) == mebibyte - 64 }) + eventually { client.queueSnapshot().frames == 0 } + assertEquals(0, client.queueSnapshot().ordinary) + request(client, "profiles.list", 300) // the queue accepts again, and the new frame goes straight out + eventually { socket.sentWithMethod("profiles.list").size == 10 } + client.disconnect() + } + + @Test fun anAttachmentFrameUpToTwelveMebibytesIsNotBlockedByAFullOrdinaryQueue() = runBlocking { + val (client, socket) = connected() + socket.buffered = true + fill(client, 8, mebibyte) + assertEquals(8 * mebibyte, client.queueSnapshot().ordinary) + assertEquals("The ordinary queue is full", HermesException.Kind.TooManyRequests, kindOf { client.request("profiles.list") }) + + val twelve = GatewayClient.ATTACHMENT_FRAME_BYTES + val attach = request(client, "file.attach", twelve, maximum = twelve) + eventually { client.queueSnapshot().attachment == twelve } + assertEquals("Counted apart from the ordinary queue", 8 * mebibyte, client.queueSnapshot().ordinary) + assertEquals("Only one attachment RPC at a time", HermesException.Kind.TooManyRequests, kindOf { + client.request("image.attach_bytes", blob("image.attach_bytes", 1_000), maximumFrameBytes = twelve) + }) + assertEquals("Twelve mebibytes is the ceiling", HermesException.Kind.MessageTooLarge, kindOf { + client.request("file.attach", blob("file.attach", twelve + 1), maximumFrameBytes = twelve) + }) + assertEquals("An ordinary frame never gets the attachment allowance", HermesException.Kind.MessageTooLarge, kindOf { + client.request("profiles.list", blob("profiles.list", GatewayClient.DEFAULT_FRAME_BYTES + 1)) + }) + + socket.buffered = false + eventually(30_000) { socket.sentWithMethod("file.attach").size == 1 && socket.sentWithMethod("profiles.list").size == 8 } + assertEquals(twelve, utf8Length(socket.sentWithMethod("file.attach").single())) + assertEquals(0, client.queueSnapshot().attachment) + assertTrue(attach.isActive) // still waiting for its reply + client.disconnect() + } + + @Test fun aLoneTwelveMebibyteAttachmentIsAcceptedOnAnEmptyQueue() = runBlocking { + val (client, socket) = connected() + socket.buffered = true + request(client, "file.attach", GatewayClient.ATTACHMENT_FRAME_BYTES, maximum = GatewayClient.ATTACHMENT_FRAME_BYTES) + eventually { client.queueSnapshot().attachment == GatewayClient.ATTACHMENT_FRAME_BYTES } + client.disconnect() + } + + @Test fun serverRepliesAreHeldToFourMebibytesAndAreIndependentOfTheOrdinaryQueue() = runBlocking { + val (client, socket) = connected { client -> + client.setServerRequestHandler("approval") { ServerResponse.Result(buildJsonObject { put("v", JsonPrimitive("r".repeat(900_000))) }) } + } + socket.buffered = true + fill(client, 8, mebibyte) // the ordinary queue is full + repeat(5) { socket.deliver(ScriptedGateway.requestLine("approval-$it", "approval", """{"session_id":"s"}""")) } + val framesBefore = 8 + eventually { client.queueSnapshot().frames == framesBefore + 5 } + val queued = client.queueSnapshot() + assertTrue("At most four mebibytes of replies: ${queued.server}", queued.server <= 4 * mebibyte) + assertTrue("The four that fit are really queued", queued.server >= 4 * 900_000) + assertEquals("The ordinary queue was never touched by replies", 8 * mebibyte, queued.ordinary) + + socket.buffered = false + eventually(30_000) { socket.sent.count { it.contains("\"approval-") } == 5 } + val replies = socket.sent.filter { it.contains("\"id\":\"approval-") }.map { Json.parseToJsonElement(it).jsonObject } + val errors = replies.filter { it.containsKey("error") } + assertEquals("Four full replies and one constant 'queue is full' answer", 4, replies.count { it.containsKey("result") }) + assertEquals(1, errors.size) + assertEquals("-32603", errors.single()["error"]!!.jsonObject["code"]!!.jsonPrimitive.content) + assertEquals("Client response queue is full", errors.single()["error"]!!.jsonObject["message"]!!.jsonPrimitive.content) + client.disconnect() + } + + @Test fun theWriterSendsOneFrameAtATimeWhileTheSocketHoldsUnwrittenData() = runBlocking { + val (client, socket) = connected() + socket.stallAfterEachSend = true + repeat(3) { request(client, "profiles.list", 200) } + eventually { socket.sentWithMethod("profiles.list").size == 1 && client.queueSnapshot().frames == 2 } + delay(150) + assertEquals("No second frame while the first sits unwritten", 1, socket.sentWithMethod("profiles.list").size) + socket.buffered = false + eventually { socket.sentWithMethod("profiles.list").size == 2 } + delay(100) + assertEquals(2, socket.sentWithMethod("profiles.list").size) + socket.buffered = false + eventually { socket.sentWithMethod("profiles.list").size == 3 && client.queueSnapshot().frames == 0 } + client.disconnect() + } + + @Test fun aQueuedServerReplyCanStillBeCancelledWhileThePeerStalls() = runBlocking { + val (client, socket) = connected { client -> + client.setServerRequestHandler("approval") { ServerResponse.Result(JsonObject(emptyMap())) } + } + socket.buffered = true + socket.deliver(ScriptedGateway.requestLine("stalled-1", "approval", """{"session_id":"s"}""")) + eventually { client.queueSnapshot().server > 0 } + socket.deliver(ScriptedGateway.eventLine("request.cancel", """{"id":"stalled-1","method":"approval","reason":"expired"}""")) + eventually { client.queueSnapshot().server == 0 } + socket.buffered = false + delay(300) + assertTrue("The cancelled reply never left", socket.sent.none { it.contains("stalled-1") }) + client.disconnect() + } + + @Test fun aRequestCancelledBeforeItLeftIsNotSentAndSaysSo() = runBlocking { + val (client, socket) = connected() + socket.buffered = true + var seen: Throwable? = null + val call = scope.async { + try { + client.request("prompt.submit", params("text" to "hello")) + } catch (e: CancellationException) { + seen = e + throw e + } + } + eventually { client.queueSnapshot().frames == 1 } + call.cancel() + eventually { seen != null } + assertEquals(DispatchOutcome.NotSent, (seen as RequestCancelledException).dispatch) + eventually { client.queueSnapshot().frames == 0 } + socket.buffered = false + delay(300) + assertTrue("A frame that never left is never sent", socket.sentWithMethod("prompt.submit").isEmpty()) + client.disconnect() + } + + private fun params(vararg pairs: Pair) = buildJsonObject { pairs.forEach { put(it.first, it.second) } } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRawPeerTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRawPeerTest.kt new file mode 100644 index 00000000..b1cdedb4 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRawPeerTest.kt @@ -0,0 +1,349 @@ +package app.bighelp.hermes + +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +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.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.Timeout + +/** + * The gateway against a peer that writes raw WebSocket frames byte by byte. These are the inbound-contract + * tests: nothing larger than 4 MiB is accepted or even waited for, UTF-8 is strict for TEXT frames whole or + * fragmented, upgrade headers are bounded, and upgrade refusals keep their types. + */ +class GatewayRawPeerTest { + private val peer = RawPeer() + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val resources = mutableListOf() + + @get:Rule val testTimeout: Timeout = Timeout.seconds(60) + + private val timings = GatewayTimings( + readyMillis = 3_000, advertiseMillis = 1_000, requestMillis = 3_000, heartbeatMillis = 60_000, pingMillis = 60_000, + pingReplyMillis = 500, livenessMillis = 500, admissionMillis = 500, reconnectDelaysMillis = emptyList(), + ) + + @After fun stop() { + scope.cancel() + resources.forEach { runCatching { it.close() } } + peer.close() + } + + private fun endpoint() = HermesEndpoint.parse("http://127.0.0.1:${peer.port}", allowPrivateHttp = true) + + private fun client(access: AccessHeaders = AccessHeaders.none, bearer: Boolean = false, timings: GatewayTimings = this.timings): GatewayClient { + val endpoint = endpoint() + val authenticator = HermesAuthenticator(endpoint, OkHttpHermesHttp(endpoint, access), InMemoryCredentialStore()) + resources += authenticator + authenticator.adoptForTest( + if (bearer) SavedConnection(endpoint, StoredAuth.Bearer("access-1", "refresh-1", System.currentTimeMillis() / 1_000 + 3_600), "basic", "u") + else SavedConnection(endpoint, StoredAuth.DashboardSession("dash-token", automatic = false), null, null), + persisted = false, + ) + return GatewayClient(authenticator, scope, timings) + } + + private class Connected(val client: GatewayClient, val session: RawPeer.Session, val events: CopyOnWriteArrayList) + + private fun GatewayClient.collectEvents(): CopyOnWriteArrayList { + val events = CopyOnWriteArrayList() + scope.launch { this@collectEvents.events.collect { events += it } } + runBlocking { eventually { subscriberCount == 1 } } + return events + } + + private suspend fun eventually(timeoutMillis: Long = 5_000, condition: () -> Boolean) { + withTimeout(timeoutMillis) { while (!condition()) delay(10) } + } + + /** A fully connected client over a peer that answers the connect sequence. */ + private fun connect(access: AccessHeaders = AccessHeaders.none, timings: GatewayTimings = this.timings): Connected { + val client = client(access, timings = timings) + val events = client.collectEvents() + val connecting = scope.async { client.connect() } + val session = peer.awaitUpgrade() + session.accept() + session.ready() + session.serve() + runBlocking { connecting.await() } + return Connected(client, session, events) + } + + /** Starts a connect, lets [answer] play the upgrade, and returns how it ended. */ + private fun connectAttempt(client: GatewayClient = client(), answer: (RawPeer.Session) -> Unit): Throwable? { + val connecting: Deferred> = scope.async { runCatching { client.connect() } } + answer(peer.awaitUpgrade()) + return runBlocking { withTimeout(10_000) { connecting.await() } }.exceptionOrNull() + } + + private fun kindOf(failure: Throwable?) = (failure as? HermesException)?.kind + + // Oversized declared length, no body + + @Test fun aFrameHeaderDeclaringTooBigABodyIsRejectedWithoutItsBodyEverArriving() { + val limit = HermesWire.MAXIMUM_MESSAGE_BYTES.toLong() + for (declared in listOf(limit + 1, 64L * 1_024 * 1_024, 0x7FFF_FFF0L, 1L shl 40)) { + val connected = connect() + val pending = scope.async { runCatching { connected.client.request("profiles.list") } } + connected.session.awaitMethodSent("profiles.list") + connected.session.frameHeaderOnly(opcode = 0x1, declaredLength = declared) // and then nothing + val failure = runBlocking { withTimeout(3_000) { pending.await() } }.exceptionOrNull() + assertEquals("declared $declared", HermesException.Kind.MessageTooLarge, kindOf(failure)) + runBlocking { eventually(3_000) { connected.client.state.value.lastFailure?.kind == HermesException.Kind.MessageTooLarge } } + assertTrue("The client dropped the connection", connected.session.awaitClientGone(3_000)) + runBlocking { connected.client.disconnect() } + } + } + + @Test fun aBodyExactlyAtTheLimitIsStillAwaitedNotRejected() { + val connected = connect() + connected.session.frameHeaderOnly(opcode = 0x1, declaredLength = HermesWire.MAXIMUM_MESSAGE_BYTES.toLong()) + Thread.sleep(700) + assertEquals(GatewayConnection.Connected, connected.client.state.value.connection) + runBlocking { connected.client.disconnect() } + } + + @Test fun fragmentsWhoseSumPassesTheLimitAreRejectedAsTheyAccumulate() { + for (shape in listOf(listOf(3, 2), listOf(1, 1, 1, 1, 1), listOf(4, 1))) { + val connected = connect() + val pending = scope.async { runCatching { connected.client.request("profiles.list") } } + connected.session.awaitMethodSent("profiles.list") + shape.forEachIndexed { index, mebibytes -> + val payload = ByteArray(mebibytes * 1_024 * 1_024) { 'a'.code.toByte() } + runCatching { connected.session.frame(if (index == 0) 0x1 else 0x0, payload, fin = index == shape.lastIndex) } + } + val failure = runBlocking { withTimeout(5_000) { pending.await() } }.exceptionOrNull() + assertEquals(shape.toString(), HermesException.Kind.MessageTooLarge, kindOf(failure)) + assertTrue("Nothing was published", connected.events.none { it.event.type != "gateway.ready" }) + runBlocking { connected.client.disconnect() } + } + } + + // Strict UTF-8 + + private val eventJson = """{"jsonrpc":"2.0","method":"event","params":{"type":"héllo wörld 😀 日本語","payload":{}}}""" + + @Test fun aCodePointSplitAnywhereAcrossFragmentsIsDeliveredIntact() { + val connected = connect() + val bytes = eventJson.toByteArray(Charsets.UTF_8) + for (cut in 1 until bytes.size) { + connected.session.frame(0x1, bytes.copyOfRange(0, cut), fin = false) + connected.session.frame(0x0, bytes.copyOfRange(cut, bytes.size), fin = true) + } + runBlocking { eventually { connected.events.count { it.event.type == "héllo wörld 😀 日本語" } == bytes.size - 1 } } + assertEquals(GatewayConnection.Connected, connected.client.state.value.connection) + runBlocking { connected.client.disconnect() } + } + + @Test fun everyByteAsItsOwnFragmentWithAPingBetweenIsDeliveredAndThePingAnswered() { + val connected = connect() + val bytes = eventJson.toByteArray(Charsets.UTF_8) + bytes.forEachIndexed { index, byte -> + connected.session.frame(if (index == 0) 0x1 else 0x0, byteArrayOf(byte), fin = index == bytes.lastIndex) + if (index % 11 == 0 && index < bytes.lastIndex) connected.session.frame(0x9, byteArrayOf(1, 2, 3)) + } + runBlocking { eventually { connected.events.any { it.event.type == "héllo wörld 😀 日本語" } } } + val pong = generateSequence { connected.session.receivedFrames.poll(2, java.util.concurrent.TimeUnit.SECONDS) }.firstOrNull { it.opcode == 0xA } + assertTrue("The library answers a ping between fragments", pong != null) + runBlocking { connected.client.disconnect() } + } + + private fun malformed(vararg bytes: Int) = ByteArray(bytes.size) { bytes[it].toByte() } + + private val invalidSequences = mapOf( + "lone continuation byte" to malformed(0x80), + "0xFF" to malformed(0xFF), + "truncated lead" to malformed(0xC3), + "overlong slash" to malformed(0xC0, 0xAF), + "encoded surrogate" to malformed(0xED, 0xA0, 0x80), + "five byte form" to malformed(0xF8, 0x88, 0x80, 0x80, 0x80), + "beyond U+10FFFF" to malformed(0xF4, 0x90, 0x80, 0x80), + "truncated four byte" to malformed(0xF0, 0x9F, 0x98), + ) + + private fun jsonWithRaw(middle: ByteArray): ByteArray = + """{"jsonrpc":"2.0","method":"event","params":{"type":"x""".toByteArray() + middle + """y","payload":{}}}""".toByteArray() + + @Test fun malformedUtf8InATextFrameIsRejectedNotRepairedToAReplacementCharacter() { + for ((name, bad) in invalidSequences) { + val connected = connect() + val pending = scope.async { runCatching { connected.client.request("profiles.list") } } + connected.session.awaitMethodSent("profiles.list") + connected.session.frame(0x1, jsonWithRaw(bad)) + val failure = runBlocking { withTimeout(5_000) { pending.await() } }.exceptionOrNull() + assertEquals(name, HermesException.Kind.InvalidResponse, kindOf(failure)) + assertTrue("$name: no event, least of all one with U+FFFD, was published", connected.events.none { it.event.type != "gateway.ready" }) + runBlocking { connected.client.disconnect() } + } + } + + @Test fun malformedUtf8InAnyFragmentOrAtTheEndOfAMessageIsRejected() { + val shapes: Map Unit> = mapOf( + "bad bytes in the final fragment" to { s -> + s.frame(0x1, jsonWithRaw(malformed()).copyOfRange(0, 60), fin = false) + s.frame(0x0, malformed(0xFF) + """y","payload":{}}}""".toByteArray(), fin = true) + }, + "bad bytes in a middle fragment" to { s -> + val head = """{"jsonrpc":"2.0","method":"event","params":{"type":"x""".toByteArray() + s.frame(0x1, head, fin = false) + s.frame(0x0, malformed(0xC0, 0xAF), fin = false) + s.frame(0x0, """y","payload":{}}}""".toByteArray(), fin = true) + }, + "message ends inside a code point" to { s -> + s.frame(0x1, """{"jsonrpc":"2.0","method":"event","params":{"type":"x""".toByteArray() + malformed(0xE6, 0x97), fin = false) + s.frame(0x0, malformed(), fin = true) + }, + ) + for ((name, send) in shapes) { + val connected = connect() + val pending = scope.async { runCatching { connected.client.request("profiles.list") } } + connected.session.awaitMethodSent("profiles.list") + send(connected.session) + val failure = runBlocking { withTimeout(5_000) { pending.await() } }.exceptionOrNull() + assertEquals(name, HermesException.Kind.InvalidResponse, kindOf(failure)) + assertTrue(name, connected.events.none { it.event.type != "gateway.ready" }) + runBlocking { connected.client.disconnect() } + } + } + + @Test fun binaryFramesKeepTheirMeaningValidJsonIsDeliveredAndInvalidUtf8IsStillRefused() { + val ok = connect() + ok.session.binary(eventJson.toByteArray(Charsets.UTF_8)) + runBlocking { eventually { ok.events.any { it.event.type == "héllo wörld 😀 日本語" } } } + runBlocking { ok.client.disconnect() } + + val bad = connect() + val pending = scope.async { runCatching { bad.client.request("profiles.list") } } + bad.session.awaitMethodSent("profiles.list") + bad.session.binary(jsonWithRaw(malformed(0xFF))) + assertEquals(HermesException.Kind.InvalidResponse, kindOf(runBlocking { withTimeout(5_000) { pending.await() } }.exceptionOrNull())) + runBlocking { bad.client.disconnect() } + } + + @Test fun compressionBitsAndUnofferedExtensionsAreRefused() { + val connected = connect() + val pending = scope.async { runCatching { connected.client.request("profiles.list") } } + connected.session.awaitMethodSent("profiles.list") + connected.session.frame(0x1, eventJson.toByteArray(), rsv = 4) // RSV1 + assertEquals(HermesException.Kind.InvalidResponse, kindOf(runBlocking { withTimeout(5_000) { pending.await() } }.exceptionOrNull())) + assertTrue(connected.events.none { it.event.type != "gateway.ready" }) + runBlocking { connected.client.disconnect() } + + var offered = true + val failure = connectAttempt { + offered = it.hasHeader("sec-websocket-extensions") + it.accept(extensions = "permessage-deflate") + } + assertEquals(HermesException.Kind.InvalidResponse, kindOf(failure)) + assertFalse("No extension was ever offered", offered) + } + + // Upgrade headers + + @Test fun anUpgradeResponseWithOversizedHeadersIsRefusedWhetherOrNotItEnds() { + val padding = (1..2_000).joinToString("") { "X-Pad-$it: ${"p".repeat(20)}\r\n" } // about 50 KB + val terminated = connectAttempt { it.accept(extraHeaders = padding.trimEnd().split("\r\n")) } + assertEquals(HermesException.Kind.MessageTooLarge, kindOf(terminated)) + + val endless = connectAttempt { session -> + session.rawText("HTTP/1.1 101 Switching Protocols\r\n") + Thread { + runCatching { repeat(200) { session.rawText("X-Never-Ends-$it: ${"e".repeat(1_000)}\r\n") } } + }.start() + } + assertEquals(HermesException.Kind.MessageTooLarge, kindOf(endless)) + } + + @Test fun aLargeButAllowedUpgradeHeaderBlockStillConnects() { + val client = client() + val connecting = scope.async { runCatching { client.connect() } } + val session = peer.awaitUpgrade() + val padding = (1..300).map { "X-Pad-$it: ${"p".repeat(30)}" } // about 12 KB + session.accept(extraHeaders = padding) + session.ready() + session.serve() + assertTrue(runBlocking { connecting.await() }.isSuccess) + runBlocking { client.disconnect() } + } + + @Test fun upgradeRefusalsKeepTheirTypes() { + fun refuse(status: String, vararg headers: String) = connectAttempt { it.rawText("HTTP/1.1 $status\r\n${headers.joinToString("") { h -> "$h\r\n" }}Content-Length: 0\r\nConnection: close\r\n\r\n") } + assertEquals(HermesException.Kind.InvalidCredentials, kindOf(refuse("401 Unauthorized"))) + assertEquals(HermesException.Kind.InvalidCredentials, kindOf(refuse("403 Forbidden"))) + assertEquals(HermesException.Kind.RedirectRefused, kindOf(refuse("301 Moved Permanently", "Location: /elsewhere"))) + assertEquals(HermesException.Kind.RedirectRefused, kindOf(refuse("302 Found", "Location: https://example.invalid/"))) + assertEquals(HermesException.Kind.RedirectRefused, kindOf(refuse("307 Temporary Redirect", "Location: /x"))) + assertEquals(HermesException.Kind.ConnectionFailed, kindOf(refuse("503 Service Unavailable"))) + assertEquals(HermesException.Kind.ConnectionFailed, kindOf(refuse("200 OK"))) + assertEquals("A 101 that does not prove the key is not an upgrade", HermesException.Kind.InvalidResponse, kindOf(connectAttempt { + it.rawText("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: AAAAAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n") + })) + assertTrue("No redirect target was ever contacted", peer.httpPaths.none { it == "/elsewhere" || it == "/x" }) + } + + // What the client sends + + @Test fun theUpgradeRequestCarriesExactlyTheContractedHeaders() { + val access = AccessHeaders.of(endpoint(), AccessCredential.proxyBasic("gate-user", "gate-pass"), listOf(CustomHeader.of("X-Gate", "é-ü"))) + val connected = connect(access) + val session = connected.session + assertEquals("GET /api/ws?token=dash-token HTTP/1.1", session.requestLine) + assertEquals("127.0.0.1:${peer.port}", session.header("host")) + assertEquals("websocket", session.header("upgrade")?.lowercase()) + assertEquals("upgrade", session.header("connection")?.lowercase()) + assertEquals("13", session.header("sec-websocket-version")) + assertEquals(24, session.header("sec-websocket-key")?.length) + assertEquals("dash-token", session.header("x-hermes-session-token")) + assertEquals("Basic Z2F0ZS11c2VyOmdhdGUtcGFzcw==", session.header("authorization")) + assertTrue("A non-ASCII proxy header value is sent as UTF-8, not turned into ?", session.head.contains("X-Gate: é-ü")) + for (absent in listOf("cookie", "origin", "sec-websocket-extensions", "sec-websocket-protocol")) { + assertNull(absent, session.header(absent)) + } + runBlocking { connected.client.disconnect() } + } + + @Test fun aTicketedUpgradeOffersTheTwoProtocolsInOrderCarriesNoQueryOrProviderTokenAndInsistsOnTheFirstBeingNegotiated() { + val client = client(bearer = true) + val connecting = scope.async { runCatching { client.connect() } } + val session = peer.awaitUpgrade() + assertEquals("GET /api/ws HTTP/1.1", session.requestLine) + assertEquals("hermes-gateway-v1, hermes-gateway-ticket.raw_ticket_1", session.header("sec-websocket-protocol")) + assertNull("The provider token never rides the gateway request", session.header("authorization")) + assertFalse("nor does it leak into the target", session.requestLine.contains("access-1")) + session.accept(subprotocol = "hermes-gateway-v1") + session.ready() + session.serve() + assertTrue(runBlocking { connecting.await() }.isSuccess) + runBlocking { client.disconnect() } + } + + @Test fun anythingButTheMainProtocolNegotiatedBackIsRefusedForATicketedUpgrade() { + for (answer in listOf("hermes-gateway-ticket.raw_ticket_1", "hermes-gateway-v1, hermes-gateway-ticket.raw_ticket_2", "hermes-gateway-v2", null)) { + val failure = connectAttempt(client(bearer = true)) { it.accept(subprotocol = answer) } + assertEquals(answer ?: "no protocol", HermesException.Kind.InvalidResponse, kindOf(failure)) + } + } + + private fun RawPeer.Session.awaitMethodSent(method: String, timeoutMillis: Long = 5_000) { + val deadline = System.nanoTime() + timeoutMillis * 1_000_000 + while (method !in receivedMethods) { + check(System.nanoTime() < deadline) { "The client never sent $method" } + Thread.sleep(10) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTest.kt new file mode 100644 index 00000000..44a14aab --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTest.kt @@ -0,0 +1,127 @@ +package app.bighelp.hermes + +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +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.Timeout + +/** The socket layer on its own, so each of its protections is proven without the client's second line of defense. */ +class GatewayTransportTest { + @get:Rule val testTimeout: Timeout = Timeout.seconds(60) + + private val peer = RawPeer() + private val transports = mutableListOf() + + private class Recorder : GatewayTransportListener { + val opened = LinkedBlockingQueue() + val messages = LinkedBlockingQueue() + val failed = LinkedBlockingQueue() + override fun opened(negotiatedSubprotocol: String?) { opened.add(negotiatedSubprotocol.orEmpty()) } + override fun message(bytes: ByteArray) { messages.add(bytes) } + override fun failed(error: HermesException) { failed.add(error) } + } + + @After fun stop() { + transports.forEach { runCatching { it.close(orderly = false) } } + peer.close() + } + + private fun open( + required: String? = null, + headers: Map = emptyMap(), + recorder: Recorder = Recorder(), + path: String = "/api/ws", + ): Pair { + val transport = GatewayWebSockets.open(SocketRequest("ws://127.0.0.1:${peer.port}$path", headers, required), recorder) + transports += transport + return transport to recorder + } + + private val ticketed = mapOf("Sec-WebSocket-Protocol" to "hermes-gateway-v1, hermes-gateway-ticket.t1") + + @Test fun aTicketedSocketOpensOnlyWhenTheMainProtocolAloneIsNegotiated() { + val (_, ok) = open(required = "hermes-gateway-v1", headers = ticketed) + val session = peer.awaitUpgrade() + assertEquals("hermes-gateway-v1, hermes-gateway-ticket.t1", session.header("sec-websocket-protocol")) + session.accept(subprotocol = "hermes-gateway-v1") + assertEquals("hermes-gateway-v1", ok.opened.poll(5, TimeUnit.SECONDS)) + assertTrue(ok.failed.isEmpty()) + } + + @Test fun theTransportItselfRefusesTheTicketEchoedBackAndEverythingElseThatIsNotTheMainProtocol() { + for (answer in listOf("hermes-gateway-ticket.t1", "hermes-gateway-v1, hermes-gateway-ticket.t1", "hermes-gateway-v2", null)) { + val (_, recorder) = open(required = "hermes-gateway-v1", headers = ticketed) + peer.awaitUpgrade().accept(subprotocol = answer) + assertEquals(answer ?: "none", HermesException.Kind.InvalidResponse, recorder.failed.poll(5, TimeUnit.SECONDS)?.kind) + assertNull("It never reported an open socket", recorder.opened.poll(100, TimeUnit.MILLISECONDS)) + } + } + + @Test fun aSocketThatOffersNoProtocolAcceptsAnUnadornedUpgrade() { + val (_, recorder) = open() + val session = peer.awaitUpgrade() + assertNull(session.header("sec-websocket-protocol")) + session.accept() + assertEquals("", recorder.opened.poll(5, TimeUnit.SECONDS)) + } + + @Test fun headersThatCouldSplitTheRequestAreRefusedBeforeAnyConnection() { + val bad = listOf( + mapOf("X-Gate" to "ok\r\nInjected: 1"), mapOf("X-Gate" to "ok\nInjected: 1"), mapOf("X-Gate" to "nul\u0000"), + mapOf("Bad Name" to "v"), mapOf("Bad:Name" to "v"), mapOf("" to "v"), mapOf("X\r\nY" to "v"), + ) + for (headers in bad) { + val failure = assertThrows(HermesException::class.java) { open(headers = headers) } + assertEquals(headers.toString(), HermesException.Kind.InvalidAccessCredentials, failure.kind) + } + for (offer in listOf("hermes-gateway-v1, bad\r\nprotocol", "has space, other", "a,,b\u007f")) { + assertThrows(HermesException::class.java) { open(headers = mapOf("Sec-WebSocket-Protocol" to offer)) } + } + assertThrows(HermesException::class.java) { GatewayWebSockets.open(SocketRequest("http://127.0.0.1:1/api/ws", emptyMap(), null), Recorder()) } + assertThrows(HermesException::class.java) { GatewayWebSockets.open(SocketRequest("not a url", emptyMap(), null), Recorder()) } + assertNull("No connection was ever made", peer.upgrades.poll(300, TimeUnit.MILLISECONDS)) + } + + @Test fun aDeliberateCloseEndsTheSocketAndReportsNothingMore() { + val (transport, recorder) = open() + val session = peer.awaitUpgrade() + session.accept() + session.serve() // a reader, so the peer can see the connection end + assertEquals("", recorder.opened.poll(5, TimeUnit.SECONDS)) + transport.close(orderly = false) + assertTrue("The peer sees the connection end", session.awaitClientGone(5_000)) + assertNull("and the owner is told nothing further", recorder.failed.poll(500, TimeUnit.MILLISECONDS)) + transport.close(orderly = false) // idempotent + assertEquals(false, transport.send("{}")) + } + + @Test fun closingWhileTheUpgradeIsStillPendingAbortsTheConnectAttempt() { + val (transport, recorder) = open() + val session = peer.awaitUpgrade() // the peer never answers + session.serve() + transport.close(orderly = false) + assertTrue("The half-made connection was dropped", session.awaitClientGone(5_000)) + assertNull(recorder.failed.poll(500, TimeUnit.MILLISECONDS)) + } + + @Test fun framesAreSentInOrderAsMaskedTextAndTheWriteBufferSignalDrains() { + val (transport, recorder) = open() + val session = peer.awaitUpgrade() + session.accept() + recorder.opened.poll(5, TimeUnit.SECONDS) + val texts = (1..50).map { """{"n":$it,"pad":"${"é".repeat(it)}"}""" } + texts.forEach { assertTrue(transport.send(it)) } + val received = (1..50).map { session.readFrame(5_000) } + assertTrue(received.all { it != null && it.opcode == 0x1 && it.fin }) + assertEquals("Same order, UTF-8 intact", texts, received.map { it!!.text }) + val deadline = System.nanoTime() + 5_000_000_000L + while (transport.hasBufferedData && System.nanoTime() < deadline) Thread.sleep(5) + assertEquals("Everything handed over was taken by the writer", false, transport.hasBufferedData) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTlsTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTlsTest.kt new file mode 100644 index 00000000..761e68fa --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTransportTlsTest.kt @@ -0,0 +1,140 @@ +package app.bighelp.hermes + +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLContext +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.tls.HandshakeCertificates +import okhttp3.tls.HeldCertificate +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.Timeout + +/** + * Real TLS to the gateway socket. The platform default trust is used and nothing is relaxed: a certificate + * that chains to the trusted root but names another host, and one that chains to nothing trusted, both fail + * as TLS errors before any WebSocket byte is read. The only thing the test changes is which root the + * *default* SSL context trusts (a test authority), the way a device trusts its certificate authorities. + */ +class GatewayTransportTlsTest { + @get:Rule val testTimeout: Timeout = Timeout.seconds(60) + + private val root = HeldCertificate.Builder().certificateAuthority(0).commonName("Bighelp Test Root").build() + private val servers = mutableListOf() + private val transports = mutableListOf() + private var originalContext: SSLContext? = null + + private class Recorder : GatewayTransportListener { + val opened = LinkedBlockingQueue() + val messages = LinkedBlockingQueue() + val failures = CopyOnWriteArrayList() + val failed = LinkedBlockingQueue() + override fun opened(negotiatedSubprotocol: String?) { opened.add(negotiatedSubprotocol.orEmpty()) } + override fun message(bytes: ByteArray) { messages.add(String(bytes, Charsets.UTF_8)) } + override fun failed(error: HermesException) { failures += error; failed.add(error) } + } + + @Before fun trustOnlyTheTestRoot() { + originalContext = SSLContext.getDefault() + val trust = HandshakeCertificates.Builder().addTrustedCertificate(root.certificate).build() + SSLContext.setDefault(SSLContext.getInstance("TLS").apply { init(null, arrayOf(trust.trustManager), null) }) + } + + @After fun restore() { + transports.forEach { runCatching { it.close(orderly = false) } } + servers.forEach { runCatching { it.shutdown() } } + SSLContext.setDefault(originalContext) + } + + private fun tlsServer(certificate: HeldCertificate, greeting: String = "hello over tls"): MockWebServer { + val identity = HandshakeCertificates.Builder().heldCertificate(certificate, root.certificate).build() + return MockWebServer().also { + it.useHttps(identity.sslSocketFactory(), false) + it.enqueue(MockResponse().withWebSocketUpgrade(object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { webSocket.send(greeting) } + })) + it.start() + servers += it + } + } + + private fun certificate(vararg names: String, signedByRoot: Boolean = true) = + HeldCertificate.Builder().apply { + names.forEach { addSubjectAlternativeName(it) } + if (signedByRoot) signedBy(root) + }.build() + + private fun connect(server: MockWebServer, recorder: Recorder): GatewayTransport = + GatewayWebSockets.open(SocketRequest("wss://127.0.0.1:${server.port}/api/ws?token=t", emptyMap(), null), recorder) + .also { transports += it } + + @Test fun aCertificateForTheHostFromATrustedAuthorityConnectsAndCarriesMessages() { + val recorder = Recorder() + connect(tlsServer(certificate("127.0.0.1")), recorder) + assertNotNull("The socket opened over TLS", recorder.opened.poll(10, TimeUnit.SECONDS)) + assertEquals("hello over tls", recorder.messages.poll(10, TimeUnit.SECONDS)) + assertTrue(recorder.failures.isEmpty()) + } + + @Test fun aTrustedCertificateForAnotherHostIsRefusedByHostnameVerification() { + val recorder = Recorder() + connect(tlsServer(certificate("other.example")), recorder) + val failure = recorder.failed.poll(10, TimeUnit.SECONDS) + assertEquals(HermesException.Kind.TlsRequired, failure?.kind) + assertNull("Not one byte of the upgrade was accepted", recorder.opened.poll(200, TimeUnit.MILLISECONDS)) + assertNull(recorder.messages.poll(200, TimeUnit.MILLISECONDS)) + } + + @Test fun aCertificateThatChainsToNothingTrustedIsRefusedEvenWhenItNamesTheHost() { + val recorder = Recorder() + val stranger = HeldCertificate.Builder().addSubjectAlternativeName("127.0.0.1").build() // self-signed + val identity = HandshakeCertificates.Builder().heldCertificate(stranger).build() + val server = MockWebServer().also { + it.useHttps(identity.sslSocketFactory(), false) + it.enqueue(MockResponse().withWebSocketUpgrade(object : WebSocketListener() {})) + it.start() + servers += it + } + connect(server, recorder) + assertEquals(HermesException.Kind.TlsRequired, recorder.failed.poll(10, TimeUnit.SECONDS)?.kind) + assertNull(recorder.opened.poll(200, TimeUnit.MILLISECONDS)) + } + + @Test fun anExpiredCertificateIsRefused() { + val recorder = Recorder() + val expired = HeldCertificate.Builder().addSubjectAlternativeName("127.0.0.1").signedBy(root) + .validityInterval(System.currentTimeMillis() - 2 * 86_400_000L, System.currentTimeMillis() - 86_400_000L).build() + connect(tlsServer(expired), recorder) + assertEquals(HermesException.Kind.TlsRequired, recorder.failed.poll(10, TimeUnit.SECONDS)?.kind) + } + + @Test fun theHttpClientAlsoRefusesACertificateThatChainsToNothingTheDeviceTrusts() { + val stranger = HeldCertificate.Builder().addSubjectAlternativeName("127.0.0.1").build() + val identity = HandshakeCertificates.Builder().heldCertificate(stranger).build() + val server = MockWebServer().also { + it.useHttps(identity.sslSocketFactory(), false) + it.enqueue(MockResponse().setBody("{}")) + it.start() + servers += it + } + val http = OkHttpHermesHttp(HermesEndpoint.parse("https://127.0.0.1:${server.port}")) + try { + val failure = kotlin.runCatching { kotlinx.coroutines.runBlocking { http.send(HermesHttpRequest("/api/status", timeoutMillis = 5_000)) } }.exceptionOrNull() + assertEquals(HermesException.Kind.TlsRequired, (failure as? HermesException)?.kind) + assertEquals("Nothing reached the application layer", 0, server.requestCount) + } finally { + http.close() + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt deleted file mode 100644 index 07ebcfdd..00000000 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt +++ /dev/null @@ -1,77 +0,0 @@ -package app.bighelp.hermes - -import java.util.concurrent.CompletableFuture -import java.util.concurrent.TimeUnit -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.Response -import okhttp3.WebSocket -import okhttp3.WebSocketListener -import okhttp3.mockwebserver.MockResponse -import okhttp3.mockwebserver.MockWebServer -import org.junit.After -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Test - -/** - * The gated gateway authenticates with `Sec-WebSocket-Protocol: hermes-gateway-v1, hermes-gateway-ticket.` - * and the host answers with the negotiated `hermes-gateway-v1`. These tests prove the platform - * WebSocket (OkHttp) really sends a hand-set two-value header, lets proxy headers ride the upgrade, - * sends no cookies, and exposes the negotiated value, before any client code depends on it. - */ -class OkHttpWebSocketNegotiationTest { - private val server = MockWebServer() - - @After fun stop() = server.shutdown() - - private fun upgrade(negotiated: String?, onOpen: (WebSocket) -> Unit = {}) { - val response = MockResponse() - if (negotiated != null) response.setHeader("Sec-WebSocket-Protocol", negotiated) - server.enqueue(response.withWebSocketUpgrade(object : WebSocketListener() { - override fun onOpen(webSocket: WebSocket, response: Response) = onOpen(webSocket) - })) - server.start() - } - - private fun open(request: Request): Pair { - val opened = CompletableFuture() - val socket = OkHttpClient.Builder().build().newWebSocket(request, object : WebSocketListener() { - override fun onOpen(webSocket: WebSocket, response: Response) { opened.complete(response) } - override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { - opened.completeExceptionally(t) - } - }) - return socket to opened.get(10, TimeUnit.SECONDS) - } - - @Test fun aHandSetTwoValueSubprotocolHeaderReachesTheHostAndTheNegotiatedValueIsReadable() { - upgrade(negotiated = "hermes-gateway-v1") - val offered = "hermes-gateway-v1, hermes-gateway-ticket.synthetic_Ticket-1" - val (socket, response) = open( - Request.Builder().url(server.url("/api/ws")).header("Sec-WebSocket-Protocol", offered).build(), - ) - val received = server.takeRequest(5, TimeUnit.SECONDS)!! - assertEquals("/api/ws", received.path) - assertEquals(offered, received.getHeader("Sec-WebSocket-Protocol")) - assertEquals("hermes-gateway-v1", response.header("Sec-WebSocket-Protocol")) - socket.cancel() - } - - @Test fun proxyHeadersRideTheUpgradeAndNoCookieIsSent() { - upgrade(negotiated = null) - val (socket, response) = open( - Request.Builder().url(server.url("/hermes/api/ws")) - .header("CF-Access-Client-Id", "id").header("X-Session-Gate", "g") - .header("X-Hermes-Session-Token", "dashboard-token").build(), - ) - val received = server.takeRequest(5, TimeUnit.SECONDS)!! - assertEquals("id", received.getHeader("CF-Access-Client-Id")) - assertEquals("g", received.getHeader("X-Session-Gate")) - assertEquals("dashboard-token", received.getHeader("X-Hermes-Session-Token")) - assertNull(received.getHeader("Cookie")) - assertNull("A dashboard upgrade offers no subprotocol", received.getHeader("Sec-WebSocket-Protocol")) - assertNull(response.header("Sec-WebSocket-Protocol")) - socket.cancel() - } -} 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 index ffb63b05..8ae9cb61 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt @@ -189,6 +189,11 @@ class RealHostIntegrationTest { 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) @@ -197,13 +202,12 @@ class RealHostIntegrationTest { val events = collect(client) client.connect() val (runtime, _) = client.newSession("default", text(host("open"), "project")) - client.runTurn(events, runtime, "default", "secure input test") - // Hermes asks only while the fixture variable is unset; an earlier answered run leaves it set. - assumeTrue("The host already holds the fixture secret, so it did not ask", "secret" in prompts.methods()) + 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", request.params["env_var"]?.jsonPrimitive?.content) + assertEquals("SECURE_INPUT_FIXTURE_2", request.params["env_var"]?.jsonPrimitive?.content) assertEquals(runtime, request.params["session_id"]?.jsonPrimitive?.content) - Unit + println("REAL-HOST open secure input: asked=${request.params["env_var"]?.jsonPrimitive?.content} answeredWith=decline") } @Test fun openHostRestFollowsTheDashboardTokenAndTheNativeContextIsGuardedByItsEtag() = runBlocking { @@ -259,16 +263,19 @@ class RealHostIntegrationTest { restoredAuthenticator.restore(expired) // expiry in the past: renews before anything else val rotated = store.load(staged.authority)!! val rotatedBearer = rotated.auth as StoredAuth.Bearer - assertNotEquals("The access token was renewed", bearer.accessToken, rotatedBearer.accessToken) + // 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: accessChanged=${bearer.accessToken != rotatedBearer.accessToken} refreshChanged=${bearer.refreshToken != rotatedBearer.refreshToken}") + 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() - assertNotEquals(first.headers["Sec-WebSocket-Protocol"], second.headers["Sec-WebSocket-Protocol"]) + 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()) From 12a79d597068f497c4cbf86d1d2134123e572e3d Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:10:04 -0500 Subject: [PATCH 14/18] Android computer setup, sign-in and removal run one action at a time Co-Authored-By: Claude Sonnet 5.5 --- .../android/live/ComputerConnectionModel.kt | 378 ++++++++++++++++++ .../live/ComputerConnectionModelTest.kt | 283 +++++++++++++ 2 files changed, 661 insertions(+) create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt 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..dcc31718 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt @@ -0,0 +1,378 @@ +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.BrowserLauncher +import app.bighelp.hermes.CredentialStore +import app.bighelp.hermes.CredentialAuthority +import app.bighelp.hermes.GatewayClient +import app.bighelp.hermes.HermesAuthenticator +import app.bighelp.hermes.HermesEndpoint +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.OkHttpHermesHttp +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.flow.MutableStateFlow +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? + 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) + suspend fun close() +} + +/** The real session stays available to the chat repository without exposing credentials to screens. */ +internal class NetworkComputerSession( + endpoint: HermesEndpoint, + credentials: CredentialStore, + scope: CoroutineScope, + browser: BrowserLauncher?, +) : ComputerSession { + private val http = OkHttpHermesHttp(endpoint) + val authenticator = HermesAuthenticator(endpoint, http, credentials, browser) + val gateway = GatewayClient(authenticator, scope) + init { scope.coroutineContext[Job]?.invokeOnCompletion { authenticator.close() } } + override val saved get() = authenticator.savedConnection + override suspend fun discover() = authenticator.discover() + override suspend fun signIn(input: SignInInput) = authenticator.signIn(input) + override suspend fun restore(saved: SavedConnection) { + authenticator.restore(saved) + } + override suspend fun connect() { gateway.connect() } + override suspend fun commit(expected: SavedConnection?, stillCurrent: () -> Boolean) { + authenticator.commit(expected, stillCurrent) + } + override suspend fun close() { + try { gateway.disconnect() } finally { authenticator.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. + */ +internal class ComputerConnectionModel( + private val registry: SavedComputerStore, + private val credentials: (UUID) -> AndroidCredentialStore, + private val consentGranted: () -> Boolean, + private val scope: CoroutineScope, + private val factory: (HermesEndpoint, CredentialStore, CoroutineScope) -> T, +) { + private val mutableState = MutableStateFlow(ComputerConnectionState()) + val state: StateFlow = mutableState.asStateFlow() + private val mutableActive = MutableStateFlow?>(null) + val active: StateFlow?> = mutableActive.asStateFlow() + 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() + owner?.credentials?.invalidate() + 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 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) } + } + } + + fun beginSetup(endpoint: HermesEndpoint): Job = launchOperation { token -> + retire() + if (!hasConsent()) return@launchOperation + val next = newOwner(UUID.randomUUID(), endpoint) + 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 next = newOwner(id, row.endpoint) + 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) + current.session.connect() + requireOwner(current, token) + var snapshot = registry.load() + requireOwner(current, token) + val existing = snapshot.computers.firstOrNull { it.id == current.id } + if (existing != null && existing.authority != candidate.authority) { + throw HermesException(HermesException.Kind.IdentityChanged) + } + if (snapshot.computers.any { it.id != current.id && it.authority == candidate.authority }) { + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, problem = ComputerProblem.AlreadyConfigured) + return@launchOperation + } + if (existing == null && snapshot.computers.size >= 32) { + mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, problem = ComputerProblem.ComputerLimit) + 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 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() + 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) + 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 next = newOwner(id, row.endpoint) + 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): 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, factory(endpoint, 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 + } + + 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") + } + + private suspend fun retire() = withContext(NonCancellable) { + val old = owner + owner = null + mutableActive.value = null + if (old != null) { + old.credentials.invalidate() + try { + old.job.cancelAndJoin() + old.session.close() + } 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/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..a2c393c0 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt @@ -0,0 +1,283 @@ +package app.bighelp.android.live + +import app.bighelp.android.storage.ProtectedRecordStore +import app.bighelp.android.storage.RecordCipher +import app.bighelp.hermes.AuthStatus +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.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 fun model(scope: CoroutineScope) = ComputerConnectionModel( + registry(), ::vault, { consent }, scope, + ) { address, credentials, _ -> FakeSession(address, credentials).also { sessions += it; prepare(it) } } + + private class FakeSession(val endpoint: HermesEndpoint, val store: CredentialStore) : ComputerSession { + override var saved: SavedConnection? = null + 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()) + store.replace(expected, requireNotNull(saved)) + commits++ + } + override suspend fun close() { + 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() + } + +} From 1b8b1ff00584e0b90dd0054a9e291bbd51a43f3c Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:43:59 -0500 Subject: [PATCH 15/18] Android chat repository: sessions, history, streaming, sends and prompts Co-Authored-By: Claude Sonnet 5.5 --- .../app/bighelp/hermes/chat/CatalogDecoder.kt | 180 +++++ .../app/bighelp/hermes/chat/CatalogEngine.kt | 143 ++++ .../app/bighelp/hermes/chat/ChatGateway.kt | 63 ++ .../app/bighelp/hermes/chat/ChatIdentity.kt | 120 ++++ .../app/bighelp/hermes/chat/ChatJson.kt | 56 ++ .../app/bighelp/hermes/chat/ChatModels.kt | 509 ++++++++++++++ .../app/bighelp/hermes/chat/ChatRecords.kt | 242 +++++++ .../app/bighelp/hermes/chat/ChatStore.kt | 253 +++++++ .../bighelp/hermes/chat/ConversationEngine.kt | 633 ++++++++++++++++++ .../hermes/chat/ConversationRuntime.kt | 90 +++ .../hermes/chat/HermesChatRepository.kt | 344 ++++++++++ .../bighelp/hermes/chat/HistoryCacheCodec.kt | 22 + .../bighelp/hermes/chat/HistoryProjection.kt | 138 ++++ .../app/bighelp/hermes/chat/HistoryRows.kt | 265 ++++++++ .../app/bighelp/hermes/chat/PromptCenter.kt | 335 +++++++++ .../bighelp/hermes/chat/RuntimeControls.kt | 206 ++++++ .../app/bighelp/hermes/chat/SessionBinder.kt | 340 ++++++++++ .../bighelp/hermes/chat/SessionOperations.kt | 199 ++++++ .../app/bighelp/hermes/chat/SlashCommands.kt | 139 ++++ .../bighelp/hermes/chat/SubmissionEngine.kt | 513 ++++++++++++++ .../app/bighelp/hermes/chat/TurnReducer.kt | 340 ++++++++++ .../bighelp/hermes/chat/CatalogDecoderTest.kt | 149 +++++ .../hermes/chat/CatalogRepositoryTest.kt | 143 ++++ .../kotlin/app/bighelp/hermes/chat/ChatRig.kt | 92 +++ .../app/bighelp/hermes/chat/ChatStoreTest.kt | 178 +++++ .../bighelp/hermes/chat/CommandRouterTest.kt | 163 +++++ .../bighelp/hermes/chat/CreateResumeTest.kt | 272 ++++++++ .../app/bighelp/hermes/chat/FakeHermesHost.kt | 631 +++++++++++++++++ .../hermes/chat/FileSnapshotChatStore.kt | 78 +++ .../hermes/chat/GatewayChatIntegrationTest.kt | 137 ++++ .../hermes/chat/HistoryRepositoryTest.kt | 125 ++++ .../app/bighelp/hermes/chat/HistoryTest.kt | 223 ++++++ .../hermes/chat/PromptRepositoryTest.kt | 216 ++++++ .../bighelp/hermes/chat/RealHostChatTest.kt | 199 ++++++ .../app/bighelp/hermes/chat/RecoveryTest.kt | 210 ++++++ .../hermes/chat/RuntimeControlsTest.kt | 156 +++++ .../app/bighelp/hermes/chat/SendFlowTest.kt | 372 ++++++++++ .../hermes/chat/SessionOperationsTest.kt | 166 +++++ .../bighelp/hermes/chat/TurnReducerTest.kt | 270 ++++++++ 39 files changed, 8910 insertions(+) create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogDecoder.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogEngine.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatIdentity.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatJson.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatModels.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatRecords.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatStore.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryProjection.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryRows.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/PromptCenter.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SlashCommands.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogDecoderTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CatalogRepositoryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatStoreTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CommandRouterTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FileSnapshotChatStore.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/PromptRepositoryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RealHostChatTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RecoveryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/RuntimeControlsTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SessionOperationsTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogDecoder.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogDecoder.kt new file mode 100644 index 00000000..c807e6a7 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogDecoder.kt @@ -0,0 +1,180 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.utf8Length +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** One decoded `GET /api/sessions` page. [hasMore] is null for the older envelope, which sends [total] instead. */ +internal class SessionPage(val rows: List, val limit: Int, val offset: Int, val hasMore: Boolean?, val total: Int?) + +/** Decodes `profiles.list` and the saved-chat list, with the checks of the current app. Anything off is `InvalidResponse`. */ +internal object CatalogDecoder { + const val PAGE_LIMIT = 100 + const val MAXIMUM_PROFILES = 512 + const val MAXIMUM_SESSIONS = 10_000 + val DEFAULT_EXCLUDED_SOURCES = listOf("tool", "kanban", "bot_room") + + fun profiles(result: JsonElement): List { + val rows = result.asObject?.get("profiles").asArray ?: throw invalidResponse() + if (rows.size > MAXIMUM_PROFILES) throw invalidResponse() + val seen = HashSet() + return rows.map { value -> + val row = value.asObject ?: throw invalidResponse() + val id = row["name"].asString?.takeIf { Coordinates.isValid(it, Coordinates.MAXIMUM_PROFILE_BYTES) } ?: throw invalidResponse() + if (!seen.add(id)) throw invalidResponse() + val label = optionalText(row["display_name"], 800)?.takeIf { it.isNotEmpty() } + AgentSummary(id, label ?: id, registry(row["canonical_session"]), row) + } + } + + private fun registry(value: JsonElement?): CanonicalChat? { + if (value == null || value is JsonNull) return null + val row = value.asObject ?: throw invalidResponse() + val id = row["id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + val resolved = optionalText(row["resolved_id"], 512) + if (resolved != null && !Coordinates.isValid(resolved)) throw invalidResponse() + return CanonicalChat(id, resolved) + } + + /** The current app's list request: explicit profile, 100 per page, deliberate archives included, creation order, internal sources excluded. */ + fun listQuery( + profile: String, + offset: Int, + archived: String = "include", + order: String = "created", + excludedSources: List = DEFAULT_EXCLUDED_SOURCES, + ): List> = buildList { + add("profile" to profile); add("limit" to PAGE_LIMIT.toString()); add("offset" to offset.toString()) + add("archived" to archived); add("order" to order) + if (excludedSources.isNotEmpty()) add("exclude_sources" to excludedSources.joinToString(",")) + } + + /** + * Accepts the standard list envelope (`object:"list"`, `data`, Boolean `has_more`) and the older typed one + * (`sessions`, `total`). The page must echo the requested offset and the fixed limit. + */ + fun sessionPage(envelope: JsonElement, profile: String, requestedOffset: Int): SessionPage { + val body = envelope.asObject ?: throw invalidResponse() + val rows: List + val hasMore: Boolean? + if (body["object"].asString == "list") { + rows = body["data"].asArray ?: throw invalidResponse() + hasMore = body["has_more"].asBool ?: throw invalidResponse() + } else { + if (body["object"] != null || body["data"] != null || body["has_more"] != null) throw invalidResponse() + rows = body["sessions"].asArray ?: throw invalidResponse() + hasMore = null + if ((body["total"].asInt ?: throw invalidResponse()) < 0) throw invalidResponse() + } + val limit = body["limit"].asInt + val offset = body["offset"].asInt + if (limit != PAGE_LIMIT || offset != requestedOffset || rows.size > MAXIMUM_SESSIONS) throw invalidResponse() + val total = body["total"]?.takeIf { it !is JsonNull }?.let { (it.asInt ?: throw invalidResponse()).also { n -> if (n < 0) throw invalidResponse() } } + val objects = rows.map { value -> + val row = value.asObject ?: throw invalidResponse() + val id = row["id"].asString + if (id.isNullOrEmpty() || id.contains('\u0000')) throw invalidResponse() + row["profile"]?.let { echoed -> if (echoed.asString != profile) throw invalidResponse() } + row + } + return SessionPage(objects, limit, offset, hasMore, total) + } + + /** Whether a next page exists: the host's `has_more`, else `total`, else a full page (older hosts add pinned rows past the limit). */ + fun hasMore(page: SessionPage, offset: Int, rows: Int): Boolean { + page.hasMore?.let { return it } + page.total?.let { return offset + page.limit < it } + return rows >= page.limit + } + + /** `archived` truthy and not `auto_archived`: someone archived it. Hermes' idle sweep marks its own. */ + fun archiveState(row: JsonObject): ArchiveState { + fun flag(value: JsonElement?): Boolean = when { + value.asBool != null -> value.asBool == true + value.asDouble != null -> value.asDouble != 0.0 + else -> false + } + if (!flag(row["archived"])) return ArchiveState.None + return if (flag(row["auto_archived"])) ArchiveState.Automatic else ArchiveState.Deliberate + } + + /** One list row. [canonical] is the profile's registry Bot Chat, which the row may be a member of. */ + fun summary(row: JsonObject, profile: String, canonical: CanonicalChat?): SessionSummary { + val id = row["id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + if (row["profile"].asString != profile) throw invalidResponse() + val root = optionalText(row["_lineage_root_id"], 512)?.also { if (!Coordinates.isValid(it)) throw invalidResponse() } + val lineage = row["_lineage_ids"]?.takeIf { it !is JsonNull }?.let { raw -> + val values = raw.asArray ?: throw invalidResponse() + if (values.size > MAXIMUM_SESSIONS) throw invalidResponse() + val ids = values.map { it.asString?.takeIf(Coordinates::isValid) ?: throw invalidResponse() } + if (ids.toSet().size != ids.size || id !in ids || (root != null && root !in ids)) throw invalidResponse() + ids + } + val matchesCanonical = canonical != null && + (canonical.id == id || canonical.resolvedId == id || root == canonical.id || lineage?.contains(canonical.id) == true) + val anchor = if (matchesCanonical) canonical!!.id else root ?: id + val started = date(row["started_at"]) ?: throw invalidResponse() + val updated = date(row["last_active"] ?: row["last_activity_at"]) ?: started + val count = row["message_count"]?.takeIf { it !is JsonNull }?.let { (it.asInt ?: throw invalidResponse()).also { n -> if (n < 0) throw invalidResponse() } } ?: 0 + val title = optionalText(row["title"], 4_096).orEmpty() + return SessionSummary( + ref = ConversationRef(profile, anchor), profile = profile, storedId = id, + title = title.ifEmpty { "Untitled" }, + preview = preview(optionalText(row["preview"], 64 * 1024).orEmpty()), + startedAtEpochSeconds = started, lastActiveEpochSeconds = updated, messageCount = count, + source = optionalText(row["source"], 128), cwd = optionalText(row["cwd"], 4_096), + pinned = flag(row["pinned"]) ?: false, archive = archiveState(row), + lineageRootId = root, lineageIds = lineage, isCanonicalBotChat = matchesCanonical, isRegistryOnly = false, + ) + } + + /** The agent's Bot Chat as only the registry names it. No title text of its own, time or preview is made up. */ + fun registryOnly(profile: String, canonical: CanonicalChat) = SessionSummary( + ref = ConversationRef(profile, canonical.id), profile = profile, storedId = canonical.resolvedId ?: canonical.id, + title = "Bot Chat", preview = "", startedAtEpochSeconds = null, lastActiveEpochSeconds = null, messageCount = 0, + source = null, cwd = null, pinned = false, archive = ArchiveState.None, lineageRootId = null, lineageIds = null, + isCanonicalBotChat = true, isRegistryOnly = true, + ) + + /** One line for the list: attachments read as "Photo" or "Attachment" instead of host paths. */ + fun preview(raw: String): String { + val shown = UserMessageDisplay.text(raw) + var photos = false + var files = false + val words = shown.split("\n").filter { line -> + when { + line.startsWith("@image:") -> { photos = true; false } + line.startsWith("@file:") -> { files = true; false } + else -> true + } + } + val body = words.joinToString("\n").trim() + return body.ifEmpty { if (photos) "Photo" else if (files) "Attachment" else "" } + } + + private fun flag(value: JsonElement?): Boolean? = when { + value == null || value is JsonNull -> null + value.asBool != null -> value.asBool + value.asLong == 0L -> false + value.asLong == 1L -> true + else -> throw invalidResponse() + } + + private fun date(value: JsonElement?): Double? { + if (value == null || value is JsonNull) return null + val seconds = value.asDouble ?: throw invalidResponse() + if (seconds < 0 || seconds > 253_402_300_799.0) throw invalidResponse() + return seconds + } + + /** Null/absent is null; a present value must be text within the bound with no control characters but \n \r \t. */ + fun optionalText(value: JsonElement?, maximumBytes: Int): String? { + if (value == null || value is JsonNull) return null + val text = value.asString ?: throw invalidResponse() + if (utf8Length(text) > maximumBytes) throw invalidResponse() + if (text.any { Character.getType(it) == Character.CONTROL.toInt() && it != '\n' && it != '\r' && it != '\t' }) throw invalidResponse() + return text + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogEngine.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogEngine.kt new file mode 100644 index 00000000..9fe6d793 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/CatalogEngine.kt @@ -0,0 +1,143 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * The agent list and the saved chats. It only reads: `profiles.list` (with each agent's sessions, so the Bot Chat + * registry is named) and `GET /api/sessions`. It never creates or resumes a chat to learn whether anything is + * running. The hidden canonical Bot Chat is merged from the registry, deliberately archived chats are left out of + * the normal list (Hermes' idle sweep archives are kept), and one unreadable row hides only itself. + */ +internal class CatalogEngine(private val ctx: ChatContext, private val binder: SessionBinder) { + private val mutableState = MutableStateFlow(CatalogState()) + val state: StateFlow = mutableState.asStateFlow() + private var unreadable = 0 + + suspend fun refresh(): CatalogState { + mutableState.value = mutableState.value.copy(loading = true, error = null) + try { + val agents = loadAgents() + val sessions = ArrayList() + val failures = LinkedHashMap() + var truncated = false + for (agent in agents) { + // One agent's list can fail on its own (a profile with no session store yet answers 503): the others stay listed. + try { + val rows = listProfile(agent.id, agent.canonicalChat, archived = "include", keepDeliberate = false) + sessions += rows.first + truncated = truncated || rows.second + } catch (e: HermesException) { + if (fatal(e)) throw e + failures[agent.id] = SessionBinder.chatError(e) + } catch (e: ChatException) { + failures[agent.id] = e.error + } + agent.canonicalChat?.let { canonical -> + // Hermes hides every Bot Chat, so the list never has it: the registry names it. Without this, a refresh dropped it. + if (sessions.none { it.profile == agent.id && (it.ref.anchor == canonical.id || it.storedId == canonical.id || it.storedId == canonical.resolvedId) }) { + sessions += CatalogDecoder.registryOnly(agent.id, canonical) + } + } + } + if (agents.isNotEmpty() && failures.size == agents.size) throw ChatException(failures.values.first()) + val next = CatalogState(agents, failures, sessions, loading = false, error = null, loadedAtMillis = ctx.config.clock(), truncated = truncated) + mutableState.value = next + return next + } catch (e: ChatException) { + return fail(e.error) + } catch (e: HermesException) { + return fail(SessionBinder.chatError(e)) + } + } + + /** A sign-in or connection problem is the whole catalog's, not one agent's. */ + private fun fatal(e: HermesException) = SessionBinder.chatError(e).kind.let { it == ChatError.Kind.SignInRequired || it == ChatError.Kind.NotConnected } + + private fun fail(error: ChatError): CatalogState { + // The previous list stays; the error is shown beside it. + val next = mutableState.value.copy(loading = false, error = error) + mutableState.value = next + return next + } + + suspend fun loadAgents(): List { + val agents = CatalogDecoder.profiles(ctx.gateway.request("profiles.list", buildJsonObject { put("include_sessions", true) })) + agents.forEach { a -> a.canonicalChat?.let { binder.canonical[a.id] = it } ?: binder.canonical.remove(a.id) } + mutableState.value = mutableState.value.copy(agents = agents) + return agents + } + + /** Chats the person archived, every agent's. A plain read: nothing is bound or opened. */ + suspend fun loadArchived(): List { + val agents = mutableState.value.agents.ifEmpty { loadAgents() } + val result = ArrayList() + for (agent in agents) { + try { + result += listProfile(agent.id, agent.canonicalChat, archived = "only", keepDeliberate = true).first + } catch (e: HermesException) { + if (fatal(e)) throw e // one agent's list failing leaves the others + } + } + return result.filter { it.archive == ArchiveState.Deliberate }.sortedByDescending { it.lastActiveEpochSeconds ?: 0.0 } + } + + /** All pages of one profile: 100 per page, bounded continuation. Returns the rows and whether the ceiling cut the list. */ + private suspend fun listProfile(profile: String, canonical: CanonicalChat?, archived: String, keepDeliberate: Boolean): Pair, Boolean> { + val rows = ArrayList() + val seen = HashSet() + var offset = 0 + while (true) { + val page = CatalogDecoder.sessionPage(ctx.rest.get("/api/sessions", CatalogDecoder.listQuery(profile, offset, archived = archived)), profile, offset) + for (row in page.rows) { + val id = row["id"].asString!! + // Hermes 0.21.x adds pinned rows to every page; they are skipped after the first. Any other repeat means the list moved. + if (!seen.add(id)) { + if (page.hasMore != null || row["pinned"].let { it.asBool == true || it.asLong == 1L }) continue + throw ChatException(ChatError.Kind.HistoryChanged) + } + if (!keepDeliberate && CatalogDecoder.archiveState(row) == ArchiveState.Deliberate) continue + val summary = try { CatalogDecoder.summary(row, profile, canonical) } catch (e: HermesException) { unreadable += 1; continue } + rows += summary + if (rows.size > CatalogDecoder.MAXIMUM_SESSIONS) throw ChatException(ChatError.Kind.TooLarge) + } + if (page.rows.isEmpty() || !CatalogDecoder.hasMore(page, offset, page.rows.size)) return rows to false + offset += page.limit + if (offset > CatalogDecoder.MAXIMUM_SESSIONS) return rows to true + } + } + + suspend fun search(profile: String, query: String, limit: Int): List { + if (query.isEmpty() || utf8(query) > 4_096 || limit !in 1..100) throw ChatException(ChatError.Kind.InvalidInput) + val canonical = binder.canonical[profile] + val envelope = ctx.rest.get("/api/sessions/search", listOf("q" to query, "profile" to profile, "limit" to limit.toString(), "exclude_sources" to CatalogDecoder.DEFAULT_EXCLUDED_SOURCES.joinToString(","))) + val rows = envelope.asObject?.get("results").asArray?.takeIf { it.size <= limit } ?: throw invalidResponse() + val seen = HashSet() + return rows.map { value -> + val row = value.asObject ?: throw invalidResponse() + val id = (row["id"] ?: row["session_id"]).asString ?: throw invalidResponse() + row["profile"]?.let { if (it.asString != profile) throw invalidResponse() } + val normalized = kotlinx.serialization.json.JsonObject(row + mapOf("id" to kotlinx.serialization.json.JsonPrimitive(id), "profile" to kotlinx.serialization.json.JsonPrimitive(profile))) + val summary = CatalogDecoder.summary(normalized, profile, canonical) + if (!seen.add(summary.ref.id)) throw invalidResponse() + SessionSearchResult(summary, CatalogDecoder.optionalText(row["snippet"], 64 * 1024).orEmpty()) + } + } + + /** Replaces one row after an edit, or drops it. */ + fun update(ref: ConversationRef, change: (SessionSummary) -> SessionSummary?) { + val current = mutableState.value + mutableState.value = current.copy(sessions = current.sessions.mapNotNull { if (it.ref == ref) change(it) else it }) + } + + fun add(summary: SessionSummary) { + val current = mutableState.value + if (current.sessions.none { it.ref == summary.ref }) mutableState.value = current.copy(sessions = listOf(summary) + current.sessions) + } + + private fun utf8(text: String) = app.bighelp.hermes.utf8Length(text) +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt new file mode 100644 index 00000000..789e4c64 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt @@ -0,0 +1,63 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.GatewayClient +import app.bighelp.hermes.GatewayEvent +import app.bighelp.hermes.GatewayState +import app.bighelp.hermes.HermesAuthenticator +import app.bighelp.hermes.HermesHttpLimits +import app.bighelp.hermes.HermesHttpRequest +import app.bighelp.hermes.ServerRequestHandler +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject + +/** + * What the chat layer needs from the gateway. [GatewayClient] satisfies it through [GatewayClientAdapter]; a + * test substitutes a scripted host that behaves like Hermes (a `prompt.submit` answers `streaming` and the + * reply arrives later as events). The repository never touches a socket directly. + */ +internal interface ChatGateway { + val state: StateFlow + val events: Flow + + /** One JSON-RPC call; failures are `HermesException`, a cancelled caller gets `RequestCancelledException`. */ + suspend fun request(method: String, params: JsonObject, timeoutMillis: Long? = null): JsonElement + + suspend fun prepareForAdmission() + suspend fun verifyLiveness() + suspend fun reconnect(): GatewayState + suspend fun adoptOpenRequests(rows: JsonElement, runtimeId: String, generation: Long) + fun setServerRequestHandler(method: String, handler: ServerRequestHandler?) +} + +internal class GatewayClientAdapter(private val client: GatewayClient) : ChatGateway { + override val state get() = client.state + override val events get() = client.events + + override suspend fun request(method: String, params: JsonObject, timeoutMillis: Long?): JsonElement = + if (timeoutMillis == null) client.request(method, params) else client.request(method, params, timeoutMillis) + + override suspend fun prepareForAdmission() = client.prepareForAdmission() + override suspend fun verifyLiveness() = client.verifyLiveness() + override suspend fun reconnect(): GatewayState = client.reconnect() + override suspend fun adoptOpenRequests(rows: JsonElement, runtimeId: String, generation: Long) = + client.adoptOpenRequests(rows, runtimeId, generation) + + override fun setServerRequestHandler(method: String, handler: ServerRequestHandler?) = + client.setServerRequestHandler(method, handler) +} + +/** The authenticated REST reads of the session catalog and history. Read-only: nothing here mutates the host. */ +internal interface ChatRest { + suspend fun get(route: String, query: List>): JsonElement +} + +internal class AuthenticatedRest(private val authenticator: HermesAuthenticator) : ChatRest { + override suspend fun get(route: String, query: List>): JsonElement = authenticator.authenticatedJson( + HermesHttpRequest( + route = route, query = query, + maximumResponseBytes = HermesHttpLimits.responseCeiling(route, "GET", query), + ), + ) +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatIdentity.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatIdentity.kt new file mode 100644 index 00000000..407c52a9 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatIdentity.kt @@ -0,0 +1,120 @@ +package app.bighelp.hermes.chat + +import java.util.Base64 + +/** + * The app-visible identity of one conversation: the exact profile and the immutable anchor (the canonical + * Bot Chat registry ID, the lineage root of a saved chat, or the stored ID a new chat was born with). It is + * what the UI routes and what drafts and journals are scoped by. It never changes when the transcript's + * stored tip moves (compaction), and it is never sent to Hermes in place of a runtime or stored ID. + */ +data class ConversationRef(val profile: String, val anchor: String) { + init { + require(Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) { "Invalid profile" } + require(Coordinates.isValid(anchor)) { "Invalid anchor" } + } + + /** A stable, URL-safe string for routing. Decodes only back to this exact pair. */ + val id: String = "c1.${encode(profile)}.${encode(anchor)}" + + override fun toString() = "ConversationRef(${id.take(24)}…)" + + companion object { + /** The ref [id] names, or null for anything that is not exactly an ID this class produced. */ + fun parse(id: String): ConversationRef? { + if (id.length > 4_096) return null + val parts = id.split('.') + if (parts.size != 3 || parts[0] != "c1") return null + val profile = decode(parts[1]) ?: return null + val anchor = decode(parts[2]) ?: return null + return runCatching { ConversationRef(profile, anchor) }.getOrNull()?.takeIf { it.id == id } + } + + private fun encode(value: String): String = + Base64.getUrlEncoder().withoutPadding().encodeToString(value.toByteArray(Charsets.UTF_8)) + + private fun decode(value: String): String? { + if (value.isEmpty() || value.length > 1_024 || !value.all { it.isLetterOrDigit() && it.code < 128 || it == '-' || it == '_' }) return null + val bytes = runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull() ?: return null + val text = runCatching { + Charsets.UTF_8.newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)).toString() + }.getOrNull() ?: return null + return text.takeIf { encode(it) == value } + } + } +} + +/** + * The coordinates of one conversation that can change, kept apart from [ref]: the stored transcript tip + * (REST history and `session.resume` target it), the old tips that were routing aliases (a notification for + * a former stored ID still finds this chat), and the registry facts. The runtime ID and replay epoch are + * live facts of one connection and live in the session binding instead. + */ +class ConversationIdentity( + val ref: ConversationRef, + val storedTip: String, + val formerStoredIds: List = emptyList(), + val lineageRootId: String? = null, + val lineageIds: List? = null, + val canonicalRegistryId: String? = null, +) { + init { + require(Coordinates.isValid(storedTip)) { "Invalid stored tip" } + } + + /** True for any ID this conversation has had: anchor, tip, former tips, lineage and registry IDs. Byte-exact. */ + fun knows(id: String): Boolean = + id == ref.anchor || id == storedTip || id in formerStoredIds || id == lineageRootId || id == canonicalRegistryId || + lineageIds?.contains(id) == true + + /** + * Moves the tip to [next] and keeps the old one as a routing alias (bounded, oldest dropped first). + * Callers validate the successor first ([IdentityAdoption]); this only records it. + */ + fun withTip(next: String): ConversationIdentity { + if (next == storedTip) return this + require(Coordinates.isValid(next)) { "Invalid stored tip" } + val aliases = (formerStoredIds.filter { it != next } + storedTip).takeLast(ChatStoreLimits.MAXIMUM_FORMER_STORED_IDS) + return ConversationIdentity(ref, next, aliases, lineageRootId, lineageIds, canonicalRegistryId) + } + + fun withCatalog(lineageRootId: String?, lineageIds: List?, canonicalRegistryId: String?) = + ConversationIdentity(ref, storedTip, formerStoredIds, lineageRootId ?: this.lineageRootId, lineageIds ?: this.lineageIds, + canonicalRegistryId ?: this.canonicalRegistryId) + + override fun toString() = "ConversationIdentity($ref)" +} + +/** + * Whether a different stored ID than the current tip may be adopted. A compaction successor is host data + * and must be proved before the transcript, draft routing or a notification alias moves to it. + */ +internal object IdentityAdoption { + enum class Evidence { + /** `session.resume` of this conversation's own tip returned it: the host resolves a tip to its successor. */ + ResumeOfCurrentTip, + + /** `session.info.stored_session_id` from the runtime this repository holds for this conversation, same socket and epoch. */ + RuntimeReport, + + /** A REST history response for the current tip named another session ID. */ + HistoryResponse, + } + + /** + * @return true when [proposed] may become the tip. Resume and runtime evidence are first-hand answers + * about this exact conversation; a history response is accepted only for an ID the catalog's lineage + * already named or a tip that a first-hand answer proved earlier. + */ + fun accepts(identity: ConversationIdentity, proposed: String, evidence: Evidence): Boolean { + if (!Coordinates.isValid(proposed)) return false + if (proposed == identity.storedTip) return true + return when (evidence) { + Evidence.ResumeOfCurrentTip, Evidence.RuntimeReport -> true + Evidence.HistoryResponse -> identity.lineageIds?.contains(proposed) == true || proposed in identity.formerStoredIds + } + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatJson.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatJson.kt new file mode 100644 index 00000000..b1a115f5 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatJson.kt @@ -0,0 +1,56 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.StrictJson +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 + +// Strict accessors for host answers and stored records. A value of the wrong type is absent, never coerced: +// `"1"` is not a number, `1.0` is not an integer, `1` is not a Boolean. + +internal val JsonElement?.asString: String? get() = (this as? JsonPrimitive)?.takeIf { it.isString }?.content + +internal val JsonElement?.asLong: Long? + get() = (this as? JsonPrimitive)?.takeIf { !it.isString && this !is JsonNull }?.content?.toLongOrNull() + +internal val JsonElement?.asInt: Int? get() = asLong?.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.toInt() + +internal val JsonElement?.asDouble: Double? + get() = (this as? JsonPrimitive)?.takeIf { !it.isString && this !is JsonNull }?.content?.toDoubleOrNull()?.takeIf { it.isFinite() } + +internal val JsonElement?.asBool: Boolean? + get() = (this as? JsonPrimitive)?.takeIf { !it.isString && this !is JsonNull }?.content?.let { + when (it) { + "true" -> true + "false" -> false + else -> null + } + } + +internal val JsonElement?.asObject: JsonObject? get() = this as? JsonObject +internal val JsonElement?.asArray: JsonArray? get() = this as? JsonArray +internal val JsonElement?.isAbsent: Boolean get() = this == null || this is JsonNull + +internal fun invalidResponse(): HermesException = HermesException(HermesException.Kind.InvalidResponse) + +/** Parses a stored record. Any grammar failure is a corrupt record, never a silent default. */ +internal fun parseRecord(bytes: ByteArray): JsonObject { + val text = try { + Charsets.UTF_8.newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)).toString() + } catch (_: java.nio.charset.CharacterCodingException) { + throw ChatStoreException(ChatStoreException.Kind.Corrupt) + } + return try { + StrictJson.parse(text) as? JsonObject ?: throw ChatStoreException(ChatStoreException.Kind.Corrupt) + } catch (_: StrictJson.Malformed) { + throw ChatStoreException(ChatStoreException.Kind.Corrupt) + } +} + +internal fun corrupt(): Nothing = throw ChatStoreException(ChatStoreException.Kind.Corrupt) diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatModels.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatModels.kt new file mode 100644 index 00000000..9f17501b --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatModels.kt @@ -0,0 +1,509 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.HermesException +import kotlinx.serialization.json.JsonObject + +// The values a screen observes and the results its actions return. Every one is immutable; the repository +// publishes a new value on each change. Nothing here carries a secret, and nothing is invented: a field is +// null or empty when the host did not say. + +/** Why an action or load did not complete. [cause] and [code] are Hermes' own classification when it gave one. */ +class ChatError(val kind: Kind, val cause: HermesException.Kind? = null, val code: Long? = null, val reason: String? = null) { + enum class Kind { + /** Not connected, or the socket was replaced while the action ran. */ + NotConnected, + + /** The host answered that it is unavailable, rate limited, or could not be reached. */ + HostUnavailable, + + /** The host wants a new sign-in. */ + SignInRequired, + + /** The conversation is not open in this repository, or the host named no such chat. */ + NotOpen, + + /** The session has no live runtime on this connection; open it again. */ + NoLiveSession, + + /** The durable store refused a write, so nothing was sent. */ + PersistenceFailed, + + /** The host or plugin answered in a shape this client does not accept. */ + InvalidResponse, + + /** Hermes answered with a refusal (see [code] and [reason]). */ + Rejected, + + /** The request or answer exceeded a documented bound. */ + TooLarge, + + /** The host does not offer this operation. */ + Unsupported, + + /** History changed between pages; the transcript was reloaded from the newest page instead of merged. */ + HistoryChanged, + + /** A chosen model was not the one the session reported. */ + ModelNotConfirmed, + + /** A requested folder was not the session's folder. */ + WorkspaceNotConfirmed, + + /** A create was sent and no answer came; its intent is retained (see [PendingCreation]). */ + CreationUnconfirmed, + + /** A create for this profile is already in flight. */ + CreationInProgress, + + /** The outcome of a mutation is unknown; reconcile before trying again. */ + OutcomeUnknown, + + /** The action does not apply now (a turn is running, the chat is not idle, it is already archived). */ + Conflict, + + /** The input is empty, or a chosen command no longer matches the text. Nothing was sent. */ + InvalidInput, + + /** Steer needs a turn that was observed running; an idle chat is never silently sent as a new turn. */ + NoActiveTurn, + + Cancelled, + } + + override fun toString() = "ChatError($kind${cause?.let { ", $it" }.orEmpty()}${code?.let { ", $it" }.orEmpty()})" +} + +class ChatException(val error: ChatError) : Exception(error.kind.name) { + constructor(kind: ChatError.Kind, cause: HermesException.Kind? = null, code: Long? = null, reason: String? = null) : + this(ChatError(kind, cause, code, reason)) +} + +// ---- Agents and sessions --------------------------------------------------------------------------------- + +class CanonicalChat(val id: String, val resolvedId: String?) + +/** One profile from `profiles.list{include_sessions:true}`. [metadata] is the host's whole row, so optional fields survive. */ +class AgentSummary( + val id: String, + val displayName: String, + val canonicalChat: CanonicalChat?, + val metadata: JsonObject, +) { + override fun toString() = "AgentSummary($id)" +} + +enum class ArchiveState { + None, + + /** Someone archived it (any client). Not in the normal list; in Archived chats. */ + Deliberate, + + /** Hermes' idle sweep archived it. It stays in the list: that was not the person's choice. */ + Automatic, +} + +/** One saved chat row from `GET /api/sessions`, or a Bot Chat the registry names but the list hides. */ +class SessionSummary( + val ref: ConversationRef, + val profile: String, + /** The row's own stored ID (its tip, as the host lists it). */ + val storedId: String, + val title: String, + val preview: String, + val startedAtEpochSeconds: Double?, + val lastActiveEpochSeconds: Double?, + val messageCount: Int, + val source: String?, + val cwd: String?, + val pinned: Boolean, + val archive: ArchiveState, + val lineageRootId: String?, + val lineageIds: List?, + val isCanonicalBotChat: Boolean, + /** True when only the registry names it (the list hides every Bot Chat): no title, preview or time is invented. */ + val isRegistryOnly: Boolean, +) { + override fun toString() = "SessionSummary($ref)" +} + +class SessionSearchResult(val session: SessionSummary, val snippet: String) + +data class CatalogState( + val agents: List = emptyList(), + /** An agent whose chat list the host could not give (for example a profile with no session store yet). Its chats are absent; the others are listed. */ + val agentErrors: Map = emptyMap(), + val sessions: List = emptyList(), + val loading: Boolean = false, + val error: ChatError? = null, + val loadedAtMillis: Long? = null, + /** More than the 10,000-chat ceiling exist; the rest are not listed. */ + val truncated: Boolean = false, +) + +/** An unfinished create, retained so a lost reply can be retried under the same key or dropped by the person. */ +data class PendingCreation(val profile: String, val intentId: String, val purpose: CreationPurpose, val phase: CreationPhase, val request: CreateRequest) + +sealed interface CreateOutcome { + /** The chat exists and is open; [ref] is its conversation. */ + data class Created(val ref: ConversationRef) : CreateOutcome + + /** The create was sent and no definite answer came. [intentId] retries the same logical create (same key). */ + data class Unconfirmed(val intentId: String, val error: ChatError) : CreateOutcome + + /** Nothing was created. */ + data class Failed(val error: ChatError) : CreateOutcome +} + +// ---- Connection ------------------------------------------------------------------------------------------- + +data class ConnectionStatus( + val gateway: GatewayConnection = GatewayConnection.Idle, + val generation: Long = 0, + /** The host's `per_session_exclusive_submit`, or null until known on this socket. False keeps chat submit off. */ + val exclusiveSubmit: Boolean? = null, + val lastFailure: HermesException.Kind? = null, +) + +// ---- Transcript --------------------------------------------------------------------------------------------- + +enum class MessageRole { User, Assistant, System, Unknown } + +enum class ItemOrigin { + /** A physical row of the host's saved history. */ + Saved, + + /** Built from this connection's live events; richer than a saved row and kept until history catches up. */ + Live, + + /** Typed here and sent (or being sent), not yet bound to a saved row. */ + Local, +} + +sealed interface TranscriptItem { + val id: String +} + +data class MessageItem( + override val id: String, + val role: MessageRole, + val rawRole: String, + val text: String, + val origin: ItemOrigin, + /** The physical history row ID, once known. Never derived from text. */ + val rowId: Long? = null, + /** `display_kind` such as `model_switch`; hidden kinds are not in the list. */ + val displayKind: String? = null, + /** Non-text content parts the host stored; they are kept, not rendered. */ + val hasUnsupportedContent: Boolean = false, + val timestampEpochSeconds: Double? = null, + val turnDurationMillis: Int? = null, + /** False while this assistant segment is still streaming. */ + val complete: Boolean = true, + /** A command's output shown once instead of a turn. */ + val isCommandResult: Boolean = false, + /** How Hermes said this reply's turn failed (a failed final), when it did. */ + val failure: TurnFailure? = null, +) : TranscriptItem { + override fun toString() = "MessageItem($id, $role, ${text.length} chars)" +} + +enum class ActivityKind { Tool, Reasoning, Notice, Subagent } + +enum class ActivityLifecycle { + Running, Succeeded, Failed, Cancelled, + + /** Seen in history or settled by a turn end without an explicit result: neither success nor failure is claimed. */ + Recorded, +} + +data class ActivityItem( + override val id: String, + val kind: ActivityKind, + val title: String, + val detail: String?, + val lifecycle: ActivityLifecycle, + val toolCallId: String? = null, + val turnId: String? = null, + val origin: ItemOrigin, + /** A tool's original arguments and result, as strings (JSON text when the host sent JSON). */ + val arguments: String? = null, + val result: String? = null, +) : TranscriptItem + +// ---- Conversation --------------------------------------------------------------------------------------------- + +enum class ConversationPhase { + /** Resuming the stored session and loading its newest page. */ + Opening, + + /** Attached to a live runtime on the current socket with coverage proved. */ + Ready, + + /** Catching up after a reconnect: sending is closed until coverage is proved. */ + Recovering, + + /** The socket is gone or the runtime was reclaimed; the transcript stays, nothing is sent until reattached. */ + Suspended, +} + +/** Why a new message cannot be admitted right now. Null in [ConversationState.sendBlock] means it can. */ +enum class SendBlock { + Opening, + NotConnected, + CatchingUp, + RecoveryRequired, + PendingAdmission, + HostLacksExclusiveSubmit, + TooManyUnresolved, + NoLiveSession, +} + +data class HistoryState(val hasOlder: Boolean = false, val loadingOlder: Boolean = false, val retainedRows: Int = 0) + +/** What the live runtime reported about itself (`session.info`, activation). Absent fields are null. */ +data class RuntimeInfo( + val model: String? = null, + val provider: String? = null, + val reasoningEffort: String? = null, + val serviceTier: String? = null, + val cwd: String? = null, + val lazy: Boolean? = null, +) + +/** The unsettled and refused submissions of one conversation, for review. The text is the person's own. */ +data class UnresolvedSubmission( + val id: String, + val method: String, + val composerText: String, + val attachments: List, + val createdAtMillis: Long, + /** Non-null for a definite refusal (nothing was admitted); null when the outcome is unknown. */ + val rejectionCode: Int?, +) + +data class ConversationState( + val ref: ConversationRef, + val title: String, + val identity: ConversationIdentity, + val phase: ConversationPhase, + val items: List = emptyList(), + /** A turn is running (observed from `message.start`/`session.info`), so Send steers by default. */ + val running: Boolean = false, + /** Real status from the host's own events (a tool name, a notice), never a guessed progress. */ + val status: String? = null, + val runtime: RuntimeInfo = RuntimeInfo(), + val draft: String = "", + val draftAttachments: List = emptyList(), + val sendBlock: SendBlock? = SendBlock.Opening, + val unresolved: List = emptyList(), + val prompts: List = emptyList(), + val history: HistoryState = HistoryState(), + /** A stop was requested and acknowledged; the turn is over only when the host says `running:false`. */ + val stopRequested: Boolean = false, + /** This host answers approvals the older way (events, not requests); such cards are not offered. */ + val legacyPromptHost: Boolean = false, + val lastError: ChatError? = null, +) + +// ---- Sending --------------------------------------------------------------------------------------------------- + +enum class SendMode { + /** Idle: a new turn. Running: steer. */ + Default, + Steer, + + /** `prompt.submit{queued:true}` behind the running turn. */ + Queue, + + /** Stop the turn, then (only after the stop receipt) queue this message. */ + InterruptAndSend, +} + +enum class Admission { Streaming, Queued, Steered, CommandOutput } + +sealed interface SendResult { + /** Hermes admitted it. A turn's answer arrives as events; this is not completion. */ + data class Admitted(val entryId: String, val admission: Admission) : SendResult + + /** Hermes definitely did not take it. The text is still the person's: it is in the composer or kept as an unsent entry. */ + data class Refused(val entryId: String?, val rejectionCode: Int?, val reachedSessionLimit: Boolean = false, val error: ChatError) : SendResult + + /** The send may or may not have reached Hermes. It is retained for review and never resent. */ + data class Uncertain(val entryId: String, val error: ChatError) : SendResult + + /** Nothing was written to the socket (a precondition, a persistence failure, an oversize message). */ + data class NotSent(val error: ChatError, val block: SendBlock? = null) : SendResult +} + +sealed interface ReviewResult { + data object Done : ReviewResult + + /** Restoring needs an empty composer; a newer draft is never overwritten. */ + data object ComposerNotEmpty : ReviewResult + data object NotFound : ReviewResult + data class Failed(val error: ChatError) : ReviewResult +} + +sealed interface StopResult { + /** `status:"interrupted"` came back; the turn ends when `session.info running:false` arrives. */ + data object Requested : StopResult + data class Refused(val error: ChatError) : StopResult + data class Uncertain(val error: ChatError) : StopResult +} + +sealed interface DraftResult { + data object Saved : DraftResult + data class NotSaved(val error: ChatError) : DraftResult +} + +enum class ReviewDecision { + /** Delete the retained entry after the person reviewed it. Does not send anything. */ + Discard, + + /** Put the entry's original text into the composer (only if the composer is empty) and delete the entry. */ + RestoreToComposer, +} + +// ---- Prompts ------------------------------------------------------------------------------------------------------ + +enum class ApprovalChoice(val wire: String) { + Once("once"), Session("session"), Always("always"), Deny("deny"); + + companion object { + fun fromWire(value: String): ApprovalChoice? = entries.firstOrNull { it.wire == value } + } +} + +class ClarifyQuestion(val id: String, val question: String, val choices: List, val multiSelect: Boolean, val lockedAnswer: String?) + +enum class SecureKind { Secret, Sudo, VaultCode, VaultSaveLogin, VaultUnlock } + +enum class PromptStatus { Pending, Answering } + +sealed interface PromptContent { + class Approval(val command: String?, val description: String?, val toolName: String?, val choices: List) : PromptContent + + class Clarification(val questions: List, val isBatch: Boolean) : PromptContent + + /** A request for a secret, password or code. Its value is never held by the repository beyond the one response. */ + class SecureInput( + val kind: SecureKind, + val envVar: String?, + val prompt: String?, + val label: String?, + val site: String?, + val backendName: String?, + val isAgentRequest: Boolean, + ) : PromptContent +} + +/** + * One actionable question from the agent, bound to the exact socket, runtime, profile and conversation it + * arrived for. [id] is the repository's own identity for it. [wireId] is the host's opaque JSON-RPC ID (echoed + * untouched in the response) and is deliberately separate from [domainRequestId] (an approval's `request_id`). + */ +class PromptState( + val id: String, + val ref: ConversationRef, + val wireId: String, + val method: String, + val domainRequestId: String?, + val createdAtMillis: Long, + val content: PromptContent, + val status: PromptStatus = PromptStatus.Pending, +) { + override fun toString() = "PromptState($method)" +} + +sealed interface PromptAnswer { + data class Approve(val choice: ApprovalChoice) : PromptAnswer + + /** Answers by question ID; a single question uses its own ID (see [ClarifyQuestion.id]). */ + data class Clarify(val answers: Map) : PromptAnswer + + /** A secret, password, code or unlock value. The array is cleared by the repository after the one response. */ + class Secure(val value: CharArray) : PromptAnswer { + override fun toString() = "Secure(value hidden)" + } + + class SaveLogin(val identifier: String, val password: CharArray) : PromptAnswer { + override fun toString() = "SaveLogin(hidden)" + } +} + +sealed interface PromptResult { + /** The response was handed to the connection. A lost socket afterwards is not reported here and is never replayed. */ + data object Answered : PromptResult + + /** The prompt is no longer active (cancelled, expired, or its socket ended). Nothing was sent. */ + data object NoLongerActive : PromptResult + + /** The answer is not valid for this prompt (an unoffered choice, an oversize or empty value). Nothing was sent; it can be corrected. */ + data class Invalid(val reason: String) : PromptResult +} + +// ---- History ---------------------------------------------------------------------------------------------------------- + +sealed interface HistoryLoad { + data class Loaded(val addedRows: Int, val hasOlder: Boolean) : HistoryLoad + data object NothingOlder : HistoryLoad + data class Failed(val error: ChatError) : HistoryLoad +} + +// ---- Configuration ----------------------------------------------------------------------------------------------------- + +/** Tunables with the contract's values; tests shorten the waits. */ +class ChatConfig( + /** Newest-page size, in turns (1–10). */ + val turnLimit: Int = 5, + val clock: () -> Long = System::currentTimeMillis, + val random: () -> String = { java.util.UUID.randomUUID().toString() }, +) { + init { require(turnLimit in 1..10) { "turnLimit is 1 to 10" } } +} + +// ---- Runtime controls ----------------------------------------------------------------------------------------------- + +class ModelProvider(val id: String, val name: String, val isCurrent: Boolean, val isCustom: Boolean, val models: List, val fastModels: Set?) + +/** The live session's own model and reasoning, read back from the runtime, and the host's catalog of choices. */ +class ModelOptions( + val model: String, + val provider: String?, + /** Empty means the host's Auto. */ + val reasoningEffort: String, + /** The raw `service_tier`; [isFast] reads the known spellings and is null for a mode this client does not know. */ + val serviceTier: String?, + val running: Boolean, + val providers: List, +) { + val isFast: Boolean? get() = when (serviceTier?.lowercase()) { + "fast", "on", "priority" -> true + null, "", "normal", "off" -> false + else -> null + } +} + +sealed interface ModelChange { + /** Read back from the live session: it runs on [model] now. */ + data class Confirmed(val model: String, val provider: String?) : ModelChange + + /** The host wants an explicit yes first; call again with `confirmed = true`. Nothing changed. */ + data class NeedsConfirmation(val message: String) : ModelChange + + /** The host queued it for the next turn. The current model is NOT confirmed changed; reopen the picker to check. */ + data class Deferred(val message: String) : ModelChange +} + +sealed interface BotChatOutcome { + /** The agent's canonical Bot Chat, resolved by the registry and opened. */ + data class Opened(val ref: ConversationRef) : BotChatOutcome + + /** The registry names no Bot Chat for this agent and creating one was not asked for. Nothing was created. */ + data object NotCreated : BotChatOutcome + + /** The first Bot Chat was started and its title or registry step is not confirmed. Retried by its own recovery, never by a new chat. */ + data class Unconfirmed(val intentId: String, val error: ChatError) : BotChatOutcome + data class Failed(val error: ChatError) : BotChatOutcome +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatRecords.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatRecords.kt new file mode 100644 index 00000000..b183b469 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatRecords.kt @@ -0,0 +1,242 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.utf8Length +import kotlinx.serialization.json.JsonArray +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 + +// The durable records. Every body repeats its exact scope, and every decode checks it against the key's scope, +// so a mis-addressed or colliding file can never present one conversation's text as another's. All of them +// are compact UTF-8 JSON bounded by RecordKind.maximumBytes; encoding refuses a larger record before any +// write is attempted. + +private const val SCHEMA = 1 + +private fun JsonObject.putScope(scope: ConversationScope): JsonObject = JsonObject( + this + mapOf( + "computer" to JsonPrimitive(scope.host.computerId), "endpoint" to JsonPrimitive(scope.host.endpoint), + "principal" to JsonPrimitive(scope.host.principal), "profile" to JsonPrimitive(scope.profile), + "anchor" to JsonPrimitive(scope.anchor), + ), +) + +private fun JsonObject.hostMatches(host: HostScope) = + this["computer"].asString == host.computerId && this["endpoint"].asString == host.endpoint && this["principal"].asString == host.principal + +private fun JsonObject.scopeMatches(scope: ConversationScope) = + hostMatches(scope.host) && this["profile"].asString == scope.profile && this["anchor"].asString == scope.anchor + +private fun encodeBounded(kind: RecordKind, body: JsonObject): ByteArray { + val bytes = body.toString().toByteArray(Charsets.UTF_8) + if (bytes.size > kind.maximumBytes) throw ChatStoreException(ChatStoreException.Kind.TooLarge) + return bytes +} + +private fun references(array: JsonArray?): List { + if (array == null) return emptyList() + if (array.size > ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCES) corrupt() + return array.map { it.asString?.takeIf { s -> s.isNotEmpty() && utf8Length(s) <= ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCE_BYTES } ?: corrupt() } +} + +private fun encodeReferences(values: List): JsonArray { + require(values.size <= ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCES) { "Too many attachment references" } + require(values.all { it.isNotEmpty() && utf8Length(it) <= ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCE_BYTES }) { "Invalid attachment reference" } + return buildJsonArray { values.forEach { add(JsonPrimitive(it)) } } +} + +/** The composer text of one conversation. Empty text with no references is stored as the absence of a record. */ +class DraftRecord(val scope: ConversationScope, val text: String, val attachments: List = emptyList(), val updatedAtMillis: Long) { + init { + require(utf8Length(text) <= ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES) { "A draft is at most 1 MiB" } + } + + val isEmpty: Boolean get() = text.isEmpty() && attachments.isEmpty() + + fun encode(): ByteArray = encodeBounded(RecordKind.Draft, buildJsonObject { + put("v", SCHEMA); put("text", text); put("attachments", encodeReferences(attachments)); put("updatedAt", updatedAtMillis) + }.putScope(scope)) + + override fun toString() = "DraftRecord(${text.length} chars)" + + companion object { + fun decode(scope: ConversationScope, bytes: ByteArray): DraftRecord { + val body = parseRecord(bytes) + if (body["v"].asInt != SCHEMA || !body.scopeMatches(scope)) corrupt() + val text = body["text"].asString ?: corrupt() + if (utf8Length(text) > ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES) corrupt() + return DraftRecord(scope, text, references(body["attachments"].asArray), body["updatedAt"].asLong ?: corrupt()) + } + } +} + +/** + * One submission that is not settled: the exact bytes Hermes may have been given ([method], [text]), what the + * person typed ([composerText], which survives wire expansion), the local UUID and creation time. It is + * written before the method is dispatched. [rejectionCode] non-null marks a definite refusal (nothing was + * admitted); otherwise the outcome is unknown and the entry is never resent. The local UUID is not a Hermes + * nonce and is never sent. + */ +class JournalEntry( + val id: String, + val scope: ConversationScope, + val method: String, + val text: String, + val composerText: String, + val attachments: List, + val createdAtMillis: Long, + val rejectionCode: Int? = null, +) { + init { + require(Coordinates.isUuid(id)) { "A journal entry ID is a UUID" } + require(method in METHODS) { "Unknown journaled method" } + } + + val isRefused: Boolean get() = rejectionCode != null + + fun withMethod(method: String, text: String) = JournalEntry(id, scope, method, text, composerText, attachments, createdAtMillis, rejectionCode) + /** [code] 0 means refused without a host code (nothing was dispatched, or the host named none). */ + fun refused(code: Int?) = JournalEntry(id, scope, method, text, composerText, attachments, createdAtMillis, code ?: 0) + + fun encode(): ByteArray = encodeBounded(RecordKind.Journal, buildJsonObject { + put("v", SCHEMA); put("id", id); put("method", method); put("text", text); put("composerText", composerText) + put("attachments", encodeReferences(attachments)); put("createdAt", createdAtMillis) + put("rejectionCode", rejectionCode) + }.putScope(scope)) + + override fun toString() = "JournalEntry($id, $method)" + + companion object { + val METHODS = setOf("prompt.submit", "session.steer", "session.interrupt", "slash.exec", "command.dispatch") + + fun decode(scope: ConversationScope, entryId: String, bytes: ByteArray): JournalEntry { + val body = parseRecord(bytes) + if (body["v"].asInt != SCHEMA || !body.scopeMatches(scope) || body["id"].asString != entryId) corrupt() + val method = body["method"].asString?.takeIf { it in METHODS } ?: corrupt() + val text = body["text"].asString ?: corrupt() + val composer = body["composerText"].asString ?: corrupt() + return JournalEntry( + entryId, scope, method, text, composer, references(body["attachments"].asArray), + body["createdAt"].asLong ?: corrupt(), body["rejectionCode"].asInt, + ) + } + } +} + +enum class CreationPurpose { Ordinary, FirstCanonical } + +enum class CreationPhase { CreateRequested, Created, TitleRequested, AwaitingRegistry, Complete, CanonicalResolved } + +/** Everything a create sends besides the profile and the fixed `source`, kept so a retry is the same logical create. */ +data class CreateRequest( + val cwd: String? = null, + val title: String? = null, + val model: String? = null, + val provider: String? = null, + val reasoningEffort: String? = null, + val fast: Boolean? = null, +) { + init { + cwd?.let { require(Coordinates.isValid(it, 4_096)) { "Invalid folder" } } + title?.let { require(it.isNotEmpty() && utf8Length(it) <= 240) { "Invalid title" } } + model?.let { require(Coordinates.isValid(it, 256)) { "Invalid model" } } + provider?.let { require(Coordinates.isValid(it, 128)) { "Invalid provider" } } + reasoningEffort?.let { require(Coordinates.isValid(it, 32)) { "Invalid reasoning" } } + require(provider == null || model != null) { "A provider accompanies a model" } + } +} + +/** + * A create intent, written before `session.create` is dispatched and updated as coordinates arrive. [intentId] + * is the lowercase UUID sent as `idempotency_key`, so every retry of this same logical create carries the same + * key (the host keeps it for a short time; it is not indefinite deduplication). + */ +data class CreationRecord( + val host: HostScope, + val intentId: String, + val profile: String, + val purpose: CreationPurpose, + val phase: CreationPhase, + val request: CreateRequest, + val storedSessionId: String? = null, + val runtimeSessionId: String? = null, + val canonicalRegistryId: String? = null, + val socketGeneration: Long = 0, + val createdAtMillis: Long, +) { + init { + require(Coordinates.isUuid(intentId) && intentId == intentId.lowercase()) { "The intent ID is a lowercase UUID" } + require(Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) { "Invalid profile" } + } + + /** The coordinate rules of each phase (a canonical-resolved record may hold neither or both). */ + val isCoherent: Boolean + get() = when (phase) { + CreationPhase.CanonicalResolved -> purpose == CreationPurpose.FirstCanonical && canonicalRegistryId != null && + (storedSessionId == null) == (runtimeSessionId == null) + CreationPhase.CreateRequested -> storedSessionId == null && runtimeSessionId == null + else -> storedSessionId != null && runtimeSessionId != null + } + + val isFinished: Boolean get() = phase == CreationPhase.Complete || phase == CreationPhase.CanonicalResolved + + fun encode(): ByteArray = encodeBounded(RecordKind.Creation, buildJsonObject { + put("v", SCHEMA); put("intent", intentId); put("purpose", purpose.name); put("phase", phase.name) + put("cwd", request.cwd); put("title", request.title); put("model", request.model); put("provider", request.provider) + put("reasoning", request.reasoningEffort); put("fast", request.fast) + put("stored", storedSessionId); put("runtime", runtimeSessionId); put("registry", canonicalRegistryId) + put("generation", socketGeneration); put("createdAt", createdAtMillis) + }.let { JsonObject(it + mapOf("computer" to JsonPrimitive(host.computerId), "endpoint" to JsonPrimitive(host.endpoint), + "principal" to JsonPrimitive(host.principal), "profile" to JsonPrimitive(profile))) }) + + companion object { + fun decode(host: HostScope, profile: String, bytes: ByteArray): CreationRecord { + val body = parseRecord(bytes) + if (body["v"].asInt != SCHEMA || !body.hostMatches(host) || body["profile"].asString != profile) corrupt() + val record = try { + CreationRecord( + host, body["intent"].asString ?: corrupt(), profile, + CreationPurpose.entries.firstOrNull { it.name == body["purpose"].asString } ?: corrupt(), + CreationPhase.entries.firstOrNull { it.name == body["phase"].asString } ?: corrupt(), + CreateRequest(body["cwd"].asString, body["title"].asString, body["model"].asString, body["provider"].asString, + body["reasoning"].asString, body["fast"].asBool), + body["stored"].asString, body["runtime"].asString, body["registry"].asString, + body["generation"].asLong ?: corrupt(), body["createdAt"].asLong ?: corrupt(), + ) + } catch (_: IllegalArgumentException) { + corrupt() + } + if (!record.isCoherent) corrupt() + return record + } + } +} + +/** A conversation's stored tip and routing aliases. Written when the tip first differs from the anchor or changes. */ +class IdentityRecord(val scope: ConversationScope, val identity: ConversationIdentity) { + fun encode(): ByteArray = encodeBounded(RecordKind.Identity, buildJsonObject { + put("v", SCHEMA); put("tip", identity.storedTip) + put("former", buildJsonArray { identity.formerStoredIds.forEach { add(JsonPrimitive(it)) } }) + put("root", identity.lineageRootId); put("registry", identity.canonicalRegistryId) + put("lineage", identity.lineageIds?.let { ids -> buildJsonArray { ids.forEach { add(JsonPrimitive(it)) } } } ?: JsonNull) + }.putScope(scope)) + + companion object { + fun decode(scope: ConversationScope, bytes: ByteArray): ConversationIdentity { + val body = parseRecord(bytes) + if (body["v"].asInt != SCHEMA || !body.scopeMatches(scope)) corrupt() + fun ids(array: JsonArray?, limit: Int): List? = array?.map { it.asString?.takeIf(Coordinates::isValid) ?: corrupt() }?.also { if (it.size > limit) corrupt() } + return try { + ConversationIdentity( + scope.ref, body["tip"].asString ?: corrupt(), ids(body["former"].asArray, ChatStoreLimits.MAXIMUM_FORMER_STORED_IDS).orEmpty(), + body["root"].asString, ids(body["lineage"].asArray, 10_000), body["registry"].asString, + ) + } catch (_: IllegalArgumentException) { + corrupt() + } + } + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatStore.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatStore.kt new file mode 100644 index 00000000..9490abc0 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatStore.kt @@ -0,0 +1,253 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.utf8Length +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * The platform-neutral durable store the chat repository writes through. The app supplies Android I/O + * (protected, atomic, backup-excluded files); this module only defines what must be stored, the exact scope + * of each record and the byte ceilings, so persistence is the same everywhere and a write failure is a typed + * result the repository can act on. Two classes of record never mix: + * + * * **Durable** records ([RecordKind.durable]): drafts, the submission journal, creation intents and the + * identity (routing aliases) of a conversation. They hold text a person typed or evidence of a possibly + * sent mutation, so a quota or eviction pass must never remove them. [ChatStore.commit] applies a list of + * them atomically (all or none) and throws [ChatStoreException] when it cannot; the repository then sends + * nothing. + * * **Cache** records: the catalog and retained history. They only make the next open faster. A cache write + * is best effort ([ChatStore.putCache]) and an implementation may drop any of them at any time; losing a + * cache record never changes what the person sees as unsent or uncertain. + */ +object ChatStoreLimits { + /** One message a person types or sends, as UTF-8. */ + const val MAXIMUM_MESSAGE_TEXT_BYTES = 1_048_576 + + /** The JSON-escaped form of one message (it must also fit one 2 MiB gateway frame with its envelope). */ + const val MAXIMUM_ENCODED_MESSAGE_BYTES = 2 * 1_048_576 - 16_384 + + /** Attachment references (names/handles, never attachment bytes) kept with a draft or journal entry. */ + const val MAXIMUM_ATTACHMENT_REFERENCES = 16 + const val MAXIMUM_ATTACHMENT_REFERENCE_BYTES = 1_024 + + /** One composer draft record: its text, escaped, plus references and envelope. */ + const val MAXIMUM_DRAFT_RECORD_BYTES = MAXIMUM_ENCODED_MESSAGE_BYTES + 65_536 + + /** One journal entry: the exact outgoing text and the original composer text, each escaped, plus envelope. */ + const val MAXIMUM_JOURNAL_ENTRY_BYTES = 2 * MAXIMUM_ENCODED_MESSAGE_BYTES + 65_536 + + /** Unresolved (uncertain or refused) entries one conversation may hold; a new send is refused past this. */ + const val MAXIMUM_UNRESOLVED_ENTRIES = 32 + + const val MAXIMUM_CREATION_RECORD_BYTES = 16_384 + const val MAXIMUM_IDENTITY_RECORD_BYTES = 131_072 + const val MAXIMUM_FORMER_STORED_IDS = 128 + + const val MAXIMUM_CATALOG_CACHE_BYTES = 8 * 1_048_576 + const val MAXIMUM_HISTORY_CACHE_BYTES = 32 * 1_048_576 + 1_048_576 +} + +/** + * One configured computer: the app's own UUID for the saved entry, its canonical endpoint + * ([app.bighelp.hermes.HermesEndpoint.canonical]) and the exact signed-in principal. Everything stored for a + * computer is scoped by all three, so another sign-in at the same address never sees these records. + */ +data class HostScope(val computerId: String, val endpoint: String, val principal: String) { + init { + require(Coordinates.isUuid(computerId)) { "The computer ID is a UUID" } + require(Coordinates.isValid(endpoint, 2_048)) { "Invalid endpoint" } + require(Coordinates.isValid(principal, 1_024)) { "Invalid principal" } + } + + override fun toString() = "HostScope($computerId)" +} + +/** A conversation's storage scope: the computer, the exact profile and the immutable anchor. */ +data class ConversationScope(val host: HostScope, val profile: String, val anchor: String) { + init { + require(Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) { "Invalid profile" } + require(Coordinates.isValid(anchor, Coordinates.MAXIMUM_COORDINATE_BYTES)) { "Invalid anchor" } + } + + val ref: ConversationRef get() = ConversationRef(profile, anchor) +} + +enum class RecordKind(val durable: Boolean, val maximumBytes: Int) { + /** The composer text of one conversation (and its attachment references). */ + Draft(true, ChatStoreLimits.MAXIMUM_DRAFT_RECORD_BYTES), + + /** One unresolved submission: an uncertain send, or a definite refusal kept for the person. */ + Journal(true, ChatStoreLimits.MAXIMUM_JOURNAL_ENTRY_BYTES), + + /** One create intent per computer and profile. */ + Creation(true, ChatStoreLimits.MAXIMUM_CREATION_RECORD_BYTES), + + /** A conversation's stored tip, former stored IDs (routing aliases) and registry facts. */ + Identity(true, ChatStoreLimits.MAXIMUM_IDENTITY_RECORD_BYTES), + + CatalogCache(false, ChatStoreLimits.MAXIMUM_CATALOG_CACHE_BYTES), + HistoryCache(false, ChatStoreLimits.MAXIMUM_HISTORY_CACHE_BYTES), +} + +/** + * The exact address of one record. Two keys are equal only when every field is equal; [canonical] is an + * unambiguous, length-prefixed rendering a store may hash into a file name (the record body repeats its + * scope, and the repository checks it on read, so a collision could never cross scopes unnoticed). + */ +class RecordKey private constructor( + val kind: RecordKind, + val host: HostScope, + val profile: String?, + val anchor: String?, + val entry: String?, +) { + val canonical: String = listOf( + kind.name, host.computerId, host.endpoint, host.principal, profile.orEmpty(), anchor.orEmpty(), entry.orEmpty(), + "${profile != null}${anchor != null}${entry != null}", + ).joinToString("|") { "${it.length}:$it" } + + override fun equals(other: Any?) = other is RecordKey && other.canonical == canonical + override fun hashCode() = canonical.hashCode() + override fun toString() = "RecordKey(${kind.name})" + + companion object { + /** + * Rebuilds a key from its stored components (a file-backed store persists them to answer [ChatStore.keys] + * after a restart). Each kind has one shape; any other combination is an `IllegalArgumentException`. + */ + fun of(kind: RecordKind, host: HostScope, profile: String?, anchor: String?, entry: String?): RecordKey { + val shape = when (kind) { + RecordKind.Draft, RecordKind.Identity, RecordKind.HistoryCache -> profile != null && anchor != null && entry == null + RecordKind.Journal -> profile != null && anchor != null && entry != null && Coordinates.isUuid(entry) + RecordKind.Creation -> profile != null && anchor == null && entry == null + RecordKind.CatalogCache -> profile == null && anchor == null && entry == null + } + require(shape) { "Invalid key shape for ${kind.name}" } + profile?.let { require(Coordinates.isValid(it, Coordinates.MAXIMUM_PROFILE_BYTES)) { "Invalid profile" } } + anchor?.let { require(Coordinates.isValid(it)) { "Invalid anchor" } } + return RecordKey(kind, host, profile, anchor, entry) + } + + fun draft(scope: ConversationScope) = RecordKey(RecordKind.Draft, scope.host, scope.profile, scope.anchor, null) + fun journal(scope: ConversationScope, entryId: String): RecordKey { + require(Coordinates.isUuid(entryId)) { "A journal entry ID is a UUID" } + return RecordKey(RecordKind.Journal, scope.host, scope.profile, scope.anchor, entryId) + } + fun creation(host: HostScope, profile: String) = RecordKey(RecordKind.Creation, host, profile, null, null) + fun identity(scope: ConversationScope) = RecordKey(RecordKind.Identity, scope.host, scope.profile, scope.anchor, null) + fun catalog(host: HostScope) = RecordKey(RecordKind.CatalogCache, host, null, null, null) + fun history(scope: ConversationScope) = RecordKey(RecordKind.HistoryCache, scope.host, scope.profile, scope.anchor, null) + } +} + +sealed interface StoreOp { + /** [bytes] never exceed `key.kind.maximumBytes`; a store refuses a larger record with [ChatStoreException.Kind.TooLarge]. */ + class Put(val key: RecordKey, val bytes: ByteArray) : StoreOp + class Delete(val key: RecordKey) : StoreOp +} + +/** A durable write that was not applied. Nothing of the failed transaction is visible afterwards. */ +class ChatStoreException(val kind: Kind, cause: Throwable? = null) : Exception(kind.name, cause) { + enum class Kind { Unavailable, TooLarge, Corrupt, QuotaExceeded } +} + +interface ChatStore { + /** The exact record, or null when absent. A corrupt record is [ChatStoreException.Kind.Corrupt], never silently empty. */ + suspend fun read(key: RecordKey): ByteArray? + + /** Keys of [kind] for [host], optionally narrowed to one profile and anchor. Used to find retained work after a restart. */ + suspend fun keys(host: HostScope, kind: RecordKind, profile: String? = null, anchor: String? = null): List + + /** + * Applies [ops] atomically, durable kinds only (a cache kind is `IllegalArgumentException`). Either every + * operation is visible afterwards, also after a process restart, or none is and this throws. + */ + suspend fun commit(ops: List) + + /** Best effort: may be dropped, never throws for capacity or I/O, never affects durable records. */ + suspend fun putCache(key: RecordKey, bytes: ByteArray) + suspend fun deleteCache(key: RecordKey) +} + +/** + * A volatile reference store: atomic by construction, bounded like any other. For tests and the labeled demo; + * the app's real store implements [ChatStore] over protected files. + */ +open class MemoryChatStore : ChatStore { + private val lock = Mutex() + protected val records = LinkedHashMap() + private val closed = AtomicBoolean(false) + + override suspend fun read(key: RecordKey): ByteArray? = lock.withLock { records[key]?.copyOf() } + + override suspend fun keys(host: HostScope, kind: RecordKind, profile: String?, anchor: String?): List = + lock.withLock { + records.keys.filter { + it.kind == kind && it.host == host && (profile == null || it.profile == profile) && + (anchor == null || it.anchor == anchor) + } + } + + override suspend fun commit(ops: List) { + for (op in ops) { + val key = op.key() + require(key.kind.durable) { "A cache record is not a durable commit" } + if (op is StoreOp.Put && op.bytes.size > key.kind.maximumBytes) throw ChatStoreException(ChatStoreException.Kind.TooLarge) + } + lock.withLock { + beforeApply(ops) + for (op in ops) when (op) { + is StoreOp.Put -> records[op.key] = op.bytes.copyOf() + is StoreOp.Delete -> records.remove(op.key) + } + afterApply() + } + } + + 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 + lock.withLock { records[key] = bytes.copyOf() } + } + + override suspend fun deleteCache(key: RecordKey) { + require(!key.kind.durable) { "A durable record is not a cache delete" } + lock.withLock { records.remove(key) } + } + + /** Hook for subclasses (failure injection, snapshots): runs under the lock before any operation is applied; throw to refuse the whole commit. */ + protected open fun beforeApply(ops: List) = Unit + + /** Runs under the lock after a commit was applied in memory. */ + protected open fun afterApply() = Unit + + private fun StoreOp.key() = when (this) { + is StoreOp.Put -> key + is StoreOp.Delete -> key + } +} + +/** Coordinate and text validation shared by every record and response check. Compares bytes, never normalized text. */ +internal object Coordinates { + const val MAXIMUM_COORDINATE_BYTES = 512 + const val MAXIMUM_PROFILE_BYTES = 128 + + /** Nonempty, bounded, exactly its trimmed self, no control or format characters (Swift `validateIdentifier`). */ + fun isValid(value: String, maximumBytes: Int = MAXIMUM_COORDINATE_BYTES): Boolean { + if (value.isEmpty() || utf8Length(value) > maximumBytes) return false + if (value != value.trim { Character.isWhitespace(it) || Character.isSpaceChar(it) }) return false + var index = 0 + while (index < value.length) { + val point = value.codePointAt(index) + index += Character.charCount(point) + val type = Character.getType(point) + if (type == Character.CONTROL.toInt() || type == Character.FORMAT.toInt()) return false + } + return true + } + + fun isUuid(value: String): Boolean = UUID_PATTERN.matches(value) + + private val UUID_PATTERN = Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt new file mode 100644 index 00000000..6073d612 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt @@ -0,0 +1,633 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.GatewayEvent +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.WireMessage +import app.bighelp.hermes.utf8Length +import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * Owns every open conversation: applying live events in order, attaching a stored chat to a runtime, the + * recovery bracket after any reconnect, canonical history and the durable drafts and journal. All mutable state + * is confined to the serial dispatcher; requests to the host are awaited outside it and every result is + * re-checked against the owner (registered runtime, socket generation, hydration token) before it is applied. + */ +internal class ConversationEngine( + private val ctx: ChatContext, + private val binder: SessionBinder, +) { + val conversations = LinkedHashMap() + private val mutableStates = MutableStateFlow>(emptyMap()) + val states: StateFlow> = mutableStates.asStateFlow() + val historyCache = HistoryWindowCache() + lateinit var prompts: PromptCenter + lateinit var submissions: SubmissionEngine + + private val rowLimit get() = minOf(400, ctx.config.turnLimit * 40) + + // ---- publishing + + fun publish(rt: ConversationRuntime) { + mutableStates.value = mutableStates.value + (rt.ref to snapshot(rt)) + } + + fun publishAll() { + mutableStates.value = conversations.mapValues { snapshot(it.value) } + } + + fun snapshot(rt: ConversationRuntime): ConversationState { + val savedIds = rt.saved?.rows?.mapTo(HashSet()) { it.id }.orEmpty() + val live = rt.reducer.items.filter { !(it is MessageItem && it.rowId != null && it.rowId in savedIds) } + return ConversationState( + ref = rt.ref, title = rt.title, identity = rt.identity, phase = rt.phase, items = rt.savedItems + live, + running = rt.reducer.running, status = rt.status, runtime = rt.runtimeInfo, draft = rt.draft, + draftAttachments = rt.draftAttachments, sendBlock = sendBlock(rt), + unresolved = rt.unresolved.map { UnresolvedSubmission(it.id, it.method, it.composerText, it.attachments, it.createdAtMillis, it.rejectionCode) }, + prompts = prompts.statesFor(rt.ref), + history = HistoryState(rt.saved?.nextOffset != null, rt.loadingOlder, rt.saved?.rows?.size ?: 0), + stopRequested = rt.stopRequested, legacyPromptHost = rt.legacyPromptHost, lastError = rt.lastError, + ) + } + + /** Why a new message cannot be admitted now; null when it can. Steering a running turn stays open while a send is pending. */ + fun sendBlock(rt: ConversationRuntime): SendBlock? { + val gateway = ctx.gateway.state.value + val binding = rt.binding + return when { + rt.phase == ConversationPhase.Opening -> SendBlock.Opening + gateway.connection != GatewayConnection.Connected -> SendBlock.NotConnected + binding == null || rt.requiresReattach -> SendBlock.NoLiveSession + binding.generation != gateway.generation -> SendBlock.NotConnected + rt.hydrating -> SendBlock.CatchingUp + rt.needsRecovery -> SendBlock.RecoveryRequired + gateway.capabilities?.perSessionExclusiveSubmit != true -> SendBlock.HostLacksExclusiveSubmit + rt.pending != null && !rt.reducer.running -> SendBlock.PendingAdmission + rt.unresolved.size >= ChatStoreLimits.MAXIMUM_UNRESOLVED_ENTRIES -> SendBlock.TooManyUnresolved + else -> null + } + } + + // ---- durable work + + /** Commits [ops] atomically. The in-memory change that goes with them is applied by the caller only after this returns. */ + suspend fun commit(ops: List) = ctx.store.commit(ops) + + fun draftOp(scope: ConversationScope, text: String, attachments: List): StoreOp = + if (text.isEmpty() && attachments.isEmpty()) StoreOp.Delete(RecordKey.draft(scope)) + else StoreOp.Put(RecordKey.draft(scope), DraftRecord(scope, text, attachments, ctx.config.clock()).encode()) + + private suspend fun loadDurable(scope: ConversationScope, hint: SessionSummary?): Triple> { + val identity = ctx.store.read(RecordKey.identity(scope))?.let { runCatching { IdentityRecord.decode(scope, it) }.getOrNull() } + ?: ConversationIdentity(scope.ref, hint?.storedId ?: scope.anchor, lineageRootId = hint?.lineageRootId, lineageIds = hint?.lineageIds, + canonicalRegistryId = if (hint?.isCanonicalBotChat == true) scope.anchor else binder.canonical[scope.profile]?.id?.takeIf { it == scope.anchor }) + val draft = ctx.store.read(RecordKey.draft(scope))?.let { runCatching { DraftRecord.decode(scope, it) }.getOrNull() } + val entries = ctx.store.keys(ctx.host, RecordKind.Journal, scope.profile, scope.anchor).mapNotNull { key -> + ctx.store.read(key)?.let { bytes -> runCatching { JournalEntry.decode(scope, key.entry!!, bytes) }.getOrNull() } + }.sortedBy { it.createdAtMillis } + return Triple(identity, draft, entries) + } + + // ---- open and attach + + /** Registers [ref], loads its durable draft, journal and identity, and attaches it when the socket is ready. */ + suspend fun open(ref: ConversationRef, hint: SessionSummary?): ConversationRuntime { + ctx.onState { conversations[ref] }?.let { existing -> + // A chat whose recovery failed, or that lost its socket, is attached again by opening it; a healthy one is left alone. + val healthy = existing.phase == ConversationPhase.Ready && !existing.needsRecovery && !existing.requiresReattach && + existing.binding?.generation == ctx.gateway.state.value.generation + if (!healthy) attach(existing) + return existing + } + val scope = ctx.conversationScope(ref) + val (identity, draft, entries) = loadDurable(scope, hint) + val rt = ConversationRuntime(scope, identity, hint?.title ?: "Chat") + rt.draft = draft?.text.orEmpty() + rt.draftAttachments = draft?.attachments.orEmpty() + rt.unresolved += entries + // A previous run's pending sends are unresolved by definition: they may or may not have reached the host. + val registered = ctx.onState { + conversations[ref]?.let { return@onState it } + conversations[ref] = rt + publish(rt) + null + } + if (registered != null) return registered + seedFromCache(rt) + attach(rt) + return rt + } + + /** A stored copy of the newest page, shown at once. It never replaces anything once live events advanced the cursor. */ + private suspend fun seedFromCache(rt: ConversationRuntime) { + val bytes = ctx.store.read(RecordKey.history(rt.scope)) ?: return + val cached = runCatching { HistoryCacheCodec.decode(bytes) }.getOrNull() ?: return + ctx.onState { + if (rt.saved == null && rt.reducer.lastSequence == 0L && !rt.reducer.hasLiveEvents) { + setSaved(rt, cached, persist = false) + publish(rt) + } + } + } + + /** Resume by stored ID on the current socket and recover coverage. Failure leaves the transcript and marks the chat suspended. */ + suspend fun attach(rt: ConversationRuntime) { + val state = ctx.gateway.state.value + if (state.connection != GatewayConnection.Connected) { + ctx.onState { suspendLocal(rt, ConversationPhase.Suspended); publish(rt) } + return + } + val generation = state.generation + ctx.onState { + rt.hydrating = true; rt.phase = if (rt.hasRecovered) ConversationPhase.Recovering else ConversationPhase.Opening + rt.lastError = null; publish(rt) + } + try { + val tip = ctx.onState { rt.identity.storedTip } + val attached = binder.resume(rt.scope.profile, tip) + val proceed = ctx.onState { + if (conversations[rt.ref] !== rt || ctx.gateway.state.value.generation != generation) return@onState false + val before = rt.binding + if (attached.storedId != rt.identity.storedTip) { + if (!IdentityAdoption.accepts(rt.identity, attached.storedId, IdentityAdoption.Evidence.ResumeOfCurrentTip)) throw ChatException(ChatError.Kind.InvalidResponse) + rt.identity = rt.identity.withTip(attached.storedId) + } + // Sequence numbers belong to one runtime: another runtime's cursor never advances this one. + if (before != null && before.runtimeId != attached.runtimeId) rt.reducer.resetCursor("", 0) + rt.binding = Binding(attached.runtimeId, attached.storedId, generation, null, rt.scope.profile) + rt.requiresReattach = false + applyInfo(rt, attached.info) + true + } + if (!proceed) return + persistIdentity(rt) + recover(rt, generation) + } catch (e: ChatException) { + fail(rt, e.error) + } catch (e: HermesException) { + fail(rt, SessionBinder.chatError(e).let { if (e.kind == HermesException.Kind.RpcRejected && (e.code == 4007L || e.code == 404L)) ChatError(ChatError.Kind.NotOpen, e.kind, e.code, e.reason) else it }) + } catch (e: app.bighelp.hermes.RequestCancelledException) { + fail(rt, ChatError(ChatError.Kind.Cancelled)) + return + } + // Reading saved history is not part of coverage: a failure here leaves the chat usable, with the error shown. + try { + refreshNewest(rt) + } catch (e: ChatException) { + ctx.onState { rt.lastError = e.error; publish(rt) } + } catch (e: HermesException) { + ctx.onState { rt.lastError = SessionBinder.chatError(e); publish(rt) } + } + } + + private suspend fun fail(rt: ConversationRuntime, error: ChatError) { + ctx.onState { + rt.hydrating = false + rt.heldEvents = ArrayList() + rt.lastError = error + if (rt.phase != ConversationPhase.Ready) rt.phase = ConversationPhase.Suspended + rt.needsRecovery = true + publish(rt) + } + } + + private fun persistIdentityLater(rt: ConversationRuntime) { ctx.scope.launch { persistIdentity(rt) } } + + private suspend fun persistIdentity(rt: ConversationRuntime) { + val identity = ctx.onState { rt.identity } + if (identity.storedTip == rt.scope.anchor && identity.formerStoredIds.isEmpty() && identity.lineageIds == null && identity.canonicalRegistryId == null) return + runCatching { ctx.store.commit(listOf(StoreOp.Put(RecordKey.identity(rt.scope), IdentityRecord(rt.scope, identity).encode()))) } + } + + private fun applyInfo(rt: ConversationRuntime, info: JsonObject) { + rt.runtimeInfo = rt.runtimeInfo.merged( + RuntimeInfo(info["model"].asString, info["provider"].asString, info["reasoning_effort"].asString, info["service_tier"].asString, + info["cwd"].asString, info["lazy"].asBool), + ) + } + + // ---- connection changes + + /** Synchronous with the `gateway.ready` that announces a new socket: close admission before any later event applies. */ + fun onSocketReady(generation: Long) { + for (rt in conversations.values) { + if (rt.binding?.generation == generation && !rt.requiresReattach) continue + suspendLocal(rt, ConversationPhase.Recovering) + rt.hydrating = true + } + publishAll() + } + + /** Re-attaches every retained conversation on the new socket, once it is fully connected. */ + suspend fun reattachAll(generation: Long) { + val targets = ctx.onState { conversations.values.filter { !(it.binding?.generation == generation && !it.requiresReattach) } } + for (rt in targets) { + if (ctx.gateway.state.value.generation != generation) return + attach(rt) + } + } + + fun onDisconnected() { + for (rt in conversations.values) suspendLocal(rt, ConversationPhase.Suspended) + publishAll() + } + + /** A conversation just created: bound from the create answer itself, then covered like any other. */ + suspend fun adoptCreated(ref: ConversationRef, attached: Attached, title: String): ConversationRuntime { + val generation = ctx.gateway.state.value.generation + val scope = ctx.conversationScope(ref) + val rt = ConversationRuntime(scope, ConversationIdentity(ref, attached.storedId), title) + ctx.onState { + conversations[ref] = rt + rt.binding = Binding(attached.runtimeId, attached.storedId, generation, null, scope.profile) + rt.hydrating = true + applyInfo(rt, attached.info) + publish(rt) + } + try { + recover(rt, generation) + } catch (e: ChatException) { fail(rt, e.error) } catch (e: HermesException) { fail(rt, SessionBinder.chatError(e)) } + return rt + } + + /** + * Revokes transport authority, not the visible transcript: held events are dropped, prompts retire, and an + * already confirmed admission keeps its evidence so an exact replay of its terminal can settle it later. + */ + fun suspendLocal(rt: ConversationRuntime, phase: ConversationPhase) { + rt.pending?.let { pending -> + if (pending.admitted && !pending.overlapped) pending.selectedTurn?.let { rt.acceptedEvidence = AcceptedEvidence(pending.entry.id, it, rt.reducer.epoch) } + rt.needsRecovery = true + } + rt.pending = null + rt.phase = phase + rt.hydrating = false + rt.heldEvents = ArrayList() + rt.heldOverflow = false + rt.stopRequested = false + prompts.retireFor(rt.ref) + rt.status = null + } + + // ---- events + + fun onEvent(gatewayEvent: GatewayEvent) { + val event = gatewayEvent.event + when (event.type) { + "gateway.ready" -> onSocketReady(gatewayEvent.generation) + "session.reclaimed" -> reclaim(event, gatewayEvent.generation) + else -> { + if (gatewayEvent.generation != ctx.gateway.state.value.generation) return + val runtime = event.sessionID ?: return + val rt = conversations.values.firstOrNull { it.binding?.runtimeId == runtime && it.binding?.generation == gatewayEvent.generation } ?: return + if (rt.hydrating) { + if (rt.heldEvents.size >= HELD_EVENT_LIMIT) rt.heldOverflow = true else rt.heldEvents += event + return + } + apply(rt, event, replaying = false) + publish(rt) + } + } + } + + /** `session.reclaimed`: revoke the writer first. Only the exact owner (both payload IDs and, if present, the outer ID) matches. */ + private fun reclaim(event: WireMessage.Event, generation: Long) { + val payload = event.payload + if (payload.keys != setOf("session_id", "stored_session_id", "reason")) return + val runtime = payload["session_id"].asString ?: return + val stored = payload["stored_session_id"].asString ?: return + if (event.sessionID != null && event.sessionID != runtime) return + val rt = conversations.values.firstOrNull { it.binding?.runtimeId == runtime && it.binding?.generation == generation && it.identity.knows(stored) } ?: return + rt.requiresReattach = true + suspendLocal(rt, ConversationPhase.Suspended) + rt.status = "Hermes ended this live session. Reopen it before sending." + publish(rt) + } + + /** Applies one event of this runtime. [replaying] marks recovery replay: it settles state but is not new live activity. */ + fun apply(rt: ConversationRuntime, event: WireMessage.Event, replaying: Boolean) { + val change = rt.reducer.accept(event) + if (change.ignored) return + if (rt.liveBaselineRowId < 0 && (change.started || rt.reducer.items.isNotEmpty())) rt.liveBaselineRowId = rt.saved?.rows?.maxOfOrNull { it.id } ?: 0 + change.storedIdReport?.let { report -> adoptReportedTip(rt, report) } + change.runtime?.let { rt.runtimeInfo = rt.runtimeInfo.merged(it) } + change.title?.let { rt.title = it } + change.status?.let { rt.status = it } + if (change.compaction == CompactionSignal.Compacted) rt.status = "Compacted" + val pending = rt.pending + if (event.type == "message.start") pending?.turnFailed = false + if (event.type == "error" || change.terminalError != null) pending?.turnFailed = true + if (pending != null && event.type == "message.start") { + if (pending.candidateTurns.size < 2 && rt.reducer.turnId !in pending.candidateTurns) pending.candidateTurns += rt.reducer.turnId + pending.select() + } + if (change.failedBeforeStart && pending != null && pending.candidateTurns.isEmpty()) pending.candidateTurns += rt.reducer.turnId + if (change.terminal) { + rt.status = null + rt.stopRequested = false + if (pending != null && rt.reducer.turnId in pending.candidateTurns) { + pending.settledTurns[rt.reducer.turnId] = pending.turnFailed + pending.select() + submissions.completeIfReady(rt) + } + rt.acceptedEvidence?.let { evidence -> + if (event.sequence != null && evidence.epoch == rt.reducer.epoch && evidence.turnId == rt.reducer.turnId && pending?.turnFailed != true) { + submissions.retireAfterReplay(rt, evidence.entryId) + rt.acceptedEvidence = null + rt.needsRecovery = false + } + } + } + if (!replaying) change.persistedTurn?.let { rt.reducer.bindRows(it) } + // The host's saved history is the truth once a turn ends: read the newest page again (live rows stay until it has caught up). + if (!replaying && change.terminal) refreshHistoryLater(rt) + if (change.errorEvent) rt.status = "Hermes reported a turn error." + } + + private fun refreshHistoryLater(rt: ConversationRuntime) { + val generation = rt.binding?.generation ?: return + ctx.scope.launch { + if (ctx.gateway.state.value.generation != generation) return@launch + try { + refreshNewest(rt) + } catch (e: ChatException) { + ctx.onState { rt.lastError = e.error; publish(rt) } + } catch (e: HermesException) { + ctx.onState { rt.lastError = SessionBinder.chatError(e); publish(rt) } + } + } + } + + private fun adoptReportedTip(rt: ConversationRuntime, report: String) { + if (report == rt.identity.storedTip) return + if (!IdentityAdoption.accepts(rt.identity, report, IdentityAdoption.Evidence.RuntimeReport)) return + rt.identity = rt.identity.withTip(report) + rt.binding = rt.binding?.copy(storedId = report) + persistIdentityLater(rt) + } + + // ---- recovery + + /** + * The bracket: replay since the cursor, activation, replay since that, then reconcile. Admission reopens only + * when every held live event extends the accepted cursor without a gap. Never resumes or resends a prompt. + */ + suspend fun recover(rt: ConversationRuntime, generation: Long) { + val profile = rt.scope.profile + val (runtimeId, hint, checkpoint, knownEpoch) = ctx.onState { + val binding = rt.binding ?: throw ChatException(ChatError.Kind.NoLiveSession) + if (binding.generation != generation) throw ChatException(ChatError.Kind.NotConnected) + rt.hydrating = true + Quad(binding.runtimeId, ctx.gateway.state.value.replayEpoch ?: rt.reducer.epoch, rt.reducer.lastSequence, rt.reducer.epoch) + } + var succeeded = false + try { + val before = eventsSince(runtimeId, if (hint == knownEpoch) checkpoint else 0) + val snapshot = binder.activate(profile, runtimeId) + ctx.onState { requireCurrent(rt, generation, runtimeId) } + val attached = validatedActivation(snapshot, runtimeId, profile) + val tail = eventsSince(runtimeId, before.latest) + if (tail.epoch != before.epoch) throw invalidResponse() + ctx.onState { requireCurrent(rt, generation, runtimeId) } + val modern = tail.openRequests != null + if (tail.openRequests != null && tail.openRequests !is JsonArray) throw invalidResponse() + if (modern) ctx.gateway.adoptOpenRequests(tail.openRequests!!, runtimeId, generation) + val exact = before.epoch == knownEpoch && checkpoint > 0 && before.truncated == false && tail.truncated == false + ctx.onState { + requireCurrent(rt, generation, runtimeId) + rt.legacyPromptHost = !modern + applyInfo(rt, attached.info) + if (attached.storedId != rt.identity.storedTip && IdentityAdoption.accepts(rt.identity, attached.storedId, IdentityAdoption.Evidence.RuntimeReport)) { + rt.identity = rt.identity.withTip(attached.storedId) + } + rt.binding = rt.binding?.copy(storedId = attached.storedId, epoch = before.epoch) + if (exact) { + replay(rt, before.events) + replay(rt, tail.events) + val tailOwnsLiveness = tail.events.any { + it.type == "message.start" || it.type == "message.delta" || (it.type == "session.info" && it.payload["running"].asBool != null) + } + if (!tailOwnsLiveness) snapshotLifecycle(rt, attached) + } else { + // No complete ring: adopt the activation as source detail, never double-append an unknown overlap. + if (rt.reducer.epoch != before.epoch) rt.reducer.resetCursor(before.epoch, 0) + rt.reducer.seedRunning(attached.running == true) + if (before.latest != tail.latest) { + tail.events.filter { it.type == "session.info" || it.type == "message.start" }.forEach { replay(rt, listOf(it)) } + } + rt.reducer.seedCheckpoint(tail.latest) + rt.needsHistoryReseed = attached.running != true + if (attached.running != true && rt.pending != null) { + // A replacement snapshot cannot prove admission of a lost RPC: keep the journal entry untouched. + rt.needsRecovery = true + rt.pending = null + } + } + if (!replayHeld(rt)) throw ChatException(ChatError.Kind.NotConnected, HermesException.Kind.TooManyRequests) + rt.needsRecovery = false + rt.hydrating = false + rt.hasRecovered = true + rt.phase = ConversationPhase.Ready + rt.status = null + publish(rt) + } + succeeded = true + } catch (e: Throwable) { + ctx.onState { + // A recovery that belongs to a socket that has since been replaced must not touch the newer owner's state. + if (!succeeded && rt.binding?.generation == generation && ctx.gateway.state.value.generation == generation) { + // Keep admission closed and the held events for the next catch-up. + rt.needsRecovery = true + rt.hydrating = false + } + } + throw e + } + } + + private class Quad(val a: A, val b: B, val c: C, val d: D) { + operator fun component1() = a + operator fun component2() = b + operator fun component3() = c + operator fun component4() = d + } + + private class Replay(val epoch: String, val latest: Long, val truncated: Boolean?, val events: List, val openRequests: JsonElement?) + + private suspend fun eventsSince(runtimeId: String, lastSeen: Long): Replay { + val result = ctx.gateway.request("session.events.since", buildJsonObject { put("session_id", runtimeId); put("last_seen", lastSeen) }).asObject ?: throw invalidResponse() + val epoch = result["epoch"].asString ?: throw invalidResponse() + val latest = result["latest_seq"].asLong?.takeIf { it >= 0 } ?: throw invalidResponse() + val events = (result["events"].asArray ?: JsonArray(emptyList())).mapNotNull { frame -> + // Stock events.since returns params dictionaries, not envelopes; accept either. + val params = frame.asObject?.get("params").asObject ?: frame.asObject ?: return@mapNotNull null + val type = params["type"].asString ?: return@mapNotNull null + WireMessage.Event(type, params["session_id"].asString, params["payload"].asObject ?: JsonObject(emptyMap()), params["seq"].asLong, params) + }.sortedBy { it.sequence ?: 0 } + return Replay(epoch, latest, result["truncated"].asBool, events, result["open_requests"]) + } + + private fun validatedActivation(snapshot: JsonObject, runtimeId: String, profile: String): Attached { + if (snapshot["session_id"].asString != runtimeId || snapshot["running"].asBool == null) throw invalidResponse() + val stored = snapshot["session_key"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + val info = snapshot["info"].asObject ?: JsonObject(emptyMap()) + info["profile_name"]?.let { if (it.asString != profile) throw invalidResponse() } + info["stored_session_id"]?.let { if (it.asString != stored) throw invalidResponse() } + return Attached(runtimeId, stored, snapshot["running"].asBool, info, info["model"].asString, info["cwd"].asString) + } + + private fun requireCurrent(rt: ConversationRuntime, generation: Long, runtimeId: String) { + val binding = rt.binding + if (conversations[rt.ref] !== rt || binding == null || binding.generation != generation || binding.runtimeId != runtimeId || + ctx.gateway.state.value.generation != generation + ) throw ChatException(ChatError.Kind.NotConnected) + } + + private fun replay(rt: ConversationRuntime, events: List) { + for (event in events.sortedBy { it.sequence ?: 0 }) apply(rt, event, replaying = true) + } + + /** The activation's `running` is the newest liveness observation unless the replay tail carried its own. */ + private fun snapshotLifecycle(rt: ConversationRuntime, attached: Attached) { + val info = JsonObject(attached.info + ("running" to JsonPrimitive(attached.running == true))) + apply(rt, WireMessage.Event("session.info", rt.binding?.runtimeId, info, null), replaying = true) + if (attached.running != true) rt.needsHistoryReseed = true + } + + /** Opens admission only if every event held during recovery extends the cursor with no gap or duplicate. */ + private fun replayHeld(rt: ConversationRuntime): Boolean { + if (rt.heldOverflow || rt.heldEvents.any { it.sequence == null }) return false + val checkpoint = rt.reducer.lastSequence + val pending = rt.heldEvents.filter { (it.sequence ?: 0) > checkpoint }.sortedBy { it.sequence } + if (!pending.withIndex().all { (index, event) -> event.sequence == checkpoint + index + 1 }) return false + rt.hydrating = false + rt.heldEvents = ArrayList() + rt.heldOverflow = false + pending.forEach { apply(rt, it, replaying = false) } + return true + } + + // ---- history + + private fun pathIdentifier(id: String): String { + if (id.isEmpty() || utf8Length(id) > 512 || id == "." || id == ".." || !id.all { it.isLetterOrDigit() && it.code < 128 || it in "-_.:" }) throw ChatException(ChatError.Kind.InvalidResponse) + return id + } + + /** Reads the newest page and refreshes the retained window; a result for a stale owner or token is discarded. */ + suspend fun refreshNewest(rt: ConversationRuntime) { + val token = ctx.onState { ++rt.historyToken } + val stored = ctx.onState { rt.identity.storedTip } + val limit = rowLimit + val envelope = ctx.rest.get("/api/sessions/${pathIdentifier(stored)}/messages", historyQuery(rt.scope.profile, limit, 0, "latest")) + val page = HistoryPage.parse(envelope, rt.scope.profile, 0, limit, "latest") + ctx.onState { + if (conversations[rt.ref] !== rt || rt.historyToken != token) return@onState + if (!acceptStored(rt, page.storedId)) throw ChatException(ChatError.Kind.HistoryChanged) + val window = HistoryWindow.refreshed(rt.saved, page) + setSaved(rt, window, persist = true) + reconcileLive(rt) + rt.needsHistoryReseed = false + publish(rt) + } + } + + private fun acceptStored(rt: ConversationRuntime, returned: String): Boolean { + if (returned == rt.identity.storedTip) return true + if (!IdentityAdoption.accepts(rt.identity, returned, IdentityAdoption.Evidence.HistoryResponse)) return false + rt.identity = rt.identity.withTip(returned) + rt.binding = rt.binding?.copy(storedId = returned) + persistIdentityLater(rt) + return true + } + + suspend fun loadOlder(ref: ConversationRef): HistoryLoad { + val rt = ctx.onState { conversations[ref] } ?: return HistoryLoad.Failed(ChatError(ChatError.Kind.NotOpen)) + val (window, token) = ctx.onState { + val held = rt.saved + if (held?.nextOffset == null || rt.loadingOlder) return@onState null to 0L + rt.loadingOlder = true; publish(rt) + held to ++rt.historyToken + } + if (window == null) return HistoryLoad.NothingOlder + try { + val offset = window.nextOffset!! + val limit = rowLimit + 1 + val envelope = ctx.rest.get("/api/sessions/${pathIdentifier(window.storedId)}/messages", historyQuery(rt.scope.profile, limit, offset - 1, "latest")) + val page = HistoryPage.parse(envelope, rt.scope.profile, offset - 1, limit, "latest") + return ctx.onState { + if (conversations[ref] !== rt || rt.historyToken != token || rt.saved !== window) return@onState HistoryLoad.Failed(ChatError(ChatError.Kind.Cancelled)) + val merged = HistoryWindow.prepended(window, page) + setSaved(rt, merged, persist = true) + publish(rt) + HistoryLoad.Loaded(merged.rows.size - window.rows.size, merged.nextOffset != null) + } + } catch (e: ChatException) { + if (e.error.kind == ChatError.Kind.HistoryChanged) { + // A shifted or rewritten window is never merged: start over from the newest page. + ctx.onState { rt.saved = null; historyCache.remove(ref) } + runCatching { refreshNewest(rt) } + } + return HistoryLoad.Failed(e.error) + } catch (e: HermesException) { + return HistoryLoad.Failed(SessionBinder.chatError(e)) + } finally { + ctx.onState { rt.loadingOlder = false; publish(rt) } + } + } + + private fun historyQuery(profile: String, limit: Int, offset: Int, order: String) = + listOf("profile" to profile, "limit" to limit.toString(), "offset" to offset.toString(), "order" to order, "include_compacted" to "true") + + fun setSaved(rt: ConversationRuntime, window: HistoryWindow, persist: Boolean) { + rt.saved = window + rt.savedItems = HistoryProjection.project(window.rows).items + historyCache.put(rt.ref, window) + if (persist) { + val bytes = HistoryCacheCodec.encode(window) + ctx.scope.launch { ctx.store.putCache(RecordKey.history(rt.scope), bytes) } + } + } + + /** + * Drops live rows once saved history holds what they showed: only when it has rows newer than when the live + * activity began, and, if the live tail carried an assistant reply, an assistant row among them. Otherwise the + * richer live rows stay and a later refresh tries again. + */ + private fun reconcileLive(rt: ConversationRuntime) { + if (rt.reducer.running || rt.pending != null) return + val live = rt.reducer.items + if (live.isEmpty()) { rt.liveBaselineRowId = -1; return } + val rows = rt.saved?.rows ?: return + val baseline = rt.liveBaselineRowId.coerceAtLeast(0) + val newer = rows.filter { it.id > baseline && it.isVisible } + if (newer.isEmpty()) return + val needsAssistant = live.any { it is MessageItem && it.role == MessageRole.Assistant } + if (needsAssistant && newer.none { it.role == "assistant" }) return + rt.reducer.clearItems() + rt.liveBaselineRowId = -1 + } + + // ---- misc + + fun byRuntime(runtimeId: String, generation: Long): ConversationRuntime? = + conversations.values.firstOrNull { it.binding?.runtimeId == runtimeId && it.binding?.generation == generation } + + companion object { + const val HELD_EVENT_LIMIT = 16_384 + } +} + +internal fun RuntimeInfo.merged(patch: RuntimeInfo) = RuntimeInfo( + patch.model ?: model, patch.provider ?: provider, patch.reasoningEffort ?: reasoningEffort, patch.serviceTier ?: serviceTier, + patch.cwd ?: cwd, patch.lazy ?: lazy, +) diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt new file mode 100644 index 00000000..25109c14 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt @@ -0,0 +1,90 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.WireMessage +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.withContext + +/** Everything the chat pieces share: the seams, the store, the one serial dispatcher that guards all mutable state. */ +internal class ChatContext( + val gateway: ChatGateway, + val rest: ChatRest, + val store: ChatStore, + val host: HostScope, + val config: ChatConfig, + val scope: CoroutineScope, + val serial: CoroutineDispatcher, +) { + /** Runs [block] on the serial dispatcher. Never await a gateway request inside it: events need this dispatcher too. */ + suspend fun onState(block: () -> T): T = withContext(serial) { block() } + + fun conversationScope(ref: ConversationRef) = ConversationScope(host, ref.profile, ref.anchor) +} + +/** + * The live attachment of one conversation to the host: the runtime ID commands target, the stored ID it was + * resumed from, and the socket generation and replay epoch that make it valid. A binding is proof only for + * the socket it came from; a new socket needs a new one. + */ +internal data class Binding(val runtimeId: String, val storedId: String, val generation: Long, val epoch: String?, val profile: String) + +/** The send being admitted: from the journal write to the owned terminal. Only one at a time per conversation. */ +internal class PendingAdmission(val entry: JournalEntry, val isCommand: Boolean, val generation: Long) { + var admitted = false + var terminalSeen = false + var turnFailed = false + var pendingTurnFailed = false + var overlapped = false + var selectedTurn: String? = null + + /** At most two candidate starts, to detect an ambiguous overlap. */ + val candidateTurns = ArrayList(2) + val settledTurns = HashMap() + + fun select() { + selectedTurn = candidateTurns.firstOrNull() + terminalSeen = selectedTurn?.let { settledTurns[it] } != null + pendingTurnFailed = selectedTurn?.let { settledTurns[it] } ?: false + } +} + +/** A confirmed admission whose local waiter ended with the socket; exact same-epoch terminal replay can settle it. */ +internal class AcceptedEvidence(val entryId: String, val turnId: String, val epoch: String) + +/** Mutable state of one conversation. Touched only on the serial dispatcher. */ +internal class ConversationRuntime(val scope: ConversationScope, var identity: ConversationIdentity, var title: String) { + val ref: ConversationRef get() = scope.ref + var phase = ConversationPhase.Opening + var binding: Binding? = null + val reducer = TurnReducer() + + var saved: HistoryWindow? = null + var savedItems: List = emptyList() + var historyToken = 0L + var loadingOlder = false + var liveBaselineRowId = -1L + var needsHistoryReseed = false + + var runtimeInfo = RuntimeInfo() + var draft = "" + var draftAttachments: List = emptyList() + val unresolved = ArrayList() + var pending: PendingAdmission? = null + var acceptedEvidence: AcceptedEvidence? = null + + var needsRecovery = false + var requiresReattach = false + var hydrating = false + var heldEvents = ArrayList() + var heldOverflow = false + var recoveryJobActive = false + var hasRecovered = false + + var status: String? = null + var stopRequested = false + var legacyPromptHost = false + var lastError: ChatError? = null + var compactingConfirmed = false + + fun isBound(generation: Long): Boolean = binding?.generation == generation +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt new file mode 100644 index 00000000..83a7afc2 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt @@ -0,0 +1,344 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.GatewayClient +import app.bighelp.hermes.GatewayConnection +import app.bighelp.hermes.HermesAuthenticator +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.ServerRequestHandler +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +/** + * The screen-facing live chat repository of one signed-in computer. + * + * **Construction.** Build it with the owner's [GatewayClient], [HermesAuthenticator] and lifetime scope when the + * computer's session object is made, *before* `gateway.connect()`. The constructor registers the server-request + * handlers (approval, clarify and the secure inputs) and starts collecting the gateway's events, so the very first + * socket's `client.capabilities` advertisement is already backed by real handlers and `gateway.ready` is seen. + * Handlers are registered again before every [reconnect]. + * + * **State.** Everything observable is a [StateFlow] of immutable values: [catalog] (agents and chats), [connection], + * [conversations] (every retained conversation with its transcript, real activity, prompts, drafts and unresolved + * sends), [prompts] (every actionable question across conversations) and [pendingCreations]. Nothing is shown that + * the host did not report. + * + * **Actions** are suspend functions returning typed results. A send is never retried by the repository: its exact + * bytes are journaled first, a lost receipt stays reviewable, and a persistence failure sends nothing. + * + * This object does not own the gateway or the authenticator: [close] stops its own work and leaves them to the owner. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class HermesChatRepository private constructor(wiring: Wiring) : AutoCloseable { + internal class Wiring( + val gateway: ChatGateway, val rest: ChatRest, val scope: CoroutineScope, val host: HostScope, val store: ChatStore, val config: ChatConfig, + ) + + constructor( + gateway: GatewayClient, + authenticator: HermesAuthenticator, + scope: CoroutineScope, + host: HostScope, + store: ChatStore, + config: ChatConfig = ChatConfig(), + ) : this(Wiring(GatewayClientAdapter(gateway), AuthenticatedRest(authenticator), scope, host, store, config)) + + internal constructor( + gateway: ChatGateway, rest: ChatRest, scope: CoroutineScope, host: HostScope, store: ChatStore, config: ChatConfig = ChatConfig(), + ) : this(Wiring(gateway, rest, scope, host, store, config)) + + private val serial: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1) + private val ctx = ChatContext(wiring.gateway, wiring.rest, wiring.store, wiring.host, wiring.config, wiring.scope, serial) + private val creations = CreationBook(ctx) + private val binder = SessionBinder(ctx, creations) + private val engine = ConversationEngine(ctx, binder) + private val catalogEngine = CatalogEngine(ctx, binder) + private val submissions = SubmissionEngine(ctx, engine) + private val promptCenter = PromptCenter(ctx, engine) + private val controls = RuntimeControls(ctx, engine) + private val operations = SessionOperations(ctx, engine, binder, catalogEngine) + private val mutableConnection = MutableStateFlow(ConnectionStatus()) + private val mutablePending = MutableStateFlow>(emptyList()) + private val jobs = ArrayList() + + init { + engine.prompts = promptCenter + engine.submissions = submissions + registerHandlers() + // Subscribe before anything can connect: UNDISPATCHED hands the collector to the serial queue right here, + // ahead of any later connect() from the same owner. A late collector would still get the retained ready. + jobs += ctx.scope.launch(start = CoroutineStart.UNDISPATCHED) { collectEvents() } + jobs += ctx.scope.launch(start = CoroutineStart.UNDISPATCHED) { collectConnection() } + jobs += ctx.scope.launch { runCatching { creations.load(); mutablePending.value = creations.pending() } } + } + + // ---- observation + + /** Agents and saved chats, merged with the hidden canonical Bot Chat; deliberately archived chats are not in `sessions`. */ + val catalog: StateFlow get() = catalogEngine.state + + val connection: StateFlow = mutableConnection.asStateFlow() + + /** Every retained conversation. A screen shows `conversations.value[ref]` and observes changes with [observe]. */ + val conversations: StateFlow> get() = engine.states + + /** Every actionable question from any retained conversation, oldest first. */ + val prompts: StateFlow> get() = promptCenter.states + + /** Unfinished creates that can be retried under their own key or dropped. */ + val pendingCreations: StateFlow> = mutablePending.asStateFlow() + + fun observe(ref: ConversationRef): Flow = conversations.map { it[ref] }.distinctUntilChanged() + + // ---- catalog + + suspend fun refreshCatalog(): CatalogState = catalogEngine.refresh() + + suspend fun archivedChats(): List = try { + catalogEngine.loadArchived() + } catch (e: HermesException) { + throw ChatException(SessionBinder.chatError(e)) + } + + suspend fun search(profile: String, query: String, limit: Int = 20): List = try { + catalogEngine.search(profile, query, limit) + } catch (e: HermesException) { + throw ChatException(SessionBinder.chatError(e)) + } + + // ---- create and open + + /** + * A new chat for [profile]. The intent is persisted before `session.create` is sent; [retryIntent] (from + * [CreateOutcome.Unconfirmed] or [pendingCreations]) retries that same logical create under the same key, while + * a call without it is an independent new chat. + */ + suspend fun createChat(profile: String, request: CreateRequest = CreateRequest(), retryIntent: String? = null): CreateOutcome { + if (!Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) return CreateOutcome.Failed(ChatError(ChatError.Kind.InvalidInput)) + val outcome = when (val step = binder.createOrdinary(profile, request, retryIntent)) { + is CreateStep.Failed -> CreateOutcome.Failed(step.error) + is CreateStep.Unconfirmed -> CreateOutcome.Unconfirmed(step.intentId, step.error) + is CreateStep.Created -> { + val ref = ConversationRef(profile, step.attached.storedId) + val title = step.record.request.title ?: "New chat" + engine.adoptCreated(ref, step.attached, title) + creations.remove(profile) + catalogEngine.add(newChatSummary(ref, step.attached.storedId, title, step.record.request.cwd)) + CreateOutcome.Created(ref) + } + } + mutablePending.value = creations.pending() + return outcome + } + + private fun newChatSummary(ref: ConversationRef, stored: String, title: String, cwd: String?) = SessionSummary( + ref, ref.profile, stored, title, "", ctx.config.clock() / 1000.0, ctx.config.clock() / 1000.0, 0, "bighelp", cwd, false, + ArchiveState.None, null, null, false, false, + ) + + /** Abandons an unfinished create the person no longer wants retried. */ + suspend fun discardCreation(profile: String) { + creations.remove(profile) + mutablePending.value = creations.pending() + } + + /** + * The agent's canonical Bot Chat, resolved by the host's registry. With no registry chat and + * [createIfMissing] false nothing is created; with it true the first Bot Chat is created, titled and read back, + * and an unfinished first creation recovers by its own intent, never by a new chat. + */ + suspend fun openBotChat(profile: String, createIfMissing: Boolean = false): BotChatOutcome { + if (!Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) return BotChatOutcome.Failed(ChatError(ChatError.Kind.InvalidInput)) + val chat = try { + binder.registry(profile) + } catch (e: HermesException) { + return BotChatOutcome.Failed(SessionBinder.chatError(e)) + } catch (e: ChatException) { + return BotChatOutcome.Failed(e.error) + } + val outcome: BotChatStep = when { + chat != null -> BotChatStep.Registered(chat) + createIfMissing -> binder.createFirstBotChat(profile) + else -> return BotChatOutcome.NotCreated + } + mutablePending.value = creations.pending() + return when (outcome) { + is BotChatStep.Failed -> BotChatOutcome.Failed(outcome.error) + is BotChatStep.Unconfirmed -> BotChatOutcome.Unconfirmed(outcome.intentId, outcome.error) + is BotChatStep.Registered -> { + val ref = ConversationRef(profile, outcome.chat.id) + engine.open(ref, CatalogDecoder.registryOnly(profile, outcome.chat)) + BotChatOutcome.Opened(ref) + } + } + } + + /** + * Opens a saved chat: loads its draft, unsent entries and identity, resumes it by its stored ID on the current + * socket, proves coverage and reads its newest history page. Safe to call again; it reattaches a suspended chat. + * Failures appear as [ConversationState.lastError]; the transcript already held stays. + */ + suspend fun open(ref: ConversationRef): ConversationState { + val hint = catalog.value.sessions.firstOrNull { it.ref == ref } + val rt = engine.open(ref, hint) + return ctx.onState { engine.snapshot(rt) } + } + + /** Stops retaining a conversation on this device (nothing on the host or in the durable store is deleted). */ + suspend fun release(ref: ConversationRef) { + ctx.onState { + engine.conversations.remove(ref)?.let { engine.historyCache.remove(ref); promptCenter.retireFor(ref) } + engine.publishAll() + } + } + + // ---- composing and sending + + /** Saves the composer text and attachment references durably. Newer edits always win over an older send's restore. */ + suspend fun updateDraft(ref: ConversationRef, text: String, attachments: List = emptyList()): DraftResult = submissions.updateDraft(ref, text, attachments) + + /** + * Sends [text]. Idle: a new turn. Running: steer (default), or [SendMode.Queue] / [SendMode.InterruptAndSend]. + * A leading `/` runs the command router; pass the [selection] the person chose from [commands] (it is checked + * against the text). The result says what Hermes did; a turn's answer arrives as events. + */ + suspend fun send( + ref: ConversationRef, + text: String, + mode: SendMode = SendMode.Default, + attachments: List = emptyList(), + selection: SlashSelection? = null, + ): SendResult = submissions.send(ref, text, mode, attachments, selection) + + /** `session.interrupt`; the turn is over only when the host reports `running:false`. */ + suspend fun stop(ref: ConversationRef): StopResult = submissions.stop(ref) + + /** Discards a retained entry, or puts its text back in an empty composer. Never sends anything. */ + suspend fun resolveUnresolved(ref: ConversationRef, entryId: String, decision: ReviewDecision): ReviewResult = submissions.review(ref, entryId, decision) + + // ---- prompts + + suspend fun answerPrompt(promptId: String, answer: PromptAnswer): PromptResult = promptCenter.answer(promptId, answer) + suspend fun declinePrompt(promptId: String): PromptResult = promptCenter.decline(promptId) + + // ---- history + + suspend fun loadOlder(ref: ConversationRef): HistoryLoad = engine.loadOlder(ref) + + suspend fun reloadHistory(ref: ConversationRef) { + val rt = ctx.onState { engine.conversations[ref] } ?: throw ChatException(ChatError.Kind.NotOpen) + try { engine.refreshNewest(rt) } catch (e: HermesException) { throw ChatException(SessionBinder.chatError(e)) } + } + + // ---- session edits + + suspend fun rename(ref: ConversationRef, title: String) = operations.rename(ref, title) + suspend fun archive(ref: ConversationRef) = operations.setArchived(ref, archived = true) + + /** Restores an archived chat and refreshes the catalog so its row returns. */ + suspend fun restore(ref: ConversationRef) { + operations.setArchived(ref, archived = false) + catalogEngine.refresh() + } + + suspend fun delete(ref: ConversationRef) = operations.delete(ref) + + /** A branch through the saved row [throughRowId]; opens and returns the new conversation. */ + suspend fun fork(ref: ConversationRef, throughRowId: Long): ConversationRef = operations.fork(ref, throughRowId) + + // ---- commands and runtime controls + + suspend fun commands(ref: ConversationRef): SlashCommandIndex = SlashCommandIndex(controls.commands(ref)) + suspend fun commandsForNewChat(profile: String, cwd: String? = null): SlashCommandIndex = SlashCommandIndex(controls.commandsForNewChat(profile, cwd)) + suspend fun modelOptions(ref: ConversationRef): ModelOptions = controls.options(ref) + suspend fun setModel(ref: ConversationRef, model: String, provider: String, confirmed: Boolean = false): ModelChange = controls.setModel(ref, model, provider, confirmed) + suspend fun setReasoning(ref: ConversationRef, level: String) = controls.setReasoning(ref, level) + suspend fun setFast(ref: ConversationRef, on: Boolean) = controls.setFast(ref, on) + suspend fun setYolo(ref: ConversationRef, on: Boolean) = controls.setYolo(ref, on) + + // ---- connection + + /** + * Reconnects the gateway (re-verifying the sign-in first). Handlers are registered again, because a connection + * that ended without automatic recovery forgets them. Nothing is resent: the new socket's `gateway.ready` + * reattaches every retained chat by its stored ID and recovers coverage. + */ + suspend fun reconnect(): ConnectionStatus { + registerHandlers() + try { + ctx.gateway.reconnect() + } catch (e: HermesException) { + publishConnection() + throw ChatException(SessionBinder.chatError(e)) + } + publishConnection() + return mutableConnection.value + } + + /** Foreground check: a silent socket is replaced at once. */ + suspend fun verifyConnection() = ctx.gateway.verifyLiveness() + + override fun close() { + jobs.forEach { it.cancel() } + promptCenter.methods.forEach { ctx.gateway.setServerRequestHandler(it, null) } + } + + // ---- internals + + private fun registerHandlers() { + for (method in promptCenter.methods) ctx.gateway.setServerRequestHandler(method, ServerRequestHandler { promptCenter.handle(it) }) + } + + private suspend fun collectEvents() { + while (ctx.scope.isActive) { + try { + ctx.gateway.events.collect { gatewayEvent -> + ctx.onState { engine.onEvent(gatewayEvent) } + if (gatewayEvent.event.type == "gateway.ready") { + val generation = gatewayEvent.generation + ctx.scope.launch { reattachWhenConnected(generation) } + } + } + return + } catch (e: HermesException) { + // The collector fell too far behind: events were lost. Close admission and reattach everything. + ctx.onState { engine.onDisconnected() } + ctx.scope.launch { reattachWhenConnected(ctx.gateway.state.value.generation) } + } + } + } + + private suspend fun reattachWhenConnected(generation: Long) { + val connected = ctx.gateway.state.first { (it.connection == GatewayConnection.Connected && it.generation == generation) || it.generation != generation } + if (connected.generation != generation) return + engine.reattachAll(generation) + } + + private suspend fun collectConnection() { + ctx.gateway.state.collect { + // Decide from the state as it is now, not as it was when this notification was queued: a late "idle" must not + // suspend a chat that a newer socket has already begun to recover. + ctx.onState { + if (ctx.gateway.state.value.connection != GatewayConnection.Connected) engine.onDisconnected() else engine.publishAll() + } + publishConnection() + } + } + + private fun publishConnection() { + val state = ctx.gateway.state.value + mutableConnection.value = ConnectionStatus(state.connection, state.generation, state.capabilities?.perSessionExclusiveSubmit, state.lastFailure?.kind) + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt new file mode 100644 index 00000000..d7f842c8 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt @@ -0,0 +1,22 @@ +package app.bighelp.hermes.chat + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** The newest retained rows of one chat, stored only to show something at once. Losing it changes nothing durable. */ +internal object HistoryCacheCodec { + fun encode(window: HistoryWindow): ByteArray = buildJsonObject { + put("v", 1); put("stored", window.storedId); put("next", window.nextOffset) + put("rows", JsonArray(window.rows.map { it.raw })) + }.toString().toByteArray(Charsets.UTF_8) + + fun decode(bytes: ByteArray): HistoryWindow { + val body = parseRecord(bytes) + if (body["v"].asInt != 1) corrupt() + val stored = body["stored"].asString ?: corrupt() + val rows = (body["rows"].asArray ?: corrupt()).map { HistoryRow.parse(it, stored) } + if (rows.map { it.id }.toSet().size != rows.size) corrupt() + return HistoryWindow(stored, rows, body["next"].asInt) + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryProjection.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryProjection.kt new file mode 100644 index 00000000..42e3f52b --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryProjection.kt @@ -0,0 +1,138 @@ +package app.bighelp.hermes.chat + +/** + * Turns physical history rows into transcript items. Rows keep the host's order (never sorted by time or + * text); a tool request and its result stay recorded evidence and are joined only when the call ID is + * unique on both sides. History alone never says a tool succeeded or failed. + */ +internal object HistoryProjection { + class Projected(val items: List, val unsupportedContentRowIds: List) + + fun itemId(rowId: Long) = "row:$rowId" + + fun project(rows: List): Projected { + val items = ArrayList(rows.size) + val unsupported = ArrayList() + + // A call ID joins to a result only when exactly one visible request and one visible result carry it. + val requestCounts = HashMap() + val resultRows = HashMap>() + for (row in rows) { + if (!row.isVisible) continue + row.toolCalls.forEach { call -> call.id?.let { requestCounts.merge(it, 1, Int::plus) } } + if (row.role == "tool" && row.toolCallId != null) resultRows.getOrPut(row.toolCallId) { ArrayList() } += row + } + val joined = HashSet() + var currentTurn: String? = null + + for (row in rows) { + if (row.role == "user" && row.isVisible && row.displayKind != "model_switch") currentTurn = "turn:${row.id}" + if (!row.isVisible) continue + if (row.hasUnsupportedContent) unsupported += row.id + val modelSwitch = row.displayKind == "model_switch" + val reasoning = row.reasoning + if (!reasoning.isNullOrEmpty()) { + items += ActivityItem( + "reasoning-row:${row.id}", ActivityKind.Reasoning, "Recorded reasoning", reasoning, ActivityLifecycle.Recorded, + turnId = currentTurn, origin = ItemOrigin.Saved, + ) + } + val role = when { + modelSwitch -> MessageRole.System + row.role == "user" -> MessageRole.User + row.role == "assistant" -> MessageRole.Assistant + else -> null + } + if (role != null) { + val text = if (row.role == "user" && !modelSwitch) UserMessageDisplay.text(row.text) else row.text + if (text.isNotEmpty() || row.hasUnsupportedContent) { + items += MessageItem( + itemId(row.id), role, row.role, text, ItemOrigin.Saved, rowId = row.id, displayKind = row.displayKind, + hasUnsupportedContent = row.hasUnsupportedContent, timestampEpochSeconds = row.timestamp, + turnDurationMillis = row.turnDurationMillis, + ) + } + } else if (row.role != "tool") { + // An unknown role stays visible as evidence; it is never shown as a human or assistant reply. + if (row.text.isNotEmpty() || row.hasUnsupportedContent) { + items += MessageItem( + itemId(row.id), MessageRole.Unknown, row.role, row.text, ItemOrigin.Saved, rowId = row.id, + displayKind = row.displayKind, hasUnsupportedContent = row.hasUnsupportedContent, + timestampEpochSeconds = row.timestamp, + ) + } + } + row.toolCalls.forEachIndexed { index, call -> + val unique = call.id != null && requestCounts[call.id] == 1 + val candidates = call.id?.let { resultRows[it] }.orEmpty() + val result = if (unique && candidates.size == 1) candidates.single() else null + if (result != null) joined += result.id + items += ActivityItem( + "tool-row:${row.id}:$index", ActivityKind.Tool, call.name ?: result?.toolName ?: "Recorded tool", null, + ActivityLifecycle.Recorded, toolCallId = call.id.takeIf { unique }, turnId = currentTurn, origin = ItemOrigin.Saved, + arguments = call.arguments, result = result?.let { HistoryRow.literalText(it.content) }, + ) + } + if (row.role == "tool" && row.id !in joined) { + // Resolved below: a result row is dropped from the list only if its call has already claimed it. + val claimed = row.toolCallId?.let { id -> requestCounts[id] == 1 && resultRows[id]?.size == 1 } == true + if (!claimed) { + items += ActivityItem( + "tool-result-row:${row.id}", ActivityKind.Tool, row.toolName ?: "Recorded tool result", null, + ActivityLifecycle.Recorded, toolCallId = row.toolCallId, turnId = currentTurn, origin = ItemOrigin.Saved, + result = HistoryRow.literalText(row.content), + ) + } + } + } + return Projected(items, unsupported) + } +} + +/** What a person sent, without the notes and hints Hermes adds to the model's copy of a user turn. */ +internal object UserMessageDisplay { + const val DEFAULT_IMAGE_CAPTION = "What do you see in this image?" + + private val MEMORY_BLOCK = Regex("<\\s*memory-context\\s*>.*?<\\s*/\\s*memory-context\\s*>", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)) + private val MEMORY_OPEN = Regex("<\\s*memory-context\\s*>", RegexOption.IGNORE_CASE) + private val MEMORY_NOTE = Regex("\\[System note:\\s*The following is recalled memory context,[^\\]]*\\]", RegexOption.IGNORE_CASE) + private val MEMORY_CLOSE = Regex("<\\s*/\\s*memory-context\\s*>", RegexOption.IGNORE_CASE) + private val IMAGE_AT = Regex("\\[Image attached at: (.+)\\]") + private val IMAGE_HINT = Regex("\\[Image attached: .+\\]") + private val BLANK_RUNS = Regex("\\n{3,}") + + fun text(raw: String): String { + if (!raw.contains("memory-context") && !raw.contains("[Image attached") && !raw.contains("[System note:")) return raw + var text = MEMORY_BLOCK.replace(raw, "") + // A truncated row can lose its closing fence; nothing after the opening fence is the person's. + MEMORY_OPEN.find(text)?.let { text = text.substring(0, it.range.first) } + text = MEMORY_CLOSE.replace(MEMORY_NOTE.replace(text, ""), "") + + val images = ArrayList() + var sawImage = false + val lines = ArrayList() + for (line in text.split("\n")) { + val trimmed = line.trim { it == ' ' || it == '\t' } + val at = IMAGE_AT.matchEntire(trimmed) + if (at != null) { + sawImage = true + reference(at.groupValues[1])?.let { images += "@image:$it" } + } else if (IMAGE_HINT.matches(trimmed)) { + sawImage = true + } else { + lines += line + } + } + if (sawImage) lines.removeAll { it.trim() == "[screenshot]" || it.trim() == "[image]" } + var body = BLANK_RUNS.replace(lines.joinToString("\n"), "\n\n").trim() + if (sawImage && body == DEFAULT_IMAGE_CAPTION) body = "" + return (listOf(body).filter { it.isNotEmpty() } + images).joinToString("\n") + } + + private fun reference(path: String): String? { + if (path.none { it.isWhitespace() || it in "[]\"'`" }) return path + val quote = listOf("\"", "'", "`").firstOrNull { it !in path } ?: return null + if (path.any { it == '\n' || it == '\r' }) return null + return quote + path + quote + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryRows.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryRows.kt new file mode 100644 index 00000000..0c567003 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryRows.kt @@ -0,0 +1,265 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.utf8Length +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 + +/** + * One physical row of the host's saved history (`GET /api/sessions/{id}/messages`). It keeps the host's raw + * object ([raw]) so a boundary check compares exactly what the host sent, and the decoded display facts. A + * row's [id] is a positive integer assigned by the host; it is not a turn ID, a position or a text hash. + */ +internal class HistoryRow private constructor( + val id: Long, + val sessionId: String, + val role: String, + val content: JsonElement, + val text: String, + val hasUnsupportedContent: Boolean, + val toolCalls: List, + val toolCallId: String?, + val toolName: String?, + val reasoning: String?, + val timestamp: Double?, + val turnDurationMillis: Int?, + val platformMessageId: String?, + val displayKind: String?, + val raw: JsonObject, +) { + class ToolCall(val id: String?, val name: String?, val arguments: String?) + + /** `hidden` and `internal_notification` rows are kept in the window but not shown. */ + val isVisible: Boolean get() = displayKind != "hidden" && displayKind != "internal_notification" + + private var canonical: String? = null + + /** Sorted-key JSON of the host's object: the byte-for-byte identity used by every boundary check. */ + fun canonicalJson(): String = canonical ?: Canonical.write(raw).also { canonical = it } + + /** The size this row counts toward the retained-read ceiling. */ + fun encodedBytes(): Int = utf8Length(canonicalJson()) + + companion object { + const val MAXIMUM_ROW_ID = 9_007_199_254_740_991L + const val MAXIMUM_TEXT_BYTES = 1_048_576 + + /** @throws app.bighelp.hermes.HermesException InvalidResponse for any row that breaks the documented shape. */ + fun parse(value: JsonElement, expectedSessionId: String): HistoryRow { + val row = value.asObject ?: throw invalidResponse() + val id = row["id"].asLong?.takeIf { it in 1..MAXIMUM_ROW_ID } ?: throw invalidResponse() + val sessionId = row["session_id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + if (sessionId != expectedSessionId) throw invalidResponse() + val role = row["role"].asString?.takeIf { Coordinates.isValid(it, 64) } ?: throw invalidResponse() + val content = row["content"] ?: JsonNull + val displayed = displayText(row["display_content"]?.takeIf { it !is JsonNull } ?: content) + val reasoningValue = listOf(row["reasoning_content"], row["reasoning"]).firstOrNull { it != null && it !is JsonNull } + val reasoning = reasoningValue?.let { (it.asString ?: throw invalidResponse()).also(::bounded) } + val toolCalls = when (val calls = row["tool_calls"]) { + null, JsonNull -> emptyList() + is JsonPrimitive -> if (calls.isString && calls.content.isEmpty()) emptyList() else throw invalidResponse() + is JsonArray -> { + if (calls.size > 128) throw invalidResponse() + calls.map { entry -> + val call = entry.asObject ?: throw invalidResponse() + val function = call["function"].asObject + ToolCall(optionalCoordinate(call["id"]), optionalCoordinate(function?.get("name"), 128), function?.get("arguments")?.let(::literalText)) + } + } + else -> throw invalidResponse() + } + return HistoryRow( + id, sessionId, role, content, displayed.first, displayed.second, toolCalls, + optionalCoordinate(row["tool_call_id"]), optionalCoordinate(row["tool_name"], 128), reasoning, + timestamp(row["timestamp"]), duration(row["turn_duration_ms"]), optionalCoordinate(row["platform_message_id"]), + optionalCoordinate(row["display_kind"], 128), row, + ) + } + + /** String verbatim; an array of `text`/`input_text`/`output_text` parts joined by newlines; any other part marks unsupported content. */ + private fun displayText(value: JsonElement): Pair = when (value) { + JsonNull -> "" to false + is JsonPrimitive -> if (value.isString) bounded(value.content) to false else "" to true + is JsonArray -> { + if (value.size > 512) throw invalidResponse() + val pieces = ArrayList() + var unsupported = false + for (part in value) { + val obj = part.asObject + val type = obj?.get("type").asString + val text = obj?.get("text").asString + if (obj == null || type !in TEXT_TYPES || text == null) unsupported = true else pieces += bounded(text) + } + bounded(pieces.joinToString("\n")) to unsupported + } + else -> "" to true + } + + fun literalText(value: JsonElement): String { + if (value is JsonPrimitive && value.isString) return bounded(value.content) + return bounded(Canonical.write(value)) + } + + private fun bounded(text: String): String { + if (utf8Length(text) > MAXIMUM_TEXT_BYTES) throw ChatException(ChatError.Kind.TooLarge) + return text + } + + private fun optionalCoordinate(value: JsonElement?, maximum: Int = 512): String? { + if (value == null || value is JsonNull || (value is JsonPrimitive && value.isString && value.content.isEmpty())) return null + return value.asString?.takeIf { Coordinates.isValid(it, maximum) } ?: throw invalidResponse() + } + + private fun timestamp(value: JsonElement?): Double? { + if (value == null || value is JsonNull) return null + val seconds = value.asDouble ?: throw invalidResponse() + if (seconds < 0 || seconds > 253_402_300_799.0) throw invalidResponse() + return seconds + } + + /** A malformed duration is ignored; it never hides the row. */ + private fun duration(value: JsonElement?): Int? = value.asLong?.takeIf { it in 0..86_400_000 }?.toInt() + + private val TEXT_TYPES = setOf("text", "input_text", "output_text") + } +} + +/** Sorted-key JSON, the same for the same host object whatever order its members arrived in. */ +internal object Canonical { + fun write(value: JsonElement): String = StringBuilder().also { append(it, value) }.toString() + + private fun append(out: StringBuilder, value: JsonElement) { + when (value) { + is JsonObject -> { + out.append('{') + value.keys.sorted().forEachIndexed { index, key -> + if (index > 0) out.append(',') + out.append(JsonPrimitive(key).toString()).append(':') + append(out, value.getValue(key)) + } + out.append('}') + } + is JsonArray -> { + out.append('[') + value.forEachIndexed { index, element -> if (index > 0) out.append(','); append(out, element) } + out.append(']') + } + else -> out.append(value.toString()) + } + } +} + +/** One decoded REST page, validated against the request that produced it. */ +internal class HistoryPage(val storedId: String, val rows: List, val returned: Int, val limit: Int) { + companion object { + /** + * The envelope must echo exactly the requested `offset`, `limit` and `order`; `returned` must equal the row + * count and rows cannot exceed the limit. A supplied `profile` must match. Duplicate row IDs mean the + * history moved under the read. + */ + fun parse(envelope: JsonElement, profile: String, offset: Int, limit: Int, order: String): HistoryPage { + val body = envelope.asObject ?: throw invalidResponse() + val storedId = body["session_id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + body["profile"]?.let { if (it.asString != profile) throw invalidResponse() } + val values = (body["messages"] ?: body["data"]).asArray ?: throw invalidResponse() + val pagination = body["pagination"].asObject ?: throw invalidResponse() + if (values.size > limit || pagination["offset"].asLong != offset.toLong() || pagination["limit"].asLong != limit.toLong() || + pagination["order"].asString != order || pagination["returned"].asLong != values.size.toLong() + ) throw invalidResponse() + val rows = values.map { HistoryRow.parse(it, storedId) } + if (rows.map { it.id }.toSet().size != rows.size) throw ChatException(ChatError.Kind.HistoryChanged) + return HistoryPage(storedId, rows, rows.size, limit) + } + } +} + +/** + * The newest rows of one saved chat that this repository holds, oldest first, and where the next older page + * starts (`nextOffset` counts rows from the newest; null once the start of the chat is reached). Every merge + * checks the overlap row byte for byte; a window that does not line up is refused, never combined. + */ +internal class HistoryWindow(val storedId: String, val rows: List, val nextOffset: Int?) { + val bytes: Long by lazy { rows.sumOf { it.encodedBytes().toLong() } } + + companion object { + const val MAXIMUM_ROWS = 50_000 + const val MAXIMUM_BYTES = 32L * 1_048_576 + const val MAXIMUM_WINDOWS = 4 + const val MAXIMUM_TOTAL_BYTES = 64L * 1_048_576 + + /** The first page for a chat with no window: all of it, with a next page when it came back full. */ + fun fresh(page: HistoryPage): HistoryWindow = + capped(HistoryWindow(page.storedId, page.rows, if (page.returned == page.limit) page.rows.size else null)) + + /** + * A newest-page refresh. When the page starts inside the held rows and its prefix lines up with the held + * tail (same IDs in order, an unchanged first row), the earlier held rows stay and the tail is replaced. + * Anything else starts a fresh window from this page alone. + */ + fun refreshed(held: HistoryWindow?, page: HistoryPage): HistoryWindow { + val kept = held?.takeIf { it.storedId == page.storedId }?.let { keptRows(it, page) } ?: return fresh(page) + val combined = kept + page.rows + val next = if (held.nextOffset == null || page.returned < page.limit) null else combined.size + return capped(HistoryWindow(page.storedId, combined, next)) + } + + /** + * An older page requested at [window].nextOffset - 1 with one overlap row. The overlap must be the held + * oldest row exactly, and the rest must not repeat any held row. + */ + fun prepended(window: HistoryWindow, page: HistoryPage): HistoryWindow { + val oldest = window.rows.firstOrNull() ?: throw ChatException(ChatError.Kind.HistoryChanged) + val anchor = page.rows.lastOrNull() + if (page.storedId != window.storedId || anchor == null || anchor.id != oldest.id || + anchor.canonicalJson() != oldest.canonicalJson() + ) throw ChatException(ChatError.Kind.HistoryChanged) + val older = page.rows.dropLast(1) + val held = window.rows.mapTo(HashSet()) { it.id } + if (older.any { it.id in held }) throw ChatException(ChatError.Kind.HistoryChanged) + val combined = older + window.rows + return capped(HistoryWindow(window.storedId, combined, if (page.returned == page.limit) combined.size else null)) + } + + private fun keptRows(held: HistoryWindow, page: HistoryPage): List? { + val first = page.rows.firstOrNull() ?: return null + val start = held.rows.indexOfFirst { it.id == first.id } + if (start < 0) return null + val tail = held.rows.subList(start, held.rows.size) + if (tail.size > page.rows.size) return null + if (tail.indices.any { tail[it].id != page.rows[it].id }) return null + if (tail[0].canonicalJson() != first.canonicalJson()) return null + val kept = held.rows.subList(0, start) + val pageIds = page.rows.mapTo(HashSet()) { it.id } + return kept.takeIf { rows -> rows.none { it.id in pageIds } }?.toList() + } + + private fun capped(window: HistoryWindow): HistoryWindow { + if (window.rows.size > MAXIMUM_ROWS || window.bytes > MAXIMUM_BYTES) throw ChatException(ChatError.Kind.TooLarge) + return window + } + } +} + +/** + * The windows this repository keeps, least recently used evicted so that at most four windows and 64 MiB are held. + * An evicted conversation reads its newest page fresh; its old paging offset is gone with it. + */ +internal class HistoryWindowCache { + private val windows = LinkedHashMap() + + operator fun get(ref: ConversationRef): HistoryWindow? = windows[ref] + + fun put(ref: ConversationRef, window: HistoryWindow) { + windows.remove(ref) + while (windows.isNotEmpty() && (windows.size >= HistoryWindow.MAXIMUM_WINDOWS || + windows.values.sumOf { it.bytes } + window.bytes > HistoryWindow.MAXIMUM_TOTAL_BYTES) + ) windows.remove(windows.keys.first()) + windows[ref] = window + } + + fun remove(ref: ConversationRef) { windows.remove(ref) } + fun clear() = windows.clear() + val size: Int get() = windows.size +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/PromptCenter.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/PromptCenter.kt new file mode 100644 index 00000000..1f63f281 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/PromptCenter.kt @@ -0,0 +1,335 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.IncomingServerRequest +import app.bighelp.hermes.ServerResponse +import app.bighelp.hermes.utf8Length +import java.security.MessageDigest +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.withContext +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 agent's questions: approvals, clarifications and the attended secure inputs. A request is actionable only + * when it names a runtime this repository holds on the very socket it arrived on; anything malformed or unbound + * is answered with an explicit error and never becomes a card. The handler suspends until a person answers or the + * host cancels (the gateway cancels it on a matching `request.cancel` by ID and method, or when the socket ends). + * + * A secure value lives only in the caller's array and in the one response built from it: it is never put in a + * transcript, draft, journal, cache, state object or log, and is cleared once used or retired. + */ +internal class PromptCenter(private val ctx: ChatContext, private val engine: ConversationEngine) { + private class Entry( + val id: String, + val ref: ConversationRef, + val wireId: String, + val method: String, + val domainRequestId: String?, + val createdAt: Long, + val content: PromptContent, + val deferred: CompletableDeferred, + var status: PromptStatus = PromptStatus.Pending, + ) { + fun state() = PromptState(id, ref, wireId, method, domainRequestId, createdAt, content, status) + } + + private val entries = LinkedHashMap() + private val mutableStates = MutableStateFlow>(emptyList()) + val states: StateFlow> = mutableStates.asStateFlow() + + fun statesFor(ref: ConversationRef): List = entries.values.filter { it.ref == ref }.map { it.state() } + + private fun publish() { + mutableStates.value = entries.values.sortedWith(compareBy({ it.createdAt }, { it.id })).map { it.state() } + engine.conversations.values.forEach { engine.publish(it) } + } + + /** The methods this client can really fulfil. Everything else is refused by the gateway with `-32601`. */ + val methods = listOf("approval", "clarify", "secret", "sudo", "vault.code", "vault.save_login", "vault.unlock_prompt") + + suspend fun handle(request: IncomingServerRequest): ServerResponse { + val decoded = try { + Decoder.decode(request.method, request.params) + } catch (_: PromptInvalid) { + return invalid + } + val entry = ctx.onState { + val rt = engine.byRuntime(decoded.runtimeId, request.generation) ?: return@onState null + if (request.generation != ctx.gateway.state.value.generation || entries.size >= MAXIMUM_OPEN) return@onState null + val id = promptId(request.generation, request.method, request.id) + if (entries.containsKey(id)) return@onState null + Entry(id, rt.ref, request.id, request.method, decoded.domainRequestId, ctx.config.clock(), decoded.content, CompletableDeferred()) + .also { entries[id] = it; publish() } + } ?: return invalid + try { + return entry.deferred.await() + } finally { + withContext(NonCancellable + ctx.serial) { if (entries.remove(entry.id) != null) publish() } + } + } + + /** The conversation's socket ended or its runtime was reclaimed: its prompts are no longer actionable. */ + fun retireFor(ref: ConversationRef) { + val retired = entries.values.filter { it.ref == ref } + if (retired.isEmpty()) return + for (entry in retired) { entries.remove(entry.id); entry.deferred.complete(retiredResponse) } + publish() + } + + suspend fun answer(promptId: String, answer: PromptAnswer): PromptResult { + val outcome = ctx.onState> { + val entry = entries[promptId] + if (entry == null || entry.status != PromptStatus.Pending) return@onState Triple(null, null, PromptResult.NoLongerActive) + val response = try { Responder.respond(entry.content, answer) } catch (e: PromptInvalid) { return@onState Triple(null, null, PromptResult.Invalid(e.reason)) } + entry.status = PromptStatus.Answering + entries.remove(entry.id) + publish() + Triple(entry, response, PromptResult.Answered) + } + val (entry, response, result) = outcome + if (entry != null && response != null) entry.deferred.complete(response) + // Whatever the outcome, a secure value held by the caller is retired: it is never offered a second time. + if (result !is PromptResult.Invalid) clear(answer) + return result + } + + suspend fun decline(promptId: String): PromptResult { + val entry = ctx.onState { entries[promptId]?.takeIf { it.status == PromptStatus.Pending }?.also { entries.remove(it.id); publish() } } + ?: return PromptResult.NoLongerActive + entry.deferred.complete(Responder.decline(entry.content)) + return PromptResult.Answered + } + + private fun clear(answer: PromptAnswer) { + when (answer) { + is PromptAnswer.Secure -> answer.value.fill('\u0000') + is PromptAnswer.SaveLogin -> answer.password.fill('\u0000') + else -> Unit + } + } + + private fun promptId(generation: Long, method: String, wireId: String): String { + val digest = MessageDigest.getInstance("SHA-256").digest("$generation\u0000$method\u0000$wireId".toByteArray(Charsets.UTF_8)) + return "prompt-" + digest.take(12).joinToString("") { "%02x".format(it) } + } + + // ---- decoding + + internal class PromptInvalid(val reason: String) : Exception(reason) + private class Decoded(val runtimeId: String, val domainRequestId: String?, val content: PromptContent) + + private object Decoder { + fun decode(method: String, p: JsonObject): Decoded { + val runtime = p["session_id"].asString?.takeIf { it.isNotEmpty() && utf8Length(it) <= 4_096 } ?: throw PromptInvalid("session") + return when (method) { + "approval" -> approval(runtime, p) + "clarify" -> clarify(runtime, p) + else -> secure(method, runtime, p) + } + } + + private fun approval(runtime: String, p: JsonObject): Decoded { + val requestId = p["request_id"].asString?.takeIf { it.isNotEmpty() && utf8Length(it) <= 4_096 } ?: throw PromptInvalid("request") + val offered = p["choices"].asArray?.takeIf { it.isNotEmpty() && it.size <= 16 } ?: throw PromptInvalid("choices") + // An unknown or repeated choice from a newer host is skipped, not fatal. + val choices = LinkedHashSet() + offered.forEach { v -> v.asString?.let(ApprovalChoice::fromWire)?.let(choices::add) } + if (choices.isEmpty()) throw PromptInvalid("choices") + fun optional(key: String, max: Int): String? = p[key]?.let { v -> v.asString?.takeIf { utf8Length(it) <= max && '\u0000' !in it } ?: throw PromptInvalid(key) } + val command = optional("command", 65_536) + val description = optional("description", 65_536) + val tool = optional("tool_name", 4_096) + optional("gateway_session_id", 4_096) + for (key in listOf("allow_permanent", "allow_session", "smart_denied")) p[key]?.let { if (it.asBool == null) throw PromptInvalid(key) } + return Decoded(runtime, requestId, PromptContent.Approval(command, description, tool, choices.toList())) + } + + private fun clarify(runtime: String, p: JsonObject): Decoded { + fun present(key: String) = p[key].let { it != null && it !is JsonNull } + val single = present("question") + if (single == present("questions")) throw PromptInvalid("shape") + if (single) { + if (present("answers")) throw PromptInvalid("answers") + val question = p["question"].asString?.takeIf(::validQuestion) ?: throw PromptInvalid("question") + val choices = choices(p["choices"]) + val multi = multi(p["multi_select"]) + if (multi && choices.isEmpty()) throw PromptInvalid("multi") + return Decoded(runtime, null, PromptContent.Clarification(listOf(ClarifyQuestion(SINGLE, question, choices, multi, null)), isBatch = false)) + } + val rows = p["questions"].asArray?.takeIf { it.isNotEmpty() && it.size <= 10 } ?: throw PromptInvalid("questions") + val locked = locked(p["answers"]) + val ids = HashSet() + val questions = rows.map { row -> + val o = row.asObject ?: throw PromptInvalid("question") + val qid = o["qid"].asString?.takeIf { it.isNotEmpty() && utf8Length(it) <= 4_096 } ?: throw PromptInvalid("qid") + if (!ids.add(qid)) throw PromptInvalid("qid") + val question = o["question"].asString?.takeIf(::validQuestion) ?: throw PromptInvalid("question") + val choices = choices(o["choices"]) + val multi = multi(o["multi_select"]) + if (multi && choices.isEmpty()) throw PromptInvalid("multi") + ClarifyQuestion(qid, question, choices, multi, locked[qid]) + } + if (!ids.containsAll(locked.keys)) throw PromptInvalid("answers") + return Decoded(runtime, null, PromptContent.Clarification(questions, isBatch = true)) + } + + private fun choices(value: JsonElement?): List { + if (value == null || value is JsonNull) return emptyList() + val rows = value.asArray?.takeIf { it.size <= 12 } ?: throw PromptInvalid("choices") + val seen = HashSet() + return rows.map { c -> + val s = c.asString?.takeIf { it.isNotEmpty() && utf8Length(it) <= 10_000 && '\u0000' !in it } ?: throw PromptInvalid("choice") + if (!seen.add(s)) throw PromptInvalid("choice") + s + } + } + + private fun multi(value: JsonElement?): Boolean = if (value == null || value is JsonNull) false else value.asBool ?: throw PromptInvalid("multi") + + private fun locked(value: JsonElement?): Map { + if (value == null) return emptyMap() + val o = value.asObject?.takeIf { it.size <= 5 } ?: throw PromptInvalid("answers") + return o.entries.associate { (key, v) -> + if (key.isEmpty() || utf8Length(key) > 4_096) throw PromptInvalid("answers") + key to (v.asString?.takeIf(::validAnswer) ?: throw PromptInvalid("answers")) + } + } + + private fun secure(method: String, runtime: String, p: JsonObject): Decoded { + if (!identifier(runtime, 4_096)) throw PromptInvalid("session") + val keys = p.keys + val content = when (method) { + "secret" -> { + if (!setOf("session_id", "env_var", "prompt", "metadata").containsAll(keys)) throw PromptInvalid("keys") + val env = p["env_var"].asString?.takeIf { identifier(it, 4_096) } ?: throw PromptInvalid("env") + val prompt = p["prompt"].asString?.takeIf { utf8Length(it) <= 65_536 && '\u0000' !in it } ?: throw PromptInvalid("prompt") + val meta = p["metadata"]?.let { if (it is JsonNull) null else it.asObject ?: throw PromptInvalid("metadata") } + val label = meta?.get("label").asString?.trim()?.takeIf { it.isNotEmpty() && utf8Length(it) <= 120 } + PromptContent.SecureInput(SecureKind.Secret, env, prompt, label, null, null, meta?.get("source").asString == "agent") + } + "sudo" -> { + if (keys != setOf("session_id")) throw PromptInvalid("keys") + PromptContent.SecureInput(SecureKind.Sudo, null, null, null, null, null, false) + } + "vault.code" -> { + if (!setOf("session_id", "site", "hint").containsAll(keys)) throw PromptInvalid("keys") + val site = label(p["site"], 255) ?: throw PromptInvalid("site") + val hint = label(p["hint"], 500) ?: throw PromptInvalid("hint") + PromptContent.SecureInput(SecureKind.VaultCode, null, hint.ifEmpty { null }, null, site.ifEmpty { null }, null, false) + } + "vault.save_login" -> { + if (keys != setOf("session_id", "origin", "site")) throw PromptInvalid("keys") + val origin = p["origin"].asString?.takeIf(::validOrigin) ?: throw PromptInvalid("origin") + label(p["site"], 255) ?: throw PromptInvalid("site") + // The origin, not the agent's label: people recognise addresses. + PromptContent.SecureInput(SecureKind.VaultSaveLogin, null, null, null, origin, null, false) + } + "vault.unlock_prompt" -> { + if (keys != setOf("session_id", "backend", "display_name")) throw PromptInvalid("keys") + val backend = p["backend"].asString?.takeIf { identifier(it, 64) } ?: throw PromptInvalid("backend") + val name = label(p["display_name"], 120) ?: throw PromptInvalid("display_name") + PromptContent.SecureInput(SecureKind.VaultUnlock, null, null, null, null, name.ifEmpty { backend }, false) + } + else -> throw PromptInvalid("method") + } + return Decoded(runtime, null, content) + } + + private fun identifier(value: String, max: Int) = value.isNotEmpty() && utf8Length(value) <= max && value.none { it.code < 0x20 || it.code == 0x7f } + + /** A missing or null label is empty; a present one is bounded single-line text. */ + private fun label(value: JsonElement?, max: Int): String? { + if (value == null || value is JsonNull) return "" + val text = value.asString?.trim() ?: return null + return text.takeIf { utf8Length(it) <= max && it.none { c -> c.code < 0x20 || c.code == 0x7f } } + } + + private fun validOrigin(value: String): Boolean { + if (utf8Length(value) > 2_048 || value.any { it.code < 0x21 || it.code == 0x7f }) return false + val uri = runCatching { java.net.URI(value) }.getOrNull() ?: return false + return uri.scheme?.lowercase() in setOf("http", "https") && !uri.host.isNullOrEmpty() && uri.userInfo == null + } + } + + // ---- responding + + private object Responder { + fun respond(content: PromptContent, answer: PromptAnswer): ServerResponse = when (content) { + is PromptContent.Approval -> { + val choice = (answer as? PromptAnswer.Approve)?.choice ?: throw PromptInvalid("answer") + if (choice !in content.choices) throw PromptInvalid("choice") + ServerResponse.Result(buildJsonObject { put("choice", choice.wire); put("all", false) }) + } + is PromptContent.Clarification -> { + val answers = (answer as? PromptAnswer.Clarify)?.answers ?: throw PromptInvalid("answer") + val resolved = LinkedHashMap() + for (q in content.questions) { + val locked = q.lockedAnswer + val given = locked ?: answers[q.id] ?: throw PromptInvalid("missing") + resolved[q.id] = if (locked != null) locked else validatedAnswer(given, q) + } + if (answers.keys.any { key -> content.questions.none { it.id == key } }) throw PromptInvalid("unknown") + ServerResponse.Result( + if (content.isBatch) buildJsonObject { put("answers", JsonObject(resolved.mapValues { JsonPrimitive(it.value) })) } + else buildJsonObject { put("answer", resolved.getValue(SINGLE)) }, + ) + } + is PromptContent.SecureInput -> when (content.kind) { + SecureKind.VaultSaveLogin -> { + val login = answer as? PromptAnswer.SaveLogin ?: throw PromptInvalid("answer") + val identifier = login.identifier.trim() + val password = String(login.password) + if (identifier.isEmpty() || utf8Length(identifier) > 512 || password.isEmpty() || utf8Length(password) > 4_096 || '\u0000' in password) throw PromptInvalid("login") + ServerResponse.Result(buildJsonObject { put("value", buildJsonObject { put("identifier", identifier); put("password", password) }.toString()) }) + } + else -> { + val secure = answer as? PromptAnswer.Secure ?: throw PromptInvalid("answer") + var value = String(secure.value) + if (content.kind == SecureKind.VaultCode) { + value = value.filter { !it.isWhitespace() && it != '-' } + if (value.isEmpty() || value.length > 64 || !value.all { it.code < 128 && it.isLetterOrDigit() }) throw PromptInvalid("code") + } else if (value.isEmpty() || utf8Length(value) > 65_536 || '\u0000' in value) throw PromptInvalid("value") + ServerResponse.Result(buildJsonObject { put("value", value) }) + } + } + } + + /** Cancel: deny, nothing, or an empty value. Never a blank chat message. */ + fun decline(content: PromptContent): ServerResponse = ServerResponse.Result( + when (content) { + is PromptContent.Approval -> buildJsonObject { put("choice", "deny"); put("all", false) } + is PromptContent.Clarification -> JsonObject(emptyMap()) + is PromptContent.SecureInput -> buildJsonObject { put("value", "") } + }, + ) + + /** A multi-select answer is a string holding JSON array text; typed "Other" text is accepted as the whole answer. */ + fun validatedAnswer(answer: String, q: ClarifyQuestion): String { + if (!validAnswer(answer)) throw PromptInvalid("answer") + if (!q.multiSelect) return answer + val selected = runCatching { app.bighelp.hermes.StrictJson.parse(answer) }.getOrNull()?.asArray ?: return answer + val values = selected.map { it.asString?.takeIf(::validAnswer) ?: throw PromptInvalid("answer") } + if (values.isEmpty() || values.size > q.choices.size + 1 || values.toSet().size != values.size) throw PromptInvalid("answer") + val customs = values.count { it !in q.choices } + if (customs > 1) throw PromptInvalid("answer") + return kotlinx.serialization.json.JsonArray(values.map { JsonPrimitive(it) }).toString() + } + } + + companion object { + const val SINGLE = "\$single" + const val MAXIMUM_OPEN = 64 + private val invalid = ServerResponse.Failure(-32602, "Invalid prompt parameters") + private val retiredResponse = ServerResponse.Failure(-32000, "Prompt is no longer active") + private fun validQuestion(value: String) = value.isNotEmpty() && utf8Length(value) <= 65_536 && '\u0000' !in value + private fun validAnswer(value: String) = value.isNotEmpty() && utf8Length(value) <= 10_000 && '\u0000' !in value + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt new file mode 100644 index 00000000..09e6666b --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt @@ -0,0 +1,206 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.RequestCancelledException +import app.bighelp.hermes.utf8Length +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * Model, reasoning, speed and approval-skipping for one live session. Every change is session-scoped (it names the + * runtime, `--session` or `scope:"session"`), so it can never rewrite the agent's profile defaults, and every + * result is read back from the runtime before it is reported as changed. + */ +internal class RuntimeControls(private val ctx: ChatContext, private val engine: ConversationEngine) { + private class Proof(val model: String, val provider: String, val reasoning: String, val tier: String?, val running: Boolean) + + private suspend fun live(ref: ConversationRef): Pair = ctx.onState { + val rt = engine.conversations[ref] ?: throw ChatException(ChatError.Kind.NotOpen) + val binding = rt.binding + if (binding == null || rt.requiresReattach || binding.generation != ctx.gateway.state.value.generation) throw ChatException(ChatError.Kind.NoLiveSession) + rt to binding + } + + private fun stale(rt: ConversationRuntime, binding: Binding) { + if (engine.conversations[rt.ref] !== rt || rt.binding != binding || ctx.gateway.state.value.generation != binding.generation) throw ChatException(ChatError.Kind.NotConnected) + } + + private suspend fun mapErrors(block: suspend () -> T): T = try { + block() + } catch (e: HermesException) { + throw ChatException(if (e.outcomeUnknown) ChatError(ChatError.Kind.OutcomeUnknown, e.kind, e.code, e.reason) else SessionBinder.chatError(e)) + } catch (e: RequestCancelledException) { + throw ChatException(ChatError.Kind.OutcomeUnknown) + } + + /** The live runtime's own model, provider and reasoning, read through activation (which never builds or creates a runtime). */ + private suspend fun proof(rt: ConversationRuntime, binding: Binding): Proof { + val response = ctx.gateway.request("session.activate", buildJsonObject { + put("session_id", binding.runtimeId); put("profile", binding.profile); put("omit_messages", true) + }).asObject ?: throw invalidResponse() + val info = response["info"].asObject + val stored = response["session_key"].asString + if (response["session_id"].asString != binding.runtimeId || stored == null || !rt.identity.knows(stored) || + response["messages_omitted"].asBool != true || response["messages"].asArray?.isEmpty() != true || + response["running"].asBool == null || info == null || info["profile_name"].asString != binding.profile || + info["stored_session_id"].asString != stored + ) throw ChatException(ChatError.Kind.Unsupported) + val model = info["model"].asString?.takeIf { Coordinates.isValid(it, 256) } ?: throw ChatException(ChatError.Kind.Unsupported) + // A chat whose agent is not built yet (lazy) reports its model but may omit provider and reasoning. + val built = info["lazy"] == null || info["lazy"].asBool == false + val provider = info["provider"].asString ?: if (built) throw ChatException(ChatError.Kind.Unsupported) else "" + val reasoning = info["reasoning_effort"].asString ?: if (built) throw ChatException(ChatError.Kind.Unsupported) else "" + if (reasoning.isNotEmpty() && reasoning !in REASONING) throw invalidResponse() + return Proof(model, provider, reasoning, info["service_tier"].asString, response["running"].asBool == true) + } + + // ---- reading + + suspend fun options(ref: ConversationRef): ModelOptions = mapErrors { + val (rt, binding) = live(ref) + val current = proof(rt, binding) + val catalog = ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }) + ctx.onState { stale(rt, binding) } + ModelOptions(current.model, current.provider.ifEmpty { null }, current.reasoning, current.tier, current.running, decodeProviders(catalog)) + } + + private fun decodeProviders(response: JsonElement): List { + val rows = response.asObject?.get("providers").asArray ?: throw invalidResponse() + val seen = HashSet() + return rows.mapNotNull { value -> + val row = value.asObject ?: return@mapNotNull null + val id = row["slug"].asString?.takeIf { Coordinates.isValid(it, 128) && seen.add(it) } ?: return@mapNotNull null + val modelSeen = HashSet() + val models = (row["models"].asArray ?: JsonArray(emptyList())).mapNotNull { it.asString?.takeIf { m -> Coordinates.isValid(m, 256) && modelSeen.add(m) } } + val unavailable = (row["unavailable_models"].asArray ?: JsonArray(emptyList())).mapNotNull { it.asString }.toSet() + val capabilities = row["capabilities"].asObject + ModelProvider( + id, row["name"].asString?.takeIf { it.isNotEmpty() && utf8Length(it) <= 800 } ?: id, row["is_current"].asBool ?: false, + row["is_user_defined"].asBool ?: false, models.filter { it !in unavailable }, + capabilities?.let { c -> models.filter { c[it].asObject?.get("fast").asBool == true }.toSet() }, + ) + } + } + + // ---- changing + + suspend fun setModel(ref: ConversationRef, model: String, provider: String, confirmed: Boolean): ModelChange = mapErrors { + if (!Coordinates.isValid(model, 256) || !Coordinates.isValid(provider, 128)) throw ChatException(ChatError.Kind.InvalidInput) + val (rt, binding) = live(ref) + val before = proof(rt, binding) + ctx.onState { stale(rt, binding) } + if (before.model == model && before.provider == provider) return@mapErrors ModelChange.Confirmed(model, provider) + val response = ctx.gateway.request("config.set", buildJsonObject { + put("profile", binding.profile); put("session_id", binding.runtimeId) + put("key", "model"); put("value", "$model --provider $provider --session") + if (confirmed) put("confirm_expensive_model", true) + }).asObject ?: throw invalidResponse() + ctx.onState { stale(rt, binding) } + val needsConfirmation = response["confirm_required"].asBool + if (response["key"].asString != "model" || response["scope"].asString != "session" || needsConfirmation == null || response?.get("value").asString == null) throw invalidResponse() + if (needsConfirmation) { + val message = response["confirm_message"].asString?.takeIf { !confirmed && it.isNotBlank() && utf8Length(it) <= 2_000 } ?: throw invalidResponse() + return@mapErrors ModelChange.NeedsConfirmation(message) + } + response["deferred"]?.let { deferred -> + if (deferred.asBool == null) throw invalidResponse() + if (deferred.asBool == true) { + return@mapErrors ModelChange.Deferred("Hermes queued this model for the next turn. The current model has not been confirmed changed; reopen the picker to check.") + } + } + // A model switch must not change how hard the session thinks: put the previous level back and read it back. + if (before.reasoning.isNotEmpty()) writeReasoning(binding, before.reasoning, rt) + val after = proof(rt, binding) + ctx.onState { stale(rt, binding) } + if (after.model != model || (after.provider != provider && !catalogMarksCurrent(binding, provider, model))) throw ChatException(ChatError.Kind.ModelNotConfirmed) + ctx.onState { rt.runtimeInfo = rt.runtimeInfo.merged(RuntimeInfo(model = after.model, provider = after.provider.ifEmpty { null }, reasoningEffort = after.reasoning, serviceTier = after.tier)); engine.publish(rt) } + ModelChange.Confirmed(after.model, after.provider.ifEmpty { null }) + } + + /** A catalog can list a provider under an alias slug while the runtime reports its canonical ID; a fresh read must mark the chosen slug current. */ + private suspend fun catalogMarksCurrent(binding: Binding, provider: String, model: String): Boolean { + val response = ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }) + if (response.asObject?.get("model").asString != model) return false + val current = decodeProviders(response).filter { it.isCurrent } + return current.size == 1 && current[0].id == provider + } + + suspend fun setReasoning(ref: ConversationRef, level: String): Unit = mapErrors { + if (level !in REASONING) throw ChatException(ChatError.Kind.InvalidInput) + val (rt, binding) = live(ref) + // Reattach the exact runtime right before config.set: a missing session would target the profile defaults. + proof(rt, binding) + ctx.onState { stale(rt, binding) } + writeReasoning(binding, level, rt) + ctx.onState { rt.runtimeInfo = rt.runtimeInfo.merged(RuntimeInfo(reasoningEffort = level)); engine.publish(rt) } + } + + private suspend fun writeReasoning(binding: Binding, level: String, rt: ConversationRuntime) { + val set = ctx.gateway.request("config.set", buildJsonObject { + put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "reasoning"); put("value", level); put("scope", "session") + }).asObject + ctx.onState { stale(rt, binding) } + if (set?.get("key").asString != "reasoning" || set?.get("value").asString != level) throw ChatException(ChatError.Kind.OutcomeUnknown) + val read = ctx.gateway.request("config.get", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "reasoning") }).asObject + ctx.onState { stale(rt, binding) } + if (read?.get("value").asString != level) throw ChatException(ChatError.Kind.OutcomeUnknown) + } + + /** Fast mode: only on an idle runtime, and only when the host's catalog says the current model supports it. */ + suspend fun setFast(ref: ConversationRef, on: Boolean): Unit = mapErrors { + val (rt, binding) = live(ref) + val before = proof(rt, binding) + if (before.running) throw ChatException(ChatError.Kind.Conflict) + val catalog = decodeProviders(ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) })) + val supported = catalog.firstOrNull { it.id == before.provider }?.fastModels?.contains(before.model) == true + if (!supported) throw ChatException(ChatError.Kind.Unsupported) + ctx.onState { stale(rt, binding) } + val value = if (on) "fast" else "normal" + val set = ctx.gateway.request("config.set", buildJsonObject { + put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "fast"); put("value", value); put("scope", "session") + }).asObject + if (set?.get("key").asString != "fast" || tierIsFast(set?.get("value").asString) != on) throw ChatException(ChatError.Kind.OutcomeUnknown) + val read = ctx.gateway.request("config.get", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "fast") }).asObject + ctx.onState { stale(rt, binding) } + if (tierIsFast(read?.get("value").asString) != on) throw ChatException(ChatError.Kind.OutcomeUnknown) + ctx.onState { rt.runtimeInfo = rt.runtimeInfo.merged(RuntimeInfo(serviceTier = value)); engine.publish(rt) } + } + + private fun tierIsFast(raw: String?): Boolean? = when (raw?.lowercase()) { + "fast", "on", "priority" -> true + null, "", "normal", "off" -> false + else -> null + } + + /** Session-scoped YOLO. The host answers `"1"`/`"0"`, which is the confirmation; there is no separate read. */ + suspend fun setYolo(ref: ConversationRef, on: Boolean): Unit = mapErrors { + val (rt, binding) = live(ref) + val response = ctx.gateway.request("config.set", buildJsonObject { + put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "yolo"); put("value", if (on) "on" else "off"); put("scope", "session") + }).asObject + ctx.onState { stale(rt, binding) } + if (response?.get("key").asString != "yolo" || response?.get("value").asString != (if (on) "1" else "0")) throw ChatException(ChatError.Kind.OutcomeUnknown) + } + + // ---- commands + + suspend fun commands(ref: ConversationRef): List = mapErrors { + val (_, binding) = live(ref) + SlashCommandCatalog.decode(ctx.gateway.request("commands.catalog", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile) })) + } + + /** The commands a new chat would have, before it exists (Code mode's `/` list). Bound to the profile, and to a folder for project-local skills. */ + suspend fun commandsForNewChat(profile: String, cwd: String?): List = mapErrors { + if (!Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) throw ChatException(ChatError.Kind.InvalidInput) + SlashCommandCatalog.decode(ctx.gateway.request("commands.catalog", buildJsonObject { + put("profile", profile); if (!cwd.isNullOrEmpty() && utf8Length(cwd) <= 4_096) put("cwd", cwd) + })) + } + + companion object { + val REASONING = setOf("none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra") + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt new file mode 100644 index 00000000..41a77b0e --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt @@ -0,0 +1,340 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.RequestCancelledException +import app.bighelp.hermes.DispatchOutcome +import java.util.UUID +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** The coordinates a create or resume answer proved, ready to become a [Binding]. */ +internal class Attached(val runtimeId: String, val storedId: String, val running: Boolean?, val info: JsonObject, val model: String?, val cwd: String?) + +/** + * The create intents of this computer, one per profile, written before `session.create` leaves and updated as + * coordinates arrive. A finished or definitely-refused intent is deleted; an intent whose outcome is unknown stays + * so the same logical create can be retried under the same key, also after a restart. + */ +internal class CreationBook(private val ctx: ChatContext) { + private val records: MutableMap = java.util.Collections.synchronizedMap(LinkedHashMap()) + private val inFlight: MutableSet = java.util.concurrent.ConcurrentHashMap.newKeySet() + + suspend fun load() { + val keys = ctx.store.keys(ctx.host, RecordKind.Creation) + val loaded = keys.mapNotNull { key -> + val bytes = ctx.store.read(key) ?: return@mapNotNull null + runCatching { CreationRecord.decode(ctx.host, key.profile!!, bytes) }.getOrNull() + } + loaded.forEach { records[it.profile] = it } + } + + fun pending(): List = + records.values.toList().filter { !it.isFinished }.map { PendingCreation(it.profile, it.intentId, it.purpose, it.phase, it.request) } + + fun record(profile: String): CreationRecord? = records[profile] + + /** Claims the profile for one create at a time. */ + fun begin(profile: String): Boolean = inFlight.add(profile) + fun end(profile: String) { inFlight.remove(profile) } + + /** Persists first, then remembers: a failed write leaves the book as it was and nothing may be dispatched. */ + suspend fun save(record: CreationRecord) { + ctx.store.commit(listOf(StoreOp.Put(RecordKey.creation(ctx.host, record.profile), record.encode()))) + records[record.profile] = record + } + + suspend fun remove(profile: String) { + runCatching { ctx.store.commit(listOf(StoreOp.Delete(RecordKey.creation(ctx.host, profile)))) } + records.remove(profile) + } +} + +/** Create, resume and the Bot Chat registry: every call that makes a conversation reachable. */ +internal class SessionBinder(private val ctx: ChatContext, val creations: CreationBook) { + /** Resolved by `profiles.list`; kept so a refresh cannot lose the registry's Bot Chat. */ + val canonical: MutableMap = java.util.concurrent.ConcurrentHashMap() + private val titleTaken: MutableSet = java.util.concurrent.ConcurrentHashMap.newKeySet() + + // ---- resume + + /** `session.resume` of a stored ID (never the runtime ID), with the app's source. A rejected optional field is retried once without it. */ + suspend fun resume(profile: String, storedId: String): Attached { + val base = buildJsonObject { + put("session_id", storedId); put("profile", profile); put("source", SOURCE) + put("defer_history", true); put("omit_messages", true) + } + val withLifetime = JsonObject(base + ("close_on_disconnect" to kotlinx.serialization.json.JsonPrimitive(false))) + val result = try { + ctx.gateway.request("session.resume", withLifetime) + } catch (e: HermesException) { + // An older host refuses a field it does not know before doing anything; the plain resume is the same request. + if (e.kind == HermesException.Kind.RpcRejected && e.code == 4000L) ctx.gateway.request("session.resume", base) else throw e + } + return decodeAttached(result, profile, requireStoredAlias = false) + } + + /** `session.activate` of an already proved runtime: attaches and touches it, never builds or creates one. */ + suspend fun activate(profile: String, runtimeId: String): JsonObject { + val result = ctx.gateway.request("session.activate", buildJsonObject { + put("session_id", runtimeId); put("profile", profile); put("omit_messages", true) + }) + return result.asObject ?: throw invalidResponse() + } + + // ---- ordinary create + + /** + * One `session.create`. The intent is persisted first; a retry of the same logical create passes its [retryIntent] + * and sends the same key. An outcome that cannot be told keeps the intent; a definite refusal drops it. + */ + suspend fun createOrdinary(profile: String, request: CreateRequest, retryIntent: String?): CreateStep { + if (!creations.begin(profile)) return CreateStep.Failed(ChatError(ChatError.Kind.CreationInProgress)) + try { + reconcileCanonicalBeforeOrdinary(profile) + val previous = creations.record(profile) + val reused = previous?.takeIf { it.purpose == CreationPurpose.Ordinary && !it.isFinished && it.intentId == retryIntent } + val record = reused ?: CreationRecord( + ctx.host, ctx.config.random().lowercase(), profile, CreationPurpose.Ordinary, CreationPhase.CreateRequested, request, + socketGeneration = ctx.gateway.state.value.generation, createdAtMillis = ctx.config.clock(), + ) + try { + creations.save(record) + } catch (e: ChatStoreException) { + return CreateStep.Failed(ChatError(ChatError.Kind.PersistenceFailed)) + } + return dispatchCreate(record) + } finally { + creations.end(profile) + } + } + + /** Sends the create under [record]'s key and proves what came back. */ + private suspend fun dispatchCreate(record: CreationRecord): CreateStep { + var sendExplicitCwd = record.request.cwd != null + var answer: JsonElement? = null + while (answer == null) { + try { + answer = ctx.gateway.request("session.create", createParams(record, sendExplicitCwd)) + } catch (e: HermesException) { + // Only an explicit rejection of cwd_explicit authorizes a retry without it: a timeout or lost reply does not. + if (sendExplicitCwd && e.kind == HermesException.Kind.RpcRejected && e.code == 4000L) { sendExplicitCwd = false; continue } + return afterFailedCreate(record, e.outcomeUnknown, chatError(e)) + } catch (e: RequestCancelledException) { + return afterFailedCreate(record, e.dispatch == DispatchOutcome.MayHaveBeenSent, ChatError(ChatError.Kind.Cancelled)) + } + } + val attached = try { + decodeAttached(answer, record.profile, requireStoredAlias = true, requireEmpty = true) + } catch (e: HermesException) { + // The host answered something unusable: whether it created a chat is unknown. Keep the intent. + return CreateStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.InvalidResponse)) + } + record.request.model?.let { chosen -> + if (attached.model != chosen) { + creations.remove(record.profile) + return CreateStep.Failed(ChatError(ChatError.Kind.ModelNotConfirmed)) + } + } + record.request.cwd?.let { requested -> + if (attached.cwd?.let { sameFolder(it, requested) } != true) { + creations.remove(record.profile) + return CreateStep.Failed(ChatError(ChatError.Kind.WorkspaceNotConfirmed)) + } + } + val created = record.copy(phase = CreationPhase.Created, storedSessionId = attached.storedId, runtimeSessionId = attached.runtimeId) + try { + creations.save(created) + } catch (e: ChatStoreException) { + // The chat exists but its coordinates cannot be kept: no further mutation. The intent stays at its old phase, so a retry returns it. + return CreateStep.Failed(ChatError(ChatError.Kind.PersistenceFailed)) + } + return CreateStep.Created(created, attached) + } + + private suspend fun afterFailedCreate(record: CreationRecord, unknown: Boolean, error: ChatError): CreateStep { + if (unknown) return CreateStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.CreationUnconfirmed, error.cause, error.code, error.reason)) + // Definitely not created: nothing to retry under this key. + creations.remove(record.profile) + return CreateStep.Failed(error) + } + + private fun createParams(record: CreationRecord, explicitCwd: Boolean): JsonObject = buildJsonObject { + put("profile", record.profile); put("source", SOURCE) + // One key per logical create: a retry after a lost reply gets the same session while the host still has it. + put("idempotency_key", record.intentId.lowercase()) + val r = record.request + r.title?.let { put("title", it) } + r.model?.let { put("model", it); r.provider?.let { p -> put("provider", p) } } + r.reasoningEffort?.let { put("reasoning_effort", it) } + r.fast?.let { put("fast", it) } + if (record.purpose == CreationPurpose.FirstCanonical) { + put("title", "Bot Chat"); put("hidden", true); put("follow_profile_config", true) + } + r.cwd?.let { put("cwd", it); if (explicitCwd) put("cwd_explicit", true) } + } + + // ---- registry and the first Bot Chat + + /** A canonical chat is resolved by the registry, never by whichever chat was last active. */ + suspend fun registry(profile: String): CanonicalChat? { + val rows = CatalogDecoder.profiles(ctx.gateway.request("profiles.list", buildJsonObject { put("include_sessions", true) })) + rows.forEach { row -> row.canonicalChat?.let { canonical[row.id] = it } } + return rows.firstOrNull { it.id == profile }?.canonicalChat + } + + /** + * An unfinished first Bot Chat that reached its title or registry steps is settled by the registry before an + * ordinary create: the registry has the chat, or the title never landed. Either way a new chat is safe, so + * one lost reply never locks an agent out of every independent chat. + */ + private suspend fun reconcileCanonicalBeforeOrdinary(profile: String) { + val pending = creations.record(profile) ?: return + if (pending.purpose != CreationPurpose.FirstCanonical || pending.isFinished) return + if (pending.phase != CreationPhase.TitleRequested && pending.phase != CreationPhase.AwaitingRegistry) return + val found = runCatching { registry(profile) }.getOrNull() + runCatching { + creations.save( + if (found != null) pending.copy(phase = CreationPhase.CanonicalResolved, canonicalRegistryId = found.id) + else pending.copy(phase = CreationPhase.Complete), + ) + } + } + + /** + * Creates the agent's first canonical Bot Chat after an explicit decision: hidden, titled `Bot Chat`, read back + * from the registry. A conflict winner is adopted from the registry. Returns the registry chat to open. + */ + suspend fun createFirstBotChat(profile: String): BotChatStep { + if (profile in titleTaken) return BotChatStep.Failed(ChatError(ChatError.Kind.Rejected, HermesException.Kind.RpcRejected, 4022)) + if (!creations.begin(profile)) return BotChatStep.Failed(ChatError(ChatError.Kind.CreationInProgress)) + try { + registry(profile)?.let { found -> + creations.record(profile)?.takeIf { it.purpose == CreationPurpose.FirstCanonical && !it.isFinished }?.let { runCatching { creations.save(it.copy(phase = CreationPhase.CanonicalResolved, canonicalRegistryId = found.id)) } } + return BotChatStep.Registered(found) + } + var record = creations.record(profile)?.takeIf { it.purpose == CreationPurpose.FirstCanonical && !it.isFinished } + var attached: Attached? = null + when { + // The reply was lost before any coordinate: create again under the same key. The host returns the same + // session while it still has it, else makes a fresh one. Never a permanent refusal. + record != null && record.storedSessionId == null -> when (val step = dispatchCreate(record)) { + is CreateStep.Created -> { record = step.record; attached = step.attached } + is CreateStep.Unconfirmed -> return BotChatStep.Unconfirmed(step.intentId, step.error) + is CreateStep.Failed -> return BotChatStep.Failed(step.error) + } + // The host made its session: resume it and finish from there. + record != null -> attached = try { resume(profile, record.storedSessionId!!) } catch (e: HermesException) { return BotChatStep.Failed(chatError(e)) } + else -> { + val fresh = CreationRecord( + ctx.host, ctx.config.random().lowercase(), profile, CreationPurpose.FirstCanonical, CreationPhase.CreateRequested, + CreateRequest(), socketGeneration = ctx.gateway.state.value.generation, createdAtMillis = ctx.config.clock(), + ) + try { creations.save(fresh) } catch (e: ChatStoreException) { return BotChatStep.Failed(ChatError(ChatError.Kind.PersistenceFailed)) } + when (val step = dispatchCreate(fresh)) { + is CreateStep.Created -> { record = step.record; attached = step.attached } + is CreateStep.Unconfirmed -> return BotChatStep.Unconfirmed(step.intentId, step.error) + is CreateStep.Failed -> return BotChatStep.Failed(step.error) + } + } + } + val titling = record!!.copy(phase = CreationPhase.TitleRequested, storedSessionId = attached!!.storedId, runtimeSessionId = attached.runtimeId) + try { creations.save(titling) } catch (e: ChatStoreException) { return BotChatStep.Failed(ChatError(ChatError.Kind.PersistenceFailed)) } + try { + val reply = ctx.gateway.request("session.title", buildJsonObject { put("session_id", attached.runtimeId); put("title", "Bot Chat") }).asObject + if (reply?.get("pending").asBool != false || reply?.get("title").asString != "Bot Chat") { + return BotChatStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.CreationUnconfirmed)) + } + } catch (e: HermesException) { + if (e.kind == HermesException.Kind.RpcRejected && e.code == 4022L) return titleConflict(profile, attached, titling) + return BotChatStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.CreationUnconfirmed, e.kind, e.code, e.reason)) + } + try { creations.save(titling.copy(phase = CreationPhase.AwaitingRegistry)) } catch (e: ChatStoreException) { return BotChatStep.Failed(ChatError(ChatError.Kind.PersistenceFailed)) } + val registered = registry(profile) ?: return BotChatStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.CreationUnconfirmed)) + creations.remove(profile) + return BotChatStep.Registered(registered) + } catch (e: HermesException) { + return BotChatStep.Failed(chatError(e)) + } finally { + creations.end(profile) + } + } + + /** 4022: another chat holds the title. The registry's winner is adopted; our empty chat is dropped. */ + private suspend fun titleConflict(profile: String, mine: Attached, record: CreationRecord): BotChatStep { + val winner = registry(profile) + runCatching { ctx.gateway.request("session.delete", buildJsonObject { put("session_id", mine.storedId); put("profile", profile) }) } + if (winner != null) { + creations.remove(profile) + return BotChatStep.Registered(winner) + } + // A chat the list does not show holds the title, so this agent has no Bot Chat here. Settle the attempt. + titleTaken += profile + creations.remove(profile) + return BotChatStep.Failed(ChatError(ChatError.Kind.Rejected, HermesException.Kind.RpcRejected, 4022)) + } + + // ---- decoding + + /** The identity needed to bind: a runtime ID, one agreeing stored alias, a profile echo, a Boolean `running`. */ + fun decodeAttached(result: JsonElement, profile: String, requireStoredAlias: Boolean, requireEmpty: Boolean = false): Attached { + val body = result.asObject ?: throw invalidResponse() + val runtime = body["session_id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + val info = body["info"].asObject ?: throw invalidResponse() + info["profile_name"]?.let { if (it.asString != profile) throw invalidResponse() } + val aliases = listOf("session_key", "stored_session_id", "resumed").mapNotNull { key -> + body[key]?.let { it.asString ?: throw invalidResponse() } + } + val stored = aliases.firstOrNull()?.takeIf { it.isNotEmpty() && utf8(it) <= 512 && Coordinates.isValid(it) } ?: throw invalidResponse() + if (aliases.any { it != stored }) throw invalidResponse() + info["stored_session_id"]?.let { if (it.asString != stored) throw invalidResponse() } + if (requireStoredAlias && body["stored_session_id"].asString != stored) throw invalidResponse() + val running = body["running"]?.let { it.asBool ?: throw invalidResponse() } + if (requireEmpty && (body["message_count"].asInt != 0 || body["messages"].asArray?.isEmpty() != true)) throw invalidResponse() + val model = info["model"].asString?.takeIf { info["lazy"].asBool != true || it.isNotEmpty() } + return Attached(runtime, stored, running, info, model, info["cwd"].asString) + } + + private fun utf8(text: String) = app.bighelp.hermes.utf8Length(text) + + companion object { + const val SOURCE = "bighelp" + + /** Windows hosts answer `D:\x` for `D:/x` and ignore case; POSIX folders match byte for byte. */ + fun sameFolder(a: String, b: String): Boolean { + if (a == b) return true + fun windows(folder: String): String? = + if (folder.startsWith("\\\\") || Regex("^[A-Za-z]:[\\\\/].*").matches(folder)) folder.replace('/', '\\').lowercase() else null + val left = windows(a) ?: return false + return left == windows(b) + } + + fun chatError(e: HermesException): ChatError { + val kind = when { + e.code == -32601L -> ChatError.Kind.Unsupported + e.kind == HermesException.Kind.NotConnected || e.kind == HermesException.Kind.Disconnected -> ChatError.Kind.NotConnected + e.outcomeUnknown -> ChatError.Kind.OutcomeUnknown + e.kind == HermesException.Kind.RpcRejected || e.kind == HermesException.Kind.ActiveSessionLimit -> ChatError.Kind.Rejected + e.kind == HermesException.Kind.InvalidResponse -> ChatError.Kind.InvalidResponse + e.kind == HermesException.Kind.MessageTooLarge -> ChatError.Kind.TooLarge + e.kind == HermesException.Kind.InvalidCredentials || e.kind == HermesException.Kind.AuthenticationRequired || + e.kind == HermesException.Kind.AuthModeChanged || e.kind == HermesException.Kind.IdentityChanged -> ChatError.Kind.SignInRequired + else -> ChatError.Kind.HostUnavailable + } + return ChatError(kind, e.kind, e.code, e.reason) + } + } +} + +internal sealed interface CreateStep { + class Created(val record: CreationRecord, val attached: Attached) : CreateStep + class Unconfirmed(val intentId: String, val error: ChatError) : CreateStep + class Failed(val error: ChatError) : CreateStep +} + +internal sealed interface BotChatStep { + class Registered(val chat: CanonicalChat) : BotChatStep + class Unconfirmed(val intentId: String, val error: ChatError) : BotChatStep + class Failed(val error: ChatError) : BotChatStep +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt new file mode 100644 index 00000000..e9171b7d --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt @@ -0,0 +1,199 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.RequestCancelledException +import app.bighelp.hermes.utf8Length +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * Everyday session edits: rename, archive, restore, delete and fork. Each goes through the socket's own methods on + * the identifiers the host expects (the registry or lineage root, not whichever tip is current), and each result is + * checked against what the host answered or read back, so a quiet no-op is never reported as done. + */ +internal class SessionOperations( + private val ctx: ChatContext, + private val engine: ConversationEngine, + private val binder: SessionBinder, + private val catalog: CatalogEngine, +) { + private suspend fun mapErrors(block: suspend () -> T): T = try { + block() + } catch (e: HermesException) { + throw ChatException(if (e.outcomeUnknown) ChatError(ChatError.Kind.OutcomeUnknown, e.kind, e.code, e.reason) else SessionBinder.chatError(e)) + } catch (e: RequestCancelledException) { + throw ChatException(ChatError.Kind.OutcomeUnknown) + } + + /** The conversation, attached to a live runtime on this socket (resuming it if needed). */ + private suspend fun attached(ref: ConversationRef): Pair { + val rt = engine.open(ref, hint = null) + return ctx.onState { + val binding = rt.binding + if (binding == null || rt.requiresReattach || binding.generation != ctx.gateway.state.value.generation) throw ChatException(rt.lastError ?: ChatError(ChatError.Kind.NoLiveSession)) + rt to binding + } + } + + // ---- rename + + suspend fun rename(ref: ConversationRef, title: String): Unit = mapErrors { + val trimmed = title.trim() + if (trimmed.isEmpty() || utf8Length(trimmed) > 240 || trimmed.any { Character.isISOControl(it) }) throw ChatException(ChatError.Kind.InvalidInput) + val (rt, binding) = attached(ref) + val registry = ctx.onState { rt.identity.canonicalRegistryId ?: binder.canonical[ref.profile]?.id?.takeIf { it == ref.anchor } } + if (registry != null) { + // Hermes refuses to rename a hidden "Bot Chat" (hidden is what makes it the agent's): release it first. + val released = ctx.gateway.request("session.set_hidden", buildJsonObject { put("session_id", registry); put("profile", ref.profile); put("hidden", false) }).asObject + if (released?.get("hidden").asBool != false || released?.get("session_key").asString.isNullOrEmpty()) throw ChatException(ChatError.Kind.InvalidResponse) + binder.canonical.remove(ref.profile) + } + val reply = ctx.gateway.request("session.title", buildJsonObject { put("session_id", binding.runtimeId); put("title", trimmed) }).asObject + ctx.onState { if (rt.binding != binding) throw ChatException(ChatError.Kind.NotConnected) } + if (reply?.get("pending").asBool != false || reply?.get("title").asString != trimmed) throw ChatException(ChatError.Kind.OutcomeUnknown) + ctx.onState { rt.title = trimmed; engine.publish(rt) } + catalog.update(ref) { SessionSummary(it.ref, it.profile, it.storedId, trimmed, it.preview, it.startedAtEpochSeconds, it.lastActiveEpochSeconds, it.messageCount, it.source, it.cwd, it.pinned, it.archive, it.lineageRootId, it.lineageIds, false, it.isRegistryOnly) } + } + + // ---- archive and restore + + /** Archives or restores [ref]; the host's own flag is read back. Restoring needs a catalog refresh to bring the row back. */ + suspend fun setArchived(ref: ConversationRef, archived: Boolean): Unit = mapErrors { + val identity = ctx.onState { engine.conversations[ref]?.identity } + val target = identity?.canonicalRegistryId ?: identity?.lineageRootId ?: ref.anchor + val reply = ctx.gateway.request("session.archive", buildJsonObject { put("session_id", target); put("profile", ref.profile); put("archived", archived) }).asObject + if (reply?.get("archived").asBool != archived || reply?.get("session_key").asString.isNullOrEmpty()) throw ChatException(ChatError.Kind.InvalidResponse) + val detail = ctx.rest.get("/api/sessions/$target", listOf("profile" to ref.profile)) + val session = detail.asObject?.let { it["session"].asObject ?: it } ?: throw invalidResponse() + if (CatalogDecoder.archiveState(session) != ArchiveState.None == !archived) throw ChatException(ChatError.Kind.Conflict) + if (archived) catalog.update(ref) { null } + } + + // ---- delete + + suspend fun delete(ref: ConversationRef): Unit = mapErrors { + val rowId = findRow(ref) ?: throw ChatException(ChatError.Kind.Conflict) + try { + val reply = ctx.gateway.request("session.delete", buildJsonObject { put("session_id", rowId); put("profile", ref.profile) }).asObject + if (reply?.get("deleted").asString != rowId) throw ChatException(ChatError.Kind.InvalidResponse) + } catch (e: HermesException) { + // A row that is already gone counts as deleted. + if (!(e.kind == HermesException.Kind.RpcRejected && e.code == 4007L)) throw e + } + forget(ref) + catalog.update(ref) { null } + } + + /** The host's own row for [ref]: the list row whose ID, lineage root or lineage names the anchor. */ + private suspend fun findRow(ref: ConversationRef): String? { + val canonical = binder.canonical[ref.profile] + var offset = 0 + while (offset <= CatalogDecoder.MAXIMUM_SESSIONS) { + val page = CatalogDecoder.sessionPage(ctx.rest.get("/api/sessions", CatalogDecoder.listQuery(ref.profile, offset)), ref.profile, offset) + for (row in page.rows) { + val summary = runCatching { CatalogDecoder.summary(row, ref.profile, canonical) }.getOrNull() ?: continue + if (summary.ref == ref || summary.storedId == ref.anchor || summary.lineageRootId == ref.anchor || summary.lineageIds?.contains(ref.anchor) == true) return summary.storedId + } + if (page.rows.isEmpty() || !CatalogDecoder.hasMore(page, offset, page.rows.size)) return null + offset += page.limit + } + return null + } + + /** A deleted chat takes its unsent text, uncertain sends and caches with it. */ + private suspend fun forget(ref: ConversationRef) { + val scope = ctx.conversationScope(ref) + val ops = ArrayList() + ops += StoreOp.Delete(RecordKey.draft(scope)); ops += StoreOp.Delete(RecordKey.identity(scope)) + ctx.store.keys(ctx.host, RecordKind.Journal, ref.profile, ref.anchor).forEach { ops += StoreOp.Delete(it) } + runCatching { ctx.store.commit(ops) } + ctx.store.deleteCache(RecordKey.history(scope)) + ctx.onState { + engine.conversations.remove(ref)?.let { engine.historyCache.remove(ref); engine.prompts.retireFor(ref) } + engine.publishAll() + } + } + + // ---- fork + + /** A branch of [ref] through the saved row [throughRowId]: the host counts visible messages, so the whole transcript is read first. */ + suspend fun fork(ref: ConversationRef, throughRowId: Long): ConversationRef = mapErrors { + val (rt, binding) = attached(ref) + val rows = hydrateAll(rt) + val checkpoint = rows.indexOfFirst { it.id == throughRowId } + if (checkpoint < 0) throw ChatException(ChatError.Kind.InvalidInput) + // Messages exactly as the host counts them: visible user, assistant and model-switch rows with text. + val messages = rows.take(checkpoint + 1).mapNotNull { row -> + if (!row.isVisible) return@mapNotNull null + val role = when { + row.displayKind == "model_switch" || row.role == "assistant" -> "assistant" + row.role == "user" -> "user" + else -> return@mapNotNull null + } + val text = if (row.role == "user" && row.displayKind != "model_switch") UserMessageDisplay.text(row.text) else row.text + if (text.isBlank()) null else Triple(row.id, role, text) + } + if (messages.isEmpty() || messages.last().first != throughRowId || messages.none { it.second == "user" } || messages.size > 50_000) throw ChatException(ChatError.Kind.InvalidInput) + val parentStored = ctx.onState { rt.identity.storedTip } + val title = forkTitle(rt.title) + val reply = ctx.gateway.request("session.branch", buildJsonObject { put("session_id", binding.runtimeId); put("count", messages.size); put("name", title) }).asObject + ?: throw invalidResponse() + val childRuntime = reply["session_id"].asString ?: throw invalidResponse() + val childStored = reply["stored_session_id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() + val info = reply["info"].asObject ?: throw invalidResponse() + val returned = reply["messages"].asArray ?: throw invalidResponse() + if (childRuntime == binding.runtimeId || childStored == parentStored || reply["title"].asString != title || reply["parent"].asString != parentStored || + reply["message_count"].asInt != messages.size || returned.size != messages.size || + info["profile_name"].asString != ref.profile || info["running"].asBool == null + ) throw invalidResponse() + returned.forEachIndexed { index, value -> + val m = value.asObject ?: throw invalidResponse() + val (_, role, text) = messages[index] + // The child's rows carry the child's own new row IDs (a real host numbers them afresh), so only role and text are compared. + if (m["role"].asString != role || m["text"].asString != text) throw invalidResponse() + } + val child = ConversationRef(ref.profile, childStored) + engine.open(child, hint = null) + child + } + + private fun forkTitle(source: String): String { + val suffix = " · Fork" + return source.take(maxOf(1, 240 - suffix.length)) + suffix + } + + /** The whole saved transcript, oldest first: 200 rows, then 201 with the previous last row repeated and checked byte for byte. */ + suspend fun hydrateAll(rt: ConversationRuntime): List { + val stored = ctx.onState { rt.identity.storedTip } + val profile = rt.scope.profile + val rows = ArrayList() + val seen = HashSet() + var bytes = 0L + var first = true + while (true) { + val offset = if (first) 0 else rows.size - 1 + val limit = if (first) 200 else 201 + val envelope: JsonElement = ctx.rest.get("/api/sessions/$stored/messages", listOf("profile" to profile, "limit" to limit.toString(), "offset" to offset.toString(), "order" to "oldest", "include_compacted" to "true")) + val page = HistoryPage.parse(envelope, profile, offset, limit, "oldest") + if (page.storedId != stored) throw ChatException(ChatError.Kind.HistoryChanged) + if (!first) { + val anchor = rows.last() + val repeated = page.rows.firstOrNull() + if (repeated == null || repeated.id != anchor.id || repeated.canonicalJson() != anchor.canonicalJson()) throw ChatException(ChatError.Kind.HistoryChanged) + } + val added = if (first) page.rows else page.rows.drop(1) + for (row in added) { + if (!seen.add(row.id)) throw ChatException(ChatError.Kind.HistoryChanged) + bytes += row.encodedBytes() + if (rows.size >= HistoryWindow.MAXIMUM_ROWS || bytes > HistoryWindow.MAXIMUM_BYTES) throw ChatException(ChatError.Kind.TooLarge) + rows += row + } + if (page.returned < page.limit) break + if (added.isEmpty()) throw ChatException(ChatError.Kind.HistoryChanged) + first = false + } + return rows + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SlashCommands.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SlashCommands.kt new file mode 100644 index 00000000..3ac57a88 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SlashCommands.kt @@ -0,0 +1,139 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.utf8Length +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject + +enum class CommandSource { Core, Plugin, Skill, User } + +enum class ArgumentMode { None, Text, Options, Mixed } + +/** One command from the host's `commands.catalog`. Its invocation identity is spelled exactly as the host named it. */ +data class SlashCommand( + val name: String, + val description: String, + val category: String, + val aliases: List, + val argumentMode: ArgumentMode, + val source: CommandSource, +) + +/** A catalog command chosen for a typed message: which command, how it was invoked, and the rest of the text. */ +data class SlashSelection(val command: SlashCommand, val invocation: String, val arguments: String) + +/** The commands of one session or draft, and the strict mapping from typed text to a selection. */ +class SlashCommandIndex(commands: List) { + val commands: List = commands.distinctBy { it.name } + + /** + * The command a draft names: a leading `/`, then a first token equal (case-insensitively) to a command name or + * alias. Text after the first whitespace is the argument. Null when the token names nothing in this catalog. + */ + fun selection(text: String): SlashSelection? { + if (!text.startsWith("/")) return null + val body = text.substring(1) + val end = body.indexOfFirst { it.isWhitespace() }.let { if (it < 0) body.length else it } + val token = body.substring(0, end).lowercase() + if (token.isEmpty()) return null + val command = commands.firstOrNull { it.name.lowercase() == token || it.aliases.any { alias -> alias.lowercase() == token } } ?: return null + return SlashSelection(command, "/$token", body.substring(end).trimStart { it.isWhitespace() }) + } + + /** Commands to suggest while a draft is just a `/word` with no whitespace; none once it names a command. */ + fun suggestions(draft: String): List { + if (!draft.startsWith("/") || draft.drop(1).any { it.isWhitespace() }) return emptyList() + if (selection(draft) != null) return emptyList() + val query = draft.drop(1).lowercase() + if (query.isEmpty()) return commands + return commands.filter { c -> c.name.lowercase().contains(query) || c.aliases.any { it.lowercase().contains(query) } || c.description.lowercase().contains(query) } + } +} + +internal object SlashCommandCatalog { + const val MAXIMUM_PAIRS = 2_048 + const val MAXIMUM_DESCRIPTION = 240 + + /** Skips an individual entry the app cannot show; the rest of the menu still loads. */ + fun decode(result: JsonElement): List { + val body = result.asObject ?: throw invalidResponse() + val pairs = body["pairs"].asArray ?: throw invalidResponse() + if (pairs.size > MAXIMUM_PAIRS) throw invalidResponse() + val categories = categoryByKey(body["categories"].asArray) + val canonical = body["canon"].asObject ?: JsonObject(emptyMap()) + val metadata = body["commands"].asObject ?: JsonObject(emptyMap()) + val skills = body["skills"].asObject ?: JsonObject(emptyMap()) + return pairs.mapNotNull { pair -> + val values = pair.asArray?.takeIf { it.size == 2 } ?: return@mapNotNull null + val rawKey = values[0].asString ?: return@mapNotNull null + val rawDescription = values[1].asString ?: return@mapNotNull null + val name = commandName(rawKey) ?: return@mapNotNull null + val isSkill = containsKey(skills, rawKey) + val source = if (isSkill) CommandSource.Skill else when (categories[rawKey.lowercase()]?.lowercase()) { + "plugin commands" -> CommandSource.Plugin + "user commands" -> CommandSource.User + else -> CommandSource.Core + } + SlashCommand( + name = name, description = displayDescription(rawDescription), + category = categories[rawKey.lowercase()] ?: if (source == CommandSource.Skill) "Skills" else "Commands", + aliases = aliases(rawKey, canonical), + argumentMode = metadataValue(metadata, rawKey)?.get("argument_mode").asString.let { mode -> ArgumentMode.entries.firstOrNull { it.name.lowercase() == mode } } ?: ArgumentMode.None, + source = source, + ) + } + } + + /** Control characters become spaces and the text is trimmed to the composer's limit. */ + fun displayDescription(raw: String): String { + val flat = raw.map { if (Character.getType(it) == Character.CONTROL.toInt()) ' ' else it }.joinToString("").trim { it == ' ' || it == '\t' } + if (flat.isEmpty()) return "Command" + if (flat.length <= MAXIMUM_DESCRIPTION) return flat + return flat.take(MAXIMUM_DESCRIPTION - 1).trim { it == ' ' || it == '\t' } + "…" + } + + private fun commandName(rawKey: String): String? { + if (!rawKey.startsWith("/")) return null + val name = rawKey.substring(1) + if (name.isEmpty() || utf8Length(name) > 96) return null + return name.takeIf { it.all { c -> Character.isLetterOrDigit(c) || c == '-' || c == '_' || c == '.' } } + } + + private fun aliases(rawKey: String, canonical: JsonObject): List { + val result = ArrayList() + for ((aliasKey, value) in canonical) { + if (aliasKey.lowercase() == rawKey.lowercase() || value.asString?.lowercase() != rawKey.lowercase()) continue + val alias = commandName(aliasKey) ?: continue + if (alias !in result) result += alias + } + return result.sorted().take(32) + } + + private fun containsKey(obj: JsonObject, key: String) = + obj.keys.any { it.lowercase() == key.lowercase() || it.lowercase() == key.drop(1).lowercase() } + + private fun metadataValue(obj: JsonObject, key: String): JsonObject? = + obj.entries.firstOrNull { it.key.lowercase() == key.lowercase() || it.key.lowercase() == key.drop(1).lowercase() }?.value.asObject + + private fun categoryByKey(values: JsonArray?): Map { + val result = HashMap() + for (value in values.orEmpty()) { + val obj = value.asObject ?: continue + val category = obj["name"].asString?.takeIf { it.length in 1..80 && it.none { c -> Character.isISOControl(c) } } ?: continue + for (pair in obj["pairs"].asArray.orEmpty()) { + val fields = pair.asArray?.takeIf { it.size == 2 } ?: continue + val key = fields[0].asString?.takeIf { it.startsWith("/") } ?: continue + result[key.lowercase()] = category + } + } + return result + } + + /** Splits typed text the way Hermes' `slash.exec` does: the name after the slashes (lowercased), then the rest. */ + fun typedDispatch(message: String): Pair { + val command = message.trim().trimStart('/') + val name = command.takeWhile { !it.isWhitespace() } + val arg = command.drop(name.length).trimStart { it.isWhitespace() } + return name.lowercase() to arg + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt new file mode 100644 index 00000000..eb921322 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt @@ -0,0 +1,513 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.DispatchOutcome +import app.bighelp.hermes.HermesException +import app.bighelp.hermes.RequestCancelledException +import app.bighelp.hermes.utf8Length +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * Admission of a person's message. The rules, in the order they bind: + * 1. The exact outgoing bytes are journaled, atomically, before anything is written to the socket. A failed write + * sends nothing. + * 2. A `streaming`/`ok` receipt proves admission only; the send stays pending until its own turn's terminal. + * `queued`/`steered` receipts hand ownership to Hermes. Neither claims the agent consumed anything. + * 3. A lost, timed-out, cancelled or malformed receipt keeps the entry, never resends, and is reviewable. The same + * text in saved history is not proof. + * 4. A definite refusal keeps or restores the text; a newer draft is never overwritten by an older send. + */ +internal class SubmissionEngine(private val ctx: ChatContext, private val engine: ConversationEngine) { + private enum class Effective { NewTurn, Steer, Queue, InterruptAndSend } + + private class Plan( + val rt: ConversationRuntime, + val effective: Effective, + val entry: JournalEntry, + val binding: Binding, + val pending: PendingAdmission?, + val isCommand: Boolean, + val selection: SlashSelection?, + val clearsDraft: Boolean, + var dispatched: Boolean = false, + var currentMethod: String = entry.method, + ) + + private sealed interface Planned { + class Go(val plan: Plan) : Planned + class Stop(val result: SendResult) : Planned + } + + private sealed interface Outcome { + class Admitted(val admission: Admission, val retire: Boolean) : Outcome + class Refused(val code: Int?, val keepEntry: Boolean, val reachedLimit: Boolean, val error: ChatError) : Outcome + class Uncertain(val error: ChatError) : Outcome + class NotSent(val error: ChatError) : Outcome + } + + // ---- send + + suspend fun send(ref: ConversationRef, text: String, mode: SendMode, attachments: List, selection: SlashSelection?): SendResult { + if (text.isBlank()) return notSent(ChatError.Kind.InvalidInput) + if (utf8Length(text) > ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES) return notSent(ChatError.Kind.TooLarge) + if (attachments.size > ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCES) return notSent(ChatError.Kind.TooLarge) + val plan = when (val planned = ctx.onState { plan(ref, text, mode, attachments, selection) }) { + is Planned.Stop -> return planned.result + is Planned.Go -> planned.plan + } + val rt = plan.rt + try { + ctx.gateway.prepareForAdmission() + } catch (e: HermesException) { + release(plan) + return SendResult.NotSent(SessionBinder.chatError(e)) + } catch (e: CancellationException) { + withContext(NonCancellable) { release(plan) } + throw e + } + val stillOwner = ctx.onState { + engine.conversations[plan.rt.ref] === rt && rt.binding == plan.binding && rt.binding?.generation == ctx.gateway.state.value.generation && + !rt.hydrating && !rt.needsRecovery && (plan.pending == null || rt.pending === plan.pending) + } + if (!stillOwner) { + release(plan) + return SendResult.NotSent(ChatError(ChatError.Kind.NotConnected)) + } + + // Journal first. A write failure, also an oversize record, sends nothing. + try { + val ops = ArrayList() + ops += StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), plan.entry.encode()) + if (plan.clearsDraft) ops += engine.draftOp(rt.scope, "", emptyList()) + engine.commit(ops) + } catch (e: ChatStoreException) { + release(plan) + return SendResult.NotSent(ChatError(if (e.kind == ChatStoreException.Kind.TooLarge) ChatError.Kind.TooLarge else ChatError.Kind.PersistenceFailed)) + } catch (e: CancellationException) { + withContext(NonCancellable) { release(plan) } + throw e + } + ctx.onState { + rt.unresolved += plan.entry + if (plan.clearsDraft) { rt.draft = ""; rt.draftAttachments = emptyList() } + rt.reducer.addLocalUser(plan.entry.id, text) + engine.publish(rt) + } + + val outcome = try { + dispatch(plan, text) + } catch (e: CancellationException) { + val sent = (e as? RequestCancelledException)?.dispatch == DispatchOutcome.MayHaveBeenSent || (e !is RequestCancelledException && plan.dispatched) + withContext(NonCancellable) { settle(plan, if (sent) Outcome.Uncertain(ChatError(ChatError.Kind.Cancelled)) else Outcome.NotSent(ChatError(ChatError.Kind.Cancelled))) } + throw e + } + settle(plan, outcome) + return when (outcome) { + is Outcome.Admitted -> SendResult.Admitted(plan.entry.id, outcome.admission) + is Outcome.Refused -> SendResult.Refused(plan.entry.id, outcome.code, outcome.reachedLimit, outcome.error) + is Outcome.Uncertain -> SendResult.Uncertain(plan.entry.id, outcome.error) + is Outcome.NotSent -> SendResult.NotSent(outcome.error) + }.also { + if (outcome is Outcome.Uncertain) ctx.scope.launch { recoverAfterLoss(plan) } + } + } + + private fun notSent(kind: ChatError.Kind) = SendResult.NotSent(ChatError(kind)) + + private fun plan(ref: ConversationRef, text: String, mode: SendMode, attachments: List, selection: SlashSelection?): Planned { + val rt = engine.conversations[ref] ?: return Planned.Stop(notSent(ChatError.Kind.NotOpen)) + val running = rt.reducer.running + val effective = when (mode) { + SendMode.Default -> if (running) Effective.Steer else Effective.NewTurn + SendMode.Steer -> if (running) Effective.Steer else return Planned.Stop(notSent(ChatError.Kind.NoActiveTurn)) + SendMode.Queue -> Effective.Queue + SendMode.InterruptAndSend -> Effective.InterruptAndSend + } + if (attachments.isNotEmpty() && effective != Effective.NewTurn && effective != Effective.Queue) return Planned.Stop(notSent(ChatError.Kind.InvalidInput)) + val isCommand = effective == Effective.NewTurn && text.startsWith("/") + if (selection != null && (!isCommand || SlashCommandIndex(listOf(selection.command)).selection(text) != selection)) { + // A chosen command is checked against the current text: an edited message never runs a stale selection. + return Planned.Stop(notSent(ChatError.Kind.InvalidInput)) + } + engine.sendBlock(rt)?.let { block -> + return Planned.Stop(SendResult.NotSent(ChatError(if (block == SendBlock.NoLiveSession || block == SendBlock.NotConnected) ChatError.Kind.NotConnected else ChatError.Kind.Conflict), block)) + } + val binding = rt.binding ?: return Planned.Stop(notSent(ChatError.Kind.NoLiveSession)) + val method = when { + effective == Effective.InterruptAndSend -> "session.interrupt" + effective == Effective.Steer -> "session.steer" + isCommand -> if (selection != null && selection.command.source != CommandSource.Core) "command.dispatch" else "slash.exec" + else -> "prompt.submit" + } + val entry = JournalEntry(ctx.config.random().lowercase(), rt.scope, method, text, text, attachments, ctx.config.clock()) + // The whole frame must fit before anything is journaled; an unsendable message is never recorded as uncertain. + if (utf8Length(buildParams(binding, text, effective, isCommand, selection, method).toString()) > ChatStoreLimits.MAXIMUM_ENCODED_MESSAGE_BYTES + 16_384) { + return Planned.Stop(notSent(ChatError.Kind.TooLarge)) + } + val pending = if (effective == Effective.NewTurn) PendingAdmission(entry, isCommand, binding.generation).also { rt.pending = it } else null + return Planned.Go(Plan(rt, effective, entry, binding, pending, isCommand, selection, clearsDraft = rt.draft == text)) + } + + /** Frees the reserved slot when nothing was journaled or sent. */ + private suspend fun release(plan: Plan) = ctx.onState { + if (plan.rt.pending === plan.pending && plan.pending != null) plan.rt.pending = null + engine.publish(plan.rt) + } + + private fun buildParams(binding: Binding, text: String, effective: Effective, isCommand: Boolean, selection: SlashSelection?, method: String): JsonObject = buildJsonObject { + put("session_id", binding.runtimeId); put("profile", binding.profile) + when { + effective == Effective.InterruptAndSend -> Unit + effective == Effective.Steer -> put("text", text) + isCommand && method == "command.dispatch" -> { + put("name", selection!!.command.name); put("arg", selection.arguments) + } + isCommand -> put("command", text) + else -> { put("text", text); put("queued", true) } + } + } + + // ---- dispatch + + private suspend fun dispatch(plan: Plan, text: String): Outcome { + val rt = plan.rt + try { + return when (plan.effective) { + Effective.Steer -> { + val receipt = call(plan, "session.steer", buildParams(plan.binding, text, Effective.Steer, false, null, "session.steer")) + when (receipt.status()) { + "queued" -> Outcome.Admitted(Admission.Steered, retire = true) + // A definite refusal: Hermes did not take the correction. The text stays the person's. + "rejected" -> Outcome.Refused(null, keepEntry = false, reachedLimit = false, error = ChatError(ChatError.Kind.Rejected)) + else -> Outcome.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) + } + } + Effective.Queue -> queueSubmit(plan, text, plan.entry) + Effective.InterruptAndSend -> { + val stopped = call(plan, "session.interrupt", buildParams(plan.binding, text, Effective.InterruptAndSend, false, null, "session.interrupt")) + if (stopped.status() != "interrupted") return Outcome.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) + // Stop clears the host's old queue; enqueue only after its receipt. Persist the method change first. + val next = plan.entry.withMethod("prompt.submit", text) + try { engine.commit(listOf(StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), next.encode()))) } + catch (e: ChatStoreException) { return Outcome.Uncertain(ChatError(ChatError.Kind.PersistenceFailed)) } + ctx.onState { replaceEntry(rt, next) } + queueSubmit(plan, text, next) + } + Effective.NewTurn -> if (plan.isCommand) commandSubmit(plan, text) else streamingSubmit(plan, text) + } + } catch (e: HermesException) { + return classify(e) + } catch (e: RequestCancelledException) { + return if (e.dispatch == DispatchOutcome.MayHaveBeenSent) Outcome.Uncertain(ChatError(ChatError.Kind.Cancelled)) else Outcome.NotSent(ChatError(ChatError.Kind.Cancelled)) + } + } + + private suspend fun call(plan: Plan, method: String, params: JsonObject): JsonElement { + plan.dispatched = true + plan.currentMethod = method + return ctx.gateway.request(method, params) + } + + private fun JsonElement.status(): String? = asObject?.get("status").asString + + /** Ordinary idle send: `prompt.submit{queued:true}`; `streaming`/`ok` admits a live turn, queue statuses transfer ownership. */ + private suspend fun streamingSubmit(plan: Plan, text: String): Outcome { + val result = call(plan, "prompt.submit", buildParams(plan.binding, text, Effective.NewTurn, false, null, "prompt.submit")) + return receipt(plan, result, expectsUserRow = true) + } + + private suspend fun queueSubmit(plan: Plan, text: String, entry: JournalEntry): Outcome { + val result = call(plan, "prompt.submit", buildParams(plan.binding, text, Effective.NewTurn, false, null, "prompt.submit")) + return when (result.status()) { + // The explicit queue path: the host queued it, or the turn had just ended and it started. + "queued", "streaming" -> Outcome.Admitted(Admission.Queued, retire = true) + else -> Outcome.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) + } + } + + private suspend fun receipt(plan: Plan, result: JsonElement, expectsUserRow: Boolean): Outcome { + val obj = result.asObject + return when (obj?.get("status").asString) { + "streaming", "ok" -> { + val owned = ctx.onState { + val rt = plan.rt + if (rt.pending !== plan.pending || rt.binding != plan.binding) return@onState false + if (expectsUserRow) obj?.get("user_row_id").asLong?.takeIf { it > 0 }?.let(rt.reducer::bindUserRow) + val pending = rt.pending!! + pending.overlapped = pending.candidateTurns.size > 1 + pending.select() + pending.admitted = true + rt.status = "Working" + completeIfReady(rt) + engine.publish(rt) + true + } + // The socket changed under this send: the receipt cannot be attributed to a turn here. The entry stays. + if (!owned) return Outcome.Uncertain(ChatError(ChatError.Kind.NotConnected)) + // The entry stays journaled until its turn's terminal; completeIfReady retires it. + Outcome.Admitted(Admission.Streaming, retire = false) + } + "queued", "steered", "redirected" -> Outcome.Admitted(Admission.Queued, retire = true) + else -> Outcome.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) + } + } + + /** `/command`: `slash.exec` for the typed or core command, `command.dispatch` for a chosen skill, plugin or user one. */ + private suspend fun commandSubmit(plan: Plan, text: String): Outcome { + val rt = plan.rt + val dispatchFirst = plan.entry.method == "command.dispatch" + val first: JsonElement = try { + call(plan, plan.entry.method, buildParams(plan.binding, text, Effective.NewTurn, true, plan.selection, plan.entry.method)) + } catch (e: HermesException) { + // 4018 on slash.exec is a refusal before any execution that names command.dispatch; its own clients retry there once. + if (dispatchFirst || e.kind != HermesException.Kind.RpcRejected || e.code != 4018L) throw e + val (name, arg) = SlashCommandCatalog.typedDispatch(text) + val next = plan.entry.withMethod("command.dispatch", text) + try { engine.commit(listOf(StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), next.encode()))) } + catch (persist: ChatStoreException) { + // The first route definitely did not run. Without the changed method on disk the fallback is not sent. + return Outcome.Refused(4018, keepEntry = false, reachedLimit = false, error = ChatError(ChatError.Kind.PersistenceFailed)) + } + ctx.onState { replaceEntry(rt, next) } + call(plan, "command.dispatch", buildJsonObject { + put("session_id", plan.binding.runtimeId); put("profile", plan.binding.profile); put("name", name); put("arg", arg) + }) + } + var response = first.asObject ?: JsonObject(emptyMap()) + var expanded = false + val type = response["type"].asString + val message = response["message"].asString + if ((type == "skill" || type == "send") && message != null) { + // The dispatcher returned an instruction, not a submission. Its exact bytes go once through prompt.submit. + val next = plan.entry.withMethod("prompt.submit", message) + try { engine.commit(listOf(StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), next.encode()))) } + catch (persist: ChatStoreException) { + return Outcome.Refused(null, keepEntry = false, reachedLimit = false, error = ChatError(ChatError.Kind.PersistenceFailed)) + } + ctx.onState { replaceEntry(rt, next) } + val accepted = call(plan, "prompt.submit", buildJsonObject { + put("session_id", plan.binding.runtimeId); put("profile", plan.binding.profile); put("text", message); put("queued", true) + }) + response = accepted.asObject ?: JsonObject(emptyMap()) + expanded = true + } + val status = response["status"].asString + val output = response["output"].asString + return when { + output != null && status != "streaming" && status != "queued" -> { + ctx.onState { + val id = "command:${plan.entry.id}" + rt.reducer.removeLocal(plan.entry.id) + rt.reducer.addCommandResult(id, output) + plan.pending?.let { it.admitted = true; it.terminalSeen = true } + completeIfReady(rt) + engine.publish(rt) + } + Outcome.Admitted(Admission.CommandOutput, retire = false) + } + status == "queued" || status == "steered" || status == "redirected" -> Outcome.Admitted(Admission.Queued, retire = true) + status == "streaming" || status == "ok" -> receipt(plan, JsonObject(response), expectsUserRow = !plan.isCommand || expanded) + else -> Outcome.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) + } + } + + private fun classify(e: HermesException): Outcome { + val code = e.code?.toInt() + if (code != null && e.kind in setOf(HermesException.Kind.RpcRejected, HermesException.Kind.ActiveSessionLimit)) { + val limit = e.kind == HermesException.Kind.ActiveSessionLimit + return when { + limit || code in KEPT_REFUSALS -> Outcome.Refused(if (limit) 4090 else code, keepEntry = true, reachedLimit = limit, error = SessionBinder.chatError(e)) + code in PROVEN_REJECTIONS -> Outcome.Refused(code, keepEntry = false, reachedLimit = false, error = SessionBinder.chatError(e)) + // An arbitrary host error from a mutation is not proof that nothing was admitted. + else -> Outcome.Uncertain(SessionBinder.chatError(e)) + } + } + if (e.outcomeUnknown) return Outcome.Uncertain(SessionBinder.chatError(e)) + return when (e.kind) { + HermesException.Kind.NotConnected, HermesException.Kind.ExclusiveSubmitUnavailable, HermesException.Kind.TooManyRequests, + HermesException.Kind.MessageTooLarge, HermesException.Kind.TimedOut -> Outcome.NotSent(SessionBinder.chatError(e)) + else -> Outcome.Uncertain(SessionBinder.chatError(e)) + } + } + + // ---- bookkeeping + + private suspend fun settle(plan: Plan, outcome: Outcome) { + val rt = plan.rt + when (outcome) { + is Outcome.Admitted -> if (outcome.retire) { retire(rt, plan.entry.id); ctx.onState { if (rt.pending === plan.pending) rt.pending = null; rt.status = null; engine.publish(rt) } } + is Outcome.Refused -> { + val code = outcome.code + if (outcome.keepEntry) keepRefused(plan, code ?: 0) else retireAndRestore(plan, code) + ctx.onState { + if (code == 4001 || code == 4007) { rt.requiresReattach = true; rt.needsRecovery = true } + if (rt.pending === plan.pending) rt.pending = null + engine.publish(rt) + } + } + is Outcome.NotSent -> { retireAndRestore(plan, null); ctx.onState { if (rt.pending === plan.pending) rt.pending = null; engine.publish(rt) } } + is Outcome.Uncertain -> ctx.onState { + // The entry stays journaled exactly as sent. The slot is freed so independent input is possible after recovery. + rt.reducer.removeLocal(plan.entry.id) + if (rt.pending === plan.pending) rt.pending = null + rt.needsRecovery = true + rt.lastError = outcome.error + engine.publish(rt) + } + } + } + + private suspend fun retire(rt: ConversationRuntime, entryId: String) { + try { + engine.commit(listOf(StoreOp.Delete(RecordKey.journal(rt.scope, entryId)))) + ctx.onState { rt.unresolved.removeAll { it.id == entryId }; engine.publish(rt) } + } catch (e: ChatStoreException) { + ctx.onState { rt.needsRecovery = true; rt.status = "The retained submission could not be cleared. Review it before sending again."; engine.publish(rt) } + } + } + + private suspend fun keepRefused(plan: Plan, code: Int) { + val rt = plan.rt + val refused = plan.entry.refused(code) + try { + engine.commit(listOf(StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), refused.encode()))) + ctx.onState { replaceEntry(rt, refused); rt.reducer.removeLocal(plan.entry.id) } + } catch (e: ChatStoreException) { + // The earlier durable entry stays as it was; nothing is retired or resent. + ctx.onState { rt.needsRecovery = true; rt.status = "The refusal could not be saved. The original submission is retained."; rt.reducer.removeLocal(plan.entry.id) } + } + } + + /** Nothing was admitted: the entry goes, and its text returns to an empty composer. A newer draft keeps its place and the entry is kept unsent instead. */ + private suspend fun retireAndRestore(plan: Plan, code: Int?) { + val rt = plan.rt + val restore = ctx.onState { rt.draft.isEmpty() && rt.draftAttachments.isEmpty() } + if (!restore) { keepRefused(plan, code ?: 0); return } + try { + val ops = listOf( + StoreOp.Delete(RecordKey.journal(rt.scope, plan.entry.id)), + engine.draftOp(rt.scope, plan.entry.composerText, plan.entry.attachments), + ) + engine.commit(ops) + ctx.onState { + rt.unresolved.removeAll { it.id == plan.entry.id } + rt.reducer.removeLocal(plan.entry.id) + if (rt.draft.isEmpty()) { rt.draft = plan.entry.composerText; rt.draftAttachments = plan.entry.attachments } + } + } catch (e: ChatStoreException) { + ctx.onState { rt.reducer.removeLocal(plan.entry.id) } + } + } + + private fun replaceEntry(rt: ConversationRuntime, entry: JournalEntry) { + val index = rt.unresolved.indexOfFirst { it.id == entry.id } + if (index >= 0) rt.unresolved[index] = entry else rt.unresolved += entry + } + + /** One exact-owner recovery so independent new input becomes possible again. It leaves the original entry untouched and resends nothing. */ + private suspend fun recoverAfterLoss(plan: Plan) { + val generation = plan.binding.generation + val live = ctx.gateway.state.value + if (live.generation != generation || live.connection != app.bighelp.hermes.GatewayConnection.Connected) return + runCatching { engine.recover(plan.rt, generation) } + } + + // ---- terminal settlement (serial) + + /** Retires the send once it is admitted and its own turn ended; an overlapping or failed-unreported turn keeps the entry for review. */ + fun completeIfReady(rt: ConversationRuntime) { + val pending = rt.pending ?: return + if (!pending.admitted || !pending.terminalSeen) return + val reportedFailure = pending.selectedTurn != null && rt.reducer.failedTurnId == pending.selectedTurn + rt.pending = null + if (!pending.overlapped && (!pending.pendingTurnFailed || reportedFailure)) { + retireLater(rt, pending.entry.id) + } else { + // The entry stays for review. One exact-owner recovery makes independent input possible again. + rt.needsRecovery = true + val generation = rt.binding?.generation + if (generation != null) ctx.scope.launch { if (ctx.gateway.state.value.generation == generation) runCatching { engine.recover(rt, generation) } } + } + } + + fun retireAfterReplay(rt: ConversationRuntime, entryId: String) = retireLater(rt, entryId) + + private fun retireLater(rt: ConversationRuntime, entryId: String) { + ctx.scope.launch { retire(rt, entryId) } + } + + // ---- stop, draft, review + + suspend fun stop(ref: ConversationRef): StopResult { + val target = ctx.onState { + val rt = engine.conversations[ref] ?: return@onState null + val binding = rt.binding + if (binding == null || binding.generation != ctx.gateway.state.value.generation || rt.requiresReattach) return@onState null + rt to binding + } ?: return StopResult.Refused(ChatError(ChatError.Kind.NotConnected)) + val (rt, binding) = target + return try { + val result = ctx.gateway.request("session.interrupt", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile) }) + if (result.status() != "interrupted") return StopResult.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) + ctx.onState { if (rt.binding == binding) { rt.stopRequested = true; rt.status = "Stop requested"; engine.publish(rt) } } + StopResult.Requested + } catch (e: HermesException) { + if (e.outcomeUnknown) StopResult.Uncertain(SessionBinder.chatError(e)) else StopResult.Refused(SessionBinder.chatError(e)) + } catch (e: RequestCancelledException) { + if (e.dispatch == DispatchOutcome.MayHaveBeenSent) StopResult.Uncertain(ChatError(ChatError.Kind.Cancelled)) else StopResult.Refused(ChatError(ChatError.Kind.Cancelled)) + } + } + + suspend fun updateDraft(ref: ConversationRef, text: String, attachments: List): DraftResult { + if (utf8Length(text) > ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES || attachments.size > ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCES) { + return DraftResult.NotSaved(ChatError(ChatError.Kind.TooLarge)) + } + val rt = ctx.onState { engine.conversations[ref] } ?: return DraftResult.NotSaved(ChatError(ChatError.Kind.NotOpen)) + return try { + engine.commit(listOf(engine.draftOp(rt.scope, text, attachments))) + ctx.onState { rt.draft = text; rt.draftAttachments = attachments; engine.publish(rt) } + DraftResult.Saved + } catch (e: ChatStoreException) { + DraftResult.NotSaved(ChatError(if (e.kind == ChatStoreException.Kind.TooLarge) ChatError.Kind.TooLarge else ChatError.Kind.PersistenceFailed)) + } + } + + suspend fun review(ref: ConversationRef, entryId: String, decision: ReviewDecision): ReviewResult { + val (rt, entry) = ctx.onState { + val rt = engine.conversations[ref] ?: return@onState null + val entry = rt.unresolved.firstOrNull { it.id == entryId } ?: return@onState null + if (rt.pending?.entry?.id == entryId) return@onState null + rt to entry + } ?: return ReviewResult.NotFound + val restoring = decision == ReviewDecision.RestoreToComposer + if (restoring && !ctx.onState { rt.draft.isEmpty() && rt.draftAttachments.isEmpty() }) return ReviewResult.ComposerNotEmpty + return try { + val ops = ArrayList() + ops += StoreOp.Delete(RecordKey.journal(rt.scope, entryId)) + if (restoring) ops += engine.draftOp(rt.scope, entry.composerText, entry.attachments) + engine.commit(ops) + ctx.onState { + rt.unresolved.removeAll { it.id == entryId } + if (restoring) { rt.draft = entry.composerText; rt.draftAttachments = entry.attachments } + engine.publish(rt) + } + ReviewResult.Done + } catch (e: ChatStoreException) { + ReviewResult.Failed(ChatError(ChatError.Kind.PersistenceFailed)) + } + } + + companion object { + /** A definite refusal Hermes sends before admission that revokes or limits the session; the entry is kept as unsent. */ + val KEPT_REFUSALS = setOf(4001, 4007, 4090) + + /** Validation and ownership rejections that precede prompt admission: non-admission is established. */ + val PROVEN_REJECTIONS = setOf(4002, 4004, 4009, 4010, 4030, 4130) + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt new file mode 100644 index 00000000..207ab155 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt @@ -0,0 +1,340 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.WireMessage +import app.bighelp.hermes.utf8Length +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** How Hermes says a turn failed (`message.complete` with `status:"error"`). Every part is optional advice. */ +data class TurnFailure( + val layer: String?, + val code: String?, + val retryable: Boolean, + val providerLabel: String?, + val resetsAtEpochSeconds: Double?, + val billingUrl: String?, +) + +enum class CompactionSignal { Compressing, Compacting, Compacted } + +internal class PersistedTurn(val userRowId: Long?, val finalAssistantRowId: Long?) + +/** What one event changed, beyond the items. The repository applies it to the conversation. */ +internal class Change { + /** The event's sequence was not newer than the cursor: it changed nothing. */ + var ignored = false + var terminal = false + var failedBeforeStart = false + var turnFailure: TurnFailure? = null + var terminalError: String? = null + var settledAnswer = false + var errorEvent = false + var status: String? = null + var title: String? = null + var runtime: RuntimeInfo? = null + var storedIdReport: String? = null + var persistedTurn: PersistedTurn? = null + var compaction: CompactionSignal? = null + var started = false +} + +/** + * The ordered reduction of one runtime's live events into transcript items, one instance per conversation. It + * is pure: no I/O, no clock. `message.complete` closes a segment; only `session.info running:false` after + * running ends the turn. Streaming rows are keyed by turn and segment so an upsert keeps its place. + */ +internal class TurnReducer(initialEpoch: String = "") { + var epoch: String = initialEpoch + private set + var lastSequence: Long = 0 + private set + var running = false + private set + var turnId: String = "" + private set + var failedTurnId: String? = null + private set + var hasLiveEvents = false + private set + + private val live = LinkedHashMap() + private var text = "" + private var reasoning = "" + private var reasoningSegment = 0 + private var reasoningSealed = false + private var segment = 0 + private var segmentId: String? = null + private var sealedSegmentId: String? = null + private var anonymous = 0L + + val items: List get() = live.values.toList() + + fun seedCheckpoint(sequence: Long) { lastSequence = maxOf(lastSequence, sequence) } + + /** A new replay epoch restarts sequence numbers. Rows stay; only the cursor moves. */ + fun resetCursor(newEpoch: String, latest: Long) { + epoch = newEpoch + lastSequence = latest + } + + fun seedRunning(value: Boolean) { running = value } + + /** An optimistic row for a message just sent from here. It is bound to a saved row by the host's row ID, never by text. */ + fun addLocalUser(localId: String, body: String) { + val id = "local:$localId" + live[id] = MessageItem(id, MessageRole.User, "user", body, ItemOrigin.Local) + } + + fun removeLocal(localId: String) { live.remove("local:$localId") } + + /** A command's output, shown once as a result instead of a turn. */ + fun addCommandResult(id: String, output: String) { + live[id] = MessageItem(id, MessageRole.Assistant, "assistant", output, ItemOrigin.Live, isCommandResult = true) + } + + /** `prompt.submit`'s `user_row_id`: the newest local user row, if it has none yet. */ + fun bindUserRow(rowId: Long) { + val last = live.values.lastOrNull { it is MessageItem && it.role == MessageRole.User && it.origin == ItemOrigin.Local } as? MessageItem ?: return + if (last.rowId == null) live[last.id] = last.copy(rowId = rowId) + } + + /** `message.complete.persisted_turn`: the newest human row and the newest assistant row, only when each is still unbound. */ + fun bindRows(turn: PersistedTurn) { + turn.userRowId?.let(::bindUserRow) + turn.finalAssistantRowId?.let { rowId -> + val last = live.values.lastOrNull { it is MessageItem && it.role == MessageRole.Assistant } as? MessageItem ?: return@let + if (last.rowId == null) live[last.id] = last.copy(rowId = rowId) + } + } + + /** Drops every live row. Called when saved history has caught up with them. */ + fun clearItems() { + live.clear() + text = ""; reasoning = ""; segmentId = null; sealedSegmentId = null; reasoningSealed = false + } + + fun retain(predicate: (TranscriptItem) -> Boolean) { + live.entries.removeAll { !predicate(it.value) } + } + + fun accept(event: WireMessage.Event): Change { + val change = Change() + event.sequence?.let { sequence -> + if (sequence <= lastSequence) return change.also { it.ignored = true } + lastSequence = sequence + } + if (event.type.startsWith("message.") || event.type.startsWith("tool.")) hasLiveEvents = true + val p = event.payload + val key = "$epoch:${event.sequence ?: "x${++anonymous}"}" + when (event.type) { + "message.start" -> { + change.started = true + running = true + turnId = key + text = ""; reasoning = ""; reasoningSegment = 0; reasoningSealed = false + segment = 0; segmentId = null; sealedSegmentId = null + } + "message.delta" -> { + val delta = p["text"].asString.orEmpty() + if (delta.isNotEmpty()) finishReasoning() + running = true + text += delta + if (text.isNotEmpty()) publishText(text, key, complete = false) + } + "message.interim" -> { + finishReasoning() + val interim = p["text"].asString.orEmpty() + if (interim.isNotEmpty()) { + publishText(interim, key, complete = true) + sealedSegmentId = segmentId + } + text = ""; reasoning = ""; segment += 1; segmentId = null + } + "message.complete" -> complete(p, key, change) + "reasoning.delta" -> { + val delta = p["text"].asString.orEmpty() + if (reasoningSealed && delta.isNotEmpty()) { reasoningSegment += 1; reasoningSealed = false; reasoning = "" } + reasoning += delta + if (reasoning.isNotEmpty()) activity("reasoning:$reasoningSegment", ActivityKind.Reasoning, "Reasoning", reasoning, terminal = false, payload = p) + } + "thinking.delta" -> thinking(p)?.let { change.status = it } + "tool.generating" -> exactly(p, setOf("name"))?.let { fields -> + val name = fields["name"].asString ?: return@let + change.status = if (name.isEmpty()) "Preparing tool" else "Preparing $name" + } + "status.update" -> exactly(p, setOf("kind", "text"))?.let { fields -> + val kind = fields["kind"].asString ?: return@let + val words = fields["text"].asString ?: return@let + change.status = words.ifEmpty { "Working" } + change.compaction = when (kind) { + "compressing" -> CompactionSignal.Compressing + "compacting" -> CompactionSignal.Compacting + "compacted" -> CompactionSignal.Compacted + else -> null + } + } + "notice" -> exactly(p, setOf("message"))?.let { fields -> + val message = fields["message"].asString ?: return@let + activity("notice:$key", ActivityKind.Notice, "Hermes notice", message, terminal = true, payload = JsonObject(emptyMap()), lifecycle = ActivityLifecycle.Recorded) + if (message.isNotEmpty()) change.status = message + } + "tool.start", "tool.progress", "tool.complete" -> { + val toolId = p["tool_id"].asString?.takeIf { it.isNotEmpty() } ?: return change + if (event.type == "tool.start") finishReasoning() + activity("tool:$toolId", ActivityKind.Tool, p["name"].asString ?: "Tool", p["context"].asString, event.type == "tool.complete", p, toolId = toolId) + } + "session.info" -> sessionInfo(p, change) + "session.title" -> p["title"].asString?.let { change.title = it } + "error" -> change.errorEvent = true + else -> if (event.type.startsWith("subagent.")) subagent(event.type, p) + } + return change + } + + private fun complete(p: JsonObject, key: String, change: Change) { + val failure = turnFailure(p) + if (failure != null && !running) { + // Hermes refused some turns before message.start. Its failed final is a turn of its own, and its end. + turnId = key + text = ""; reasoning = ""; reasoningSegment = 0; reasoningSealed = false + segment = 0; segmentId = null; sealedSegmentId = null + change.terminal = true + change.failedBeforeStart = true + } + if (failure != null) { failedTurnId = turnId; change.turnFailure = failure } + finishReasoning() + val final = p["text"].asString ?: text + val reused = p["response_reused"].asBool == true || p["response_previewed"].asBool == true + if (final.isNotEmpty() && reused && segmentId == null && settleSealedAnswer(final)) { + change.settledAnswer = true + } else if (final.isNotEmpty()) { + publishText(final, key, complete = true, failure = failure) + } + p["reasoning"].asString?.takeIf { it.isNotEmpty() }?.let { + reasoning = it + activity("reasoning:$reasoningSegment", ActivityKind.Reasoning, "Reasoning", it, terminal = true, payload = p) + } + p["error"].asString?.let { change.terminalError = it } + p["persisted_turn"].asObject?.let { turn -> + change.persistedTurn = PersistedTurn(turn["user_row_id"].asLong?.takeIf { it > 0 }, turn["final_assistant_row_id"].asLong?.takeIf { it > 0 }) + } + } + + private fun sessionInfo(p: JsonObject, change: Change) { + p["stored_session_id"].asString?.let { change.storedIdReport = it } + val info = RuntimeInfo( + model = p["model"].asString, provider = p["provider"].asString, reasoningEffort = p["reasoning_effort"].asString, + serviceTier = p["service_tier"].asString, cwd = p["cwd"].asString, + ) + if (info != RuntimeInfo()) change.runtime = info + p["title"].asString?.takeIf { it.isNotEmpty() }?.let { change.title = it } + val active = p["running"].asBool ?: return + change.terminal = running && !active + running = active + if (change.terminal) { + for ((id, item) in live.entries.toList()) { + if (item is ActivityItem && item.kind != ActivityKind.Subagent && item.lifecycle == ActivityLifecycle.Running) { + val settled = if (item.kind == ActivityKind.Tool) ActivityLifecycle.Recorded else ActivityLifecycle.Succeeded + live[id] = item.copy(lifecycle = settled) + } + } + } + } + + private fun subagent(type: String, p: JsonObject) { + val child = p["child_session_id"].asString?.takeIf { it.isNotEmpty() } + val id = p["subagent_id"].asString?.takeIf { it.isNotEmpty() } ?: child ?: return + val key = "subagent:$id" + val previous = live["$turnId:$key"] as? ActivityItem + val detail = if (type == "subagent.thinking" || type == "subagent.text") { + (previous?.detail ?: "") + p["text"].asString.orEmpty() + } else p["summary"].asString ?: p["tool_preview"].asString ?: p["text"].asString + activity(key, ActivityKind.Subagent, p["goal"].asString?.takeIf { it.isNotEmpty() } ?: previous?.title ?: "Subagent", + detail ?: previous?.detail, type == "subagent.complete", p) + } + + private fun finishReasoning() { + if (reasoningSealed || reasoning.isEmpty()) return + val unfinished = live.entries.filter { (_, item) -> + item is ActivityItem && item.turnId == turnId && item.kind == ActivityKind.Reasoning && item.lifecycle == ActivityLifecycle.Running + } + if (unfinished.isEmpty()) return + reasoningSealed = true + for ((id, item) in unfinished) live[id] = (item as ActivityItem).copy(lifecycle = ActivityLifecycle.Succeeded) + } + + private fun publishText(value: String, eventKey: String, complete: Boolean, failure: TurnFailure? = null) { + val id = segmentId ?: "live:${turnId.ifEmpty { eventKey }}:$segment".also { segmentId = it } + val old = live[id] as? MessageItem + live[id] = (old ?: MessageItem(id, MessageRole.Assistant, "assistant", value, ItemOrigin.Live)) + .copy(text = value, complete = complete, failure = failure ?: old?.failure) + } + + private fun settleSealedAnswer(final: String): Boolean { + val id = sealedSegmentId ?: return false + val item = live[id] as? MessageItem ?: return false + if (item.role != MessageRole.Assistant || item.text.trim() != final.trim()) return false + live[id] = item.copy(complete = true) + segmentId = id + return true + } + + private fun activity( + key: String, kind: ActivityKind, title: String, detail: String?, terminal: Boolean, payload: JsonObject, + toolId: String? = null, lifecycle: ActivityLifecycle? = null, + ) { + val id = "$turnId:$key" + val old = live[id] as? ActivityItem + val status = payload["status"].asString + val finalOnlyReasoning = terminal && kind == ActivityKind.Reasoning && old == null + val state = lifecycle ?: when { + status == "failed" || status == "error" -> ActivityLifecycle.Failed + status == "cancelled" || status == "interrupted" -> ActivityLifecycle.Cancelled + finalOnlyReasoning -> ActivityLifecycle.Recorded + terminal -> ActivityLifecycle.Succeeded + old != null && old.lifecycle != ActivityLifecycle.Running -> old.lifecycle + else -> ActivityLifecycle.Running + } + live[id] = ActivityItem( + id = id, kind = kind, title = old?.title ?: title, detail = detail ?: old?.detail, lifecycle = state, + toolCallId = toolId ?: old?.toolCallId, turnId = turnId, origin = ItemOrigin.Live, + arguments = jsonText(payload["args"]) ?: old?.arguments, result = jsonText(payload["result"]) ?: old?.result, + ) + } + + private fun jsonText(value: JsonElement?): String? = when { + value == null || value is JsonNull -> null + value is JsonPrimitive && value.isString -> value.content + else -> value.toString() + } + + private fun exactly(p: JsonObject, keys: Set): JsonObject? = p.takeIf { it.keys == keys } + + /** Spinner text only: `text`, optionally `rendered` and `verbose`, nothing else. */ + private fun thinking(p: JsonObject): String? { + if (!setOf("text", "rendered", "verbose").containsAll(p.keys)) return null + val raw = p["text"].asString ?: return null + p["rendered"]?.let { if (it !is JsonNull && it.asString == null) return null } + p["verbose"]?.let { if (it !is JsonNull && it.asBool == null) return null } + val trimmed = raw.take(256).trim() + return trimmed.ifEmpty { "Working" } + } + + private fun turnFailure(p: JsonObject): TurnFailure? { + if (p["status"].asString != "error") return null + val surface = p["error_surface"].asObject ?: JsonObject(emptyMap()) + val billing = p["billing"].asObject ?: JsonObject(emptyMap()) + fun token(v: JsonElement?) = v.asString?.trim()?.takeIf { it.isNotEmpty() && utf8Length(it) <= 64 && it.all { c -> c.code in 33..126 } } + fun label(v: JsonElement?) = v.asString?.trim()?.takeIf { s -> s.isNotEmpty() && s.none { c -> Character.isISOControl(c) } }?.take(80) + val resets = surface["resets_at"].asDouble?.takeIf { it > 1_000_000_000 && it < 100_000_000_000 } + val billingUrl = billing["billing_url"].asString?.takeIf { it.length <= 2_048 && it.startsWith("https://") && it.length > 8 } + return TurnFailure( + layer = token(surface["layer"]), code = token(surface["code"]) ?: token(p["failure_reason"]), + retryable = surface["retryable"].asBool ?: true, + providerLabel = label(surface["provider_label"]) ?: label(billing["provider_label"]), + resetsAtEpochSeconds = resets, billingUrl = billingUrl, + ) + } +} 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..5e8ec513 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt @@ -0,0 +1,92 @@ +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 + +/** 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..3ace4d83 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt @@ -0,0 +1,272 @@ +package app.bighelp.hermes.chat + +import java.io.File +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")) + } +} + +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/FakeHermesHost.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt new file mode 100644 index 00000000..fdf723f1 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt @@ -0,0 +1,631 @@ +package app.bighelp.hermes.chat + +import app.bighelp.hermes.ConnectionOwner +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 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 { + class Recorded(val method: String, val params: JsonObject, val generation: Long) + 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()) + private val delivery = Channel(Channel.RENDEZVOUS) + override val events: Flow = flow { for (event in delivery) emit(event) } + + 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 + + override suspend fun request(method: String, params: JsonObject, timeoutMillis: Long?): JsonElement { + val live = state.value + if (live.connection != GatewayConnection.Connected) throw HermesException(HermesException.Kind.NotConnected) + requests += Recorded(method, params, live.generation) + overrides[method]?.removeFirstOrNull()?.let { return it(params) } + return defaultHandle(method, params) + } + + 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/GatewayChatIntegrationTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt new file mode 100644 index 00000000..bddeabf8 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt @@ -0,0 +1,137 @@ +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.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() + } +} 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..414fbf13 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt @@ -0,0 +1,125 @@ +package app.bighelp.hermes.chat + +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)) + 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) + } +} 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/SendFlowTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt new file mode 100644 index 00000000..b96d5793 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt @@ -0,0 +1,372 @@ +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()) + } +} 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/TurnReducerTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt new file mode 100644 index 00000000..1efbcdb8 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt @@ -0,0 +1,270 @@ +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 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) + } +} From fb5d45249b7dcab15c84c42ab029a7e1dbc61804 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:49:45 -0500 Subject: [PATCH 16/18] Android app connects to Hermes: sign-in, saved computers, agents, sessions and live chat Co-Authored-By: Claude Sonnet 5.5 --- .../storage/AndroidChatStoreDeviceTest.kt | 66 ++ .../kotlin/app/bighelp/android/AccessInput.kt | 60 ++ .../kotlin/app/bighelp/android/AppState.kt | 20 + .../kotlin/app/bighelp/android/BighelpApp.kt | 156 +++-- .../app/bighelp/android/BighelpAppModel.kt | 201 +++++- .../kotlin/app/bighelp/android/ChatScreen.kt | 113 +++- .../app/bighelp/android/LiveChatScreen.kt | 582 ++++++++++++++++ .../app/bighelp/android/LiveListsScreens.kt | 313 +++++++++ .../app/bighelp/android/LiveModelSheet.kt | 163 +++++ .../app/bighelp/android/LiveSettings.kt | 185 +++++ .../kotlin/app/bighelp/android/LiveUiParts.kt | 172 +++++ .../app/bighelp/android/MainActivity.kt | 50 +- .../kotlin/app/bighelp/android/Markdown.kt | 120 ++++ .../app/bighelp/android/PreviewPreferences.kt | 25 +- .../app/bighelp/android/SettingsScreen.kt | 39 +- .../kotlin/app/bighelp/android/SetupScreen.kt | 103 ++- .../app/bighelp/android/SignInScreen.kt | 223 ++++++ .../app/bighelp/android/WelcomeScreens.kt | 11 +- .../app/bighelp/android/live/AccessSetup.kt | 153 +++++ .../app/bighelp/android/live/ChatService.kt | 104 +++ .../android/live/ComputerConnectionModel.kt | 137 ++-- .../app/bighelp/android/live/ComputerLink.kt | 39 ++ .../app/bighelp/android/live/LiveModel.kt | 477 +++++++++++++ .../app/bighelp/android/live/LiveText.kt | 100 +++ .../android/live/NetworkComputerSession.kt | 108 +++ .../bighelp/android/live/SessionListing.kt | 78 +++ .../bighelp/android/live/TranscriptRows.kt | 69 ++ .../android/storage/AndroidChatStore.kt | 637 ++++++++++++++++++ .../app/bighelp/android/AccessInputTest.kt | 43 ++ .../app/bighelp/android/LiveNavigationTest.kt | 206 ++++++ .../app/bighelp/android/MarkdownTest.kt | 53 ++ .../bighelp/android/live/AccessSetupTest.kt | 79 +++ .../live/ComputerConnectionModelTest.kt | 163 ++++- .../bighelp/android/live/ComputerLinkTest.kt | 34 + .../app/bighelp/android/live/LiveModelTest.kt | 279 ++++++++ .../bighelp/android/live/LiveTestSupport.kt | 150 +++++ .../app/bighelp/android/live/LiveTextTest.kt | 42 ++ .../live/NetworkComputerSessionTest.kt | 112 +++ .../android/live/SessionListingTest.kt | 105 +++ .../android/live/TranscriptRowsTest.kt | 98 +++ .../android/storage/AndroidChatStoreTest.kt | 398 +++++++++++ 41 files changed, 6100 insertions(+), 166 deletions(-) create mode 100644 android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidChatStoreDeviceTest.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/AccessInput.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/LiveChatScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/LiveListsScreens.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/LiveModelSheet.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/LiveSettings.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/LiveUiParts.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/Markdown.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/SignInScreen.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/AccessSetup.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/ChatService.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/ComputerLink.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/LiveModel.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/LiveText.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/NetworkComputerSession.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/SessionListing.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/live/TranscriptRows.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/AndroidChatStore.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/AccessInputTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/LiveNavigationTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/MarkdownTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/AccessSetupTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/ComputerLinkTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/LiveModelTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/LiveTestSupport.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/LiveTextTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/NetworkComputerSessionTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/SessionListingTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/live/TranscriptRowsTest.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/storage/AndroidChatStoreTest.kt 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/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/AppState.kt b/android/app/src/main/kotlin/app/bighelp/android/AppState.kt index 6684ee00..566e1d87 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/AppState.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/AppState.kt @@ -13,7 +13,14 @@ sealed interface 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. */ @@ -25,6 +32,9 @@ sealed interface DiscoveryState { 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 } @@ -32,6 +42,8 @@ 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) @@ -76,6 +88,14 @@ data class AppState( 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 index 01a626be..9f64ef42 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpApp.kt @@ -2,20 +2,29 @@ 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 @@ -25,11 +34,15 @@ fun BighelpApp( 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( @@ -37,47 +50,110 @@ fun BighelpApp( modifier = Modifier.fillMaxSize().semantics { testTagsAsResourceId = true }, ) { BackHandler(enabled = state.backStack.size > 1) { model.back() } - val demo = state.demo - when (val route = state.route) { - Route.Welcome -> WelcomeScreen(onTryDemo = model::tryDemo, onConnect = model::connectComputer) - 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, - ) - // The demo places exist only while the demo does. - Route.Sessions -> demo?.let { - SessionsScreen(it, model::setSearch, model::openChat, model::startNewChat, model::openPlace) - } - Route.Agents -> demo?.let { AgentsScreen(it, model::selectAgent, model::startNewChat, model::openPlace) } - Route.Settings -> SettingsScreen( - appearance = state.appearance, - consentGranted = state.consentGranted, - versionName = versionName, - onAppearance = model::setAppearance, - onPrivacyPolicy = onOpenPrivacyPolicy, - onLeaveDemo = model::leaveDemo, - onOpenPlace = model::openPlace, - ) - 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) }, - ) - } + 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 index 22874076..74f257c9 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt @@ -1,12 +1,19 @@ 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 @@ -19,19 +26,58 @@ import kotlinx.coroutines.launch * - **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( +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), + 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 ------------------------------------------------------------------------- @@ -39,15 +85,29 @@ class BighelpAppModel( fun back(): Boolean { val stack = mutableState.value.backStack if (stack.size <= 1) return false - if (stack.last() == Route.Setup) dropCheck() + 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) { - if (mutableState.value.demo == null) return + 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)) } @@ -64,7 +124,10 @@ class BighelpAppModel( fun connectComputer() { dropCheck() val next = if (mutableState.value.consentGranted) Route.Setup else Route.Consent - mutableState.update { it.copy(backStack = listOf(Route.Welcome, next), demo = null) } + // 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. */ @@ -82,6 +145,12 @@ class BighelpAppModel( 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() @@ -106,6 +175,10 @@ class BighelpAppModel( return } + if (live != null) { + startLiveCheck(live, endpoint) + return + } val generation = ++checkGeneration setDiscovery(DiscoveryState.Checking) checkJob = scope.launch { @@ -124,6 +197,100 @@ class BighelpAppModel( 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)) } @@ -132,7 +299,11 @@ class BighelpAppModel( checkGeneration++ checkJob?.cancel() checkJob = null - if (mutableState.value.setup.discovery != DiscoveryState.Idle) setDiscovery(DiscoveryState.Idle) + 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 --------------------------------------------------------------------------------- @@ -229,8 +400,26 @@ class BighelpAppModel( 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/ChatScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt index 491b2888..18b15312 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt @@ -44,6 +44,7 @@ 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 @@ -56,9 +57,7 @@ import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch /** - * A demo chat. The reader owns the scroll position: nothing moves it while they read history, Send always - * brings the newest message into view, and a Latest button appears, in its own row above the message box, - * whenever they are away from the end. + * 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 @@ -78,10 +77,47 @@ fun ChatScreen( return } val agent = demo.agent(session.agentId) - val messages = session.messages + 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 = messages.lastIndex.coerceAtLeast(0)) - val lastIndex by rememberUpdatedState(messages.lastIndex) + 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. @@ -91,8 +127,8 @@ fun ChatScreen( if (!scrolling) followTail = !listState.canScrollForward } } - // Sending (the only way this list grows) always shows the new messages, even from older history. - val lastId = messages.lastOrNull()?.id + // 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) { @@ -101,6 +137,12 @@ fun ChatScreen( 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) { @@ -110,23 +152,30 @@ fun ChatScreen( } } } + // 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")) { - ChatHeader(session.title, agent, onBack) + 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 (messages.isEmpty()) { - item(key = "empty") { EmptyChatNote(agent) } + if (rows.isEmpty() && empty != null) { + item(key = "empty") { empty() } } - items(messages, key = { it.id }) { message -> MessageRow(message) } + 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. @@ -139,14 +188,7 @@ fun ChatScreen( ) } } - // Keyed by chat, so a draft is read once when the chat opens and then owned by the box while typing. - Composer( - key = session.id, - initialDraft = demo.drafts[session.id].orEmpty(), - agentName = agent.name, - onDraft = onDraft, - onSend = onSend, - ) + bottomBar() } } @@ -203,18 +245,31 @@ private fun EmptyChatNote(agent: DemoAgent) { @Composable private fun MessageRow(message: DemoMessage) { - val fromUser = message.fromUser - Row( - Modifier.fillMaxWidth().testTag("chat.message.${message.id}"), - horizontalArrangement = if (fromUser) Arrangement.End else Arrangement.Start, + 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 (message.isExample) { + if (caption != null) { Text( - "Example reply, not from an agent", + caption, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, bottom = 2.dp), @@ -230,9 +285,7 @@ private fun MessageRow(message: DemoMessage) { ), modifier = Modifier.widthIn(max = 560.dp), ) { - SelectionContainer { - Text(message.text, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) - } + SelectionContainer { content() } } } } 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 index 3379e641..1d71186d 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/MainActivity.kt @@ -1,6 +1,7 @@ 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 @@ -12,10 +13,51 @@ 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 model itself is plain Kotlin, tested without Android. */ -class BighelpViewModel(preferences: PreviewPreferences, hostChecker: HostChecker) : ViewModel() { - val model = BighelpAppModel(preferences, hostChecker, viewModelScope) +/** + * 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() { @@ -23,7 +65,7 @@ class MainActivity : ComponentActivity() { object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun create(modelClass: Class, extras: CreationExtras): T = - BighelpViewModel(SharedPreviewPreferences(applicationContext), HostDiscovery()) as T + BighelpViewModel(applicationContext, SharedPreviewPreferences(applicationContext), HostDiscovery()) as T } } 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/PreviewPreferences.kt b/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt index aeed3277..10a8cbd2 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/PreviewPreferences.kt @@ -4,12 +4,23 @@ import android.content.Context import androidx.core.content.edit /** - * The only things this milestone keeps on the device: the one-time AI data agreement and the look. No - * credential, address or chat is stored. Backup and device transfer are excluded in the manifest. + * 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 { @@ -24,11 +35,21 @@ class SharedPreviewPreferences(context: Context) : PreviewPreferences { ?: 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/SettingsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt index 840b0bf1..379c6f19 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt @@ -3,6 +3,7 @@ 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 @@ -27,7 +28,10 @@ import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp -/** The one Settings page: look, data agreement, the demo, and what this build is. */ +/** + * 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, @@ -37,10 +41,12 @@ fun SettingsScreen( 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) }) - DemoBanner(Modifier.padding(horizontal = 16.dp)) + if (showDemo) DemoBanner(Modifier.padding(horizontal = 16.dp)) Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.TopCenter) { Column( Modifier @@ -50,6 +56,7 @@ fun SettingsScreen( .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"), @@ -82,23 +89,25 @@ fun SettingsScreen( Text("Privacy policy") } - 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") + 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. This preview has the demo and a check that a Hermes " + - "computer answers. Signing in and chatting with your computer come next.", + "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 index 7afb2fee..423afe9c 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt @@ -18,7 +18,16 @@ 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 @@ -40,8 +49,9 @@ import androidx.compose.ui.unit.dp import app.bighelp.hermes.HermesEndpointException /** - * Asks a typed address whether a Hermes computer answers. The result says "found", never "connected": - * this milestone collects no password or token and opens no chat. + * 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( @@ -52,6 +62,9 @@ fun SetupScreen( 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")) { @@ -88,6 +101,7 @@ fun SetupScreen( 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) @@ -96,7 +110,7 @@ fun SetupScreen( InkButton("Check computer", onCheck, tag = "setup.check", enabled = setup.address.isNotBlank()) } - DiscoveryResultCard(setup.discovery, setup.allowPrivateHttp, onCheck = onCheck, onTryDemo = onTryDemo) + DiscoveryResultCard(setup.discovery, setup.allowPrivateHttp, live = live, onCheck = onCheck, onTryDemo = onTryDemo, onContinue = onContinue) Spacer(Modifier.height(8.dp)) } } @@ -145,12 +159,22 @@ private fun PrivateHttpRow(checked: Boolean, enabled: Boolean, onChange: (Boolea 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) { @@ -187,13 +211,14 @@ private fun DiscoveryResultCard( if (discovery.authRequired) { append(if (discovery.browserSignIn) " Browser sign-in is offered." else " Browser sign-in is not offered.") } - append("\n\nThis is not a connection. Signing in and chatting come in a later update; ") - append("this preview sent no password or chat.") + 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") - InkButton("Try the demo meanwhile", onTryDemo, tag = "setup.demo") + if (!live) InkButton("Try the demo meanwhile", onTryDemo, tag = "setup.demo") } } } @@ -218,3 +243,69 @@ private fun ResultCard( } } } + +/** + * 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 index 5e62dc7a..539d256f 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/WelcomeScreens.kt @@ -18,9 +18,9 @@ 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 checks a real computer. */ +/** 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) { +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)) @@ -32,7 +32,8 @@ fun WelcomeScreen(onTryDemo: () -> Unit, onConnect: () -> Unit) { color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, ) - Spacer(Modifier.height(40.dp)) + Spacer(Modifier.height(32.dp)) + extra() InkButton("Try the demo", onTryDemo, tag = "welcome.demo") Spacer(Modifier.height(6.dp)) Text( @@ -45,7 +46,7 @@ fun WelcomeScreen(onTryDemo: () -> Unit, onConnect: () -> Unit) { InkOutlinedButton("Connect your computer", onConnect, tag = "welcome.connect") Spacer(Modifier.height(6.dp)) Text( - "Check that your Hermes computer answers. Chatting with it comes in a later update.", + "Sign in to your Hermes computer and chat with your own agents.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, @@ -80,7 +81,7 @@ fun ConsentScreen(onAgree: () -> Unit, onNotNow: () -> Unit, onPrivacyPolicy: () ) Spacer(Modifier.height(12.dp)) Text( - "Right now bighelp only asks whether your computer answers. It sends no password and no chat.", + "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, 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/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 index dcc31718..521b1097 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/live/ComputerConnectionModel.kt @@ -3,14 +3,10 @@ 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.BrowserLauncher import app.bighelp.hermes.CredentialStore import app.bighelp.hermes.CredentialAuthority -import app.bighelp.hermes.GatewayClient -import app.bighelp.hermes.HermesAuthenticator import app.bighelp.hermes.HermesEndpoint import app.bighelp.hermes.HermesException -import app.bighelp.hermes.OkHttpHermesHttp import app.bighelp.hermes.SavedConnection import app.bighelp.hermes.SignInInput import app.bighelp.hermes.StaleCredentialException @@ -25,7 +21,12 @@ 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 @@ -48,38 +49,21 @@ internal data class ComputerConnectionState( /** 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) - suspend fun close() -} -/** The real session stays available to the chat repository without exposing credentials to screens. */ -internal class NetworkComputerSession( - endpoint: HermesEndpoint, - credentials: CredentialStore, - scope: CoroutineScope, - browser: BrowserLauncher?, -) : ComputerSession { - private val http = OkHttpHermesHttp(endpoint) - val authenticator = HermesAuthenticator(endpoint, http, credentials, browser) - val gateway = GatewayClient(authenticator, scope) - init { scope.coroutineContext[Job]?.invokeOnCompletion { authenticator.close() } } - override val saved get() = authenticator.savedConnection - override suspend fun discover() = authenticator.discover() - override suspend fun signIn(input: SignInInput) = authenticator.signIn(input) - override suspend fun restore(saved: SavedConnection) { - authenticator.restore(saved) - } - override suspend fun connect() { gateway.connect() } - override suspend fun commit(expected: SavedConnection?, stillCurrent: () -> Boolean) { - authenticator.commit(expected, stillCurrent) - } - override suspend fun close() { - try { gateway.disconnect() } finally { authenticator.close() } - } + /** 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) @@ -110,17 +94,23 @@ internal class OwnedCredentialStore(private val delegate: CredentialStore, priva * 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 factory: (HermesEndpoint, CredentialStore, CoroutineScope) -> T, + 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 @@ -132,7 +122,6 @@ internal class ComputerConnectionModel( ++generation val previous = operation previous?.cancel() - owner?.credentials?.invalidate() return CoroutineScope(scope.coroutineContext.minusKey(Job) + NonCancellable).launch { previous?.join() try { retire() } catch (_: Exception) { /* The owner is invalid even if socket cleanup fails. */ } @@ -141,7 +130,7 @@ internal class ComputerConnectionModel( } private class Owner( - val id: UUID, val endpoint: HermesEndpoint, val session: T, val job: Job, val scope: CoroutineScope, + val id: UUID, val endpoint: HermesEndpoint, val access: AccessSetup, val session: T, val job: Job, val scope: CoroutineScope, val credentials: OwnedCredentialStore, ) @@ -159,10 +148,11 @@ internal class ComputerConnectionModel( } } - fun beginSetup(endpoint: HermesEndpoint): Job = launchOperation { token -> + /** [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) + 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() @@ -177,7 +167,9 @@ internal class ComputerConnectionModel( requireCurrent(token) publishIndex(snapshot) val row = snapshot.computers.firstOrNull { it.id == id } ?: return@launchOperation - val next = newOwner(id, row.endpoint) + 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() @@ -196,20 +188,21 @@ internal class ComputerConnectionModel( 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 } - if (existing != null && existing.authority != candidate.authority) { - throw HermesException(HermesException.Kind.IdentityChanged) - } - if (snapshot.computers.any { it.id != current.id && it.authority == candidate.authority }) { - mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, problem = ComputerProblem.AlreadyConfigured) - return@launchOperation - } - if (existing == null && snapshot.computers.size >= 32) { - mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignIn, problem = ComputerProblem.ComputerLimit) + 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) } @@ -219,6 +212,9 @@ internal class ComputerConnectionModel( 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) @@ -243,7 +239,7 @@ internal class ComputerConnectionModel( 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() + 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) @@ -254,6 +250,8 @@ internal class ComputerConnectionModel( } } 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) @@ -275,7 +273,9 @@ internal class ComputerConnectionModel( mutableState.value = mutableState.value.copy(phase = ComputerPhase.SignInRequired, selectedID = id) return } - val next = newOwner(id, row.endpoint) + 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) @@ -288,11 +288,11 @@ internal class ComputerConnectionModel( mutableState.value = mutableState.value.copy(phase = ComputerPhase.Connected) } - private fun newOwner(id: UUID, endpoint: HermesEndpoint): Owner { + 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, factory(endpoint, store, ownedScope), job, ownedScope, store) } + return try { Owner(id, endpoint, access, factory(id, endpoint, access, store, ownedScope), job, ownedScope, store) } catch (failure: Exception) { store.invalidate(); job.cancel(); throw failure } } @@ -329,6 +329,15 @@ internal class ComputerConnectionModel( 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) @@ -345,16 +354,34 @@ internal class ComputerConnectionModel( if (owner !== expected || !expected.job.isActive) throw CancellationException("Connection retired") } - private suspend fun retire() = withContext(NonCancellable) { + /** + * 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) { - old.credentials.invalidate() - try { - old.job.cancelAndJoin() - old.session.close() - } finally { old.credentials.awaitIdle() } + 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() } + } + } } } 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/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/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/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/ComputerConnectionModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt index a2c393c0..da28cf2b 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/live/ComputerConnectionModelTest.kt @@ -2,7 +2,9 @@ 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 @@ -12,6 +14,7 @@ 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 @@ -36,12 +39,34 @@ class ComputerConnectionModelTest { 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, - ) { address, credentials, _ -> FakeSession(address, credentials).also { sessions += it; prepare(it) } } + 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) : ComputerSession { + 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 @@ -58,10 +83,20 @@ class ComputerConnectionModelTest { } 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") } @@ -280,4 +315,126 @@ class ComputerConnectionModelTest { 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/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) +} From 943608a7dfa9812ab68479e23cb6fb2e98463c57 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:52:38 -0500 Subject: [PATCH 17/18] Android chat recovers from cancelled sends, queue overflow, socket swaps and double attach Co-Authored-By: Claude Sonnet 5.5 --- .../app/bighelp/hermes/GatewayClient.kt | 24 ++- .../app/bighelp/hermes/chat/ChatGateway.kt | 13 +- .../bighelp/hermes/chat/ConversationEngine.kt | 147 +++++++++++++++--- .../hermes/chat/ConversationRuntime.kt | 20 ++- .../hermes/chat/HermesChatRepository.kt | 18 ++- .../bighelp/hermes/chat/HistoryCacheCodec.kt | 31 +++- .../bighelp/hermes/chat/RuntimeControls.kt | 22 +-- .../app/bighelp/hermes/chat/SessionBinder.kt | 57 +++++-- .../bighelp/hermes/chat/SessionOperations.kt | 4 +- .../bighelp/hermes/chat/SubmissionEngine.kt | 129 +++++++++------ .../app/bighelp/hermes/chat/TurnReducer.kt | 11 +- .../app/bighelp/hermes/FakeTransport.kt | 5 +- .../app/bighelp/hermes/GatewayQueueTest.kt | 18 +++ .../app/bighelp/hermes/GatewayRpcTest.kt | 28 +++- .../kotlin/app/bighelp/hermes/chat/ChatRig.kt | 7 + .../bighelp/hermes/chat/CreateResumeTest.kt | 58 +++++++ .../bighelp/hermes/chat/EventOverflowTest.kt | 92 +++++++++++ .../app/bighelp/hermes/chat/FakeHermesHost.kt | 47 +++++- .../app/bighelp/hermes/chat/GatedChatStore.kt | 27 ++++ .../hermes/chat/GatewayChatIntegrationTest.kt | 33 ++++ .../hermes/chat/HistoryRepositoryTest.kt | 32 +++- .../hermes/chat/SendCancellationTest.kt | 109 +++++++++++++ .../app/bighelp/hermes/chat/SendFlowTest.kt | 22 +++ .../hermes/chat/SingleFlightAttachTest.kt | 80 ++++++++++ .../bighelp/hermes/chat/SocketFenceTest.kt | 70 +++++++++ .../bighelp/hermes/chat/TurnReducerTest.kt | 13 ++ 26 files changed, 993 insertions(+), 124 deletions(-) create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/EventOverflowTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatedChatStore.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendCancellationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SingleFlightAttachTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SocketFenceTest.kt diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt index 17cad7ce..df7c4fb7 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt @@ -416,6 +416,11 @@ class GatewayClient internal constructor( * 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, @@ -423,8 +428,9 @@ class GatewayClient internal constructor( timeoutMillis: Long = timings.requestMillis, operation: GatewayOperation? = null, maximumFrameBytes: Int = DEFAULT_FRAME_BYTES, + generation: Long? = null, ): JsonElement { - val live = withContext(serial) { link } ?: throw notConnected() + val live = withContext(serial) { link?.takeIf { generation == null || it.generation == generation } } ?: throw notConnected() return requestOn(live, method, params, timeoutMillis, operation, maximumFrameBytes) } @@ -574,14 +580,25 @@ class GatewayClient internal constructor( } } - /** Resumes the writer once the socket has taken what it was given. */ + /** + * 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(DRAIN_POLL_MILLIS) else pump(owner) + 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 @@ -909,6 +926,7 @@ class GatewayClient internal constructor( 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/chat/ChatGateway.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt index 789e4c64..cbe64558 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ChatGateway.kt @@ -21,8 +21,12 @@ internal interface ChatGateway { val state: StateFlow val events: Flow - /** One JSON-RPC call; failures are `HermesException`, a cancelled caller gets `RequestCancelledException`. */ - suspend fun request(method: String, params: JsonObject, timeoutMillis: Long? = null): JsonElement + /** + * One JSON-RPC call; failures are `HermesException`, a cancelled caller gets `RequestCancelledException`. + * [generation] is the socket generation a runtime-addressed call was planned on: on any other socket the call + * fails `NotConnected` and nothing is written. + */ + suspend fun request(method: String, params: JsonObject, timeoutMillis: Long? = null, generation: Long? = null): JsonElement suspend fun prepareForAdmission() suspend fun verifyLiveness() @@ -35,8 +39,9 @@ internal class GatewayClientAdapter(private val client: GatewayClient) : ChatGat override val state get() = client.state override val events get() = client.events - override suspend fun request(method: String, params: JsonObject, timeoutMillis: Long?): JsonElement = - if (timeoutMillis == null) client.request(method, params) else client.request(method, params, timeoutMillis) + override suspend fun request(method: String, params: JsonObject, timeoutMillis: Long?, generation: Long?): JsonElement = + if (timeoutMillis == null) client.request(method, params, generation = generation) + else client.request(method, params, timeoutMillis, generation = generation) override suspend fun prepareForAdmission() = client.prepareForAdmission() override suspend fun verifyLiveness() = client.verifyLiveness() diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt index 6073d612..cd57e3eb 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationEngine.kt @@ -5,7 +5,9 @@ import app.bighelp.hermes.GatewayEvent import app.bighelp.hermes.HermesException import app.bighelp.hermes.WireMessage import app.bighelp.hermes.utf8Length +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -51,7 +53,8 @@ internal class ConversationEngine( return ConversationState( ref = rt.ref, title = rt.title, identity = rt.identity, phase = rt.phase, items = rt.savedItems + live, running = rt.reducer.running, status = rt.status, runtime = rt.runtimeInfo, draft = rt.draft, - draftAttachments = rt.draftAttachments, sendBlock = sendBlock(rt), + // A running turn is steered by default, and a steer is not a submission. + draftAttachments = rt.draftAttachments, sendBlock = sendBlock(rt, submission = !rt.reducer.running), unresolved = rt.unresolved.map { UnresolvedSubmission(it.id, it.method, it.composerText, it.attachments, it.createdAtMillis, it.rejectionCode) }, prompts = prompts.statesFor(rt.ref), history = HistoryState(rt.saved?.nextOffset != null, rt.loadingOlder, rt.saved?.rows?.size ?: 0), @@ -59,8 +62,12 @@ internal class ConversationEngine( ) } - /** Why a new message cannot be admitted now; null when it can. Steering a running turn stays open while a send is pending. */ - fun sendBlock(rt: ConversationRuntime): SendBlock? { + /** + * Why a new message cannot be admitted now; null when it can. Steering a running turn stays open while a send is pending. + * [submission] is false for a steer, which is not one of the host's submission methods: only a message that starts, queues + * or runs a turn needs the host's `per_session_exclusive_submit` guarantee. + */ + fun sendBlock(rt: ConversationRuntime, submission: Boolean = true): SendBlock? { val gateway = ctx.gateway.state.value val binding = rt.binding return when { @@ -68,9 +75,11 @@ internal class ConversationEngine( gateway.connection != GatewayConnection.Connected -> SendBlock.NotConnected binding == null || rt.requiresReattach -> SendBlock.NoLiveSession binding.generation != gateway.generation -> SendBlock.NotConnected + // Suspended means this chat's transcript may have a hole (events were dropped, or the host reclaimed its runtime). + rt.phase == ConversationPhase.Suspended -> SendBlock.NoLiveSession rt.hydrating -> SendBlock.CatchingUp rt.needsRecovery -> SendBlock.RecoveryRequired - gateway.capabilities?.perSessionExclusiveSubmit != true -> SendBlock.HostLacksExclusiveSubmit + submission && gateway.capabilities?.perSessionExclusiveSubmit != true -> SendBlock.HostLacksExclusiveSubmit rt.pending != null && !rt.reducer.running -> SendBlock.PendingAdmission rt.unresolved.size >= ChatStoreLimits.MAXIMUM_UNRESOLVED_ENTRIES -> SendBlock.TooManyUnresolved else -> null @@ -130,8 +139,10 @@ internal class ConversationEngine( /** A stored copy of the newest page, shown at once. It never replaces anything once live events advanced the cursor. */ private suspend fun seedFromCache(rt: ConversationRuntime) { val bytes = ctx.store.read(RecordKey.history(rt.scope)) ?: return - val cached = runCatching { HistoryCacheCodec.decode(bytes) }.getOrNull() ?: return + val cached = runCatching { HistoryCacheCodec.decode(bytes, rt.scope) }.getOrNull() ?: return ctx.onState { + // Another conversation's rows are never this one's: the window must be of an ID this chat has had. + if (!rt.identity.knows(cached.storedId)) return@onState if (rt.saved == null && rt.reducer.lastSequence == 0L && !rt.reducer.hasLiveEvents) { setSaved(rt, cached, persist = false) publish(rt) @@ -139,8 +150,41 @@ internal class ConversationEngine( } } - /** Resume by stored ID on the current socket and recover coverage. Failure leaves the transcript and marks the chat suspended. */ + /** + * Resume by stored ID on the current socket and recover coverage. Failure leaves the transcript and marks the chat suspended. + * One attach runs per conversation and socket: a caller that arrives while it runs (a second screen, [open], the socket's own + * re-attach) joins it instead of resuming and recovering the same chat again. An attach for an older socket is never joined. + */ suspend fun attach(rt: ConversationRuntime) { + val flight = ctx.onState { + val generation = ctx.gateway.state.value.generation + rt.attachFlight?.let { current -> + if (current.generation == generation && current.done.isActive && !current.superseded) return@onState current + current.superseded = true + } + val started = AttachFlight(generation) + rt.attachFlight = started + // The flight is the repository's, not a caller's: a screen going away must not abandon a half-made attach for the others. + val job = ctx.scope.launch { + try { + attachOnce(rt, started) + finishAttach(rt, started, null) + } catch (e: Throwable) { + finishAttach(rt, started, e) + } + } + job.invokeOnCompletion { cause -> if (cause != null) started.done.completeExceptionally(cause) } + started + } + flight.done.await() + } + + private suspend fun finishAttach(rt: ConversationRuntime, flight: AttachFlight, failure: Throwable?) { + withContext(NonCancellable + ctx.serial) { if (rt.attachFlight === flight) rt.attachFlight = null } + if (failure == null) flight.done.complete(Unit) else flight.done.completeExceptionally(failure) + } + + private suspend fun attachOnce(rt: ConversationRuntime, flight: AttachFlight) { val state = ctx.gateway.state.value if (state.connection != GatewayConnection.Connected) { ctx.onState { suspendLocal(rt, ConversationPhase.Suspended); publish(rt) } @@ -153,9 +197,9 @@ internal class ConversationEngine( } try { val tip = ctx.onState { rt.identity.storedTip } - val attached = binder.resume(rt.scope.profile, tip) + val attached = binder.resume(rt.scope.profile, tip, generation) val proceed = ctx.onState { - if (conversations[rt.ref] !== rt || ctx.gateway.state.value.generation != generation) return@onState false + if (conversations[rt.ref] !== rt || ctx.gateway.state.value.generation != generation || flight.superseded) return@onState false val before = rt.binding if (attached.storedId != rt.identity.storedTip) { if (!IdentityAdoption.accepts(rt.identity, attached.storedId, IdentityAdoption.Evidence.ResumeOfCurrentTip)) throw ChatException(ChatError.Kind.InvalidResponse) @@ -165,6 +209,8 @@ internal class ConversationEngine( if (before != null && before.runtimeId != attached.runtimeId) rt.reducer.resetCursor("", 0) rt.binding = Binding(attached.runtimeId, attached.storedId, generation, null, rt.scope.profile) rt.requiresReattach = false + // Admission stays closed from here until the bracket below has covered the chat, whatever an earlier attach did to the flag. + rt.hydrating = true applyInfo(rt, attached.info) true } @@ -172,11 +218,11 @@ internal class ConversationEngine( persistIdentity(rt) recover(rt, generation) } catch (e: ChatException) { - fail(rt, e.error) + failUnlessSuperseded(rt, e.error, generation, flight) } catch (e: HermesException) { - fail(rt, SessionBinder.chatError(e).let { if (e.kind == HermesException.Kind.RpcRejected && (e.code == 4007L || e.code == 404L)) ChatError(ChatError.Kind.NotOpen, e.kind, e.code, e.reason) else it }) + failUnlessSuperseded(rt, SessionBinder.chatError(e).let { if (e.kind == HermesException.Kind.RpcRejected && (e.code == 4007L || e.code == 404L)) ChatError(ChatError.Kind.NotOpen, e.kind, e.code, e.reason) else it }, generation, flight) } catch (e: app.bighelp.hermes.RequestCancelledException) { - fail(rt, ChatError(ChatError.Kind.Cancelled)) + failUnlessSuperseded(rt, ChatError(ChatError.Kind.Cancelled), generation, flight) return } // Reading saved history is not part of coverage: a failure here leaves the chat usable, with the error shown. @@ -200,6 +246,12 @@ internal class ConversationEngine( } } + /** A failure of work done for [generation] says nothing about a newer socket, or a newer attach, which own the chat now. */ + private suspend fun failUnlessSuperseded(rt: ConversationRuntime, error: ChatError, generation: Long, flight: AttachFlight? = null) { + if (ctx.onState { ctx.gateway.state.value.generation != generation || flight?.superseded == true }) return + fail(rt, error) + } + private fun persistIdentityLater(rt: ConversationRuntime) { ctx.scope.launch { persistIdentity(rt) } } private suspend fun persistIdentity(rt: ConversationRuntime) { @@ -241,9 +293,28 @@ internal class ConversationEngine( publishAll() } + /** + * The event stream dropped events (the collector fell too far behind) while the socket itself carried on. Every chat that + * is, or may be, bound now has a hole that no later event announces: admission closes, the binding is no longer trusted and + * the next [reattachAll] resumes each chat by its stored ID and covers it again. + */ + fun onEventsLost() { + for (rt in conversations.values) { + // The socket is the same one: the host's open questions are still open on it, so they stay answerable. + suspendLocal(rt, ConversationPhase.Suspended, retirePrompts = false) + rt.requiresReattach = true + rt.needsRecovery = true + // An attach already running may have read its replay before the loss: it cannot vouch for the chat, so the next one starts afresh. + rt.attachFlight?.superseded = true + rt.attachFlight = null + } + publishAll() + } + /** A conversation just created: bound from the create answer itself, then covered like any other. */ suspend fun adoptCreated(ref: ConversationRef, attached: Attached, title: String): ConversationRuntime { - val generation = ctx.gateway.state.value.generation + // The runtime ID belongs to the socket the create was fenced to, whichever socket is current by now. + val generation = attached.generation ?: ctx.gateway.state.value.generation val scope = ctx.conversationScope(ref) val rt = ConversationRuntime(scope, ConversationIdentity(ref, attached.storedId), title) ctx.onState { @@ -253,9 +324,15 @@ internal class ConversationEngine( applyInfo(rt, attached.info) publish(rt) } + if (ctx.gateway.state.value.generation != generation) { + // The socket was replaced before the answer was applied: that runtime is not reachable here. Resume the chat by its stored ID. + ctx.onState { suspendLocal(rt, ConversationPhase.Recovering); rt.requiresReattach = true; rt.hydrating = true; publish(rt) } + attach(rt) + return rt + } try { recover(rt, generation) - } catch (e: ChatException) { fail(rt, e.error) } catch (e: HermesException) { fail(rt, SessionBinder.chatError(e)) } + } catch (e: ChatException) { failUnlessSuperseded(rt, e.error, generation) } catch (e: HermesException) { failUnlessSuperseded(rt, SessionBinder.chatError(e), generation) } return rt } @@ -263,7 +340,7 @@ internal class ConversationEngine( * Revokes transport authority, not the visible transcript: held events are dropped, prompts retire, and an * already confirmed admission keeps its evidence so an exact replay of its terminal can settle it later. */ - fun suspendLocal(rt: ConversationRuntime, phase: ConversationPhase) { + fun suspendLocal(rt: ConversationRuntime, phase: ConversationPhase, retirePrompts: Boolean = true) { rt.pending?.let { pending -> if (pending.admitted && !pending.overlapped) pending.selectedTurn?.let { rt.acceptedEvidence = AcceptedEvidence(pending.entry.id, it, rt.reducer.epoch) } rt.needsRecovery = true @@ -274,7 +351,7 @@ internal class ConversationEngine( rt.heldEvents = ArrayList() rt.heldOverflow = false rt.stopRequested = false - prompts.retireFor(rt.ref) + if (retirePrompts) prompts.retireFor(rt.ref) rt.status = null } @@ -382,6 +459,34 @@ internal class ConversationEngine( * when every held live event extends the accepted cursor without a gap. Never resumes or resends a prompt. */ suspend fun recover(rt: ConversationRuntime, generation: Long) { + // One bracket per runtime and socket: a second caller (a reopen, the recovery after a lost send) joins the one already + // running instead of replaying and activating the same chat again from a snapshot that is older than the first's events. + var started: RecoveryFlight? = null + val running = ctx.onState { + val binding = rt.binding ?: throw ChatException(ChatError.Kind.NoLiveSession) + if (binding.generation != generation) throw ChatException(ChatError.Kind.NotConnected) + rt.recoveryFlight?.takeIf { it.generation == generation && it.runtimeId == binding.runtimeId && it.done.isActive }?.let { return@onState it } + started = RecoveryFlight(generation, binding.runtimeId).also { rt.recoveryFlight = it } + null + } + if (running != null) { + running.done.await() + return + } + val mine = started!! + try { + recoverOnce(rt, generation) + mine.done.complete(Unit) + } catch (e: Throwable) { + // A joiner must not mistake the first caller's cancellation for its own. + mine.done.completeExceptionally(if (e is kotlin.coroutines.cancellation.CancellationException) ChatException(ChatError.Kind.Cancelled) else e) + throw e + } finally { + withContext(NonCancellable + ctx.serial) { if (rt.recoveryFlight === mine) rt.recoveryFlight = null } + } + } + + private suspend fun recoverOnce(rt: ConversationRuntime, generation: Long) { val profile = rt.scope.profile val (runtimeId, hint, checkpoint, knownEpoch) = ctx.onState { val binding = rt.binding ?: throw ChatException(ChatError.Kind.NoLiveSession) @@ -391,11 +496,11 @@ internal class ConversationEngine( } var succeeded = false try { - val before = eventsSince(runtimeId, if (hint == knownEpoch) checkpoint else 0) - val snapshot = binder.activate(profile, runtimeId) + val before = eventsSince(runtimeId, if (hint == knownEpoch) checkpoint else 0, generation) + val snapshot = binder.activate(profile, runtimeId, generation) ctx.onState { requireCurrent(rt, generation, runtimeId) } val attached = validatedActivation(snapshot, runtimeId, profile) - val tail = eventsSince(runtimeId, before.latest) + val tail = eventsSince(runtimeId, before.latest, generation) if (tail.epoch != before.epoch) throw invalidResponse() ctx.onState { requireCurrent(rt, generation, runtimeId) } val modern = tail.openRequests != null @@ -463,8 +568,8 @@ internal class ConversationEngine( private class Replay(val epoch: String, val latest: Long, val truncated: Boolean?, val events: List, val openRequests: JsonElement?) - private suspend fun eventsSince(runtimeId: String, lastSeen: Long): Replay { - val result = ctx.gateway.request("session.events.since", buildJsonObject { put("session_id", runtimeId); put("last_seen", lastSeen) }).asObject ?: throw invalidResponse() + private suspend fun eventsSince(runtimeId: String, lastSeen: Long, generation: Long): Replay { + val result = ctx.gateway.request("session.events.since", buildJsonObject { put("session_id", runtimeId); put("last_seen", lastSeen) }, generation = generation).asObject ?: throw invalidResponse() val epoch = result["epoch"].asString ?: throw invalidResponse() val latest = result["latest_seq"].asLong?.takeIf { it >= 0 } ?: throw invalidResponse() val events = (result["events"].asArray ?: JsonArray(emptyList())).mapNotNull { frame -> @@ -593,7 +698,7 @@ internal class ConversationEngine( rt.savedItems = HistoryProjection.project(window.rows).items historyCache.put(rt.ref, window) if (persist) { - val bytes = HistoryCacheCodec.encode(window) + val bytes = HistoryCacheCodec.encode(window, rt.scope) ctx.scope.launch { ctx.store.putCache(RecordKey.history(rt.scope), bytes) } } } diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt index 25109c14..9f2d9956 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/ConversationRuntime.kt @@ -1,6 +1,7 @@ package app.bighelp.hermes.chat import app.bighelp.hermes.WireMessage +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.withContext @@ -51,6 +52,22 @@ internal class PendingAdmission(val entry: JournalEntry, val isCommand: Boolean, /** A confirmed admission whose local waiter ended with the socket; exact same-epoch terminal replay can settle it. */ internal class AcceptedEvidence(val entryId: String, val turnId: String, val epoch: String) +/** + * The one attach (resume by stored ID, then the recovery bracket, then the newest history page) running for a + * conversation on one socket generation. Every other caller for the same generation joins [done]. + */ +internal class AttachFlight(val generation: Long) { + val done = CompletableDeferred() + + /** Set when something happened that this attach cannot cover (a newer socket, dropped events): it then leaves the decisions to the next one. */ + @Volatile var superseded = false +} + +/** The one recovery bracket running for a runtime on a socket; a caller asking for the same one joins [done]. */ +internal class RecoveryFlight(val generation: Long, val runtimeId: String) { + val done = CompletableDeferred() +} + /** Mutable state of one conversation. Touched only on the serial dispatcher. */ internal class ConversationRuntime(val scope: ConversationScope, var identity: ConversationIdentity, var title: String) { val ref: ConversationRef get() = scope.ref @@ -77,7 +94,8 @@ internal class ConversationRuntime(val scope: ConversationScope, var identity: C var hydrating = false var heldEvents = ArrayList() var heldOverflow = false - var recoveryJobActive = false + var attachFlight: AttachFlight? = null + var recoveryFlight: RecoveryFlight? = null var hasRecovered = false var status: String? = null diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt index 83a7afc2..895c6942 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HermesChatRepository.kt @@ -127,7 +127,14 @@ class HermesChatRepository private constructor(wiring: Wiring) : AutoCloseable { */ suspend fun createChat(profile: String, request: CreateRequest = CreateRequest(), retryIntent: String? = null): CreateOutcome { if (!Coordinates.isValid(profile, Coordinates.MAXIMUM_PROFILE_BYTES)) return CreateOutcome.Failed(ChatError(ChatError.Kind.InvalidInput)) - val outcome = when (val step = binder.createOrdinary(profile, request, retryIntent)) { + // A cancelled caller still changed the book (an intent kept or dropped): the list people see follows it. + val step = try { + binder.createOrdinary(profile, request, retryIntent) + } catch (e: kotlin.coroutines.cancellation.CancellationException) { + mutablePending.value = creations.pending() + throw e + } + val outcome = when (step) { is CreateStep.Failed -> CreateOutcome.Failed(step.error) is CreateStep.Unconfirmed -> CreateOutcome.Unconfirmed(step.intentId, step.error) is CreateStep.Created -> { @@ -170,7 +177,12 @@ class HermesChatRepository private constructor(wiring: Wiring) : AutoCloseable { } val outcome: BotChatStep = when { chat != null -> BotChatStep.Registered(chat) - createIfMissing -> binder.createFirstBotChat(profile) + createIfMissing -> try { + binder.createFirstBotChat(profile) + } catch (e: kotlin.coroutines.cancellation.CancellationException) { + mutablePending.value = creations.pending() + throw e + } else -> return BotChatOutcome.NotCreated } mutablePending.value = creations.pending() @@ -314,7 +326,7 @@ class HermesChatRepository private constructor(wiring: Wiring) : AutoCloseable { return } catch (e: HermesException) { // The collector fell too far behind: events were lost. Close admission and reattach everything. - ctx.onState { engine.onDisconnected() } + ctx.onState { engine.onEventsLost() } ctx.scope.launch { reattachWhenConnected(ctx.gateway.state.value.generation) } } } diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt index d7f842c8..f8e96ac3 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/HistoryCacheCodec.kt @@ -1,19 +1,36 @@ package app.bighelp.hermes.chat import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put -/** The newest retained rows of one chat, stored only to show something at once. Losing it changes nothing durable. */ +/** + * The newest retained rows of one chat, stored only to show something at once. Losing it changes nothing durable. + * Like every other record, the body repeats its exact scope and a decode checks it against the key's scope, so a + * mis-addressed or stale file can never show one conversation's text as another's. + */ internal object HistoryCacheCodec { - fun encode(window: HistoryWindow): ByteArray = buildJsonObject { - put("v", 1); put("stored", window.storedId); put("next", window.nextOffset) - put("rows", JsonArray(window.rows.map { it.raw })) - }.toString().toByteArray(Charsets.UTF_8) + private const val SCHEMA = 2 - fun decode(bytes: ByteArray): HistoryWindow { + fun encode(window: HistoryWindow, scope: ConversationScope): ByteArray = JsonObject( + buildJsonObject { + put("v", SCHEMA); put("stored", window.storedId); put("next", window.nextOffset) + put("rows", JsonArray(window.rows.map { it.raw })) + } + mapOf( + "computer" to JsonPrimitive(scope.host.computerId), "endpoint" to JsonPrimitive(scope.host.endpoint), + "principal" to JsonPrimitive(scope.host.principal), "profile" to JsonPrimitive(scope.profile), + "anchor" to JsonPrimitive(scope.anchor), + ), + ).toString().toByteArray(Charsets.UTF_8) + + fun decode(bytes: ByteArray, scope: ConversationScope): HistoryWindow { val body = parseRecord(bytes) - if (body["v"].asInt != 1) corrupt() + if (body["v"].asInt != SCHEMA) corrupt() + if (body["computer"].asString != scope.host.computerId || body["endpoint"].asString != scope.host.endpoint || + body["principal"].asString != scope.host.principal || body["profile"].asString != scope.profile || body["anchor"].asString != scope.anchor + ) corrupt() val stored = body["stored"].asString ?: corrupt() val rows = (body["rows"].asArray ?: corrupt()).map { HistoryRow.parse(it, stored) } if (rows.map { it.id }.toSet().size != rows.size) corrupt() diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt index 09e6666b..28a082cc 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/RuntimeControls.kt @@ -40,7 +40,7 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: private suspend fun proof(rt: ConversationRuntime, binding: Binding): Proof { val response = ctx.gateway.request("session.activate", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile); put("omit_messages", true) - }).asObject ?: throw invalidResponse() + }, generation = binding.generation).asObject ?: throw invalidResponse() val info = response["info"].asObject val stored = response["session_key"].asString if (response["session_id"].asString != binding.runtimeId || stored == null || !rt.identity.knows(stored) || @@ -62,7 +62,7 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: suspend fun options(ref: ConversationRef): ModelOptions = mapErrors { val (rt, binding) = live(ref) val current = proof(rt, binding) - val catalog = ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }) + val catalog = ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }, generation = binding.generation) ctx.onState { stale(rt, binding) } ModelOptions(current.model, current.provider.ifEmpty { null }, current.reasoning, current.tier, current.running, decodeProviders(catalog)) } @@ -97,7 +97,7 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: put("profile", binding.profile); put("session_id", binding.runtimeId) put("key", "model"); put("value", "$model --provider $provider --session") if (confirmed) put("confirm_expensive_model", true) - }).asObject ?: throw invalidResponse() + }, generation = binding.generation).asObject ?: throw invalidResponse() ctx.onState { stale(rt, binding) } val needsConfirmation = response["confirm_required"].asBool if (response["key"].asString != "model" || response["scope"].asString != "session" || needsConfirmation == null || response?.get("value").asString == null) throw invalidResponse() @@ -122,7 +122,7 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: /** A catalog can list a provider under an alias slug while the runtime reports its canonical ID; a fresh read must mark the chosen slug current. */ private suspend fun catalogMarksCurrent(binding: Binding, provider: String, model: String): Boolean { - val response = ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }) + val response = ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }, generation = binding.generation) if (response.asObject?.get("model").asString != model) return false val current = decodeProviders(response).filter { it.isCurrent } return current.size == 1 && current[0].id == provider @@ -141,10 +141,10 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: private suspend fun writeReasoning(binding: Binding, level: String, rt: ConversationRuntime) { val set = ctx.gateway.request("config.set", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "reasoning"); put("value", level); put("scope", "session") - }).asObject + }, generation = binding.generation).asObject ctx.onState { stale(rt, binding) } if (set?.get("key").asString != "reasoning" || set?.get("value").asString != level) throw ChatException(ChatError.Kind.OutcomeUnknown) - val read = ctx.gateway.request("config.get", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "reasoning") }).asObject + val read = ctx.gateway.request("config.get", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "reasoning") }, generation = binding.generation).asObject ctx.onState { stale(rt, binding) } if (read?.get("value").asString != level) throw ChatException(ChatError.Kind.OutcomeUnknown) } @@ -154,16 +154,16 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: val (rt, binding) = live(ref) val before = proof(rt, binding) if (before.running) throw ChatException(ChatError.Kind.Conflict) - val catalog = decodeProviders(ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) })) + val catalog = decodeProviders(ctx.gateway.request("model.options", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId) }, generation = binding.generation)) val supported = catalog.firstOrNull { it.id == before.provider }?.fastModels?.contains(before.model) == true if (!supported) throw ChatException(ChatError.Kind.Unsupported) ctx.onState { stale(rt, binding) } val value = if (on) "fast" else "normal" val set = ctx.gateway.request("config.set", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "fast"); put("value", value); put("scope", "session") - }).asObject + }, generation = binding.generation).asObject if (set?.get("key").asString != "fast" || tierIsFast(set?.get("value").asString) != on) throw ChatException(ChatError.Kind.OutcomeUnknown) - val read = ctx.gateway.request("config.get", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "fast") }).asObject + val read = ctx.gateway.request("config.get", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "fast") }, generation = binding.generation).asObject ctx.onState { stale(rt, binding) } if (tierIsFast(read?.get("value").asString) != on) throw ChatException(ChatError.Kind.OutcomeUnknown) ctx.onState { rt.runtimeInfo = rt.runtimeInfo.merged(RuntimeInfo(serviceTier = value)); engine.publish(rt) } @@ -180,7 +180,7 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: val (rt, binding) = live(ref) val response = ctx.gateway.request("config.set", buildJsonObject { put("profile", binding.profile); put("session_id", binding.runtimeId); put("key", "yolo"); put("value", if (on) "on" else "off"); put("scope", "session") - }).asObject + }, generation = binding.generation).asObject ctx.onState { stale(rt, binding) } if (response?.get("key").asString != "yolo" || response?.get("value").asString != (if (on) "1" else "0")) throw ChatException(ChatError.Kind.OutcomeUnknown) } @@ -189,7 +189,7 @@ internal class RuntimeControls(private val ctx: ChatContext, private val engine: suspend fun commands(ref: ConversationRef): List = mapErrors { val (_, binding) = live(ref) - SlashCommandCatalog.decode(ctx.gateway.request("commands.catalog", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile) })) + SlashCommandCatalog.decode(ctx.gateway.request("commands.catalog", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile) }, generation = binding.generation)) } /** The commands a new chat would have, before it exists (Code mode's `/` list). Bound to the profile, and to a folder for project-local skills. */ diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt index 41a77b0e..63c0fe01 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionBinder.kt @@ -4,13 +4,22 @@ import app.bighelp.hermes.HermesException import app.bighelp.hermes.RequestCancelledException import app.bighelp.hermes.DispatchOutcome import java.util.UUID +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put -/** The coordinates a create or resume answer proved, ready to become a [Binding]. */ -internal class Attached(val runtimeId: String, val storedId: String, val running: Boolean?, val info: JsonObject, val model: String?, val cwd: String?) +/** + * The coordinates a create or resume answer proved, ready to become a [Binding]. [generation] is the socket the + * request was fenced to: the runtime ID belongs to that socket and to no later one (null: not from a request). + */ +internal data class Attached( + val runtimeId: String, val storedId: String, val running: Boolean?, val info: JsonObject, val model: String?, val cwd: String?, + val generation: Long? = null, +) /** * The create intents of this computer, one per profile, written before `session.create` leaves and updated as @@ -46,7 +55,14 @@ internal class CreationBook(private val ctx: ChatContext) { } suspend fun remove(profile: String) { - runCatching { ctx.store.commit(listOf(StoreOp.Delete(RecordKey.creation(ctx.host, profile)))) } + try { + ctx.store.commit(listOf(StoreOp.Delete(RecordKey.creation(ctx.host, profile)))) + } catch (e: CancellationException) { + // The record stays where it is, in memory and on disk alike; a caller that needs it gone finishes this uncancellably. + throw e + } catch (_: Exception) { + // A failed delete leaves a stale intent that the next create reconciles; the in-memory book still lets go. + } records.remove(profile) } } @@ -59,27 +75,31 @@ internal class SessionBinder(private val ctx: ChatContext, val creations: Creati // ---- resume - /** `session.resume` of a stored ID (never the runtime ID), with the app's source. A rejected optional field is retried once without it. */ - suspend fun resume(profile: String, storedId: String): Attached { + /** + * `session.resume` of a stored ID (never the runtime ID), with the app's source. A rejected optional field is retried once without it. + * The call is fenced to [generation] (default: the socket as it is now), so a runtime is never made on a socket the caller did not plan for. + */ + suspend fun resume(profile: String, storedId: String, generation: Long? = null): Attached { + val fence = generation ?: ctx.gateway.state.value.generation val base = buildJsonObject { put("session_id", storedId); put("profile", profile); put("source", SOURCE) put("defer_history", true); put("omit_messages", true) } val withLifetime = JsonObject(base + ("close_on_disconnect" to kotlinx.serialization.json.JsonPrimitive(false))) val result = try { - ctx.gateway.request("session.resume", withLifetime) + ctx.gateway.request("session.resume", withLifetime, generation = fence) } catch (e: HermesException) { // An older host refuses a field it does not know before doing anything; the plain resume is the same request. - if (e.kind == HermesException.Kind.RpcRejected && e.code == 4000L) ctx.gateway.request("session.resume", base) else throw e + if (e.kind == HermesException.Kind.RpcRejected && e.code == 4000L) ctx.gateway.request("session.resume", base, generation = fence) else throw e } - return decodeAttached(result, profile, requireStoredAlias = false) + return decodeAttached(result, profile, requireStoredAlias = false).copy(generation = fence) } /** `session.activate` of an already proved runtime: attaches and touches it, never builds or creates one. */ - suspend fun activate(profile: String, runtimeId: String): JsonObject { + suspend fun activate(profile: String, runtimeId: String, generation: Long): JsonObject { val result = ctx.gateway.request("session.activate", buildJsonObject { put("session_id", runtimeId); put("profile", profile); put("omit_messages", true) - }) + }, generation = generation) return result.asObject ?: throw invalidResponse() } @@ -112,21 +132,30 @@ internal class SessionBinder(private val ctx: ChatContext, val creations: Creati /** Sends the create under [record]'s key and proves what came back. */ private suspend fun dispatchCreate(record: CreationRecord): CreateStep { + // The socket this create is planned on: the answer's runtime ID belongs to it and to no later socket. + val generation = ctx.gateway.state.value.generation var sendExplicitCwd = record.request.cwd != null var answer: JsonElement? = null while (answer == null) { try { - answer = ctx.gateway.request("session.create", createParams(record, sendExplicitCwd)) + answer = ctx.gateway.request("session.create", createParams(record, sendExplicitCwd), generation = generation) } catch (e: HermesException) { // Only an explicit rejection of cwd_explicit authorizes a retry without it: a timeout or lost reply does not. if (sendExplicitCwd && e.kind == HermesException.Kind.RpcRejected && e.code == 4000L) { sendExplicitCwd = false; continue } return afterFailedCreate(record, e.outcomeUnknown, chatError(e)) } catch (e: RequestCancelledException) { - return afterFailedCreate(record, e.dispatch == DispatchOutcome.MayHaveBeenSent, ChatError(ChatError.Kind.Cancelled)) + // The caller is gone, but how far the frame got still decides the intent: kept for a retry when it may have + // reached the host, dropped (on disk too) when it did not. That finishes first; then the cancellation goes on. + try { + withContext(NonCancellable) { afterFailedCreate(record, e.dispatch == DispatchOutcome.MayHaveBeenSent, ChatError(ChatError.Kind.Cancelled)) } + } catch (_: CancellationException) { + // The settlement above ran to completion; the caller's own cancellation is rethrown below. + } + throw e } } val attached = try { - decodeAttached(answer, record.profile, requireStoredAlias = true, requireEmpty = true) + decodeAttached(answer, record.profile, requireStoredAlias = true, requireEmpty = true).copy(generation = generation) } catch (e: HermesException) { // The host answered something unusable: whether it created a chat is unknown. Keep the intent. return CreateStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.InvalidResponse)) @@ -242,7 +271,7 @@ internal class SessionBinder(private val ctx: ChatContext, val creations: Creati val titling = record!!.copy(phase = CreationPhase.TitleRequested, storedSessionId = attached!!.storedId, runtimeSessionId = attached.runtimeId) try { creations.save(titling) } catch (e: ChatStoreException) { return BotChatStep.Failed(ChatError(ChatError.Kind.PersistenceFailed)) } try { - val reply = ctx.gateway.request("session.title", buildJsonObject { put("session_id", attached.runtimeId); put("title", "Bot Chat") }).asObject + val reply = ctx.gateway.request("session.title", buildJsonObject { put("session_id", attached.runtimeId); put("title", "Bot Chat") }, generation = attached.generation).asObject if (reply?.get("pending").asBool != false || reply?.get("title").asString != "Bot Chat") { return BotChatStep.Unconfirmed(record.intentId, ChatError(ChatError.Kind.CreationUnconfirmed)) } diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt index e9171b7d..c5bdd94c 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SessionOperations.kt @@ -50,7 +50,7 @@ internal class SessionOperations( if (released?.get("hidden").asBool != false || released?.get("session_key").asString.isNullOrEmpty()) throw ChatException(ChatError.Kind.InvalidResponse) binder.canonical.remove(ref.profile) } - val reply = ctx.gateway.request("session.title", buildJsonObject { put("session_id", binding.runtimeId); put("title", trimmed) }).asObject + val reply = ctx.gateway.request("session.title", buildJsonObject { put("session_id", binding.runtimeId); put("title", trimmed) }, generation = binding.generation).asObject ctx.onState { if (rt.binding != binding) throw ChatException(ChatError.Kind.NotConnected) } if (reply?.get("pending").asBool != false || reply?.get("title").asString != trimmed) throw ChatException(ChatError.Kind.OutcomeUnknown) ctx.onState { rt.title = trimmed; engine.publish(rt) } @@ -138,7 +138,7 @@ internal class SessionOperations( if (messages.isEmpty() || messages.last().first != throughRowId || messages.none { it.second == "user" } || messages.size > 50_000) throw ChatException(ChatError.Kind.InvalidInput) val parentStored = ctx.onState { rt.identity.storedTip } val title = forkTitle(rt.title) - val reply = ctx.gateway.request("session.branch", buildJsonObject { put("session_id", binding.runtimeId); put("count", messages.size); put("name", title) }).asObject + val reply = ctx.gateway.request("session.branch", buildJsonObject { put("session_id", binding.runtimeId); put("count", messages.size); put("name", title) }, generation = binding.generation).asObject ?: throw invalidResponse() val childRuntime = reply["session_id"].asString ?: throw invalidResponse() val childStored = reply["stored_session_id"].asString?.takeIf { Coordinates.isValid(it) } ?: throw invalidResponse() diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt index eb921322..b2879c29 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/SubmissionEngine.kt @@ -57,67 +57,107 @@ internal class SubmissionEngine(private val ctx: ChatContext, private val engine if (text.isBlank()) return notSent(ChatError.Kind.InvalidInput) if (utf8Length(text) > ChatStoreLimits.MAXIMUM_MESSAGE_TEXT_BYTES) return notSent(ChatError.Kind.TooLarge) if (attachments.size > ChatStoreLimits.MAXIMUM_ATTACHMENT_REFERENCES) return notSent(ChatError.Kind.TooLarge) - val plan = when (val planned = ctx.onState { plan(ref, text, mode, attachments, selection) }) { - is Planned.Stop -> return planned.result - is Planned.Go -> planned.plan - } - val rt = plan.rt - try { - ctx.gateway.prepareForAdmission() - } catch (e: HermesException) { - release(plan) - return SendResult.NotSent(SessionBinder.chatError(e)) + // Planning reserves the admission slot on the serial dispatcher. A caller cancelled just as the plan comes back never sees + // it, so the plan is also noted here and its slot is freed in that case. + var reserved: Plan? = null + val plan = try { + when (val planned = ctx.onState { plan(ref, text, mode, attachments, selection).also { if (it is Planned.Go) reserved = it.plan } }) { + is Planned.Stop -> return planned.result + is Planned.Go -> planned.plan + } } catch (e: CancellationException) { - withContext(NonCancellable) { release(plan) } + reserved?.let { withContext(NonCancellable) { release(it) } } throw e } - val stillOwner = ctx.onState { - engine.conversations[plan.rt.ref] === rt && rt.binding == plan.binding && rt.binding?.generation == ctx.gateway.state.value.generation && - !rt.hydrating && !rt.needsRecovery && (plan.pending == null || rt.pending === plan.pending) - } - if (!stillOwner) { - release(plan) - return SendResult.NotSent(ChatError(ChatError.Kind.NotConnected)) - } - - // Journal first. A write failure, also an oversize record, sends nothing. + val rt = plan.rt + // Until the journal entry is durable, nothing exists but the reserved slot: a cancelled caller only gives it back. try { - val ops = ArrayList() - ops += StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), plan.entry.encode()) - if (plan.clearsDraft) ops += engine.draftOp(rt.scope, "", emptyList()) - engine.commit(ops) - } catch (e: ChatStoreException) { - release(plan) - return SendResult.NotSent(ChatError(if (e.kind == ChatStoreException.Kind.TooLarge) ChatError.Kind.TooLarge else ChatError.Kind.PersistenceFailed)) + try { + ctx.gateway.prepareForAdmission() + } catch (e: HermesException) { + release(plan) + return SendResult.NotSent(SessionBinder.chatError(e)) + } + val stillOwner = ctx.onState { + engine.conversations[plan.rt.ref] === rt && rt.binding == plan.binding && rt.binding?.generation == ctx.gateway.state.value.generation && + !rt.hydrating && !rt.needsRecovery && (plan.pending == null || rt.pending === plan.pending) + } + if (!stillOwner) { + release(plan) + return SendResult.NotSent(ChatError(ChatError.Kind.NotConnected)) + } + + // Journal first. A write failure, also an oversize record, sends nothing. + try { + val ops = ArrayList() + ops += StoreOp.Put(RecordKey.journal(rt.scope, plan.entry.id), plan.entry.encode()) + if (plan.clearsDraft) ops += engine.draftOp(rt.scope, "", emptyList()) + engine.commit(ops) + } catch (e: ChatStoreException) { + release(plan) + return SendResult.NotSent(ChatError(if (e.kind == ChatStoreException.Kind.TooLarge) ChatError.Kind.TooLarge else ChatError.Kind.PersistenceFailed)) + } } catch (e: CancellationException) { withContext(NonCancellable) { release(plan) } throw e } - ctx.onState { - rt.unresolved += plan.entry - if (plan.clearsDraft) { rt.draft = ""; rt.draftAttachments = emptyList() } - rt.reducer.addLocalUser(plan.entry.id, text) - engine.publish(rt) + + // The entry is durable from here. Whatever happens to the caller, the bookkeeping that follows must complete: a cancelled + // send that skipped it would leave the admission slot taken, the entry out of reach of review and a second bubble on screen. + var cancelled: CancellationException? = null + val shown = uncancellably { + ctx.onState { + rt.unresolved += plan.entry + if (plan.clearsDraft) { rt.draft = ""; rt.draftAttachments = emptyList() } + rt.reducer.addLocalUser(plan.entry.id, text) + engine.publish(rt) + } } + shown.cancellation?.let { cancelled = it } - val outcome = try { + val outcome: Outcome = if (cancelled != null) { + // Cancelled before the frame could be written: nothing was dispatched. + Outcome.NotSent(ChatError(ChatError.Kind.Cancelled)) + } else try { dispatch(plan, text) } catch (e: CancellationException) { - val sent = (e as? RequestCancelledException)?.dispatch == DispatchOutcome.MayHaveBeenSent || (e !is RequestCancelledException && plan.dispatched) - withContext(NonCancellable) { settle(plan, if (sent) Outcome.Uncertain(ChatError(ChatError.Kind.Cancelled)) else Outcome.NotSent(ChatError(ChatError.Kind.Cancelled))) } - throw e + cancelled = e + // The request itself says how far it got; any other cancellation counts as sent once a frame was begun. + val sent = if (e is RequestCancelledException) e.dispatch == DispatchOutcome.MayHaveBeenSent else plan.dispatched + if (sent) Outcome.Uncertain(ChatError(ChatError.Kind.Cancelled)) else Outcome.NotSent(ChatError(ChatError.Kind.Cancelled)) + } + val settled = uncancellably { + settle(plan, outcome) + // One exact-owner recovery so independent new input becomes possible again; the repository's scope runs it, not the caller's. + if (outcome is Outcome.Uncertain) ctx.scope.launch { recoverAfterLoss(plan) } } - settle(plan, outcome) + cancelled?.let { throw it } + settled.cancellation?.let { throw it } return when (outcome) { is Outcome.Admitted -> SendResult.Admitted(plan.entry.id, outcome.admission) is Outcome.Refused -> SendResult.Refused(plan.entry.id, outcome.code, outcome.reachedLimit, outcome.error) is Outcome.Uncertain -> SendResult.Uncertain(plan.entry.id, outcome.error) is Outcome.NotSent -> SendResult.NotSent(outcome.error) - }.also { - if (outcome is Outcome.Uncertain) ctx.scope.launch { recoverAfterLoss(plan) } } } + private class Uncancelled(val cancellation: CancellationException?) + + /** + * Runs [block] to the end even when the caller is cancelled. Returning into a cancelled caller rethrows its cancellation + * after the block has finished; that is reported in the result, not thrown, so the caller can finish what it owes first. + */ + private suspend fun uncancellably(block: suspend () -> Unit): Uncancelled { + var finished = false + try { + withContext(NonCancellable) { block(); finished = true } + } catch (e: CancellationException) { + if (!finished) throw e + return Uncancelled(e) + } + return Uncancelled(null) + } + private fun notSent(kind: ChatError.Kind) = SendResult.NotSent(ChatError(kind)) private fun plan(ref: ConversationRef, text: String, mode: SendMode, attachments: List, selection: SlashSelection?): Planned { @@ -135,7 +175,7 @@ internal class SubmissionEngine(private val ctx: ChatContext, private val engine // A chosen command is checked against the current text: an edited message never runs a stale selection. return Planned.Stop(notSent(ChatError.Kind.InvalidInput)) } - engine.sendBlock(rt)?.let { block -> + engine.sendBlock(rt, submission = effective != Effective.Steer)?.let { block -> return Planned.Stop(SendResult.NotSent(ChatError(if (block == SendBlock.NoLiveSession || block == SendBlock.NotConnected) ChatError.Kind.NotConnected else ChatError.Kind.Conflict), block)) } val binding = rt.binding ?: return Planned.Stop(notSent(ChatError.Kind.NoLiveSession)) @@ -203,15 +243,14 @@ internal class SubmissionEngine(private val ctx: ChatContext, private val engine } } catch (e: HermesException) { return classify(e) - } catch (e: RequestCancelledException) { - return if (e.dispatch == DispatchOutcome.MayHaveBeenSent) Outcome.Uncertain(ChatError(ChatError.Kind.Cancelled)) else Outcome.NotSent(ChatError(ChatError.Kind.Cancelled)) } + // A cancelled caller (RequestCancelledException) is not an outcome: it reaches send(), which settles and then rethrows it. } private suspend fun call(plan: Plan, method: String, params: JsonObject): JsonElement { plan.dispatched = true plan.currentMethod = method - return ctx.gateway.request(method, params) + return ctx.gateway.request(method, params, generation = plan.binding.generation) } private fun JsonElement.status(): String? = asObject?.get("status").asString @@ -453,7 +492,7 @@ internal class SubmissionEngine(private val ctx: ChatContext, private val engine } ?: return StopResult.Refused(ChatError(ChatError.Kind.NotConnected)) val (rt, binding) = target return try { - val result = ctx.gateway.request("session.interrupt", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile) }) + val result = ctx.gateway.request("session.interrupt", buildJsonObject { put("session_id", binding.runtimeId); put("profile", binding.profile) }, generation = binding.generation) if (result.status() != "interrupted") return StopResult.Uncertain(ChatError(ChatError.Kind.InvalidResponse)) ctx.onState { if (rt.binding == binding) { rt.stopRequested = true; rt.status = "Stop requested"; engine.publish(rt) } } StopResult.Requested diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt index 207ab155..68c44f35 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/chat/TurnReducer.kt @@ -69,14 +69,21 @@ internal class TurnReducer(initialEpoch: String = "") { private var sealedSegmentId: String? = null private var anonymous = 0L + /** Counts the cursor restarts. The first numbering keeps the plain `epoch:sequence` key. */ + private var numbering = 0 + val items: List get() = live.values.toList() fun seedCheckpoint(sequence: Long) { lastSequence = maxOf(lastSequence, sequence) } - /** A new replay epoch restarts sequence numbers. Rows stay; only the cursor moves. */ + /** + * A new replay epoch, or another runtime, restarts sequence numbers. Rows stay; only the cursor moves. Each restart is a new + * numbering, so the IDs made after it never repeat one from before it (the same epoch and sequence on another runtime). + */ fun resetCursor(newEpoch: String, latest: Long) { epoch = newEpoch lastSequence = latest + numbering += 1 } fun seedRunning(value: Boolean) { running = value } @@ -127,7 +134,7 @@ internal class TurnReducer(initialEpoch: String = "") { } if (event.type.startsWith("message.") || event.type.startsWith("tool.")) hasLiveEvents = true val p = event.payload - val key = "$epoch:${event.sequence ?: "x${++anonymous}"}" + val key = (if (numbering == 0) "$epoch:" else "$epoch~$numbering:") + (event.sequence ?: "x${++anonymous}") when (event.type) { "message.start" -> { change.started = true diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt index bb45e644..30771286 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt @@ -22,7 +22,10 @@ internal class FakeTransports : GatewayTransportFactory { @Volatile var stallAfterEachSend = false @Volatile var closed = false - override val hasBufferedData: Boolean get() = buffered + /** How often the sender asked whether the socket had taken its data (a stalled writer must not spin). */ + val bufferedReads = java.util.concurrent.atomic.AtomicLong() + + override val hasBufferedData: Boolean get() { bufferedReads.incrementAndGet(); return buffered } override fun send(text: String): Boolean { if (closed) return false diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt index a376fda6..bf72a25f 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt @@ -96,6 +96,24 @@ class GatewayQueueTest { return calls } + @Test fun aStalledWriterWaitsWithoutSpinningAndStillResumesPromptly() = runBlocking { + val (client, socket) = connected() + socket.buffered = true // the peer stopped reading + val call = request(client, "profiles.list", 200) + eventually { client.queueSnapshot().frames == 1 } + val baseline = socket.bufferedReads.get() + delay(600) + val polls = socket.bufferedReads.get() - baseline + assertTrue("A stalled writer polled $polls times in 600 ms", polls < 80) + + val before = socket.sent.size + socket.buffered = false + val resumed = System.nanoTime() + eventually(2_000) { socket.sent.size > before } + assertTrue("The frame went out ${(System.nanoTime() - resumed) / 1_000_000} ms after the socket drained", System.nanoTime() - resumed < 300_000_000L) + call.cancel() + } + @Test fun ordinaryRequestsAreHeldToEightMebibytesExactlyAndReleasedInOrder() = runBlocking { val (client, socket) = connected() val before = socket.sent.size diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRpcTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRpcTest.kt index 7aad79d4..2e70e515 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRpcTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRpcTest.kt @@ -30,9 +30,11 @@ class GatewayRpcTest : GatewayTestSupport() { @Test fun requestsAreWrittenAsJsonRpcWithUniqueStringIdsAndCorrelatedByExactId() = runBlocking { val (client, conn) = connected() + // The second request starts only once the first one's frame was seen: awaitMethod discards frames it skips, so two + // requests racing to the socket could swap places and lose one. Both are still pending together when answered. val first = async(kotlinx.coroutines.Dispatchers.Default) { client.request("profiles.list", params("a" to "1")) } - val second = async(kotlinx.coroutines.Dispatchers.Default) { client.request("session.usage", params("b" to "2")) } val a = conn.awaitMethod("profiles.list") + val second = async(kotlinx.coroutines.Dispatchers.Default) { client.request("session.usage", params("b" to "2")) } val b = conn.awaitMethod("session.usage") assertEquals("""{"a":"1"}""", a["params"].toString()) assertEquals(setOf("jsonrpc", "id", "method", "params"), a.keys) @@ -44,6 +46,30 @@ class GatewayRpcTest : GatewayTestSupport() { client.disconnect() } + @Test fun aRequestFencedToAnotherSocketGenerationIsRefusedBeforeAnythingIsQueued() = runBlocking { + val (client, first) = connected() + val firstGeneration = client.state.value.generation + val fenced = async(kotlinx.coroutines.Dispatchers.Default) { client.request("session.title", params("a" to "1"), generation = firstGeneration) } + first.result(id(first.awaitMethod("session.title")), """{"fine":true}""") + assertTrue("On the socket it names, the call goes through", fenced.await().jsonObject["fine"]!!.jsonPrimitive.content.toBoolean()) + + val before = first.allFrames.size + assertKind(HermesException.Kind.NotConnected) { client.request("session.title", generation = firstGeneration + 1) } + assertEquals("A fence naming a socket that is not current writes nothing", before, first.allFrames.size) + + first.drop() + val second = gateway.awaitConnection() + eventually { client.state.value.connection == GatewayConnection.Connected && client.state.value.generation > firstGeneration } + assertKind(HermesException.Kind.NotConnected) { client.request("session.title", params("a" to "stale"), generation = firstGeneration) } + assertEquals("The old runtime's call never reaches the replacement socket", 0, second.framesWithMethod("session.title").size) + + val current = client.state.value.generation + val ok = async(kotlinx.coroutines.Dispatchers.Default) { client.request("session.title", params("a" to "2"), generation = current) } + second.result(id(second.awaitMethod("session.title")), """{"fine":true}""") + assertTrue(ok.await().jsonObject["fine"]!!.jsonPrimitive.content.toBoolean()) + client.disconnect() + } + @Test fun rpcFailuresKeepCodeReasonAndFlattenedWords() = runBlocking { val (client, conn) = connected() val busy = async(kotlinx.coroutines.Dispatchers.Default) { runCatching { client.request("session.create") } } 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 index 5e8ec513..572b7614 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/ChatRig.kt @@ -15,6 +15,13 @@ 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(), 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 index 3ace4d83..3eed60ad 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/CreateResumeTest.kt @@ -1,6 +1,8 @@ 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 @@ -267,6 +269,62 @@ class CreateResumeTest : ChatTestBase() { 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 index fdf723f1..d63f7e7d 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/FakeHermesHost.kt @@ -1,6 +1,8 @@ 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 @@ -13,6 +15,8 @@ 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 @@ -38,7 +42,8 @@ import kotlinx.serialization.json.put * a lost receipt still applies the mutation, and a compaction successor shows up only on resume or in history. */ internal class FakeHermesHost : ChatGateway, ChatRest { - class Recorded(val method: String, val params: JsonObject, val generation: Long) + /** [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) { @@ -91,9 +96,19 @@ internal class FakeHermesHost : ChatGateway, ChatRest { var heartbeat = true override val state: MutableStateFlow = MutableStateFlow(connectedState()) - private val delivery = Channel(Channel.RENDEZVOUS) + @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 { @@ -270,12 +285,28 @@ internal class FakeHermesHost : ChatGateway, ChatRest { // ---- ChatGateway - override suspend fun request(method: String, params: JsonObject, timeoutMillis: Long?): JsonElement { - val live = state.value - if (live.connection != GatewayConnection.Connected) throw HermesException(HermesException.Kind.NotConnected) - requests += Recorded(method, params, live.generation) - overrides[method]?.removeFirstOrNull()?.let { return it(params) } - return defaultHandle(method, params) + /** 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 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 index bddeabf8..c956bef9 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/GatewayChatIntegrationTest.kt @@ -8,6 +8,7 @@ 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 @@ -134,4 +135,36 @@ class GatewayChatIntegrationTest : GatewayTestSupport() { 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 index 414fbf13..ceafb791 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/HistoryRepositoryTest.kt @@ -1,5 +1,6 @@ package app.bighelp.hermes.chat +import kotlinx.coroutines.async import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue @@ -75,7 +76,7 @@ class HistoryRepositoryTest : ChatTestBase() { // 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)) + 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) @@ -122,4 +123,33 @@ class HistoryRepositoryTest : ChatTestBase() { 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/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 index b96d5793..be596c28 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/SendFlowTest.kt @@ -369,4 +369,26 @@ class SendFlowTest : ChatTestBase() { 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/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 index 1efbcdb8..505fca8a 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/chat/TurnReducerTest.kt @@ -240,6 +240,19 @@ class TurnReducerTest { 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") From 9eb8e8dd0fb34bb0972c6b1a6c3835618095fa9b Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:56:15 -0500 Subject: [PATCH 18/18] Gateway hard-close fallback survives the owner scope being cancelled Co-Authored-By: Claude Sonnet 5.5 --- .../src/main/kotlin/app/bighelp/hermes/GatewayClient.kt | 7 ++++++- .../src/test/kotlin/app/bighelp/hermes/FakeTransport.kt | 5 ++++- .../test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt | 8 ++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt index df7c4fb7..1a8130fd 100644 --- a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt @@ -11,6 +11,7 @@ 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 @@ -83,6 +84,9 @@ class GatewayClient internal constructor( 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 @@ -811,7 +815,8 @@ class GatewayClient internal constructor( owner.transport?.let { transport -> if (orderly) { transport.close(orderly = true) - scope.launch(serial) { delay(1_000); transport.close(orderly = false) } + // 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) } diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt index 30771286..dd380d90 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/FakeTransport.kt @@ -42,7 +42,10 @@ internal class FakeTransports : GatewayTransportFactory { return true } - override fun close(orderly: Boolean) { closed = true } + /** Every close request in order: true = orderly attempt, false = hard close. */ + val closes = CopyOnWriteArrayList() + + override fun close(orderly: Boolean) { closes += orderly; closed = true } /** Delivers a line as if the host sent it, from another thread (the reader thread of a real socket). */ fun deliver(line: String) { diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt index bf72a25f..4aa2b8ab 100644 --- a/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayQueueTest.kt @@ -257,4 +257,12 @@ class GatewayQueueTest { } private fun params(vararg pairs: Pair) = buildJsonObject { pairs.forEach { put(it.first, it.second) } } + + @Test fun theHardCloseFallbackStillRunsWhenTheOwnerScopeIsCancelledRightAfterDisconnect() = runBlocking { + val (client, fake) = connected() + client.disconnect() + scope.cancel() // the app cancels the owner scope as soon as disconnect() returns + eventually(3_000) { fake.closes.contains(false) } + assertEquals(listOf(true, false), fake.closes.toList()) + } }