From 9a94eabaa3b6b0be4cec5e1aa2afbf8412dce81a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 13 Oct 2026 17:20:18 +0100 Subject: [PATCH] Add the native Android client for the Pipelines server Kotlin and Jetpack Compose Material 3 client that speaks the existing WebSocket protocol: settings requiring an explicit server URL and workspace, pipeline list and detail with the workflow graph, run history, run detail and evidence, start and cancel run, reconnect, and the loading/empty/error/disconnected states. It stores no credentials and keeps execution, definitions and run history on the server. Verified on the host: :app:compileDebugKotlin and :app:assembleDebug succeed and :app:testDebugUnitTest passes 19 tests. Ignore Gradle outputs and re-include the net.awan.pipelines.data package, which the repository runtime data/ rule would otherwise exclude. --- .gitignore | 17 + android/README.md | 125 ++++++ android/app/build.gradle.kts | 69 +++ android/app/proguard-rules.pro | 11 + android/app/src/main/AndroidManifest.xml | 32 ++ .../java/net/awan/pipelines/MainActivity.kt | 24 ++ .../awan/pipelines/PipelinesApplication.kt | 24 ++ .../net/awan/pipelines/data/ErrorMessages.kt | 23 + .../pipelines/data/PipelinesRepository.kt | 136 ++++++ .../awan/pipelines/data/SettingsRepository.kt | 43 ++ .../pipelines/data/protocol/GraphSemantics.kt | 97 +++++ .../net/awan/pipelines/data/protocol/Json.kt | 16 + .../awan/pipelines/data/protocol/Message.kt | 395 +++++++++++++++++ .../data/transport/ConnectionState.kt | 14 + .../data/transport/PipelinesClient.kt | 210 +++++++++ .../pipelines/data/transport/ServerUrl.kt | 85 ++++ .../net/awan/pipelines/ui/AppViewModel.kt | 265 ++++++++++++ .../main/java/net/awan/pipelines/ui/Format.kt | 33 ++ .../net/awan/pipelines/ui/PipelinesApp.kt | 122 ++++++ .../ui/components/ConnectionBanner.kt | 88 ++++ .../awan/pipelines/ui/components/States.kt | 75 ++++ .../awan/pipelines/ui/graph/WorkflowGraph.kt | 401 ++++++++++++++++++ .../ui/screens/PipelineDetailScreen.kt | 218 ++++++++++ .../ui/screens/PipelineListScreen.kt | 118 ++++++ .../pipelines/ui/screens/RunDetailScreen.kt | 374 ++++++++++++++++ .../pipelines/ui/screens/RunHistoryScreen.kt | 143 +++++++ .../pipelines/ui/screens/SettingsScreen.kt | 141 ++++++ .../java/net/awan/pipelines/ui/theme/Theme.kt | 29 ++ .../app/src/main/res/drawable/ic_launcher.xml | 15 + .../app/src/main/res/values-night/themes.xml | 6 + android/app/src/main/res/values/strings.xml | 3 + android/app/src/main/res/values/themes.xml | 6 + .../data/protocol/GraphSemanticsTest.kt | 81 ++++ .../data/protocol/ProtocolModelTest.kt | 219 ++++++++++ .../pipelines/data/transport/ServerUrlTest.kt | 64 +++ android/build.gradle.kts | 7 + android/gradle.properties | 9 + android/gradle/libs.versions.toml | 37 ++ .../gradle/wrapper/gradle-wrapper.properties | 11 + android/settings.gradle.kts | 24 ++ 40 files changed, 3810 insertions(+) create mode 100644 android/README.md create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/proguard-rules.pro create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/java/net/awan/pipelines/MainActivity.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/ErrorMessages.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/protocol/GraphSemantics.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/protocol/Json.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/transport/ConnectionState.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/transport/ServerUrl.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/Format.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/components/ConnectionBanner.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/components/States.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/graph/WorkflowGraph.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/screens/SettingsScreen.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/theme/Theme.kt create mode 100644 android/app/src/main/res/drawable/ic_launcher.xml create mode 100644 android/app/src/main/res/values-night/themes.xml create mode 100644 android/app/src/main/res/values/strings.xml create mode 100644 android/app/src/main/res/values/themes.xml create mode 100644 android/app/src/test/java/net/awan/pipelines/data/protocol/GraphSemanticsTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/data/protocol/ProtocolModelTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/data/transport/ServerUrlTest.kt create mode 100644 android/build.gradle.kts create mode 100644 android/gradle.properties create mode 100644 android/gradle/libs.versions.toml create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100644 android/settings.gradle.kts diff --git a/.gitignore b/.gitignore index 090a6598..f13cd4ab 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,20 @@ dist/ release-bin/ /.pipelines-releases.json /.pipelines-releases-* + +# Android client: ignore Gradle build outputs and local configuration, but keep +# the Kotlin sources. The negation is required because the runtime `data/` rule +# above would otherwise exclude the app's net.awan.pipelines.data package. +android/.gradle/ +android/.kotlin/ +android/local.properties +android/**/build/ +android/captures/ +android/.idea/ +android/*.iml +android/**/*.apk +android/**/*.aab +android/**/*.jks +android/**/*.keystore +!android/**/data/ + diff --git a/android/README.md b/android/README.md new file mode 100644 index 00000000..7e1f27d9 --- /dev/null +++ b/android/README.md @@ -0,0 +1,125 @@ +# Pipelines Android client + +A native Android (Kotlin + Jetpack Compose Material 3) client for an existing +Pipelines server. All execution, model credentials, definitions and run history +stay on the server; the app only speaks the existing WebSocket protocol. + +## Scope and safety + +- **Trusted LAN/VPN only.** The Pipelines API has **no authentication** and is + **not internet-safe**. Do not expose the server to untrusted networks. +- **No secrets.** The app stores no credentials, tokens or provider keys and + sends no auth headers. Only the server URL and workspace path are persisted as + plain, non-secret preferences. +- **No hardcoded server.** The server URL and workspace path must be entered + explicitly by the user; there is no default/disposable address baked in. +- The app does **not** run Docker, execute stages, or reimplement any Go + parsing/execution logic. `android/` contains only the client. + +## Requirements + +- JDK 17 (see `compileOptions` / `kotlinOptions.jvmTarget`). +- Android SDK with a platform and build-tools matching `compileSdk = 35` + (`app/build.gradle.kts`), and `ANDROID_HOME`/`ANDROID_SDK_ROOT` set. +- Gradle 8.9+ (AGP 8.7.2, Kotlin 2.0.21). + +The version numbers above are deliberate defaults chosen without a discovered +SDK; adjust `compileSdk`, `targetSdk`, and the versions in +`gradle/libs.versions.toml` to whatever is actually installed. If a required +SDK/Gradle component is missing, fix the environment rather than downloading +untracked artifacts. + +### Gradle wrapper + +`gradle/wrapper/gradle-wrapper.jar` is a generated binary and is intentionally +**not committed**. Generate a working wrapper on a machine with Gradle installed: + +```sh +cd android +gradle wrapper --gradle-version 8.9 +``` + +Until then, build with a locally installed Gradle: + +```sh +cd android +gradle :app:assembleDebug +``` + +## Build, test and install + +```sh +cd android +gradle :app:testDebugUnitTest # protocol/URL/graph unit tests +gradle :app:assembleDebug # debug APK +gradle :app:lintDebug # Android lint +# install on a connected device/emulator: +gradle :app:installDebug +adb shell am start -n net.awan.pipelines/.MainActivity +``` + +## Configuration + +Open the **Settings** tab and enter: + +- **Server URL** — `ws://HOST:PORT/connect` (LAN/VPN) or `wss://…/connect` + (proxy/VPN). A path is optional and defaults to `/connect`, matching the Go + server's `GET /connect`. `http(s)`, userinfo and fragments are rejected with a + specific message. +- **Workspace path** — an **absolute directory that already exists on the + execution server**. This is *not* the phone's storage. For Docker, mount the + host directory at the same absolute path with the owner's UID/GID so the + server can resolve it (see `docs/docker.md` and `compose.yaml`). The field + flags a non-absolute path and will not save it, mirroring the repository's + start-run guard. + +Tap **Connect** to open the single shared WebSocket (probed with `ping`, showing +the server build). Reconnect uses bounded exponential backoff; **Disconnect** +stops it. + +## Features + +- Pipeline list (search/refresh, empty/error/loading states), pipeline details + (version list, content hash, source) and the workflow graph. +- Workflow graph composable: content-sized nodes, labelled outcome edges + (`error*` marks the implicit fallback), `#success`/`#failure` terminals, loops + and branches, pan/zoom, and run highlighting (executed routes highlighted, + others dimmed) plus a screen-reader description. +- Run history with server `usage` aggregates, and run details with steps + (status/outcome/diagnostic/session/transcript/file changes/notifications/ + control evidence). Session evidence is scoped to the selected run and each + record is rendered (sequence/session id/backend/directory/data/diagnostic) on + demand via `get_run_evidence`; it is never part of the 1s poll. +- A shared connection banner above every screen surfaces a distinct + Idle/Connecting/Disconnected state with a Reconnect action (and stays hidden + while connected), so a dropped connection is not just a generic request error. +- Start run (confirmation dialog; sends `PipelineID`, `Version`, a reused + `request_key` ≤128 chars, the configured absolute workspace and `input.prompt`) + and cancel run (confirmation; sends the `RunID`, then refreshes). Retry is + offered only for terminal failed runs. +- A run being polled at a fixed 1s interval is stopped as soon as it is no + longer executing. + +## Architecture + +``` +data/protocol kotlinx.serialization models mirroring internal/protocol/* + (Message, Graph/Stage, RunDetail/RunStep, UsageStats, …) plus + GraphSemantics reproducing internal/tui/graph.go rules. +data/transport ServerUrl validation (mirrors internal/client/config.go) and + PipelinesClient — one reused WebSocket, serialized requests, + client ids matched against replies, unsolicited envelopes + dropped, bounded reconnect backoff. +data SettingsRepository (non-secret prefs) and PipelinesRepository + (typed request builders + per-session graph/detail cache). +ui Compose Material 3 screens, one AppViewModel, navigation. +``` + +## Verification status + +The project sources, protocol model and unit tests are present, but **no build, +lint, unit test or emulator run has been performed here**: this stage has no +command-execution tool, and no JDK/Gradle/Android SDK was discoverable in the +environment. The exact commands to run are listed above; run them on a machine +with the toolchain and capture the real results. Do not treat this file as +evidence of a successful build. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 00000000..4b89f8dc --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,69 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) +} + +android { + namespace = "net.awan.pipelines" + // Version numbers follow what the build environment provides; adjust to the + // installed SDK/build-tools if the release/target differs. See android/README.md. + compileSdk = 35 + + defaultConfig { + applicationId = "net.awan.pipelines" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "0.1.0" + vectorDrawables { useSupportLibrary = true } + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + buildFeatures { + compose = true + } + + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.activity.compose) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons.extended) + implementation(libs.androidx.navigation.compose) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.lifecycle.viewmodel.ktx) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.kotlinx.serialization.json) + implementation(libs.okhttp) + + testImplementation(libs.junit) + debugImplementation(libs.androidx.compose.ui.tooling) +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 00000000..477726d6 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,11 @@ +# Default ProGuard/R8 rules. The app keeps kotlinx.serialization models used by the +# Pipelines protocol, which are otherwise pruned when minification is enabled. +-keepattributes *Annotation*, InnerClasses +-dontnote kotlinx.serialization.** + +-keepclassmembers class net.awan.pipelines.data.protocol.** { + *** Companion; +} +-keepclasseswithmembers class net.awan.pipelines.data.protocol.** { + kotlinx.serialization.KSerializer serializer(...); +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..5b9ad4e3 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/net/awan/pipelines/MainActivity.kt b/android/app/src/main/java/net/awan/pipelines/MainActivity.kt new file mode 100644 index 00000000..8f61c8ce --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/MainActivity.kt @@ -0,0 +1,24 @@ +package net.awan.pipelines + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.lifecycle.viewmodel.compose.viewModel +import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.PipelinesApp +import net.awan.pipelines.ui.theme.PipelinesTheme + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val app = application as PipelinesApplication + setContent { + PipelinesTheme { + val vm: AppViewModel = viewModel(factory = AppViewModel.factory(app)) + PipelinesApp(vm) + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt b/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt new file mode 100644 index 00000000..ffc183d2 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt @@ -0,0 +1,24 @@ +package net.awan.pipelines + +import android.app.Application +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import net.awan.pipelines.data.PipelinesRepository +import net.awan.pipelines.data.SettingsRepository +import net.awan.pipelines.data.transport.PipelinesClient + +/** + * Holds the single long-lived repository, WebSocket client and application + * scope. There is intentionally no dependency-injection framework here. + */ +class PipelinesApplication : Application() { + + private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + val settings: SettingsRepository by lazy { SettingsRepository(this) } + + val client: PipelinesClient by lazy { PipelinesClient(scope = applicationScope) } + + val repository: PipelinesRepository by lazy { PipelinesRepository(client, settings) } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/ErrorMessages.kt b/android/app/src/main/java/net/awan/pipelines/data/ErrorMessages.kt new file mode 100644 index 00000000..c0a97179 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/ErrorMessages.kt @@ -0,0 +1,23 @@ +package net.awan.pipelines.data + +import java.io.IOException +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import net.awan.pipelines.data.transport.NotConnectedException +import net.awan.pipelines.data.transport.ProtocolException + +/** + * Turns transport failures into distinct, non-technical messages. The server + * error text is surfaced verbatim because it is actionable (bad workspace, + * missing prompt, active run). + */ +object ErrorMessages { + fun describe(t: Throwable): String = when (t) { + is ProtocolException -> t.message ?: "The server rejected the request." + is NotConnectedException -> "Not connected. Check the server URL, then reconnect." + is UnknownHostException -> "Server not found. Check the host name and that you are on the trusted LAN/VPN." + is SocketTimeoutException -> "The server did not respond in time. Check the connection and retry." + is IOException -> "Network error: ${t.message ?: "connection failed"}. Reconnect and retry." + else -> t.message?.takeIf { it.isNotBlank() } ?: "Unexpected error: ${t.javaClass.simpleName}" + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt new file mode 100644 index 00000000..088261ef --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -0,0 +1,136 @@ +package net.awan.pipelines.data + +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.JsonElement +import net.awan.pipelines.data.protocol.Message +import net.awan.pipelines.data.protocol.PipelineDetail +import net.awan.pipelines.data.protocol.PipelineSummary +import net.awan.pipelines.data.protocol.Protocol +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.RunSummary +import net.awan.pipelines.data.protocol.SessionEvidence +import net.awan.pipelines.data.protocol.UsageStats +import net.awan.pipelines.data.transport.NotConnectedException +import net.awan.pipelines.data.transport.PipelinesClient +import net.awan.pipelines.data.transport.ProtocolException +import net.awan.pipelines.data.transport.ServerUrl + +/** Run history plus the server's aggregate usage statistics. */ +data class RunHistory(val runs: List, val usage: UsageStats?) + +/** + * Typed access to the existing WebSocket protocol. Request builders and ID + * matching live here so screens never construct frames by hand or invent + * divergent field names. Pipeline details/graphs are cached per session. + */ +class PipelinesRepository( + private val client: PipelinesClient, + private val settings: SettingsRepository, +) { + val connectionState = client.state + + /** Opens the single shared connection to a validated server URL. */ + fun connect(validated: ServerUrl.Validated) = client.connect(validated) + + /** Explicit disconnect; the client then stays Idle. */ + fun disconnect() = client.disconnect() + + private data class CacheKey(val id: Long, val version: Int) + + private val detailCache = ConcurrentHashMap() + + fun clearCache() = detailCache.clear() + + suspend fun ping(): Message = client.call(Message(type = Protocol.PING)) + + suspend fun listPipelines(): List = + client.call(Message(type = Protocol.LIST)).pipelines ?: emptyList() + + suspend fun getPipeline(id: Long, version: Int): PipelineDetail { + val key = CacheKey(id, version) + detailCache[key]?.let { return it } + val response = client.call( + Message(type = Protocol.GET_PIPELINE, pipelineId = id, version = version), + ) + val detail = response.detail + ?: throw ProtocolException("The server returned no pipeline detail.") + if (detail.version > 0) detailCache[key] = detail + return detail + } + + suspend fun listRuns(): RunHistory { + val response = client.call(Message(type = Protocol.LIST_RUNS)) + return RunHistory(response.runs ?: emptyList(), response.usage) + } + + suspend fun getRun(id: Long): RunDetail = client.call( + Message(type = Protocol.GET_RUN, runId = id), + ).runDetail ?: throw ProtocolException("The server returned no run detail.") + + suspend fun getRunEvidence(id: Long): List = + client.call(Message(type = Protocol.GET_RUN_EVIDENCE, runId = id)).evidence ?: emptyList() + + suspend fun startRun( + pipelineId: Long, + version: Int, + prompt: String, + requestKey: String, + ): RunDetail { + requireConfigured() + if (pipelineId <= 0) throw ProtocolException("Select a pipeline to run.") + if (version <= 0) throw ProtocolException("An explicit pipeline version is required.") + if (requestKey.isBlank() || requestKey.length > MAX_REQUEST_KEY) { + throw ProtocolException("A run request key of at most $MAX_REQUEST_KEY characters is required.") + } + if (prompt.trim().isEmpty()) throw ProtocolException("Enter a non-empty prompt before starting a run.") + val workspace = settings.workspace.value + if (!workspace.startsWith("/")) { + throw ProtocolException("Set an absolute workspace path that exists on the execution server.") + } + val input: Map = mapOf("prompt" to JsonPrimitive(prompt.trim())) + val response = client.call( + Message( + type = Protocol.RUN_PIPELINE, + pipelineId = pipelineId, + version = version, + requestKey = requestKey, + workspace = workspace, + input = input, + ), + ) + return response.runDetail ?: throw ProtocolException("The server returned no run detail.") + } + + suspend fun cancelRun(id: Long): RunDetail = client.call( + Message(type = Protocol.CANCEL_RUN, runId = id), + ).runDetail ?: throw ProtocolException("The server returned no run detail.") + + /** + * Retry is only offered for terminal failed runs; the server enforces this + * too. The caller supplies a new request key so the retry is its own run. + */ + suspend fun retryRun(id: Long, requestKey: String): RunDetail = client.call( + Message(type = Protocol.RETRY_RUN, runId = id, requestKey = requestKey), + ).runDetail ?: throw ProtocolException("The server returned no run detail.") + + private fun requireConfigured() { + if (settings.serverUrl.value.isBlank()) { + throw NotConnectedException("Set the Pipelines server URL in Settings first.") + } + if (settings.workspace.value.isBlank()) { + throw ProtocolException("Set the workspace path in Settings first.") + } + } + + companion object { + const val MAX_REQUEST_KEY = 128 + + /** + * A stable per-start request key (<=128 chars). Reuse it across retries of + * the same start intent so the server can dedupe idempotent repeats. + */ + fun newRequestKey(): String = "android-" + UUID.randomUUID().toString() + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt new file mode 100644 index 00000000..f29a9c8e --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt @@ -0,0 +1,43 @@ +package net.awan.pipelines.data + +import android.content.Context +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** + * Persists the explicitly configured server URL and workspace path as plain, + * non-secret preferences. No credentials or tokens are ever stored, because the + * server has no authentication. + */ +class SettingsRepository(context: Context) { + + private val prefs = context.applicationContext + .getSharedPreferences("pipelines_settings", Context.MODE_PRIVATE) + + private val _serverUrl = MutableStateFlow(prefs.getString(KEY_SERVER_URL, "").orEmpty()) + val serverUrl: StateFlow = _serverUrl.asStateFlow() + + private val _workspace = MutableStateFlow(prefs.getString(KEY_WORKSPACE, "").orEmpty()) + val workspace: StateFlow = _workspace.asStateFlow() + + fun setServerUrl(value: String) { + val trimmed = value.trim() + _serverUrl.value = trimmed + prefs.edit().putString(KEY_SERVER_URL, trimmed).apply() + } + + fun setWorkspace(value: String) { + val trimmed = value.trim() + _workspace.value = trimmed + prefs.edit().putString(KEY_WORKSPACE, trimmed).apply() + } + + /** True only when the user has explicitly supplied both required values. */ + fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank() + + private companion object { + const val KEY_SERVER_URL = "server_url" + const val KEY_WORKSPACE = "workspace" + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/GraphSemantics.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/GraphSemantics.kt new file mode 100644 index 00000000..6e09e422 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/GraphSemantics.kt @@ -0,0 +1,97 @@ +package net.awan.pipelines.data.protocol + +/** + * Shared graph semantics reproduced from internal/tui/graph.go. Keeping the + * outcome ordering, fallback-label and compact thresholds here means the UI has a + * single source of truth and cannot diverge between the pipeline and run screens. + */ +object GraphSemantics { + + /** Same ordering as tui.outcomes: success first, error last, others alphabetical. */ + fun outcomes(stage: Stage): List = stage.edges.keys.sortedWith( + compareBy({ priority(it) }, { it }), + ) + + private fun priority(outcome: String): Int = when (outcome) { + "success" -> 0 + "error" -> 2 + else -> 1 + } + + /** Mirrors tui.compactGraph: oversized graphs use a reduced-detail layout. */ + fun compactGraph(graph: Graph): Boolean { + var edges = 0 + for (stage in graph.stages) edges += stage.edges.size + return graph.stages.size > 200 || edges > 500 + } + + fun nodeLabel(key: String): String = when (key) { + Protocol.SUCCESS_END -> "SUCCESS" + Protocol.FAILURE_END -> "FAILURE" + else -> key + } + + /** + * The outcome label shown on an edge. Matches tui.graphEdges: the implicit + * fallback error route is marked `error*`. + */ + fun edgeLabel(stage: Stage, outcome: String): String = + if (outcome == "error" && stage.fallbackError) "error*" else outcome +} + +data class GraphRoute(val source: String, val outcome: String, val target: String) + +data class GraphEdge( + val id: Int, + val source: String, + val outcome: String, + val target: String, + val label: String, +) + +/** Builds every definition edge in stable id order, exactly like tui.graphEdges. */ +fun Graph.edges(): List { + val result = ArrayList() + for (stage in stages) { + for (outcome in GraphSemantics.outcomes(stage)) { + val target = Protocol.resolveTarget(outcome, stage.edges[outcome] ?: continue) + result += GraphEdge( + id = result.size + 1, + source = stage.key, + outcome = outcome, + target = target, + label = GraphSemantics.edgeLabel(stage, outcome), + ) + } + } + return result +} + +/** + * Which stages and routes a run actually recorded, used to highlight executed + * paths and dim everything else (tui/run_graph.go runGraphState). + */ +data class RunGraphState( + val visitedStages: Set, + val takenRoutes: Set, + val currentStage: String?, +) { + companion object { + fun from(run: RunDetail): RunGraphState { + val stages = LinkedHashSet() + val routes = LinkedHashSet() + for (step in run.steps) { + stages += step.stage + if (step.target.isNotEmpty() && step.outcome.isNotEmpty()) { + val target = Protocol.resolveTarget(step.outcome, step.target) + routes += GraphRoute(step.stage, step.outcome, target) + if (Protocol.isTerminal(target)) stages += target + } + } + val current = run.currentStage.ifEmpty { + run.steps.lastOrNull()?.stage ?: "" + } + return RunGraphState(stages, routes, current.ifEmpty { null }) + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Json.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Json.kt new file mode 100644 index 00000000..d3c1b769 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Json.kt @@ -0,0 +1,16 @@ +package net.awan.pipelines.data.protocol + +import kotlinx.serialization.json.Json + +/** + * Tolerant JSON: unknown server fields are ignored, explicit nulls are dropped, + * and wrong types fall back to defaults so a partial or newer envelope never + * crashes the client. + */ +val PipelinesJson: Json = Json { + ignoreUnknownKeys = true + explicitNulls = false + coerceInputValues = true + isLenient = true + encodeDefaults = false +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt new file mode 100644 index 00000000..4b4a0288 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt @@ -0,0 +1,395 @@ +package net.awan.pipelines.data.protocol + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement + +/** + * Protocol command/type constants. These mirror the Go constants in + * internal/protocol/message.go, runs.go and status.go exactly so later renames + * cannot drift from the server. + */ +object Protocol { + // message.go + const val PING = "ping" + const val PONG = "pong" + const val ERROR = "error" + const val SUBMIT = "submit" + const val SUBMITTED = "submitted" + const val LIST = "list_pipelines" + const val PIPELINE_LIST = "pipelines" + const val GET_PIPELINE = "get_pipeline" + const val PIPELINE = "pipeline" + const val LIST_TEMPLATES = "list_templates" + const val TEMPLATES = "templates" + const val VALIDATE = "validate" + const val VALIDATED = "validated" + + // runs.go + const val RUN_PIPELINE = "run_pipeline" + const val RUN_STARTED = "run_started" + const val LIST_RUNS = "list_runs" + const val RUNS = "runs" + const val GET_RUN = "get_run" + const val RUN = "run" + const val CANCEL_RUN = "cancel_run" + const val RETRY_RUN = "retry_run" + const val GET_RUN_EVIDENCE = "get_run_evidence" + const val RUN_EVIDENCE = "run_evidence" + + // status.go + const val GET_STATUS = "get_status" + const val STATUS = "status" + + // terminals.go + const val SUCCESS_END = "#success" + const val FAILURE_END = "#failure" + + fun isTerminal(target: String): Boolean = target == SUCCESS_END || target == FAILURE_END + + /** Mirrors protocol.ResolveTarget: preserve the # shorthand as an explicit terminal. */ + fun resolveTarget(outcome: String, target: String): String = when { + target != "#" -> target + outcome == "error" -> FAILURE_END + else -> SUCCESS_END + } +} + +@Serializable +data class BuildInfo( + val version: String = "", + val commit: String = "", + val dirty: Boolean? = null, +) + +@Serializable +data class NotificationEndpoint( + val destination: String = "", + @SerialName("server_url") val serverUrl: String? = null, + val topic: String = "", +) + +@Serializable +data class Template( + val key: String = "", + val name: String = "", + val description: String = "", + val source: String = "", + val scheduled: Boolean = false, +) + +@Serializable +data class StageLimits( + @SerialName("max_visits") val maxVisits: Int = 0, + val on: List? = null, +) + +@Serializable +data class NotificationPolicy( + val on: List = emptyList(), + val destination: String = "", + val artifacts: List? = null, +) + +@Serializable +data class Stage( + val limits: StageLimits? = null, + val memory: Map? = null, + val notify: NotificationPolicy? = null, + val key: String = "", + val type: String? = null, + val output: String = "", + val prompt: String = "", + val configs: Map = emptyMap(), + val edges: Map = emptyMap(), + @SerialName("fallback_error") val fallbackError: Boolean = false, + val blocks: Map? = null, +) + +@Serializable +data class Schedule( + val days: List? = null, + val times: List? = null, + val every: String? = null, + val timezone: String? = null, +) + +@Serializable +data class Settings( + val prompt: String = "", + val schedules: List = emptyList(), +) + +@Serializable +data class Graph( + val stages: List = emptyList(), + val settings: Settings? = null, +) + +@Serializable +data class PipelineSummary( + val id: Long = 0, + val name: String = "", + val version: Int = 0, + val stages: Int = 0, + @SerialName("created_at") val createdAt: String = "", + @SerialName("updated_at") val updatedAt: String = "", +) + +@Serializable +data class VersionSummary( + val version: Int = 0, + val stages: Int = 0, + @SerialName("created_at") val createdAt: String = "", +) + +// kotlinx.serialization rejects overriding an inherited serializable property +// (duplicate serial name in the class and its supertype), so the server's +// embedded PipelineSummary fields are declared flat here with the same wire +// names as internal/protocol/message.go. +@Serializable +data class PipelineDetail( + val id: Long = 0, + val name: String = "", + val version: Int = 0, + val stages: Int = 0, + @SerialName("created_at") val createdAt: String = "", + @SerialName("updated_at") val updatedAt: String = "", + @SerialName("latest_version") val latestVersion: Int = 0, + @SerialName("version_created_at") val versionCreatedAt: String = "", + @SerialName("content_hash") val contentHash: String = "", + val source: String = "", + val graph: Graph = Graph(), + val versions: List = emptyList(), +) + +@Serializable +data class MemoryRead( + val source: String = "", + val sequence: Int = 0, +) + +@Serializable +data class ControlEvidence( + val visit: Int = 0, + @SerialName("max_visits") val maxVisits: Int = 0, + @SerialName("limit_reached") val limitReached: Boolean = false, + @SerialName("model_target") val modelTarget: String? = null, + val memory: Map? = null, +) + +@Serializable +data class FileChange( + val path: String = "", + val kind: String = "", + val patch: String? = null, + val binary: Boolean = false, + val truncated: Boolean = false, + @SerialName("before_mode") val beforeMode: String? = null, + @SerialName("after_mode") val afterMode: String? = null, +) + +@Serializable +data class StageFileChanges( + val omitted: Int = 0, + val scope: String? = null, + val status: String = "", + val files: List = emptyList(), + val skipped: Int = 0, + val diagnostic: String? = null, +) + +@Serializable +data class NotificationReceipt( + val destination: String = "", + val status: String = "", + val filename: String? = null, + @SerialName("message_id") val messageId: String? = null, + @SerialName("attachment_url") val attachmentUrl: String? = null, + val diagnostic: String? = null, +) + +@Serializable +data class SessionEvidence( + val sequence: Int = 0, + @SerialName("session_id") val sessionId: String = "", + val backend: String = "", + val directory: String = "", + val data: String? = null, + val diagnostic: String? = null, +) + +@Serializable +data class RunSummary( + val id: Long = 0, + @SerialName("pipeline_id") val pipelineId: Long = 0, + val name: String = "", + val version: Int = 0, + @SerialName("content_hash") val contentHash: String = "", + val status: String = "", + val executing: Boolean = false, + val outcome: String = "", + @SerialName("current_stage") val currentStage: String = "", + @SerialName("created_at") val createdAt: String = "", + @SerialName("finished_at") val finishedAt: String = "", + val diagnostic: String = "", + @SerialName("result_preview") val resultPreview: String? = null, + @SerialName("completed_steps") val completedSteps: Int = 0, +) + +@Serializable +data class RunStep( + val control: ControlEvidence? = null, + @SerialName("file_changes") val fileChanges: StageFileChanges? = null, + val notifications: List? = null, + val sequence: Int = 0, + val stage: String = "", + val status: String = "", + val outcome: String = "", + val target: String = "", + val input: Map? = null, + val output: Map? = null, + val diagnostic: String = "", + @SerialName("session_id") val sessionId: String = "", + @SerialName("agent_active") val agentActive: Boolean = false, + val transcript: String = "", + @SerialName("started_at") val startedAt: String = "", + @SerialName("finished_at") val finishedAt: String = "", +) + +// Same flattening as PipelineDetail: the embedded RunSummary fields are +// declared directly with the exact internal/protocol/runs.go wire names. +@Serializable +data class RunDetail( + val id: Long = 0, + @SerialName("pipeline_id") val pipelineId: Long = 0, + val name: String = "", + val version: Int = 0, + @SerialName("content_hash") val contentHash: String = "", + val status: String = "", + val executing: Boolean = false, + val outcome: String = "", + @SerialName("current_stage") val currentStage: String = "", + @SerialName("created_at") val createdAt: String = "", + @SerialName("finished_at") val finishedAt: String = "", + val diagnostic: String = "", + @SerialName("result_preview") val resultPreview: String? = null, + @SerialName("completed_steps") val completedSteps: Int = 0, + val graph: Graph = Graph(), + @SerialName("retry_of") val retryOf: Long = 0, + val workspace: String = "", + @SerialName("allow_tools") val allowTools: Boolean = false, + @SerialName("write_paths") val writePaths: List = emptyList(), + val input: Map? = null, + val output: Map? = null, + val steps: List = emptyList(), +) + +@Serializable +data class RunCounts( + val total: Int = 0, + val succeeded: Int = 0, + val failed: Int = 0, + val canceled: Int = 0, + val interrupted: Int = 0, + val active: Int = 0, + @SerialName("average_seconds") val averageSeconds: Double = 0.0, +) + +// The server embeds RunCounts (internal/protocol/stats.go); flatten its fields +// with matching wire names rather than overriding a serializable supertype. +@Serializable +data class PipelineUsage( + @SerialName("pipeline_id") val pipelineId: Long = 0, + val name: String = "", + val total: Int = 0, + val succeeded: Int = 0, + val failed: Int = 0, + val canceled: Int = 0, + val interrupted: Int = 0, + val active: Int = 0, + @SerialName("average_seconds") val averageSeconds: Double = 0.0, +) + +@Serializable +data class DailyUsage( + val date: String = "", + val runs: Int = 0, +) + +@Serializable +data class UsageStats( + val total: Int = 0, + val succeeded: Int = 0, + val failed: Int = 0, + val canceled: Int = 0, + val interrupted: Int = 0, + val active: Int = 0, + @SerialName("average_seconds") val averageSeconds: Double = 0.0, + val pipelines: List = emptyList(), + val days: List = emptyList(), +) + +@Serializable +data class NetworkAddress( + @SerialName("interface") val interfaceName: String? = null, + val ip: String = "", +) + +@Serializable +data class ServiceStatus( + val health: String = "", + val url: String? = null, + val port: String? = null, + @SerialName("candidate_urls") val candidateUrls: List? = null, +) + +@Serializable +data class SystemStatus( + val hostname: String = "", + @SerialName("started_at") val startedAt: String = "", + val uptime: String = "", + val addresses: List = emptyList(), + val server: ServiceStatus = ServiceStatus(), + val ntfy: ServiceStatus = ServiceStatus(), + val topic: String? = null, + @SerialName("ntfy_user") val ntfyUser: String? = null, + val note: String = "", +) + +/** + * The shared JSON envelope. Every field is optional/nullable with defaults so + * unknown or missing server fields never crash the client. + */ +@Serializable +data class Message( + @SerialName("default_harness") val defaultHarness: String? = null, + val build: BuildInfo? = null, + @SerialName("default_model") val defaultModel: String? = null, + val evidence: List? = null, + val usage: UsageStats? = null, + val status: SystemStatus? = null, + val graph: Graph? = null, + @SerialName("expected_version") val expectedVersion: Int = 0, + val templates: List