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.
This commit is contained in:
2026-10-13 17:20:18 +01:00
parent a70e3aef4b
commit 9a94eabaa3
40 changed files with 3810 additions and 0 deletions
+17
View File
@@ -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/
+125
View File
@@ -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.
+69
View File
@@ -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)
}
+11
View File
@@ -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(...);
}
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:name=".PipelinesApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Pipelines"
android:usesCleartextTraffic="true">
<!--
usesCleartextTraffic is required because the Pipelines server speaks
unencrypted ws:// on a trusted LAN/VPN. It is deliberately broad because
the user types an arbitrary host. Do not expose the server to the internet.
-->
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Pipelines">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -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)
}
}
}
}
@@ -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) }
}
@@ -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}"
}
}
@@ -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<RunSummary>, 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<CacheKey, PipelineDetail>()
fun clearCache() = detailCache.clear()
suspend fun ping(): Message = client.call(Message(type = Protocol.PING))
suspend fun listPipelines(): List<PipelineSummary> =
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<SessionEvidence> =
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<String, JsonElement> = 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()
}
}
@@ -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<String> = _serverUrl.asStateFlow()
private val _workspace = MutableStateFlow(prefs.getString(KEY_WORKSPACE, "").orEmpty())
val workspace: StateFlow<String> = _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"
}
}
@@ -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<String> = stage.edges.keys.sortedWith(
compareBy<String>({ 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<GraphEdge> {
val result = ArrayList<GraphEdge>()
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<String>,
val takenRoutes: Set<GraphRoute>,
val currentStage: String?,
) {
companion object {
fun from(run: RunDetail): RunGraphState {
val stages = LinkedHashSet<String>()
val routes = LinkedHashSet<GraphRoute>()
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 })
}
}
}
@@ -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
}
@@ -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<String>? = null,
)
@Serializable
data class NotificationPolicy(
val on: List<String> = emptyList(),
val destination: String = "",
val artifacts: List<String>? = null,
)
@Serializable
data class Stage(
val limits: StageLimits? = null,
val memory: Map<String, String>? = null,
val notify: NotificationPolicy? = null,
val key: String = "",
val type: String? = null,
val output: String = "",
val prompt: String = "",
val configs: Map<String, String> = emptyMap(),
val edges: Map<String, String> = emptyMap(),
@SerialName("fallback_error") val fallbackError: Boolean = false,
val blocks: Map<String, String>? = null,
)
@Serializable
data class Schedule(
val days: List<String>? = null,
val times: List<String>? = null,
val every: String? = null,
val timezone: String? = null,
)
@Serializable
data class Settings(
val prompt: String = "",
val schedules: List<Schedule> = emptyList(),
)
@Serializable
data class Graph(
val stages: List<Stage> = 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<VersionSummary> = 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<String, MemoryRead>? = 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<FileChange> = 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<NotificationReceipt>? = null,
val sequence: Int = 0,
val stage: String = "",
val status: String = "",
val outcome: String = "",
val target: String = "",
val input: Map<String, JsonElement>? = null,
val output: Map<String, JsonElement>? = 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<String> = emptyList(),
val input: Map<String, JsonElement>? = null,
val output: Map<String, JsonElement>? = null,
val steps: List<RunStep> = 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<PipelineUsage> = emptyList(),
val days: List<DailyUsage> = 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<String>? = null,
)
@Serializable
data class SystemStatus(
val hostname: String = "",
@SerialName("started_at") val startedAt: String = "",
val uptime: String = "",
val addresses: List<NetworkAddress> = 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<SessionEvidence>? = null,
val usage: UsageStats? = null,
val status: SystemStatus? = null,
val graph: Graph? = null,
@SerialName("expected_version") val expectedVersion: Int = 0,
val templates: List<Template>? = null,
@SerialName("create_only") val createOnly: Boolean = false,
@SerialName("notification_endpoints") val notificationEndpoints: List<NotificationEndpoint>? = null,
val type: String = "",
val id: String? = null,
val time: String? = null,
val error: String? = null,
val name: String? = null,
val source: String? = null,
val version: Int = 0,
val pipelines: List<PipelineSummary>? = null,
@SerialName("pipeline_id") val pipelineId: Long = 0,
val detail: PipelineDetail? = null,
@SerialName("run_id") val runId: Long = 0,
@SerialName("run_detail") val runDetail: RunDetail? = null,
val runs: List<RunSummary>? = null,
val input: Map<String, JsonElement>? = null,
@SerialName("allow_tools") val allowTools: Boolean = false,
@SerialName("write_paths") val writePaths: List<String>? = null,
@SerialName("request_key") val requestKey: String? = null,
val workspace: String? = null,
)
@@ -0,0 +1,14 @@
package net.awan.pipelines.data.transport
import net.awan.pipelines.data.protocol.BuildInfo
/** Connection lifecycle exposed to the UI, including the last server build. */
sealed interface ConnectionState {
data object Idle : ConnectionState
data class Connecting(val attempt: Int) : ConnectionState
data class Connected(val build: BuildInfo?, val serverTime: String?) : ConnectionState
data class Disconnected(val message: String, val retrying: Boolean) : ConnectionState
}
@@ -0,0 +1,210 @@
package net.awan.pipelines.data.transport
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import kotlin.random.Random
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.PipelinesJson
import net.awan.pipelines.data.protocol.Protocol
/** A server `type:"error"` reply, surfaced with the server's own text. */
class ProtocolException(message: String) : Exception(message)
/** No live WebSocket connection is available for the request. */
class NotConnectedException(message: String = "Not connected to the Pipelines server") : Exception(message)
/**
* A single, reused WebSocket connection to `/connect`.
*
* Requests are serialized; each carries a client-generated stable id and the
* client matches replies by id, skipping unsolicited envelopes exactly like
* internal/client/client.go Call. There is no authentication of any kind.
*/
class PipelinesClient(
private val json: Json = PipelinesJson,
private val scope: CoroutineScope,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val requestTimeoutMillis: Long = 30_000L,
clientFactory: () -> OkHttpClient = { defaultPipelinesHttpClient() },
) {
private val httpClient = clientFactory()
private val _state = MutableStateFlow<ConnectionState>(ConnectionState.Idle)
val state: StateFlow<ConnectionState> = _state.asStateFlow()
private val sendLock = Mutex()
private val pending = ConcurrentHashMap<String, CompletableDeferred<Message>>()
private val sequence = AtomicLong(0)
@Volatile
private var webSocket: WebSocket? = null
@Volatile
private var endpoint: String? = null
@Volatile
private var manualClose = false
private var reconnectJob: Job? = null
private var attempt = 0
/** Opens (or re-opens) the connection to a validated server URL. */
fun connect(validated: ServerUrl.Validated) {
val httpUrl = validated.httpUrl ?: throw IllegalArgumentException("server URL is not valid")
endpoint = httpUrl
manualClose = false
attempt = 0
reconnectJob?.cancel()
reconnectJob = null
open()
}
/** Explicit user disconnect: stops reconnection and closes the socket. */
fun disconnect() {
manualClose = true
reconnectJob?.cancel()
reconnectJob = null
val socket = webSocket
webSocket = null
socket?.close(NORMAL_CLOSURE, "client closing")
failPending("Disconnected")
_state.value = ConnectionState.Idle
}
fun close() {
disconnect()
httpClient.dispatcher.executorService.shutdown()
}
/**
* Sends one request and awaits the reply with the matching id. Serialized by
* a mutex so concurrent screens cannot interleave frames.
*/
suspend fun call(request: Message): Message = withContext(ioDispatcher) {
sendLock.withLock {
val socket = webSocket ?: throw NotConnectedException()
if (_state.value !is ConnectionState.Connected) throw NotConnectedException()
val id = "android-" + sequence.incrementAndGet()
val deferred = CompletableDeferred<Message>()
pending[id] = deferred
try {
val payload = json.encodeToString(Message.serializer(), request.copy(id = id))
if (!socket.send(payload)) throw IOException("websocket send failed")
val response = withTimeout(requestTimeoutMillis) { deferred.await() }
if (response.type == Protocol.ERROR) {
throw ProtocolException(response.error?.ifBlank { "server error" } ?: "server error")
}
response
} finally {
pending.remove(id)
}
}
}
private fun open() {
val current = endpoint ?: return
attempt += 1
_state.value = ConnectionState.Connecting(attempt)
val request = Request.Builder().url(current).build()
webSocket = httpClient.newWebSocket(request, listener)
}
private fun failPending(reason: String) {
val snapshot = pending.keys.toList()
for (key in snapshot) {
pending.remove(key)?.completeExceptionally(IOException(reason))
}
}
private fun handleClosed(reason: String) {
webSocket = null
failPending(reason)
if (manualClose) {
_state.value = ConnectionState.Idle
return
}
scheduleReconnect(reason)
}
private fun scheduleReconnect(reason: String) {
if (reconnectJob?.isActive == true) return
_state.value = ConnectionState.Disconnected(reason, retrying = true)
val nextAttempt = attempt
val backoff = (BASE_BACKOFF_MILLIS shl (nextAttempt - 1).coerceAtMost(6))
.coerceAtMost(MAX_BACKOFF_MILLIS)
val jitter = Random.nextLong(0, 400)
reconnectJob = scope.launch {
delay(backoff + jitter)
if (!manualClose && endpoint != null) open()
}
}
private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
attempt = 0
_state.value = ConnectionState.Connected(build = null, serverTime = null)
}
override fun onMessage(webSocket: WebSocket, text: String) {
val message = try {
json.decodeFromString(Message.serializer(), text)
} catch (_: Exception) {
// Malformed frame: never misattribute it to a request.
return
}
val id = message.id
val deferred = if (id != null) pending.remove(id) else null
if (deferred != null) {
deferred.complete(message)
}
// Unsolicited envelopes (for example the connection's initial
// pipeline_list) have no matching id and are intentionally dropped.
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
handleClosed("Connection closed (${code})")
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(NORMAL_CLOSURE, null)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
val reason = t.message?.ifBlank { t.javaClass.simpleName } ?: "connection failed"
handleClosed(reason)
}
}
companion object {
private const val NORMAL_CLOSURE = 1000
private const val BASE_BACKOFF_MILLIS = 1_000L
private const val MAX_BACKOFF_MILLIS = 30_000L
}
}
private fun defaultPipelinesHttpClient(): OkHttpClient = OkHttpClient.Builder()
.pingInterval(20, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(0, java.util.concurrent.TimeUnit.MILLISECONDS)
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build()
@@ -0,0 +1,85 @@
package net.awan.pipelines.data.transport
import java.net.URI
import java.net.URISyntaxException
/**
* Server-URL validation mirroring internal/client/config.go: only ws/wss with a
* non-empty hostname and no userinfo/fragment. The endpoint path defaults to
* /connect, matching internal/server/websocket.go `GET /connect`.
*/
object ServerUrl {
enum class ErrorKind {
EMPTY,
MALFORMED,
UNSUPPORTED_SCHEME,
MISSING_HOST,
USER_INFO,
FRAGMENT,
}
data class Validated(
val valid: Boolean,
val wsUrl: String? = null,
val httpUrl: String? = null,
val host: String? = null,
val port: Int = 0,
val secure: Boolean = false,
val kind: ErrorKind? = null,
val message: String? = null,
)
fun validate(raw: String): Validated {
val trimmed = raw.trim()
if (trimmed.isEmpty()) {
return Validated(false, kind = ErrorKind.EMPTY, message = "Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect")
}
val uri = try {
URI(trimmed)
} catch (e: URISyntaxException) {
return Validated(false, kind = ErrorKind.MALFORMED, message = "That is not a valid URL: ${e.reason ?: "malformed syntax"}")
}
val scheme = uri.scheme?.lowercase()
if (scheme == null) {
return Validated(false, kind = ErrorKind.UNSUPPORTED_SCHEME, message = "The URL must start with ws:// or wss://")
}
if (scheme != "ws" && scheme != "wss") {
return Validated(false, kind = ErrorKind.UNSUPPORTED_SCHEME, message = "Unsupported scheme \"$scheme\"; use ws:// (trusted LAN/VPN) or wss://")
}
if (uri.userInfo != null) {
return Validated(false, kind = ErrorKind.USER_INFO, message = "Credentials are not supported; the server has no authentication. Remove userinfo from the URL")
}
if (!uri.fragment.isNullOrEmpty()) {
return Validated(false, kind = ErrorKind.FRAGMENT, message = "Remove the # fragment; it is not part of the server endpoint")
}
val host = uri.host
if (host.isNullOrBlank()) {
return Validated(false, kind = ErrorKind.MISSING_HOST, message = "The URL is missing a host, for example ws://192.168.1.20:8081/connect")
}
val secure = scheme == "wss"
val port = if (uri.port != -1) uri.port else if (secure) 443 else 80
var path = uri.path ?: ""
if (path.isBlank() || path == "/") path = "/connect"
val normalized = buildString {
append(scheme).append("://").append(host)
if (uri.port != -1) append(':').append(uri.port)
append(path)
if (!uri.query.isNullOrEmpty()) append('?').append(uri.query)
}
val httpUrl = buildString {
append(if (secure) "https" else "http").append("://").append(host)
if (uri.port != -1) append(':').append(uri.port)
append(path)
if (!uri.query.isNullOrEmpty()) append('?').append(uri.query)
}
return Validated(
valid = true,
wsUrl = normalized,
httpUrl = httpUrl,
host = host,
port = port,
secure = secure,
)
}
}
@@ -0,0 +1,265 @@
package net.awan.pipelines.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import net.awan.pipelines.PipelinesApplication
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.PipelinesRepository
import net.awan.pipelines.data.RunHistory
import net.awan.pipelines.data.SettingsRepository
import net.awan.pipelines.data.protocol.BuildInfo
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.data.transport.ServerUrl
/** Generic loading/empty/error/data state used by every screen. */
data class LoadState<T>(
val loading: Boolean = false,
val data: T? = null,
val error: String? = null,
val loaded: Boolean = false,
)
/**
* Single application ViewModel. It owns screen state and delegates all network
* work to [PipelinesRepository]; it never touches the socket directly and does
* no blocking work on the main thread.
*/
class AppViewModel(
private val repository: PipelinesRepository,
private val settings: SettingsRepository,
) : ViewModel() {
val connectionState: StateFlow<ConnectionState> = repository.connectionState
val configuredServerUrl: StateFlow<String> = settings.serverUrl
val configuredWorkspace: StateFlow<String> = settings.workspace
private val _serverUrlDraft = MutableStateFlow(settings.serverUrl.value)
val serverUrlDraft: StateFlow<String> = _serverUrlDraft.asStateFlow()
private val _workspaceDraft = MutableStateFlow(settings.workspace.value)
val workspaceDraft: StateFlow<String> = _workspaceDraft.asStateFlow()
private val _urlError = MutableStateFlow<String?>(null)
val urlError: StateFlow<String?> = _urlError.asStateFlow()
private val _workspaceError = MutableStateFlow<String?>(null)
val workspaceError: StateFlow<String?> = _workspaceError.asStateFlow()
private val _serverBuild = MutableStateFlow<BuildInfo?>(null)
val serverBuild: StateFlow<BuildInfo?> = _serverBuild.asStateFlow()
private val _serverTime = MutableStateFlow<String?>(null)
val serverTime: StateFlow<String?> = _serverTime.asStateFlow()
private val _pipelines = MutableStateFlow(LoadState<List<PipelineSummary>>())
val pipelines: StateFlow<LoadState<List<PipelineSummary>>> = _pipelines.asStateFlow()
private val _pipelineDetail = MutableStateFlow(LoadState<PipelineDetail>())
val pipelineDetail: StateFlow<LoadState<PipelineDetail>> = _pipelineDetail.asStateFlow()
private val _runs = MutableStateFlow(LoadState<RunHistory>())
val runs: StateFlow<LoadState<RunHistory>> = _runs.asStateFlow()
private val _runDetail = MutableStateFlow(LoadState<RunDetail>())
val runDetail: StateFlow<LoadState<RunDetail>> = _runDetail.asStateFlow()
private val _evidence = MutableStateFlow(LoadState<List<SessionEvidence>>())
val evidence: StateFlow<LoadState<List<SessionEvidence>>> = _evidence.asStateFlow()
private val startKeys = ConcurrentHashMap<Long, String>()
private val retryKeys = ConcurrentHashMap<Long, String>()
fun updateServerUrlDraft(value: String) {
_serverUrlDraft.value = value
_urlError.value = null
}
fun updateWorkspaceDraft(value: String) {
_workspaceDraft.value = value
_workspaceError.value = validateWorkspace(value)
}
/** Saves only an absolute path, mirroring the repository's start-run guard. */
fun saveWorkspace() {
val error = validateWorkspace(_workspaceDraft.value)
_workspaceError.value = error
if (error == null) settings.setWorkspace(_workspaceDraft.value)
}
private fun validateWorkspace(value: String): String? {
val trimmed = value.trim()
return when {
trimmed.isEmpty() -> null
!trimmed.startsWith("/") ->
"The workspace must be an absolute path that exists on the execution server."
else -> null
}
}
var lastConnectError: String? = null
private set
/** Validates and opens the shared connection, then probes with ping. */
fun connect() {
val result = ServerUrl.validate(_serverUrlDraft.value)
if (!result.valid) {
_urlError.value = result.message
return
}
_urlError.value = null
_serverUrlDraft.value = result.wsUrl ?: _serverUrlDraft.value
settings.setServerUrl(result.wsUrl ?: _serverUrlDraft.value)
repository.connect(result)
awaitConnected()
}
/** Manual reconnect using the already saved URL. */
fun reconnect() {
val result = ServerUrl.validate(settings.serverUrl.value)
if (!result.valid) {
_urlError.value = result.message
return
}
repository.connect(result)
awaitConnected()
}
fun disconnect() = repository.disconnect()
private fun awaitConnected() {
viewModelScope.launch {
val connected = withTimeoutOrNull(CONNECT_TIMEOUT_MILLIS) {
connectionState.filterIsInstance<ConnectionState.Connected>().first()
}
if (connected != null) {
probe()
} else {
lastConnectError = (connectionState.value as? ConnectionState.Disconnected)?.message
?: "Could not reach the server. Check the URL and that you are on the trusted LAN/VPN."
}
}
}
private suspend fun probe() {
try {
val pong = repository.ping()
_serverBuild.value = pong.build
_serverTime.value = pong.time
} catch (t: Throwable) {
if (t is CancellationException) throw t
// Connection state already reflects a failed probe; nothing to add.
}
}
fun refreshPipelines() = load(_pipelines) { repository.listPipelines() }
fun loadPipeline(id: Long, version: Int) = load(_pipelineDetail) {
repository.getPipeline(id, version)
}
fun refreshRuns() = load(_runs) { repository.listRuns() }
fun loadEvidence(id: Long) = load(_evidence) { repository.getRunEvidence(id) }
/**
* Drops any previously loaded evidence so a different run never shows the
* previous run's records. Evidence is then fetched on demand, never polled.
*/
fun resetEvidence() {
_evidence.value = LoadState()
}
/**
* Loads a run. [silent] is used by the bounded poll while a run is executing
* so the screen does not flash a spinner on every tick.
*/
fun loadRun(id: Long, silent: Boolean = false) {
viewModelScope.launch {
if (!silent) _runDetail.value = _runDetail.value.copy(loading = true, error = null)
try {
val run = repository.getRun(id)
_runDetail.value = LoadState(loading = false, data = run, loaded = true)
} catch (t: Throwable) {
if (t is CancellationException) throw t
if (!silent) {
_runDetail.value = _runDetail.value.copy(loading = false, error = ErrorMessages.describe(t))
}
}
}
}
fun startRun(pipelineId: Long, version: Int, prompt: String, onResult: (Result<RunDetail>) -> Unit) {
viewModelScope.launch {
try {
// Reuse the key across failed/duplicated attempts, clear on success.
val key = startKeys.getOrPut(pipelineId) { PipelinesRepository.newRequestKey() }
val run = repository.startRun(pipelineId, version, prompt, key)
startKeys.remove(pipelineId)
onResult(Result.success(run))
} catch (t: Throwable) {
if (t is CancellationException) throw t
onResult(Result.failure(t))
}
}
}
fun cancelRun(id: Long, onResult: (Result<RunDetail>) -> Unit) {
viewModelScope.launch {
try {
onResult(Result.success(repository.cancelRun(id)))
} catch (t: Throwable) {
if (t is CancellationException) throw t
onResult(Result.failure(t))
}
}
}
fun retryRun(id: Long, onResult: (Result<RunDetail>) -> Unit) {
viewModelScope.launch {
try {
val key = retryKeys.getOrPut(id) { PipelinesRepository.newRequestKey() }
val run = repository.retryRun(id, key)
retryKeys.remove(id)
onResult(Result.success(run))
} catch (t: Throwable) {
if (t is CancellationException) throw t
onResult(Result.failure(t))
}
}
}
private fun <T> load(target: MutableStateFlow<LoadState<T>>, block: suspend () -> T) {
viewModelScope.launch {
target.value = target.value.copy(loading = true, error = null)
try {
target.value = LoadState(loading = false, data = block(), loaded = true)
} catch (t: Throwable) {
if (t is CancellationException) throw t
target.value = target.value.copy(loading = false, error = ErrorMessages.describe(t))
}
}
}
companion object {
private const val CONNECT_TIMEOUT_MILLIS = 20_000L
fun factory(app: PipelinesApplication) = viewModelFactory {
initializer { AppViewModel(app.repository, app.settings) }
}
}
}
@@ -0,0 +1,33 @@
package net.awan.pipelines.ui
import java.time.Duration
import java.time.OffsetDateTime
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
/** Human duration between two RFC3339 timestamps, or null when unavailable. */
fun formatDuration(start: String, end: String): String? {
if (start.isBlank() || end.isBlank()) return null
return runCatching {
val seconds = Duration.between(OffsetDateTime.parse(start), OffsetDateTime.parse(end)).seconds
when {
seconds < 0 -> null
seconds < 60 -> "${seconds}s"
seconds < 3600 -> "${seconds / 60}m ${seconds % 60}s"
else -> "${seconds / 3600}h ${(seconds % 3600) / 60}m"
}
}.getOrNull()
}
/** Compact rendering of arbitrary protocol JSON values for read-only display. */
fun JsonElement.displayText(): String = when (this) {
is JsonPrimitive -> content
is JsonArray -> joinToString(", ") { it.displayText() }
is JsonObject -> entries.joinToString(", ") { "${it.key}=${it.value.displayText()}" }
else -> toString()
}
fun Map<String, JsonElement>?.displayMap(): String =
this?.entries?.joinToString("\n") { "${it.key}: ${it.value.displayText()}" }.orEmpty()
@@ -0,0 +1,122 @@
package net.awan.pipelines.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import net.awan.pipelines.ui.components.ConnectionBanner
import net.awan.pipelines.ui.screens.PipelineDetailScreen
import net.awan.pipelines.ui.screens.PipelineListScreen
import net.awan.pipelines.ui.screens.RunDetailScreen
import net.awan.pipelines.ui.screens.RunHistoryScreen
import net.awan.pipelines.ui.screens.SettingsScreen
private data class TopDestination(val route: String, val label: String, val icon: ImageVector)
private val destinations = listOf(
TopDestination("pipelines", "Pipelines", Icons.AutoMirrored.Filled.List),
TopDestination("runs", "Runs", Icons.Default.History),
TopDestination("settings", "Settings", Icons.Default.Settings),
)
@Composable
fun PipelinesApp(vm: AppViewModel) {
val navController = rememberNavController()
val backStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = backStackEntry?.destination?.route
val connectionState by vm.connectionState.collectAsStateWithLifecycle()
val configuredUrl by vm.configuredServerUrl.collectAsStateWithLifecycle()
Scaffold(
bottomBar = {
NavigationBar {
destinations.forEach { destination ->
val selected = currentRoute == destination.route ||
(destination.route == "pipelines" && currentRoute?.startsWith("pipeline/") == true) ||
(destination.route == "runs" && currentRoute?.startsWith("run/") == true)
NavigationBarItem(
selected = selected,
onClick = {
if (currentRoute != destination.route) {
navController.navigate(destination.route) {
popUpTo("pipelines") { inclusive = destination.route == "pipelines" }
launchSingleTop = true
}
}
},
icon = { Icon(destination.icon, contentDescription = destination.label) },
label = { Text(destination.label) },
)
}
}
},
) { padding ->
Column(Modifier.padding(padding)) {
ConnectionBanner(
state = connectionState,
configuredUrl = configuredUrl,
onReconnect = vm::reconnect,
)
NavHost(
navController = navController,
startDestination = "pipelines",
modifier = Modifier.weight(1f),
) {
composable("pipelines") {
PipelineListScreen(vm, onOpen = { id, version ->
navController.navigate("pipeline/$id/$version")
})
}
composable(
route = "pipeline/{id}/{version}",
arguments = listOf(
navArgument("id") { type = NavType.LongType },
navArgument("version") { type = NavType.IntType },
),
) { entry ->
PipelineDetailScreen(
vm = vm,
pipelineId = entry.arguments?.getLong("id") ?: 0L,
version = entry.arguments?.getInt("version") ?: 0,
onBack = { navController.popBackStack() },
onOpenRun = { runId -> navController.navigate("run/$runId") },
)
}
composable("runs") {
RunHistoryScreen(vm, onOpenRun = { runId -> navController.navigate("run/$runId") })
}
composable(
route = "run/{id}",
arguments = listOf(navArgument("id") { type = NavType.LongType }),
) { entry ->
RunDetailScreen(
vm = vm,
runId = entry.arguments?.getLong("id") ?: 0L,
onBack = { navController.popBackStack() },
)
}
composable("settings") {
SettingsScreen(vm)
}
}
}
}
}
@@ -0,0 +1,88 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
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.graphics.Color
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.transport.ConnectionState
/**
* A small, shared connection banner shown above every screen so a disconnected
* client reads as a distinct state with a reconnect affordance rather than as a
* generic request error. It reuses the Settings connection copy and renders
* nothing while connected.
*/
@Composable
fun ConnectionBanner(
state: ConnectionState,
configuredUrl: String,
onReconnect: () -> Unit,
modifier: Modifier = Modifier,
) {
when (state) {
is ConnectionState.Connected -> return
is ConnectionState.Idle -> Banner(
text = "Not connected. Enter the server URL in Settings, then connect.",
container = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
actionLabel = "Reconnect",
onAction = onReconnect,
actionEnabled = configuredUrl.isNotBlank(),
modifier = modifier,
)
is ConnectionState.Connecting -> Banner(
text = "Connecting (attempt ${state.attempt})…",
container = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = modifier,
)
is ConnectionState.Disconnected -> Banner(
text = buildString {
append("Disconnected: ${state.message}")
if (state.retrying) append(" · retrying with backoff")
},
container = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
actionLabel = "Reconnect",
onAction = onReconnect,
modifier = modifier,
)
}
}
@Composable
private fun Banner(
text: String,
container: Color,
contentColor: Color,
modifier: Modifier = Modifier,
actionLabel: String? = null,
onAction: (() -> Unit)? = null,
actionEnabled: Boolean = true,
) {
Surface(color = container, contentColor = contentColor, modifier = modifier.fillMaxWidth()) {
Row(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
text = text,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f),
)
if (actionLabel != null && onAction != null) {
TextButton(onClick = onAction, enabled = actionEnabled) { Text(actionLabel) }
}
}
}
}
@@ -0,0 +1,75 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
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.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@Composable
fun LoadingState(message: String = "Loading…", modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxSize().semantics { contentDescription = message },
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
CircularProgressIndicator()
Text(message, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 12.dp))
}
}
@Composable
fun ErrorState(message: String, onRetry: (() -> Unit)? = null, modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxSize().padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = message,
color = MaterialTheme.colorScheme.error,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyLarge,
)
if (onRetry != null) {
Button(onClick = onRetry, modifier = Modifier.padding(top = 16.dp)) { Text("Retry") }
}
}
}
@Composable
fun EmptyState(message: String, modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxSize().padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = message,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
/** Renders a labelled key/value row used across detail screens. */
@Composable
fun KeyValueRow(label: String, value: String, modifier: Modifier = Modifier) {
if (value.isBlank()) return
Column(modifier = modifier.fillMaxWidth().padding(vertical = 4.dp)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)
Text(value, style = MaterialTheme.typography.bodyMedium)
}
}
@@ -0,0 +1,401 @@
package net.awan.pipelines.ui.graph
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.abs
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.edges
private data class NodeLayout(
val key: String,
val label: String,
val x: Float,
val y: Float,
val width: Float,
val height: Float,
val terminal: Boolean,
)
private data class EdgeLayout(
val edge: GraphEdge,
val from: Offset,
val to: Offset,
val backEdge: Boolean,
val sourceRank: Int,
val targetRank: Int,
)
private data class GraphLayout(
val nodes: List<NodeLayout>,
val edges: List<EdgeLayout>,
val width: Float,
val height: Float,
)
/**
* Renders a workflow [Graph] as a pannable, zoomable node-and-arrow diagram.
*
* Node/edge/outcome semantics come from [GraphSemantics] and [edges], mirroring
* internal/tui/graph.go: content-sized stage nodes, labelled outcome edges with
* the `error*` fallback marker, `#success`/`#failure` terminals and loop routes.
* When [runState] is supplied, executed stages/routes are highlighted and the
* rest dimmed; when it is null the full definition is shown.
*/
@Composable
fun WorkflowGraph(
graph: Graph,
modifier: Modifier = Modifier,
runState: RunGraphState? = null,
selectedStage: String? = null,
) {
val density = LocalDensity.current
val textMeasurer = rememberTextMeasurer()
val layout = remember(graph, density) {
with(density) { layoutGraph(graph, this) }
}
val description = remember(graph, runState) { graphDescription(graph, runState) }
val scheme = MaterialTheme.colorScheme
val colors = remember(scheme) {
GraphColors(
success = scheme.tertiary,
error = scheme.error,
accent = listOf(scheme.primary, scheme.secondary, scheme.primaryContainer, scheme.secondaryContainer),
nodeFill = scheme.surfaceVariant,
nodeFillActive = scheme.primaryContainer,
nodeBorder = scheme.outline,
nodeText = scheme.onSurface,
terminalFill = scheme.secondaryContainer,
)
}
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
var canvasSize by remember { mutableStateOf(IntSize.Zero) }
var centered by remember { mutableStateOf(false) }
Box(
modifier = modifier
.background(MaterialTheme.colorScheme.surface)
.semantics { contentDescription = description }
.onSizeChanged { size ->
canvasSize = size
if (!centered && layout.width > 0f && layout.height > 0f) {
offset = Offset(
x = (size.width - layout.width * scale) / 2f,
y = (size.height - layout.height * scale) / 2f,
).coerceAtLeast(0f)
centered = true
}
}
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(MIN_SCALE, MAX_SCALE)
offset += pan
}
},
) {
Canvas(Modifier.fillMaxSize()) {
if (graph.stages.isEmpty()) return@Canvas
withTransform({
translate(offset.x, offset.y)
scale(scale, scale, pivot = Offset.Zero)
}) {
drawEdges(layout, colors, runState, textMeasurer)
drawNodes(layout, colors, runState, selectedStage, textMeasurer)
}
}
}
}
private fun Offset.coerceAtLeast(minimum: Float): Offset =
Offset(x.coerceAtLeast(minimum), y.coerceAtLeast(minimum))
private class GraphColors(
val success: Color,
val error: Color,
val accent: List<Color>,
val nodeFill: Color,
val nodeFillActive: Color,
val nodeBorder: Color,
val nodeText: Color,
val terminalFill: Color,
)
private fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density): GraphLayout {
if (graph.stages.isEmpty()) return GraphLayout(emptyList(), emptyList(), 0f, 0f)
val nodeWidth = with(density) { 132.dp.toPx() }
val nodeHeight = with(density) { 56.dp.toPx() }
val hGap = with(density) { 88.dp.toPx() }
val vGap = with(density) { 28.dp.toPx() }
val pad = with(density) { 32.dp.toPx() }
val ranks = rankStages(graph)
val maxRank = ranks.values.maxOrNull() ?: 0
val terminalRank = maxRank + 1
val columns = HashMap<Int, MutableList<String>>()
for (stage in graph.stages) {
val rank = ranks[stage.key] ?: 0
columns.getOrPut(rank) { mutableListOf() } += stage.key
}
val terminalKeys = mutableListOf<String>()
if (graph.stages.any { stage -> stage.edges.values.any { Protocol.isTerminal(it) || it == "#" } }) {
terminalKeys += Protocol.SUCCESS_END
terminalKeys += Protocol.FAILURE_END
}
val columnHeights = HashMap<Int, Float>()
for ((rank, keys) in columns) {
columnHeights[rank] = keys.size * nodeHeight + (keys.size - 1).coerceAtLeast(0) * vGap
}
columnHeights[terminalRank] = terminalKeys.size * nodeHeight + (terminalKeys.size - 1).coerceAtLeast(0) * vGap
val tallest = columnHeights.values.maxOrNull() ?: nodeHeight
val positions = HashMap<String, NodeLayout>()
val sortedRanks = columns.keys.sorted()
for ((columnIndex, rank) in sortedRanks.withIndex()) {
val keys = columns.getValue(rank)
val columnHeight = columnHeights.getValue(rank)
var y = (tallest - columnHeight) / 2f
val x = pad + columnIndex * (nodeWidth + hGap)
for (key in keys) {
positions[key] = NodeLayout(
key = key,
label = GraphSemantics.nodeLabel(key),
x = x,
y = y,
width = nodeWidth,
height = nodeHeight,
terminal = false,
)
y += nodeHeight + vGap
}
}
terminalKeys.forEachIndexed { index, key ->
val columnHeight = columnHeights.getValue(terminalRank)
val x = pad + sortedRanks.size * (nodeWidth + hGap)
val y = (tallest - columnHeight) / 2f + index * (nodeHeight + vGap)
positions[key] = NodeLayout(
key = key,
label = GraphSemantics.nodeLabel(key),
x = x,
y = y,
width = nodeWidth,
height = nodeHeight,
terminal = true,
)
}
val edgeLayouts = graph.edges().mapNotNull { edge ->
val source = positions[edge.source] ?: return@mapNotNull null
val target = positions[edge.target] ?: return@mapNotNull null
val sourceRank = ranks[edge.source] ?: 0
val targetRank = if (Protocol.isTerminal(edge.target)) terminalRank else (ranks[edge.target] ?: 0)
EdgeLayout(
edge = edge,
from = Offset(source.x + source.width, source.y + source.height / 2f),
to = Offset(target.x, target.y + target.height / 2f),
backEdge = targetRank <= sourceRank,
sourceRank = sourceRank,
targetRank = targetRank,
)
}
val width = pad * 2 + (sortedRanks.size + 1) * nodeWidth + sortedRanks.size * hGap
val height = pad * 2 + tallest
return GraphLayout(positions.values.toList(), edgeLayouts, width, height)
}
/** Bellman-Ford relaxation of the longest path from the entry stage, loops capped. */
private fun rankStages(graph: Graph): Map<String, Int> {
val ranks = HashMap<String, Int>()
val entry = graph.stages.firstOrNull()?.key ?: return ranks
for (stage in graph.stages) ranks[stage.key] = 0
var changed = true
var guard = 0
while (changed && guard <= graph.stages.size) {
changed = false
guard++
for (stage in graph.stages) {
for (target in stage.edges.values) {
if (Protocol.isTerminal(target) || target == "#") continue
val next = ranks[stage.key]!! + 1
if (next > (ranks[target] ?: 0)) {
ranks[target] = next
changed = true
}
}
}
}
if (!ranks.containsKey(entry)) ranks[entry] = 0
return ranks
}
private fun DrawScope.drawEdges(
layout: GraphLayout,
colors: GraphColors,
runState: RunGraphState?,
textMeasurer: TextMeasurer,
) {
for (edge in layout.edges) {
val route = GraphRoute(edge.edge.source, edge.edge.outcome, edge.edge.target)
val executed = runState == null || route in runState.takenRoutes
val color = outcomeColor(edge.edge, colors)
val alpha = if (executed) 1f else 0.25f
val path = Path()
path.moveTo(edge.from.x, edge.from.y)
if (edge.backEdge) {
val dip = maxOf(edge.from.y, edge.to.y) + 64f
path.cubicTo(edge.from.x + 24f, dip, edge.to.x - 24f, dip, edge.to.x, edge.to.y)
} else {
val midX = (edge.from.x + edge.to.x) / 2f
path.cubicTo(midX, edge.from.y, midX, edge.to.y, edge.to.x, edge.to.y)
}
drawPath(path, color = color.copy(alpha = alpha), style = Stroke(width = 3f))
drawArrowHead(edge.from, edge.to, color.copy(alpha = alpha))
val label = edge.edge.label
val measured = textMeasurer.measure(label, TextStyle(fontSize = 11.sp, color = color.copy(alpha = alpha)))
drawText(
textMeasurer = textMeasurer,
text = label,
topLeft = Offset(edge.from.x + 8f, edge.from.y - measured.size.height - 4f),
style = TextStyle(fontSize = 11.sp, color = color.copy(alpha = alpha)),
)
}
}
private fun DrawScope.drawArrowHead(from: Offset, to: Offset, color: Color) {
val angle = kotlin.math.atan2((to.y - from.y).toDouble(), (to.x - from.x).toDouble())
val size = 12f
val left = Offset(
x = to.x - size * kotlin.math.cos(angle - 0.5).toFloat(),
y = to.y - size * kotlin.math.sin(angle - 0.5).toFloat(),
)
val right = Offset(
x = to.x - size * kotlin.math.cos(angle + 0.5).toFloat(),
y = to.y - size * kotlin.math.sin(angle + 0.5).toFloat(),
)
val head = Path().apply {
moveTo(to.x, to.y)
lineTo(left.x, left.y)
lineTo(right.x, right.y)
close()
}
drawPath(head, color)
}
private fun DrawScope.drawNodes(
layout: GraphLayout,
colors: GraphColors,
runState: RunGraphState?,
selectedStage: String?,
textMeasurer: TextMeasurer,
) {
for (node in layout.nodes) {
val executed = runState == null || node.key in runState.visitedStages
val selected = node.key == selectedStage
val alpha = if (executed) 1f else 0.3f
val fill = when {
node.terminal -> colors.terminalFill
selected -> colors.nodeFillActive
else -> colors.nodeFill
}.copy(alpha = alpha)
val border = when {
node.terminal -> colors.success
else -> colors.nodeBorder
}.copy(alpha = alpha)
val topLeft = Offset(node.x, node.y)
drawRoundRect(
color = fill,
topLeft = topLeft,
size = Size(node.width, node.height),
cornerRadius = androidx.compose.ui.geometry.CornerRadius(14f, 14f),
)
drawRoundRect(
color = border,
topLeft = topLeft,
size = Size(node.width, node.height),
cornerRadius = androidx.compose.ui.geometry.CornerRadius(14f, 14f),
style = Stroke(width = if (selected) 4f else 2f),
)
val label = "[" + node.label + "]"
val measured = textMeasurer.measure(
label,
TextStyle(fontSize = 13.sp, fontWeight = FontWeight.Medium, color = colors.nodeText.copy(alpha = alpha)),
)
drawText(
textMeasurer = textMeasurer,
text = label,
topLeft = Offset(
node.x + (node.width - measured.size.width) / 2f,
node.y + (node.height - measured.size.height) / 2f,
),
style = TextStyle(fontSize = 13.sp, fontWeight = FontWeight.Medium, color = colors.nodeText.copy(alpha = alpha)),
)
}
}
private fun outcomeColor(edge: GraphEdge, colors: GraphColors): Color = when (edge.outcome) {
"error" -> colors.error
"success" -> colors.success
else -> colors.accent[abs(edge.outcome.hashCode()) % colors.accent.size]
}
/** A screen-reader description so meaning is never conveyed by colour alone. */
private fun graphDescription(graph: Graph, runState: RunGraphState?): String {
if (graph.stages.isEmpty()) return "Empty workflow graph"
val builder = StringBuilder("Workflow graph with ${graph.stages.size} stages. ")
for (stage in graph.stages) {
val executed = runState == null || stage.key in runState.visitedStages
builder.append("Stage ${stage.key}")
if (runState != null) builder.append(if (executed) ", executed" else ", not executed")
builder.append(". ")
for (outcome in GraphSemantics.outcomes(stage)) {
val target = Protocol.resolveTarget(outcome, stage.edges[outcome] ?: continue)
val label = GraphSemantics.edgeLabel(stage, outcome)
builder.append("Outcome $label goes to ${GraphSemantics.nodeLabel(target)}. ")
}
}
return builder.toString()
}
private const val MIN_SCALE = 0.3f
private const val MAX_SCALE = 3f
@@ -0,0 +1,218 @@
package net.awan.pipelines.ui.screens
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
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.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
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.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.KeyValueRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.graph.WorkflowGraph
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PipelineDetailScreen(
vm: AppViewModel,
pipelineId: Long,
version: Int,
onBack: () -> Unit,
onOpenRun: (Long) -> Unit,
modifier: Modifier = Modifier,
) {
val state by vm.pipelineDetail.collectAsStateWithLifecycle()
var showStart by remember { mutableStateOf(false) }
LaunchedEffect(pipelineId, version) { vm.loadPipeline(pipelineId, version) }
val detail = state.data?.takeIf { it.id == pipelineId }
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = { Text(detail?.name ?: "Pipeline") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { vm.loadPipeline(pipelineId, version) }) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh pipeline")
}
IconButton(onClick = { showStart = true }, enabled = detail != null) {
Icon(Icons.Default.PlayArrow, contentDescription = "Start run")
}
},
)
},
) { padding ->
when {
detail == null && state.error != null -> ErrorState(
state.error!!,
onRetry = { vm.loadPipeline(pipelineId, version) },
modifier = Modifier.padding(padding),
)
detail == null -> LoadingState("Loading pipeline…", Modifier.padding(padding))
else -> PipelineDetailContent(detail, Modifier.padding(padding))
}
}
if (showStart && detail != null) {
StartRunDialog(
vm = vm,
detail = detail,
onDismiss = { showStart = false },
onStarted = { runId ->
showStart = false
onOpenRun(runId)
},
)
}
}
@Composable
private fun PipelineDetailContent(detail: PipelineDetail, modifier: Modifier = Modifier) {
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text("${detail.name}", style = MaterialTheme.typography.headlineSmall)
Text(
"id ${detail.id} · v${detail.version} · ${detail.graph.stages.size} stages",
style = MaterialTheme.typography.bodyMedium,
)
KeyValueRow("Content hash", detail.contentHash)
KeyValueRow("Latest version", if (detail.latestVersion > 0) "v${detail.latestVersion}" else "")
KeyValueRow("Version created", detail.versionCreatedAt)
KeyValueRow("Pipeline created", detail.createdAt)
KeyValueRow("Pipeline updated", detail.updatedAt)
if (detail.versions.isNotEmpty()) {
Text("Versions", style = MaterialTheme.typography.titleMedium)
detail.versions.forEach { v ->
Card(Modifier.fillMaxWidth()) {
Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Text("v${v.version}", style = MaterialTheme.typography.titleSmall)
Text("${v.stages} stages", style = MaterialTheme.typography.bodySmall)
Text(v.createdAt, style = MaterialTheme.typography.bodySmall)
}
}
}
}
Text("Workflow graph", style = MaterialTheme.typography.titleMedium)
Text(
"Pinch to zoom, drag to pan. Edges are labelled with their outcome; error* is the implicit fallback.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Box(Modifier.fillMaxWidth().height(360.dp)) {
WorkflowGraph(graph = detail.graph, modifier = Modifier.fillMaxSize())
}
if (detail.source.isNotBlank()) {
Text("Source", style = MaterialTheme.typography.titleMedium)
Card(Modifier.fillMaxWidth()) {
Text(
text = detail.source,
fontFamily = FontFamily.Monospace,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(12.dp),
)
}
}
}
}
@Composable
private fun StartRunDialog(
vm: AppViewModel,
detail: PipelineDetail,
onDismiss: () -> Unit,
onStarted: (Long) -> Unit,
) {
var prompt by remember { mutableStateOf("") }
var submitting by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
val workspace by vm.configuredWorkspace.collectAsStateWithLifecycle()
AlertDialog(
onDismissRequest = { if (!submitting) onDismiss() },
title = { Text("Start run: ${detail.name} v${detail.version}") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
value = prompt,
onValueChange = { prompt = it },
label = { Text("Prompt (required)") },
enabled = !submitting,
minLines = 2,
modifier = Modifier.fillMaxWidth(),
)
Text(
"Workspace: ${workspace.ifBlank { "(not set — configure it in Settings)" }}",
style = MaterialTheme.typography.bodySmall,
)
if (error != null) {
Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
}
},
confirmButton = {
Button(
enabled = !submitting && prompt.isNotBlank() && workspace.isNotBlank(),
onClick = {
submitting = true
error = null
vm.startRun(detail.id, detail.version, prompt) { result ->
submitting = false
result.onSuccess { onStarted(it.id) }
.onFailure { error = ErrorMessages.describe(it) }
}
},
) { Text(if (submitting) "Starting…" else "Start") }
},
dismissButton = {
TextButton(onClick = onDismiss, enabled = !submitting) { Text("Cancel") }
},
)
}
@@ -0,0 +1,118 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.LoadingState
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PipelineListScreen(
vm: AppViewModel,
onOpen: (id: Long, version: Int) -> Unit,
modifier: Modifier = Modifier,
) {
val state by vm.pipelines.collectAsStateWithLifecycle()
var query by remember { mutableStateOf("") }
LaunchedEffect(Unit) { vm.refreshPipelines() }
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = { Text("Pipelines") },
actions = {
IconButton(onClick = vm::refreshPipelines) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh pipelines")
}
},
)
},
) { padding ->
Column(Modifier.fillMaxSize().padding(padding)) {
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Search pipelines") },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
singleLine = true,
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
)
when {
state.loading && state.data == null -> LoadingState("Loading pipelines…")
state.error != null && state.data == null -> ErrorState(state.error!!, onRetry = vm::refreshPipelines)
else -> {
val items = (state.data ?: emptyList())
.filter { it.name.contains(query, ignoreCase = true) }
if (items.isEmpty()) {
EmptyState(
if (query.isBlank()) "No pipelines are defined on this server."
else "No pipelines match \"$query\".",
)
} else {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(items, key = { it.id }) { pipeline ->
PipelineRow(pipeline) { onOpen(pipeline.id, pipeline.version) }
}
}
}
}
}
if (state.error != null && state.data != null) {
Text(
text = state.error!!,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(16.dp),
)
}
}
}
}
@Composable
private fun PipelineRow(pipeline: PipelineSummary, onClick: () -> Unit) {
Card(modifier = Modifier.fillMaxWidth().clickable(onClick = onClick)) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(pipeline.name, style = MaterialTheme.typography.titleMedium)
Text("id ${pipeline.id} · v${pipeline.version} · ${pipeline.stages} stages", style = MaterialTheme.typography.bodySmall)
if (pipeline.updatedAt.isNotBlank()) {
Text("updated ${pipeline.updatedAt}", style = MaterialTheme.typography.bodySmall)
}
}
}
}
@@ -0,0 +1,374 @@
package net.awan.pipelines.ui.screens
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
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.Cancel
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Replay
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
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.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.protocol.FileChange
import net.awan.pipelines.data.protocol.NotificationReceipt
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.LoadState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.KeyValueRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.displayMap
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.graph.WorkflowGraph
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RunDetailScreen(
vm: AppViewModel,
runId: Long,
onBack: () -> Unit,
modifier: Modifier = Modifier,
) {
val state by vm.runDetail.collectAsStateWithLifecycle()
val evidenceState by vm.evidence.collectAsStateWithLifecycle()
var confirmCancel by remember { mutableStateOf(false) }
var confirmRetry by remember { mutableStateOf(false) }
var actionError by remember { mutableStateOf<String?>(null) }
LaunchedEffect(runId) {
// Scope evidence to this run: drop the previous run's records, then fetch
// this run's evidence once (on demand; never part of the 1s poll).
vm.resetEvidence()
vm.loadRun(runId)
vm.loadEvidence(runId)
}
val run = state.data?.takeIf { it.id == runId }
val executing = run?.executing == true
// Bounded polling: only while the run is executing, stopped on terminal status.
LaunchedEffect(runId, executing) {
if (executing) {
while (true) {
delay(POLL_INTERVAL_MILLIS)
vm.loadRun(runId, silent = true)
}
}
}
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = { Text(run?.let { "Run ${it.id}" } ?: "Run") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { vm.loadRun(runId) }) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh run")
}
if (executing) {
IconButton(onClick = { confirmCancel = true }) {
Icon(Icons.Default.Cancel, contentDescription = "Cancel run")
}
}
if (run != null && !executing && run.status == "failed") {
IconButton(onClick = { confirmRetry = true }) {
Icon(Icons.Default.Replay, contentDescription = "Retry run")
}
}
},
)
},
) { padding ->
when {
run == null && state.error != null -> ErrorState(
state.error!!,
onRetry = { vm.loadRun(runId) },
modifier = Modifier.padding(padding),
)
run == null -> LoadingState("Loading run…", Modifier.padding(padding))
else -> RunDetailContent(
run = run,
onLoadEvidence = { vm.loadEvidence(runId) },
evidenceState = evidenceState,
modifier = Modifier.padding(padding),
)
}
}
if (actionError != null) {
AlertDialog(
onDismissRequest = { actionError = null },
title = { Text("Action failed") },
text = { Text(actionError!!) },
confirmButton = { TextButton(onClick = { actionError = null }) { Text("OK") } },
)
}
if (confirmCancel) {
ConfirmDialog(
title = "Cancel run $runId?",
message = "This asks the server to stop the active run.",
confirmLabel = "Cancel run",
onConfirm = {
confirmCancel = false
vm.cancelRun(runId) { result ->
result.onFailure { actionError = ErrorMessages.describe(it) }
vm.loadRun(runId, silent = true)
}
},
onDismiss = { confirmCancel = false },
)
}
if (confirmRetry) {
ConfirmDialog(
title = "Retry run $runId?",
message = "Only failed runs can be retried. The server starts a new run from the same input.",
confirmLabel = "Retry",
onConfirm = {
confirmRetry = false
vm.retryRun(runId) { result ->
result.onFailure { actionError = ErrorMessages.describe(it) }
vm.loadRun(runId, silent = true)
}
},
onDismiss = { confirmRetry = false },
)
}
}
@Composable
private fun ConfirmDialog(
title: String,
message: String,
confirmLabel: String,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = { Text(message) },
confirmButton = { Button(onClick = onConfirm) { Text(confirmLabel) } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Keep") } },
)
}
@Composable
private fun RunDetailContent(
run: RunDetail,
onLoadEvidence: () -> Unit,
evidenceState: LoadState<List<SessionEvidence>>,
modifier: Modifier = Modifier,
) {
val runState = remember(run.id, run.steps) { RunGraphState.from(run) }
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(run.name, style = MaterialTheme.typography.headlineSmall)
Text(
buildString {
append("run ${run.id} · ${run.status.ifBlank { "unknown" }}")
if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}")
if (run.executing) append(" · executing")
append(" · ${run.steps.size} recorded visits")
},
style = MaterialTheme.typography.bodyMedium,
)
KeyValueRow("Pipeline", "id ${run.pipelineId} · v${run.version}")
KeyValueRow("Workspace", run.workspace)
KeyValueRow("Content hash", run.contentHash)
KeyValueRow("Started", run.createdAt)
KeyValueRow("Finished", run.finishedAt)
KeyValueRow("Duration", formatDuration(run.createdAt, run.finishedAt) ?: "")
if (run.diagnostic.isNotBlank()) {
Text(run.diagnostic, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
if (run.graph.stages.isNotEmpty()) {
Text("Run graph", style = MaterialTheme.typography.titleMedium)
Text(
"Executed stages and routes are highlighted; the rest are dimmed. Pinch to zoom, drag to pan.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Box(Modifier.fillMaxWidth().height(340.dp)) {
WorkflowGraph(
graph = run.graph,
modifier = Modifier.fillMaxSize(),
runState = runState,
selectedStage = runState.currentStage,
)
}
} else {
Text("This server did not include the run graph.", style = MaterialTheme.typography.bodySmall)
}
val input = run.input.displayMap()
if (input.isNotBlank()) {
Text("Input", style = MaterialTheme.typography.titleMedium)
Card(Modifier.fillMaxWidth()) {
Text(input, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(12.dp))
}
}
val output = run.output.displayMap()
if (output.isNotBlank()) {
Text("Output", style = MaterialTheme.typography.titleMedium)
Card(Modifier.fillMaxWidth()) {
Text(output, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(12.dp))
}
}
Text("Session evidence", style = MaterialTheme.typography.titleMedium)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = onLoadEvidence, enabled = !evidenceState.loading) {
Text(if (evidenceState.loading) "Loading…" else "Reload session evidence")
}
}
when {
evidenceState.loading && evidenceState.data == null ->
Text("Loading session evidence…", style = MaterialTheme.typography.bodySmall)
evidenceState.error != null ->
Text(evidenceState.error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
evidenceState.loaded && evidenceState.data.isNullOrEmpty() ->
Text("No session evidence recorded.", style = MaterialTheme.typography.bodySmall)
else -> evidenceState.data.orEmpty().forEach { EvidenceCard(it) }
}
Text("Steps", style = MaterialTheme.typography.titleMedium)
if (run.steps.isEmpty()) {
Text("No steps recorded.", style = MaterialTheme.typography.bodySmall)
} else {
run.steps.forEach { StepCard(it) }
}
}
}
@Composable
private fun StepCard(step: RunStep) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text("${step.sequence}. ${step.stage}", style = MaterialTheme.typography.titleSmall)
Text(step.status, style = MaterialTheme.typography.bodySmall)
if (step.outcome.isNotBlank()) Text("outcome ${step.outcome}", style = MaterialTheme.typography.bodySmall)
if (step.agentActive) Text("agent active", style = MaterialTheme.typography.bodySmall)
}
if (step.target.isNotBlank()) Text("target ${step.target}", style = MaterialTheme.typography.bodySmall)
val duration = formatDuration(step.startedAt, step.finishedAt)
if (duration != null) Text("took $duration", style = MaterialTheme.typography.bodySmall)
if (step.sessionId.isNotBlank()) Text("session ${step.sessionId}", style = MaterialTheme.typography.bodySmall)
if (step.diagnostic.isNotBlank()) {
Text(step.diagnostic, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
step.control?.let { control ->
Text(
"visit ${control.visit}/${control.maxVisits}" +
(if (control.limitReached) " · limit reached" else "") +
(control.modelTarget?.let { " · model $it" } ?: ""),
style = MaterialTheme.typography.bodySmall,
)
}
val input = step.input.displayMap()
if (input.isNotBlank()) Text("input:\n$input", fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
val output = step.output.displayMap()
if (output.isNotBlank()) Text("output:\n$output", fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
step.fileChanges?.let { changes ->
Text(
"file changes: ${changes.status}" +
(if (changes.files.isNotEmpty()) " (${changes.files.size})" else "") +
(if (changes.skipped > 0) " · ${changes.skipped} skipped" else ""),
style = MaterialTheme.typography.bodySmall,
)
changes.files.take(MAX_LISTED_FILES).forEach { file -> FileChangeRow(file) }
}
step.notifications.orEmpty().forEach { notification -> NotificationRow(notification) }
if (step.transcript.isNotBlank()) {
Text("transcript", style = MaterialTheme.typography.labelMedium)
Text(step.transcript, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
}
}
}
}
@Composable
private fun FileChangeRow(file: FileChange) {
Text(
"· ${file.kind} ${file.path}" +
(if (file.binary) " (binary)" else "") +
(if (file.truncated) " (truncated)" else ""),
style = MaterialTheme.typography.bodySmall,
)
}
@Composable
private fun NotificationRow(receipt: NotificationReceipt) {
Text(
"notification ${receipt.status} → ${receipt.destination}" +
(receipt.diagnostic?.let { " · $it" } ?: ""),
style = MaterialTheme.typography.bodySmall,
)
}
@Composable
private fun EvidenceCard(evidence: SessionEvidence) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Evidence ${evidence.sequence}", style = MaterialTheme.typography.titleSmall)
if (evidence.sessionId.isNotBlank()) Text("session ${evidence.sessionId}", style = MaterialTheme.typography.bodySmall)
if (evidence.backend.isNotBlank()) Text("backend ${evidence.backend}", style = MaterialTheme.typography.bodySmall)
if (evidence.directory.isNotBlank()) Text("directory ${evidence.directory}", style = MaterialTheme.typography.bodySmall)
if (!evidence.diagnostic.isNullOrBlank()) {
Text(evidence.diagnostic, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
if (!evidence.data.isNullOrBlank()) {
Text(evidence.data, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
}
}
}
}
private const val POLL_INTERVAL_MILLIS = 1_000L
private const val MAX_LISTED_FILES = 20
@@ -0,0 +1,143 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.data.protocol.UsageStats
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.formatDuration
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RunHistoryScreen(
vm: AppViewModel,
onOpenRun: (Long) -> Unit,
modifier: Modifier = Modifier,
filterPipelineId: Long? = null,
) {
val state by vm.runs.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { vm.refreshRuns() }
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = { Text(if (filterPipelineId == null) "Runs" else "Runs for this pipeline") },
actions = {
IconButton(onClick = vm::refreshRuns) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh runs")
}
},
)
},
) { padding ->
when {
state.loading && state.data == null -> LoadingState("Loading runs…", Modifier.padding(padding))
state.error != null && state.data == null -> ErrorState(
state.error!!,
onRetry = vm::refreshRuns,
modifier = Modifier.padding(padding),
)
else -> {
val history = state.data
val runs = history?.runs.orEmpty()
.filter { filterPipelineId == null || it.pipelineId == filterPipelineId }
Column(Modifier.fillMaxSize().padding(padding)) {
history?.usage?.let { UsageCard(it) }
if (runs.isEmpty()) {
EmptyState("No runs have been recorded yet.")
} else {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(runs, key = { it.id }) { run -> RunRow(run) { onOpenRun(run.id) } }
}
}
if (state.error != null) {
Text(state.error!!, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
}
}
}
}
}
}
@Composable
private fun UsageCard(usage: UsageStats) {
Card(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text("Usage", style = MaterialTheme.typography.titleMedium)
Text(
"total ${usage.total} · succeeded ${usage.succeeded} · failed ${usage.failed} · " +
"canceled ${usage.canceled} · interrupted ${usage.interrupted} · active ${usage.active}",
style = MaterialTheme.typography.bodySmall,
)
if (usage.averageSeconds > 0) {
Text("average ${"%.1f".format(usage.averageSeconds)}s", style = MaterialTheme.typography.bodySmall)
}
}
}
}
@Composable
private fun RunRow(run: RunSummary, onClick: () -> Unit) {
Card(Modifier.fillMaxWidth().clickable(onClick = onClick)) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(run.name, style = MaterialTheme.typography.titleMedium)
Text("v${run.version}", style = MaterialTheme.typography.bodySmall)
}
Text(
buildString {
append("run ${run.id} · ${run.status.ifBlank { "unknown" }}")
if (run.outcome.isNotBlank()) append(" · outcome ${run.outcome}")
if (run.executing) append(" · executing")
if (run.currentStage.isNotBlank()) append(" · stage ${run.currentStage}")
append(" · ${run.completedSteps} steps")
},
style = MaterialTheme.typography.bodySmall,
)
val duration = formatDuration(run.createdAt, run.finishedAt)
val timing = buildString {
append("started ${run.createdAt}")
if (duration != null) append(" · took $duration")
}
if (run.createdAt.isNotBlank()) Text(timing, style = MaterialTheme.typography.bodySmall)
if (run.diagnostic.isNotBlank()) {
Text(run.diagnostic, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
}
if (!run.resultPreview.isNullOrBlank()) {
Text(run.resultPreview, style = MaterialTheme.typography.bodySmall)
}
}
}
}
@@ -0,0 +1,141 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.ui.AppViewModel
@Composable
fun SettingsScreen(vm: AppViewModel, modifier: Modifier = Modifier) {
val serverUrl by vm.serverUrlDraft.collectAsStateWithLifecycle()
val workspace by vm.workspaceDraft.collectAsStateWithLifecycle()
val urlError by vm.urlError.collectAsStateWithLifecycle()
val state by vm.connectionState.collectAsStateWithLifecycle()
val build by vm.serverBuild.collectAsStateWithLifecycle()
val serverTime by vm.serverTime.collectAsStateWithLifecycle()
val configuredWorkspace by vm.configuredWorkspace.collectAsStateWithLifecycle()
val workspaceError by vm.workspaceError.collectAsStateWithLifecycle()
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text("Connection", style = MaterialTheme.typography.headlineSmall)
OutlinedTextField(
value = serverUrl,
onValueChange = vm::updateServerUrlDraft,
label = { Text("Server URL") },
placeholder = { Text("ws://192.168.1.20:8081/connect") },
singleLine = true,
isError = urlError != null,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
supportingText = {
Text(urlError ?: "ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. No authentication is used.")
},
modifier = Modifier.fillMaxWidth(),
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = vm::connect) { Text("Connect") }
if (state is ConnectionState.Connected || state is ConnectionState.Connecting) {
OutlinedButton(onClick = vm::disconnect) { Text("Disconnect") }
} else {
OutlinedButton(onClick = vm::reconnect) { Text("Reconnect") }
}
}
ConnectionStatusCard(state, build?.version, build?.commit, serverTime)
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
Text(
text = "Trusted LAN/VPN only. The Pipelines API has no authentication and is not " +
"internet-safe. Do not expose it to untrusted networks, and never enter provider " +
"credentials here \u2014 the app stores none.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onErrorContainer,
modifier = Modifier.padding(16.dp),
)
}
Text("Workspace", style = MaterialTheme.typography.headlineSmall)
OutlinedTextField(
value = workspace,
onValueChange = vm::updateWorkspaceDraft,
label = { Text("Workspace path (on the server)") },
placeholder = { Text("/Users/you/repos/pipelines") },
singleLine = true,
isError = workspaceError != null,
supportingText = {
Text(
workspaceError
?: "An absolute directory that already exists on the execution server. For Docker, " +
"mount the host directory at the same absolute path with its owner's UID/GID. " +
"This is not the phone's storage.",
)
},
modifier = Modifier.fillMaxWidth(),
)
Button(onClick = vm::saveWorkspace, enabled = workspaceError == null) { Text("Save workspace") }
Text("Saved workspace: ${configuredWorkspace.ifBlank { "(none)" }}")
}
}
@Composable
private fun ConnectionStatusCard(
state: ConnectionState,
version: String?,
commit: String?,
serverTime: String?,
) {
Card(modifier = Modifier.fillMaxWidth()) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
when (state) {
is ConnectionState.Idle -> Text("Not connected", style = MaterialTheme.typography.titleMedium)
is ConnectionState.Connecting -> {
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.padding(end = 12.dp))
Text("Connecting (attempt ${state.attempt})\u2026")
}
}
is ConnectionState.Connected -> {
Text("Connected", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)
if (version != null) {
Text("Server build ${version}${if (!commit.isNullOrBlank()) " ($commit)" else ""}")
}
if (serverTime != null) Text("Server time $serverTime")
}
is ConnectionState.Disconnected -> {
Text("Disconnected", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.error)
Text(state.message)
if (state.retrying) Text("Retrying with backoff\u2026")
}
}
}
}
}
@@ -0,0 +1,29 @@
package net.awan.pipelines.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
/** Material 3 theming with optional dynamic color and dark-mode support. */
@Composable
fun PipelinesTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val context = LocalContext.current
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> darkColorScheme()
else -> lightColorScheme()
}
MaterialTheme(colorScheme = colorScheme, content = content)
}
@@ -0,0 +1,15 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#1565C0"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#FFFFFF"
android:pathData="M30,32h18v8h-18z M30,50h38v8h-38z M30,68h28v8h-28z" />
<path
android:fillColor="#FFFFFF"
android:pathData="M62,32l16,4l-16,4z" />
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Pipelines" parent="android:Theme.Material.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">Pipelines</string>
</resources>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Pipelines" parent="android:Theme.Material.Light.NoActionBar">
<item name="android:windowBackground">@android:color/white</item>
</style>
</resources>
@@ -0,0 +1,81 @@
package net.awan.pipelines.data.protocol
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class GraphSemanticsTest {
private fun stage(key: String, edges: Map<String, String>, fallback: Boolean = false) =
Stage(key = key, edges = edges, fallbackError = fallback)
@Test
fun outcomeOrderIsSuccessThenOthersThenError() {
val s = stage("a", mapOf("error" to "#failure", "retry" to "b", "success" to "#success"))
assertEquals(listOf("success", "retry", "error"), GraphSemantics.outcomes(s))
}
@Test
fun fallbackErrorIsMarked() {
val s = stage("a", mapOf("error" to "#failure"), fallback = true)
assertEquals("error*", GraphSemantics.edgeLabel(s, "error"))
assertEquals("success", GraphSemantics.edgeLabel(stage("b", mapOf("success" to "#success")), "success"))
}
@Test
fun resolvesHashShorthandToTerminal() {
assertEquals("#success", Protocol.resolveTarget("success", "#"))
assertEquals("#failure", Protocol.resolveTarget("error", "#"))
assertEquals("next", Protocol.resolveTarget("success", "next"))
assertTrue(Protocol.isTerminal("#success"))
assertFalse(Protocol.isTerminal("next"))
}
@Test
fun edgesUseStableIdsAndResolvedTargets() {
val graph = Graph(
stages = listOf(
stage("a", mapOf("success" to "b", "error" to "#")),
stage("b", mapOf("success" to "#success", "error" to "#"), fallback = true),
),
)
val edges = graph.edges()
assertEquals(4, edges.size)
assertEquals(1, edges[0].id)
assertEquals("a", edges[0].source)
assertEquals("b", edges[0].target)
assertEquals("#failure", edges[1].target)
assertEquals("error", edges[1].outcome)
assertEquals("error*", edges.last().label)
assertEquals("#failure", edges.last().target)
assertEquals("success", edges[2].label)
assertEquals("#success", edges[2].target)
}
@Test
fun compactThresholdMatchesTui() {
val stages = (1..201).map { stage("s$it", mapOf("success" to "#success")) }
assertTrue(GraphSemantics.compactGraph(Graph(stages = stages)))
assertFalse(GraphSemantics.compactGraph(Graph(stages = stages.take(10))))
}
@Test
fun runGraphStateTracksVisitedStagesAndRoutes() {
val run = RunDetail(
id = 1,
name = "demo",
version = 1,
status = "failed",
currentStage = "b",
steps = listOf(
RunStep(sequence = 1, stage = "a", outcome = "error", target = "#failure"),
RunStep(sequence = 2, stage = "b", outcome = "success", target = "#success"),
),
)
val state = RunGraphState.from(run)
assertEquals(setOf("a", "b", "#failure", "#success"), state.visitedStages)
assertTrue(GraphRoute("a", "error", "#failure") in state.takenRoutes)
assertEquals("b", state.currentStage)
}
}
@@ -0,0 +1,219 @@
package net.awan.pipelines.data.protocol
import kotlinx.serialization.json.JsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class ProtocolModelTest {
@Test
fun parsesEnvelopeWithUnknownFieldsAndNestedDetail() {
val json = """
{
"type": "pipeline",
"id": "cli-3",
"future_field": {"nested": true},
"detail": {
"id": 7,
"name": "demo",
"version": 2,
"stages": 3,
"latest_version": 2,
"content_hash": "abc",
"source": "# stage one",
"graph": {"stages": [{"key": "one", "edges": {"success": "#success"}, "fallback_error": true}]},
"versions": [{"version": 1, "stages": 2, "created_at": "2026-01-01T00:00:00Z"}]
}
}
""".trimIndent()
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
assertEquals(Protocol.PIPELINE, message.type)
assertEquals("cli-3", message.id)
val detail = message.detail!!
assertEquals(7L, detail.id)
assertEquals("demo", detail.name)
assertEquals(2, detail.latestVersion)
assertEquals(1, detail.versions.size)
assertEquals("#success", detail.graph.stages.first().edges["success"])
assertTrue(detail.graph.stages.first().fallbackError)
}
@Test
fun runDetailWithNullOutputDoesNotCrash() {
val json = """
{
"type": "run",
"run_detail": {
"id": 11,
"pipeline_id": 7,
"name": "demo",
"version": 2,
"status": "failed",
"executing": false,
"steps": [
{"sequence": 1, "stage": "one", "status": "failed", "outcome": "error", "target": "#failure", "output": null}
]
}
}
""".trimIndent()
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
val run = message.runDetail!!
assertEquals(11L, run.id)
assertEquals(1, run.steps.size)
assertNull(run.output)
assertEquals("#failure", run.steps.first().target)
}
@Test
fun runRequestRoundTripsRequestKeyAndPrompt() {
val request = Message(
type = Protocol.RUN_PIPELINE,
id = "android-1",
pipelineId = 7,
version = 2,
requestKey = "android-key",
workspace = "/work",
input = mapOf("prompt" to JsonPrimitive("do it")),
)
val encoded = PipelinesJson.encodeToString(Message.serializer(), request)
val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded)
assertEquals(Protocol.RUN_PIPELINE, decoded.type)
assertEquals("android-key", decoded.requestKey)
assertEquals(7L, decoded.pipelineId)
assertEquals(2, decoded.version)
assertEquals("/work", decoded.workspace)
assertEquals("do it", decoded.input?.get("prompt")?.let { (it as JsonPrimitive).content })
}
@Test
fun cancelRunRequestKeepsRunId() {
val request = Message(type = Protocol.CANCEL_RUN, id = "android-2", runId = 11)
val encoded = PipelinesJson.encodeToString(Message.serializer(), request)
val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded)
assertEquals(Protocol.CANCEL_RUN, decoded.type)
assertEquals(11L, decoded.runId)
}
@Test
fun pipelineDetailPopulatesInheritedAndWireNameFields() {
val json = """
{
"type": "pipeline",
"detail": {
"id": 7,
"name": "demo",
"version": 2,
"stages": 3,
"created_at": "2026-01-01T00:00:00Z",
"updated_at": "2026-01-02T00:00:00Z",
"latest_version": 4,
"version_created_at": "2026-01-02T00:00:00Z",
"content_hash": "abc123",
"source": "# stage one",
"graph": {"stages": []},
"versions": [{"version": 1, "stages": 2, "created_at": "2026-01-01T00:00:00Z"}]
}
}
""".trimIndent()
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
val detail = message.detail!!
assertEquals(7L, detail.id)
assertEquals("demo", detail.name)
assertEquals(2, detail.version)
assertEquals(3, detail.stages)
assertEquals("2026-01-01T00:00:00Z", detail.createdAt)
assertEquals("2026-01-02T00:00:00Z", detail.updatedAt)
assertEquals(4, detail.latestVersion)
assertEquals("2026-01-02T00:00:00Z", detail.versionCreatedAt)
assertEquals("abc123", detail.contentHash)
}
@Test
fun runDetailPopulatesInheritedAndWireNameFields() {
val json = """
{
"type": "run",
"run_detail": {
"id": 11,
"pipeline_id": 7,
"name": "demo",
"version": 2,
"content_hash": "abc",
"status": "failed",
"executing": false,
"outcome": "error",
"current_stage": "one",
"created_at": "2026-01-01T00:00:00Z",
"finished_at": "2026-01-01T00:01:00Z",
"diagnostic": "boom",
"result_preview": "partial",
"completed_steps": 2,
"retry_of": 3,
"workspace": "/work",
"steps": []
}
}
""".trimIndent()
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
val run = message.runDetail!!
assertEquals(11L, run.id)
assertEquals(7L, run.pipelineId)
assertEquals("abc", run.contentHash)
assertEquals("failed", run.status)
assertEquals("one", run.currentStage)
assertEquals("2026-01-01T00:00:00Z", run.createdAt)
assertEquals("2026-01-01T00:01:00Z", run.finishedAt)
assertEquals("partial", run.resultPreview)
assertEquals(2, run.completedSteps)
assertEquals(3L, run.retryOf)
assertEquals("/work", run.workspace)
}
@Test
fun usageStatsAndPipelineUsagePopulateInheritedCounts() {
val json = """
{
"type": "runs",
"usage": {
"total": 5,
"succeeded": 3,
"failed": 1,
"canceled": 1,
"interrupted": 0,
"active": 0,
"average_seconds": 12.5,
"pipelines": [
{
"pipeline_id": 7,
"name": "demo",
"total": 2,
"succeeded": 2,
"failed": 0,
"canceled": 0,
"interrupted": 0,
"active": 0,
"average_seconds": 3.5
}
],
"days": [{"date": "2026-01-01", "runs": 2}]
},
"runs": []
}
""".trimIndent()
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
val usage = message.usage!!
assertEquals(5, usage.total)
assertEquals(3, usage.succeeded)
assertEquals(1, usage.failed)
assertEquals(12.5, usage.averageSeconds, 0.0)
assertEquals(1, usage.days.size)
val pipeline = usage.pipelines.single()
assertEquals(7L, pipeline.pipelineId)
assertEquals("demo", pipeline.name)
assertEquals(2, pipeline.total)
assertEquals(2, pipeline.succeeded)
assertEquals(3.5, pipeline.averageSeconds, 0.0)
}
}
@@ -0,0 +1,64 @@
package net.awan.pipelines.data.transport
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ServerUrlTest {
@Test
fun acceptsWsWithExplicitPort() {
val result = ServerUrl.validate("ws://192.168.1.20:8081/connect")
assertTrue(result.valid)
assertEquals("ws://192.168.1.20:8081/connect", result.wsUrl)
assertEquals("http://192.168.1.20:8081/connect", result.httpUrl)
assertEquals("192.168.1.20", result.host)
assertEquals(8081, result.port)
assertFalse(result.secure)
}
@Test
fun defaultsPathToConnect() {
val result = ServerUrl.validate("wss://pipelines.example/vpn")
assertTrue(result.valid)
assertEquals("wss://pipelines.example/vpn", result.wsUrl)
assertTrue(result.secure)
val noPath = ServerUrl.validate("ws://host:8080")
assertTrue(noPath.valid)
assertEquals("ws://host:8080/connect", noPath.wsUrl)
}
@Test
fun rejectsUnsupportedScheme() {
val result = ServerUrl.validate("http://192.168.1.20:8081/connect")
assertFalse(result.valid)
assertEquals(ServerUrl.ErrorKind.UNSUPPORTED_SCHEME, result.kind)
}
@Test
fun rejectsMissingHost() {
val result = ServerUrl.validate("ws:///connect")
assertFalse(result.valid)
assertEquals(ServerUrl.ErrorKind.MISSING_HOST, result.kind)
}
@Test
fun rejectsUserInfoAndFragment() {
assertEquals(
ServerUrl.ErrorKind.USER_INFO,
ServerUrl.validate("ws://user:pass@host:8080/connect").kind,
)
assertEquals(
ServerUrl.ErrorKind.FRAGMENT,
ServerUrl.validate("ws://host:8080/connect#frag").kind,
)
}
@Test
fun rejectsEmptyAndSchemeLessInput() {
assertEquals(ServerUrl.ErrorKind.EMPTY, ServerUrl.validate(" ").kind)
assertEquals(ServerUrl.ErrorKind.UNSUPPORTED_SCHEME, ServerUrl.validate("host:8080/connect").kind)
}
}
+7
View File
@@ -0,0 +1,7 @@
// Top-level build file. Plugins are declared here (apply false) and applied per module.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.kotlin.serialization) apply false
}
+9
View File
@@ -0,0 +1,9 @@
# Project-wide Gradle settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.caching=true
# AndroidX / Kotlin
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
+37
View File
@@ -0,0 +1,37 @@
[versions]
agp = "8.7.2"
kotlin = "2.0.21"
coreKtx = "1.13.1"
activityCompose = "1.9.3"
composeBom = "2024.10.00"
navigationCompose = "2.8.4"
lifecycle = "2.8.7"
coroutines = "1.9.0"
serialization = "1.7.3"
okhttp = "4.12.0"
junit = "4.13.2"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
+11
View File
@@ -0,0 +1,11 @@
## NOTE: the wrapper JAR (gradle/wrapper/gradle-wrapper.jar) is a generated binary
## and is intentionally not committed. Generate a working wrapper on a machine with
## Gradle installed: `cd android && gradle wrapper --gradle-version 8.9`.
## Until then, build with a locally installed Gradle 8.9+: `gradle :app:assembleDebug`.
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+24
View File
@@ -0,0 +1,24 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "PipelinesAndroid"
include(":app")