chore: remove the JavaScript web client and the Kotlin Android app; the Flutter app replaces both

This commit is contained in:
2026-10-23 21:46:58 +01:00
parent 7958d1830e
commit 8527506da1
373 changed files with 105 additions and 107868 deletions
+1 -19
View File
@@ -15,24 +15,6 @@ 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/
# Web client: review captures (`ui-smoke.mjs --out captures`) are evidence, not
# tracked source. They live beside the checkout, so the whole name is ignored to
# keep the delivery checkout clean for landing.
# Review captures are evidence, not tracked source.
captures/
android/.idea/
android/*.iml
android/**/*.apk
android/**/*.aab
android/**/*.jks
android/**/*.keystore
!android/**/data/
+1 -1
View File
@@ -45,6 +45,6 @@ Update relevant rules, skills and documentation when they are the requested task
ordinary feature work can leave a focused docs/notes entry instead.
Use the current-source skill installer to refresh managed installed skills.
Do not restart a shared service over active work. Do not use the personal Fold
for tests; it is a delivery device. Follow the Android map's target leases.
for tests; it is a delivery device. Follow the device leases in app/AGENTS.md.
Ask only for genuinely missing decisions or destructive/out-of-scope actions,
not routine steps already covered by the user's request.
+3 -3
View File
@@ -98,8 +98,8 @@ Notifications have separate channels:
- **Web alerts:** require the page to be open and browser permission where
supported. Closed-app browser push is not implemented.
- **ntfy:** optional phone notifications, independent of the Pipelines Android
app. Removing that app does not unsubscribe an ntfy client.
- **ntfy:** optional phone notifications, independent of the Pipelines app.
Removing the app does not unsubscribe an ntfy client.
See [notification setup](docs/ntfy.md). The installer checks publishing, not
actual delivery to your phone.
@@ -111,7 +111,7 @@ actual delivery to your phone.
- [Configured harnesses and models](docs/harnesses-and-control.md)
- [CLI commands](docs/cli.md)
- [Pipeline format](internal/author/skill/references/format.md)
- [Web client and verification](web/README.md)
- [App (web and Android)](app/README.md) · [Web proxy](web/README.md)
- [Artifacts](docs/stage-artifacts.md) · [File diffs](docs/stage-file-diffs.md)
- [Transfer pipeline definitions](docs/pipeline-transfer.md)
-107
View File
@@ -1,107 +0,0 @@
# The Android app — working map
Read this before touching `android/`. It is the project-specific half; how Android projects in
general are built, tested and reviewed belongs to the pipeline that started you.
## Build and test (offline, never with the daemon)
This checkout has no `gradlew`; the toolchain uses the installed distribution:
```sh
# Run these commands from the repository root.
export JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home'
export ANDROID_HOME="$HOME/Library/Android/sdk"
GRADLE=/Users/alan/.gradle/wrapper/dists/gradle-8.11.1-bin/bpt9gzteqjrbo1mjrsomdt32c/gradle-8.11.1/bin/gradle
"$GRADLE" -p android --offline --no-daemon :app:assembleDebug # ~7 s incremental
"$GRADLE" -p android --offline --no-daemon :app:testDebugUnitTest # 400+ tests, ~8-13 s
```
Always `--no-daemon`: a leftover daemon is what makes these look slow. Add **one** test class at a
time while iterating — the full suite is for the end.
## Devices and the resource pool
The ADB executable is `/Users/alan/Library/Android/sdk/platform-tools/adb`.
Use that absolute path (or explicitly add its directory to PATH); `adb: command
not found` alone is not evidence that the leased device is disconnected.
For populated attention review, `TestExportReadyAttentionReviewFixture` exports a
create-only scratch database when `PIPELINES_ATTENTION_REVIEW_DIR` names a new
directory. Its fixture.json identifies one failed, one finished and one waiting
run and the workspace. Build a scratch server, read back those states, and keep
the owned server alive through all UI interactions. The export itself does not
leave a server running or configure a device. Never use a dead scratch endpoint.
Only the **UI reviewer**, while its stage holds the runner-granted resource for its
visit, may use a device. Implementers and code reviewers do code, builds, unit
tests and source review only: **no adb, installs, captures, device-setting changes
or main-build restoration**. Never acquire a device using sleep/check loops. The
runner grants exactly one concrete member of the `android-devices` resource pool
and passes it to the stage as `resource_target`; take the `adb -s` target from
`resource_target.metadata.adb_serial` and do not choose a device yourself.
The pool's two members are:
- `phone-47241FDAS00DLK` — the operator's **Pixel 9 Pro XL**, adb serial
`47241FDAS00DLK` (metadata `kind=phone`).
- `emulator-Pipelines_Fold_A` — one managed **foldable emulator**, adb serial
`emulator-5554` (metadata `kind=emulator`, `avd=Pipelines_Fold_A`). Its unfolded
built-in display is 2076x2152; its cover display is 1080x2424.
The operator's **Pixel 10 Pro Fold** (`58281FDCG000JF`) is delivery-only: never a
test target. Do not start an ad-hoc emulator — the one managed foldable AVD above
is the only emulator in scope.
The UI reviewer records original app connection/workspace, display size and power/settings
before changing them. Before any capture: `svc power stayon usb`, `settings put global stay_on_while_plugged_in 7`,
`input keyevent KEYCODE_WAKEUP`, `wm dismiss-keyguard`. Capture with
`adb -s <serial> shell screencap -p /sdcard/shot.png` then `adb pull` — never `exec-out > file`.
Wide layout: `wm size 2000x2244`; the fold's unfolded shape is `wm size 2076x2152`; `wm size reset`
afterwards either way.
Create controlled fixtures for changed screens/states (including human-decision sheets)
on a scratch server/database and throwaway session; never depend on incidental production
state, change a real operator session, or restart a deployed service. Use the configured
authoritative endpoint, never a scratch URL as a project default. Keep all shell/ADB work
foreground and awaited: no detached/background processes may outlive the lease.
UI review includes restoring the captured original settings and main's build before its
successful return. Confirm every tool has exited. If capture, restoration or cleanup fails,
report the failure explicitly; do not claim verification or readiness. Uncertain termination
must fail closed and keep ownership quarantined, not delete a lock or expire it by age.
Return `output.resource_cleanup_confirmed=false` if restoration/readiness is uncertain;
that generic release veto retains the runner lease even if the harness reports idle.
## Geometry is tokenised, and a test enforces it
Every dimension comes from `ui/theme/Dimens.kt` (plus the layout itself) — no new hardcoded `dp`, no
percentages. `DimensTest` fails the build for a raw literal outside that file, so a value that
genuinely needs a new token goes there, named for its purpose.
## Where things are
- `ui/PipelinesApp.kt` — the app shell: destinations, the floating pill, the omni-search morph.
- `ui/chat/` — the chat: `ChatScreen`/`ChatTranscript`/`ChatComposer` (list, transcript, composer),
`ChatStore` (multi-conversation state), `ChatFormat` (parts → rendering), `ChatOverrides` (local
rename/hide), `Markdown`, `ChatScroll`.
- `ui/screens/` — `PipelineListScreen`, `PipelineDetailScreen`, `RunHistoryScreen`, `RunDetailScreen`,
`SettingsScreen`, `Timeline`.
- `ui/graph/` — the workflow graph, stage panes, artifacts gallery and viewer.
- `ui/components/` — `ListRow`, `DetailTabs`, `PaneIdentity`, `RunStatus`, `AttentionSurface`.
- `data/` — `PipelinesRepository` (the socket client) and `data/protocol/` (wire shapes).
- The app talks to the Pipelines server over the websocket in `data/PipelinesRepository.kt`; live run
state arrives as pushed `run_event` frames, and every view that shows run state folds them.
## Publishing a build
Copy the APK into the running run's artifacts directory as `pipelines-debug-wip-<short-HEAD>.apk` and
report the LAN URL. The UI reviewer alone, under the same lease, restores **main's** build after an install:
`/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/deploy-app.sh main`.
## Traps
- A build made in a worktree that is behind main is missing features main has — sync before building,
and say which revision you built.
- Restore the app's captured original connection and workspace after a fixture test,
using the configured authoritative endpoint; then force-stop and relaunch under the lease.
Never substitute a hardcoded or disposable scratch endpoint for the original configuration.
- `mStayOn`/screen timeout are already set; do not "fix" the device by locking or sleeping it.
-6326
View File
File diff suppressed because it is too large Load Diff
-70
View File
@@ -1,70 +0,0 @@
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.process)
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
@@ -1,11 +0,0 @@
# 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(...);
}
-81
View File
@@ -1,81 +0,0 @@
<?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" />
<!--
POST_NOTIFICATIONS is requested at runtime on Android 13+ (API 33), the
first time a run actually needs the operator or the attention surface is
opened, and asked at most once: a refusal degrades to the in-app Needs you
surface rather than nagging. Runs that need the operator post into the one
"Runs that need you" channel from the app's own process.
-->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="true"
android:enableOnBackInvokedCallback="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.
-->
<!--
adjustResize: the app is drawn edge-to-edge (enableEdgeToEdge), so it
reads the IME from the Compose window insets (paneSafeArea /
WindowInsets.safeDrawing) and applies it once in the surface that owns
it. Both the omni-search field and the chat composer (imePadding) sit
directly above the keyboard. This is the mode the chat UI was reviewed
with; re-check that composer before changing it to adjustNothing.
-->
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:launchMode="singleTop"
android:theme="@style/Theme.Pipelines"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!--
The notification click action opens the run it names. The server
publishes `pipelines://run/<id>` as the ntfy Click URL, so a tap on
the phone's own notification resolves here rather than to a browser.
This is the app's one deep link and it only opens a run; it starts
nothing.
-->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="pipelines" android:host="run" />
</intent-filter>
</activity>
<!--
The only exported-URI surface: fetched artifacts are shared out of
the app cache through ACTION_SEND. The provider is not exported
and grants read access per-uri (FLAG_GRANT_READ_URI_PERMISSION), and
file_paths.xml scopes it to the single `shared-artifacts` cache
subdirectory. No other app-visible file path is exposed.
-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
@@ -1,59 +0,0 @@
package net.awan.pipelines
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewmodel.compose.viewModel
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.PipelinesApp
import net.awan.pipelines.ui.runLinkFromDeepLink
import net.awan.pipelines.ui.theme.PipelinesTheme
class MainActivity : ComponentActivity() {
// The run a deep link asks to open — the notification's `pipelines://run/<id>`
// click action — and what inside it to open (a waiting run's `decide` action
// opens its decision sheet). Both are read from the launch or update intent
// and cleared once PipelinesApp has opened them, so a recomposition never
// re-navigates.
private var deepLinkedRunId by mutableStateOf<Long?>(null)
private var deepLinkedAction by mutableStateOf<String?>(null)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
applyDeepLink(intent)
enableEdgeToEdge()
val app = application as PipelinesApplication
setContent {
PipelinesTheme {
val vm: AppViewModel = viewModel(factory = AppViewModel.factory(app))
PipelinesApp(
vm = vm,
initialRunId = deepLinkedRunId,
initialRunAction = deepLinkedAction,
onInitialRunHandled = {
deepLinkedRunId = null
deepLinkedAction = null
},
)
}
}
}
/** A notification tap while the app is already open opens its run in place. */
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
applyDeepLink(intent)
}
private fun applyDeepLink(intent: Intent?) {
val link = runLinkFromDeepLink(intent?.data?.toString())
deepLinkedRunId = link?.runId
deepLinkedAction = link?.action
}
}
@@ -1,71 +0,0 @@
package net.awan.pipelines
import android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import net.awan.pipelines.data.ForegroundReconnector
import net.awan.pipelines.data.PipelinesRepository
import net.awan.pipelines.data.SettingsRepository
import net.awan.pipelines.data.transport.PipelinesClient
import net.awan.pipelines.data.transport.ServerUrl
import net.awan.pipelines.notify.RunNotifier
/**
* 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) }
/**
* Posts the app's own Android notifications for runs that need the operator.
* Its channel is created once, before anything can post, so a notification is
* never dropped for a missing channel.
*/
val runNotifier: RunNotifier by lazy { RunNotifier(this) }
/**
* The one owner of return-to-foreground recovery: when the process comes back
* to the front it restores a connection the background took away, with no
* interaction. It is created once with the Application and observes the
* process lifecycle, so every Activity and ViewModel recreation leaves it
* untouched. The liveness check is the existing `ping`; the reconnect is the
* same shared-client connect the app's own Connect/Reconnect uses, so the
* policy lives only in `foregroundAction` and the client's backoff stays the
* only reconnect mechanism.
*/
private val foregroundReconnector: ForegroundReconnector by lazy {
ForegroundReconnector(
state = { repository.connectionState.value },
confirmAlive = {
// The existing ping is the positive check: on a dead socket it
// throws (or never answers) instead of returning, so reaching the
// next line is the proof of life.
repository.ping()
true
},
reconnect = {
// A saved URL that no longer validates is left for Settings to
// report; there is nothing to reconnect to.
val validated = ServerUrl.validate(settings.serverUrl.value)
if (validated.valid) repository.recover(validated)
},
scope = applicationScope,
)
}
override fun onCreate() {
super.onCreate()
runNotifier.ensureChannel()
ProcessLifecycleOwner.get().lifecycle.addObserver(foregroundReconnector)
}
}
@@ -1,23 +0,0 @@
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}"
}
}
@@ -1,81 +0,0 @@
package net.awan.pipelines.data
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.data.transport.ForegroundAction
import net.awan.pipelines.data.transport.foregroundAction
/**
* The one lifecycle-aware owner of the app's return-to-foreground recovery.
*
* While another app is in front Android freezes — and often kills — this process,
* so the socket it holds dies or goes quiet and the client's own bounded backoff
* either never starts or starts too late for the operator, who comes back and
* taps Connect. The client's backoff (see `PipelinesClient.scheduleReconnect`) is
* still the only reconnect mechanism; this owner only decides *when* to drive it,
* and does so the moment the app becomes visible again.
*
* It observes the whole process lifecycle (a `ProcessLifecycleOwner`), never the
* Activity or the ViewModel, both of which Android recreates: the owner is
* created once with the Application and survives every recreation. The decision
* itself is the one pure [foregroundAction] policy; this class supplies only the
* current state, a positive liveness check and the reconnect effect, so the
* policy is unit-testable with no device, socket or framework.
*/
class ForegroundReconnector(
private val state: () -> ConnectionState,
private val confirmAlive: suspend () -> Boolean,
private val reconnect: () -> Unit,
private val scope: CoroutineScope,
private val confirmTimeoutMillis: Long = CONFIRM_TIMEOUT_MILLIS,
) : DefaultLifecycleObserver {
/**
* The app became visible again. A state the policy calls reconnecting is
* reconnected at once — the pending backoff delay is cancelled by the
* reconnect effect, so the operator never waits it out. A socket the state
* still calls Connected is first confirmed to answer, so a silent
* "Connected" is never trusted; the state is re-read afterwards, because the
* socket's own failure callback may have run while the check was in flight.
*/
override fun onStart(owner: LifecycleOwner) {
val before = state()
if (before !is ConnectionState.Connected) {
if (foregroundAction(before, confirmedAlive = false) == ForegroundAction.Reconnect) reconnect()
return
}
scope.launch {
val alive = confirm()
if (foregroundAction(state(), alive) == ForegroundAction.Reconnect) reconnect()
}
}
/**
* Confirms a supposedly-connected socket still answers, bounded so a dead one
* cannot hold recovery: the check runs off the main thread on the app scope
* and a probe that fails, throws or outlives its budget counts as not alive.
*/
private suspend fun confirm(): Boolean =
withTimeoutOrNull(confirmTimeoutMillis) {
try {
confirmAlive()
} catch (t: Throwable) {
if (t is CancellationException) throw t
false
}
} ?: false
companion object {
/**
* Bounds the liveness check. A healthy round trip on the trusted LAN/VPN
* is far shorter, so a socket that cannot answer is noticed promptly
* instead of holding the "Connected" the operator is looking at.
*/
const val CONFIRM_TIMEOUT_MILLIS = 3_000L
}
}
@@ -1,419 +0,0 @@
package net.awan.pipelines.data
import android.os.Build
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.JsonElement
import net.awan.pipelines.data.protocol.ChatCreateRequest
import net.awan.pipelines.data.protocol.ChatHistoryPage
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPromptRequest
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatQuery
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatShellOutputPage
import net.awan.pipelines.data.protocol.ChatShell
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.Graph
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.SearchRequest
import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.data.protocol.Template
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
/**
* The default label this device reports: its model name, so other clients can
* attribute a message to "Pixel 9 Pro XL". A build without a usable model (or a
* local unit test where the framework stub has none) falls back to a generic
* label rather than sending a blank one.
*/
private fun defaultClientLabel(): String {
val model = runCatching { Build.MODEL }.getOrNull()?.trim().orEmpty()
return model.ifBlank { "Android device" }
}
/** 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,
/**
* The label this device sends with its prompts and approval answers, so every
* other client can attribute a user message to the device that sent it and see
* which device answered an approval. Defaults to the device model; injectable
* so a unit test does not depend on the build.
*/
val clientLabel: String = defaultClientLabel(),
) {
val connectionState = client.state
/** Server-pushed chat frames (chat_event / chat_permission), with no request id. */
val events: SharedFlow<Message> = client.events
/** Opens the single shared connection to a validated server URL. */
fun connect(validated: ServerUrl.Validated) = client.connect(validated)
/** Recovers a lost connection without reversing an explicit Disconnect. */
fun recover(validated: ServerUrl.Validated) = client.recover(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)
}
/**
* The server's template catalog: each template's name/description and its
* full, defaulted source, exactly as `pipelines templates` prints it.
*/
suspend fun listTemplates(): List<Template> =
client.call(Message(type = Protocol.LIST_TEMPLATES)).templates ?: emptyList()
/**
* Parses a definition source on the server (the `validate` command) and
* returns the resulting graph. Listing templates carries only the source, not
* its graph, so this is how the app learns a template's stages. A source the
* server cannot parse surfaces as a [ProtocolException], which the caller
* treats as "unparseable" and still shows the raw source.
*/
suspend fun validateSource(source: String): Graph =
client.call(Message(type = Protocol.VALIDATE, source = source)).graph
?: throw ProtocolException("The server returned no graph for the source.")
/**
* Creates a new pipeline from a definition [source] (the `submit` command).
* create-only, matching `pipelines new`: the name must not already exist, so
* this can only ever add a draft and never overwrite a retained pipeline. No
* run is started.
*/
suspend fun createPipeline(name: String, source: String): PipelineDetail {
if (name.isBlank()) throw ProtocolException("Enter a pipeline name.")
val response = client.call(
Message(
type = Protocol.SUBMIT,
name = name.trim(),
source = source,
createOnly = true,
),
)
// A successful submit can add a pipeline summary; the per-id detail cache
// is not affected, but keep it from serving a stale list-derived view.
clearCache()
return response.detail ?: throw ProtocolException("The server returned no pipeline detail.")
}
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()
/**
* Subscribes this connection to run-state pushes. The server first sends the
* current state of every matching run as `run_event` frames (which arrive on
* [events]), then a compact delta on each transition, so a reconnecting client
* re-syncs before it applies deltas. [workspace] scopes the watch; the default
* blank scope watches every workspace, which is what the runs list displays
* (the work an operator watches can run in any workspace). [runIds] narrows
* the watch further; an empty list watches the whole scope.
*
* Returns the request id and does not wait for the ack: a server that never
* acks must not block the send lock, and the pushes themselves confirm the
* watch (see `AppViewModel.observeRunEvents`). Any ack or error reply lands on
* [events] with this id.
*/
suspend fun subscribeRuns(workspace: String = "", runIds: List<Long> = emptyList()): String =
client.sendOnly(
Message(
type = Protocol.SUBSCRIBE,
workspace = workspace,
runIds = runIds.ifEmpty { null },
),
)
/** Stops this connection's run-state pushes (best effort; a disconnect also drops them). */
suspend fun unsubscribeRuns() {
client.sendOnly(Message(type = Protocol.UNSUBSCRIBE))
}
/**
* Sends one omni-search query over the shared transport and returns the raw
* reply envelope. [kind] narrows the server-side scan to one SearchKind (see
* SearchKindFilter); a blank kind searches every kind. The reply is classified
* by its envelope type: [Protocol.SEARCH_RESULTS] is the accepted search, and
* any other type is an unexpected reply the caller reports rather than parsing.
*/
suspend fun search(query: String, kind: String = ""): Message =
client.call(Message(type = Protocol.SEARCH, search = SearchRequest(query = query.trim(), kind = kind)))
/** Fetches an artifact's bytes (image preview) over the shared HTTP client. */
suspend fun fetchArtifactBytes(url: String): ByteArray = client.fetchBytes(url)
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.")
/**
* Answers a run's waiting human stage with the chosen [option] and optional
* [feedback] (the `decide` command behind `pipelines decide`). The server
* validates the option against the waiting stage and resumes the run along
* that edge; the reply is the resumed run's detail. A refused decision (the
* run moved on, the stage changed, or another client answered first) comes
* back as a [ProtocolException] carrying the server's own reason.
*/
suspend fun decideRun(
runId: Long,
stage: String,
option: String,
feedback: String = "",
): RunDetail {
if (runId <= 0) throw ProtocolException("Select a run to decide.")
if (option.isBlank()) throw ProtocolException("Choose one of the stage's options.")
val response = client.call(
Message(
type = Protocol.DECIDE_RUN,
runId = runId,
stage = stage.takeIf { it.isNotBlank() },
option = option,
feedback = feedback.takeIf { it.isNotBlank() },
),
)
return response.runDetail ?: throw ProtocolException("The server returned no run detail.")
}
// ---- Brokered OpenCode chat (route B): the phone never speaks OpenCode
// directly and never holds its credentials. ----
/**
* Lists the sessions this server owns. The server already returns operator
* sessions only, so the app never filters this list by ownership; a session is
* never marked read-only.
*/
suspend fun chatSessions(): List<ChatSession> =
client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList()
/**
* The directories a new chat can be started in: the operator's home first,
* then the directories of previous operator sessions, most recently used
* first. The server is the only source of these choices — the app never
* invents one.
*/
suspend fun chatDirectories(): List<String> =
client.call(Message(type = Protocol.CHAT_DIRECTORIES)).chatDirectories ?: emptyList()
/**
* Creates a session in an explicit [directory] and returns it. The directory
* is always sent (the server resolves `~` to the operator's home), so a chat
* is never created in whatever directory the server happens to be running in.
* The server reports its own error when it does not broker creation; the
* caller surfaces that message rather than guessing at a session id.
*/
suspend fun chatCreate(
title: String,
directory: String,
operationId: String = newChatCreateOperationId(),
): ChatSession {
val response = client.call(
Message(
type = Protocol.CHAT_CREATE,
chatCreate = ChatCreateRequest(title = title, directory = directory, operationId = operationId),
),
)
return response.chatSession
?: throw ProtocolException("The server did not return the new chat session.")
}
/** Loads a bounded chronological page; [cursor] is an opaque older-history continuation. */
suspend fun chatMessages(sessionId: String, limit: Int = 0, cursor: String = ""): ChatHistoryPage {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val response = client.call(
Message(type = Protocol.CHAT_MESSAGES, chatQuery = ChatQuery(sessionId = sessionId, limit = limit, cursor = cursor)),
)
// Old servers only have chat_messages and therefore honestly expose no continuation.
return response.chatHistory ?: ChatHistoryPage(messages = response.chatMessages ?: emptyList())
}
/** Reads one bounded page from a verified, currently observable shell. */
suspend fun chatShellOutput(sessionId: String, shellId: String, cursor: Long = 0, limit: Int = ChatProtocol.SHELL_OUTPUT_LIMIT): ChatShellOutputPage {
if (sessionId.isBlank() || shellId.isBlank()) throw ProtocolException("Select a shell first.")
if (cursor < 0 || limit <= 0 || limit > ChatProtocol.SHELL_OUTPUT_LIMIT) {
throw ProtocolException("Shell output bounds are invalid.")
}
return client.call(ChatProtocol.shellOutputRequest(sessionId, shellId, cursor, limit)).chatShellOutput
?: throw ProtocolException("The server returned no shell output page.")
}
/** Lists currently observed shells owned by this operator chat session. */
suspend fun chatShells(sessionId: String): List<ChatShell> {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
return client.call(ChatProtocol.shellsRequest(sessionId)).chatShells ?: emptyList()
}
/**
* Attaches this connection to [sessionId]'s shared live stream, so it sees
* every frame any client's turn produces — the other devices' prompts and the
* turn's streaming output — and can answer a shared approval. Best-effort: an
* older server that does not know `chat_subscribe` simply answers an error
* frame, which the caller ignores while history still loads.
*/
suspend fun chatSubscribe(sessionId: String) {
if (sessionId.isBlank()) return
client.call(ChatProtocol.subscribeRequest(sessionId))
}
/**
* Sends one prompt with its attached file URIs; the server echoes an ack and
* then pushes chat_event frames. The prompt carries this device's label so the
* other clients can attribute it. The attachments travel only here, with the
* prompt the operator actually sent — never on their own. Returns true when the
* server queued the prompt behind an in-flight turn.
*/
suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList(), operationId: String = newRequestKey()): Boolean {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val trimmed = text.trim()
if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.")
return client.call(ChatProtocol.promptRequest(sessionId, trimmed, files, clientLabel, operationId, nativeMessageId(operationId))).chatQueued
}
suspend fun chatInterrupt(sessionId: String) {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
client.call(ChatProtocol.interruptRequest(sessionId))
}
/**
* Finishes a chat on the server: any running turn is stopped and the session
* is recorded closed, so every client sees it. Nothing is deleted. The
* server returns the closed session, which the caller folds into its list.
*/
suspend fun chatClose(sessionId: String): ChatSession {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val response = client.call(ChatProtocol.closeRequest(sessionId))
return response.chatSession
?: throw ProtocolException("The server did not return the closed chat session.")
}
/** Clears a closed chat's state so it returns to the active list. */
suspend fun chatReopen(sessionId: String): ChatSession {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val response = client.call(ChatProtocol.reopenRequest(sessionId))
return response.chatSession
?: throw ProtocolException("The server did not return the reopened chat session.")
}
suspend fun chatReply(sessionId: String, requestId: String, decision: String, message: String = "") {
if (sessionId.isBlank() || requestId.isBlank()) {
throw ProtocolException("A pending permission request is required.")
}
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message, clientLabel))
}
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()
/** A durable key for one chat-create intent; retain it when retrying. */
fun newChatCreateOperationId(): String = "android-chat-" + UUID.randomUUID().toString()
/** OpenCode's optional caller id is the canonical bridge to history. */
fun nativeMessageId(operationId: String): String =
operationId.filter { character -> character.isLetterOrDigit() }.take(120)
.takeIf { it.isNotEmpty() }
?.let { "msg_" + it }
.orEmpty()
}
}
@@ -1,196 +0,0 @@
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, the list
* sort/filter choices and the operator's local chat-session changes 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()
// The chosen list orderings, stored as their stable storage keys. The value
// is resolved (with a default fallback for a stale/unknown key) by the list
// screens, so this repository stays unaware of the UI's sort enums.
private val _pipelineSort = MutableStateFlow(prefs.getString(KEY_PIPELINE_SORT, "").orEmpty())
val pipelineSort: StateFlow<String> = _pipelineSort.asStateFlow()
private val _runSort = MutableStateFlow(prefs.getString(KEY_RUN_SORT, "").orEmpty())
val runSort: StateFlow<String> = _runSort.asStateFlow()
// The chosen list filters, stored as their stable storage keys/encodings and
// resolved (with a default fallback for a stale/unknown value) by the list
// screens, so this repository stays unaware of the UI's filter enums.
private val _runFilterStatuses = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_STATUSES, "").orEmpty())
val runFilterStatuses: StateFlow<String> = _runFilterStatuses.asStateFlow()
private val _runFilterPipeline = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_PIPELINE, "").orEmpty())
val runFilterPipeline: StateFlow<String> = _runFilterPipeline.asStateFlow()
private val _runFilterTimeRange = MutableStateFlow(prefs.getString(KEY_RUN_FILTER_TIME_RANGE, "").orEmpty())
val runFilterTimeRange: StateFlow<String> = _runFilterTimeRange.asStateFlow()
private val _pipelineFilterPresence = MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_PRESENCE, "").orEmpty())
val pipelineFilterPresence: StateFlow<String> = _pipelineFilterPresence.asStateFlow()
private val _pipelineFilterRunStatuses =
MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_RUN_STATUSES, "").orEmpty())
val pipelineFilterRunStatuses: StateFlow<String> = _pipelineFilterRunStatuses.asStateFlow()
private val _pipelineFilterName = MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_NAME, "").orEmpty())
val pipelineFilterName: StateFlow<String> = _pipelineFilterName.asStateFlow()
// The operator's local chat-session changes (renames and removals), stored as
// one opaque JSON string: the chat layer owns the shape, so this repository
// stays unaware of the chat model, exactly like the sort/filter keys above.
private val _chatOverrides = MutableStateFlow(prefs.getString(KEY_CHAT_OVERRIDES, "").orEmpty())
val chatOverrides: StateFlow<String> = _chatOverrides.asStateFlow()
// What the operator has read of the chat session list, stored as one opaque
// JSON string the same way the overrides above are: the chat layer owns the
// shape, so this repository stays unaware of the chat model.
private val _chatSeen = MutableStateFlow(prefs.getString(KEY_CHAT_SEEN, "").orEmpty())
val chatSeen: StateFlow<String> = _chatSeen.asStateFlow()
// What the operator has dealt with on the attention surface (dismissals and
// finished runs already looked at), stored as one opaque JSON string the same
// way the chat state above is: the attention layer owns the shape.
private val _attention = MutableStateFlow(prefs.getString(KEY_ATTENTION, "").orEmpty())
val attention: StateFlow<String> = _attention.asStateFlow()
// Whether the operator has already been asked for POST_NOTIFICATIONS. Asked
// once and remembered, so the rationale and the system dialog never nag: the
// app degrades to its in-app attention surface instead.
private val _notificationPermissionAsked =
MutableStateFlow(prefs.getBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, false))
val notificationPermissionAsked: StateFlow<Boolean> = _notificationPermissionAsked.asStateFlow()
// The omni-search kind narrowing (a server kind, "" = every kind) and the
// search order, stored as their stable values and resolved by the UI.
private val _searchFilterKind = MutableStateFlow(prefs.getString(KEY_SEARCH_FILTER_KIND, "").orEmpty())
val searchFilterKind: StateFlow<String> = _searchFilterKind.asStateFlow()
private val _searchSort = MutableStateFlow(prefs.getString(KEY_SEARCH_SORT, "").orEmpty())
val searchSort: StateFlow<String> = _searchSort.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()
}
fun setPipelineSort(value: String) {
_pipelineSort.value = value
prefs.edit().putString(KEY_PIPELINE_SORT, value).apply()
}
fun setRunSort(value: String) {
_runSort.value = value
prefs.edit().putString(KEY_RUN_SORT, value).apply()
}
fun setRunFilterStatuses(value: String) {
_runFilterStatuses.value = value
prefs.edit().putString(KEY_RUN_FILTER_STATUSES, value).apply()
}
fun setRunFilterPipeline(value: String) {
_runFilterPipeline.value = value
prefs.edit().putString(KEY_RUN_FILTER_PIPELINE, value).apply()
}
fun setRunFilterTimeRange(value: String) {
_runFilterTimeRange.value = value
prefs.edit().putString(KEY_RUN_FILTER_TIME_RANGE, value).apply()
}
fun setPipelineFilterPresence(value: String) {
_pipelineFilterPresence.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_PRESENCE, value).apply()
}
fun setPipelineFilterRunStatuses(value: String) {
_pipelineFilterRunStatuses.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_RUN_STATUSES, value).apply()
}
fun setPipelineFilterName(value: String) {
_pipelineFilterName.value = value
prefs.edit().putString(KEY_PIPELINE_FILTER_NAME, value).apply()
}
fun setChatOverrides(value: String) {
if (value == _chatOverrides.value) return
_chatOverrides.value = value
prefs.edit().putString(KEY_CHAT_OVERRIDES, value).apply()
}
fun setChatSeen(value: String) {
if (value == _chatSeen.value) return
_chatSeen.value = value
prefs.edit().putString(KEY_CHAT_SEEN, value).apply()
}
fun setAttention(value: String) {
if (value == _attention.value) return
_attention.value = value
prefs.edit().putString(KEY_ATTENTION, value).apply()
}
/** Records that the runtime notification permission has been asked for (or declined). */
fun setNotificationPermissionAsked(asked: Boolean) {
if (asked == _notificationPermissionAsked.value) return
_notificationPermissionAsked.value = asked
prefs.edit().putBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, asked).apply()
}
fun setSearchFilterKind(value: String) {
_searchFilterKind.value = value
prefs.edit().putString(KEY_SEARCH_FILTER_KIND, value).apply()
}
fun setSearchSort(value: String) {
_searchSort.value = value
prefs.edit().putString(KEY_SEARCH_SORT, value).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"
const val KEY_PIPELINE_SORT = "pipeline_sort"
const val KEY_RUN_SORT = "run_sort"
const val KEY_RUN_FILTER_STATUSES = "run_filter_statuses"
const val KEY_RUN_FILTER_PIPELINE = "run_filter_pipeline"
const val KEY_RUN_FILTER_TIME_RANGE = "run_filter_time_range"
const val KEY_PIPELINE_FILTER_PRESENCE = "pipeline_filter_presence"
const val KEY_PIPELINE_FILTER_RUN_STATUSES = "pipeline_filter_run_statuses"
const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name"
const val KEY_CHAT_OVERRIDES = "chat_overrides"
const val KEY_CHAT_SEEN = "chat_seen"
const val KEY_ATTENTION = "attention"
const val KEY_NOTIFICATION_PERMISSION_ASKED = "notification_permission_asked"
const val KEY_SEARCH_FILTER_KIND = "search_filter_kind"
const val KEY_SEARCH_SORT = "search_sort"
}
}
@@ -1,434 +0,0 @@
package net.awan.pipelines.data.protocol
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
/**
* Brokered OpenCode chat wire types (route B in the research report): the phone
* talks only to `/connect` and the server holds the OpenCode credentials,
* translating each type below. The field names and JSON tags mirror
* `internal/protocol/chat.go` exactly so the two cannot drift.
*
* Every list/field is optional with a default, so an older peer or a partial
* envelope never crashes the client.
*/
@Serializable
data class ChatSession(
val id: String = "",
val title: String = "",
val agent: String = "",
val model: String = "",
val directory: String = "",
@SerialName("parent_id") val parentId: String = "",
// The stored session kind. The only value the server records is "operator"
// (a chat the person created); a pipeline stage session is never tagged and
// is never listed by chat_sessions. Additive/optional, so an older server
// simply omits it and the client shows no kind chip.
val tag: String = "",
@SerialName("created_at") val createdAt: Long = 0,
@SerialName("updated_at") val updatedAt: Long = 0,
// Another client holds the session, or the server itself owns it as an active
// run. Kept for wire compatibility; the server no longer sets it, and a
// session is never read-only for a client.
val busy: Boolean = false,
// The operator finished with this session: the server recorded it as closed,
// so every client sees the same state. The session, its transcript and its
// history are kept and the closed chat stays in the list (grouped as history),
// where it can be reopened. [closedAt] is the epoch-millisecond close time, 0
// while open. Additive/optional, so an older server simply never sets them.
val closed: Boolean = false,
@SerialName("closed_at") val closedAt: Long = 0,
)
/**
* The outcome of a `chat_close`, mirroring `internal/protocol/chat.go`
* ChatCloseResult: the closed session's id, the epoch-millisecond close time and
* whether an in-flight turn was interrupted to stop it. It is the record that a
* running turn was stopped.
*/
@Serializable
data class ChatCloseResult(
@SerialName("session_id") val sessionId: String = "",
@SerialName("closed_at") val closedAt: Long = 0,
val interrupted: Boolean = false,
)
@Serializable
data class ChatCreateRequest(
val title: String = "",
val directory: String = "",
@SerialName("operation_id") val operationId: String = "",
)
/** The session-scoped request body for chat_messages and chat_interrupt. */
@Serializable
data class ChatQuery(
@SerialName("session_id") val sessionId: String = "",
val limit: Int = 0,
val cursor: String = "",
)
@Serializable
data class ChatPromptRequest(
@SerialName("session_id") val sessionId: String = "",
val text: String = "",
val model: String = "",
val agent: String = "",
val files: List<String> = emptyList(),
// The sending device's human-readable label (a device name), so every other
// client can attribute the message; the server sanitises it and falls back to
// a generic label when it is blank.
val client: String = "",
@SerialName("operation_id") val operationId: String = "",
@SerialName("native_message_id") val nativeMessageId: String = "",
)
/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */
@Serializable
data class ChatMessage(
val id: String = "",
@SerialName("session_id") val sessionId: String = "",
val role: String = "",
val model: String = "",
val agent: String = "",
@SerialName("created_at") val createdAt: Long = 0,
// The sending device's label on a user turn the server echoed, so a resumed
// transcript still says who sent the message. Empty on an assistant turn.
val client: String = "",
@SerialName("operation_id") val operationId: String = "",
val parts: List<ChatPart> = emptyList(),
)
/**
* One element of a [ChatMessage]; [type] selects which fields are meaningful.
*
* A [ChatProtocol.PART_FILE] part is the operator's attachment: [uri] is the
* local `content://` reference the picker returned and [mime] decides whether it
* is drawn as an image or a plain file. That part exists only in the optimistic
* user turn the app appends when it sends; the brokered server stores user turns
* as text, so a history round-trip must not be expected to carry it back.
*/
@Serializable
data class ChatPart(
val type: String = "",
val id: String = "",
val text: String = "",
val name: String = "",
val executed: Boolean = false,
val state: ChatToolState? = null,
val time: ChatTime? = null,
val uri: String = "",
val mime: String = "",
)
/** The lifecycle of a tool call; [input] is a partial-JSON string while streaming, an object afterwards. */
@Serializable
data class ChatToolState(
val status: String = "",
val input: JsonElement? = null,
val content: List<ChatToolContent> = emptyList(),
val metadata: JsonObject? = null,
val error: ChatError? = null,
// A bounded history preview is not the complete tool result.
val truncated: Boolean = false,
)
@Serializable
data class ChatHistoryPage(
val messages: List<ChatMessage> = emptyList(),
@SerialName("next_cursor") val nextCursor: String = "",
@SerialName("has_more") val hasMore: Boolean = false,
)
@Serializable
data class ChatToolContent(
val type: String = "",
val text: String = "",
val uri: String = "",
val mime: String = "",
val name: String = "",
)
@Serializable
data class ChatError(
val type: String = "",
val message: String = "",
)
/** Epoch-millisecond timing envelope of a tool call. */
@Serializable
data class ChatTime(
val created: Long = 0,
val ran: Long = 0,
val completed: Long = 0,
)
/**
* A server-pushed chat_event frame. [kind] selects the payload: text/reasoning
* carry an incremental [delta] for the target [part], tool carries a full [part],
* step marks turn progress and usage reports the turn totals.
*/
@Serializable
data class ChatEventFrame(
@SerialName("session_id") val sessionId: String = "",
@SerialName("message_id") val messageId: String = "",
val kind: String = "",
val delta: String = "",
val part: ChatPart? = null,
val step: ChatStep? = null,
val usage: ChatUsage? = null,
// The payload of a `shell` frame: the lifecycle of one shell the agent
// started. Nil on every other kind. A shell carries no message id, because a
// background process outlives the tool call (and the turn) that started it.
val shell: ChatShell? = null,
// The sending device's label on a `user` frame (another client's prompt), so
// the transcript can say who sent it. Empty on the agent's own frames.
val client: String = "",
@SerialName("operation_id") val operationId: String = "",
)
/**
* The state of one shell command the agent started, mirroring
* `internal/protocol/chat.go`'s ChatShell. [id] is stable across the created and
* exited frames so a running process is keyed by it; [status] is one of
* [ChatProtocol.SHELL_RUNNING]/[ChatProtocol.SHELL_EXITED]; [command] is the
* command line the shell was given (present on the created frame); [exit] is the
* process exit code and is non-null only once the shell has exited.
*/
@Serializable
data class ChatShell(
val id: String = "",
val status: String = "",
val command: String = "",
val exit: Int? = null,
)
@Serializable
@OptIn(ExperimentalSerializationApi::class)
data class ChatShellOutputQuery(
@SerialName("session_id") val sessionId: String = "",
@SerialName("shell_id") val shellId: String = "",
@EncodeDefault(EncodeDefault.Mode.ALWAYS)
val cursor: Long = 0,
@EncodeDefault(EncodeDefault.Mode.ALWAYS)
val limit: Int = ChatProtocol.SHELL_OUTPUT_LIMIT,
)
@Serializable
data class ChatShellOutputPage(
val shell: ChatShell = ChatShell(),
val output: String = "",
val cursor: Long = 0,
val size: Long = 0,
val truncated: Boolean = false,
val unavailable: Boolean = false,
)
@Serializable
data class ChatStep(
val status: String = "",
val index: Int = 0,
)
@Serializable
data class ChatUsage(
@SerialName("input_tokens") val inputTokens: Int = 0,
@SerialName("output_tokens") val outputTokens: Int = 0,
val cost: Double = 0.0,
)
/**
* One pending OpenCode approval request the phone answers with chat_reply.
*
* [resolved] and [decision] carry the server's outcome when it reports a request
* that is no longer open (another client answered it, or it expired): the phone
* then shows the verdict instead of live controls. They are additive and
* optional, so an older peer simply never sets them and every request stays
* pending.
*/
@Serializable
data class ChatPermissionFrame(
@SerialName("session_id") val sessionId: String = "",
@SerialName("request_id") val requestId: String = "",
val action: String = "",
val resources: List<String> = emptyList(),
val save: List<String> = emptyList(),
val metadata: JsonObject? = null,
val source: ChatPermissionSource? = null,
val message: String = "",
val resolved: Boolean = false,
val decision: String = "",
// The label of the client whose answer resolved the request, so every other
// client can show which device answered.
@SerialName("resolved_by") val resolvedBy: String = "",
)
@Serializable
data class ChatPermissionSource(
val type: String = "",
@SerialName("message_id") val messageId: String = "",
val id: String = "",
)
@Serializable
data class ChatReplyRequest(
@SerialName("session_id") val sessionId: String = "",
@SerialName("request_id") val requestId: String = "",
val decision: String = "",
val message: String = "",
// The answering device's label, recorded with the resolution.
val client: String = "",
)
/** Chat part/kind/state/reply constants, mirroring `internal/protocol/chat.go`. */
object ChatProtocol {
const val PART_TEXT = "text"
const val PART_REASONING = "reasoning"
const val PART_TOOL = "tool"
/**
* A file the operator attached to a prompt. The value is the app's own local
* part kind for an optimistic user turn; the [ChatMessage.parts] the server
* returns never use it (the brokered server stores user turns as text).
*/
const val PART_FILE = "file"
const val EVENT_STEP = "step"
const val EVENT_USAGE = "usage"
/**
* The lifecycle of one shell the agent started. It carries a [ChatShell],
* no message id and no [ChatPart]: a background process can outlive the turn
* that started it, so it is a frame of its own and never a tool part.
*/
const val EVENT_SHELL = "shell"
const val SHELL_RUNNING = "running"
const val SHELL_EXITED = "exited"
const val SHELL_OUTPUT_LIMIT = 64 * 1024
/**
* A prompt another client sent, echoed live to this client so it appears in
* the transcript attributed to the sending device. The sender never receives
* its own frame (it already has the message locally).
*/
const val EVENT_USER = "user"
const val STEP_STARTED = "started"
const val STEP_ENDED = "ended"
const val TOOL_STREAMING = "streaming"
const val TOOL_RUNNING = "running"
const val TOOL_COMPLETED = "completed"
const val TOOL_ERROR = "error"
const val ROLE_USER = "user"
const val ROLE_ASSISTANT = "assistant"
const val DECISION_ONCE = "once"
const val DECISION_ALWAYS = "always"
const val DECISION_REJECT = "reject"
/**
* The only stored [ChatSession.tag] value, mirroring `internal/protocol/
* chat.go`: a session the operator created. The display label (`Operator`) is
* derived from it by the UI rather than carried as a second field.
*/
const val TAG_OPERATOR = "operator"
/** A tool call still in flight (no result or error yet). */
fun toolRunning(state: ChatToolState?): Boolean = when (state?.status) {
TOOL_STREAMING, TOOL_RUNNING -> true
else -> false
}
/**
* The stable part id an incremental text/reasoning delta stream addresses,
* mirroring `ChatDeltaPartID` in `internal/protocol/chat.go`. OpenCode numbers
* one message's text and reasoning parts independently from 0, so the kind is
* part of the id: a message's first text delta and its first reasoning delta
* are distinct parts, and answer text can never be appended into the thinking
* block.
*/
fun deltaPartId(messageId: String, kind: String, ordinal: Int): String = "$messageId#$kind#$ordinal"
/**
* The `chat_prompt` frame the composer sends. [files] are the attached files'
* URIs, in the order they were attached, and are omitted when empty (the
* shape a text-only prompt has always sent). Built here (not inline in the
* repository) so production and its unit test share the one wire shape.
*/
fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList(), client: String = "", operationId: String = "", nativeMessageId: String = ""): Message =
Message(
type = Protocol.CHAT_PROMPT,
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files, client = client, operationId = operationId, nativeMessageId = nativeMessageId),
)
/**
* The `chat_subscribe` frame that attaches this connection to [sessionId]'s
* shared live stream, so the client sees every frame any client's turn
* produces. Built here so production and its unit test share the one shape.
*/
fun subscribeRequest(sessionId: String): Message =
Message(
type = Protocol.CHAT_SUBSCRIBE,
chatSubscribe = ChatQuery(sessionId = sessionId),
)
/**
* The `chat_interrupt` frame the composer's stop control sends: the server
* aborts the in-flight turn for [sessionId]. Built here (not inline in the
* repository) so production and its unit test share the one wire shape.
*/
fun interruptRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
fun shellOutputRequest(sessionId: String, shellId: String, cursor: Long = 0, limit: Int = SHELL_OUTPUT_LIMIT): Message =
Message(
type = Protocol.CHAT_SHELL_OUTPUT,
chatShellOutputQuery = ChatShellOutputQuery(sessionId, shellId, cursor, limit),
)
fun shellsRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_SHELLS, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_close` frame that finishes [sessionId]: the server stops any
* running turn (through the same interrupt) and records the session closed on
* the server, sharing the state with every client. Nothing is deleted. Built
* here (not inline in the repository) so production and its unit test share
* the one wire shape.
*/
fun closeRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_CLOSE, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_reopen` frame that clears a closed session's state so it returns
* to the active list; the inverse of [closeRequest]. Built here so production
* and its unit test share the one wire shape.
*/
fun reopenRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_REOPEN, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_reply` frame that answers one permission request: [decision] is
* one of [DECISION_ONCE]/[DECISION_ALWAYS]/[DECISION_REJECT]. Built here (not
* inline in the repository) so the approval card's actions and their unit
* test share the one wire shape.
*/
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = "", client: String = ""): Message =
Message(
type = Protocol.CHAT_REPLY,
chatReply = ChatReplyRequest(
sessionId = sessionId,
requestId = requestId,
decision = decision,
message = message,
client = client,
),
)
}
@@ -1,118 +0,0 @@
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?,
/**
* True while the server still reports the run as executing. The graph only
* animates a live run; a finished one is drawn settled and static.
*/
val executing: Boolean = false,
/**
* RFC3339 start of the visit currently running for [currentStage], or null
* when the run is not live or that visit's start is unknown. The graph uses
* it for the live ticking elapsed time on the active node.
*/
val currentStageStartedAt: String? = null,
) {
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 ?: ""
}
val stage = current.ifEmpty { null }
// Only a live run carries a ticking active stage; the matching running
// step's start keeps the timer on the same node as the halo.
val runningSince = if (run.executing && stage != null) {
run.steps.lastOrNull { it.stage == stage && it.status == "running" }
?.startedAt
?.takeIf { it.isNotBlank() }
} else {
null
}
return RunGraphState(stages, routes, stage, run.executing, runningSince)
}
}
}
@@ -1,68 +0,0 @@
package net.awan.pipelines.data.protocol
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
/**
* A `type=human` stage pauses its run until a person chooses one of its
* non-error edges. The step's status, the run's status and the recorded
* evidence keys below mirror `internal/protocol/runs.go` exactly, so the phone
* reads the same one definition the store, runner, CLI and TUI write.
*
* The names are the wire contract: [WAITING_PROMPT_KEY]/[WAITING_OPTIONS_KEY]
* are the keys the server records in the waiting step's output
* (`protocol.NewWaitingEvidence`), and the phone is their read side
* (`protocol.WaitingPrompt`/`WaitingOptions`).
*/
/** Run status while parked on a person; no later stage runs until it is decided. */
const val RUN_STATUS_WAITING = "waiting"
/** The waiting step's status, i.e. the step a decision answers. */
const val STEP_STATUS_WAITING = "waiting"
/** Waiting evidence key holding the author's operator instructions. */
const val WAITING_PROMPT_KEY = "prompt"
/** Waiting evidence key holding the author's ordered selectable options. */
const val WAITING_OPTIONS_KEY = "options"
/**
* The recorded operator instructions from a waiting step's output, or "" when
* none were recorded. Mirrors `protocol.WaitingPrompt`.
*/
fun waitingPrompt(output: Map<String, JsonElement>?): String =
(output?.get(WAITING_PROMPT_KEY) as? JsonPrimitive)?.contentOrNull.orEmpty()
/**
* The recorded selectable options from a waiting step's output, in recorded
* order. Mirrors `protocol.WaitingOptions`: strings only, a malformed entry
* dropped rather than crashing, and an absent key yields an empty list. The
* options are exactly the author's non-error edge keys, recorded at wait time so
* the choice is answerable without re-reading the pinned graph.
*/
fun waitingOptions(output: Map<String, JsonElement>?): List<String> {
val array = output?.get(WAITING_OPTIONS_KEY) as? JsonArray ?: return emptyList()
return array.mapNotNull { element ->
// Only string options, exactly like protocol.WaitingOptions' `option.(string)`.
(element as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull
}.filter { it.isNotBlank() }
}
/**
* A stage's selectable outcomes: its non-error edges in sorted order. Mirrors
* `stage.HumanOptions`, the fallback when a waiting step recorded no options
* (a step from an older server).
*/
fun humanOptions(edges: Map<String, String>): List<String> =
edges.keys.filter { it != "error" }.sorted()
/**
* The most recent step a run is waiting on (the last waiting step by sequence),
* or null when no step is waiting. Mirrors `tui.lastWaitingStep`, so the phone
* and the run inspector answer the same step.
*/
fun lastWaitingStep(steps: List<RunStep>): RunStep? =
steps.lastOrNull { it.status == STEP_STATUS_WAITING }
@@ -1,16 +0,0 @@
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
}
@@ -1,720 +0,0 @@
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"
// Answers a waiting human stage: the stage (optional; the server infers it
// from the run's current stage), the chosen option and optional feedback.
const val DECIDE_RUN = "decide_run"
const val GET_RUN_EVIDENCE = "get_run_evidence"
const val RUN_EVIDENCE = "run_evidence"
// runevents.go: the workspace-scoped run-state push subscription.
const val SUBSCRIBE = "subscribe"
const val UNSUBSCRIBE = "unsubscribe"
const val RUN_EVENT = "run_event"
// status.go
const val GET_STATUS = "get_status"
const val STATUS = "status"
// search.go
const val SEARCH = "search"
const val SEARCH_RESULTS = "search_results"
// search.go result kinds (mirrors protocol.SearchKind*); an empty kind
// searches every kind and an unknown kind is shown read-only.
const val SEARCH_KIND_PIPELINE = "pipeline"
const val SEARCH_KIND_VERSION = "version"
const val SEARCH_KIND_RUN = "run"
const val SEARCH_KIND_STEP = "step"
const val SEARCH_KIND_FIELD = "field"
const val SEARCH_KIND_ARTIFACT = "artifact"
// chat.go (brokered OpenCode chat)
const val CHAT_SESSIONS = "chat_sessions"
const val CHAT_CREATE = "chat_create"
const val CHAT_PROMPT = "chat_prompt"
const val CHAT_MESSAGES = "chat_messages"
const val CHAT_INTERRUPT = "chat_interrupt"
const val CHAT_REPLY = "chat_reply"
// Close/reopen an operator session on the server (its closed state is
// recorded so every client sees it). Both ride on chat_query like
// chat_interrupt; chat_close also carries a ChatCloseResult on the response.
const val CHAT_CLOSE = "chat_close"
const val CHAT_REOPEN = "chat_reopen"
// Attaches this connection to one session's shared live stream, so every
// client watching a session receives every frame any client's turn produces.
const val CHAT_SUBSCRIBE = "chat_subscribe"
// The operator's directory choices for a new chat (home first, then the
// directories of previous operator sessions, most recently used first).
const val CHAT_DIRECTORIES = "chat_directories"
const val CHAT_SHELLS = "chat_shells"
const val CHAT_SHELL_OUTPUT = "chat_shell_output"
// Server-pushed frames with no matching request.
const val CHAT_EVENT = "chat_event"
const val CHAT_PERMISSION = "chat_permission"
// 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,
)
/**
* One file a stage left in its artifacts directory. Mirrors
* internal/protocol/runs.go StageArtifact exactly: observed server-side
* evidence, not a model's claim. An absent artifact list means nothing was
* recorded for the visit (including historical steps).
*/
@Serializable
data class StageArtifact(
val name: String = "",
@SerialName("size_bytes") val sizeBytes: Long = 0,
@SerialName("content_type") val contentType: String = "",
val url: String = "",
)
/**
* The plain-language outcome of one completed stage visit, derived server-side
* and mirrored from `internal/protocol/verdict.go` StageVerdict: the chosen
* option (the outcome and the target it routed to), a bounded one-line reason
* with its provenance ([reasonSource]), and the names of the recorded artifacts
* the reason refers to. A null on a step means the server reported no verdict
* (for example a running visit), so the pane shows no block at all.
*/
@Serializable
data class StageVerdict(
val option: String = "",
val reason: String = "",
@SerialName("reason_source") val reasonSource: String = "",
val artifacts: List<String> = emptyList(),
)
@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,
)
/**
* The recorded evidence of one stage's session file export, mirroring
* internal/protocol/runs.go SessionExport exactly: the html file name written
* under the step's artifacts directory, its byte size, the decoded message
* count, the source, whether the export was truncated and a sanitized
* diagnostic. An absent (null) value means the step recorded no export (a
* non-OpenCode harness, a failed export or a pre-export server), so no Session
* section is shown. A record written before the HTML-only change also carried
* markdown and markdown_bytes; unknown keys are ignored.
*/
@Serializable
data class SessionExport(
@SerialName("session_id") val sessionId: String = "",
val backend: String = "",
val source: String = "",
val html: String = "",
@SerialName("html_bytes") val htmlBytes: Long = 0,
val messages: Int = 0,
val truncated: Boolean = false,
val diagnostic: String = "",
)
@Serializable
data class RunSummary(
@SerialName("resource_wait") val resourceWait: ResourceWait? = null,
val id: Long = 0,
@SerialName("pipeline_id") val pipelineId: Long = 0,
val name: String = "",
// The operator-facing, bounded description of what the run is for, generated
// by the server from its prompt. Null/blank on a server that predates the
// field, so the UI falls back to [name] rather than showing an empty line.
val title: String? = null,
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,
// Absent (null) means the step carried no artifact field; an empty list means
// an explicitly recorded, empty capture. Mirrors internal/protocol/runs.go.
val artifacts: List<StageArtifact>? = null,
@SerialName("artifacts_skipped") val artifactsSkipped: Int = 0,
@SerialName("artifacts_truncated") val artifactsTruncated: Int = 0,
// The server's derived plain-language verdict; absent (null) on a running step
// or a pre-verdict server, so the pane shows no block.
val verdict: StageVerdict? = null,
// The step's recorded session file export; absent (null) when the visit has
// none, so the stage pane lists no Session section.
@SerialName("session_export") val sessionExport: SessionExport? = 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(
@SerialName("resource_wait") val resourceWait: ResourceWait? = null,
val id: Long = 0,
@SerialName("pipeline_id") val pipelineId: Long = 0,
val name: String = "",
// Mirrors the embedded RunSummary.title (see internal/protocol/runs.go).
val title: String? = null,
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(),
)
/**
* The server-pushed `run_event` delta (internal/protocol/runevents.go
* RunEventFrame). It carries only the values that changed, never the whole run:
* the run's identity, status, outcome, current stage, completed-step count and
* timestamps, plus at most one changed step. Every field is optional so a client
* folds the frame into its cached run rather than replacing it.
*/
@Serializable
data class RunEventFrame(
@SerialName("resource_wait") val resourceWait: ResourceWait? = null,
@SerialName("resource_wait_set") val resourceWaitSet: Boolean = false,
@SerialName("run_id") val runId: Long = 0,
val workspace: String = "",
// The run's pipeline identity and stored title, repeated on every frame so a
// client that has never held the run can build its list row from the frame
// (the fold's new-run case) rather than re-reading the whole list. Blank on a
// server that predates them, which makes the fold fall back to a resync.
@SerialName("pipeline_id") val pipelineId: Long = 0,
val name: String = "",
val title: String = "",
val version: Int = 0,
val status: String = "",
val outcome: String = "",
@SerialName("current_stage") val currentStage: String = "",
@SerialName("completed_steps") val completedSteps: Int = 0,
@SerialName("created_at") val createdAt: String = "",
@SerialName("finished_at") val finishedAt: String = "",
// Protocol-mirror field (runevents.go `artifacts`): carried for wire parity,
// not read by the fold. Artifact capture surfaces through the full `get_run`
// the fold requests for a settled step, not from this count.
val artifacts: Int = 0,
val step: RunStepDelta? = null,
)
@Serializable
data class ResourceWait(
val resource: String = "",
val stage: String = "",
val sequence: Int = 0,
@SerialName("queued_since") val queuedSince: String = "",
) {
fun statusLabel(): String = "Waiting for resource $resource"
}
/**
* The compact change of one step within a [RunEventFrame]
* (internal/protocol/runevents.go RunStepDelta): a delta, not a RunStep, so it
* omits the input/output, transcript, file changes and artifact list a full step
* carries.
*/
@Serializable
data class RunStepDelta(
val sequence: Int = 0,
val stage: String = "",
val status: String = "",
val outcome: String = "",
val target: String = "",
val diagnostic: String = "",
// Protocol-mirror field, like RunEventFrame.artifacts: mirrored for wire
// parity and not read by the fold.
val artifacts: Int = 0,
)
@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 omni-search request body (internal/protocol/search.go SearchRequest): the
* free text query, an optional single-kind narrowing, and an optional result
* cap (0 = server default). The typed, ranked result payload is added with the
* search-results item; for now the reply is classified by its envelope type so a
* server that cannot answer is reported, never mis-parsed.
*/
@Serializable
data class SearchRequest(
val query: String = "",
val kind: String = "",
val limit: Int = 0,
)
/**
* The typed, ranked omni-search reply body (internal/protocol/search.go
* SearchResponse). [results] are ordered by score, then recency, then a stable
* kind/target tie-break; [truncated] reports that the result cap or the
* field-scan budget dropped matches and the scan counters make that bound
* observable. An empty [results] list is a real, empty result, not a failure.
*/
@Serializable
data class SearchResponse(
val query: String = "",
val kind: String = "",
val results: List<SearchResult> = emptyList(),
val truncated: Boolean = false,
@SerialName("scanned_steps") val scannedSteps: Int = 0,
@SerialName("scanned_bytes") val scannedBytes: Int = 0,
val cap: Int = 0,
@SerialName("scan_bound_bytes") val scanBoundBytes: Int = 0,
)
/**
* One typed search match (internal/protocol/search.go SearchResult). [kind]
* selects which payload is set; [target] is a stable token an existing command
* resolves and [matchedField] records why it matched. Every payload is
* nullable, so an unknown kind decodes without crashing and is shown read-only
* rather than dropped.
*/
@Serializable
data class SearchResult(
val kind: String = "",
val target: String = "",
val score: Int = 0,
@SerialName("matched_field") val matchedField: String = "",
val recency: String? = null,
val pipeline: SearchPipeline? = null,
val version: SearchVersion? = null,
val run: SearchRun? = null,
val step: SearchStep? = null,
val field: SearchField? = null,
val artifact: SearchArtifact? = null,
)
@Serializable
data class SearchPipeline(
val id: Long = 0,
val name: String = "",
val version: Int = 0,
val stages: Int = 0,
)
@Serializable
data class SearchVersion(
@SerialName("pipeline_id") val pipelineId: Long = 0,
val version: Int = 0,
@SerialName("content_hash") val contentHash: String = "",
@SerialName("created_at") val createdAt: String = "",
)
@Serializable
data class SearchRun(
val id: Long = 0,
@SerialName("pipeline_name") val pipelineName: String = "",
val status: String = "",
val workspace: String? = null,
@SerialName("created_at") val createdAt: String = "",
@SerialName("finished_at") val finishedAt: String? = null,
@SerialName("duration_seconds") val durationSeconds: Double = 0.0,
)
@Serializable
data class SearchStep(
@SerialName("run_id") val runId: Long = 0,
val sequence: Int = 0,
val stage: String = "",
val visit: Int = 0,
val outcome: String? = null,
val target: String? = null,
val diagnostic: String? = null,
)
@Serializable
data class SearchField(
@SerialName("run_id") val runId: Long = 0,
val sequence: Int = 0,
val field: String = "",
val snippet: String = "",
)
@Serializable
data class SearchArtifact(
@SerialName("run_id") val runId: Long = 0,
val sequence: Int = 0,
val name: String = "",
@SerialName("content_type") val contentType: String = "",
@SerialName("size_bytes") val sizeBytes: Long = 0,
val url: 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,
// The decide request body (runs.go DecideRun): the stage to answer (empty
// lets the server infer it), the chosen option and optional feedback. Every
// field is optional so an unrelated envelope never carries them.
val stage: String? = null,
val option: String? = null,
val feedback: String? = null,
// The workspace-scoped run-state push subscription: `run_ids` is the optional
// subscribe scope and `run_event` the server-pushed delta (runevents.go).
@SerialName("run_ids") val runIds: List<Long>? = null,
@SerialName("run_event") val runEvent: RunEventFrame? = null,
val search: SearchRequest? = null,
@SerialName("search_results") val searchResults: SearchResponse? = 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,
// Brokered chat traffic (see Chat.kt). Optional so an older server never
// breaks the existing envelope.
@SerialName("chat_sessions") val chatSessions: List<ChatSession>? = null,
@SerialName("chat_session") val chatSession: ChatSession? = null,
@SerialName("chat_create") val chatCreate: ChatCreateRequest? = null,
@SerialName("chat_query") val chatQuery: ChatQuery? = null,
@SerialName("chat_prompt") val chatPrompt: ChatPromptRequest? = null,
// A chat_prompt response with this set was accepted into the session's queue
// because a turn is already in flight; the composer shows queued/steering
// instead of blocking input.
@SerialName("chat_queued") val chatQueued: Boolean = false,
@SerialName("chat_subscribe") val chatSubscribe: ChatQuery? = null,
@SerialName("chat_messages") val chatMessages: List<ChatMessage>? = null,
@SerialName("chat_history") val chatHistory: ChatHistoryPage? = null,
@SerialName("chat_event") val chatEvent: ChatEventFrame? = null,
@SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null,
@SerialName("chat_reply") val chatReply: ChatReplyRequest? = null,
// The outcome of a chat_close (session id, closed_at, interrupted); the
// close/reopen requests themselves ride on chat_query like chat_interrupt.
@SerialName("chat_close") val chatClose: ChatCloseResult? = null,
@SerialName("chat_directories") val chatDirectories: List<String>? = null,
@SerialName("chat_shell_output_query") val chatShellOutputQuery: ChatShellOutputQuery? = null,
@SerialName("chat_shells") val chatShells: List<ChatShell>? = null,
@SerialName("chat_shell_output") val chatShellOutput: ChatShellOutputPage? = null,
)
@@ -1,40 +0,0 @@
package net.awan.pipelines.data.transport
/** What the app does with the connection the moment it becomes visible again. */
enum class ForegroundAction {
/** Leave the connection exactly as it is. */
LeaveAlone,
/** Re-establish the connection now, cancelling any pending reconnect delay. */
Reconnect,
}
/**
* The app's return-to-foreground recovery policy, in one pure place.
*
* Android freezes and often kills a backgrounded app's process, so the socket
* the app holds dies or goes quiet while another app is in front and nothing in
* the process notices in time. Coming back must restore that connection without
* the operator tapping Connect — but an explicit Disconnect is the operator's
* own decision and stays authoritative. A deliberate Disconnect is the only way
* the client reaches [ConnectionState.Idle], so Idle is left alone; every other
* state reconnects.
*
* A still [ConnectionState.Connected] socket is not trusted on return: a frozen
* process can leave it claiming Connected while it answers nothing, which is
* exactly the stale state this replaces. The caller therefore checks it with a
* positive probe (the existing ping) and passes the verdict as [confirmedAlive];
* only a connection just confirmed to answer is left alone.
*
* @param state the connection state at the moment the app became visible again.
* @param confirmedAlive whether a [ConnectionState.Connected] socket has just
* been confirmed to answer. It is consulted only for Connected; every other
* state carries its own answer.
*/
fun foregroundAction(state: ConnectionState, confirmedAlive: Boolean): ForegroundAction = when (state) {
ConnectionState.Idle -> ForegroundAction.LeaveAlone
is ConnectionState.Connected ->
if (confirmedAlive) ForegroundAction.LeaveAlone else ForegroundAction.Reconnect
is ConnectionState.Connecting -> ForegroundAction.Reconnect
is ConnectionState.Disconnected -> ForegroundAction.Reconnect
}
@@ -1,14 +0,0 @@
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
}
@@ -1,333 +0,0 @@
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.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
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()
// Unsolicited server frames (server-pushed chat_event / chat_permission /
// stream errors). Buffered and dropped-oldest so a slow collector can never
// block the socket read loop; chats re-sync from history after a gap anyway.
private val _events = MutableSharedFlow<Message>(
extraBufferCapacity = 256,
onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
)
val events: SharedFlow<Message> = _events.asSharedFlow()
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
/** Serializes socket replacement with callbacks arriving on OkHttp threads. */
private val connectionLock = Any()
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) {
synchronized(connectionLock) {
connectLocked(validated)
}
}
/**
* Re-opens a connection the transport lost without reversing an explicit
* [disconnect]. The check and connection replacement share one lock, so a
* Disconnect racing a foreground liveness probe wins even after that probe
* has decided recovery is needed.
*/
fun recover(validated: ServerUrl.Validated) {
synchronized(connectionLock) {
if (manualClose) return
connectLocked(validated)
}
}
private fun connectLocked(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() {
synchronized(connectionLock) {
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 (id, deferred) = synchronized(connectionLock) {
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
val payload = json.encodeToString(Message.serializer(), request.copy(id = id))
if (!socket.send(payload)) {
pending.remove(id)
throw IOException("websocket send failed")
}
id to deferred
}
try {
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)
}
}
}
/**
* Sends one request and returns its generated id without awaiting a matching
* reply. For a command whose reply is optional (the run-event `subscribe` ack)
* or whose effect is observed through the push stream instead, so a server
* that never acks cannot hold the send lock for the whole request timeout. The
* command still carries a stable id, so any reply lands on [events] and can be
* matched there.
*/
suspend fun sendOnly(request: Message): String = withContext(ioDispatcher) {
sendLock.withLock {
synchronized(connectionLock) {
val socket = webSocket ?: throw NotConnectedException()
if (_state.value !is ConnectionState.Connected) throw NotConnectedException()
val id = "android-" + sequence.incrementAndGet()
val payload = json.encodeToString(Message.serializer(), request.copy(id = id))
if (!socket.send(payload)) throw IOException("websocket send failed")
id
}
}
}
/**
* Fetches raw bytes for a resolved artifact url over the existing OkHttp
* client on the IO dispatcher. Used for image previews; never part of the
* run poll. A non-2xx response or an empty body is an error.
*/
suspend fun fetchBytes(url: String): ByteArray = withContext(ioDispatcher) {
val request = Request.Builder().url(url).build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("HTTP ${response.code} for $url")
response.body?.bytes() ?: throw IOException("empty response body for $url")
}
}
private fun open() = synchronized(connectionLock) { openLocked() }
private fun openLocked() {
val current = endpoint ?: return
attempt += 1
_state.value = ConnectionState.Connecting(attempt)
val request = Request.Builder().url(current).build()
// Replace the current socket, then close the one it superseded. Its
// callbacks are ignored from then on (see [isCurrent]), so a failure the
// old socket reports late — the common case when the process was frozen
// while it died — can neither clear the new socket nor schedule a
// reconnect that would undo it.
val superseded = webSocket
webSocket = httpClient.newWebSocket(request, listener)
// A request sent over the superseded socket cannot receive a reply from
// the replacement. Fail it now rather than leaving a screen waiting for
// the ordinary request timeout after recovery.
if (superseded != null) failPending("Connection replaced")
superseded?.close(NORMAL_CLOSURE, "superseded")
}
/**
* Whether [socket] is still the connection this client acts on. A socket this
* client has already replaced (a deliberate reconnect, or the foreground
* recovery re-establishing a frozen one) must never drive the state again.
*/
private fun isCurrent(socket: WebSocket): Boolean = webSocket === socket
private fun failPending(reason: String) {
val snapshot = pending.keys.toList()
for (key in snapshot) {
pending.remove(key)?.completeExceptionally(IOException(reason))
}
}
private fun handleClosed(socket: WebSocket, reason: String) {
if (!isCurrent(socket)) return
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 backoff = reconnectBackoffMillis(attempt)
val jitter = Random.nextLong(0, 400)
reconnectJob = scope.launch {
delay(backoff + jitter)
synchronized(connectionLock) {
if (!manualClose && endpoint != null) open()
}
}
}
private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
synchronized(connectionLock) {
if (!isCurrent(webSocket)) return
attempt = 0
_state.value = ConnectionState.Connected(build = null, serverTime = null)
}
}
override fun onMessage(webSocket: WebSocket, text: String) {
synchronized(connectionLock) {
if (!isCurrent(webSocket)) return
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)
} else {
// Unsolicited envelopes (the connection's initial pipeline_list,
// server-pushed chat frames, stream errors) carry no matching id:
// hand them to the event stream instead of dropping them.
_events.tryEmit(message)
}
}
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
synchronized(connectionLock) {
handleClosed(webSocket, "Connection closed (${code})")
}
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
synchronized(connectionLock) {
if (!isCurrent(webSocket)) return
webSocket.close(NORMAL_CLOSURE, null)
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
synchronized(connectionLock) {
val reason = t.message?.ifBlank { t.javaClass.simpleName } ?: "connection failed"
handleClosed(webSocket, 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
/**
* The successful open callback resets [attempt] to zero. A later socket
* failure must therefore begin at the base delay, never shift by -1
* (which Kotlin masks into a very large shift count).
*/
internal fun reconnectBackoffMillis(attempt: Int): Long {
val exponent = (attempt - 1).coerceIn(0, 6)
return (BASE_BACKOFF_MILLIS shl exponent).coerceAtMost(MAX_BACKOFF_MILLIS)
}
}
}
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()
@@ -1,111 +0,0 @@
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,
)
}
/**
* Resolves a server-relative artifact url (for example
* `/artifacts/55/4/shot.png`) against the configured server URL by reusing
* [validate]'s host/port/secure and mapping ws/wss to http/https, dropping the
* `/connect` websocket path. Never hardcodes a host: a blank or invalid
* configuration, or a blank path, yields null so the UI can disable actions.
*
* An already-absolute `http(s)://` url is returned unchanged.
*/
fun resolveArtifactUrl(configured: String, artifactUrl: String): String? {
val relative = artifactUrl.trim()
if (relative.isEmpty()) return null
if (relative.startsWith("http://") || relative.startsWith("https://")) return relative
val validated = validate(configured)
if (!validated.valid || validated.host.isNullOrBlank()) return null
val origin = buildString {
append(if (validated.secure) "https" else "http").append("://").append(validated.host)
val defaultPort = if (validated.secure) 443 else 80
if (validated.port > 0 && validated.port != defaultPort) {
append(':').append(validated.port)
}
}
val path = if (relative.startsWith("/")) relative else "/$relative"
return origin + path
}
}
@@ -1,249 +0,0 @@
package net.awan.pipelines.notify
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.AttentionKind
import net.awan.pipelines.ui.RUN_DEEP_LINK_ACTION_DECIDE
import net.awan.pipelines.ui.RUN_DEEP_LINK_ACTION_PARAM
import net.awan.pipelines.ui.RUN_DEEP_LINK_PREFIX
/**
* The one place the app decides what becomes an Android notification.
*
* The operator's rule is the same on every surface: only a run waiting for a
* decision and a run that failed ask for a person. A successful run, a running
* run or a cancelled one raises nothing, so the system tray can never fill with
* work that is not actionable. The mapping reads the attention model's kinds
* (see `ui/Attention.kt`), so the tray and the in-app surface can never disagree
* about what needs the operator.
*
* Everything here is pure — no Android types, no `Context`, no clock — so the
* mapping, the coalescing and clearing rules, the permission paths and the tap
* destination are all unit-tested on the JVM without a device.
*/
/** The two run events that raise a notification. */
enum class RunAlertKind { Decision, Failed }
/**
* Where the app's notifications actually go. The ViewModel depends on this, not
* on Android, so the run-watch logic stays free of `Context` and the concrete
* poster ([RunNotifier]) is the only Android part.
*/
interface RunAlertSink {
/** Whether a notification can be shown right now (permission granted, not silenced). */
fun notificationsAllowed(): Boolean
/** Moves the tray to exactly the alerts the attention list currently raises. */
fun sync(alerts: List<RunAlert>)
/** Clears one run's notifications because the operator reached it. */
fun arrived(runId: Long)
}
/** A sink that shows nothing: the default until the Android poster is wired in. */
object NoRunAlerts : RunAlertSink {
override fun notificationsAllowed(): Boolean = false
override fun sync(alerts: List<RunAlert>) = Unit
override fun arrived(runId: Long) = Unit
}
/** Where a notification's tap lands inside the app. */
enum class AlertTapTarget { DecisionSheet, Run }
/** One run that needs the operator, as the tray shows it. */
data class RunAlert(
val runId: Long,
val kind: RunAlertKind,
val title: String,
val text: String,
) {
/** The stable identity of one run+event-kind alert; the unit of dedupe. */
val key: String get() = alertKey(runId, kind)
}
/** The identity of one run+kind alert: exactly one notification, never repeated. */
internal fun alertKey(runId: Long, kind: RunAlertKind): String = "$runId:${kind.name}"
/**
* The alert kind an attention kind maps to. The attention model already holds
* only what needs a person — a waiting run ([AttentionKind.Decision]) and a
* failed run ([AttentionKind.Failed]) — so every entry raises exactly one
* notification and nothing else can.
*/
fun alertKindOf(kind: AttentionKind): RunAlertKind = when (kind) {
AttentionKind.Decision -> RunAlertKind.Decision
AttentionKind.Failed -> RunAlertKind.Failed
}
/** The short headline a notification shows for one kind. */
internal fun alertTitle(kind: RunAlertKind): String = when (kind) {
RunAlertKind.Decision -> "A run needs your decision"
RunAlertKind.Failed -> "A run failed"
}
/** The line naming the run: its label, then the pipeline it belongs to. */
internal fun alertText(entry: AttentionEntry): String =
if (entry.pipeline.isBlank() || entry.pipeline == entry.label) {
entry.label
} else {
"${entry.label} · ${entry.pipeline}"
}
/**
* The alerts the current attention list raises, in the surface's own order
* (decision, then failure). The attention list already holds only what needs a
* person, so nothing that needs nobody can reach the tray.
*/
fun runAlerts(entries: List<AttentionEntry>): List<RunAlert> = entries.map { entry ->
val kind = alertKindOf(entry.kind)
RunAlert(runId = entry.runId, kind = kind, title = alertTitle(kind), text = alertText(entry))
}
/**
* The one summary a coalesced group shows: how many runs need the operator and
* what each is. Present only when more than one alert is pending, so a single
* run never gets a redundant wrapper and several are one grouped notification
* rather than a pile.
*/
data class AlertSummary(
val count: Int,
val title: String,
val text: String,
val lines: List<String>,
)
/** The grouped summary for [alerts], or null when at most one is pending. */
fun alertSummary(alerts: List<RunAlert>): AlertSummary? {
if (alerts.size < 2) return null
val waiting = alerts.count { it.kind == RunAlertKind.Decision }
val failed = alerts.count { it.kind == RunAlertKind.Failed }
val counts = buildList {
if (waiting > 0) add(if (waiting == 1) "1 waiting for you" else "$waiting waiting for you")
if (failed > 0) add(if (failed == 1) "1 failed" else "$failed failed")
}.joinToString(" · ")
return AlertSummary(
count = alerts.size,
title = "${alerts.size} runs need you",
text = counts,
lines = alerts.map { "${it.title} — ${it.text}" },
)
}
/** The alerts to post and the keys to cancel after one reconciliation. */
data class AlertDelta(val post: List<RunAlert>, val cancel: List<RunAlert>) {
val isEmpty: Boolean get() = post.isEmpty() && cancel.isEmpty()
}
/**
* What the tray is currently showing, keyed by run+kind. It is what makes the
* notifications deduplicated and non-repeating:
*
* - [reconcile] posts only a run+kind that is not already shown, so a run that
* stays failed or waiting is never re-posted (no storm, no duplicate).
* - It cancels exactly the keys that left the desired set, so a resolved,
* answered or dismissed run's notification is cleared.
* - [arrived] cancels one run's notifications when the operator reaches it, but
* keeps its keys, so arriving at a still-waiting run does not make the next
* reconciliation post it again.
*/
class AlertLedger {
private val posted = LinkedHashMap<String, RunAlert>()
/** Keys the operator already reached, kept for dedupe but no longer visible. */
private val hidden = LinkedHashSet<String>()
/** The alerts currently shown, by key. */
val shown: Map<String, RunAlert> get() = posted.toMap()
/** The alerts still on screen: posted and not cleared by the operator arriving. */
fun visible(): List<RunAlert> = posted.values.filter { it.key !in hidden }
/** The post/cancel delta that moves what is shown to exactly [desired]. */
fun reconcile(desired: List<RunAlert>): AlertDelta {
val desiredByKey = desired.associateBy { it.key }
val toPost = desired.filter { it.key !in posted }
val toCancel = posted.values.filter { it.key !in desiredByKey }
toPost.forEach {
posted[it.key] = it
// A new event for a run the operator reached earlier is shown again.
hidden.remove(it.key)
}
toCancel.forEach {
posted.remove(it.key)
hidden.remove(it.key)
}
return AlertDelta(post = toPost, cancel = toCancel)
}
/**
* The alerts to cancel because the operator arrived at [runId]. Their keys
* are kept, so a run that is still waiting is not re-notified on the next
* reconciliation, and they are hidden from the visible set so a grouped
* summary stops counting them; when the run leaves the attention list it is
* removed here.
*/
fun arrived(runId: Long): List<RunAlert> {
val arrived = posted.values.filter { it.runId == runId }
hidden.addAll(arrived.map { it.key })
return arrived
}
/** Forgets everything (used when permission is revoked, so a later grant re-posts). */
fun clear() {
posted.clear()
hidden.clear()
}
}
/**
* Whether the notification permission should be requested now, and why.
*
* The request happens at most once: [granted] means there is nothing to ask,
* [asked] means the operator has already been asked (or refused) and must never
* be nagged again, and [trigger] is the sensible moment (the first time a run
* needs them, or the operator opening the attention surface). Only "not granted,
* never asked, and something actually needs the operator" asks.
*/
data class AlertPermissionPrompt(val request: Boolean, val rationale: String?)
/** The rationale shown once before the system permission dialog. */
const val NOTIFICATION_RATIONALE: String =
"Pipelines can notify you when a run is waiting for your decision or has failed. " +
"Without it, those runs still appear in the in-app Needs you surface."
/** The permission prompt decision for the current state. Pure, so every path is tested. */
fun alertPermissionPrompt(granted: Boolean, asked: Boolean, trigger: Boolean): AlertPermissionPrompt =
when {
granted -> AlertPermissionPrompt(request = false, rationale = null)
asked -> AlertPermissionPrompt(request = false, rationale = null)
!trigger -> AlertPermissionPrompt(request = false, rationale = null)
else -> AlertPermissionPrompt(request = true, rationale = NOTIFICATION_RATIONALE)
}
/** The tap destination one kind opens. */
fun alertTapTarget(kind: RunAlertKind): AlertTapTarget = when (kind) {
RunAlertKind.Decision -> AlertTapTarget.DecisionSheet
RunAlertKind.Failed -> AlertTapTarget.Run
}
/**
* The deep link a notification's tap opens. A waiting run carries the decide
* action so it lands on the decision sheet; a failed run opens the run itself.
* Both resolve through the app's one `pipelines://run/<id>` deep link, which
* only ever opens a run and starts nothing.
*/
fun alertDeepLink(runId: Long, kind: RunAlertKind): String {
val base = "$RUN_DEEP_LINK_PREFIX$runId"
return when (alertTapTarget(kind)) {
AlertTapTarget.DecisionSheet -> "$base?$RUN_DEEP_LINK_ACTION_PARAM=$RUN_DEEP_LINK_ACTION_DECIDE"
AlertTapTarget.Run -> base
}
}
/**
* The notification id for one run+kind: stable for the life of the run, so
* re-posting the same event updates in place instead of stacking a duplicate.
*/
fun alertNotificationId(runId: Long, kind: RunAlertKind): Int =
((runId * 2L + kind.ordinal) and 0x7FFFFFFFL).toInt()
@@ -1,187 +0,0 @@
package net.awan.pipelines.notify
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import net.awan.pipelines.MainActivity
import net.awan.pipelines.R
/**
* The app's own Android notifications for runs that need the operator.
*
* It is deliberately thin: every decision — what becomes an alert, when several
* are one grouped summary, when one is cleared, whether the permission should be
* asked — is the pure [RunAlerts] model, unit-tested on the JVM. This class only
* creates the channel and posts/cancels through [NotificationManagerCompat], so
* it holds no rule of its own that a test would have to reach through Android.
*
* Notifications are posted from the app's own process. While the app is
* backgrounded the process (and the run subscription feeding [sync]) is alive, so
* the events still arrive and are shown; the server also publishes the same two
* events to the operator's ntfy topic, which is the out-of-process backstop when
* the app's process is killed.
*/
class RunNotifier(private val context: Context) : RunAlertSink {
private val manager = NotificationManagerCompat.from(context)
private val ledger = AlertLedger()
/** Whether the tray last showed a grouped summary, so a threshold change re-groups. */
private var grouped = false
/** Creates the one channel runs that need the operator post into. Idempotent. */
fun ensureChannel() {
val channel = NotificationChannel(
CHANNEL_ID,
"Runs that need you",
NotificationManager.IMPORTANCE_HIGH,
).apply {
description = "A run waiting for your decision or a run that failed"
}
manager.createNotificationChannel(channel)
}
/**
* Whether a notification can actually be shown right now: the POST_NOTIFICATIONS
* runtime permission on Android 13+, the app's own notification switch before
* that. When false the app degrades to the in-app attention surface and shows
* nothing here, rather than pretending a notification was posted.
*/
override fun notificationsAllowed(): Boolean =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ContextCompat.checkSelfPermission(context, POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
} else {
manager.areNotificationsEnabled()
}
/**
* Moves the tray to exactly the alerts the attention list currently raises:
* each run+kind posted once (never repeated while it stays failed or waiting),
* a run that no longer needs the operator cleared, and several pending runs
* coalesced into one grouped summary. Without the permission nothing is posted
* and the ledger is forgotten, so a later grant re-posts rather than assuming.
*/
override fun sync(alerts: List<RunAlert>) {
if (!notificationsAllowed()) {
ledger.clear()
manager.cancelAll()
grouped = false
return
}
val delta = ledger.reconcile(alerts)
delta.cancel.forEach { manager.cancel(alertNotificationId(it.runId, it.kind)) }
render(visible = ledger.visible(), delta = delta)
}
/**
* Clears one run's notifications because the operator reached it, and refreshes
* the grouped summary so it stops counting a run the operator has already
* opened. The ledger keeps the run+kind, so a run that stays waiting is not
* re-notified.
*/
override fun arrived(runId: Long) {
if (!notificationsAllowed()) return
val arrived = ledger.arrived(runId)
if (arrived.isEmpty()) return
arrived.forEach { manager.cancel(alertNotificationId(it.runId, it.kind)) }
render(visible = ledger.visible(), delta = AlertDelta(post = emptyList(), cancel = emptyList()))
}
/**
* Draws the still-visible alerts at the group/summary shape their count needs.
* A move across the one-versus-many boundary re-posts the visible children once
* (only-alert-once keeps it silent); otherwise only genuinely new alerts are
* posted, so nothing is repeated or re-alerted.
*/
private fun render(visible: List<RunAlert>, delta: AlertDelta) {
val groupedNow = visible.size >= 2
val toPost = if (groupedNow != grouped) visible else delta.post
toPost.forEach { manager.notify(alertNotificationId(it.runId, it.kind), buildAlert(it, groupedNow)) }
val summary = if (groupedNow) alertSummary(visible) else null
if (summary != null) manager.notify(SUMMARY_ID, buildSummary(summary)) else manager.cancel(SUMMARY_ID)
grouped = groupedNow
}
private fun buildAlert(alert: RunAlert, grouped: Boolean): Notification {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(alert.title)
.setContentText(alert.text)
.setContentIntent(tapIntent(alert))
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
if (grouped) {
builder.setGroup(GROUP_KEY)
// Several arriving together alert once, through the summary, instead of
// a burst of per-run sounds.
builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
}
return builder.build()
}
private fun buildSummary(summary: AlertSummary): Notification =
NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(summary.title)
.setContentText(summary.text)
.setStyle(NotificationCompat.InboxStyle().also { style ->
summary.lines.forEach(style::addLine)
})
// The group's own tap opens the app, where the Needs you chip lists
// every run the summary counts; the individual taps open each run.
.setContentIntent(openAppIntent())
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build()
/** The tap intent: the run's own deep link, which only ever opens a run. */
private fun tapIntent(alert: RunAlert): PendingIntent {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(alertDeepLink(alert.runId, alert.kind)), context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
return PendingIntent.getActivity(
context,
alertNotificationId(alert.runId, alert.kind),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
/** Opens the app (where the attention surface lives) without naming a run. */
private fun openAppIntent(): PendingIntent {
val intent = Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
return PendingIntent.getActivity(
context,
SUMMARY_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}
private companion object {
const val CHANNEL_ID = "runs_need_you"
/** The single grouped-summary notification id; children derive from run+kind. */
const val SUMMARY_ID = 1
const val GROUP_KEY = "net.awan.pipelines.RUNS"
/** The POST_NOTIFICATIONS permission name, spelled out to keep the import list lean. */
const val POST_NOTIFICATIONS = "android.permission.POST_NOTIFICATIONS"
}
}
File diff suppressed because it is too large Load Diff
@@ -1,99 +0,0 @@
package net.awan.pipelines.ui
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.ui.screens.runTimeline
/**
* Every artifact one visit of one stage recorded, in the order the visit's
* artifacts were reported. Duplicate names are tolerated (kept, not deduped): an
* artifact's identity is its recorded url, not its name.
*/
data class ArtifactGroup(
val stageKey: String,
val visit: Int,
val artifacts: List<StageArtifact>,
)
/**
* The retired markdown session export file name. Nothing writes it any more, but
* a run recorded before the HTML-only change still has `session.md` on disk: it
* is dated evidence that is never presented, so it is hidden from every artifact
* listing rather than shown beside the session html.
*/
const val LEGACY_SESSION_MARKDOWN_ARTIFACT = "session.md"
/**
* The artifacts of one visit as the operator sees them: the recorded files with
* the retired markdown session export filtered out. Every artifact listing — the
* per-visit summary, the run gallery, the timeline indicator and the selection
* candidates — derives from this one function, so a stage's artifacts never show
* a session markdown beside the session html and the recorded counts can never
* disagree with the tiles. Pure, O(artifacts) per step.
*/
fun presentedArtifacts(step: RunStep): List<StageArtifact> =
step.artifacts.orEmpty().filterNot { it.name == LEGACY_SESSION_MARKDOWN_ARTIFACT }
/**
* Groups a run's artifacts by stage and visit, purely and deterministically.
* Order follows [runTimeline]: stages in first-appearance order and each stage's
* visits by sequence, with the same display visit number (the recorded control
* visit, else the position within the stage). Only visits that recorded at least
* one artifact produce a group, so an empty/absent capture never yields an empty
* group and an artifact-less run yields an empty list. O(steps), single pass.
*/
fun runArtifactGroups(steps: List<RunStep>): List<ArtifactGroup> {
if (steps.isEmpty()) return emptyList()
val timeline = runTimeline(steps)
// Reuse runTimeline's display visit number rather than re-deriving it: the
// entries already carry (stage, sequence) -> visit. O(steps), built once.
val visitByStageSequence = timeline.entries.associate { (it.stageKey to it.step.sequence) to it.visit }
val groups = ArrayList<ArtifactGroup>()
timeline.visitsByStage.forEach { (stageKey, visits) ->
visits.forEach { step ->
val artifacts = presentedArtifacts(step)
if (artifacts.isNotEmpty()) {
val visit = visitByStageSequence[stageKey to step.sequence] ?: 1
groups += ArtifactGroup(stageKey, visit, artifacts)
}
}
}
return groups
}
/**
* The explicit message shown where the run's artifacts gallery would be when
* there are none: while the run is executing it uses the same "capture pending"
* wording as a running visit, otherwise it says plainly that nothing was
* recorded.
*/
fun artifactsEmptyMessage(executing: Boolean): String =
if (executing) {
"Artifacts · $ARTIFACT_CAPTURE_PENDING"
} else {
"No artifacts recorded for this run."
}
/**
* The run summary's Artifacts section header, complete on its own while the
* section is collapsed: the title, how many artifacts the run recorded (the
* title takes its singular form for exactly one) and "partial capture" when any
* visit excluded or omitted files. It mirrors the per-visit [artifactsSummary]
* vocabulary at run level and reuses the shared [artifactsEmptyMessage] for the
* empty case, so a run with nothing recorded still gets a self-describing
* collapsed header. The recorded count is exactly the number of tiles
* [runArtifactGroups] yields, so the header and the expanded gallery can never
* disagree. Pure.
*/
fun runArtifactsHeader(steps: List<RunStep>, executing: Boolean): String {
val recorded = steps.sumOf { presentedArtifacts(it).size }
if (recorded == 0) return artifactsEmptyMessage(executing)
val partial = steps.any { it.artifactsSkipped > 0 || it.artifactsTruncated > 0 }
return buildString {
append(if (recorded == 1) "Artifact" else "Artifacts")
append(" · ")
append(recorded)
append(" recorded")
if (partial) append(" · partial capture")
}
}
@@ -1,193 +0,0 @@
package net.awan.pipelines.ui
import kotlinx.serialization.Serializable
import net.awan.pipelines.data.protocol.PipelinesJson
import net.awan.pipelines.data.protocol.RunSummary
/**
* The one place the app decides what needs the operator and how much it matters.
*
* A run's server status maps to at most one [AttentionKind]: a run parked on a
* person ([AttentionKind.Decision]) is the most important and a failed run
* ([AttentionKind.Failed]) next. Everything else — queued, running, succeeded,
* canceled, interrupted — asks nothing and is not listed, so the surface (and the
* system tray fed from it) can only ever show something that is genuinely
* actionable. A successful run is never announced.
*
* The list is advanced from the run events the server already pushes: the same
* `RunSummary` rows that the runs list is folded from feed [attentionEntries], so
* an entry appears and clears with no refresh and no request of its own.
*/
/** The two things the attention surface ranks, most important first. */
enum class AttentionKind(val rank: Int) {
Decision(0),
Failed(1),
}
/** One entry on the attention surface: what run needs the operator, and why. */
data class AttentionEntry(
val runId: Long,
val pipeline: String,
val label: String,
val kind: AttentionKind,
val detail: String,
/**
* The run's own recency (its finish time, else its creation time), used only
* to order equal kinds newest-first so the list never reshuffles on a read.
*/
val recency: String = "",
) {
/** The stable identity a dismissal is keyed by, so it survives the fold. */
val key: String get() = attentionKey(runId, kind)
}
/** The identity of one run+kind entry; the unit an explicit dismissal removes. */
internal fun attentionKey(runId: Long, kind: AttentionKind): String = "$runId:${kind.name}"
/**
* The attention kind a run status maps to, or null when the run needs nobody. It
* reads the server's own words only, so an unknown status can never invent an
* entry.
*/
internal fun attentionKindOf(status: String): AttentionKind? =
when (status.trim().lowercase()) {
"waiting" -> AttentionKind.Decision
"failed" -> AttentionKind.Failed
else -> null
}
/**
* What one entry asks of the operator, in the operator's words. A failed run
* shows the server's own diagnostic when it recorded one so the line is
* actionable rather than a bare "failed".
*/
internal fun attentionDetail(kind: AttentionKind, run: RunSummary): String = when (kind) {
AttentionKind.Decision -> "Waiting for your decision"
AttentionKind.Failed -> run.diagnostic.trim().ifBlank { "Run failed" }
}
/**
* The ordered attention list. Every run that needs the operator becomes one
* entry, ranked by kind (decision, then failure) and then newest-first within a
* kind, so the order is stable and never reshuffles between reads. An entry the
* operator explicitly dismissed never returns, and a waiting or failed run stays
* until it is resolved or dismissed, because it is still asking.
*/
internal fun attentionEntries(runs: List<RunSummary>, state: AttentionState): List<AttentionEntry> =
runs.mapNotNull { run ->
val kind = attentionKindOf(run.status) ?: return@mapNotNull null
if (attentionKey(run.id, kind) in state.dismissed) return@mapNotNull null
AttentionEntry(
runId = run.id,
pipeline = run.name,
label = run.title?.trim()?.takeIf { it.isNotEmpty() } ?: run.name,
kind = kind,
detail = attentionDetail(kind, run),
recency = run.finishedAt.ifBlank { run.createdAt },
)
}.sortedWith(
compareBy<AttentionEntry> { it.kind.rank }
.thenByDescending { it.recency }
.thenByDescending { it.runId },
)
/**
* What the operator has already dealt with on the attention surface, kept as one
* serializable preference so it survives a restart exactly like the app's other
* stored state:
*
* - [dismissed] is the run+kind keys the operator deliberately dismissed, so a
* still-waiting or still-failed run stays out of the list after an explicit
* dismissal.
*
* A successful run is never on the surface, so there is nothing to remember as
* "already looked at": the surface only ever holds work that still asks.
*/
@Serializable
data class AttentionState(
val dismissed: Set<String> = emptySet(),
) {
/** Removes one entry for good, whatever its run goes on to do. */
fun dismissed(key: String): AttentionState =
if (key.isBlank() || key in dismissed) this else copy(dismissed = dismissed + key)
/** The one-line JSON this value is stored as; never fails on our own value. */
fun encode(): String = PipelinesJson.encodeToString(serializer(), this)
companion object {
/** Decodes a stored value; anything unreadable falls back to nothing dealt with. */
fun decode(stored: String): AttentionState =
if (stored.isBlank()) {
AttentionState()
} else {
runCatching { PipelinesJson.decodeFromString(serializer(), stored) }
.getOrDefault(AttentionState())
}
}
}
/** The deep-link scheme the run notification's click action opens. */
internal const val RUN_DEEP_LINK_PREFIX = "pipelines://run/"
/** The query parameter a run deep link may carry to name what it should open. */
internal const val RUN_DEEP_LINK_ACTION_PARAM = "action"
/** The [RUN_DEEP_LINK_ACTION_PARAM] value that opens a waiting run's decision sheet. */
internal const val RUN_DEEP_LINK_ACTION_DECIDE = "decide"
/**
* What a `pipelines://run/<id>` deep link names: the run, and an optional action
* for what inside it to open (`decide` opens the decision sheet). Null for
* anything that is not a well-formed run link, so a malformed link opens nothing
* rather than a guessed run.
*/
internal data class RunLink(val runId: Long, val action: String?)
/**
* Parses the run id and optional action from a run deep link. The id must be the
* whole path segment, so `pipelines://run/1x` and `pipelines://run/0` parse to
* null instead of being truncated to a real run.
*/
internal fun runLinkFromDeepLink(link: String?): RunLink? {
val value = link?.trim().orEmpty()
if (!value.startsWith(RUN_DEEP_LINK_PREFIX)) return null
val rest = value.removePrefix(RUN_DEEP_LINK_PREFIX)
val path = rest.substringBefore('?')
if (path.isEmpty() || !path.all { it.isDigit() }) return null
val runId = path.toLongOrNull()?.takeIf { it > 0 } ?: return null
val action = rest.substringAfter('?', "")
.split('&')
.mapNotNull { part ->
val pair = part.split('=', limit = 2)
pair.getOrNull(1)?.takeIf { pair[0] == RUN_DEEP_LINK_ACTION_PARAM && it.isNotBlank() }
}
.firstOrNull()
return RunLink(runId, action)
}
/**
* The one-line headline the indicator shows: the single most important thing when
* there is one entry, else the count. Pure, so it can be asserted without a device.
*/
internal fun attentionHeadline(entries: List<AttentionEntry>): String = when {
entries.isEmpty() -> ""
entries.size == 1 -> when (entries[0].kind) {
AttentionKind.Decision -> "A run is waiting for you"
AttentionKind.Failed -> "A run failed"
}
else -> "${entries.size} runs need you"
}
/**
* Captures the entries shown when the attention sheet opens. Bulk dismissal uses
* this snapshot so entries that arrive while the sheet is open are not removed.
*/
internal fun attentionDismissalSnapshot(entries: List<AttentionEntry>): List<AttentionEntry> = entries.toList()
/**
* Parses the run id from a `pipelines://run/<id>` deep link, or null for
* anything else. Pure and total, so a malformed link simply opens nothing rather
* than a guessed run.
*/
internal fun runIdFromDeepLink(link: String?): Long? = runLinkFromDeepLink(link)?.runId
@@ -1,107 +0,0 @@
package net.awan.pipelines.ui
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RUN_STATUS_WAITING
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.humanOptions
import net.awan.pipelines.data.protocol.lastWaitingStep
import net.awan.pipelines.data.protocol.waitingOptions
import net.awan.pipelines.data.protocol.waitingPrompt
/**
* One option the author wrote for a waiting human stage: the edge [key] (the
* exact outcome the decision carries) and the [target] it routes to, resolved to
* the same label the graph shows (`publish`, `SUCCESS`, `FAILURE`). The target is
* what tells the operator where an option leads; it is blank when the pinned
* graph does not declare the option (an older server, or a recorded option the
* graph no longer carries).
*/
data class DecisionOption(val key: String, val target: String)
/**
* A run parked on a person: the run, the stage waiting, the author's recorded
* instructions and their ordered options. Derived purely from the run detail the
* app already holds (the waiting step's recorded evidence, falling back to the
* pinned graph), so the decision sheet and its unit test read one model instead
* of each parsing the step.
*/
data class PendingDecision(
val runId: Long,
val runLabel: String,
val stageKey: String,
val instructions: String,
val options: List<DecisionOption>,
) {
/** The author's option keys, in recorded order. */
val optionKeys: List<String> get() = options.map { it.key }
}
/**
* The pending decision a [run] is waiting on, or null when it is not waiting (or
* recorded no selectable options). The waiting step's own evidence wins over the
* pinned graph, so the decision still works when the graph is absent; the graph
* only supplies the target labels and, for a step from an older server, the
* option set itself.
*/
fun pendingDecision(run: RunDetail?): PendingDecision? {
if (run == null || run.status != RUN_STATUS_WAITING) return null
val step = lastWaitingStep(run.steps)
val stageKey = step?.stage?.takeIf { it.isNotBlank() }
?: run.currentStage.takeIf { it.isNotBlank() }
?: return null
val declared = run.graph.stages.firstOrNull { it.key == stageKey }
val keys = step?.let { waitingOptions(it.output) }.orEmpty()
.ifEmpty { declared?.let { humanOptions(it.edges) }.orEmpty() }
if (keys.isEmpty()) return null
val edges = declared?.edges.orEmpty()
val options = keys.map { key -> DecisionOption(key, decisionTargetLabel(key, edges[key])) }
val instructions = step?.let { waitingPrompt(it.output) }.orEmpty()
.ifBlank { declared?.prompt.orEmpty() }
return PendingDecision(
runId = run.id,
runLabel = runLabel(run.title, run.name),
stageKey = stageKey,
instructions = instructions,
options = options,
)
}
/**
* The resolved target label for one option: the author's target, with the `#`
* shorthand resolved and terminals named as the graph names them. Blank when the
* option's edge is not declared, so the sheet omits the detail instead of
* inventing a destination.
*/
internal fun decisionTargetLabel(option: String, target: String?): String {
if (target.isNullOrBlank()) return ""
return GraphSemantics.nodeLabel(Protocol.resolveTarget(option, target))
}
/**
* The operator's in-progress answer to a [PendingDecision]: the chosen option and
* optional feedback. Pure, so the deliberate-confirm rule (nothing is sent until
* an option is chosen and the confirm pressed) is unit-tested without a device.
*/
data class DecisionDraft(
val selected: String? = null,
val feedback: String = "",
) {
/** A decision is only sendable once the operator has chosen one option. */
val canSubmit: Boolean get() = !selected.isNullOrBlank()
/** Selecting an option is not an answer: it only enables the confirm. */
fun select(option: String): DecisionDraft = copy(selected = option)
/** Feedback is optional and carried verbatim (trimmed by the sender). */
fun withFeedback(text: String): DecisionDraft = copy(feedback = text)
}
/**
* The message a refused decision shows. The server's own text is used verbatim
* because it names exactly what happened (the run moved on, the stage changed,
* another client answered first), so a refusal is reported, never replaced by a
* generic failure.
*/
fun decisionRefusalMessage(error: Throwable): String = ErrorMessages.describe(error)
@@ -1,294 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.components.MotionStandard
import net.awan.pipelines.ui.components.spec
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
/**
* The horizontal offset of the pill's travelling selection indicator for the
* destination at [index]: the pill's inner padding plus [index] item slots
* ([itemSize] + [gap]). Pure and in one place, so the indicator lines up exactly
* with the icon it selects and the geometry is unit-testable without a device.
* A missing selection (-1) pins to the first slot and the caller draws nothing.
*/
internal fun destinationIndicatorOffsetDp(index: Int, itemSize: Dp, gap: Dp): Dp =
gap + (itemSize + gap) * index.coerceAtLeast(0)
/**
* The bottom container: the destination pill that morphs into the omni-search
* field. It is one [Surface] so the morph reads as the same container changing
* role, not two surfaces swapping. Neither opening nor dismissing navigates, so
* the destination the pill had selected is untouched and the reverse restores
* exactly that pill.
*/
@Composable
internal fun DestinationBar(
destinations: List<TopDestination>,
currentRoute: String?,
state: OmniSearchState,
onSelect: (TopDestination) -> Unit,
onOpenSearch: () -> Unit,
onDismissSearch: () -> Unit,
onQueryChange: (String) -> Unit,
onFocusChange: (Boolean) -> Unit,
onSubmitSearch: () -> Unit,
modifier: Modifier = Modifier,
) {
val scheme = MaterialTheme.colorScheme
Surface(
modifier = modifier,
shape = RoundedCornerShape(50),
color = scheme.surfaceContainerHigh,
tonalElevation = 3.dp,
shadowElevation = 6.dp,
) {
// The icons fade out while the field fades in, and the container takes the
// new content's size. The field fills the width the caller's inset padding
// leaves, so the grown size derives from that plus the field's own layout,
// and the position from the container's right-anchored alignment; no pill
// size is copied.
AnimatedContent(
targetState = state.open,
transitionSpec = {
(fadeIn(animationSpec = MotionStandard.spec()) togetherWith
fadeOut(animationSpec = MotionStandard.spec()))
.using(SizeTransform(clip = false) { _, _ -> MotionStandard.spec() })
},
contentAlignment = Alignment.CenterEnd,
label = "omni-search-morph",
) { open ->
if (open) {
OmniSearchField(
query = state.query,
onQueryChange = onQueryChange,
onFocusChange = onFocusChange,
onSubmit = onSubmitSearch,
onDismiss = onDismissSearch,
)
} else {
DestinationIcons(
destinations = destinations,
currentRoute = currentRoute,
onSelect = onSelect,
onOpenSearch = onOpenSearch,
)
}
}
}
}
/**
* The resting destination pill: the Pipelines/Runs/Settings destinations plus the
* omni-search entry point, each a [DESTINATION_ITEM_SIZE] touch target. Selection
* is one tonal indicator that travels between the icons ([MotionStandard], so it
* slides rather than jumping) plus the icon's fading tint, while the `Role.Tab`
* selected accessibility state is never conveyed by colour alone. Tapping a
* destination switches through the caller's existing navigate/popUpTo logic; the
* icons own the taps, so a tap registers even while the indicator is still
* travelling, and the settled pill equals the old one.
*
* The fourth control (Search) does not navigate: it is a plain [Role.Button]
* action that morphs this container into the search field.
*/
@Composable
private fun DestinationIcons(
destinations: List<TopDestination>,
currentRoute: String?,
onSelect: (TopDestination) -> Unit,
onOpenSearch: () -> Unit,
) {
val scheme = MaterialTheme.colorScheme
val selectedIndex = destinations.indexOfFirst { destinationSelected(currentRoute, it.route) }
// One long-lived animator, so a rapid run of taps only retargets it (never
// half-way) and the first composition starts already settled at the target.
val indicatorOffset by animateDpAsState(
targetValue = destinationIndicatorOffsetDp(
selectedIndex,
DESTINATION_ITEM_SIZE,
DESTINATION_ITEM_GAP,
),
animationSpec = MotionStandard.spec(),
label = "destination-indicator",
)
Box {
// Drawn behind the icons, so the highlight slides under whichever is
// selected; before the nav graph settles there is no selection and
// nothing is drawn.
if (selectedIndex >= 0) {
Box(
Modifier
.offset(x = indicatorOffset, y = DESTINATION_ITEM_GAP)
.size(DESTINATION_ITEM_SIZE)
.clip(CircleShape)
.background(scheme.secondaryContainer),
)
}
Row(
modifier = Modifier.padding(DESTINATION_ITEM_GAP),
horizontalArrangement = Arrangement.spacedBy(DESTINATION_ITEM_GAP),
verticalAlignment = Alignment.CenterVertically,
) {
destinations.forEach { destination ->
val selected = destinationSelected(currentRoute, destination.route)
// The glyph tint fades in step with the travelling indicator.
val iconColor by animateColorAsState(
targetValue = if (selected) scheme.onSecondaryContainer else scheme.onSurfaceVariant,
animationSpec = MotionStandard.spec(),
label = "destination-icon",
)
Box(
modifier = Modifier
.size(DESTINATION_ITEM_SIZE)
.clip(CircleShape)
.selectable(
selected = selected,
role = Role.Tab,
onClick = { onSelect(destination) },
),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = destination.icon,
contentDescription = destination.label,
tint = iconColor,
)
}
}
Box(
modifier = Modifier
.size(DESTINATION_ITEM_SIZE)
.clip(CircleShape)
.clickable(
role = Role.Button,
onClickLabel = "Search",
onClick = onOpenSearch,
),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = "Search",
tint = scheme.onSurfaceVariant,
)
}
}
}
}
/**
* The search field the pill morphs into: a single-line input focused as it opens
* (so the keyboard is up), a leading search glyph and a trailing close action. It
* reports focus changes into [OmniSearchState] and every keystroke to the caller,
* which debounces the query and drives the results panel above it.
*/
@Composable
private fun OmniSearchField(
query: String,
onQueryChange: (String) -> Unit,
onFocusChange: (Boolean) -> Unit,
onSubmit: () -> Unit,
onDismiss: () -> Unit,
) {
val scheme = MaterialTheme.colorScheme
val interaction = remember { MutableInteractionSource() }
val focused by interaction.collectIsFocusedAsState()
val focusRequester = remember { FocusRequester() }
LaunchedEffect(focused) { onFocusChange(focused) }
// Focus as the field opens so the keyboard is up; an open field restored after
// a process death re-focuses the same way.
LaunchedEffect(Unit) { focusRequester.requestFocus() }
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_M, vertical = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null,
tint = scheme.onSurfaceVariant,
)
BasicTextField(
value = query,
onValueChange = onQueryChange,
singleLine = true,
textStyle = MaterialTheme.typography.bodyLarge.copy(color = scheme.onSurface),
cursorBrush = SolidColor(scheme.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { onSubmit() }),
interactionSource = interaction,
modifier = Modifier
.weight(1f)
.padding(horizontal = SPACING_S)
.focusRequester(focusRequester),
decorationBox = { innerTextField ->
if (query.isEmpty()) {
Text(
text = "Search pipelines, runs and artifacts",
style = MaterialTheme.typography.bodyLarge,
color = scheme.onSurfaceVariant,
)
}
innerTextField()
},
)
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Close search")
}
}
}
/** The destination pill's icon touch target and the size of its selection indicator. */
internal val DESTINATION_ITEM_SIZE = 48.dp
/** The gap between destinations, also the pill's inner padding. */
internal val DESTINATION_ITEM_GAP = 4.dp
@@ -1,224 +0,0 @@
package net.awan.pipelines.ui
import java.time.Duration
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import net.awan.pipelines.data.protocol.FileChange
import net.awan.pipelines.data.protocol.NotificationReceipt
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageFileChanges
/**
* Parses an RFC3339 timestamp, or null when blank or unparseable. The single
* parser every time-reading the UI shares, so a bad timestamp is handled the
* same way everywhere.
*/
internal fun parseInstant(text: String): OffsetDateTime? {
if (text.isBlank()) return null
return runCatching { OffsetDateTime.parse(text) }.getOrNull()
}
/**
* Non-negative whole seconds between two RFC3339 timestamps, or null when either
* is blank/unparseable or the end precedes the start. The numeric counterpart of
* [formatDuration] (which delegates here), so a sort key and the printed
* duration can never disagree.
*/
internal fun durationSeconds(start: String, end: String): Long? {
val from = parseInstant(start) ?: return null
val to = parseInstant(end) ?: return null
return Duration.between(from, to).seconds.takeIf { it >= 0 }
}
/** Human duration between two RFC3339 timestamps, or null when unavailable. */
fun formatDuration(start: String, end: String): String? =
durationSeconds(start, end)?.let(::formatDuration)
/**
* Non-negative whole seconds from a [start] RFC3339 timestamp to [nowMillis]
* (wall-clock epoch millis), or null when [start] is blank/unparseable. Clamps a
* future/unparseable elapsed to 0 so a live timer never prints a negative or a
* nonsensical value. The one derivation behind the run graph's ticking elapsed
* time, so it is pure and testable without the Compose runtime.
*/
internal fun secondsSince(start: String, nowMillis: Long): Long? =
parseInstant(start)?.let { ((nowMillis - it.toInstant().toEpochMilli()) / 1000).coerceAtLeast(0) }
/**
* The time a run has taken so far: while it is still [executing], its live
* elapsed time from its server start timestamp to [nowMillis]; once it has
* finished, its stored total duration. The single rule the runs list's meta line,
* the pipeline last-run line and the run detail summary share, so the same run is
* never described differently in the three places. Null when the start (or, for a
* finished run, the end) is unusable, so the caller omits the value instead of
* printing a blank; a running run with a future start (clock skew) reads as `0s`,
* never a negative.
*/
internal fun runDurationText(
createdAt: String,
finishedAt: String,
executing: Boolean,
nowMillis: Long,
): String? =
if (executing) secondsSince(createdAt, nowMillis)?.let(::formatDuration)
else formatDuration(createdAt, finishedAt)
/**
* Human duration for a whole number of seconds. The single formatting rule for
* every duration the UI shows (list meta, usage average, run summary, step
* duration); the timestamp overload above delegates here so the two never drift.
* A negative total is rendered as "0s" so a caller with a clamped/rounded
* average never prints a negative duration.
*/
fun formatDuration(totalSeconds: Long): String {
val seconds = totalSeconds.coerceAtLeast(0)
return when {
seconds < 60 -> "${seconds}s"
seconds < 3600 -> "${seconds / 60}m ${seconds % 60}s"
else -> "${seconds / 3600}h ${(seconds % 3600) / 60}m"
}
}
/**
* An RFC3339 timestamp as the app's one human, local rendering (`d MMM HH:mm`,
* e.g. `17 Oct 21:26`), or null when blank/unparseable so a caller omits the
* value rather than printing a blank. The runs list's own start line uses it, and
* the pipeline list, versions and every detail share it, so no surface prints the
* server's raw ISO string and the same instant never reads two ways.
*/
fun formatLocalTimestamp(instant: String): String? {
val parsed = parseInstant(instant) ?: return null
return parsed.atZoneSameInstant(ZoneId.systemDefault()).format(LOCAL_TIMESTAMP_FORMAT)
}
private val LOCAL_TIMESTAMP_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm")
/**
* A stage count in the app's one singular/plural spelling (`1 stage` /
* `n stages`), shared by the pipeline list, the pipeline detail and the template
* detail so a single-stage pipeline never reads "1 stages".
*/
fun stageCountText(count: Int): String = "$count ${if (count == 1) "stage" else "stages"}"
/** 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()
/**
* A run's step count in the server's own vocabulary, mirroring
* internal/tui/results.go ("%d completed visits") and internal/tui/run_graph.go
* ("%d recorded visits"), with a singular form for a single visit. The runs list
* and run detail share this so the same run is never described inconsistently.
*/
fun visitCount(count: Int, adjective: String): String =
"$count $adjective ${if (count == 1) "visit" else "visits"}"
/**
* One changed-file line, e.g. `modified src/a.kt (binary) (truncated)`. The
* single spelling used by the stage detail sheet and the run steps timeline.
*/
fun fileChangeLine(file: FileChange): String =
"${file.kind} ${file.path}" +
(if (file.binary) " (binary)" else "") +
(if (file.truncated) " (truncated)" else "")
/** One notification receipt, e.g. `delivered → ntfy · ok`, skipping a blank diagnostic. */
fun notificationLine(receipt: NotificationReceipt): String =
"${receipt.status} → ${receipt.destination}" +
(receipt.diagnostic?.takeIf { it.isNotBlank() }?.let { " · $it" } ?: "")
/**
* A compact file-change summary, e.g. `success (3 files), 1 skipped`. Blank parts
* (missing status, no files, nothing skipped) are omitted so no dangling label is
* ever emitted; an entirely blank change set renders as "".
*/
fun fileChangesSummary(changes: StageFileChanges): String = buildString {
if (changes.status.isNotBlank()) append(changes.status)
if (changes.files.isNotEmpty()) {
if (isNotEmpty()) append(" ")
append("(${changes.files.size} files)")
}
if (changes.skipped > 0) {
if (isNotEmpty()) append(", ")
append("${changes.skipped} skipped")
}
}
/**
* Human-readable byte size, matching internal/tui/file_changes.go humanBytes
* exactly: whole bytes under 1 KiB, otherwise one decimal with a binary unit
* (KiB/MiB/GiB/TiB/PiB/EiB). The single formatter for every size the UI shows.
*/
fun humanBytes(size: Long): String {
val unit = 1024L
if (size < unit) return "$size B"
var div = unit
var exp = 0
var value = size / unit
while (value >= unit) {
div *= unit
exp++
value /= unit
}
return String.format(java.util.Locale.US, "%.1f %ciB", size.toDouble() / div.toDouble(), "KMGTPE"[exp])
}
/** Whether an artifact's content type is an image the sheet can preview. */
fun isImageContentType(contentType: String): Boolean = contentType.startsWith("image/")
/**
* Whether an artifact's content type is a video. Videos are shown in the gallery
* as a still/poster frame with a play marker; they are never decoded inline.
*/
fun isVideoContentType(contentType: String): Boolean = contentType.startsWith("video/")
/**
* The "capture pending" wording shared by a running visit's summary and the
* run-level empty state, so the two never spell it differently.
*/
const val ARTIFACT_CAPTURE_PENDING = "capture pending"
/**
* The artifacts summary label, mirroring internal/tui/file_changes.go
* artifactsSummary: "capture pending" while the visit runs, "not recorded for
* this visit" for a finished visit with no artifacts, otherwise the recorded
* count plus " · partial capture" when files were excluded or omitted.
*/
fun artifactsSummary(step: RunStep): String {
val artifacts = presentedArtifacts(step)
if (artifacts.isEmpty()) {
val state = if (step.status == "running") {
ARTIFACT_CAPTURE_PENDING
} else {
"not recorded for this visit"
}
return "Artifacts · $state"
}
var label = "Artifacts · ${artifacts.size} recorded"
if (step.artifactsSkipped > 0 || step.artifactsTruncated > 0) label += " · partial capture"
return label
}
/**
* The partial-capture notes, mirroring internal/tui/file_changes.go artifactLines:
* one line per non-zero count, and nothing when the capture was complete. An
* empty artifact list yields no notes at all (the TUI returns nothing for it), so
* the notes never accompany the empty-state summary.
*/
fun artifactCaptureNotes(step: RunStep): List<String> = buildList {
if (presentedArtifacts(step).isEmpty()) return@buildList
if (step.artifactsSkipped > 0) add("${step.artifactsSkipped} files excluded from artifact capture.")
if (step.artifactsTruncated > 0) add("${step.artifactsTruncated} files omitted by artifact capture limits.")
}
@@ -1,67 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.runtime.saveable.Saver
/**
* The floating bottom container's two surfaces: the destination icons (the
* pill) and the omni-search field it morphs into. [open] is that morph;
* [focused] records whether the field owns the keyboard's focus; [query] is the
* typed text.
*
* Opening and dismissing deliberately change nothing else, so the destination
* the pill had selected is untouched by a search: the nav route is owned
* elsewhere and never navigated away from here, so the reverse morph restores
* exactly the pill that was on screen.
*/
data class OmniSearchState(
val open: Boolean = false,
val focused: Boolean = false,
val query: String = "",
) {
companion object {
/** The resting pill: no field, no text. */
val Closed = OmniSearchState()
}
}
/** Tapping the Search icon opens the field and asks for focus (keyboard up). */
fun openOmniSearch(state: OmniSearchState): OmniSearchState =
state.copy(open = true, focused = true)
/**
* Dismissing (Back, the back gesture or a scrim tap) plays the reverse and
* returns to the resting pill, clearing the text so the next open starts fresh.
*/
fun dismissOmniSearch(state: OmniSearchState): OmniSearchState = OmniSearchState.Closed
/** The field gained ([focused] true) or lost the focus; [open] is unchanged. */
fun setOmniSearchFocus(state: OmniSearchState, focused: Boolean): OmniSearchState =
state.copy(focused = focused)
/** Records the typed query; [open] and [focused] are unchanged. */
fun setOmniSearchQuery(state: OmniSearchState, query: String): OmniSearchState =
state.copy(query = query)
/**
* Encodes an [OmniSearchState] as Bundle-able primitives (a small `List<Any>`),
* so a still-open field survives rotation, configuration change and process
* death. Paired with [decodeOmniSearch].
*/
internal fun encodeOmniSearch(state: OmniSearchState): List<Any> =
listOf(state.open, state.focused, state.query)
/** Restores an [OmniSearchState] encoded by [encodeOmniSearch]. */
internal fun decodeOmniSearch(encoded: List<Any>): OmniSearchState = OmniSearchState(
open = encoded[0] as Boolean,
focused = encoded[1] as Boolean,
query = encoded[2] as String,
)
/**
* Saves/restores an [OmniSearchState] across configuration change and process
* death. The payload is primitives only (see [encodeOmniSearch]).
*/
val OmniSearchStateSaver: Saver<OmniSearchState, List<Any>> = Saver(
save = { encodeOmniSearch(it) },
restore = { decodeOmniSearch(it) },
)
@@ -1,421 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.automirrored.filled.Segment
import androidx.compose.material.icons.automirrored.filled.Subject
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Commit
import androidx.compose.material.icons.filled.History
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.vector.ImageVector
import java.time.OffsetDateTime
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.SearchArtifact
import net.awan.pipelines.data.protocol.SearchField
import net.awan.pipelines.data.protocol.SearchPipeline
import net.awan.pipelines.data.protocol.SearchResponse
import net.awan.pipelines.data.protocol.SearchResult
import net.awan.pipelines.data.protocol.SearchRun
import net.awan.pipelines.data.protocol.SearchStep
import net.awan.pipelines.data.protocol.SearchVersion
import net.awan.pipelines.ui.graph.artifactIcon
import net.awan.pipelines.ui.graph.artifactKind
import net.awan.pipelines.ui.graph.artifactKindLabel
import net.awan.pipelines.ui.screens.runTimeline
// ---------------------------------------------------------------------------
// Row model: the glyph, title and secondary line of one result. Pure (no
// Compose, no coroutines), so the mapping for every kind is unit-testable.
// ---------------------------------------------------------------------------
/**
* The glyph that names one result's type at a glance: the result's kind, and for
* an artifact the file type its content resolves to. The artifact mapping is the
* gallery's own ([artifactKind]/[artifactIcon]) rather than a second copy, so the
* two surfaces can never disagree about a file. The payload decides the branch,
* exactly as [searchRow] does, so a known payload with an unknown kind string
* still gets the right glyph and an unrecognised result falls back to a neutral
* mark instead of vanishing.
*/
fun searchResultIcon(hit: SearchResult): ImageVector = when {
hit.pipeline != null -> Icons.Filled.AccountTree
hit.version != null -> Icons.Filled.Commit
hit.run != null -> Icons.Filled.History
hit.step != null -> Icons.AutoMirrored.Filled.Segment
hit.field != null -> Icons.AutoMirrored.Filled.Subject
hit.artifact != null -> artifactIcon(artifactKind(hit.artifact.contentType, hit.artifact.name))
else -> Icons.AutoMirrored.Filled.HelpOutline
}
/**
* The kind in words for a row's accessible description, so a screen reader hears
* what the row is even though the glyph alone carries no text. An artifact is
* named by its own content type ("Image artifact", "JSON artifact"), from the
* same gallery classification [searchResultIcon] uses.
*/
fun searchResultKindLabel(hit: SearchResult): String = when {
hit.pipeline != null -> "Pipeline"
hit.version != null -> "Pipeline version"
hit.run != null -> "Run"
hit.step != null -> "Step"
hit.field != null -> "Field"
hit.artifact != null ->
"${artifactKindLabel(artifactKind(hit.artifact.contentType, hit.artifact.name))} artifact"
else -> "Unrecognised result"
}
/**
* One run of snippet text with [matched] true for the span the query hit. The row
* renders a matched span with a weight/underline difference, so the match stays
* legible without relying on colour.
*/
@Immutable
data class SnippetSpan(val text: String, val matched: Boolean)
/**
* One rendered search row: its title and a secondary line. [snippet] is non-null
* only for a text ("field") match and carries the snippet split so the matched
* span is distinguishable without colour.
*/
@Immutable
data class SearchRow(
val title: String,
val secondary: String,
val snippet: List<SnippetSpan>? = null,
)
/**
* The row for one [hit]. [query] is the typed text, used only to locate the
* matched span in a text snippet. An unknown/absent payload is never dropped: it
* renders its stable target (or a placeholder) and a `read-only` note.
*/
fun searchRow(hit: SearchResult, query: String): SearchRow {
val pipeline: SearchPipeline? = hit.pipeline
val version: SearchVersion? = hit.version
val run: SearchRun? = hit.run
val step: SearchStep? = hit.step
val field: SearchField? = hit.field
val artifact: SearchArtifact? = hit.artifact
return when {
pipeline != null -> SearchRow(
pipeline.name.ifBlank { "pipeline ${pipeline.id}" },
"pipeline ${pipeline.id} · v${pipeline.version} · ${stageCountText(pipeline.stages)}",
)
version != null -> SearchRow(
"pipeline ${version.pipelineId} · v${version.version}",
listOfNotNull(
version.contentHash.takeIf { it.isNotBlank() }?.let { "content $it" },
formatLocalTimestamp(version.createdAt),
).joinToString(" · "),
)
run != null -> SearchRow(
"run #${run.id}" + run.pipelineName.takeIf { it.isNotBlank() }?.let { " · $it" }.orEmpty(),
listOfNotNull(
run.status.takeIf { it.isNotBlank() },
run.workspace?.takeIf { it.isNotBlank() },
formatLocalTimestamp(run.createdAt),
).joinToString(" · "),
)
step != null -> SearchRow(
"run #${step.runId} · ${step.stage.ifBlank { "step" }} visit ${step.visit}",
stepSecondary(step),
)
field != null -> SearchRow(
"run #${field.runId} · step ${field.sequence} · ${field.field.ifBlank { "field" }}",
field.snippet,
snippetSpans(field.snippet, query),
)
artifact != null -> SearchRow(
artifact.name.ifBlank { "artifact" },
listOfNotNull(
"run #${artifact.runId}",
"step ${artifact.sequence}",
artifact.contentType.takeIf { it.isNotBlank() },
humanBytes(artifact.sizeBytes),
).joinToString(" · "),
)
else -> SearchRow(
hit.target.ifBlank { "Unrecognised result" },
if (hit.kind.isBlank()) "read-only" else "kind \"${hit.kind}\" · read-only",
)
}
}
/** The one-line non-snippet summary of a step hit: its outcome, route and first diagnostic line. */
private fun stepSecondary(step: SearchStep): String {
val parts = listOfNotNull(
step.outcome?.takeIf { it.isNotBlank() },
step.target?.takeIf { it.isNotBlank() }?.let { "→ $it" },
step.diagnostic?.lineSequence()?.firstOrNull { it.isNotBlank() }?.trim()?.takeIf { it.isNotBlank() },
)
return parts.joinToString(" · ").ifBlank { "step ${step.sequence}" }
}
/**
* Splits [snippet] into runs so the first case-insensitive occurrence of [query]
* is a distinct, [SnippetSpan.matched] span. When the query is blank or does not
* appear (a bare status/date query, or a server-trimmed snippet), the whole
* snippet is returned unmatched, so the caller never drops text.
*/
fun snippetSpans(snippet: String, query: String): List<SnippetSpan> {
if (snippet.isEmpty()) return emptyList()
val trimmed = query.trim()
if (trimmed.isEmpty()) return listOf(SnippetSpan(snippet, false))
val index = snippet.indexOf(trimmed, ignoreCase = true)
if (index < 0) return listOf(SnippetSpan(snippet, false))
val end = index + trimmed.length
return buildList {
if (index > 0) add(SnippetSpan(snippet.substring(0, index), false))
add(SnippetSpan(snippet.substring(index, end), true))
if (end < snippet.length) add(SnippetSpan(snippet.substring(end), false))
}
}
// ---------------------------------------------------------------------------
// Narrowing and ordering: the filter/sort control's pure model. Pure (no
// Compose), so the kind narrowing and each order are unit-testable.
// ---------------------------------------------------------------------------
/**
* The kind narrowing the search filter control offers. [serverKind] is exactly the
* server's SearchRequest kind vocabulary (internal/protocol/search.go), sent and
* stored verbatim; [All] is the empty kind.
*
* There is deliberately no "prompts" entry: the server has no such kind (its
* kinds are pipeline, version, run, step, field and artifact), so a filter that
* could only ever match nothing is not offered.
*/
enum class SearchKindFilter(val label: String, val serverKind: String) {
All("All kinds", ""),
Pipelines("Pipelines", Protocol.SEARCH_KIND_PIPELINE),
Runs("Runs", Protocol.SEARCH_KIND_RUN),
Steps("Steps", Protocol.SEARCH_KIND_STEP),
Fields("Fields", Protocol.SEARCH_KIND_FIELD),
Artifacts("Artifacts", Protocol.SEARCH_KIND_ARTIFACT),
Versions("Versions", Protocol.SEARCH_KIND_VERSION);
companion object {
val Default = All
/** Resolves a stored kind, tolerating a blank/stale value by returning [Default]. */
fun fromStorage(value: String?): SearchKindFilter =
entries.firstOrNull { it.serverKind == value } ?: Default
}
}
/**
* The orders the search sort control offers. [Relevance] keeps the server's own
* ranking (score, then recency, then a stable kind/target tie-break). [Newest]
* and [Name] cannot be asked of the server - its search command takes only a
* query, an optional kind and a limit - so they order the results already in
* hand, and the control says so.
*/
enum class SearchSort(val label: String, val storageKey: String) {
Relevance("Relevance", "relevance"),
Newest("Newest first", "newest"),
Name("Name", "name");
companion object {
val Default = Relevance
/** Resolves a stored order, tolerating a blank/stale value by returning [Default]. */
fun fromStorage(value: String?): SearchSort =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/** The one-line summary of the active filter and sort the collapsed control shows. */
fun searchControlsSummary(kind: SearchKindFilter, sort: SearchSort): String {
// Only Relevance is the server's own ranking; the other orders run on the
// results in hand, so the summary says so even when the menu is closed.
val reach = if (sort == SearchSort.Relevance) "" else " (in hand)"
return "${kind.label} · ${sort.label}$reach"
}
/**
* Narrows [results] to [filter]'s kind. The filter is also sent to the server
* (SearchRequest.kind), so this only re-narrows the results already in hand,
* keeping the panel honest while a narrowed request loads.
*/
fun filterSearchResults(results: List<SearchResult>, filter: SearchKindFilter): List<SearchResult> =
if (filter == SearchKindFilter.All) results else results.filter { it.kind == filter.serverKind }
/**
* Orders [results] by [sort]. [Relevance] leaves the server's ranking untouched;
* [Newest] and [Name] sort the results in hand (the server has no sort). The
* sorts are stable, so two results that tie keep the server's order rather than
* swapping arbitrarily.
*/
fun sortSearchResults(results: List<SearchResult>, sort: SearchSort): List<SearchResult> = when (sort) {
SearchSort.Relevance -> results
SearchSort.Newest -> results.sortedWith(
compareByDescending<SearchResult> { parseInstant(it.recency.orEmpty()) ?: OffsetDateTime.MIN },
)
SearchSort.Name -> results
.map { it to searchRow(it, "").title }
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.second })
.map { it.first }
}
// ---------------------------------------------------------------------------
// Navigation: the destination a result resolves to. Pure, so the mapping for
// every kind is unit-testable.
// ---------------------------------------------------------------------------
/**
* The navigation a selected search result asks for. A null target (see
* [searchTarget]) means the result is shown read-only and selecting it does
* nothing.
*/
sealed interface SearchTarget {
/** Open the Pipelines destination at this pipeline's detail (version 0 = latest). */
data class Pipeline(val pipelineId: Long, val version: Int) : SearchTarget
/**
* Open the Runs destination at this run. [sequence] > 0 opens the recorded
* visit's stage pane, whose fixed section order leads with the visit's
* artifacts, so an artifact and a step hit resolve the same way. [field] names
* the run-detail section holding a matched text field for a text match.
*/
data class Run(
val runId: Long,
val sequence: Int = 0,
val field: String = "",
) : SearchTarget
}
/**
* The navigation target for [hit], or null for a kind with no known payload (an
* unknown match), which is shown read-only rather than dropped.
*/
fun searchTarget(hit: SearchResult): SearchTarget? = when {
hit.pipeline != null -> SearchTarget.Pipeline(hit.pipeline.id, hit.pipeline.version)
hit.version != null -> SearchTarget.Pipeline(hit.version.pipelineId, hit.version.version)
hit.run != null -> SearchTarget.Run(hit.run.id)
hit.step != null -> SearchTarget.Run(hit.step.runId, hit.step.sequence)
hit.field != null -> SearchTarget.Run(hit.field.runId, hit.field.sequence, field = hit.field.field)
hit.artifact != null -> SearchTarget.Run(hit.artifact.runId, hit.artifact.sequence)
else -> null
}
/** The run-detail tab holding a matched step field's text (see `runDetailTabs`). */
fun searchFieldSection(field: String): Int = when (field) {
"input" -> 2
"output" -> 3
// Evidence was a retired run-detail tab. Keep old search hits safe by
// opening Summary rather than accidentally selecting Timeline.
"evidence", "transcript" -> 0
else -> 0
}
/**
* Resolves a [SearchTarget.Run] against the loaded run's [steps] into the pane
* selection showing the requested visit/section. A visit that cannot be located
* (or a bare run target) falls back to the run detail itself, so a hit is never
* dropped. [runId] is the run the target named.
*/
fun resolveRunTarget(target: SearchTarget.Run, runId: Long, steps: List<RunStep>): PaneSelection {
// A text match names a section (tab) directly; the matched field's own text
// lives in the run-detail section with that name.
if (target.field.isNotBlank()) {
return PaneSelection(MasterPane.Detail, runId, sectionIndex = searchFieldSection(target.field))
}
if (target.sequence <= 0) return PaneSelection(MasterPane.Detail, runId)
val step = steps.firstOrNull { it.sequence == target.sequence }
?: return PaneSelection(MasterPane.Detail, runId)
// The visit's stage pane, with the correct zero-based visit index for that
// stage (the server's visit number need not equal the index).
val visits = runTimeline(steps).visitsByStage[step.stage].orEmpty()
val visitIndex = visits.indexOfFirst { it.sequence == target.sequence }.coerceAtLeast(0)
return PaneSelection(
pane = MasterPane.Stage,
itemId = runId,
stageKey = step.stage,
stageVisit = visitIndex,
)
}
// ---------------------------------------------------------------------------
// Query sequencing: debounce + stale-response gating. Pure (no coroutines and
// no clock) so a keystroke burst and an out-of-order reply are unit-testable.
// ---------------------------------------------------------------------------
/** One typed query awaiting its debounce window. */
data class SearchEdit(val token: Long, val query: String)
/** A query whose debounce elapsed and which is still the newest edit. */
data class SentSearch(val token: Long, val query: String)
/**
* The pure ordering behind omni-search.
*
* [edit] records a keystroke and returns the pending edit to debounce; when the
* quiet period elapses the caller passes it to [begin], which returns the query
* to send only if no newer keystroke arrived — so a burst of keystrokes collapses
* into one request for the last one. Every sent request carries a monotonically
* increasing token and [accepts] is true only for the newest sent token, so a
* slower older reply can never overwrite a newer one.
*/
class SearchSequencer {
private var edits = 0L
private var newestSent = 0L
fun edit(query: String): SearchEdit = SearchEdit(++edits, query)
fun begin(edit: SearchEdit): SentSearch? {
if (edit.token != edits) return null
newestSent = edit.token
return SentSearch(edit.token, edit.query)
}
fun accepts(token: Long): Boolean = token == newestSent
}
/** The omni-search panel state; the previous results stay put while a new query loads. */
@Immutable
data class SearchUiState(
val query: String = "",
val results: List<SearchResult> = emptyList(),
val loading: Boolean = false,
val error: String? = null,
val loaded: Boolean = false,
)
/** A keystroke: keep the previous results (no flicker to empty) and mark a request in flight. */
fun SearchUiState.editing(query: String): SearchUiState =
copy(query = query, loading = query.isNotBlank(), error = null, loaded = false)
/** A reply landed: replace the results and stop loading. */
fun SearchUiState.loaded(response: SearchResponse): SearchUiState =
copy(results = response.results, loading = false, error = null, loaded = true)
/**
* A load failed: stop loading and record the reason. The previous results are
* kept in the state (the panel shows the error in their place until the error
* clears), so a later successful reply never has to re-fetch what was already
* shown.
*/
fun SearchUiState.failed(message: String?): SearchUiState =
copy(loading = false, error = message, loaded = true)
/**
* The empty-state line the panel shows when it has no rows to render for [query]
* under [kind], or null when it is showing rows, progress or nothing at all.
* [shown] is the filtered and sorted list actually displayed, so a filter that
* empties the list reports itself ("No runs match …") rather than the generic
* line. Pure, so the empty state is unit-testable without a device.
*/
fun searchPanelEmptyMessage(
state: SearchUiState,
shown: List<SearchResult>,
kind: SearchKindFilter,
): String? = when {
state.error != null -> null
shown.isNotEmpty() -> null
state.loading -> null
state.query.isBlank() -> null
kind == SearchKindFilter.All -> "No matches for \"${state.query}\"."
else -> "No ${kind.label.lowercase()} match \"${state.query}\"."
}
@@ -1,132 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.runtime.saveable.Saver
/**
* Which pane of the sliding stack is showing: the list (level 0), the selected
* item's detail (level 1), the stage/node pane (level 2) and, when a stage
* section is opened, that section's pane (level 3). On a wide window the panes
* stack left to right and share a fixed peek budget; on a narrow window only the
* topmost pane is visible and it fills the window.
*/
enum class MasterPane { List, Detail, Stage, Section }
/**
* The declared bound on the stack: list (0), detail (1), stage (2), section (3).
* The stack can never grow deeper than this; selecting a different stage, list
* item or section replaces the rightmost pane instead of pushing a new level.
*/
const val MAX_PANE_DEPTH = 3
/**
* The saved pane-stack selection: which pane is rightmost, which item (0 = none),
* its pipeline/run version, which detail section (page) is showing and its
* stable tab key, which stage/visit the stage pane is on and, when a stage
* section is open, its key.
* Every field is a primitive, so the state round-trips through a Bundle cheaply
* and survives rotation, configuration change and process death.
*
* Geometry (peek width, insets, measured pane widths) is deliberately *not* part
* of this model; it is derived from layout so nothing is hardcoded here.
*/
data class PaneSelection(
val pane: MasterPane = MasterPane.List,
val itemId: Long = 0L,
val itemVersion: Int = 0,
val sectionIndex: Int = 0,
val stageKey: String? = null,
val stageVisit: Int = 0,
val sectionKey: String? = null,
val detailTabKey: String? = null,
) {
/** How many panes are stacked: 0 list, 1 detail, 2 stage, 3 section. */
val depth: Int
get() = when (pane) {
MasterPane.List -> 0
MasterPane.Detail -> 1
MasterPane.Stage -> 2
MasterPane.Section -> 3
}
}
/** The result of one Back step: show a new selection, or leave the app. */
sealed interface BackResult {
/** The list is showing, so Back leaves the app (no pane to close). */
data object Exit : BackResult
/** Show [selection] (exactly one pane level back). */
data class Show(val selection: PaneSelection) : BackResult
}
/**
* Exactly one pane level of Back. Inside a stage section it steps back to the
* stage pane; inside the stage pane it steps back to the detail; inside the
* detail it steps back to the list; at the list it leaves the app. The peek tap
* and the Back button/gesture therefore always pop the same single level.
*/
fun backStep(selection: PaneSelection): BackResult = when (selection.pane) {
MasterPane.List -> BackResult.Exit
MasterPane.Detail -> BackResult.Show(PaneSelection(pane = MasterPane.List))
MasterPane.Stage -> BackResult.Show(
selection.copy(pane = MasterPane.Detail, stageKey = null, stageVisit = 0, sectionKey = null),
)
MasterPane.Section -> BackResult.Show(
selection.copy(pane = MasterPane.Stage, sectionKey = null),
)
}
/**
* The selection after tapping the peek of the pane at [level]: every pane to its
* right is closed. Level 0 (the list) shows a bare list; level 1 shows the same
* item's detail with no stage; level 2 shows the same item's stage with no
* section; a [level] at or beyond the current depth is a no-op (there is nothing
* to its right). Peeks exist only on a wide window; narrow windows use
* Back/gesture for the same one-level step.
*/
fun popTo(selection: PaneSelection, level: Int): PaneSelection = when {
level <= 0 -> PaneSelection()
level == 1 -> selection.copy(
pane = MasterPane.Detail,
stageKey = null,
stageVisit = 0,
sectionKey = null,
)
level == 2 -> selection.copy(pane = MasterPane.Stage, sectionKey = null)
else -> selection
}
/**
* Encodes a [PaneSelection] as Bundle-able primitives (a small `List<Any>`), so
* the saved state stays tiny. Paired with [decodePaneSelection].
*/
internal fun encodePaneSelection(selection: PaneSelection): List<Any> = listOf(
selection.pane.name,
selection.itemId,
selection.itemVersion,
selection.sectionIndex,
selection.stageKey ?: "",
selection.stageVisit,
selection.sectionKey ?: "",
selection.detailTabKey ?: "",
)
/** Restores a [PaneSelection] encoded by [encodePaneSelection]. */
internal fun decodePaneSelection(encoded: List<Any>): PaneSelection = PaneSelection(
pane = MasterPane.valueOf(encoded[0] as String),
itemId = encoded[1] as Long,
itemVersion = encoded[2] as Int,
sectionIndex = encoded[3] as Int,
stageKey = (encoded[4] as String).takeIf { it.isNotEmpty() },
stageVisit = encoded[5] as Int,
sectionKey = (encoded[6] as String).takeIf { it.isNotEmpty() },
detailTabKey = encoded.getOrNull(7)?.let { it as String }?.takeIf { it.isNotEmpty() },
)
/**
* Saves/restores a [PaneSelection] across configuration change and process
* death. The save payload is primitives only (see [encodePaneSelection]).
*/
val PaneSelectionSaver: Saver<PaneSelection, List<Any>> = Saver(
save = { encodePaneSelection(it) },
restore = { decodePaneSelection(it) },
)
@@ -1,148 +0,0 @@
package net.awan.pipelines.ui
import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import kotlinx.coroutines.flow.collect
import net.awan.pipelines.ui.components.SlidingPaneStack
import net.awan.pipelines.ui.components.clampTabIndex
import net.awan.pipelines.ui.components.pipelineDetailTabs
import net.awan.pipelines.ui.components.rememberPaneContent
import net.awan.pipelines.ui.graph.PipelineStagePane
import net.awan.pipelines.ui.screens.PipelineDetailScreen
import net.awan.pipelines.ui.screens.PipelineListScreen
/**
* The Pipelines destination: one sliding pane stack whose pane 0 is the pipeline
* list, pane 1 is the selected pipeline (Summary/Graph/Source) and pane 2 is the
* stage pane for a graph node. The saved [PaneSelection] survives rotation,
* configuration change and process death. Back (gesture/button) and the nearest
* peek tap both step back exactly one level via [backFrom]; tapping a lower peek
* closes every pane to its right via [popTo].
*/
@Composable
internal fun PipelineDestination(
vm: AppViewModel,
wide: Boolean,
selection: PaneSelection,
onSelectionChange: (PaneSelection) -> Unit,
listState: LazyListState,
onOpenRun: (Long) -> Unit,
attention: List<AttentionEntry>,
onOpenAttention: () -> Unit,
) {
val depth = selection.depth
val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) }
PredictiveBackHandler(enabled = depth >= 1) { progress ->
// Consume the gesture; on completion perform exactly one Back step.
progress.collect { }
onBack()
}
SlidingPaneStack(
depth = depth,
wide = wide,
onPopTo = { level -> onSelectionChange(popTo(selection, level)) },
compactLabel = "Pipelines",
compactIcon = Icons.Filled.AccountTree,
// Every covered pane in this stack (the list, or a pipeline's detail) carries
// a statistics block, so the region is sized for it and a single covered
// pane can show the last-run and average lines rather than only counts.
compactStats = true,
backContentDescription = { level ->
when (level) {
0 -> "Back to pipelines"
1 -> "Back to pipeline"
else -> "Back to stage"
}
},
pane = { level, covered, paneModifier ->
when (level) {
0 -> PipelineListScreen(
vm = vm,
onOpen = { id, version ->
onSelectionChange(PaneSelection(MasterPane.Detail, id, version))
},
modifier = paneModifier,
selectedId = selection.itemId.takeIf { depth >= 1 },
covered = covered,
wide = wide,
listState = listState,
attention = attention,
onOpenAttention = onOpenAttention,
)
1 -> rememberPaneContent(
selection.itemId.takeIf { it != 0L }?.let {
Triple(it, selection.itemVersion, selection.sectionIndex)
},
)?.let { (itemId, version, sectionIndex) ->
PipelineDetailScreen(
vm = vm,
pipelineId = itemId,
version = version,
onBack = onBack,
onOpenRun = onOpenRun,
selectedSection = clampTabIndex(sectionIndex, pipelineDetailTabs.size),
onSelectSection = { onSelectionChange(selection.copy(sectionIndex = it)) },
modifier = paneModifier,
wide = wide,
onOpenStage = { key ->
onSelectionChange(
selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = 0),
)
},
covered = covered,
attention = attention,
onOpenAttention = onOpenAttention,
)
}
2 -> rememberPaneContent(
selection.stageKey?.let {
Triple(selection.itemId, selection.itemVersion, it)
},
)?.let { (itemId, version, key) ->
PipelineStagePane(
vm = vm,
pipelineId = itemId,
version = version,
stageKey = key,
openSection = null,
onOpenSection = { sectionKey ->
onSelectionChange(
selection.copy(pane = MasterPane.Section, sectionKey = sectionKey),
)
},
onBack = onBack,
wide = wide,
modifier = paneModifier,
covered = covered,
)
}
3 -> rememberPaneContent(
selection.sectionKey?.let {
Triple(selection.itemId, it, selection.stageKey)
},
)?.let { (itemId, sectionKey, key) ->
// A closing section pane keeps the identity that opened it, so
// it renders its content until it is fully off-screen.
PipelineStagePane(
vm = vm,
pipelineId = itemId,
version = selection.itemVersion,
stageKey = key.orEmpty(),
openSection = sectionKey,
onOpenSection = {},
onBack = onBack,
wide = wide,
modifier = paneModifier,
covered = covered,
)
}
}
},
)
}
@@ -1,587 +0,0 @@
package net.awan.pipelines.ui
import android.Manifest
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Chat
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import net.awan.pipelines.data.protocol.SearchResult
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.notify.NOTIFICATION_RATIONALE
import net.awan.pipelines.notify.alertPermissionPrompt
import net.awan.pipelines.ui.chat.ChatScreen
import net.awan.pipelines.ui.components.AttentionSheet
import net.awan.pipelines.ui.components.BottomStripInset
import net.awan.pipelines.ui.components.ConnectionBanner
import net.awan.pipelines.ui.components.LocalBottomStripInset
import net.awan.pipelines.ui.components.LocalPillBottomInset
import net.awan.pipelines.ui.components.MotionStandard
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.spec
import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
import net.awan.pipelines.ui.theme.SPACING_L
/** One destination the floating pill holds: its nav [route], the accessible [label] and its glyph. */
internal data class TopDestination(val route: String, val label: String, val icon: ImageVector)
/**
* The pill's destinations, in display order. Templates is deliberately absent: it
* is configuration, reached from the Settings page instead, so the pill holds only
* the surfaces a person moves between constantly. The pill's width derives from
* this list (its icon row), never a fixed value, so removing a destination only
* narrows it.
*/
internal val destinations = listOf(
TopDestination(PIPELINES_ROUTE, "Pipelines", Icons.Default.AccountTree),
TopDestination("runs", "Runs", Icons.Default.History),
TopDestination("chat", "Chat", Icons.AutoMirrored.Filled.Chat),
TopDestination("settings", "Settings", Icons.Default.Settings),
)
/** The home route remains beneath top-level navigation, so Back returns to Runs. */
internal const val HOME_ROUTE = "runs"
/** Returning to home clears the accumulated top-level stack; other destinations keep it. */
internal fun topLevelPopUpToHomeInclusive(destination: String): Boolean =
destination == HOME_ROUTE
/**
* Whether [route] is the current destination. Detail panes are no longer
* separate routes (they are saved state inside a destination), so this is a
* plain equality check.
*/
internal fun destinationSelected(currentRoute: String?, route: String): Boolean =
currentRoute == route
/**
* One Back step as a selection update. The peek tap, the detail's top-bar back
* button and the system Back button/gesture all call through here, so a section
* never disagrees with the pane.
*/
internal fun backFrom(selection: PaneSelection): PaneSelection =
when (val result = backStep(selection)) {
is BackResult.Show -> result.selection
BackResult.Exit -> selection
}
@Composable
fun PipelinesApp(
vm: AppViewModel,
initialRunId: Long? = null,
initialRunAction: String? = null,
onInitialRunHandled: () -> Unit = {},
) {
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()
// The ordered list of runs that need the operator, derived from the same
// pushed run state the rest of the app folds, so it is live with no refresh.
val attention by vm.attention.collectAsStateWithLifecycle()
// Window-size driven (never a hardcoded device): the same sliding pane works at
// every width; only the section index presentation (tab row vs rail) changes.
val wide = isWideLayout(LocalConfiguration.current.screenWidthDp)
// The Pipelines and Runs destinations' selections are hoisted here so a search
// result can open either one (and the Pipelines detail can jump to a freshly
// started run). There is no longer a run/route to navigate to.
var pipelineSelection by rememberSaveable(stateSaver = PaneSelectionSaver) {
mutableStateOf(PaneSelection())
}
var runSelection by rememberSaveable(stateSaver = PaneSelectionSaver) {
mutableStateOf(PaneSelection())
}
// A run search hit that names a recorded visit cannot be resolved until the
// run's steps are loaded; the Runs destination applies it then (see below).
var runSearchNav by remember { mutableStateOf<SearchTarget.Run?>(null) }
// A waiting run's decision sheet to open once its detail has loaded. Set by a
// notification's `decide` deep link (the tap lands on the decision, not just
// the run), cleared by the detail once it has opened the sheet.
var decisionRequest by rememberSaveable { mutableStateOf<Long?>(null) }
// Whether the attention list is open. It is not a navigation destination, so
// the operator's current destination and panes are untouched while it shows.
var attentionOpen by rememberSaveable { mutableStateOf(false) }
// The notification permission: asked at most once, at a sensible moment — the
// first time a run actually needs the operator, or the first time the
// attention surface is opened — and never nagged. The rationale is shown
// before the one system dialog; a refusal simply leaves the in-app Needs you
// surface as the only surface, which is exactly what the app did before.
val notificationsAllowed by vm.notificationsAllowed.collectAsStateWithLifecycle()
val permissionAsked by vm.notificationPermissionAsked.collectAsStateWithLifecycle()
var rationaleOpen by rememberSaveable { mutableStateOf(false) }
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) { vm.refreshNotificationsAllowed() }
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { vm.refreshNotificationsAllowed() }
val needsPerson = attention.isNotEmpty()
LaunchedEffect(notificationsAllowed, permissionAsked, needsPerson, attentionOpen) {
val prompt = alertPermissionPrompt(
granted = notificationsAllowed,
asked = permissionAsked,
trigger = needsPerson || attentionOpen,
)
if (prompt.request) {
// Remember the ask first, so dismissing the rationale is never a nag
// and a recomposition cannot ask twice.
vm.markNotificationPermissionAsked()
rationaleOpen = true
}
}
// The bottom container's morph (destination pill <-> omni-search field) is
// saved state, so a still-open field survives rotation, configuration change
// and process death. Opening never navigates, so the destination the pill had
// selected is untouched and dismissing restores exactly that pill.
var searchState by rememberSaveable(stateSaver = OmniSearchStateSaver) {
mutableStateOf(OmniSearchState())
}
val search by vm.search.collectAsStateWithLifecycle()
// Whether the Chat destination currently shows an open conversation. The
// floating pill stands down there (see [destinationPillVisible]); it is
// read from the chat store, so it flips in the same recomposition that swaps
// the chat list for the conversation.
val conversationOpen by vm.conversationOpen.collectAsStateWithLifecycle()
// A run or pipeline detail owns the lower part of the screen, including its
// graph, stage, artifact and decision surfaces. Hide the pill for the entire
// detail stack, not just one sheet inside it; returning to the list restores it.
val runDetailOpen = runDetailOpen(currentRoute, runSelection)
val pipelineDetailOpen = pipelineDetailOpen(currentRoute, pipelineSelection)
val pillVisible = destinationPillVisible(currentRoute, conversationOpen, runDetailOpen, pipelineDetailOpen)
val searchKind by vm.searchKind.collectAsStateWithLifecycle()
val searchSort by vm.searchSort.collectAsStateWithLifecycle()
/** Back/scrim/close and a selection all dismiss the morph and clear the panel. */
val dismissSearch: () -> Unit = {
vm.clearSearch()
searchState = dismissOmniSearch(searchState)
}
// Selecting a result navigates and closes the search. A read-only (unknown
// kind) result has a null target and only closes.
val onSelectResult: (SearchResult) -> Unit = { hit ->
when (val target = searchTarget(hit)) {
is SearchTarget.Pipeline -> {
pipelineSelection = PaneSelection(MasterPane.Detail, target.pipelineId, target.version)
navController.navigate(PIPELINES_ROUTE) {
popUpTo(HOME_ROUTE) { inclusive = false }
launchSingleTop = true
}
}
is SearchTarget.Run -> {
runSelection = PaneSelection(MasterPane.Detail, target.runId)
runSearchNav = target.takeIf { it.sequence > 0 }
navController.navigate(HOME_ROUTE) { launchSingleTop = true }
}
null -> Unit
}
dismissSearch()
}
// Opening the run a notification or an attention entry names: the Runs
// destination's saved selection points at it, then that destination is shown.
// Reaching it also clears its notification, and a run that is still waiting is
// not re-notified.
val openRunFromAttention: (Long) -> Unit = { runId ->
vm.arrivedAtRun(runId)
runSelection = PaneSelection(pane = MasterPane.Detail, itemId = runId)
navController.navigate(HOME_ROUTE) { launchSingleTop = true }
}
// A deep link (or the notification's click action) opens its run once. The
// effect re-runs only when the link changes, and the link is cleared once
// handled, so a rotation re-opens nothing. A waiting run's notification also
// asks for the decision sheet, so the tap lands on the decision itself.
LaunchedEffect(initialRunId, initialRunAction) {
if (initialRunId != null) {
if (initialRunAction == RUN_DEEP_LINK_ACTION_DECIDE) decisionRequest = initialRunId
openRunFromAttention(initialRunId)
onInitialRunHandled()
}
}
// Closing the list counts as looking, but only at what still asks: a waiting
// or failed run stays on the surface until it is resolved or deliberately
// dismissed, so closing never hides work that still needs the operator.
val closeAttentionList: () -> Unit = {
attentionOpen = false
}
// Opening an entry deals with it: a failure is cleared by opening it, a
// waiting run is not, because only its decision clears it.
val openAttentionEntry: (AttentionEntry) -> Unit = { entry ->
if (entry.kind != AttentionKind.Decision) {
vm.dismissAttention(entry.runId, entry.kind)
}
closeAttentionList()
openRunFromAttention(entry.runId)
}
// One list scroll position each, owned here above the NavHost so it survives
// the destination (and list screen) being recreated when a pane is covered or
// the runs selection changes, as well as a configuration change and process
// death. The list screens only clamp it when the list changed underneath.
val pipelineListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val templateListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val runListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val onNavigate: (TopDestination) -> Unit = { destination ->
if (currentRoute != destination.route) {
navController.navigate(destination.route) {
popUpTo(HOME_ROUTE) {
inclusive = topLevelPopUpToHomeInclusive(destination.route)
}
launchSingleTop = true
}
}
}
// No bottomBar: the destinations float over the content as a pill (below).
//
// Exactly one layer owns the top inset. The outer Scaffold's content insets
// are zeroed so it no longer reserves the status bar on top of the inner
// screens' app bars (a Material 3 TopAppBar applies the top safe-area inset),
// which removed the duplicate top band. The bottom is owned by each screen's
// Scaffold, and the floating pill explicitly clears the safe area (system
// bars, cutout, gesture area and IME) via windowInsetsPadding.
//
// The pill is a true overlay: it is drawn in its own bottom-anchored layer over
// the content and never takes layout space, so the content keeps its full
// height. Nothing is positioned by the pill; its bottom clearance
// ([pillScrollInset], published through [LocalPillBottomInset]) is applied
// inside each scrollable screen's own scroll content, so scrolling to the end
// still reveals the last row clear of the pill, and while the pill is hidden
// (an open conversation or a run's open decision surface, see
// [destinationPillVisible]) that clearance is zero
// so a hidden pill leaves no empty band. See [contentPillPadding].
val bannerVisible = connectionState !is ConnectionState.Connected
// The live height of any bottom selector strip the current pane is showing. The
// strip publishes it while it is shown and the pill below reads it, so the two
// never overlap: the pill is lifted clear of the strip (see [pillBottomOffset]).
val bottomStripInset = remember { BottomStripInset() }
Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0)) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
CompositionLocalProvider(
LocalPillBottomInset provides pillScrollInset(pillVisible),
LocalBottomStripInset provides bottomStripInset,
) {
Column(Modifier.fillMaxSize().padding(bottom = contentPillPadding(pillVisible))) {
ConnectionBanner(
state = connectionState,
configuredUrl = configuredUrl,
onReconnect = vm::reconnect,
)
NavHost(
navController = navController,
startDestination = HOME_ROUTE,
// While the banner is visible it owns the status-bar inset, so
// the inner app bars below must not apply it a second time.
modifier = Modifier
.weight(1f)
.then(
if (bannerVisible) {
Modifier.consumeWindowInsets(
paneSafeArea().only(WindowInsetsSides.Top),
)
} else {
Modifier
},
),
) {
composable(PIPELINES_ROUTE) {
PipelineDestination(
vm = vm,
wide = wide,
selection = pipelineSelection,
onSelectionChange = { pipelineSelection = it },
listState = pipelineListState,
attention = attention,
onOpenAttention = { attentionOpen = true },
onOpenRun = { runId ->
runSelection = PaneSelection(
pane = MasterPane.Detail,
itemId = runId,
)
navController.navigate(HOME_ROUTE) { launchSingleTop = true }
},
)
}
composable(HOME_ROUTE) {
RunsDestination(
vm = vm,
wide = wide,
selection = runSelection,
onSelectionChange = { runSelection = it },
pendingNav = runSearchNav,
onPendingNavResolved = { runSearchNav = null },
listState = runListState,
decisionRequest = decisionRequest,
onDecisionRequestHandled = { decisionRequest = null },
attention = attention,
onOpenAttention = { attentionOpen = true },
)
}
composable("chat") {
ChatScreen(vm = vm, wide = wide)
}
composable("settings") {
SettingsDestination(vm = vm, wide = wide, listState = templateListState)
}
}
}
}
// The open search covers the content behind a scrim; tapping it plays
// the reverse morph, the same dismissal as Back.
AnimatedVisibility(
visible = searchState.open,
enter = fadeIn(animationSpec = MotionStandard.spec()),
exit = fadeOut(animationSpec = MotionStandard.spec()),
) {
Box(
Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.scrim.copy(alpha = SEARCH_SCRIM_ALPHA))
.pointerInput(Unit) {
detectTapGestures { dismissSearch() }
},
)
}
// Composed after the NavHost, so while the field is open Back (button
// or gesture) dismisses the morph before any pane's own Back handler.
BackHandler(enabled = searchState.open) { dismissSearch() }
// The results panel and destination bar share
// one bottom-anchored, inset-clearing column — the overlay layer, drawn
// above the content and never part of its layout. `paneSafeArea`
// (WindowInsets.safeDrawing) is applied once here, so the pill clears the
// system bars, cutout, gesture area and IME: the panel then takes exactly
// the height the IME and navigation bar leave (weight, `fill = false` so
// a short panel wraps) and scrolls inside it, and the input always sits
// directly below the panel and above the keyboard. The activity declares
// `adjustResize` and the app is edge-to-edge, so the Compose window inset
// is the only source of the IME geometry and it is applied once, here.
//
// The overlay's resting place is the window width's in [destinationPillAlignment]:
// horizontally centred on a narrow window, anchored to the bottom-right
// corner on a wide one. Its margin comes from the named [SPACING_L], so the
// corner placement adds no new number.
// While a bottom selector strip is up, the whole overlay is lifted by that
// strip's measured height ([pillBottomOffset]), so the pill never overlaps it.
Column(
modifier = Modifier
.fillMaxSize()
.windowInsetsPadding(paneSafeArea())
.padding(
end = if (wide) SPACING_L else 0.dp,
bottom = pillBottomOffset(bottomStripInset.height),
),
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = destinationPillAlignment(wide),
) {
if (searchState.open) {
SearchResultsPanel(
state = search,
kind = SearchKindFilter.fromStorage(searchKind),
sort = SearchSort.fromStorage(searchSort),
onKind = { vm.setSearchKind(it.serverKind) },
onSort = { vm.setSearchSort(it.storageKey) },
onSelect = onSelectResult,
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = false)
.padding(bottom = SPACING_L),
)
}
// The pill stands down while a conversation or run detail is open;
// the search field it morphs into is unreachable there anyway (the
// field opens from the pill), so nothing is stranded by not drawing it.
if (pillVisible) {
DestinationBar(
destinations = destinations,
currentRoute = currentRoute,
state = searchState,
onSelect = onNavigate,
onOpenSearch = { searchState = openOmniSearch(searchState) },
onDismissSearch = dismissSearch,
onQueryChange = {
searchState = setOmniSearchQuery(searchState, it)
vm.onSearchQueryChanged(it)
},
onFocusChange = { searchState = setOmniSearchFocus(searchState, it) },
onSubmitSearch = { vm.searchNow() },
)
}
}
if (attentionOpen) {
AttentionSheet(
entries = attention,
onOpen = openAttentionEntry,
onDismissEntry = { entry -> vm.dismissAttention(entry.runId, entry.kind) },
onDismiss = closeAttentionList,
)
}
// The one-time rationale before the system notification dialog. It is
// shown only on the first ask (the permission model decides), so a
// refusal or dismissal leaves the in-app surface alone from then on.
if (rationaleOpen) {
AlertDialog(
onDismissRequest = { rationaleOpen = false },
title = { Text("Notifications") },
text = { Text(NOTIFICATION_RATIONALE) },
confirmButton = {
TextButton(
onClick = {
rationaleOpen = false
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
},
) { Text("Allow") }
},
dismissButton = {
TextButton(onClick = { rationaleOpen = false }) { Text("Not now") }
},
)
}
}
}
}
/** How dark the scrim behind the open search field is. */
private const val SEARCH_SCRIM_ALPHA = 0.5f
/** The Chat destination's navigation route. */
private const val CHAT_ROUTE = "chat"
private const val RUNS_ROUTE = "runs"
private const val PIPELINES_ROUTE = "pipelines"
/** A run detail is any non-list level of the Runs pane stack. */
internal fun runDetailOpen(currentRoute: String?, selection: PaneSelection): Boolean =
currentRoute == RUNS_ROUTE && selection.depth >= 1
/** A pipeline detail is any non-list level of the Pipelines pane stack. */
internal fun pipelineDetailOpen(currentRoute: String?, selection: PaneSelection): Boolean =
currentRoute == PIPELINES_ROUTE && selection.depth >= 1
/**
* Whether the floating destination pill is drawn for [currentRoute]. The pill
* stands down in the three places a deliberate detail surface owns the foot of
* the screen and the pill would sit over it:
*
* - while the Chat destination is showing an open conversation — a session's
* transcript and composer — where it would compete with send/stop;
* - while a run detail is open ([runDetailOpen]), including its summary, graph,
* stage, artifact and decision surfaces, where it would cover their controls;
* - while a pipeline detail is open ([pipelineDetailOpen]), including its
* description, graph and run history, where it would cover their controls.
*
* Everything else keeps it: the chat list, run list and pipeline list all draw
* it, and the covered peek strip and Back still leave every hiding state, so
* hiding the pill strands nothing. The
* clearance and the drawn pill both key off this one predicate. Pure, so the one
* rule is unit-testable without a device.
*/
internal fun destinationPillVisible(
currentRoute: String?,
conversationOpen: Boolean,
runDetailOpen: Boolean,
pipelineDetailOpen: Boolean,
): Boolean =
!(currentRoute == CHAT_ROUTE && conversationOpen) && !runDetailOpen && !pipelineDetailOpen
/**
* Where the bottom destination pill rests in the window: horizontally centred on a
* **narrow** window and anchored
* to the bottom-right **corner** on a **wide** one. The overlay is drawn above the
* content and never takes layout space either way, so this is purely where it
* sits. A pure function of the window width, so the one arrangement rule is
* unit-testable and no screen hardcodes a width.
*/
internal fun destinationPillAlignment(wide: Boolean): Alignment.Horizontal =
if (wide) Alignment.End else Alignment.CenterHorizontally
/**
* The bottom padding the app's content column applies for the pill: none, whether
* the pill is [pillVisible] or not. The pill is an overlay drawn above the
* content, so it must never size or offset it — the content keeps its own full
* height and the pill's clearance lives in each scrollable's own scroll content
* (see [pillScrollInset]). The value is a function of the drawn state (both of
* which the unit test pins at zero) rather than left implicit in an absent
* modifier, so a later change that reintroduces a reserved band here fails the
* test.
*/
internal fun contentPillPadding(pillVisible: Boolean): Dp = 0.dp
/**
* The trailing bottom space a scrollable screen keeps so its last row scrolls clear
* of the floating destination pill, built from the named [DESTINATION_PILL_RESERVE]
* while the pill is drawn, and none while it is hidden (an open conversation or a
* run detail, see [destinationPillVisible]) so a hidden pill
* leaves no empty band at the end of a list. Published to the content through
* `LocalPillBottomInset` and applied inside
* each scrollable's own scroll content, never as layout padding on the content. It
* is derived from [pillVisible] alone, so the clearance and the drawn pill can
* never disagree into a frame with a drawn pill over content it does not clear, or
* a reserved gap behind a hidden one — which is what keeps a list from jumping as
* the pill appears and disappears.
*/
internal fun pillScrollInset(pillVisible: Boolean): Dp =
if (pillVisible) DESTINATION_PILL_RESERVE else 0.dp
/**
* How far above the window's bottom the floating pill rests: its own [SPACING_L]
* margin, lifted by exactly the height of any bottom selector strip the current pane
* is showing ([stripHeight], published by the strip and zero when none is up). The
* pill therefore never overlaps the strip — while the strip is up the two are stacked
* with the pill clear above it — and it keeps its resting margin when no strip is up.
* Pure, so the one clearance rule is unit-testable without a device.
*/
internal fun pillBottomOffset(stripHeight: Dp): Dp = SPACING_L + stripHeight
@@ -1,332 +0,0 @@
package net.awan.pipelines.ui
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.RunEventFrame
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.RunStepDelta
import net.awan.pipelines.data.protocol.RunSummary
/**
* The pure fold from a server-pushed [RunEventFrame] into the client's cached
* run state. The app never polls: every value on the runs list, the pipeline
* rows' last-run line, the run detail (status, timeline, stages, completed
* count) is advanced here from the pushes.
*
* The fold is deliberately monotonic so an out-of-order or duplicated delta can
* never move a run or a step backwards. A delta that names a run the list does
* not hold is inserted as a new row from the frame's own identity (pipeline id,
* name, title, version), so a run started after the screen loaded appears
* without a fetch; only a frame with no such identity (an older server) reports
* [RunListFold.needsResync], and the caller re-reads the server's current list
* once instead.
*/
/** Run statuses from which a run never transitions again. */
internal val TERMINAL_RUN_STATUSES = setOf("succeeded", "failed", "canceled", "interrupted")
/**
* Whether [status] is the human-stage status a run (or its waiting step) parks on:
* it is not terminal and it is not executing, but it still needs the full detail
* (the compact delta carries no options/prompt), so a pending decision is
* surfaced live.
*/
internal fun isWaitingRunStatus(status: String): Boolean =
status.trim().lowercase() == "waiting"
/** The lifecycle rank at which a status is settled: a later status never rewrites it. */
private const val SETTLED_RANK = 2
/** Whether [status] is a settled run status (no further transitions expected). */
internal fun isTerminalRunStatus(status: String): Boolean =
status.trim().lowercase() in TERMINAL_RUN_STATUSES
/**
* The run lifecycle as an ordinal so a delta can only advance it:
* queued (0) < running/waiting (1) < terminal (2). A blank or unknown word is -1.
*/
internal fun runLifecycleRank(status: String): Int = when (status.trim().lowercase()) {
"queued" -> 0
"running", "waiting" -> 1
"succeeded", "failed", "canceled", "interrupted" -> 2
else -> -1
}
/**
* The step lifecycle as an ordinal so a settled visit is never reopened:
* in-flight running/waiting (1) < finished completed/failed/canceled (2).
*/
internal fun stepLifecycleRank(status: String): Int = when (status.trim().lowercase()) {
"running", "waiting" -> 1
"completed", "failed", "canceled", "interrupted" -> 2
else -> -1
}
/**
* The outcome of folding one frame into the runs list: the list with the matching
* run updated in place (same order, so a read never reshuffles), or
* [needsResync] when the frame names a run the list does not hold and carries no
* identity to build its row from.
*/
internal data class RunListFold(val runs: List<RunSummary>, val needsResync: Boolean)
/**
* Folds one pushed frame into the runs list, in place and without reordering.
* A run the list has never held is inserted as a new row at the head (newest
* first, matching the server's own order) when the frame carries its pipeline
* identity, so a run started after the screen loaded appears while the operator
* watches without a fetch; a frame with no identity (an older server) still
* reports [RunListFold.needsResync] so the caller re-reads once instead.
*/
internal fun foldRunEvent(runs: List<RunSummary>, frame: RunEventFrame): RunListFold {
if (frame.runId <= 0) return RunListFold(runs, needsResync = false)
val index = runs.indexOfFirst { it.id == frame.runId }
if (index < 0) {
val added = frame.newRunSummary() ?: return RunListFold(runs, needsResync = true)
return RunListFold(listOf(added) + runs, needsResync = false)
}
val current = runs[index]
val updated = current.applying(frame)
if (updated == current) return RunListFold(runs, needsResync = false)
val next = runs.toMutableList()
next[index] = updated
return RunListFold(next, needsResync = false)
}
/**
* The row a frame for a run the list has never held describes, or null when the
* frame lacks the pipeline identity a row needs (an older server), in which case
* the caller resyncs instead of inventing an incomplete row. The frame already
* carries everything the row shows, so no field is guessed from cached state.
*/
internal fun RunEventFrame.newRunSummary(): RunSummary? {
if (pipelineId <= 0 || name.isBlank()) return null
return RunSummary(
resourceWait = resourceWait,
id = runId,
pipelineId = pipelineId,
name = name,
title = title.ifBlank { null },
version = version,
status = status,
executing = executingFor(status, true),
outcome = outcome,
currentStage = currentStage,
createdAt = createdAt,
finishedAt = finishedAt,
completedSteps = completedSteps,
)
}
/**
* Folds one pushed frame into a cached run detail: the run's own status/outcome/
* stage/timestamps plus at most one step, matched by sequence so a duplicate or
* out-of-order step delta is idempotent and never adds a second visit. A frame
* for another run is ignored unchanged.
*/
internal fun foldRunEvent(detail: RunDetail, frame: RunEventFrame): RunDetail {
if (frame.runId != detail.id) return detail
if (isStaleRunFrame(detail.status, frame.status, frame.resourceWaitSet)) return detail
val merged = detail.fields().applying(frame)
val steps = frame.step?.let { upsertStep(detail.steps, it) } ?: detail.steps
val updated = detail.copy(
resourceWait = merged.resourceWait,
status = merged.status,
outcome = merged.outcome,
currentStage = merged.currentStage,
completedSteps = merged.completedSteps,
createdAt = merged.createdAt,
finishedAt = merged.finishedAt,
executing = merged.executing,
steps = steps,
)
return if (updated == detail) detail else updated
}
/**
* Whether a frame carries data the compact delta cannot express (recorded
* artifacts, output, a settled visit's diagnostic), so the caller fetches the
* full run once to fill those in rather than showing a stale gallery. A waiting
* run or step is included: its options and prompt live in the waiting step's
* `output`, which the compact delta deliberately omits, so the fetch is what
* surfaces a pending decision without a manual refresh.
*/
internal fun runDetailNeedsFullSync(frame: RunEventFrame): Boolean {
val step = frame.step
val stepSettled = step != null && stepLifecycleRank(step.status) >= 2
val stepWaiting = step != null && isWaitingRunStatus(step.status)
return stepSettled || stepWaiting || isTerminalRunStatus(frame.status) || isWaitingRunStatus(frame.status)
}
/**
* Advances a run status forward only. A same-or-lower rank never wins, and once
* both words are terminal the settled one is kept, so a late `running` delta
* cannot resurrect a finished run.
*/
private fun advanceRunStatus(current: String, incoming: String): String =
advanceStatus(current, incoming, ::runLifecycleRank)
/**
* Whether a frame is a stale transition that must be dropped whole: its run
* status is behind the local one, or it is a different terminal word after the
* run already settled. Dropping every field (not just the status) is what keeps
* a late `running` delta from also rewriting the stage or step of a settled run.
*/
private fun isStaleRunFrame(current: String, incoming: String, resourceWaitSet: Boolean = false): Boolean =
if (resourceWaitSet && incoming == "queued" && !isTerminalRunStatus(current)) false
else isStaleTransition(current, incoming, ::runLifecycleRank)
/** The step counterpart of [isStaleRunFrame]: a settled visit drops a stale delta whole. */
private fun isStaleStepDelta(current: String, incoming: String): Boolean =
isStaleTransition(current, incoming, ::stepLifecycleRank)
/**
* The one staleness rule, shared by the run and step ladders so they cannot
* drift: a status behind the current rank, or a different settled word after the
* state already settled, marks the whole delta stale.
*/
private fun isStaleTransition(current: String, incoming: String, rank: (String) -> Int): Boolean {
if (incoming.isBlank()) return false
val cur = rank(current)
val inc = rank(incoming)
if (cur < 0 || inc < 0) return false
return inc < cur || (cur >= SETTLED_RANK && inc >= SETTLED_RANK && incoming != current)
}
/** Advances a step status forward only, never reopening a settled visit. */
private fun advanceStepStatus(current: String, incoming: String): String =
advanceStatus(current, incoming, ::stepLifecycleRank)
/**
* The one monotonic status rule, shared by the run and step ladders so they
* cannot drift: a blank or unknown word never wins, a higher rank always does,
* and once a settled rank is reached its word is kept forever.
*/
private fun advanceStatus(current: String, incoming: String, rank: (String) -> Int): String {
if (incoming.isBlank() || incoming == current) return current
val cur = rank(current)
val inc = rank(incoming)
return when {
cur < 0 -> incoming
inc < 0 -> current
inc > cur -> incoming
cur >= SETTLED_RANK -> current
else -> incoming
}
}
/** The run-state fields a frame advances, shared by the summary row and the detail. */
private data class RunStateFields(
val resourceWait: net.awan.pipelines.data.protocol.ResourceWait?,
val status: String,
val outcome: String,
val currentStage: String,
val completedSteps: Int,
val createdAt: String,
val finishedAt: String,
val executing: Boolean,
) {
/**
* The single run-field merge: every value advances forward, so the row and the
* detail can never apply a frame differently.
*/
fun applying(frame: RunEventFrame): RunStateFields {
val status = if (frame.resourceWaitSet && frame.status == "queued" && !isTerminalRunStatus(status))
"queued" else advanceRunStatus(status, frame.status)
return RunStateFields(
resourceWait = if (isTerminalRunStatus(status)) null else if (frame.resourceWaitSet) frame.resourceWait else resourceWait,
status = status,
outcome = frame.outcome.ifBlank { outcome },
currentStage = frame.currentStage.ifBlank { currentStage },
completedSteps = maxOf(completedSteps, frame.completedSteps),
createdAt = frame.createdAt.ifBlank { createdAt },
finishedAt = frame.finishedAt.ifBlank { finishedAt },
executing = executingFor(status, executing),
)
}
}
private fun RunSummary.fields() = RunStateFields(
resourceWait = resourceWait,
status = status,
outcome = outcome,
currentStage = currentStage,
completedSteps = completedSteps,
createdAt = createdAt,
finishedAt = finishedAt,
executing = executing,
)
private fun RunDetail.fields() = RunStateFields(
resourceWait = resourceWait,
status = status,
outcome = outcome,
currentStage = currentStage,
completedSteps = completedSteps,
createdAt = createdAt,
finishedAt = finishedAt,
executing = executing,
)
/** The client's best knowledge of `executing`: queued/running only; unknown keeps [current]. */
private fun executingFor(status: String, current: Boolean): Boolean = when (status.trim().lowercase()) {
"queued", "running" -> true
"waiting", "succeeded", "failed", "canceled", "interrupted" -> false
else -> current
}
private fun RunSummary.applying(frame: RunEventFrame): RunSummary {
if (isStaleRunFrame(status, frame.status, frame.resourceWaitSet)) return this
val current = fields()
val merged = current.applying(frame)
if (merged == current) return this
return copy(
resourceWait = merged.resourceWait,
status = merged.status,
outcome = merged.outcome,
currentStage = merged.currentStage,
completedSteps = merged.completedSteps,
createdAt = merged.createdAt,
finishedAt = merged.finishedAt,
executing = merged.executing,
)
}
/**
* Upserts one step delta, matched by sequence: an existing visit has only its
* non-blank fields advanced, and a new visit is inserted in sequence order so a
* late delta for an earlier step cannot reorder the timeline.
*/
private fun upsertStep(steps: List<RunStep>, delta: RunStepDelta): List<RunStep> {
val index = steps.indexOfFirst { it.sequence == delta.sequence }
if (index >= 0) {
val current = steps[index]
val updated = current.applying(delta)
if (updated == current) return steps
val next = steps.toMutableList()
next[index] = updated
return next
}
val added = RunStep(
sequence = delta.sequence,
stage = delta.stage,
status = advanceStepStatus("", delta.status),
outcome = delta.outcome,
target = delta.target,
diagnostic = delta.diagnostic,
)
val next = steps.toMutableList()
val at = next.indexOfFirst { it.sequence > delta.sequence }
if (at < 0) next.add(added) else next.add(at, added)
return next
}
private fun RunStep.applying(delta: RunStepDelta): RunStep {
if (isStaleStepDelta(status, delta.status)) return this
return copy(
stage = delta.stage.ifBlank { stage },
status = advanceStepStatus(status, delta.status),
outcome = delta.outcome.ifBlank { outcome },
target = delta.target.ifBlank { target },
diagnostic = delta.diagnostic.ifBlank { diagnostic },
)
}
@@ -1,45 +0,0 @@
package net.awan.pipelines.ui
/**
* The operator-facing name of a run: the server's stored title when it sent one,
* otherwise the pipeline name (a run predating the title field, or one the server
* could not title). Mirrors the server's `RunSummary.Label`, so the runs list, the
* run detail header and the stage pane never spell the same run differently.
*/
fun runLabel(title: String?, name: String): String {
val stored = title?.trim().orEmpty()
return if (stored.isEmpty()) name else stored
}
/**
* The runs list's two identity lines: [label] is the run's primary line and
* [pipeline] is the pipeline the run belongs to, shown as a second line only when
* the label is a stored title (so two runs of one pipeline read as different
* goals). A run with no title falls back to the pipeline name as its only line —
* never a title line followed by an empty one.
*/
data class RunIdentity(val label: String, val pipeline: String?)
fun runIdentity(title: String?, name: String): RunIdentity {
val stored = title?.trim().orEmpty()
return if (stored.isEmpty()) RunIdentity(name, null) else RunIdentity(stored, name)
}
/**
* The line budget for a run's title in each place the app shows it. A title is
* derived from the run's prompt, so it is often long, and the places it appears
* have different jobs: the run view exists to let the operator read the run, so
* its own title is complete, while a runs-list row (one of many) and the stage
* pane's compact run-context line may clamp because the run view still carries
* the whole title. Kept here, named, so the budgets are a deliberate choice the
* tests pin rather than a bare `maxLines` literal at each call site.
*/
/** The run view's own title never elides: it wraps over as many lines as it needs. */
internal const val RUN_VIEW_TITLE_LINES: Int = Int.MAX_VALUE
/** A runs-list row's title grows to two lines for a longer title, then ellipsises. */
internal const val RUN_ROW_TITLE_LINES: Int = 2
/** The stage pane's compact run-context line shows at most two lines, then ellipsises. */
internal const val STAGE_RUN_LABEL_LINES: Int = 2
@@ -1,17 +0,0 @@
package net.awan.pipelines.ui
/**
* Whether the live run stream is delivering pushes, so the runs list and the run
* detail can say so honestly instead of leaving the operator to trust a view that
* may have silently stopped updating. [label] is the short word the badge shows.
*/
enum class RunStreamState(val label: String) {
/** Subscribed and receiving the server's run-state pushes. */
Live("live"),
/** Connecting, or re-subscribing after a drop: pushes are paused in the gap. */
Connecting("reconnecting"),
/** No connection, or the server refused the subscription. */
Offline("not live"),
}
@@ -1,168 +0,0 @@
package net.awan.pipelines.ui
import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.History
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.collect
import net.awan.pipelines.ui.components.SlidingPaneStack
import net.awan.pipelines.ui.components.rememberPaneContent
import net.awan.pipelines.ui.components.runDetailTabIndex
import net.awan.pipelines.ui.components.runDetailTabs
import net.awan.pipelines.ui.graph.RunStagePane
import net.awan.pipelines.ui.screens.RunDetailScreen
import net.awan.pipelines.ui.screens.RunHistoryScreen
/**
* The Runs destination: the same shared pane stack with the run list, the
* selected run's tabs and the stage pane. Its selection is owned by
* [PipelinesApp] so the Pipelines detail can open a run it just started.
*/
@Composable
internal fun RunsDestination(
vm: AppViewModel,
wide: Boolean,
selection: PaneSelection,
onSelectionChange: (PaneSelection) -> Unit,
pendingNav: SearchTarget.Run?,
onPendingNavResolved: () -> Unit,
listState: LazyListState,
decisionRequest: Long? = null,
onDecisionRequestHandled: () -> Unit = {},
attention: List<AttentionEntry>,
onOpenAttention: () -> Unit,
) {
val depth = selection.depth
val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) }
// A run search hit that names a recorded visit is applied once the run's steps
// have loaded: the visit's stage pane (or the matched section) replaces the
// plain run detail. A target for another run waits for its own detail.
val runState by vm.runDetail.collectAsStateWithLifecycle()
LaunchedEffect(pendingNav, runState.data) {
val target = pendingNav ?: return@LaunchedEffect
val run = runState.data ?: return@LaunchedEffect
if (run.id != target.runId) return@LaunchedEffect
onSelectionChange(resolveRunTarget(target, run.id, run.steps))
onPendingNavResolved()
}
PredictiveBackHandler(enabled = depth >= 1) { progress ->
progress.collect { }
onBack()
}
SlidingPaneStack(
depth = depth,
wide = wide,
onPopTo = { level -> onSelectionChange(popTo(selection, level)) },
compactLabel = "Runs",
compactIcon = Icons.Filled.History,
// Every covered pane in this stack (the runs list, or a run's detail) carries
// a statistics block, so the region is sized for it and the runs list's
// counts and most-recent run are actually shown rather than dropped by the
// title-only tier.
compactStats = true,
backContentDescription = { level ->
when (level) {
0 -> "Back to runs"
1 -> "Back to run"
else -> "Back to stage"
}
},
pane = { level, covered, paneModifier ->
when (level) {
0 -> RunHistoryScreen(
vm = vm,
onOpenRun = { runId -> onSelectionChange(PaneSelection(MasterPane.Detail, runId)) },
modifier = paneModifier,
selectedRunId = selection.itemId.takeIf { depth >= 1 },
covered = covered,
wide = wide,
listState = listState,
attention = attention,
onOpenAttention = onOpenAttention,
)
1 -> rememberPaneContent(
selection.itemId.takeIf { it != 0L }?.let { it to selection.sectionIndex },
)?.let { (itemId, sectionIndex) ->
RunDetailScreen(
vm = vm,
runId = itemId,
onBack = onBack,
selectedSection = runDetailTabIndex(selection.detailTabKey, sectionIndex),
onSelectSection = { index ->
onSelectionChange(
selection.copy(
sectionIndex = index,
detailTabKey = runDetailTabs[index].key,
),
)
},
modifier = paneModifier,
wide = wide,
onOpenStage = { key, visit ->
onSelectionChange(
selection.copy(pane = MasterPane.Stage, stageKey = key, stageVisit = visit),
)
},
covered = covered,
requestDecision = decisionRequest == itemId,
onDecisionRequestHandled = onDecisionRequestHandled,
attention = attention,
onOpenAttention = onOpenAttention,
)
}
2 -> rememberPaneContent(
selection.stageKey?.let {
Triple(selection.itemId, it, selection.stageVisit)
},
)?.let { (itemId, key, visit) ->
RunStagePane(
vm = vm,
runId = itemId,
stageKey = key,
visitIndex = visit,
openSection = null,
onOpenSection = { sectionKey ->
onSelectionChange(
selection.copy(pane = MasterPane.Section, sectionKey = sectionKey),
)
},
onVisitChange = { onSelectionChange(selection.copy(stageVisit = it)) },
onBack = onBack,
wide = wide,
modifier = paneModifier,
covered = covered,
)
}
3 -> rememberPaneContent(
selection.sectionKey?.let {
Triple(selection.itemId, it, selection.stageKey)
},
)?.let { (itemId, sectionKey, key) ->
// A closing section pane keeps the identity that opened it, so
// it renders its content until it is fully off-screen.
RunStagePane(
vm = vm,
runId = itemId,
stageKey = key.orEmpty(),
visitIndex = selection.stageVisit,
openSection = sectionKey,
onOpenSection = {},
onVisitChange = { onSelectionChange(selection.copy(stageVisit = it)) },
onBack = onBack,
wide = wide,
modifier = paneModifier,
covered = covered,
)
}
}
},
)
}
@@ -1,279 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.SearchResult
import net.awan.pipelines.ui.components.FilterCheckItem
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.SortMenu
import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.SEARCH_PROGRESS_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The omni-search results panel: one scrolling surface that sits above the search
* field. It leads with the filter and sort controls (the same shared menu
* controls the runs list uses), then renders the last accepted results; while a
* newer query loads it keeps those results and adds a thin progress bar rather
* than blanking, and a failure is reported without discarding what is already
* shown. Its height is bounded by the caller (the window's IME/navigation-bar
* insets), so it scrolls inside the remainder instead of running under the
* keyboard.
*/
@Composable
internal fun SearchResultsPanel(
state: SearchUiState,
kind: SearchKindFilter,
sort: SearchSort,
onKind: (SearchKindFilter) -> Unit,
onSort: (SearchSort) -> Unit,
onSelect: (SearchResult) -> Unit,
modifier: Modifier = Modifier,
) {
val scheme = MaterialTheme.colorScheme
val error = state.error
// The filter and sort are applied to the results in hand as well as being sent
// to the server (the kind) or held client-side (the order), so the list always
// matches the active control, even for the moment a narrowed request loads.
val shown = remember(state.results, kind, sort) {
sortSearchResults(filterSearchResults(state.results, kind), sort)
}
Surface(
modifier = modifier,
shape = RoundedCornerShape(SPACING_XL),
color = scheme.surfaceContainerHigh,
tonalElevation = 3.dp,
shadowElevation = 6.dp,
) {
Column(Modifier.fillMaxWidth()) {
SearchControls(kind = kind, sort = sort, onKind = onKind, onSort = onSort)
HorizontalDivider(color = scheme.outlineVariant)
// A refresh of an already-populated panel shows progress without
// replacing the results; the first load shows the searching row below.
if (state.loading && state.results.isNotEmpty()) {
LinearProgressIndicator(Modifier.fillMaxWidth())
}
when {
error != null -> PanelMessage(error, isError = true)
shown.isNotEmpty() -> SearchResultList(shown, state.query, onSelect)
state.loading && state.results.isEmpty() -> SearchingRow()
else -> searchPanelEmptyMessage(state, shown, kind)?.let { PanelMessage(it, isError = false) }
}
}
}
}
/**
* The search surface's filter and sort control, the same shared [FilterMenu] and
* [SortMenu] the runs list uses rather than a new pattern, plus the one-line
* summary of the active choice so the collapsed controls are legible. The kind
* filter narrows server-side; the sort orders the results in hand.
*/
@Composable
private fun SearchControls(
kind: SearchKindFilter,
sort: SearchSort,
onKind: (SearchKindFilter) -> Unit,
onSort: (SearchSort) -> Unit,
) {
Row(
// The top inset leaves room for the filter badge, which is drawn above the
// icon button; without it the badge spills over the panel's rounded edge.
modifier = Modifier
.fillMaxWidth()
.padding(start = SPACING_S, end = SPACING_XS, top = SPACING_S, bottom = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
FilterMenu(
activeCount = if (kind == SearchKindFilter.All) 0 else 1,
contentDescription = "Filter results",
resetLabel = "Clear filter",
onReset = { onKind(SearchKindFilter.Default) },
) { dismiss ->
SearchKindFilter.entries.forEach { option ->
FilterCheckItem(option.label, option == kind) {
onKind(option)
dismiss()
}
}
}
SortMenu(
options = SearchSort.entries,
selected = sort,
label = { it.label },
header = "Sort results in hand",
contentDescription = "Sort results in hand",
onSelect = onSort,
onReset = { onSort(SearchSort.Default) },
)
Text(
text = searchControlsSummary(kind, sort),
style = pipelinesText().meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f).padding(start = SPACING_S),
)
}
}
@Composable
private fun PanelMessage(message: String, isError: Boolean) {
Text(
text = message,
style = MaterialTheme.typography.bodyMedium,
color = if (isError) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_M),
)
}
@Composable
private fun SearchingRow() {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_M),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
CircularProgressIndicator(Modifier.size(SEARCH_PROGRESS_DP))
Text(
text = "Searching…",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun SearchResultList(
results: List<SearchResult>,
query: String,
onSelect: (SearchResult) -> Unit,
) {
LazyColumn(Modifier.fillMaxWidth()) {
items(results) { hit ->
SearchResultRow(
hit = hit,
query = query,
onClick = searchTarget(hit)?.let { { onSelect(hit) } },
)
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
}
}
}
/**
* One result row: the type glyph (its kind, or an artifact's content type), a
* title and a secondary line. The glyph carries the kind in words as its
* content description, since the mark alone is not readable, and the matched span
* of a text match is rendered bold+underlined, so the match is distinguishable
* without relying on colour. A result with no navigation target (an unknown kind)
* is shown read-only and is not clickable.
*/
@Composable
private fun SearchResultRow(
hit: SearchResult,
query: String,
onClick: (() -> Unit)?,
) {
val text = pipelinesText()
val row = remember(hit, query) { searchRow(hit, query) }
Row(
modifier = Modifier
.fillMaxWidth()
.then(
if (onClick != null) {
Modifier.clickable(role = Role.Button, onClick = onClick)
} else {
Modifier
},
)
.padding(horizontal = SPACING_L, vertical = SPACING_M),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
Icon(
imageVector = searchResultIcon(hit),
contentDescription = searchResultKindLabel(hit),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ICON_LIST_DP),
)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
Text(
text = row.title,
style = text.cardTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val snippet = row.snippet
if (snippet != null) {
Text(
text = annotatedSnippet(snippet),
style = text.meta,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
} else {
Text(
text = row.secondary,
style = text.meta,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
/** Renders a snippet, emphasising the matched span with weight+underline (not colour). */
private fun annotatedSnippet(spans: List<SnippetSpan>): AnnotatedString = buildAnnotatedString {
spans.forEach { span ->
if (span.matched) {
withStyle(SpanStyle(fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline)) {
append(span.text)
}
} else {
append(span.text)
}
}
}
@@ -1,89 +0,0 @@
package net.awan.pipelines.ui
import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import kotlinx.coroutines.flow.collect
import net.awan.pipelines.ui.components.SlidingPaneStack
import net.awan.pipelines.ui.components.rememberPaneContent
import net.awan.pipelines.ui.screens.SettingsScreen
import net.awan.pipelines.ui.screens.TemplateDetailScreen
import net.awan.pipelines.ui.screens.TemplateGalleryScreen
/**
* The Settings destination: the same shared pane stack the other destinations
* use, with the settings page as pane 0 and the templates gallery it opens from
* its Templates row as pane 1 and the selected template's detail as pane 2.
* Templates is configuration, so it is one of the settings destinations rather
* than a floating-pill entry; the gallery is the existing [TemplateGalleryScreen]
* (and its detail the existing [TemplateDetailScreen]), so no second templates
* surface is built. Its selection is saved state, so it survives rotation,
* configuration change and process death; the covered-pane strip, the back gesture
* and the pane's own back control all step exactly one level via [settingsBack].
* Nothing here starts a run.
*/
@Composable
internal fun SettingsDestination(
vm: AppViewModel,
wide: Boolean,
listState: LazyListState,
) {
var selection by rememberSaveable(stateSaver = SettingsSelectionSaver) {
mutableStateOf(SettingsSelection())
}
val depth = selection.depth
val onBack: () -> Unit = { selection = settingsBack(selection) }
PredictiveBackHandler(enabled = depth >= 1) { progress ->
// Consume the gesture; on completion perform exactly one Back step.
progress.collect { }
onBack()
}
SlidingPaneStack(
depth = depth,
wide = wide,
onPopTo = { level -> selection = settingsPopTo(selection, level) },
compactLabel = "Settings",
compactIcon = Icons.Filled.Settings,
backContentDescription = { level ->
if (level == 0) "Back to settings" else "Back to templates"
},
pane = { level, covered, paneModifier ->
when (level) {
0 -> SettingsScreen(
vm = vm,
onOpenTemplates = { selection = openTemplatesGallery(selection) },
wide = wide,
modifier = paneModifier,
covered = covered,
)
1 -> TemplateGalleryScreen(
vm = vm,
wide = wide,
onOpen = { key -> selection = openTemplateDetail(selection, key) },
listState = listState,
modifier = paneModifier,
covered = covered,
)
2 -> rememberPaneContent(selection.templateKey)?.let { key ->
TemplateDetailScreen(
vm = vm,
templateKey = key,
onBack = onBack,
wide = wide,
modifier = paneModifier,
covered = covered,
)
}
}
},
)
}
@@ -1,86 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.runtime.saveable.Saver
/**
* Which pane of the Settings destination's sliding stack is rightmost: the
* settings page itself (level 0), the templates gallery opened from its Templates
* row (level 1) or the selected template's detail (level 2). Templates is
* configuration, so it is one of the settings destinations reached from the
* Settings page rather than an entry in the floating destination pill; modelling
* the stack here is what gives the gallery the same covered-pane strip and
* one-level Back step the other destinations use.
*/
internal enum class SettingsPane(val level: Int) {
Settings(0),
Gallery(1),
Template(2),
}
/**
* The Settings destination's saved pane selection. The only state beyond the
* rightmost pane is the open template's key, so the whole selection is
* Bundle-able primitives and survives rotation, configuration change and process
* death. Geometry (peek widths, insets) is deliberately not part of the model; it
* is derived from layout by the shared stack.
*/
internal data class SettingsSelection(
val pane: SettingsPane = SettingsPane.Settings,
val templateKey: String? = null,
) {
/** How many panes are stacked: 0 settings, 1 gallery, 2 template detail. */
val depth: Int
get() = pane.level
}
/** The Settings page's Templates row opens the gallery as its own pane. */
internal fun openTemplatesGallery(selection: SettingsSelection): SettingsSelection =
selection.copy(pane = SettingsPane.Gallery, templateKey = null)
/** A gallery card opens the selected template's detail as the next pane. */
internal fun openTemplateDetail(selection: SettingsSelection, key: String): SettingsSelection =
selection.copy(pane = SettingsPane.Template, templateKey = key)
/**
* Exactly one pane level of Back, so the back gesture, the covered strip's tap and
* the detail's own back control all step the same single level: detail → gallery →
* settings. At settings there is nothing to close and the selection is unchanged,
* so the caller lets Back leave the destination.
*/
internal fun settingsBack(selection: SettingsSelection): SettingsSelection = when (selection.pane) {
SettingsPane.Settings -> selection
SettingsPane.Gallery -> selection.copy(pane = SettingsPane.Settings, templateKey = null)
SettingsPane.Template -> selection.copy(pane = SettingsPane.Gallery, templateKey = null)
}
/**
* The selection after tapping a covered pane's strip at [level]: every pane to its
* right is closed. Level 0 closes back to the settings page, level 1 closes the
* template detail back to the gallery, and a [level] at or beyond the current
* depth is a no-op. Peeks exist only on a wide window; narrow windows use
* Back/gesture for the same one-level step.
*/
internal fun settingsPopTo(selection: SettingsSelection, level: Int): SettingsSelection = when {
level <= 0 -> SettingsSelection()
level == 1 -> selection.copy(pane = SettingsPane.Gallery, templateKey = null)
else -> selection
}
/**
* Encodes a [SettingsSelection] as Bundle-able primitives. Paired with
* [decodeSettingsSelection].
*/
internal fun encodeSettingsSelection(selection: SettingsSelection): List<Any> =
listOf(selection.pane.name, selection.templateKey ?: "")
/** Restores a [SettingsSelection] encoded by [encodeSettingsSelection]. */
internal fun decodeSettingsSelection(encoded: List<Any>): SettingsSelection = SettingsSelection(
pane = SettingsPane.valueOf(encoded[0] as String),
templateKey = (encoded[1] as String).takeIf { it.isNotEmpty() },
)
/** Saves/restores a [SettingsSelection] across configuration change and process death. */
internal val SettingsSelectionSaver: Saver<SettingsSelection, List<Any>> = Saver(
save = { encodeSettingsSelection(it) },
restore = { decodeSettingsSelection(it) },
)
@@ -1,77 +0,0 @@
package net.awan.pipelines.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Widgets
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.ui.components.galleryGrid
/**
* The Templates surface's own glyph (the destination pill's icon and a covered
* pane's compact identity), deliberately a gallery/grid glyph rather than the
* Pipelines destination's workflow tree.
*/
internal val TemplatesIcon: ImageVector = Icons.Filled.Widgets
/**
* One server template plus the graph the server parsed from its source (null when
* the source could not be parsed, or the server does not answer `validate`). The
* gallery and the detail view both read this one entry, so a card's stage count
* and the detail's stage list/graph can never disagree.
*/
data class TemplateEntry(
val key: String,
val name: String,
val description: String,
val source: String,
val scheduled: Boolean,
val graph: Graph?,
)
/**
* One gallery card's content: the template's name and description (from the
* catalog) and its stage count (from the graph parsed out of the source; null
* when the source could not be parsed, so the card says so rather than claiming
* zero stages). Pure, so the mapping is unit-tested without a device.
*/
internal data class TemplateCard(
val key: String,
val name: String,
val description: String,
val stageCount: Int?,
)
/** The card content for [entry]: name/description from the catalog, count from the parsed source. */
internal fun templateCard(entry: TemplateEntry): TemplateCard =
TemplateCard(
key = entry.key,
name = entry.name,
description = entry.description,
stageCount = entry.graph?.stages?.size,
)
/**
* How many columns the templates gallery lays out at a given window: a single
* column on a narrow window (the list form) and, on a wide one, as many
* [preferred]-width cards as fit [availableWidth] with their [spacing] gaps —
* the shared [galleryGrid] fitting, so the gallery widens by adding columns
* rather than stretching cards. Pure, so the grid/list decision is unit-tested
* without a device.
*/
internal fun templateGridColumns(
wide: Boolean,
availableWidth: Dp,
preferred: Dp,
spacing: Dp,
): Int = if (!wide) 1 else galleryGrid(availableWidth, preferred, spacing).columns
/**
* The card's stage-count line: the count from the parsed source, or an explicit
* "unavailable" when the source could not be parsed (never "0 stages", which
* would claim a count the app does not have). Pure, so it is unit-tested.
*/
internal fun templateStageCountLabel(stageCount: Int?): String = when (stageCount) {
null -> "stage count unavailable"
else -> stageCountText(stageCount)
}
@@ -1,16 +0,0 @@
package net.awan.pipelines.ui
/**
* Window-width breakpoint (dp) between the narrow single-pane and the wide
* list-and-detail layout. A foldable's cover display (~400dp) stays narrow while
* the inner display (~700-800dp and up) is wide.
*
* Kept as a pure predicate so the decision is unit-testable and no screen has to
* hardcode device numbers; composables read the live width from
* `LocalConfiguration.current.screenWidthDp` so it follows window-size changes
* without any new listener or dependency.
*/
const val WIDE_LAYOUT_MIN_WIDTH_DP = 600
/** True when [widthDp] is wide enough for the two-pane / side-rail layout. */
fun isWideLayout(widthDp: Int): Boolean = widthDp >= WIDE_LAYOUT_MIN_WIDTH_DP
@@ -1,512 +0,0 @@
package net.awan.pipelines.ui.changes
import android.view.WindowManager
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsPadding
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.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.QuestionMark
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import net.awan.pipelines.ui.chat.DiffKind
import net.awan.pipelines.ui.chat.diffLineColor
import net.awan.pipelines.ui.chat.diffLineSymbol
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusPalette
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The run summary's Changes section body: the observed-file list plus the honest
* capture notes. It is a non-lazy [Column] of rows so it nests safely inside the
* summary's single `LazyColumn` (the artifacts gallery does the same), and it
* renders the same [ChangeFileRow] for every file, tapping any row open into
* [ChangeDiffViewer].
*
* The whole section is read-only evidence of the workspace the run changed; the
* wording never claims the model authored a change.
*/
@Composable
internal fun ChangeFileList(
changes: RunChanges,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
var openIndex by remember(changes) { mutableStateOf(NO_OPEN_FILE) }
Column(
modifier = modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_S),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Text(changesListSummary(changes), style = text.label, color = MaterialTheme.colorScheme.primary)
val note = runChangesNote(changes)
if (note.isNotBlank()) Text(note, style = text.meta)
if (changes.isEmpty) {
Text(noChangeDetail(changes), style = text.meta)
} else {
Column(Modifier.fillMaxWidth()) {
changes.files.forEachIndexed { index, entry ->
ChangeFileRow(entry = entry, onClick = { openIndex = index })
}
}
}
}
if (openIndex in changes.files.indices) {
ChangeDiffViewer(
files = changes.files,
index = openIndex,
onIndexChange = { openIndex = it },
onDismiss = { openIndex = NO_OPEN_FILE },
)
}
}
/** No file is open in the changes viewer. */
private const val NO_OPEN_FILE = -1
/** Why no change is listed: a pending capture, an unavailable one, or a recorded none. */
private fun noChangeDetail(changes: RunChanges): String = when {
changes.pending -> "The capture runs after the stage finishes; nothing is recorded yet."
changes.unavailable -> "The workspace snapshot could not be compared, so no changes can be shown."
changes.stepsWithChanges == 0 ->
"This run recorded no change capture (a historical step, or a stage that does not capture)."
else -> "The captured snapshots were identical: the workspace was unchanged."
}
/**
* One file in the changes list: a kind glyph, the path in monospace, the `+N -M`
* stat, the read-me-first tags, and the stage(s) that changed it. Tapping opens
* the diff viewer on this file, whose location is confirmed by its position there.
*/
@Composable
private fun ChangeFileRow(entry: FileChangeEntry, onClick: () -> Unit) {
val text = pipelinesText()
val stat = changeStat(entry.added, entry.removed)
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(role = Role.Button, onClick = onClick, onClickLabel = "Open ${entry.path}")
.padding(vertical = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Icon(
imageVector = changeKindIcon(entry.kind),
contentDescription = changeKindLabel(entry.kind),
tint = changeKindTint(entry.kind),
modifier = Modifier.size(ICON_INLINE_DP),
)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) {
Text(
entry.path,
style = text.mono,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(changeRowMeta(entry), style = text.meta, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (stat.isNotBlank()) {
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
if (entry.added > 0) StatText("+${entry.added}", RunStatusPalette.of(RunState.Succeeded).color)
if (entry.removed > 0) StatText("-${entry.removed}", RunStatusPalette.of(RunState.Failed).color)
}
}
}
}
/** The row's secondary line: which stage(s) changed it, and how to read the entry. */
internal fun changeRowMeta(entry: FileChangeEntry): String = buildString {
append("changed by ")
append(entry.steps.joinToString(" → "))
changeEntryTags(entry).forEach { append(" · $it") }
if (entry.modeChanged && !entry.binary) {
append(" · mode ${entry.beforeMode.orEmpty()}→${entry.afterMode.orEmpty()}")
}
}
/** One side of a file's stat, monospace in the app's success/failure hue. */
@Composable
private fun StatText(value: String, color: Color) {
Text(
text = value,
style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace),
color = color,
)
}
/** The glyph for a file's recorded kind, so the list reads at a glance. */
internal fun changeKindIcon(kind: ChangeKind): ImageVector = when (kind) {
ChangeKind.Added -> Icons.Default.Add
ChangeKind.Modified -> Icons.Default.Edit
ChangeKind.Deleted -> Icons.Default.Delete
ChangeKind.Other -> Icons.Default.QuestionMark
}
/** The tint for a file's kind: added green, deleted red, anything else neutral. */
@Composable
private fun changeKindTint(kind: ChangeKind): Color = when (kind) {
ChangeKind.Added -> RunStatusPalette.of(RunState.Succeeded).color
ChangeKind.Deleted -> RunStatusPalette.of(RunState.Failed).color
else -> MaterialTheme.colorScheme.onSurfaceVariant
}
/** The two forms one file's change can be read in. */
private enum class ChangeViewForm { Rendered, Raw }
/**
* The full-screen diff viewer for one changed file. It pages through the run's
* changed files exactly as the artifact viewer pages through a gallery's media
* (one shared index, previous/next affordances, Back/the close button dismissing),
* and it shows both forms the brief requires, switchable from one control row:
*
* - **Rendered** — the file header with its `+N -M` stat, then each hunk's `@@`
* header, the added/removed/context colouring and the old/new line numbers,
* through the app's one diff language.
* - **Raw patch** — the server's unified patch verbatim in monospace, so the
* operator can read the exact evidence alongside the rendered reading.
*
* A file the server could not give a patch for (binary, truncated, or a capture
* that recorded none) shows the honest reason in place of a diff rather than a
* fabricated one. Nothing here claims authorship: it reports the workspace change
* the server observed.
*/
@Composable
internal fun ChangeDiffViewer(
files: List<FileChangeEntry>,
index: Int,
onIndexChange: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val entry = files.getOrNull(index) ?: return
var form by remember(entry.path) { mutableStateOf(ChangeViewForm.Rendered) }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
) {
// Stretch the dialog window over the whole display (behind the status bar
// and navigation bar), exactly as the artifact viewer does. Without a
// bounded window height a weighted child measures its full content and
// pushes the page row off-screen; MATCH_PARENT gives the body the space
// that remains, so the header, the form switch, the diff body and the
// page controls are all on screen.
val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window
SideEffect {
dialogWindow?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
)
}
Box(Modifier.fillMaxSize().windowInsetsPadding(paneSafeArea())) {
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
) {
ChangeViewerHeader(entry = entry, index = index, count = files.size, onDismiss = onDismiss)
// The form switch and the file pager share one control row: the
// Rendered/Raw choice on the left, the previous/next file
// affordances on the right, so moving between files never depends
// on the diff body's height.
ChangeViewerControls(
entry = entry,
form = form,
onSelect = { form = it },
hasPrevious = index > 0,
hasNext = index < files.lastIndex,
onPrevious = { onIndexChange((index - 1).coerceAtLeast(0)) },
onNext = { onIndexChange((index + 1).coerceAtMost(files.lastIndex)) },
)
ChangeViewerBody(
entry = entry,
form = form,
modifier = Modifier.weight(1f),
)
}
}
}
}
/** The open file: its kind, path, stat, position, stages and the close affordance. */
@Composable
private fun ChangeViewerHeader(
entry: FileChangeEntry,
index: Int,
count: Int,
onDismiss: () -> Unit,
) {
val text = pipelinesText()
val clipboard = LocalClipboardManager.current
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_M),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Icon(
imageVector = changeKindIcon(entry.kind),
contentDescription = null,
tint = changeKindTint(entry.kind),
modifier = Modifier.size(ICON_INLINE_DP),
)
Text(
changeKindLabel(entry.kind).replaceFirstChar { it.uppercase() },
style = text.label,
color = changeKindTint(entry.kind),
)
if (changeStat(entry.added, entry.removed).isNotBlank()) {
Text(changeStat(entry.added, entry.removed), style = text.mono)
}
}
Text(entry.path, style = text.mono, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(
"${changePositionLabel(index, count)} · changed by ${entry.steps.joinToString(" → ")}",
style = text.meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(
onClick = { entry.patch?.takeIf { it.isNotBlank() }?.let { clipboard.copyText(it) } },
enabled = !entry.patch.isNullOrBlank(),
) {
Icon(Icons.Default.ContentCopy, contentDescription = "Copy raw patch for ${entry.path}")
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Close diff")
}
}
}
/**
* The Rendered/Raw switch and the file pager in one control row: each form is a
* labelled control whose selected form is disabled and emphasised, so the
* operator can always see which reading is open, and the previous/next
* affordances page through the run's changed files, disabled exactly at the ends.
* Keeping the pager in this row (rather than a bottom band) means moving between
* files never depends on the diff body's height.
*/
@Composable
private fun ChangeViewerControls(
entry: FileChangeEntry,
form: ChangeViewForm,
onSelect: (ChangeViewForm) -> Unit,
hasPrevious: Boolean,
hasNext: Boolean,
onPrevious: () -> Unit,
onNext: () -> Unit,
) {
val text = pipelinesText()
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
TextButton(onClick = { onSelect(ChangeViewForm.Rendered) }, enabled = form != ChangeViewForm.Rendered) {
Text("Rendered", style = if (form == ChangeViewForm.Rendered) text.body else text.label)
}
TextButton(
onClick = { onSelect(ChangeViewForm.Raw) },
enabled = !entry.patch.isNullOrBlank(),
) {
Text("Raw patch", style = if (form == ChangeViewForm.Raw) text.body else text.label)
}
Spacer(Modifier.weight(1f))
IconButton(onClick = onPrevious, enabled = hasPrevious) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Previous file")
}
IconButton(onClick = onNext, enabled = hasNext) {
Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = "Next file")
}
}
}
/** The open file's body in the chosen form, or the honest reason a diff cannot be shown. */
@Composable
private fun ChangeViewerBody(entry: FileChangeEntry, form: ChangeViewForm, modifier: Modifier = Modifier) {
when {
entry.binary || entry.patch.isNullOrBlank() -> HonestMessage(
if (entry.binary) {
"This is a binary file: the server recorded the change but has no textual diff to show."
} else {
patchUnavailableReason(entry)
},
modifier,
)
form == ChangeViewForm.Raw -> Column(
modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(SPACING_L),
) {
Text(entry.patch.orEmpty(), style = pipelinesText().mono, modifier = Modifier.fillMaxWidth())
}
else -> Column(
modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_M),
) {
val parsed = remember(entry.patch) { parseUnifiedPatch(entry.patch) }
ChangeDiffStat(parsed)
if (entry.truncated) {
Text(
"The server truncated this patch at its capture limit; the raw text is the whole record.",
style = pipelinesText().meta,
)
}
parsed.hunks.forEach { hunk -> HunkView(hunk) }
}
}
}
/** A centred honest explanation where a diff cannot be rendered. */
@Composable
private fun HonestMessage(message: String, modifier: Modifier = Modifier) {
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(message, style = pipelinesText().meta, modifier = Modifier.padding(SPACING_XL))
}
}
/** Why a file has no patch to render, in the entry's own recorded terms. */
internal fun patchUnavailableReason(entry: FileChangeEntry): String = when {
entry.truncated -> "The server truncated this file's patch at its capture limit; no diff text was recorded."
entry.otherModeChange ->
"Only the file's mode changed (${entry.beforeMode.orEmpty()}→${entry.afterMode.orEmpty()}); the server recorded no text diff."
else -> "The server recorded this change without a patch."
}
/** The file's `+N -M` stat line above the rendered hunks. */
@Composable
private fun ChangeDiffStat(parsed: FileDiff) {
val text = pipelinesText()
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
if (parsed.added > 0) StatText("+${parsed.added}", RunStatusPalette.of(RunState.Succeeded).color)
if (parsed.removed > 0) StatText("-${parsed.removed}", RunStatusPalette.of(RunState.Failed).color)
if (parsed.added == 0 && parsed.removed == 0) Text("no line changes recorded", style = text.meta)
}
}
/**
* One `@@` hunk: its header, then its numbered lines. Each line is drawn with the
* app's shared diff symbols and colours ([diffLineSymbol]/[diffLineColor], the
* same the chat's edit card uses), preceded by its old/new gutter numbers, so the
* changes viewer and the chat diff are one renderer rather than two.
*/
@Composable
private fun HunkView(hunk: ChangeHunk) {
val text = pipelinesText()
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) {
Text(
hunk.header,
style = text.mono,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
.padding(horizontal = SPACING_XS, vertical = SPACING_XXS),
)
val gutter = remember(hunk) { gutterWidth(hunk) }
Column(
Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.horizontalScroll(rememberScrollState())
.padding(vertical = SPACING_XS),
) {
hunk.lines.forEach { line -> NumberedDiffLine(line, gutter) }
}
}
}
/** The widest line number in a hunk, so its gutter lines up across every row. */
internal fun gutterWidth(hunk: ChangeHunk): Int =
(hunk.lines.maxOfOrNull { maxOf(it.oldLine, it.newLine) } ?: 1).toString().length
/**
* One rendered diff line: the old/new gutter numbers (blank on the side a line
* has no number, and on a `\ No newline` annotation) and the marked content.
*/
@Composable
private fun NumberedDiffLine(line: ChangeLine, gutter: Int) {
val text = pipelinesText()
val kind = line.kind.toDiffKind()
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
Text(
text = if (line.noNewlineMarker) {
" ".repeat(gutter * 2 + 1)
} else {
gutterText(line.oldLine, gutter) + " " + gutterText(line.newLine, gutter)
},
style = text.meta,
maxLines = 1,
)
Text(
text = "${diffLineSymbol(kind)} ${line.text}",
style = text.mono,
color = diffLineColor(kind),
)
}
}
/** One gutter number padded to [width]; 0 means no number on that side. */
private fun gutterText(value: Int, width: Int): String =
if (value <= 0) " ".repeat(width) else value.toString().padStart(width)
/** A parsed line's kind in the app's shared diff vocabulary. */
internal fun ChangeLineKind.toDiffKind(): DiffKind = when (this) {
ChangeLineKind.Add -> DiffKind.ADD
ChangeLineKind.Remove -> DiffKind.REMOVE
ChangeLineKind.Context -> DiffKind.CONTEXT
}
@@ -1,441 +0,0 @@
package net.awan.pipelines.ui.changes
import java.util.Locale
import net.awan.pipelines.data.protocol.FileChange
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageFileChanges
/**
* The kind of observed file change the server recorded, mirroring
* `internal/protocol/runs.go` FileChange.Kind (added|modified|deleted). An
* unrecognised or blank kind stays [Other] rather than being guessed, so a
* future server value is shown read-only instead of mislabelled.
*/
enum class ChangeKind { Added, Modified, Deleted, Other }
/** Maps the server's kind token to [ChangeKind]; never invents one. Pure. */
internal fun changeKind(kind: String): ChangeKind = when (kind.trim().lowercase(Locale.US)) {
"added" -> ChangeKind.Added
"modified" -> ChangeKind.Modified
"deleted" -> ChangeKind.Deleted
else -> ChangeKind.Other
}
/** The word a file's kind is named by in the list and the diff header. */
internal fun changeKindLabel(kind: ChangeKind): String = when (kind) {
ChangeKind.Added -> "added"
ChangeKind.Modified -> "modified"
ChangeKind.Deleted -> "deleted"
ChangeKind.Other -> "changed"
}
/** Which kind of line this is within a unified patch. */
enum class ChangeLineKind { Context, Add, Remove }
/**
* One line of a parsed unified patch, with the old/new line numbers a rendered
* diff gutter shows (0 where the line has no number on that side: an added line
* has no old number, a removed line no new one, a `\ No newline` marker neither).
* [text] is the line's content without its leading marker; [noNewlineMarker] marks
* the `\ No newline at end of file` annotation so a renderer draws no numbers for
* it.
*/
internal data class ChangeLine(
val kind: ChangeLineKind,
val text: String,
val oldLine: Int = 0,
val newLine: Int = 0,
val noNewlineMarker: Boolean = false,
)
/** One `@@` hunk: the server's own header plus its parsed lines. */
internal data class ChangeHunk(
val header: String,
val oldStart: Int,
val oldCount: Int,
val newStart: Int,
val newCount: Int,
val lines: List<ChangeLine>,
)
/**
* A parsed unified patch for one file: the raw text exactly as the server
* recorded it ([raw], the thing the raw view shows verbatim), the file header
* lines the patch carried, the parsed [hunks], and the true `+N -M` stat counted
* from the hunk body (never from the header text, so a relocated header cannot
* misstate the change).
*/
internal data class FileDiff(
val raw: String,
val headerLines: List<String>,
val hunks: List<ChangeHunk>,
val added: Int,
val removed: Int,
)
/**
* Parses a server-recorded unified patch into hunks, lines, line numbers and
* the true `+N -M` stat. The server builds these patches with a Go unified-diff
* writer (internal/filediff), so the shape is a standard `---`/`+++` header,
* optional metadata lines, `@@ -a,b +c,d @@` hunk headers and a ` `/`+`/`-`
* body. Anything unrecognised (a truncated tail, an exotic header) is carried
* verbatim in [FileDiff.headerLines] when it sits before the first hunk, and
* otherwise skipped, so the raw view always has the exact source while the
* rendered view shows only lines it can stand behind. A blank patch parses to an
* empty [FileDiff] rather than a fabricated one.
*/
internal fun parseUnifiedPatch(patch: String?): FileDiff {
val text = patch.orEmpty()
if (text.isBlank()) return FileDiff(raw = "", headerLines = emptyList(), hunks = emptyList(), added = 0, removed = 0)
val rawLines = text.split("\n")
val headers = ArrayList<String>()
val hunks = ArrayList<ChangeHunk>()
var current: HunkBuilder? = null
for (line in rawLines) {
val hunkStart = parseHunkHeader(line)
when {
hunkStart != null -> {
current?.let { hunks += it.build() }
current = HunkBuilder(line, hunkStart.oldStart, hunkStart.oldCount, hunkStart.newStart, hunkStart.newCount)
}
// An aggregated entry can contain one complete patch from each
// contributing stage. A new file header closes the preceding hunk
// instead of being rendered as an unnumbered context line in it.
line.startsWith("--- ") || line.startsWith("+++ ") -> {
current?.let {
hunks += it.build()
current = null
}
headers += line
}
current == null -> headers += line
else -> current.lines += parseBodyLine(line, current)
}
}
current?.let { hunks += it.build() }
val added = hunks.sumOf { hunk -> hunk.lines.count { it.kind == ChangeLineKind.Add } }
val removed = hunks.sumOf { hunk -> hunk.lines.count { it.kind == ChangeLineKind.Remove } }
return FileDiff(raw = text, headerLines = headers, hunks = hunks, added = added, removed = removed)
}
/**
* Mutable accumulator for one hunk as it is parsed, carrying the running old/new
* line counters so each body line gets its gutter numbers without a second pass.
*/
private class HunkBuilder(
val header: String,
val oldStart: Int,
val oldCount: Int,
val newStart: Int,
val newCount: Int,
) {
val lines = ArrayList<ChangeLine>()
private var oldLine = oldStart
private var newLine = newStart
fun build(): ChangeHunk = ChangeHunk(
header = header,
oldStart = oldStart,
oldCount = oldCount,
newStart = newStart,
newCount = newCount,
lines = lines,
)
fun nextOld(): Int = oldLine++
fun nextNew(): Int = newLine++
}
/**
* The parsed `@@ -oldStart,oldCount +newStart,newCount @@` of a hunk header, or
* null when [line] is not one. A missing count defaults to 1 (the unified-diff
* rule) so a single-line hunk header is still read exactly. Pure.
*/
private fun parseHunkHeader(line: String): HunkStart? {
if (!line.startsWith("@@")) return null
val end = line.indexOf("@@", 2)
if (end < 0) return null
val ranges = tokenizeRanges(line.substring(2, end)) ?: return null
return HunkStart(ranges[0], ranges[1], ranges[2], ranges[3])
}
private data class HunkStart(val oldStart: Int, val oldCount: Int, val newStart: Int, val newCount: Int)
/** The four numbers of a hunk header's range text, or null when malformed. Pure. */
private fun tokenizeRanges(body: String): List<Int>? {
val old = body.substringBefore('+')
val new = body.substringAfter('+', "")
if (old.isEmpty() || new.isEmpty()) return null
val oldRange = parseRange(old) ?: return null
val newRange = parseRange(new) ?: return null
return listOf(oldRange.first, oldRange.second, newRange.first, newRange.second)
}
/** One `-start,count` / `+start,count` side of a hunk header. Pure. */
private fun parseRange(text: String): Pair<Int, Int>? {
val trimmed = text.trim().removePrefix("-").removePrefix("+")
if (trimmed.isEmpty()) return null
val start = trimmed.substringBefore(',').trim().toIntOrNull() ?: return null
val countText = trimmed.substringAfter(',', "").trim()
val count = if (countText.isEmpty()) 1 else countText.toIntOrNull() ?: return null
return start to count
}
/** One body line of a hunk, tagged and numbered from [builder]'s counters. */
private fun parseBodyLine(line: String, builder: HunkBuilder): ChangeLine = when {
line.startsWith("+") -> ChangeLine(ChangeLineKind.Add, line.substring(1), oldLine = 0, newLine = builder.nextNew())
line.startsWith("-") -> ChangeLine(ChangeLineKind.Remove, line.substring(1), oldLine = builder.nextOld(), newLine = 0)
line.startsWith("\\") -> ChangeLine(ChangeLineKind.Context, line, noNewlineMarker = true)
line.startsWith(" ") -> ChangeLine(ChangeLineKind.Context, line.substring(1), oldLine = builder.nextOld(), newLine = builder.nextNew())
line.isEmpty() -> ChangeLine(ChangeLineKind.Context, "", oldLine = builder.nextOld(), newLine = builder.nextNew())
// A truncated tail or an unexpected marker: keep the text, don't number it.
else -> ChangeLine(ChangeLineKind.Context, line)
}
/**
* One file the run changed, aggregated across the steps that changed it. A file
* touched by several steps appears once; [steps] names every stage that changed
* it (in the run's step order), so the section can say which stage(s) did.
*
* [added]/[removed] sum the patches the server actually recorded for this path.
* [binary] is true when any step recorded it as binary, [truncated] when any
* step's patch was truncated (or omitted), and [otherModeChange] when the mode
* changed without the content — all of which the viewer states plainly rather
* than rendering a diff it does not have.
*/
internal data class FileChangeEntry(
val path: String,
val kind: ChangeKind,
val added: Int,
val removed: Int,
val binary: Boolean,
val truncated: Boolean,
val beforeMode: String?,
val afterMode: String?,
val otherModeChange: Boolean,
val steps: List<String>,
val patch: String?,
) {
/** True when a patch the operator can read is present. */
val hasPatch: Boolean get() = !patch.isNullOrBlank() && !binary
/** True when the recorded permissions differ and no content change explains it. */
val modeChanged: Boolean get() = beforeMode != null && afterMode != null && beforeMode != afterMode
/** The number of stages that changed this file. */
val stepCount: Int get() = steps.size
}
/**
* The Changes disclosure's entire state, derived purely from the run's steps.
*
* It aggregates every stage step's observed `file_changes` capture: a path
* changed by several steps appears once ([files]), each carrying the stages that
* changed it, and the totals describe the recorded patches. The capture's own
* honesty flags are preserved: [unavailable] when a step's snapshot could not be
* compared, [partial] when a capture was incomplete, truncated or omitted,
* [pending] when nothing has been recorded yet, and [diagnostic] the server's own
* explanation. [status] is the one-line summary the collapsed section shows.
*/
internal data class RunChanges(
val files: List<FileChangeEntry>,
val stepsWithChanges: Int,
val stepsPending: Int,
val added: Int,
val removed: Int,
val partial: Boolean,
val unavailable: Boolean,
val pending: Boolean,
val missingCaptures: Int,
val skipped: Int,
val omitted: Int,
val diagnostic: String,
) {
val fileCount: Int get() = files.size
/** No recorded change of any kind: the section states so rather than showing an empty list. */
val isEmpty: Boolean get() = files.isEmpty()
}
/** A file is captured as binary when either side of the snapshot was binary. */
private fun binaryOf(change: FileChange): Boolean = change.binary
/**
* Aggregates a run's stage steps into its Changes state. Pure and total over its
* input: a null `file_changes` on a step is a historical (or non-capturing) step
* and contributes nothing (it is not "no changes"); a present capture with no
* files is a real, observed no-change. Files are keyed by path and keep first-seen
* order, so a path several steps changed is one entry naming all of them.
*/
internal fun runChanges(steps: List<RunStep>): RunChanges {
val entries = LinkedHashMap<String, FileChangeEntry>()
var stepsWithChanges = 0
var stepsPending = 0
var partial = false
var unavailable = false
var missingCaptures = 0
var skipped = 0
var omitted = 0
val diagnostics = LinkedHashSet<String>()
for (step in steps) {
val changes = step.fileChanges
if (changes == null) {
if (step.status == "running" || step.status == "waiting") stepsPending++
else missingCaptures++
continue
}
stepsWithChanges++
if (changes.status == "unavailable") unavailable = true
if (changes.status == "partial") partial = true
if (!changes.diagnostic.isNullOrBlank()) diagnostics += changes.diagnostic.orEmpty().trim()
skipped += changes.skipped
omitted += changes.omitted
val stage = step.stage.ifBlank { "stage" }
for (file in changes.files) {
if (file.path.isBlank()) continue
val kind = changeKind(file.kind)
val parsed = parseUnifiedPatch(file.patch)
val existing = entries[file.path]
val mergedSteps = buildList {
if (existing != null) addAll(existing.steps)
if (stage !in this) add(stage)
}
val entry = FileChangeEntry(
path = file.path,
// A later step wins the kind: it is the observed state the run left.
kind = if (existing == null || kind != ChangeKind.Other) kind else existing.kind,
added = (existing?.added ?: 0) + parsed.added,
removed = (existing?.removed ?: 0) + parsed.removed,
binary = (existing?.binary == true) || file.binary,
truncated = (existing?.truncated == true) || file.truncated,
// Keep the first-seen before-mode and the last-seen after-mode, so the
// pair describes the run's net effect on the file.
beforeMode = existing?.beforeMode ?: file.beforeMode,
afterMode = file.afterMode ?: existing?.afterMode,
otherModeChange = (existing?.otherModeChange == true) ||
(file.beforeMode != null && file.afterMode != null &&
file.beforeMode != file.afterMode && !file.binary && parsed.added == 0 && parsed.removed == 0),
steps = mergedSteps,
// Preserve every recorded textual patch for a path. A file may be
// changed by several stages, and retaining only the first one
// would make the displayed hunks disagree with the aggregate stat.
patch = listOfNotNull(existing?.patch, file.patch?.takeIf { it.isNotBlank() })
.joinToString("\n")
.takeIf { it.isNotBlank() },
)
entries[file.path] = entry
}
}
val files = entries.values.toList()
val pending = stepsWithChanges == 0 && stepsPending > 0
val totalPartial = partial || files.any { it.truncated } || omitted > 0
return RunChanges(
files = files,
stepsWithChanges = stepsWithChanges,
stepsPending = stepsPending,
added = files.sumOf { it.added },
removed = files.sumOf { it.removed },
partial = totalPartial,
unavailable = unavailable,
pending = pending,
missingCaptures = missingCaptures,
skipped = skipped,
omitted = omitted,
diagnostic = diagnostics.joinToString(" "),
)
}
/**
* The Changes section header's one-line summary: the observed file count, the
* total `+N -M`, and the honest capture caveats. Wording never implies the
* server proved authorship — it reports the workspace change it observed. A run
* with no recorded change, an unavailable capture and a still-running one each
* say exactly that rather than showing a fabricated zero.
*/
internal fun runChangesHeader(changes: RunChanges): String {
if (changes.unavailable) return "Changes · capture unavailable"
if (changes.isEmpty) {
return when {
changes.pending -> "Changes · capture pending"
changes.partial -> "Changes · partial capture"
changes.stepsWithChanges == 0 -> "Changes · not recorded for this run"
changes.missingCaptures > 0 -> "Changes · capture incomplete"
else -> "Changes · no changes observed"
}
}
val stat = changeStat(changes.added, changes.removed)
val label = if (stat.isBlank()) {
"${changes.fileCount} ${if (changes.fileCount == 1) "file" else "files"} changed"
} else {
"${changes.fileCount} ${if (changes.fileCount == 1) "file" else "files"} changed · $stat"
}
return when {
changes.partial -> "$label · partial capture"
changes.missingCaptures > 0 -> "$label · capture incomplete"
else -> label
}
}
/**
* The honest one-line note under the header for a capture that is not complete,
* or "" when the capture was. The wording distinguishes an unavailable capture, a
* partial one (with its counts) and a capture that has recorded nothing yet.
*/
internal fun runChangesNote(changes: RunChanges): String = when {
changes.unavailable -> changes.diagnostic.ifBlank {
"The workspace snapshot could not be compared; the changes below may be incomplete."
}
else -> buildString {
if (changes.partial) {
append("Partial capture: some changes may be missing.")
val caveats = ArrayList<String>()
if (changes.skipped > 0) caveats += "${changes.skipped} files skipped"
if (changes.omitted > 0) caveats += "${changes.omitted} omitted"
val truncated = changes.files.count { it.truncated }
if (truncated > 0) caveats += "$truncated truncated"
if (caveats.isNotEmpty()) append(" (" + caveats.joinToString(", ") + ")")
if (changes.diagnostic.isNotBlank()) append(" ${changes.diagnostic}")
}
if (changes.missingCaptures > 0) {
if (isNotEmpty()) append(" ")
append("Missing capture: ${changes.missingCaptures} ")
append(if (changes.missingCaptures == 1) "stage did" else "stages did")
append(" not record changes.")
}
}.trim()
}
/** The `+N -M` stat, or "" when both counts are zero. Shared by the header and a file row. */
internal fun changeStat(added: Int, removed: Int): String = buildString {
if (added > 0) append("+$added")
if (removed > 0) {
if (isNotEmpty()) append(" ")
append("-$removed")
}
}
/**
* The tags shown beside a file row: the traits that change how the entry must be
* read (binary, truncated, a mode-only change), never a fabricated diff.
*/
internal fun changeEntryTags(entry: FileChangeEntry): List<String> = buildList {
if (entry.binary) add("binary")
if (entry.truncated) add("truncated")
if (entry.otherModeChange && !entry.binary) add("mode change")
}
/**
* The file list's own summary line: the observed file count and the aggregate
* stat, with the same ambiguity-free wording as the header.
*/
internal fun changesListSummary(changes: RunChanges): String {
val count = "${changes.fileCount} ${if (changes.fileCount == 1) "file" else "files"} changed"
val stat = changeStat(changes.added, changes.removed)
return if (stat.isBlank()) count else "$count · $stat"
}
/** The `N of M` position label the viewer shows for its open file. Pure. */
internal fun changePositionLabel(index: Int, count: Int): String = "${index + 1} of $count"
@@ -1,105 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Shield
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.ui.theme.HAIRLINE_DP
import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The approval card's amber review panel and pending-card border strengths,
* echoing the reference app's 10%-alpha amber `RISK REVIEW` box.
*/
private const val RISK_REVIEW_ALPHA = 0.12f
private const val APPROVAL_PENDING_BORDER_ALPHA = 0.5f
/**
* One approval request as a card in the conversation (research §1.3 `_CodeRun` /
* risk review): the action being requested, the affected resources, the amber
* `RISK REVIEW` panel repeating the server's risk summary, and once/always/reject
* actions answered with `chat_reply`, so the server-held credentials and the tool
* never leave it. A card that is already answered or resolved keeps its place but
* drops the actions and states the outcome, so it can never offer a stale choice.
*/
@Composable
internal fun ApprovalCardItem(card: ApprovalCard, onDecision: (String) -> Unit) {
val amber = MaterialTheme.colorScheme.tertiary
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
border = if (card.actionable) BorderStroke(HAIRLINE_DP, amber.copy(alpha = APPROVAL_PENDING_BORDER_ALPHA)) else null,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_LIST_DP))
Column(Modifier.weight(1f)) {
Text(card.headline, style = pipelinesText().cardTitle)
Text(
text = card.statusLine,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (card.resources.isNotEmpty()) {
Text(
text = card.resources.joinToString("\n"),
style = pipelinesText().mono,
maxLines = 6,
overflow = TextOverflow.Ellipsis,
)
}
if (card.showRisk && card.risk.isNotBlank()) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(CHAT_ITEM_GAP))
.background(amber.copy(alpha = RISK_REVIEW_ALPHA))
.padding(CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_STATUS_DP))
Text("RISK REVIEW", style = MaterialTheme.typography.labelSmall, color = amber)
}
Text(card.risk, style = MaterialTheme.typography.bodySmall)
}
}
if (card.actionable) {
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Button(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") }
TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always allow") }
TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Reject") }
}
}
}
}
}
@@ -1,272 +0,0 @@
package net.awan.pipelines.ui.chat
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.foundation.shape.RoundedCornerShape
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.awan.pipelines.ui.humanBytes
import net.awan.pipelines.ui.theme.CHAT_ATTACHMENT_NAME_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.CHAT_ATTACHMENT_PREVIEW_DP
import net.awan.pipelines.ui.theme.CHAT_ATTACHMENT_THUMB_DP
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.SPACING_XS
/**
* The attachment surface: resolving a picked file into a [ChatAttachment], the
* local thumbnail a preview draws, and the two places an attachment is shown —
* the composer's removable chips and the file part inside a sent message's
* bubble. Geometry comes from the named tokens, so no call site writes a raw dp.
*/
/**
* Resolves one picked [uri] into the attachment the composer holds. It reads only
* the file's metadata and confirms it can be opened; the bytes are not read (and
* nothing is transmitted) until the message carrying it is sent. A file that
* cannot be queried or opened is returned with its error set rather than dropped.
*/
internal fun resolveChatAttachment(context: Context, uri: Uri): ChatAttachment {
val resolver = context.contentResolver
var name = uri.lastPathSegment.orEmpty()
var size = 0L
var readable = true
try {
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
if (c.moveToFirst()) {
val nameIndex = c.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (nameIndex >= 0 && !c.isNull(nameIndex)) name = c.getString(nameIndex)
val sizeIndex = c.getColumnIndex(OpenableColumns.SIZE)
if (sizeIndex >= 0 && !c.isNull(sizeIndex)) size = c.getLong(sizeIndex)
}
}
} catch (_: Exception) {
readable = false
}
if (readable) {
// Opening and closing proves the content is reachable without reading it.
try {
resolver.openInputStream(uri)?.close() ?: run { readable = false }
} catch (_: Exception) {
readable = false
}
}
val mime = runCatching { resolver.getType(uri) }.getOrNull().orEmpty()
return ChatAttachment(
uri = uri.toString(),
name = name,
mime = mime,
sizeBytes = size,
error = attachmentError(name, size, readable),
)
}
/** The composer's attachment strip: one removable chip per attached file. */
@Composable
internal fun ChatAttachmentStrip(
attachments: List<ChatAttachment>,
onRemove: (String) -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier.fillMaxWidth().padding(bottom = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
attachments.forEach { attachment ->
ChatAttachmentChip(attachment = attachment, onRemove = { onRemove(attachment.id) })
}
}
}
/** One attached file in the composer: its preview, its name and its remove action. */
@Composable
private fun ChatAttachmentChip(attachment: ChatAttachment, onRemove: () -> Unit) {
val failed = attachment.error != null
Surface(
shape = RoundedCornerShape(CHAT_ITEM_GAP),
color = if (failed) {
MaterialTheme.colorScheme.errorContainer
} else {
MaterialTheme.colorScheme.surfaceContainerHigh
},
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.padding(start = CHAT_ITEM_GAP, top = SPACING_XS, end = SPACING_XXS, bottom = SPACING_XS),
) {
AttachmentThumb(attachment, CHAT_ATTACHMENT_THUMB_DP)
Column(Modifier.widthIn(max = CHAT_ATTACHMENT_NAME_MAX_WIDTH_DP)) {
Text(
text = attachment.displayName,
style = MaterialTheme.typography.labelMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = if (failed) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSurface,
)
AttachmentMeta(attachment)
}
IconButton(onClick = onRemove, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove ${attachment.displayName}",
modifier = Modifier.size(ICON_INLINE_DP),
)
}
}
}
}
/** The chip's second line: why it cannot go, or how big it is. */
@Composable
private fun AttachmentMeta(attachment: ChatAttachment) {
val error = attachment.error
if (error != null) {
Text(
text = error,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
} else if (attachment.sizeBytes > 0) {
Text(
text = humanBytes(attachment.sizeBytes),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
}
}
/** An attached file inside the sent message's bubble: the same part the transcript renders. */
@Composable
internal fun FilePart(part: net.awan.pipelines.data.protocol.ChatPart) {
val attachment = ChatAttachment(uri = part.uri, name = part.name, mime = part.mime)
if (attachment.isImage) {
AttachmentThumb(attachment, CHAT_ATTACHMENT_PREVIEW_DP)
} else {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
Box(Modifier.size(ICON_LIST_DP), contentAlignment = Alignment.Center) {
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, contentDescription = null)
}
Text(
text = attachment.displayName,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
/** A square preview: the decoded thumbnail for an image, a glyph for anything else. */
@Composable
private fun AttachmentThumb(attachment: ChatAttachment, size: Dp) {
val shape = RoundedCornerShape(SPACING_XXS)
if (attachment.isImage) {
val bitmap = rememberLocalThumbnail(attachment.uri, size)
if (bitmap != null) {
Image(
bitmap = bitmap,
contentDescription = attachment.displayName,
contentScale = ContentScale.Crop,
modifier = Modifier.size(size).clip(shape),
)
} else {
Box(
modifier = Modifier.size(size).clip(shape).background(MaterialTheme.colorScheme.surfaceContainerHighest),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Default.Image, contentDescription = "Image preview", modifier = Modifier.size(ICON_INLINE_DP))
}
}
} else {
Box(Modifier.size(size), contentAlignment = Alignment.Center) {
Icon(
Icons.AutoMirrored.Filled.InsertDriveFile,
contentDescription = null,
modifier = Modifier.size(ICON_INLINE_DP),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/**
* Decodes a local content URI to roughly [size] on the longest edge, off the main
* thread. Null while loading or when the file is not a decodable image, so the
* caller falls back to a glyph instead of showing a broken frame.
*/
@Composable
private fun rememberLocalThumbnail(uri: String, size: Dp): ImageBitmap? {
val context = LocalContext.current
val maxDim = with(LocalDensity.current) { size.roundToPx() }
var bitmap by remember(uri, maxDim) { mutableStateOf<ImageBitmap?>(null) }
LaunchedEffect(uri, maxDim) {
bitmap = withContext(Dispatchers.IO) { decodeLocalThumbnail(context, uri, maxDim) }
}
return bitmap
}
/** Decodes [uri] at or below [maxDim] on its longest edge; null on any failure. */
private fun decodeLocalThumbnail(context: Context, uri: String, maxDim: Int): ImageBitmap? = try {
val resolver = context.contentResolver
val parsed = Uri.parse(uri)
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
resolver.openInputStream(parsed)?.use { BitmapFactory.decodeStream(it, null, bounds) }
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
null
} else {
var sample = 1
while (bounds.outWidth / sample > maxDim || bounds.outHeight / sample > maxDim) {
sample *= 2
}
val options = BitmapFactory.Options().apply { inSampleSize = sample }
resolver.openInputStream(parsed)?.use { BitmapFactory.decodeStream(it, null, options)?.asImageBitmap() }
}
} catch (_: Exception) {
null
}
@@ -1,154 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.minimumInteractiveComponentSize
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.semantics.Role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.text.style.TextOverflow
import net.awan.pipelines.ui.theme.CHAT_COMMAND_LIST_MAX_HEIGHT
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The slash-command offer list, shown above the composer while the draft is a
* bare command word. Each row names the command and says in a few words what it
* does; the highlighted row is the one Enter runs, and a tap runs a row directly.
* It is capped and scrolls rather than growing without bound over the transcript.
*/
@Composable
internal fun ChatCommandSuggestions(
commands: List<ChatCommand>,
selectedIndex: Int,
onPick: (ChatCommand) -> Unit,
modifier: Modifier = Modifier,
) {
if (commands.isEmpty()) return
Surface(
color = MaterialTheme.colorScheme.surfaceContainerHigh,
shape = MaterialTheme.shapes.medium,
modifier = modifier.fillMaxWidth().heightIn(max = CHAT_COMMAND_LIST_MAX_HEIGHT),
) {
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
commands.forEachIndexed { index, command ->
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
modifier = Modifier
.fillMaxWidth()
.background(
if (index == selectedIndex) {
MaterialTheme.colorScheme.secondaryContainer
} else {
Color.Transparent
},
)
.minimumInteractiveComponentSize()
// The highlight is also reported to assistive tech, so the
// row Enter runs is not conveyed by colour alone.
.semantics { selected = index == selectedIndex }
.clickable(role = Role.Button) { onPick(command) }
.padding(horizontal = SPACING_M, vertical = SPACING_S),
) {
Text(
text = "/" + command.name,
style = pipelinesText().cardTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = command.summary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
}
}
}
}
/**
* One local command line in the transcript. It is deliberately unlike a message
* bubble: full width, a `Command` label and a terminal glyph, and a container
* that turns to the error colour when the command could not be honoured. An
* unrecognised command keeps the operator's draft as an offer — send it as a
* message or cancel — so a typo never becomes a prompt on its own.
*/
@Composable
internal fun ChatCommandNoticeItem(
notice: ChatCommandNotice,
onSendAsMessage: () -> Unit,
onDismiss: () -> Unit,
) {
val container = if (notice.failed) {
MaterialTheme.colorScheme.errorContainer
} else {
MaterialTheme.colorScheme.surfaceContainerHigh
}
val content = if (notice.failed) {
MaterialTheme.colorScheme.onErrorContainer
} else {
MaterialTheme.colorScheme.onSurface
}
Surface(
color = container,
shape = MaterialTheme.shapes.medium,
modifier = Modifier.fillMaxWidth(),
) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Icon(
Icons.Default.Terminal,
contentDescription = null,
tint = content,
modifier = Modifier.size(ICON_INLINE_DP),
)
Text(
text = if (notice.failed) "Command failed" else "Command",
style = MaterialTheme.typography.labelMedium,
color = content,
)
}
Text(text = notice.text, style = MaterialTheme.typography.bodySmall, color = content)
if (notice.offer != null) {
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
TextButton(onClick = onSendAsMessage) { Text("Send as message") }
TextButton(onClick = onDismiss) { Text("Cancel") }
}
}
}
}
}
@@ -1,213 +0,0 @@
package net.awan.pipelines.ui.chat
/**
* One command the composer understands. [name] is the word after the slash,
* [usage] is what the operator types (including any argument) and [summary] is
* the few-word description the offer list shows beside it. [takesArgument] is
* false for the commands that act on the current session alone, so a stray
* argument is reported instead of being silently ignored.
*/
internal data class ChatCommand(
val name: String,
val summary: String,
val usage: String,
val takesArgument: Boolean = false,
)
internal const val CHAT_COMMAND_NEW = "new"
internal const val CHAT_COMMAND_CLOSE = "close"
internal const val CHAT_COMMAND_RENAME = "rename"
internal const val CHAT_COMMAND_STOP = "stop"
internal const val CHAT_COMMAND_HELP = "help"
/**
* The commands offered by the composer, in the order the list shows them. The
* terminal's own vocabulary is the model here (`:status`, `:logs`, …): a command
* acts on the chat surface itself and is never sent to the agent.
*
* `/close` is the server's own close (`chat_close`, shared by every client), not
* the local "remove from list": the chat is finished for every device, its
* history is kept, and it can be reopened.
*/
internal val CHAT_COMMANDS: List<ChatCommand> = listOf(
ChatCommand(CHAT_COMMAND_NEW, "Start a fresh session in this directory", "/new"),
ChatCommand(
CHAT_COMMAND_CLOSE,
"Finish this session for every client, keeping its history",
"/close",
),
ChatCommand(CHAT_COMMAND_RENAME, "Rename this session on this device", "/rename <title>", takesArgument = true),
ChatCommand(CHAT_COMMAND_STOP, "Stop the turn that is running", "/stop"),
ChatCommand(CHAT_COMMAND_HELP, "List every command", "/help"),
)
/**
* What the composer's draft parses to. [Plain] is any text that is not a slash
* command and follows the ordinary send path. [Unknown] is a draft that starts
* with a slash but names no command: it must never be sent as a prompt without
* the operator explicitly choosing to, so [text] is carried verbatim.
*/
internal sealed interface ChatInput {
data object Plain : ChatInput
data class Invocation(val command: ChatCommand, val argument: String) : ChatInput
data class Unknown(val text: String, val token: String) : ChatInput
}
/**
* Parses [text] as a slash command. Only the start of the draft counts, the
* command word is the run of non-space characters after the slash, and the rest
* (trimmed) is its argument. Recognition is case-insensitive; the returned
* command is always the canonical entry from [CHAT_COMMANDS].
*/
internal fun parseChatInput(text: String): ChatInput {
val trimmed = text.trim()
if (!trimmed.startsWith("/")) return ChatInput.Plain
val token = trimmed.takeWhile { !it.isWhitespace() }
val argument = trimmed.drop(token.length).trim()
val name = token.removePrefix("/")
val command = CHAT_COMMANDS.firstOrNull { it.name.equals(name, ignoreCase = true) }
?: return ChatInput.Unknown(text = trimmed, token = token)
return ChatInput.Invocation(command = command, argument = argument)
}
/**
* The commands the offer list shows for [draft]: every command after a bare `/`,
* narrowed by the command word as the operator keeps typing. The list is for the
* command word only, so once an argument begins (a space follows the word) it
* hides and the draft is executed as typed. Text that does not start with a
* slash offers nothing.
*/
internal fun chatCommandSuggestions(draft: String): List<ChatCommand> {
val trimmed = draft.trimStart()
if (!trimmed.startsWith("/")) return emptyList()
if (trimmed.any { it.isWhitespace() }) return emptyList()
val query = trimmed.drop(1)
return CHAT_COMMANDS.filter { it.name.startsWith(query, ignoreCase = true) }
}
/**
* The command text Enter runs for [draft] while the offer list is showing. The
* list's highlighted entry wins, so a partially typed word (`/clo`) is runnable
* with Enter without also being sent as a prompt; the caller clamps [selected]
* to the list. Returns null when no list is showing, which is when the ordinary
* send path applies.
*/
internal fun chatCommandForEnter(draft: String, selected: Int): String? {
val suggestions = chatCommandSuggestions(draft)
if (suggestions.isEmpty()) return null
val command = suggestions.getOrNull(selected) ?: suggestions.first()
return "/" + command.name
}
/** The `/help` reply: every command with its usage and what it does. */
internal fun chatCommandHelp(): String =
CHAT_COMMANDS.joinToString("\n") { "${it.usage} — ${it.summary}" }
/**
* What a parsed invocation asks the chat surface to do. Kept separate from the
* side effects so the routing (which command is available, which one needs an
* argument, which argument it receives) is unit-testable without a server.
*/
internal sealed interface ChatCommandEffect {
/** Create a fresh session in [directory] and switch to it. */
data class StartSession(val directory: String) : ChatCommandEffect
/** Finish the current session for every client. */
data object FinishSession : ChatCommandEffect
/** Rename the current session to [title] (the device's own rename today). */
data class RenameSession(val title: String) : ChatCommandEffect
/** Interrupt the session's running turn. */
data object StopTurn : ChatCommandEffect
/** Show the command list in the transcript. */
data object ShowHelp : ChatCommandEffect
/**
* A command that cannot act as asked; [text] says why. [offer] is set for an
* unknown command and carries the operator's draft, so the transcript can
* offer to send it as a message instead — the one way it reaches the agent.
*/
data class Report(val text: String, val offer: String? = null) : ChatCommandEffect
}
/**
* Routes parsed [input] to one effect. [thread] supplies the current session's
* directory (which `/new` must reuse) and whether a turn is running (which
* `/stop` needs). A null result is text that is not a command at all.
*/
internal fun chatCommandEffect(input: ChatInput, thread: ChatThread): ChatCommandEffect? = when (input) {
ChatInput.Plain -> null
is ChatInput.Unknown -> ChatCommandEffect.Report(
"“${input.token}” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.",
offer = input.text,
)
is ChatInput.Invocation -> {
val command = input.command
if (!command.takesArgument && input.argument.isNotBlank()) {
ChatCommandEffect.Report("${command.usage} does not take an argument.")
} else {
when (command.name) {
CHAT_COMMAND_NEW ->
if (thread.directory.isBlank()) {
ChatCommandEffect.Report(
"Can't start a new session here: the server reported no directory for this chat.",
)
} else {
ChatCommandEffect.StartSession(thread.directory)
}
CHAT_COMMAND_CLOSE -> ChatCommandEffect.FinishSession
CHAT_COMMAND_RENAME ->
if (input.argument.isBlank()) {
ChatCommandEffect.Report(
"Usage: ${command.usage} — renames this session on this device.",
)
} else {
ChatCommandEffect.RenameSession(input.argument)
}
CHAT_COMMAND_STOP ->
if (thread.running) {
ChatCommandEffect.StopTurn
} else {
ChatCommandEffect.Report("No turn is running in this chat.")
}
CHAT_COMMAND_HELP -> ChatCommandEffect.ShowHelp
else -> ChatCommandEffect.Report("“/${command.name}” is not a command.")
}
}
}
}
/**
* The effects the chat surface actually performs. [notify] appends a local
* command line to the transcript; it is not a prompt, so nothing here reaches
* the agent unless the operator explicitly sends an unknown command as a
* message from its offer.
*/
internal interface ChatCommandHost {
fun startSession(directory: String)
fun finishSession()
fun renameSession(title: String)
fun stopTurn()
fun notify(text: String, failed: Boolean = false, offer: String? = null)
}
/**
* Runs [text] against the current [thread] through [host]. A draft that starts
* with a slash is always consumed here (the caller clears it) and is never
* handed to the prompt path; an unknown command becomes an offer the operator
* must answer, and an argument-less command rejects extra words instead of
* guessing what they meant.
*/
internal fun runChatSlashCommand(text: String, thread: ChatThread, host: ChatCommandHost) {
when (val effect = chatCommandEffect(parseChatInput(text), thread)) {
null -> Unit
is ChatCommandEffect.StartSession -> host.startSession(effect.directory)
ChatCommandEffect.FinishSession -> host.finishSession()
is ChatCommandEffect.RenameSession -> host.renameSession(effect.title)
ChatCommandEffect.StopTurn -> host.stopTurn()
ChatCommandEffect.ShowHelp -> host.notify(chatCommandHelp())
is ChatCommandEffect.Report -> host.notify(effect.text, failed = true, offer = effect.offer)
}
}
@@ -1,147 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun ChatComposer(
thread: ChatThread,
onDraft: (String) -> Unit,
onAttach: (List<ChatAttachment>) -> Unit,
onRemoveAttachment: (String) -> Unit,
onSend: () -> Unit,
onStop: () -> Unit,
onRunCommand: (String) -> Unit,
) {
val action = composerAction(thread)
// The slash-command offer list follows the draft: every command after a bare
// `/`, narrowed as the operator keeps typing, hidden once an argument begins.
// The highlighted row is what Enter runs, and a tap runs a row directly, so a
// half-typed command is never sent as a prompt.
val suggestions = chatCommandSuggestions(thread.draft)
var selected by remember(thread.sessionId) { mutableIntStateOf(0) }
LaunchedEffect(suggestions) {
if (selected !in suggestions.indices) selected = 0
}
val slashDraft = thread.draft.trimStart().startsWith("/")
val submit: () -> Unit = {
val command = chatCommandForEnter(thread.draft, selected)
when {
command != null -> onRunCommand(command)
slashDraft -> onRunCommand(thread.draft)
action == ComposerAction.Send && thread.canSend -> onSend()
}
}
val context = LocalContext.current
val scope = rememberCoroutineScope()
// The platform picker: the operator chooses files and they are only resolved
// into attachments here — nothing is sent until the message is.
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isNotEmpty()) {
scope.launch {
val resolved = withContext(Dispatchers.IO) { uris.map { resolveChatAttachment(context, it) } }
onAttach(resolved)
}
}
}
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) {
if (thread.queued) {
Text(
text = "Queued — it will send when the current turn finishes.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
)
}
if (thread.attachments.isNotEmpty()) {
ChatAttachmentStrip(attachments = thread.attachments, onRemove = onRemoveAttachment)
}
ChatCommandSuggestions(
commands = suggestions,
selectedIndex = selected,
onPick = { onRunCommand("/" + it.name) },
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
)
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) {
IconButton(
onClick = { picker.launch(arrayOf("*/*")) },
) {
Icon(Icons.Default.AttachFile, contentDescription = "Attach file")
}
OutlinedTextField(
value = thread.draft,
onValueChange = onDraft,
placeholder = { Text("Message the agent… or / for commands") },
minLines = 1,
maxLines = 6,
keyboardActions = KeyboardActions(onSend = { submit() }),
// Up/Down move the highlight and Enter runs it, but only while
// the offer list is showing, so every other key — and the
// field's ordinary send action — is left untouched.
modifier = Modifier.weight(1f).onPreviewKeyEvent { event ->
if (suggestions.isEmpty()) return@onPreviewKeyEvent false
when (event.key) {
Key.DirectionDown, Key.DirectionUp -> {
if (event.type == KeyEventType.KeyDown) {
val step = if (event.key == Key.DirectionDown) 1 else -1
selected = (selected + step + suggestions.size) % suggestions.size
}
true
}
Key.Enter, Key.NumPadEnter -> {
if (event.type == KeyEventType.KeyDown) submit()
true
}
else -> false
}
},
)
when (action) {
// While a turn is in flight the send control becomes the stop
// control, so it must interrupt rather than send the draft.
ComposerAction.Stop -> IconButton(onClick = onStop) {
Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error)
}
ComposerAction.Send -> IconButton(onClick = { submit() }, enabled = thread.canSend || slashDraft) {
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
}
}
}
}
}
}
@@ -1,279 +0,0 @@
package net.awan.pipelines.ui.chat
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.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.PanTool
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Stop
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.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
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.LabelChip
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
// ---- Pane 1: the active conversation -----------------------------------------
/**
* The conversation's identity context, directly below the app bar that carries
* its title: the session kind (labelled, never a bare name), its activity and,
* when the server knows them, the directory and model. The title is not repeated
* here — this block adds only what the title cannot say.
*/
@Composable
private fun ConversationHeader(header: ConversationHeader) {
val texts = pipelinesText()
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
header.kind?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
Text(
text = header.activity,
style = texts.label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (header.context.isNotEmpty()) {
Text(
text = header.context.joinToString(" · "),
style = texts.meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ChatConversationPane(
vm: AppViewModel,
state: ChatState,
thread: ChatThread,
modifier: Modifier,
) {
val approval = approvalCard(thread.permission, thread.permissionAnswer)
val awaiting = approval?.actionable == true
// The header's one identity: the title, with the kind, activity, directory and
// model as context below it. It is built once so the app bar and the context
// line cannot disagree about the session's name.
val header = conversationHeader(thread)
// Reasoning expansion is hoisted here, not into the lazy transcript: a
// reasoning part keeps its open/closed state while the operator scrolls (and
// the item is disposed), and the state is per conversation, so a newly opened
// chat starts with every reasoning part collapsed.
var reasoning by remember(thread.sessionId) { mutableStateOf(ReasoningExpansion()) }
// A turn blocked on an approval is not generating, so the running indicator
// (and its ticking clock) stands down while the card is unanswered.
val showRunning = thread.running && !awaiting
// The count of the transcript's items: its rows (the operator's messages and
// the folded agent replies), the local command lines, the running indicator
// while a turn is in flight and a pending approval card, which is the last
// item the top bar's approval action jumps to.
val rows = transcriptRows(thread.messages)
val itemCount = rows.size + thread.notices.size +
(if (showRunning) 1 else 0) + (if (approval != null) 1 else 0)
// The position the operator left this conversation at, read once: a
// conversation with none of its own opens at its newest message instead (see
// chatOpensAtNewest), so the current turn is never hunted for.
val savedScroll = remember(thread.sessionId) { thread.scroll }
// The list state is created the moment the conversation first has content, so
// its very first measure is already at the newest item rather than at the top:
// opening a chat must not show anything else first. It is still saveable, so a
// rotation or process death keeps the operator's position.
val listState = rememberSaveable(thread.sessionId, itemCount > 0, saver = LazyListState.Saver) {
val first = chatFirstScroll(savedScroll, itemCount)
LazyListState(
firstVisibleItemIndex = first.index,
firstVisibleItemScrollOffset = first.offset,
)
}
// Persist the scroll position when the operator leaves this chat, so switching
// away and back returns them exactly where they were. Keyed on the list state,
// so the position saved is the one that was actually shown; a state that never
// held content (replaced when the conversation first loaded) saves nothing,
// leaving the conversation with no position of its own to open at its newest.
DisposableEffect(listState) {
onDispose {
if (listState.layoutInfo.totalItemsCount > 0) {
vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset)
}
}
}
val scope = rememberCoroutineScope()
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = {
// The one identity: the app bar carries the title (the value
// the context line below is built beside), and under it the
// model meta the server reports — its model, kind tag and
// directory — so what is answering is visible without leaving
// the conversation. Every part is server-reported; a blank one
// is simply omitted.
Column {
Text(
text = header.title,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val meta = chatHeaderMeta(thread)
if (meta.isNotBlank()) {
Text(
text = meta,
style = pipelinesText().meta,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
},
navigationIcon = {
IconButton(onClick = vm::showChatList) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to chats")
}
},
actions = {
if (thread.hasMore) {
IconButton(
onClick = { vm.loadOlderChatHistory(thread.sessionId) },
) {
Icon(Icons.Default.KeyboardArrowUp, contentDescription = "Load older messages")
}
}
if (awaiting) {
IconButton(
onClick = {
// The transcript's one scroll path, so a pending
// request is brought into view the same way new
// content is.
scope.launch { listState.scrollToEnd(itemCount, animated = true) }
},
) {
Icon(
Icons.Default.PanTool,
contentDescription = "Waiting for your approval",
tint = MaterialTheme.colorScheme.tertiary,
)
}
}
if (thread.running) {
IconButton(onClick = { vm.stopChat(thread.sessionId) }) {
Icon(Icons.Default.Stop, contentDescription = "Stop")
}
}
},
)
},
) { padding ->
Column(Modifier.fillMaxSize().padding(padding).imePadding()) {
ConversationHeader(header)
// Every *other* open chat is still one tap away; the active one is
// already named by the app bar, so it is not repeated here.
OpenChatStrip(
state = state,
onSelect = vm::activateChat,
onClose = vm::closeChat,
excludeSessionId = thread.sessionId,
)
Box(Modifier.weight(1f).fillMaxWidth()) {
when {
thread.loading && !thread.loaded -> LoadingState("Loading conversation…")
thread.error != null && !thread.loaded -> ErrorState(
message = thread.error,
onRetry = { vm.loadChatHistory(thread.sessionId) },
)
thread.messages.isEmpty() && thread.notices.isEmpty() && !thread.running &&
approval == null && thread.runningShells.isEmpty() ->
EmptyState(
message = "This chat has no messages yet. Ask something below.",
)
else -> ChatTranscript(
thread = thread,
rows = rows,
listState = listState,
savedScroll = savedScroll,
itemCount = itemCount,
approval = approval,
showRunning = showRunning,
reasoning = reasoning,
onToggleReasoning = { reasoning = reasoning.toggled(it) },
onDecision = { decision ->
approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) }
},
onNoticeSend = { vm.sendChatCommandOffer(thread.sessionId, it) },
onNoticeDismiss = { vm.dismissChatCommandNotice(thread.sessionId, it) },
)
}
}
// Only tasks still running are shown; the bar goes away when the last
// one ends rather than keeping a list of finished tasks on screen.
if (thread.runningShells.isNotEmpty()) {
BackgroundProcessBar(
shells = thread.runningShells,
selectedID = thread.selectedShellId,
output = thread.shellOutput,
onSelect = { vm.selectChatShell(thread.sessionId, it) },
onRefresh = { vm.refreshChatShellOutput(thread.sessionId, it) },
)
}
if (thread.error != null && thread.loaded) {
Text(
text = thread.error,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp),
)
}
ChatComposer(
thread = thread,
onDraft = { vm.updateChatDraft(thread.sessionId, it) },
onAttach = { vm.attachChatFiles(thread.sessionId, it) },
onRemoveAttachment = { vm.removeChatAttachment(thread.sessionId, it) },
onSend = { vm.sendChatPrompt(thread.sessionId) },
onStop = { vm.stopChat(thread.sessionId) },
onRunCommand = { vm.submitChatCommand(thread.sessionId, it) },
)
}
}
}
@@ -1,189 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
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.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.pillContentPadding
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.pipelinesText
// ---- The create flow: choose the directory, then create ----------------------
/**
* Where the operator starts a new chat: the server's directories, the home first
* and the recents after it, each with its full path. It is a normal pane of the
* chat stack — Back or its Cancel control leaves without creating anything — so
* starting a chat is a step in the flow rather than a modal dead end, and a
* session is never created wherever the server happens to run.
*
* The operator's home is the default; a recent is chosen with one tap, and the
* chat is created only when the operator confirms.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun NewChatPane(
vm: AppViewModel,
state: ChatState,
create: ChatCreateState,
modifier: Modifier,
) {
val choices = remember(state.directories) { directoryChoices(state.directories) }
val selected = remember(create.directory, choices) {
choices.firstOrNull { it.createDirectory == create.directory } ?: defaultDirectoryChoice(choices)
}
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = { Text("Start a chat") },
navigationIcon = {
IconButton(onClick = vm::cancelNewChat) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel new chat")
}
},
)
},
) { padding ->
Column(Modifier.fillMaxSize().padding(padding)) {
when {
state.directoriesError != null && !state.directoriesLoaded ->
ErrorState(state.directoriesError, onRetry = vm::refreshChatDirectories)
!state.directoriesLoaded -> LoadingState("Loading directories…")
else -> {
Text(
text = "Where should this chat live?",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
LazyColumn(
modifier = Modifier.weight(1f).fillMaxWidth(),
contentPadding = pillContentPadding(PaddingValues()),
) {
items(choices, key = { it.createDirectory }) { choice ->
DirectoryRow(
choice = choice,
selected = choice.createDirectory == selected?.createDirectory,
onClick = { vm.selectChatDirectory(choice.createDirectory) },
)
}
}
if (state.directoriesError != null) {
Text(
text = state.directoriesError,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
}
create.error?.let { error ->
Text(
text = error,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
}
// The brokered server exposes no request for choosing a
// session's model: chat_prompt carries model/agent fields but
// the server does not forward them, and there is no catalogue
// request to offer a choice from. So the flow says so plainly
// rather than shipping a picker that would do nothing. The
// conversation header then shows whatever model the server
// reports for the created session.
Text(
text = "This server has no request for choosing a chat's model, so a new chat uses the server's default.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
NewChatActions(
directory = selected?.createDirectory ?: create.directory,
creating = create.creating,
onCreate = vm::createNewChat,
onCancel = vm::cancelNewChat,
)
}
}
}
}
}
/** One directory the new chat can live in: the home first, then the recents. */
@Composable
private fun DirectoryRow(choice: ChatDirectoryChoice, selected: Boolean, onClick: () -> Unit) {
ListRow(selected = selected, onClick = onClick) {
Text(
text = choice.label,
style = pipelinesText().cardTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
// The home row's label is `~`, so its full path is shown beneath it; a
// recent's own label already is its full path.
choice.secondary?.let { path ->
Text(text = path, style = pipelinesText().meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
/** The create flow's footer: the chosen directory, its confirm and its cancel. */
@Composable
private fun NewChatActions(directory: String, creating: Boolean, onCreate: () -> Unit, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP),
modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER),
) {
Text(
text = "Start in $directory",
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
TextButton(onClick = onCancel, enabled = !creating) { Text("Cancel") }
Button(onClick = onCreate, enabled = !creating) {
if (creating) {
Box(contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.size(ICON_INLINE_DP), strokeWidth = 2.dp)
}
} else {
Text("New chat")
}
}
}
}
}
@@ -1,106 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusPalette
import net.awan.pipelines.ui.theme.pipelinesText
/** The `+N -M` counts, green/red monospace, exactly as the reference diff stat. */
@Composable
internal fun DiffStat(diff: ToolDiff) {
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Text(
text = "+${diff.added}",
style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace),
color = RunStatusPalette.of(RunState.Succeeded).color,
)
Text(
text = "-${diff.removed}",
style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace),
color = RunStatusPalette.of(RunState.Failed).color,
)
}
}
/**
* The gutter symbol one [DiffKind] is drawn with, the app's one spelling of the
* unified-diff marker (`+`/`-`/space). Shared by the chat's edit card and the run
* summary's changes viewer, so the two renderers never disagree about what a kind
* looks like. Pure.
*/
internal fun diffLineSymbol(kind: DiffKind): String = when (kind) {
DiffKind.ADD -> "+"
DiffKind.REMOVE -> "-"
DiffKind.CONTEXT -> " "
}
/**
* The colour one [DiffKind] is drawn in: the app's success hue for an addition,
* its failure hue for a removal and the secondary on-surface role for context.
* The one place a diff line's colour is decided, shared by every renderer.
*/
@Composable
internal fun diffLineColor(kind: DiffKind): Color = when (kind) {
DiffKind.ADD -> RunStatusPalette.of(RunState.Succeeded).color
DiffKind.REMOVE -> RunStatusPalette.of(RunState.Failed).color
DiffKind.CONTEXT -> MaterialTheme.colorScheme.onSurfaceVariant
}
/**
* The unified diff body of an edit card: line-by-line monospace with `+`/`-`
* gutter symbols and the app's success/failure hues, bounded so a long diff
* scrolls inside the card instead of pushing the transcript down.
*/
@Composable
internal fun DiffView(diff: ToolDiff) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = CODE_BLOCK_MAX_HEIGHT)
.verticalScroll(rememberScrollState())
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
) {
if (diff.omitted > 0) {
// A very large edit is summarised rather than rendered in full, so
// the card stays short and readable on a phone. The note sits first
// so the truncation is visible without scrolling to the end.
Text(
text = "… ${diff.omitted} more changed " +
(if (diff.omitted == 1) "line" else "lines") + " not shown",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
)
}
diff.lines.forEach { line ->
Text(
text = "${diffLineSymbol(line.kind)} ${line.text}",
style = pipelinesText().mono,
color = diffLineColor(line.kind),
)
}
}
}
}
@@ -1,56 +0,0 @@
package net.awan.pipelines.ui.chat
/**
* The value chat_create uses for the operator's home directory. It is the one
* literal the server documents (`~`, `~/...` and an omitted/empty value all
* resolve to the operator's home), so the home choice is sent exactly as the
* server defines it instead of relying on a locally known absolute path.
*/
const val HOME_DIRECTORY = "~"
/**
* One directory the operator can start a new chat in, derived from the server's
* `chat_directories` reply (the operator's home first, then the directories of
* previous operator sessions, most recently used first).
*
* [label] is what the row shows; [path] is the full directory, always shown so
* the operator can tell two directories apart. [createDirectory] is what
* chat_create sends: the home choice goes as [HOME_DIRECTORY] and a recent as
* its absolute path.
*/
data class ChatDirectoryChoice(
val label: String,
val path: String,
val home: Boolean,
) {
val createDirectory: String get() = if (home) HOME_DIRECTORY else path
/** The full path shown beneath the home row; a recent's own label is its path. */
val secondary: String? get() = if (home) path else null
}
/**
* The picker's choices from the server's reported directories. The first entry is
* the operator's home — the one entry the server always returns first and never
* dedupes away — and the rest keep the server's most-recently-used order. A blank
* entry is dropped, and a reply with nothing in it still yields the home choice,
* so the picker is never empty.
*/
fun directoryChoices(directories: List<String>): List<ChatDirectoryChoice> {
val cleaned = directories.filter { it.isNotBlank() }
val home = cleaned.firstOrNull() ?: HOME_DIRECTORY
return buildList {
add(ChatDirectoryChoice(label = HOME_TEXT, path = home, home = true))
cleaned.drop(1).forEach { add(ChatDirectoryChoice(label = it, path = it, home = false)) }
}
}
/**
* The choice a freshly opened picker starts on: the operator's home, first. The
* operator has to touch the picker only to change the directory, never to accept
* the default.
*/
fun defaultDirectoryChoice(choices: List<ChatDirectoryChoice>): ChatDirectoryChoice? = choices.firstOrNull()
/** The home row's label; the `~` the server accepts, named so the flow reads. */
private const val HOME_TEXT = "Home ($HOME_DIRECTORY)"
@@ -1,945 +0,0 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatShell
import net.awan.pipelines.data.protocol.ChatToolState
import net.awan.pipelines.ui.humanBytes
/**
* Pure chat formatting helpers shared by the session list and the conversation,
* so the same value is never spelled differently in two places. Kept free of
* Compose and of the transport so they are unit-testable.
*/
private val PRETTY_JSON = Json { prettyPrint = true; isLenient = true }
/**
* The INPUT section of a tool call: pretty-printed JSON once the arguments are
* an object/array, a partial-JSON string while still streaming, or the raw text
* when it cannot be parsed. Blank when there is nothing.
*/
internal fun prettyToolInput(input: JsonElement?): String = when (input) {
null -> ""
is JsonObject, is JsonArray -> PRETTY_JSON.encodeToString(JsonElement.serializer(), input)
is JsonPrimitive -> input.content
else -> input.toString()
}
/**
* The OUTPUT section of a tool call: the concatenated textual content, or the
* literal `(no output)` when the call returned nothing (mirroring jarvis), and
* an empty string while the call is still running.
*/
internal fun toolOutputText(state: ChatToolState?): String {
if (state == null) return ""
val text = state.content
.filter { it.type == "text" && it.text.isNotBlank() }
.joinToString("\n") { it.text }
if (text.isNotBlank()) return text
if (ChatProtocol.toolRunning(state)) return ""
return "(no output)"
}
/**
* The ERROR section of a failed tool call. The server's error message takes
* precedence over any partial output the call had already produced — a failed
* call can carry both, and the output text must not be labelled as the error —
* falling back to the output text so the block is never blank when the failure
* carries no message.
*/
internal fun toolErrorText(state: ChatToolState?): String {
val message = state?.error?.message
return if (!message.isNullOrBlank()) message else toolOutputText(state)
}
/** Wall-clock duration of a tool call, or null while it has no completion time. */
internal fun toolDurationMillis(part: ChatPart): Long? {
val time = part.time ?: return null
val start = if (time.ran > 0) time.ran else time.created
if (start <= 0 || time.completed <= 0 || time.completed < start) return null
return time.completed - start
}
/** True when a tool call ended in an error state. */
internal fun toolFailed(state: ChatToolState?): Boolean = state?.status == ChatProtocol.TOOL_ERROR
/** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */
internal fun formatToolDuration(millis: Long): String = when {
millis < 1_000 -> "${millis}ms"
millis < 60_000 -> String.format(java.util.Locale.US, "%.1fs", millis / 1000.0)
else -> "${millis / 60_000}m ${(millis % 60_000) / 1000}s"
}
/** The chip label for a tool call: its name, or a placeholder when unnamed. */
internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" }
/**
* A turn's one summary chip: `N tools called`, and `1 tool called` for a single
* call — a count of one is never pluralised. The chip is the transcript's only
* tool-call surface, so this label stands in for every call of the turn.
*/
internal fun toolCallsLabel(count: Int): String =
if (count == 1) "1 tool called" else "$count tools called"
/**
* What the summary chip announces to a screen reader, since the individual
* calls only exist inside the popup: the count, plus how to reach the detail.
* Singular and plural follow [toolCallsLabel] so the two never disagree.
*/
internal fun toolCallsAnnouncement(count: Int): String =
if (count == 1) "1 tool call, expand for details" else "$count tool calls, expand for details"
/**
* How many tool calls [parts] holds. Counted by kind rather than by
* `parts.size`, so a turn that also carries text or reasoning never inflates
* the number the summary chip shows.
*/
internal fun toolCallCount(parts: List<ChatPart>): Int =
parts.count { it.type == ChatProtocol.PART_TOOL }
/** True while any tool call in [parts] is still in flight. */
internal fun toolsRunning(parts: List<ChatPart>): Boolean =
parts.any { it.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(it.state) }
/**
* The in-flight tool calls across a conversation's [messages], in transcript
* order, so the conversation's indicator and the session row read the same set
* and its order is stable from frame to frame (a chip is never re-ordered by a
* rebuild). A call drops out the moment it completes or errors, which is what
* clears the indicator, so nothing here ever invents a finish time.
*/
internal fun runningToolCalls(messages: List<ChatMessage>): List<ChatPart> =
messages.flatMap { it.parts }
.filter { it.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(it.state) }
/**
* The input keys, in preference order, that carry a human-facing command or a
* short description of what a tool call is doing. OpenCode's tools put the
* substance in different places (`command` for a shell, `description` for a task,
* a path or pattern for the file/search tools), so the first one present is shown
* rather than the raw arguments.
*/
private val TOOL_DETAIL_KEYS = listOf(
"description", "command", "filePath", "file_path", "path", "pattern", "query", "url",
)
/** How much of a command/description the phone shows before it is elided. */
private const val TOOL_DETAIL_MAX_LENGTH = 72
private val TOOL_DETAIL_WHITESPACE = Regex("\\s+")
/**
* A one-line command or short description for [part], taken from the input the
* part actually carries: the first of [TOOL_DETAIL_KEYS] present, collapsed to a
* single line and elided past [TOOL_DETAIL_MAX_LENGTH]. Null when the input
* carries no such key (a partial-JSON string while the call is still streaming,
* or a tool that reports none), so a caller shows the name alone rather than a
* fabricated summary.
*/
internal fun toolDetail(part: ChatPart): String? {
val obj = part.state?.input as? JsonObject ?: return null
for (key in TOOL_DETAIL_KEYS) {
val value = obj[key] as? JsonPrimitive ?: continue
if (!value.isString) continue
val text = value.content.trim().replace(TOOL_DETAIL_WHITESPACE, " ")
if (text.isBlank()) continue
return if (text.length <= TOOL_DETAIL_MAX_LENGTH) {
text
} else {
text.take(TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…"
}
}
return null
}
/**
* Everything one row of the tool panel shows for a single call, derived once so
* the row, the summary chip and their unit test agree: the call's real name (the
* name the earlier frames taught it, only falling back to `tool` when none was
* ever seen), its one-line detail, its duration, the pretty-printed INPUT, the
* OUTPUT, the ERROR text for a failed call and the synthesised edit diff.
* [error] is null for a call that did not fail, and [diff] is null for every
* non-edit call, so the row shows only the sections that have content.
*/
internal data class ToolCallRow(
val name: String,
val detail: String?,
val duration: String?,
val input: String,
val output: String,
val error: String?,
val diff: ToolDiff?,
)
/** Builds the one row a turn's tool panel shows for [part]. */
internal fun toolCallRow(part: ChatPart): ToolCallRow = ToolCallRow(
name = toolLabel(part),
detail = toolDetail(part),
duration = toolDurationMillis(part)?.let(::formatToolDuration),
input = prettyToolInput(part.state?.input),
output = toolOutputText(part.state),
error = if (toolFailed(part.state)) toolErrorText(part.state) else null,
diff = toolEditDiff(part.state?.input),
)
/**
* How long a running [part] has been going at [nowMillis]. The protocol's own
* timing wins whenever the part carries it (a running call from stored history
* has `time.ran`, the moment it started); otherwise the elapsed is measured
* locally from [startedAt] — the wall clock at which this client first saw the
* part running. Zero when neither is usable, so a caller never shows a time it
* cannot stand behind.
*/
internal fun runningToolElapsedMillis(part: ChatPart, startedAt: Long, nowMillis: Long): Long {
val protocolStart = part.time?.let { if (it.ran > 0) it.ran else it.created } ?: 0L
val start = if (protocolStart > 0) protocolStart else startedAt
return if (start in 1 until nowMillis) nowMillis - start else 0L
}
/**
* A tool call running longer than this reads as unusually long on the phone and
* is marked, so a genuinely stuck call is visible without a fabricated ETA. One
* minute: long enough that ordinary calls (a build, a search, a command) are not
* flagged, short enough that a hung call stands out while the operator is still
* wondering.
*/
internal const val TOOL_LONG_RUNNING_MILLIS: Long = 60_000L
/** Whether a running call has been going long enough to be marked as unusual. */
internal fun toolLongRunning(elapsedMillis: Long): Boolean = elapsedMillis >= TOOL_LONG_RUNNING_MILLIS
/**
* How recently a text or reasoning delta must have arrived for a turn to read as
* still thinking. Long enough that the once-a-second tick the indicator runs on
* cannot flicker between thinking and waiting on a steady stream, short enough
* that a stalled turn starts reading as waiting while the operator still wonders.
*/
internal const val TURN_THINKING_WINDOW_MILLIS: Long = 2_500L
/**
* What an in-flight turn is actually doing, from evidence already on the wire.
* It is the one derivation the running indicator and its unit test share, so the
* headline never disagrees with the tool lines under it:
*
* - [THINKING] while text or reasoning deltas are still arriving (within
* [TURN_THINKING_WINDOW_MILLIS] of the last one);
* - [TOOL] while one or more tool calls are in flight, which the indicator names
* separately;
* - [WAITING] otherwise — the turn is running but nothing is arriving and no
* tool is running, for example while the model is awaited between steps.
*
* No percentage, ETA or progress is ever invented: the only inputs are the calls
* the stream reported and the time since the last delta.
*/
internal enum class TurnPhase { THINKING, TOOL, WAITING }
/**
* The [TurnPhase] of a turn in flight. [runningTools] are the calls the stream
* reports as still running; [silentMillis] is how long ago the last text or
* reasoning delta arrived, or null when none has (a turn that has not streamed
* yet reads as waiting rather than inventing thinking).
*/
internal fun turnPhase(runningTools: List<ChatPart>, silentMillis: Long?): TurnPhase = when {
runningTools.isNotEmpty() -> TurnPhase.TOOL
silentMillis != null && silentMillis in 0 until TURN_THINKING_WINDOW_MILLIS -> TurnPhase.THINKING
else -> TurnPhase.WAITING
}
/** The running indicator's headline for [phase], naming what is happening. */
internal fun turnPhaseLabel(phase: TurnPhase): String = when (phase) {
TurnPhase.THINKING -> "Thinking…"
TurnPhase.TOOL -> "Running a tool…"
TurnPhase.WAITING -> "Waiting…"
}
/**
* The background processes still running for a session, in the order they
* started, from the shells the server reported and the session retains. A shell
* that has exited is never listed — that is what clears the indicator — and the
* set is independent of the turn, because a background process outlives the tool
* call (and often the turn) that started it.
*/
internal fun runningBackgroundShells(shells: Map<String, ChatShell>): List<ChatShell> =
shells.values.filter { it.id.isNotBlank() && it.status == ChatProtocol.SHELL_RUNNING }
/**
* The one-line command a background process is running, collapsed to a single
* line and elided past [TOOL_DETAIL_MAX_LENGTH] like a tool call's detail, so a
* long command line cannot flood the indicator. A shell that reported no command
* reads as a generic `background process` rather than a blank line.
*/
internal fun shellCommandSummary(command: String): String {
val text = command.trim().replace(TOOL_DETAIL_WHITESPACE, " ")
if (text.isEmpty()) return "background process"
return if (text.length <= TOOL_DETAIL_MAX_LENGTH) {
text
} else {
text.take(TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…"
}
}
/**
* The running-tool start stamps after a thread's [messages] changed: every tool
* part in flight keeps the stamp it already had, or is stamped with [now] when it
* has just turned running, and a part that is no longer running loses its stamp.
* Kept free of Compose and of [ChatStore] so the bookkeeping and its unit test
* share one rule, and a stamp never moves forward while a call keeps running.
*/
internal fun runningToolStamps(
current: Map<String, Long>,
messages: List<ChatMessage>,
now: Long,
): Map<String, Long> {
val stamps = LinkedHashMap<String, Long>()
messages.forEach { message ->
message.parts.forEach { part ->
if (part.id.isNotEmpty() && part.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(part.state)) {
stamps[part.id] = current[part.id] ?: now
}
}
}
return stamps
}
/**
* The id a text or reasoning delta must be applied to for [kind] within [parts].
* The broker gives the two kinds distinct ids (see `ChatDeltaPartID`), but a peer
* that still shares one id between them must never have answer text appended into
* a reasoning part (or the reverse): when another kind already holds the bare id,
* the delta is moved onto a suffixed id of its own so the two kinds stay in
* separate parts. Once a part of this kind exists under either id, that part is
* the one addressed, so a stream keeps growing the part it started.
*/
internal fun deltaPartId(parts: List<ChatPart>, kind: String, id: String): String {
if (parts.any { it.type == kind && it.id == id }) return id
val suffixed = "$id#$kind"
if (parts.any { it.type == kind && it.id == suffixed }) return suffixed
return if (parts.any { it.id == id }) suffixed else id
}
/**
* Folds one tool frame's part onto the part retained from earlier frames. A tool
* call is reported across several frames that each carry only part of it (the name
* in `input.started`, the arguments in `input.ended`'s text or `called`'s input,
* then `progress`/`success` carrying neither), so a field already learned is never
* blanked by a later frame that omits it. A non-empty incoming field wins;
* otherwise the retained value is kept.
*/
internal fun mergeToolPart(previous: ChatPart?, incoming: ChatPart): ChatPart {
if (previous == null) return incoming
val priorState = previous.state
val incomingState = incoming.state
return incoming.copy(
type = incoming.type.ifBlank { previous.type },
name = incoming.name.ifBlank { previous.name },
executed = incoming.executed || previous.executed,
time = incoming.time ?: previous.time,
state = when {
incomingState == null -> priorState
priorState == null -> incomingState
else -> incomingState.copy(
status = incomingState.status.ifBlank { priorState.status },
input = incomingState.input ?: priorState.input,
content = incomingState.content.ifEmpty { priorState.content },
metadata = incomingState.metadata ?: priorState.metadata,
error = incomingState.error ?: priorState.error,
)
},
)
}
/**
* The status a session row reports while a turn is in flight: it names the tool
* call it is parked on (or how many, when several run at once) so a working chat
* says what it is doing rather than just `Running`, and a chat only generating
* text still reads as plain `Running` — the two are never confused. A chat with
* nothing running falls back to the ordinary busy/idle label, so a session
* waiting on another client is never shown as idle.
*/
internal fun sessionWorkLabel(busy: Boolean, thread: ChatThread?): String = when {
thread?.running == true -> runningSessionLabel(thread.runningTools)
busy -> "Busy · read-only"
else -> "Idle"
}
private fun runningSessionLabel(tools: List<ChatPart>): String = when (tools.size) {
0 -> "Running"
1 -> "Running ${toolLabel(tools.single())}"
else -> "Running ${tools.size} tools"
}
/**
* A session's short title: the server title, or a truncated id when untitled, so
* a row never renders as a blank line.
*/
internal fun sessionTitle(session: ChatSession): String =
session.title.ifBlank { session.id.take(18).ifBlank { "Untitled chat" } }
/**
* The kind chip a session row shows, derived from the server's own tag: a session
* the server tagged `operator` reads `Operator`. Any other tag is shown verbatim
* (a kind this client does not know is never silently dropped) and an untagged
* session shows no chip. This only *labels*; the app never filters on the tag,
* because the server already lists operator sessions only.
*/
internal fun sessionTagLabel(session: ChatSession): String? = tagLabel(session.tag)
/**
* The kind chip label for a session's own tag value (see [sessionTagLabel]).
* Kept as the single mapping so a session and the conversation it opens cannot
* label the same tag differently.
*/
internal fun sessionTagLabel(tag: String): String? = tagLabel(tag)
private fun tagLabel(tag: String): String? = when {
tag.isBlank() -> null
tag == ChatProtocol.TAG_OPERATOR -> OPERATOR_TAG_LABEL
else -> tag
}
/**
* The one-line meta under a conversation's own title: the model the server
* reports is answering, the session's kind tag and its directory. Every part is
* a value the server reported (a model id, the wire tag, the directory), so
* nothing is guessed and no catalogue is invented; a blank part is omitted, so a
* session the server reported without a model (or an older server that omits the
* field) shows no model claim at all.
*/
internal fun chatHeaderMeta(thread: ChatThread): String = listOfNotNull(
thread.model.takeIf { it.isNotBlank() },
sessionTagLabel(thread.tag),
thread.directory.takeIf { it.isNotBlank() },
).joinToString(" · ")
private const val OPERATOR_TAG_LABEL = "Operator"
/**
* The status a session row shows: `Running` while this client has a turn in
* flight, else `Idle`. A session is never reported `Busy` or read-only because
* another client is watching it — the server fans the stream out and accepts a
* prompt from any client, so the session stays writable everywhere.
*/
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String =
sessionStatusLabel(runningLocally, session.closed)
/**
* The status of a conversation from its own flags (see [sessionStatusLabel]).
* A closed session reads `Closed` first: it is finished, whatever a stale local
* running mark says. A session is never reported `Busy` or read-only because
* another client is watching it — the server fans the stream out and accepts a
* prompt from any client, so the session stays writable everywhere.
*/
internal fun sessionStatusLabel(runningLocally: Boolean, closed: Boolean = false): String = when {
closed -> "Closed"
runningLocally -> "Running"
else -> "Idle"
}
/**
* The activity a session row signals beyond its open/tag/directory state. An
* idle session has nothing extra; an unseen one finished since the operator last
* read it; a streaming one is producing a reply right now.
*/
enum class SessionActivity { IDLE, UNSEEN, STREAMING }
/**
* The one derivation of a row's activity, so the badge and its unit test cannot
* disagree: a turn streaming right now outranks a finished-but-unread
* transcript, which outranks an idle session. Kept pure (no Compose, no
* transport) like the other chat formatting.
*/
internal fun sessionActivity(running: Boolean, unseen: Boolean): SessionActivity = when {
running -> SessionActivity.STREAMING
unseen -> SessionActivity.UNSEEN
else -> SessionActivity.IDLE
}
/**
* The one identity a conversation header shows: the title is the session's
* name, and everything else is context that cannot be mistaken for a second
* name — the server's kind tag, the live activity and the directory/model.
* Kept pure so the header and its unit test agree that the title appears once.
*/
internal data class ConversationHeader(
val title: String,
val kind: String?,
val activity: String,
val directory: String,
val model: String,
) {
/** The extra identity context, in reading order, with blank fields omitted. */
val context: List<String> = listOf(directory, model).filter { it.isNotBlank() }
}
/** Builds the conversation header from the open thread's copied session fields. */
internal fun conversationHeader(thread: ChatThread): ConversationHeader = ConversationHeader(
title = sessionTitle(ChatSession(id = thread.sessionId, title = thread.title)),
kind = sessionTagLabel(thread.tag),
activity = sessionStatusLabel(thread.running, thread.closed),
directory = thread.directory,
model = thread.model,
)
/**
* The open chats a conversation still offers to switch to: every other open
* chat, never the active one, so its title is not repeated beside its own
* header. The session list keeps showing all open chats.
*/
internal fun openChatsBeside(open: List<ChatThread>, activeSessionId: String): List<ChatThread> =
open.filterNot { it.sessionId == activeSessionId }
/**
* How the transcript renders one part. The decision is pure so the markdown
* route out of the transcript can be tested without Compose: assistant text is
* markdown, reasoning feeds the turn's one folded block, any other part with
* text is plain, and an empty part renders nothing.
*/
internal enum class PartRendering { MARKDOWN, REASONING, PLAIN, HIDDEN }
internal fun partRendering(part: ChatPart): PartRendering = when {
part.type == ChatProtocol.PART_TEXT && part.text.isNotBlank() -> PartRendering.MARKDOWN
part.type == ChatProtocol.PART_REASONING && part.text.isNotBlank() -> PartRendering.REASONING
part.text.isNotBlank() -> PartRendering.PLAIN
else -> PartRendering.HIDDEN
}
/**
* Which turns' reasoning the operator has opened. A set keyed by the turn's own
* stable key, so a streaming turn keeps its state as deltas arrive — the block is
* not rebuilt when the turn grows — and every turn starts collapsed in a freshly
* opened conversation.
*/
internal data class ReasoningExpansion(private val expanded: Set<String> = emptySet()) {
fun isExpanded(turnKey: String): Boolean = turnKey in expanded
fun toggled(turnKey: String): ReasoningExpansion {
if (turnKey.isBlank()) return this
return copy(expanded = if (turnKey in expanded) expanded - turnKey else expanded + turnKey)
}
}
/** The stable key for one turn's single reasoning block: the turn's own message id. */
internal fun reasoningTurnKey(messageId: String): String = messageId
/**
* One assistant turn's reasoning, folded into the single collapsible block the
* transcript shows. [steps] are the reasoning parts that carry text, in the order
* the server sent them; a turn that reasons several times is therefore one entry
* rather than a stack of them.
*/
internal data class ReasoningTurn(val steps: List<String>) {
val count: Int get() = steps.size
val empty: Boolean get() = steps.isEmpty()
/** The turn's reasoning as the one expanded block reads it, steps in order. */
val text: String get() = steps.joinToString("\n\n")
}
/**
* The reasoning of a turn — every reasoning part with text, in order. The one
* fold the transcript and its tests share, so "one block per turn" is a single
* derivation rather than a rule each call site re-implements.
*/
internal fun turnReasoning(parts: List<ChatPart>): ReasoningTurn =
ReasoningTurn(
parts.filter { it.type == ChatProtocol.PART_REASONING && it.text.isNotBlank() }
.map { it.text },
)
/**
* One agent reply: everything the agent produced between two of the operator's
* messages, however many model steps that took. OpenCode reports a turn as one
* assistant message per step, so this is the single fold the transcript uses to
* render a reply as one bubble — the turn's thinking block, then its tool-call
* chips, then its answer — instead of one bubble (and one thinking block) per
* step.
*/
internal data class ChatTurn(val key: String, val parts: List<ChatPart>) {
/** The turn's reasoning, folded into the one block the transcript shows first. */
val reasoning: ReasoningTurn get() = turnReasoning(parts)
/** The turn's tool calls, in the order the agent made them. */
val tools: List<ChatPart> get() = parts.filter { it.type == ChatProtocol.PART_TOOL }
/**
* The turn's answer: just its text parts, joined in order. Reasoning feeds the
* folded thinking block and a tool call its chip, so the answer block never
* carries thinking or a command.
*/
val answer: String
get() = parts
.filter {
it.type != ChatProtocol.PART_TOOL &&
(partRendering(it) == PartRendering.MARKDOWN || partRendering(it) == PartRendering.PLAIN)
}
.joinToString("\n\n") { it.text }
/** The turn's own timing, or null when its parts carry none. */
val elapsedMillis: Long? get() = turnElapsedMillis(parts)
/** Whether the turn has anything to draw; an empty turn renders no bubble. */
val visible: Boolean get() = reasoning.count > 0 || tools.isNotEmpty() || answer.isNotBlank()
}
/**
* One item of the transcript: an operator message, or one folded agent reply. The
* key is stable as a reply grows — an agent turn is keyed by its first message id
* — so the list is not rebuilt and an expanded thinking block keeps its state as
* new steps stream in.
*/
internal sealed interface TranscriptRow {
val key: String
data class User(val message: ChatMessage) : TranscriptRow {
override val key: String get() = message.id
}
data class Agent(val turn: ChatTurn) : TranscriptRow {
override val key: String get() = turn.key
}
}
/**
* The transcript's rows for [messages]: each run of consecutive assistant
* messages folds into one [TranscriptRow.Agent], and each of the operator's own
* messages is its own [TranscriptRow.User]. This is the one fold that makes a
* reply a single bubble, so the transcript and its tests cannot disagree about
* where one agent turn ends and the next begins.
*/
internal fun transcriptRows(messages: List<ChatMessage>): List<TranscriptRow> {
val rows = ArrayList<TranscriptRow>(messages.size)
var turnKey: String? = null
var parts = ArrayList<ChatPart>()
fun flush() {
val key = turnKey
if (key != null) {
val turn = ChatTurn(key, parts)
if (turn.visible) rows.add(TranscriptRow.Agent(turn))
}
turnKey = null
parts = ArrayList()
}
for (message in messages) {
if (message.role == ChatProtocol.ROLE_ASSISTANT) {
if (turnKey == null) turnKey = message.id
parts.addAll(message.parts)
} else {
flush()
rows.add(TranscriptRow.User(message))
}
}
flush()
return rows
}
/** The live label of a single-step turn's reasoning block while it streams. */
private const val REASONING_STREAMING_LABEL = "Thinking…"
/** The settled label of a single-step turn's reasoning block. */
private const val REASONING_SETTLED_LABEL = "Reasoning"
/**
* The collapsed thinking line's label. A turn that reasoned once keeps the plain
* one-block wording — a count of one is never shown — while a turn that reasoned
* several times reads as its step count, so the operator can tell before opening
* it how much thinking there is.
*/
internal fun reasoningLabel(count: Int, streaming: Boolean): String = when {
count > 1 && streaming -> "Thinking · $count steps"
count > 1 -> "Reasoning · $count steps"
streaming -> REASONING_STREAMING_LABEL
else -> REASONING_SETTLED_LABEL
}
/**
* The close confirmation's body: it says exactly what closing does — stops a
* running turn, marks the chat closed on every device — and what it does not do:
* nothing is deleted, the chat and its history are kept and can be reopened. Kept
* pure so the confirmation wording and its unit test share one string instead of
* the copy drifting from the promise.
*/
internal fun closeChatConfirmation(title: String): String =
"Closes \"$title\" and marks it closed on every device. " +
"A turn that is running is stopped first. " +
"Nothing is deleted — the chat and its history are kept, " +
"and you can reopen it from the list."
/**
* The elapsed time the server's own timing gives a settled turn: from the
* earliest start to the latest completion across the parts that carry a timing
* envelope (a tool call reports both). Null when the turn carries no usable
* timing, so the collapsed line shows a duration only when there is one to show
* rather than guessing one.
*/
internal fun turnElapsedMillis(parts: List<ChatPart>): Long? {
val start = parts.mapNotNull { part ->
part.time?.let { if (it.ran > 0) it.ran else it.created }?.takeIf { it > 0 }
}.minOrNull() ?: return null
val end = parts.mapNotNull { it.time?.completed?.takeIf { it > 0 } }.maxOrNull() ?: return null
return (end - start).takeIf { it > 0 }
}
/** Which action the composer's single primary control offers for a chat. */
enum class ComposerAction { Send, Stop }
/**
* The composer's primary control: while a turn is in flight the send control
* becomes the stop control (interrupt), otherwise it sends the draft. One
* derivation drives both the trailing button and the keyboard's send action, so
* a running turn can never be sent to from the other control.
*/
internal fun composerAction(thread: ChatThread): ComposerAction =
if (thread.running) ComposerAction.Stop else ComposerAction.Send
/**
* One line of a derived unified diff. [CONTEXT] lines are unchanged, [ADD] came
* from the edit's `newString` and [REMOVE] from its `oldString`.
*/
enum class DiffKind { CONTEXT, ADD, REMOVE }
data class DiffLine(val kind: DiffKind, val text: String)
/**
* A synthesised edit diff: the file, the true `+N -M` counts and the ordered
* lines. [omitted] is how many diff lines are not in [lines] because the edit was
* too large to render in full (0 when the whole diff is shown); the counts always
* describe the whole edit, never just the rendered prefix.
*/
data class ToolDiff(
val file: String,
val added: Int,
val removed: Int,
val lines: List<DiffLine>,
val omitted: Int = 0,
)
/**
* Derives a unified diff for an `edit`-family tool call from its
* `oldString`/`newString` arguments. The brokered protocol carries no diff field
* (research report §2.5), so the +/- view is synthesised here instead. A diff
* longer than [MAX_RENDERED_DIFF_LINES] is summarised — only that many lines are
* kept, with [ToolDiff.omitted] carrying the rest — so a very large edit cannot
* flood the transcript on a phone. Returns null for any other tool, so non-edit
* calls keep the INPUT/OUTPUT panel.
*/
internal fun toolEditDiff(input: JsonElement?): ToolDiff? {
val obj = input as? JsonObject ?: return null
val old = obj.stringOrNull("oldString", "old_string") ?: return null
val new = obj.stringOrNull("newString", "new_string") ?: return null
if (old.isEmpty() && new.isEmpty()) return null
val lines = lineDiff(old.split("\n"), new.split("\n"))
return ToolDiff(
file = obj.stringOrNull("filePath", "file_path", "file").orEmpty(),
added = lines.count { it.kind == DiffKind.ADD },
removed = lines.count { it.kind == DiffKind.REMOVE },
lines = lines.take(MAX_RENDERED_DIFF_LINES),
omitted = (lines.size - MAX_RENDERED_DIFF_LINES).coerceAtLeast(0),
)
}
private fun JsonObject.stringOrNull(vararg keys: String): String? {
for (key in keys) {
val value = this[key]
if (value is JsonPrimitive && value.isString) return value.content
}
return null
}
/**
* A minimal line diff (LCS) so only the changed lines are marked, not the whole
* block. A pathologically large edit falls back to a plain remove-then-add block
* to bound the quadratic table.
*/
private fun lineDiff(old: List<String>, new: List<String>): List<DiffLine> {
if (old.size > MAX_DIFF_LINES || new.size > MAX_DIFF_LINES) {
return old.map { DiffLine(DiffKind.REMOVE, it) } + new.map { DiffLine(DiffKind.ADD, it) }
}
val m = old.size
val n = new.size
val lcs = Array(m + 1) { IntArray(n + 1) }
for (i in m - 1 downTo 0) {
for (j in n - 1 downTo 0) {
lcs[i][j] = if (old[i] == new[j]) lcs[i + 1][j + 1] + 1
else maxOf(lcs[i + 1][j], lcs[i][j + 1])
}
}
val result = ArrayList<DiffLine>(m + n)
var i = 0
var j = 0
while (i < m && j < n) {
when {
old[i] == new[j] -> {
result.add(DiffLine(DiffKind.CONTEXT, old[i])); i++; j++
}
lcs[i + 1][j] >= lcs[i][j + 1] -> {
result.add(DiffLine(DiffKind.REMOVE, old[i])); i++
}
else -> {
result.add(DiffLine(DiffKind.ADD, new[j])); j++
}
}
}
while (i < m) { result.add(DiffLine(DiffKind.REMOVE, old[i])); i++ }
while (j < n) { result.add(DiffLine(DiffKind.ADD, new[j])); j++ }
return result
}
/**
* How many diff lines are rendered before the remainder is summarised. Small
* enough to stay readable on a phone, large enough that ordinary edits are
* always shown in full. [MAX_DIFF_LINES] is the larger algorithm guard that
* bounds the quadratic LCS table.
*/
internal const val MAX_RENDERED_DIFF_LINES = 200
private const val MAX_DIFF_LINES = 400
/**
* How one permission request stands: still waiting for the operator, answered
* here (optimistically, while the reply is in flight), or already settled by the
* server (another client answered it, or it expired).
*/
enum class ApprovalState { PENDING, ANSWERED, RESOLVED }
/**
* What the conversation renders for one permission request. Derived purely from
* the server's [ChatPermissionFrame] plus the operator's local answer, so the
* approval card and its unit test share one model instead of each reading the
* frame. [actionable] is true only while nothing has settled the request, which
* is what keeps a resolved request from offering stale once/always/reject
* controls.
*/
data class ApprovalCard(
val requestId: String,
val action: String,
val resources: List<String>,
val risk: String,
val state: ApprovalState,
val decision: String = "",
val note: String = "",
) {
/** The once/always/reject controls are live only while the request is open. */
val actionable: Boolean get() = state == ApprovalState.PENDING
/**
* The amber risk box is shown while the request is open and after the
* operator denies it (jarvis shows it while "pending/denied"), but not for a
* request the server already settled, whose note carries the outcome.
*/
val showRisk: Boolean
get() = state == ApprovalState.PENDING ||
(state == ApprovalState.ANSWERED && decision == ChatProtocol.DECISION_REJECT)
/** The card headline: what is being requested, or the verdict once settled. */
val headline: String
get() = when (state) {
ApprovalState.PENDING -> "Approve " + action.ifBlank { "tool call" }
ApprovalState.ANSWERED -> decisionLabel(decision)
ApprovalState.RESOLVED -> if (decision.isBlank()) "Already resolved" else decisionLabel(decision)
}
/** The one-line explanation under the headline. */
val statusLine: String
get() = when (state) {
ApprovalState.PENDING -> "Waiting for your response"
ApprovalState.ANSWERED -> "Waiting for the agent to continue…"
ApprovalState.RESOLVED -> note.ifBlank { "Another client already answered this request." }
}
}
/**
* The approval card for [permission], or null when there is no request to show.
* A request the server reports as settled wins over any local answer, so a stale
* tap can never reopen controls for a request that is already done.
*/
internal fun approvalCard(permission: ChatPermissionFrame?, answer: String): ApprovalCard? {
if (permission == null || permission.requestId.isBlank()) return null
val resolvedByServer = permission.resolved || permission.decision.isNotBlank()
val state = when {
resolvedByServer -> ApprovalState.RESOLVED
answer.isNotBlank() -> ApprovalState.ANSWERED
else -> ApprovalState.PENDING
}
return ApprovalCard(
requestId = permission.requestId,
action = permission.action,
resources = permission.resources.filter { it.isNotBlank() },
risk = permissionRiskText(permission),
state = state,
decision = if (resolvedByServer) permission.decision else answer,
note = if (resolvedByServer) permission.message else "",
)
}
/**
* The text in the amber risk-review box: the server's own summary when it carries
* one (jarvis shows the model's risk summary), otherwise a neutral sentence
* naming the action so the box is never blank.
*/
internal fun permissionRiskText(permission: ChatPermissionFrame): String {
if (permission.message.isNotBlank()) return permission.message
val what = permission.action.ifBlank { "a tool call" }
return "The agent is asking to run $what; review the request before allowing."
}
/** A human label for a once/always/reject decision, blank-safe. */
internal fun decisionLabel(decision: String): String = when (decision) {
ChatProtocol.DECISION_ONCE -> "Allowed once"
ChatProtocol.DECISION_ALWAYS -> "Always allowed"
ChatProtocol.DECISION_REJECT -> "Rejected"
else -> "Resolved"
}
/**
* The largest file the composer will attach. A phone-side guard, so a runaway
* pick is refused with a reason instead of being handed to the server; the
* server applies its own limits on top and a prompt it rejects comes back
* flagged against the attachment.
*/
internal const val MAX_ATTACHMENT_BYTES: Long = 25L * 1024 * 1024
/**
* Why an attachment cannot be sent, or null when it can. [readable] is the
* picker's own answer to whether the file could be opened; a file that cannot be
* read or that is over [MAX_ATTACHMENT_BYTES] is reported by name, so the
* operator sees which one and why rather than losing it.
*/
internal fun attachmentError(name: String, sizeBytes: Long, readable: Boolean): String? {
val display = name.ifBlank { "file" }
return when {
!readable -> "\"$display\" could not be read."
sizeBytes > MAX_ATTACHMENT_BYTES ->
"\"$display\" is too large (${humanBytes(MAX_ATTACHMENT_BYTES)} limit)."
else -> null
}
}
/**
* The `files` carried by a prompt: the URIs of the attachments that can go. One
* place derives the wire list from the attachments, so the request the operator
* builds and the transcript's own file parts can never disagree about which
* files are attached.
*/
internal fun attachmentFiles(attachments: List<ChatAttachment>): List<String> =
attachments.filter { it.error == null }.map { it.uri }
/**
* One attachment as a [ChatProtocol.PART_FILE] part of the optimistic user turn,
* so the transcript shows the file through the same parts it already renders
* rather than a second attachment list under the bubble.
*/
internal fun attachmentPart(attachment: ChatAttachment): ChatPart = ChatPart(
type = ChatProtocol.PART_FILE,
id = attachment.id,
name = attachment.name,
uri = attachment.uri,
mime = attachment.mime,
)
@@ -1,53 +0,0 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatSession
/**
* The session-list narrowing: a case-insensitive substring the operator types to
* find a chat by what it is called or where it lives. Blank narrows nothing, and
* the list's own recency order is never touched — filtering keeps the order the
* server returned (and the operator's local overrides applied on top).
*
* Kept pure (no Compose, no transport) like the other chat formatting, so the
* match rule and its unit test share one derivation.
*/
internal fun sessionMatchesQuery(session: ChatSession, query: String): Boolean {
val needle = query.trim()
if (needle.isEmpty()) return true
return sessionTitle(session).contains(needle, ignoreCase = true) ||
session.directory.contains(needle, ignoreCase = true)
}
/**
* Narrows [sessions] to those matching [query] over their title and directory. A
* blank query changes nothing, and the surviving sessions keep their original
* relative order, so a narrowing composes with the recency order rather than
* re-sorting it.
*/
internal fun filterChatSessions(sessions: List<ChatSession>, query: String): List<ChatSession> =
if (query.isBlank()) sessions else sessions.filter { sessionMatchesQuery(it, query) }
/**
* One run of sessions sharing one directory, so sessions of the same repository
* can be placed together while each keeps its recency position inside the run.
*/
data class ChatSessionGroup(val directory: String, val sessions: List<ChatSession>)
/**
* Groups [sessions] by directory, so sessions in the same repository sit together.
* The sessions keep their incoming recency order (within each group), and the
* groups themselves are ordered by the first — most recent — session they contain,
* so the top of the list still leads with the newest activity. A blank directory is
* a group of its own, labelled by the row as usual.
*
* The caller renders the groups as sections only when there is more than one;
* with a single directory the flat list is already "together".
*/
internal fun groupChatSessionsByDirectory(sessions: List<ChatSession>): List<ChatSessionGroup> {
if (sessions.isEmpty()) return emptyList()
val order = LinkedHashMap<String, MutableList<ChatSession>>()
for (session in sessions) {
order.getOrPut(session.directory) { mutableListOf() }.add(session)
}
return order.map { (directory, grouped) -> ChatSessionGroup(directory, grouped) }
}
@@ -1,534 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.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.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Surface
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.FilterSectionHeader
import net.awan.pipelines.ui.components.LabelChip
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.pillContentPadding
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
// ---- Pane 0: the server's session list ---------------------------------------
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ChatListPane(
vm: AppViewModel,
state: ChatState,
connected: Boolean,
covered: Boolean,
wide: Boolean,
modifier: Modifier,
) {
// A covered pane shows its compact identity only; the server list and the
// operator's own local changes are folded into the visible projection only
// for the pane actually drawn, never for the sliver behind a conversation.
if (covered) {
val count = state.visibleSessionCount
PaneIdentity(
title = "Chat",
subtitle = when {
state.open.isNotEmpty() -> "${state.open.size} open"
count > 0 -> "$count sessions"
else -> null
},
modifier = modifier.fillMaxSize(),
)
return
}
// The server returns operator sessions only, with the operator's own local
// renames and removals applied on top; the app never guesses which session
// belongs to a run. The operator's search narrows that list without touching
// its order. Active sessions are grouped by directory when there is more than
// one; the closed ones the operator finished with sit below them as history.
val sessions = state.filteredSessions
val active = state.activeSessions
val closed = state.closedSessions
val groups = groupChatSessionsByDirectory(active)
val query = state.sessionQuery
// A removal is reported for what it is: a local, undoable change, never a
// pretend delete — the server is not asked to remove anything.
val snackbarHostState = remember { SnackbarHostState() }
val removalNotice = state.removalNotice
LaunchedEffect(removalNotice?.id) {
removalNotice?.let { notice ->
// Claim delivery before showing. Completion remains separate so a
// cancelled effect cannot make this same notice replay on re-entry.
if (vm.beginChatRemovalNotice(notice.id)) {
// A rapid second hide replaces, rather than queues behind, the first.
snackbarHostState.currentSnackbarData?.dismiss()
if (snackbarHostState.showSnackbar(
message = CHAT_REMOVED_MESSAGE,
actionLabel = "Undo",
duration = SnackbarDuration.Short,
) == SnackbarResult.ActionPerformed) {
vm.undoRemoveChat(notice.sessionId)
}
vm.consumeChatRemovalNotice(notice.id)
}
}
}
var renaming by remember { mutableStateOf<ChatSession?>(null) }
var closing by remember { mutableStateOf<ChatSession?>(null) }
Scaffold(
modifier = modifier,
snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = {
TopAppBar(
title = { Text("Chat") },
actions = {
ChatListSearchControl(query = query, onQuery = vm::setChatSessionQuery)
IconButton(onClick = vm::refreshChatSessions) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh chats")
}
// The create path stays one tap away while the list is
// narrowed: it is the same trailing action, never hidden.
IconButton(onClick = vm::startNewChat) {
Icon(Icons.Default.Add, contentDescription = "New chat")
}
},
)
},
) { padding ->
Column(Modifier.fillMaxSize().padding(padding)) {
if (state.open.isNotEmpty()) {
OpenChatStrip(
state = state,
onSelect = vm::activateChat,
onClose = vm::closeChat,
)
}
if (!connected) {
NotConnectedNotice()
}
when {
state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…")
state.sessionsError != null && state.sessions.isEmpty() -> {
ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions)
}
sessions.isEmpty() && query.isNotBlank() -> EmptyState(
// A narrowing that matches nothing says so plainly and offers
// to clear it, the same empty-state pattern the other lists use.
message = "No chats match \"${query.trim()}\".",
actionLabel = "Clear search",
onAction = { vm.setChatSessionQuery("") },
)
sessions.isEmpty() -> EmptyState(
message = "No chat sessions on this server yet.",
actionLabel = "New chat",
onAction = vm::startNewChat,
)
// On a wide window the session rows keep the app's comfortable
// reading width (centred) instead of letting the identity's chips
// drift hundreds of pixels from its title, the same constraint the
// other lists and detail bodies use; narrow windows fill as before.
else -> DetailTabBody(wide, Modifier.fillMaxSize()) { listModifier ->
LazyColumn(
modifier = listModifier,
contentPadding = pillContentPadding(PaddingValues()),
) {
if (groups.size > 1) {
// More than one directory: one section per repository so
// same-directory chats sit together, each keeping the
// recency order inside it.
groups.forEach { group ->
item(key = "dir-" + group.directory) { DirectoryHeader(group.directory) }
items(group.sessions, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it }, onClose = { closing = it })
}
}
} else {
items(active, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it }, onClose = { closing = it })
}
}
if (closed.isNotEmpty()) {
// Finished chats stay reachable as history: a clearly
// labelled section, in the same recency order, from which
// each one can be reopened.
item(key = "closed-header") { DirectoryHeader(CLOSED_SECTION_LABEL) }
items(closed, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it }, onClose = { closing = it })
}
}
if (state.sessionsError != null) {
item("error") {
Text(
text = state.sessionsError,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(CHAT_GUTTER),
)
}
}
}
}
}
}
}
renaming?.let { session ->
RenameChatDialog(
session = session,
onDismiss = { renaming = null },
onConfirm = { title ->
vm.renameChat(session.id, title)
renaming = null
},
)
}
closing?.let { session ->
CloseChatDialog(
session = session,
onDismiss = { closing = null },
onConfirm = {
vm.closeChatSession(session.id)
closing = null
},
)
}
}
/**
* The session-list search control: the same top-bar filter-menu pattern the other
* lists use, with one free-text field that narrows the list by title and directory
* as the operator types. The active-count badge and the reset action report and
* clear the narrowing, and the create action beside it is never hidden.
*/
@Composable
private fun ChatListSearchControl(query: String, onQuery: (String) -> Unit) {
FilterMenu(
activeCount = if (query.isBlank()) 0 else 1,
contentDescription = "Search chats",
resetLabel = "Clear search",
onReset = { onQuery("") },
) {
FilterSectionHeader("Search")
OutlinedTextField(
value = query,
onValueChange = onQuery,
label = { Text("Title or directory contains") },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_M, vertical = SPACING_S),
)
}
}
/**
* One session of the list, whether it is rendered flat or inside a directory
* section: [SessionRow] fed from the live [state], so the activity marks, the open
* flag and the rename/remove actions are identical in both layouts.
*/
@Composable
private fun SessionListItem(
state: ChatState,
session: ChatSession,
vm: AppViewModel,
onRename: (ChatSession) -> Unit,
onClose: (ChatSession) -> Unit,
) {
val thread = state.thread(session.id)
SessionRow(
session = session,
thread = thread,
open = thread != null,
unseen = !session.closed && state.isUnseen(session),
active = state.activeId == session.id,
onClick = { vm.openChatSession(session) },
onRename = { onRename(session) },
onClose = { onClose(session) },
onReopen = { vm.reopenChatSession(session.id) },
onHide = { vm.removeChat(session.id) },
)
}
/**
* The heading of one directory section. The directory is shown here as well as on
* every row, so the grouping is legible even after a row scrolls out of view.
*/
@Composable
private fun DirectoryHeader(directory: String) {
Text(
text = directory.ifBlank { NO_DIRECTORY_LABEL },
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
}
/** The section heading for sessions the server reported without a directory. */
private const val NO_DIRECTORY_LABEL = "No directory"
@Composable
private fun SessionRow(
session: ChatSession,
thread: ChatThread?,
open: Boolean,
unseen: Boolean,
active: Boolean,
onClick: () -> Unit,
onRename: () -> Unit,
onClose: () -> Unit,
onReopen: () -> Unit,
onHide: () -> Unit,
) {
val texts = pipelinesText()
val running = thread?.running == true
val activity = sessionActivity(running, unseen)
ListRow(selected = active, onClick = onClick) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth(),
) {
Text(
text = sessionTitle(session),
style = texts.cardTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
// The kind chip names the session kind the server reported, so an
// operator chat is tellable from anything run-related at a glance.
sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
// A closed chat is named as such on the row itself, so it is never
// confused with a hide (which only affects this device) or with a
// still-open chat.
if (session.closed) LabelChip(CLOSED_CHIP_LABEL, SPACING_S, SPACING_XXS)
// The activity badge is the new-activity signal; the tag and the
// directory below are unchanged beside it.
SessionActivityBadge(activity, open)
SessionMenu(
closed = session.closed,
onRename = onRename,
onClose = onClose,
onReopen = onReopen,
onHide = onHide,
)
}
val meta = buildList {
add(sessionWorkLabel(session.busy, thread))
if (session.directory.isNotBlank()) add(session.directory)
if (session.model.isNotBlank()) add(session.model)
}.joinToString(" · ")
Text(text = meta, style = texts.meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
/**
* A session row's management actions. Closing is the real, server-side finish
* (shared by every device); hiding only affects this device and is named so the
* two cannot be confused. A closed chat offers Reopen instead of Close.
*/
@Composable
private fun SessionMenu(
closed: Boolean,
onRename: () -> Unit,
onClose: () -> Unit,
onReopen: () -> Unit,
onHide: () -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { expanded = true }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
Icon(
Icons.Default.MoreVert,
contentDescription = "Chat actions",
modifier = Modifier.size(ICON_INLINE_DP),
)
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
DropdownMenuItem(
text = { Text("Rename…") },
onClick = {
expanded = false
onRename()
},
)
if (closed) {
DropdownMenuItem(
text = { Text("Reopen") },
onClick = {
expanded = false
onReopen()
},
)
} else {
DropdownMenuItem(
text = { Text("Close chat…") },
onClick = {
expanded = false
onClose()
},
)
}
DropdownMenuItem(
text = { Text("Hide on this device") },
onClick = {
expanded = false
onHide()
},
)
}
}
}
/**
* The close confirmation. It says exactly what closing does and does not do:
* stops any running turn, keeps the whole history, and marks the chat closed for
* every device — never a delete, and distinct from the local hide.
*/
@Composable
private fun CloseChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Close chat?") },
text = {
Text(closeChatConfirmation(sessionTitle(session)))
},
confirmButton = { TextButton(onClick = onConfirm) { Text("Close chat") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/**
* The rename dialog. The brokered protocol has no rename for a chat session, so
* the dialog says plainly that the name is kept on this device rather than
* implying the server was told.
*/
@Composable
private fun RenameChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: (String) -> Unit) {
var title by remember(session.id) { mutableStateOf(sessionTitle(session)) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Rename chat") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
OutlinedTextField(
value = title,
onValueChange = { title = it },
singleLine = true,
label = { Text("Name") },
modifier = Modifier.fillMaxWidth(),
)
Text(
text = "The server has no rename for a chat, so this name is kept on this device.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
confirmButton = {
TextButton(onClick = { onConfirm(title) }, enabled = title.isNotBlank()) { Text("Save") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** The removal report: what happened and how to undo it. */
private const val CHAT_REMOVED_MESSAGE = "Hidden on this device; the chat stays on the server."
/** The row chip and section heading for a chat the operator finished with. */
private const val CLOSED_CHIP_LABEL = "Closed"
/** The heading of the section that keeps closed chats reachable as history. */
private const val CLOSED_SECTION_LABEL = "Closed"
/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */
@Composable
private fun SessionActivityBadge(activity: SessionActivity, open: Boolean) {
val label = when (activity) {
SessionActivity.STREAMING -> "Streaming"
SessionActivity.UNSEEN -> "New"
SessionActivity.IDLE -> if (open) "Open" else return
}
val color = when (activity) {
SessionActivity.STREAMING -> MaterialTheme.colorScheme.tertiary
SessionActivity.UNSEEN -> MaterialTheme.colorScheme.primary
SessionActivity.IDLE -> MaterialTheme.colorScheme.outline
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color))
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
private fun NotConnectedNotice() {
Surface(
color = MaterialTheme.colorScheme.errorContainer,
modifier = Modifier.fillMaxWidth(),
) {
Text(
text = "Not connected. Chats are served by the Pipelines server; connect in Settings.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
}
}
@@ -1,116 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PanTool
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.CHAT_TITLE_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
/**
* The open-conversation switcher: one chip per open conversation, so several
* chats can be kept at once and switched between in one tap. A running chat
* carries its live dot, a chat waiting on an approval carries its hand, and the
* X closes that chat (optional close is provided). [excludeSessionId] omits one
* chat — the conversation pane omits its own active one, whose title already
* stands in the app bar, while the session list shows every open chat.
*/
@Composable
internal fun OpenChatStrip(
state: ChatState,
onSelect: (String) -> Unit,
onClose: (String) -> Unit,
excludeSessionId: String? = null,
) {
val threads = if (excludeSessionId == null) {
state.open
} else {
openChatsBeside(state.open, excludeSessionId)
}
if (threads.isEmpty()) return
Row(
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
threads.forEach { thread ->
val selected = state.activeId == thread.sessionId
Surface(
shape = RoundedCornerShape(50),
color = if (selected) {
MaterialTheme.colorScheme.secondaryContainer
} else {
MaterialTheme.colorScheme.surfaceContainerHigh
},
modifier = Modifier
.selectable(selected = selected, role = Role.Tab, onClick = { onSelect(thread.sessionId) }),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.padding(start = CHAT_ITEM_GAP + 4.dp, end = 2.dp, top = 4.dp, bottom = 4.dp),
) {
if (thread.running) {
Box(
Modifier.size(CHAT_STATUS_DOT).clip(CircleShape)
.background(MaterialTheme.colorScheme.tertiary),
)
}
if (approvalCard(thread.permission, thread.permissionAnswer)?.actionable == true) {
// A request waiting on the operator is surfaced on the
// chat's own chip, so it is findable without opening it.
Icon(
Icons.Default.PanTool,
contentDescription = "Waiting for your approval",
tint = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.size(ICON_STATUS_DP),
)
}
Text(
text = thread.title.ifBlank { thread.sessionId.take(12) },
style = MaterialTheme.typography.labelMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.widthIn(max = CHAT_TITLE_MAX_WIDTH_DP),
)
IconButton(onClick = { onClose(thread.sessionId) }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
Icon(
Icons.Default.Close,
contentDescription = "Close chat ${thread.title}",
modifier = Modifier.size(16.dp),
)
}
}
}
}
}
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
}
@@ -1,59 +0,0 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.Serializable
import net.awan.pipelines.data.protocol.PipelinesJson
/**
* The operator's own changes to the session list, which the server has no
* request for: a chat cannot be renamed through the brokered protocol (there is
* no chat_rename type), so it is kept here, on the device, and applied over
* whatever the server lists. Closing a chat and reopening it are *not* here: they
* are server-side (`chat_close`/`chat_reopen`) so every device sees them.
*
* - [titles] are local renames, keyed by session id; a renamed chat shows its
* local title and the server's title is left untouched.
* - [hidden] are sessions the operator hid on this device. Nothing is deleted on
* the server, and no other device is affected, so the hide is honest and
* reversible ([remove] can be undone with [restore]). It is distinct from a
* server-side close, which marks the chat closed for every client.
*
* Kept as a serializable value so it survives a restart as one preference,
* exactly like the app's other stored settings.
*/
@Serializable
data class ChatSessionOverrides(
val titles: Map<String, String> = emptyMap(),
val hidden: List<String> = emptyList(),
) {
/** The hidden ids as a set, so membership checks on the list are O(1). */
val hiddenIds: Set<String> get() = hidden.toSet()
/** Records a local rename for [id]; a blank id or title is ignored. */
fun renamed(id: String, title: String): ChatSessionOverrides {
val trimmed = title.trim()
if (id.isBlank() || trimmed.isEmpty()) return this
return copy(titles = titles + (id to trimmed))
}
/** Hides [id] from the list; a blank id or an already-hidden one changes nothing. */
fun hide(id: String): ChatSessionOverrides =
if (id.isBlank() || id in hidden) this else copy(hidden = hidden + id)
/** Restores a hidden [id] to the list, undoing [hide]. */
fun restore(id: String): ChatSessionOverrides =
if (id !in hidden) this else copy(hidden = hidden - id)
/** The one-line JSON this value is stored as; never fails on our own value. */
fun encode(): String = PipelinesJson.encodeToString(serializer(), this)
companion object {
/** Decodes a stored value; anything unreadable falls back to no overrides. */
fun decode(stored: String): ChatSessionOverrides =
if (stored.isBlank()) {
ChatSessionOverrides()
} else {
runCatching { PipelinesJson.decodeFromString(serializer(), stored) }
.getOrDefault(ChatSessionOverrides())
}
}
}
@@ -1,85 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.collect
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.SlidingPaneStack
/**
* Geometry tokens for the chat surface. Every value is a named constant so no
* screen body holds an ad-hoc number; Material's own minimum interactive size
* governs touch targets.
*/
internal val CHAT_GUTTER = 16.dp
internal val CHAT_ITEM_GAP = 8.dp
internal val CHAT_COMPOSER_GAP = 12.dp
internal val CHAT_STATUS_DOT = 8.dp
/**
* The Chat destination. It is the same adaptive [SlidingPaneStack] the Pipelines
* and Runs destinations use: pane 0 is the server's session list (the operator
* can hold several chats open at once) and pane 1 is the active conversation.
*
* Every open chat keeps its own messages, running flag, composer draft and
* scroll position in [ChatStore]; switching away and back never loses them, and
* returning to a running chat re-syncs it from the server instead of showing a
* stale copy.
*/
@Composable
fun ChatScreen(vm: AppViewModel, wide: Boolean, modifier: Modifier = Modifier) {
val state by vm.chat.collectAsStateWithLifecycle()
val connection by vm.connectionState.collectAsStateWithLifecycle()
val active = state.active
val create = state.create
// Fetch the server's session list once when the Chat destination opens.
LaunchedEffect(Unit) { vm.refreshChatSessions() }
// Back leaves the create flow first, then a conversation, before leaving the
// destination, exactly one level at a time (the same rule the other
// destinations use).
PredictiveBackHandler(enabled = create != null || active != null) { progress ->
progress.collect { }
if (create != null) vm.cancelNewChat() else vm.showChatList()
}
SlidingPaneStack(
// The directory picker and the conversation share the second level: they
// are mutually exclusive, so a pane is never mounted empty behind either.
depth = if (create != null || active != null) 1 else 0,
wide = wide,
onPopTo = { if (state.create != null) vm.cancelNewChat() else vm.showChatList() },
compactLabel = "Chats",
backContentDescription = { "Back to chats" },
modifier = modifier,
) { level, covered, paneModifier ->
when (level) {
0 -> ChatListPane(
vm = vm,
state = state,
connected = connection is ConnectionState.Connected,
covered = covered,
wide = wide,
modifier = paneModifier,
)
1 -> when {
create != null -> NewChatPane(vm = vm, state = state, create = create, modifier = paneModifier)
active != null -> {
// Key by session so each conversation gets its own list state
// and disposes (saving its scroll) when the operator switches away.
key(active.sessionId) {
ChatConversationPane(vm = vm, state = state, thread = active, modifier = paneModifier)
}
}
}
}
}
}
@@ -1,80 +0,0 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.ui.components.ListScrollAnchor
import net.awan.pipelines.ui.components.restoredScrollAnchor
/**
* The pixels the end of the transcript still sits below the viewport's bottom
* edge, or null when the viewport does not show the last item at all (a whole
* item is still below the fold) or the list has not been measured yet. A value of
* 0 means the end is in view. [lastVisibleIndex] is the index of the last item
* the viewport shows (or -1 before measurement), [lastVisibleEndPx] where that
* item ends and [viewportEndPx] the viewport's own bottom edge, both in the
* list's pixel space.
*
* A null — the last item is entirely below the fold — is also what tells the
* follow path that it must bring the item into view before any gap can be
* measured: an item appended exactly at the viewport's edge has no visible pixel
* yet, so it is not in the layout's visible items and the gap reads as unknown.
*
* Pure and Android-free, so the decisions built on it are checked without a
* device.
*/
internal fun chatBottomDistancePx(
lastVisibleIndex: Int,
lastVisibleEndPx: Int,
itemCount: Int,
viewportEndPx: Int,
): Int? {
if (itemCount <= 0 || lastVisibleIndex != itemCount - 1) return null
return (lastVisibleEndPx - viewportEndPx).coerceAtLeast(0)
}
/**
* Whether the view sits at the bottom: the end is in view and within
* [thresholdPx] of the bottom edge. Used for both decisions that depend on where
* the operator is — resuming the follow when a scroll settles, and offering the
* jump-to-latest affordance — so the two can never disagree about "at the
* bottom".
*/
internal fun chatFollowsAt(distanceFromBottomPx: Int?, thresholdPx: Int, itemCount: Int): Boolean =
itemCount > 0 && distanceFromBottomPx != null && distanceFromBottomPx <= thresholdPx
/**
* Whether the jump-to-latest affordance is offered: only while the transcript is
* *not* following [following] and there is genuinely something below the fold to
* return to ([distanceFromBottomPx] null or further than [thresholdPx]). Hidden
* when already at the bottom, and never shown for an empty transcript.
*/
internal fun chatShowJumpToLatest(
following: Boolean,
distanceFromBottomPx: Int?,
thresholdPx: Int,
itemCount: Int,
): Boolean = !following && itemCount > 0 && !chatFollowsAt(distanceFromBottomPx, thresholdPx, itemCount)
/**
* Whether opening a conversation should land on its newest message: only when the
* operator has no position of their own there yet (a null [saved]), which is
* every freshly opened chat, so the current turn is in view without hunting for
* it. A position the operator deliberately left behind — including the very top of
* the transcript, [ChatScrollPosition]`(0, 0)` — is restored instead; a saved
* position is never confused with the absence of one.
*/
internal fun chatOpensAtNewest(saved: ChatScrollPosition?): Boolean = saved == null
/**
* The position a conversation's transcript is placed at when it first shows: the
* newest message for a conversation with no position of the operator's own,
* otherwise the position they left. The clamp rule is the same one every other
* list in the app uses ([restoredScrollAnchor]): the saved index is clamped to the
* messages that still exist, and the pixel offset is kept only when the saved item
* survived, so a conversation that shrank underneath neither throws nor draws
* nothing part-way down an unrelated message.
*/
internal fun chatFirstScroll(saved: ChatScrollPosition?, itemCount: Int): ChatScrollPosition {
if (itemCount <= 0) return ChatScrollPosition()
val position = saved ?: return ChatScrollPosition(index = itemCount - 1, offset = 0)
val anchor = restoredScrollAnchor(ListScrollAnchor(position.index, position.offset), itemCount)
return ChatScrollPosition(index = anchor.index, offset = anchor.offset)
}
@@ -1,78 +0,0 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.Serializable
import net.awan.pipelines.data.protocol.PipelinesJson
/**
* What the operator has already seen of the session list, derived from data the
* app already receives — the sessions' own `updated_at` recency and the message
* ids/timestamps of the pushed chat events and history — so no server request is
* added to tell a chat with new activity from an idle one.
*
* - [seenAt] is the recency watermark per session: the newest `updated_at` the
* operator has seen. A session the operator has never opened is compared
* against it, so a reply that arrived while the app was closed (a newer
* `updated_at`) still reads as unseen after a restart. First sight of a session
* is seeded, so a chat that predates this feature is not reported as new.
* - [unseen] is the session ids that moved on while the app was open (a pushed
* frame for a chat that is not on screen). It is kept explicitly because a
* live stream carries no wall-clock stamp to compare, and it is what survives a
* restart for a chat whose server recency has not been re-read yet.
*
* Kept as a serializable value so it survives a restart as one preference,
* exactly like the app's other stored chat state ([ChatSessionOverrides]).
*/
@Serializable
data class ChatSeenState(
val seenAt: Map<String, Long> = emptyMap(),
val unseen: Set<String> = emptySet(),
) {
/** The newest recency the operator has seen for [id], or 0 when never seen. */
fun watermark(id: String): Long = seenAt[id] ?: 0L
/** True when [updatedAt] is newer than everything seen for [id]. */
fun isNewer(id: String, updatedAt: Long): Boolean = updatedAt > watermark(id)
/**
* Records the first sight of [id] at [updatedAt]: its baseline recency, so a
* pre-existing chat is not reported as new activity. A session already known
* (or with no recency to record) is left untouched, and an explicit [unseen]
* mark is never cleared here — this only opens a baseline, it does not read.
*/
fun seeded(id: String, updatedAt: Long): ChatSeenState =
if (id.isBlank() || updatedAt <= 0 || watermark(id) != 0L) this
else copy(seenAt = seenAt + (id to updatedAt))
/**
* Records that [id] has been read up to [updatedAt]: its watermark advances
* (never rewinds, so a stale list cannot un-read it) and any [unseen] mark is
* cleared. Called when the operator opens a conversation.
*/
fun read(id: String, updatedAt: Long): ChatSeenState {
if (id.isBlank()) return this
val advanced = updatedAt > watermark(id)
if (!advanced && id !in unseen) return this
return copy(
seenAt = if (advanced) seenAt + (id to updatedAt) else seenAt,
unseen = unseen - id,
)
}
/** Marks [id] as having moved on while it was not on screen. */
fun unread(id: String): ChatSeenState =
if (id.isBlank() || id in unseen) this else copy(unseen = unseen + id)
/** The one-line JSON this value is stored as; never fails on our own value. */
fun encode(): String = PipelinesJson.encodeToString(serializer(), this)
companion object {
/** Decodes a stored value; anything unreadable falls back to nothing seen. */
fun decode(stored: String): ChatSeenState =
if (stored.isBlank()) {
ChatSeenState()
} else {
runCatching { PipelinesJson.decodeFromString(serializer(), stored) }
.getOrDefault(ChatSeenState())
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,341 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.clickable
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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_HEIGHT_DP
import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP
/** The tool panel floats over the transcript; these bound its width and offsets. */
private val TOOL_PANEL_GAP = 4.dp
private val TOOL_PANEL_MARGIN = 8.dp
private val TOOL_PANEL_ELEVATION = 12.dp
/**
* One turn's tool calls behind a single summary chip: `N tools called`, with the
* existing spinner while any call is still in flight and a `· long` mark while a
* running call has passed [TOOL_LONG_RUNNING_MILLIS]. A settled turn never shows
* either mark, so a finished turn cannot fake work it is not doing.
*
* The chip is the transcript's only tool-call surface: tapping it opens the tool
* panel as a popup listing every call of the turn in the order the agent made
* them, each row collapsing independently. Because the panel is a popup and not
* part of the transcript layout, opening or closing it never re-flows the
* conversation nor moves its scroll position.
*
* [elapsedMillis] is the live age of a call — the conversation supplies it from
* its own clock, so the `long` mark is derived from real elapsed time rather
* than guessed. [live] is whether the turn is still streaming: a stored call can
* carry a stale `running` status long after the turn ended, and a settled chip
* must not spin (or wear the `long` mark) on that.
*/
@Composable
internal fun ToolCalls(parts: List<ChatPart>, live: Boolean, elapsedMillis: (ChatPart) -> Long = { 0L }) {
val calls = parts.filter { it.type == ChatProtocol.PART_TOOL }
if (calls.isEmpty()) return
// One panel at a time: the chip toggles it, and the panel's own X or a tap
// outside dismisses it. No key is needed: the calls belong to this turn.
var open by remember { mutableStateOf(false) }
val running = live && toolsRunning(calls)
val failed = calls.any { toolFailed(it.state) }
// The "long" mark is a running-call signal only: it is meaningful on the
// summary chip while a call is in flight, so a settled chip never wears it.
val long = running && calls.any { toolLongRunning(elapsedMillis(it)) }
Box(Modifier.fillMaxWidth().padding(vertical = CHAT_ITEM_GAP)) {
ToolCallsChip(
count = toolCallCount(calls),
running = running,
failed = failed,
long = long,
expanded = open,
onToggle = { open = !open },
)
if (open) {
Popup(
popupPositionProvider = rememberToolPanelPositionProvider(),
onDismissRequest = { open = false },
properties = PopupProperties(focusable = true),
) {
ToolPanel(calls = calls, onDismiss = { open = false })
}
}
}
}
/**
* The turn's one summary chip: the call count, the running spinner (or a state
* icon once settled), the optional `long` mark and a chevron naming the popup
* it opens. Its content description carries the count and how to reach the
* calls, so the summary is understandable without opening the panel.
*/
@Composable
private fun ToolCallsChip(
count: Int,
running: Boolean,
failed: Boolean,
long: Boolean,
expanded: Boolean,
onToggle: () -> Unit,
) {
Surface(
shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp),
color = if (failed) {
MaterialTheme.colorScheme.errorContainer
} else {
MaterialTheme.colorScheme.surfaceContainerHigh
},
modifier = Modifier
.semantics { contentDescription = toolCallsAnnouncement(count) }
.clickable(onClick = onToggle),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP),
) {
if (running) {
CircularProgressIndicator(Modifier.size(ICON_STATUS_DP), strokeWidth = 2.dp)
} else {
Icon(
imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build,
contentDescription = null,
modifier = Modifier.size(ICON_INLINE_DP),
tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
text = toolCallsLabel(count),
style = MaterialTheme.typography.labelMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (long) {
Text(
text = "· long",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.error,
)
}
Icon(
imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
contentDescription = if (expanded) "Hide tool calls" else "Show tool calls",
modifier = Modifier.size(ICON_INLINE_DP),
)
}
}
}
/**
* Anchors the tool panel just below its chip, or above it when there is no room
* below, keeping it inside the window margins — the same flip the reference
* panel does. Resolved in px, so it is independent of the current density.
*/
internal class ToolPanelPositionProvider(private val gapPx: Int, private val marginPx: Int) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize,
): IntOffset {
val maxX = (windowSize.width - popupContentSize.width - marginPx).coerceAtLeast(marginPx)
val x = anchorBounds.left.coerceIn(marginPx, maxX)
val below = anchorBounds.bottom + gapPx
val above = anchorBounds.top - popupContentSize.height - gapPx
val maxY = (windowSize.height - popupContentSize.height - marginPx).coerceAtLeast(marginPx)
val y = if (below <= maxY) below else above.coerceAtLeast(marginPx)
return IntOffset(x, y)
}
}
@Composable
private fun rememberToolPanelPositionProvider(): PopupPositionProvider {
val density = LocalDensity.current
return remember(density) {
ToolPanelPositionProvider(
gapPx = with(density) { TOOL_PANEL_GAP.roundToPx() },
marginPx = with(density) { TOOL_PANEL_MARGIN.roundToPx() },
)
}
}
/**
* The turn's whole tool history as one panel, grown from the single-call panel: a
* header naming the count with a close X, then one collapsible row per call in
* the order the agent made them. The list is bounded ([TOOL_PANEL_MAX_HEIGHT_DP])
* and scrolls inside the panel, so a turn with many calls neither grows the popup
* past the window nor moves the transcript behind it.
*/
@Composable
private fun ToolPanel(calls: List<ChatPart>, onDismiss: () -> Unit, modifier: Modifier = Modifier) {
var expandedIds by remember { mutableStateOf<Set<String>>(emptySet()) }
Surface(
shape = RoundedCornerShape(CHAT_ITEM_GAP),
color = MaterialTheme.colorScheme.surfaceContainer,
shadowElevation = TOOL_PANEL_ELEVATION,
modifier = modifier.widthIn(max = TOOL_PANEL_MAX_WIDTH_DP).fillMaxWidth(),
) {
Column(
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth().padding(CHAT_ITEM_GAP + 2.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Icon(
imageVector = Icons.Default.Build,
contentDescription = null,
modifier = Modifier.size(ICON_INLINE_DP),
tint = MaterialTheme.colorScheme.primary,
)
Text(
text = toolCallsLabel(calls.size),
style = MaterialTheme.typography.labelLarge,
modifier = Modifier.weight(1f),
)
IconButton(onClick = onDismiss, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
Icon(Icons.Default.Close, contentDescription = "Close tool calls", modifier = Modifier.size(ICON_INLINE_DP))
}
}
Column(
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier
.fillMaxWidth()
.heightIn(max = TOOL_PANEL_MAX_HEIGHT_DP)
.verticalScroll(rememberScrollState()),
) {
calls.forEach { part ->
val row = toolCallRow(part)
ToolCallRowItem(
row = row,
expanded = part.id in expandedIds,
onToggle = {
expandedIds = if (part.id in expandedIds) expandedIds - part.id else expandedIds + part.id
},
)
}
}
}
}
}
/**
* One call inside the panel: a header naming the call, its `+N -M` stat for an
* edit and its duration, and — expanded in place — the pretty-printed INPUT, the
* synthesised diff for an edit-family call, then the ERROR block for a failed
* call or the OUTPUT (or `(no output)`) for a settled one. Rows expand and
* collapse independently, so comparing two calls never loses the other's detail.
*/
@Composable
private fun ToolCallRowItem(row: ToolCallRow, expanded: Boolean, onToggle: () -> Unit) {
Column(Modifier.fillMaxWidth()) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier
.fillMaxWidth()
.minimumInteractiveComponentSize()
.clickable(role = Role.Button, onClick = onToggle)
.padding(vertical = CHAT_ITEM_GAP),
) {
Icon(
imageVector = when {
row.error != null -> Icons.Default.ErrorOutline
row.diff != null -> Icons.Default.Edit
else -> Icons.Default.Build
},
contentDescription = if (row.error != null) "Failed tool call" else null,
modifier = Modifier.size(ICON_INLINE_DP),
tint = if (row.error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
)
Column(Modifier.weight(1f)) {
Text(
text = row.name,
style = MaterialTheme.typography.labelMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
row.detail?.let {
Text(
text = it,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
row.diff?.let { DiffStat(it) }
row.duration?.let {
Text(it, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Icon(
imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
contentDescription = if (expanded) "Collapse ${row.name}" else "Expand ${row.name}",
modifier = Modifier.size(ICON_INLINE_DP),
)
}
if (expanded) {
Column(
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth().padding(start = ICON_INLINE_DP + CHAT_ITEM_GAP, bottom = CHAT_ITEM_GAP),
) {
CodeBlock(label = "INPUT", text = row.input)
row.diff?.let { DiffView(it) }
if (row.error != null) {
CodeBlock(label = "ERROR", text = row.error)
} else {
CodeBlock(label = "OUTPUT", text = row.output)
}
}
}
}
}
@@ -1,739 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Psychology
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SmallFloatingActionButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatShell
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.theme.CHAT_BUBBLE_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.CHAT_FOLLOW_THRESHOLD_DP
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.SPACING_XS
/** The running indicator's elapsed time ticks once a second, never per frame. */
private const val CHAT_ELAPSED_TICK_MILLIS = 1_000L
/**
* The bottom-anchored transcript: content is packed to the bottom (so a short or
* freshly opened chat sits against the composer) and the running indicator sits
* at the newest end while a turn is in flight.
*
* The transcript has one scroll path ([scrollToEnd] / [closeBottomGap]) and one
* decision for whether it follows new content. It opens at the newest message
* (placed by the pane's initial position, with any part of a last message taller
* than the viewport closed instantly here), and then — while the operator intends
* to read the newest part — every arrival (a message, a streamed delta, a tool
* chip, a grown composer or the appearing keyboard) is followed smoothly, so the
* newest content stays in view. An item that arrives entirely below the fold is
* brought in rather than left there. A freshly arrived approval card is followed
* the same way. Once the operator has scrolled up to read history nothing moves
* under them, and the jump-to-latest affordance is offered instead.
*/
@Composable
internal fun ChatTranscript(
thread: ChatThread,
rows: List<TranscriptRow>,
listState: LazyListState,
savedScroll: ChatScrollPosition?,
itemCount: Int,
approval: ApprovalCard?,
showRunning: Boolean,
reasoning: ReasoningExpansion,
onToggleReasoning: (String) -> Unit,
onDecision: (String) -> Unit,
onNoticeSend: (String) -> Unit,
onNoticeDismiss: (String) -> Unit,
) {
val scope = rememberCoroutineScope()
val density = LocalDensity.current
val thresholdPx = remember(density) { with(density) { CHAT_FOLLOW_THRESHOLD_DP.roundToPx() } }
// The transcript's item count, read at use time: the drag collector and the
// derived state below outlive any single recomposition, so a count captured
// when they were created would go stale as messages arrive and the follow
// would measure against how many items there used to be.
val currentItemCount by rememberUpdatedState(itemCount)
// Whether the operator wants the newest content kept in view. Only their own
// drag changes it — a programmatic scroll never touches the list's
// interactionSource, so it cannot un-stick the view — and a drag that settles
// at (or within the threshold of) the bottom resumes the follow. Its real
// value is settled once the transcript is placed, when the live distance to
// the bottom is known.
// Saved, so a rotation or process death while the operator is reading history
// restores "not following" too, rather than the restored transcript being
// yanked to the bottom by the placement the new composition would otherwise run.
var following by rememberSaveable(thread.sessionId) { mutableStateOf(true) }
LaunchedEffect(listState, thresholdPx) {
listState.interactionSource.interactions.collect { interaction ->
when (interaction) {
is DragInteraction.Start -> following = false
is DragInteraction.Stop, is DragInteraction.Cancel ->
following = chatFollowsAt(
distanceFromBottomPx = listState.bottomDistancePx(currentItemCount),
thresholdPx = thresholdPx,
itemCount = currentItemCount,
)
else -> Unit
}
}
}
// The distance to the transcript's end, read through a derived state so the
// affordance's visibility is recomputed only when it actually changes rather
// than on every scrolled pixel. The item count is read through
// [currentItemCount] so the derived value also recomputes as content arrives.
val showJumpToLatest by remember(listState, thresholdPx) {
derivedStateOf {
chatShowJumpToLatest(
following = following,
distanceFromBottomPx = listState.bottomDistancePx(currentItemCount),
thresholdPx = thresholdPx,
itemCount = currentItemCount,
)
}
}
// The transcript is placed once, when it first has content, and only after it
// has been measured; the viewport height is an input too, so a grown composer
// or the appearing keyboard re-follows rather than leaving the newest message
// hidden behind it. Placement itself is saved, so restoring a rotation does not
// re-place (and re-follow) a transcript the operator had scrolled up.
var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) }
val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } }
LaunchedEffect(thread.messages, thread.notices, thread.running, approval?.requestId, viewportHeight) {
if (itemCount <= 0) return@LaunchedEffect
if (!placed) {
// Wait for the first measure: placement run before it would no-op and
// leave the first display to the measured re-run, which animates, and
// the first display must not animate.
if (viewportHeight <= 0) return@LaunchedEffect
placed = true
if (chatOpensAtNewest(savedScroll)) {
// No position of the operator's own: bring the newest item fully
// into view, instantly — the first display must not animate — and
// through the same path the follow uses, so placement and follow
// cannot disagree about what the newest item is (a last message
// taller than the viewport has its below-the-fold part closed by
// the same call), then follow.
listState.scrollToEnd(itemCount, animated = false)
following = true
} else {
// A position the operator left: follow only if it was the bottom, so
// returning to a chat never yanks the view.
following = chatFollowsAt(listState.bottomDistancePx(itemCount), thresholdPx, itemCount)
}
return@LaunchedEffect
}
if (following) listState.scrollToEnd(itemCount, animated = true)
}
Box(Modifier.fillMaxSize()) {
// Only the newest turn can be streaming, so its reasoning wears the live
// label; a settled turn's reasoning is labelled as settled. The turn is
// the transcript's last row only while it is the turn in flight.
val streamingTurnKey = (rows.lastOrNull() as? TranscriptRow.Agent)?.key?.takeIf { thread.running }
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom),
) {
items(rows, key = { it.key }) { row ->
when (row) {
is TranscriptRow.User -> UserMessageItem(row.message)
is TranscriptRow.Agent -> AgentTurnItem(
turn = row.turn,
reasoning = reasoning,
streaming = row.key == streamingTurnKey,
runningSince = thread.runningSince,
toolStartedAt = thread.toolStartedAt,
onToggleReasoning = onToggleReasoning,
)
}
}
// A slash command reports as its own line, after the turns it acted
// between and visually distinct from any message to the agent.
items(thread.notices, key = { it.id }) { notice ->
ChatCommandNoticeItem(
notice = notice,
onSendAsMessage = { onNoticeSend(notice.id) },
onDismiss = { onNoticeDismiss(notice.id) },
)
}
if (showRunning) {
item(key = "pending") { RunningIndicator(thread) }
}
if (approval != null) {
// Keyed by request id so switching between requests swaps the card
// instead of reusing the previous one's state.
item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) }
}
}
// Offered only once the transcript is placed and the operator has left the
// bottom, so it never covers the newest content it would return to.
if (placed && showJumpToLatest) {
SmallFloatingActionButton(
onClick = {
following = true
scope.launch { listState.scrollToEnd(itemCount, animated = true) }
},
modifier = Modifier.align(Alignment.BottomEnd).padding(CHAT_GUTTER),
) {
Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Jump to latest")
}
}
}
}
/**
* The transcript's one scroll path, shared by the first placement, the follow,
* the app-bar approval jump and the jump-to-latest affordance. The newest item is
* brought into view when it sits entirely below the fold — an item appended past
* the viewport's edge, so no pixel of it is on screen and the remaining distance
* cannot be measured — and any part of it still below the fold (a message taller
* than the viewport) is then closed by exactly that distance. An item that is
* already partly visible is only gap-closed, never moved up first. [animated] is
* false only for the first placement, which must not animate.
*
* [itemCount] is the transcript's *content* count, which can be ahead of the
* layout's: an appended item exists in the content before the recomposition that
* measures it, and the effect that follows it is dispatched ahead of that measure,
* so the layout still describes the previous items and its own last visible item
* reads as the end. Measuring against [itemCount] — see [bottomDistancePx] — is
* what stops an appended item from being mistaken for the already-visible end and
* left below the fold: it has no pixel on screen, so it is unknown-distance and is
* brought into view rather than gap-closed at zero.
*/
internal suspend fun LazyListState.scrollToEnd(itemCount: Int, animated: Boolean) {
if (itemCount <= 0) return
if (bottomDistancePx(itemCount) == null) {
if (animated) animateScrollToItem(itemCount - 1) else scrollToItem(itemCount - 1)
}
closeBottomGap(itemCount, animated)
}
/**
* Scrolls the transcript's end into view by exactly the distance it sits below
* the viewport, measured against the same [itemCount] the decisions above use.
*/
private suspend fun LazyListState.closeBottomGap(itemCount: Int, animated: Boolean) {
val remaining = bottomDistancePx(itemCount) ?: return
if (remaining <= 0) return
if (animated) animateScrollBy(remaining.toFloat()) else scrollBy(remaining.toFloat())
}
/**
* The distance from the transcript's end to the viewport's bottom, measured
* against [itemCount] — the transcript's *content* count, not the layout's. The
* two differ on the frame content arrives: the layout still describes the
* previous items, so its own last visible item reads as the end and the appended
* item's absence is invisible. Measuring against the content count makes the
* appended item read exactly as [chatBottomDistancePx] defines it — no pixel on
* screen — so the scroll path above brings it into view rather than trusting a
* stale layout's "already at the end". [itemCount] is what the transcript
* renders, so the two counts agree as soon as the layout catches up.
*/
private fun LazyListState.bottomDistancePx(itemCount: Int): Int? {
val info = layoutInfo
val last = info.visibleItemsInfo.lastOrNull()
return chatBottomDistancePx(
lastVisibleIndex = last?.index ?: -1,
lastVisibleEndPx = last?.let { it.offset + it.size } ?: 0,
itemCount = itemCount,
viewportEndPx = info.viewportEndOffset,
)
}
/**
* The in-flight turn indicator: a spinner, the turn's actual state (see
* [TurnPhase] — `Thinking…` while deltas arrive, `Running a tool…` while calls are
* in flight, `Waiting…` otherwise) and its live elapsed time, then one compact
* line for each tool call in flight — its name, the command or description the
* part carries, and how long that call has been running. The headline is derived
* from [ChatThread.phase] so the operator can tell generating from waiting on a
* command instead of watching a bare `Working…`; the elapsed values come from the
* turn's own start ([ChatThread.elapsedMillis]) and each call's own start
* ([ChatThread.toolElapsedMillis]), so they keep counting across a chat switch,
* and the tick loop stops the moment the turn settles.
*/
@Composable
private fun RunningIndicator(thread: ChatThread) {
val now = rememberElapsedNow(thread.runningSince)
val elapsedMillis = thread.elapsedMillis(now)
val tools = thread.runningTools
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Text(turnPhaseLabel(thread.phase(now)), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
text = "· ${formatDuration(elapsedMillis / 1_000)}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// One line per call in flight, in transcript order and keyed by the part,
// so several running at once read together rather than flickering between
// them; a call's line drops out the moment it completes or errors.
tools.forEach { part ->
key(part.id) { RunningToolLine(part, thread.toolElapsedMillis(part, now)) }
}
}
}
/**
* One tool call in flight: its name, the command or short description the part
* carries (when it carries one) and how long it has been running. A call that has
* been running past [TOOL_LONG_RUNNING_MILLIS] is tinted and labelled so a stuck
* call stands out. The elapsed time is the only progress signal; no percentage,
* ETA or progress bar is ever invented.
*/
@Composable
private fun RunningToolLine(part: ChatPart, elapsedMillis: Long) {
val long = toolLongRunning(elapsedMillis)
val tint = if (long) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant
val detail = toolDetail(part)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth().padding(start = CHAT_GUTTER),
) {
Icon(
Icons.Default.Build,
contentDescription = null,
tint = tint,
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = toolLabel(part),
style = MaterialTheme.typography.labelMedium,
color = tint,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (detail == null) Modifier.weight(1f) else Modifier,
)
if (detail != null) {
Text(
text = detail,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
Text(
text = formatDuration(elapsedMillis / 1_000) + if (long) " · long" else "",
style = MaterialTheme.typography.labelMedium,
color = tint,
)
}
}
/**
* How many running background tasks are visible at once in the chat bar. Beyond
* this the list scrolls instead of growing taller, so a burst of tasks cannot
* push the composer down the screen.
*/
internal const val BACKGROUND_TASK_VISIBLE_ROWS = 3
/**
* The tallest the running-task list is drawn: [BACKGROUND_TASK_VISIBLE_ROWS]
* entries at the platform minimum touch target plus the gaps between them. Past
* that the list scrolls rather than growing.
*/
internal fun backgroundTaskListMaxHeight(minTouch: Dp): Dp =
(minTouch + SPACING_XS) * BACKGROUND_TASK_VISIBLE_ROWS
/**
* The read-only task viewer for the background shells this chat still has
* running. A task that has exited is not a background task any more and is never
* listed, so the bar exists only while something is actually running and goes
* away when the last task ends. The list is capped at
* [BACKGROUND_TASK_VISIBLE_ROWS] rows and scrolls beyond that.
*/
@Composable
internal fun BackgroundProcessBar(
shells: List<ChatShell>,
selectedID: String?,
output: ChatShellOutputState?,
onSelect: (String?) -> Unit,
onRefresh: (String) -> Unit,
modifier: Modifier = Modifier,
) {
if (shells.isEmpty()) return
val selected = shells.firstOrNull { it.id == selectedID }
val minTouch = LocalMinimumInteractiveComponentSize.current
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = 4.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Text(
text = "Background tasks",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = "${shells.size} running",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = Modifier
.fillMaxWidth()
.heightIn(max = backgroundTaskListMaxHeight(minTouch))
.verticalScroll(rememberScrollState()),
) {
shells.forEach { shell ->
key(shell.id) {
BackgroundProcessLine(shell, selectedID == shell.id) {
onSelect(if (selectedID == shell.id) null else shell.id)
}
}
}
}
if (selected != null) {
BackgroundProcessDetail(selected, output, onRefresh)
}
}
}
/** One running shell task; selection reveals its read-only detail. */
@Composable
private fun BackgroundProcessLine(shell: ChatShell, selected: Boolean, onSelect: () -> Unit) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier
.fillMaxWidth()
.minimumInteractiveComponentSize()
.clickable(role = Role.Button, onClick = onSelect),
) {
Icon(
Icons.Default.PlayArrow,
contentDescription = null,
tint = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = "Running",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.tertiary,
)
Text(
text = shellCommandSummary(shell.command),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
if (selected) {
Text(
text = "Details",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/** Detail intentionally exposes only state known from verified lifecycle frames. */
@Composable
private fun BackgroundProcessDetail(shell: ChatShell, output: ChatShellOutputState?, onRefresh: (String) -> Unit) {
Surface(
color = MaterialTheme.colorScheme.surfaceContainer,
shape = RoundedCornerShape(CHAT_GUTTER),
modifier = Modifier.fillMaxWidth(),
) {
SelectionContainer {
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = Modifier.padding(CHAT_GUTTER),
) {
Text("Command", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(shell.command.ifBlank { "Unavailable" }, style = MaterialTheme.typography.bodyMedium)
Text("Task identity", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(shell.id, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)
Text("Status: running", style = MaterialTheme.typography.bodySmall)
when {
output?.loading == true -> CircularProgressIndicator(modifier = Modifier.size(ICON_STATUS_DP))
output?.error != null -> Row(horizontalArrangement = Arrangement.spacedBy(SPACING_XS)) {
Text(output.error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Text("Retry", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary,
modifier = Modifier.clickable { onRefresh(shell.id) })
}
output?.page?.unavailable == true -> Text("Output unavailable for this task.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
output?.page != null && output.page.output.isEmpty() -> Text("No output yet.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
output?.page != null -> {
Text("Output", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(output.page.output, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)
if (output.page.truncated) {
Text("Output is bounded to 64 KiB.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("Refresh", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary,
modifier = Modifier.clickable { onRefresh(shell.id) })
}
}
}
}
}
}
/**
* The wall clock, re-read once a second while a turn is in flight, so the
* indicator derives the elapsed time with [ChatThread.elapsedMillis] — the one
* derivation its unit test also shares — instead of subtracting the turn's start
* itself. Keyed on [runningSince] and only entered for a live turn, so a settled
* chat schedules nothing.
*/
@Composable
private fun rememberElapsedNow(runningSince: Long): Long {
var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }
LaunchedEffect(runningSince) {
if (runningSince <= 0) return@LaunchedEffect
while (true) {
nowMillis = System.currentTimeMillis()
delay(CHAT_ELAPSED_TICK_MILLIS)
}
}
return nowMillis
}
@Composable
private fun UserMessageItem(message: ChatMessage) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
) {
Surface(
shape = RoundedCornerShape(CHAT_GUTTER),
color = MaterialTheme.colorScheme.secondaryContainer,
modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP),
) {
SelectionContainer {
Column(Modifier.padding(CHAT_GUTTER)) {
// A user turn another device sent is attributed to it, so the
// transcript says who sent the message. Our own messages carry
// no label.
if (message.client.isNotBlank()) {
Text(
text = message.client,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
UserParts(message.parts)
}
}
}
}
}
/**
* One agent reply as a single bubble: the turn's one collapsible thinking block
* first, then its one tool-call summary chip, then its answer text. A turn's
* reasoning and answer are never mixed — the fold in [ChatTurn] keeps them
* separate, so the answer is never drawn inside the thinking block — and the
* whole reply is one item however many model steps produced it. The individual
* calls live inside the chip's popup, not in the transcript.
*/
@Composable
private fun AgentTurnItem(
turn: ChatTurn,
reasoning: ReasoningExpansion,
streaming: Boolean,
runningSince: Long,
toolStartedAt: Map<String, Long>,
onToggleReasoning: (String) -> Unit,
) {
// The turn's own timing for the collapsed thinking line: a streaming turn
// counts live from its own start (the same clock the running indicator uses,
// so the two never disagree), a settled turn shows the span its parts' timing
// envelopes report, and a turn with neither shows no duration rather than a
// guessed one. The same tick ages the summary chip's running calls, so its
// "long" mark never comes from a stale clock.
val now = if (streaming && runningSince > 0) rememberElapsedNow(runningSince) else 0L
val elapsedMillis: Long? = if (streaming && runningSince > 0) {
if (runningSince < now) now - runningSince else 0L
} else {
turn.elapsedMillis
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
) {
Surface(
shape = RoundedCornerShape(CHAT_GUTTER),
color = MaterialTheme.colorScheme.surfaceContainer,
modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP),
) {
SelectionContainer {
Column(Modifier.padding(CHAT_GUTTER)) {
val turnKey = reasoningTurnKey(turn.key)
ReasoningBlock(
turn = turn.reasoning,
expanded = reasoning.isExpanded(turnKey),
streaming = streaming,
elapsedMillis = elapsedMillis,
onToggle = { onToggleReasoning(turnKey) },
)
if (turn.tools.isNotEmpty()) {
ToolCalls(
parts = turn.tools,
live = streaming,
elapsedMillis = { part ->
runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, now)
},
)
}
if (turn.answer.isNotBlank()) MarkdownText(turn.answer)
}
}
}
}
}
/**
* A user turn: its text, then the files that rode with it. The attachments are
* the same [ChatProtocol.PART_FILE] parts the user bubble already renders, so the
* sent message shows its file in the transcript through the one display path
* rather than a second attachment list under the bubble.
*/
@Composable
private fun UserParts(parts: List<ChatPart>) {
val text = parts.filter { it.type == ChatProtocol.PART_TEXT || it.type.isBlank() }
.joinToString("\n") { it.text }
.trim()
val files = parts.filter { it.type == ChatProtocol.PART_FILE }
Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
if (text.isNotBlank()) Text(text, style = MaterialTheme.typography.bodyMedium)
files.forEach { FilePart(it) }
}
}
/**
* A turn's reasoning: one compact, muted line that names the block — its step
* count when it reasoned more than once, and its elapsed time when the turn's own
* timing is known — and expands on tap to the whole turn's reasoning in order,
* still muted so it stays secondary to the answer. The expansion state lives on
* the conversation keyed by the turn, so it survives the transcript disposing the
* item while the operator scrolls and a streaming turn keeps it as deltas arrive.
*/
@Composable
private fun ReasoningBlock(
turn: ReasoningTurn,
expanded: Boolean,
streaming: Boolean,
elapsedMillis: Long?,
onToggle: () -> Unit,
) {
if (turn.empty) return
val label = reasoningLabel(turn.count, streaming)
val duration = elapsedMillis?.let { formatDuration(it / 1_000) }
Column(Modifier.fillMaxWidth()) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier
.fillMaxWidth()
.minimumInteractiveComponentSize()
.clickable(role = Role.Button, onClick = onToggle)
.padding(vertical = SPACING_XS),
) {
Icon(
Icons.Default.Psychology,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ICON_INLINE_DP),
)
Text(
text = if (duration != null) "$label · $duration" else label,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
Icon(
imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
contentDescription = if (expanded) "Hide reasoning" else "Show reasoning",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ICON_INLINE_DP),
)
}
if (expanded) {
Text(
text = turn.text,
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Default),
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = ICON_INLINE_DP + CHAT_ITEM_GAP, bottom = CHAT_ITEM_GAP),
)
}
}
}
@@ -1,532 +0,0 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withLink
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.theme.HAIRLINE_DP
import net.awan.pipelines.ui.theme.pipelinesText
/**
* A small, dependency-free CommonMark subset for assistant prose. The brokered
* protocol carries assistant text as markdown and the reference experience renders
* it (research §1.2): body paragraphs, `#`..`######` headings, fenced code (the
* shared [CodeBlock], so the copy action comes for free), block quotes, bullet and
* ordered lists, `|` tables, thematic rules, and inline code / bold / italic /
* links. Anything outside the subset renders as plain text, never dropped.
*
* The parser is pure Kotlin (no Compose, no transport) so it is unit-testable; the
* composables below turn the same blocks into themed, selectable content.
*/
// ---- Parsed model ------------------------------------------------------------
internal sealed interface MdBlock
internal data class MdHeading(val level: Int, val text: String) : MdBlock
internal data class MdParagraph(val text: String) : MdBlock
internal data class MdCodeBlock(val language: String, val code: String) : MdBlock
internal data class MdQuote(val lines: List<String>) : MdBlock
internal data class MdListBlock(val ordered: Boolean, val items: List<String>) : MdBlock
internal data class MdTableBlock(val header: List<String>, val rows: List<List<String>>) : MdBlock
internal data object MdRule : MdBlock
internal sealed interface MdSpan
internal data class MdPlain(val text: String) : MdSpan
internal data class MdCodeSpan(val text: String) : MdSpan
internal data class MdStrong(val spans: List<MdSpan>) : MdSpan
internal data class MdEmphasis(val spans: List<MdSpan>) : MdSpan
internal data class MdLinkSpan(val spans: List<MdSpan>, val url: String) : MdSpan
// ---- Block parser ------------------------------------------------------------
/**
* Decodes the HTML entities an assistant message can carry: the server's own
* session export escapes text with Go's `html.EscapeString`, so a message that
* quotes an export arrives with `&#x27;`, `&quot;`, `&amp;` and friends still in
* it. The common named entities plus numeric decimal and hex references are
* decoded; an unknown or malformed reference is left exactly as written so no
* visible text is invented. A single left-to-right pass never re-decodes an entity
* produced by decoding another (`&amp;lt;` stays `&lt;`).
*/
internal fun decodeHtmlEntities(text: String): String {
if ('&' !in text) return text
return HTML_ENTITY.replace(text) { match ->
when (val body = match.groupValues[1]) {
"amp" -> "&"
"lt" -> "<"
"gt" -> ">"
"quot" -> "\""
"apos" -> "'"
"nbsp" -> "\u00A0"
"hellip" -> "\u2026"
"mdash" -> "\u2014"
"ndash" -> "\u2013"
"lsquo" -> "\u2018"
"rsquo" -> "\u2019"
"ldquo" -> "\u201C"
"rdquo" -> "\u201D"
else -> numericReference(body) ?: match.value
}
}
}
/** The character one numeric entity's body (`#27`/`#x1b`) names, or null. */
private fun numericReference(body: String): String? {
val codePoint = when {
body.startsWith("#x") || body.startsWith("#X") -> body.drop(2).toIntOrNull(16)
body.startsWith("#") -> body.drop(1).toIntOrNull()
else -> null
} ?: return null
return if (codePoint in 1..0x10FFFF) String(Character.toChars(codePoint)) else null
}
private val HTML_ENTITY = Regex("&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);")
/** Parses [source] into the block list the renderer walks. Never throws. */
internal fun parseMarkdown(source: String): List<MdBlock> {
val lines = decodeHtmlEntities(source).replace("\r\n", "\n").replace('\r', '\n').split('\n')
val blocks = mutableListOf<MdBlock>()
var i = 0
while (i < lines.size) {
val line = lines[i]
val trimmed = line.trim()
when {
trimmed.isEmpty() -> i++
fenceRun(trimmed) != null -> {
val fence = fenceRun(trimmed)!!
val language = trimmed.removePrefix(fence).trim().substringBefore(' ')
val code = mutableListOf<String>()
i++
while (i < lines.size && fenceRun(lines[i].trim()) == null) {
code.add(lines[i])
i++
}
if (i < lines.size) i++ // consume the closing fence
blocks.add(MdCodeBlock(language, code.joinToString("\n")))
}
headingLevel(trimmed) > 0 -> {
val level = headingLevel(trimmed)
blocks.add(MdHeading(level, trimmed.drop(level).trim().trimEnd('#')))
i++
}
isRule(trimmed) -> {
blocks.add(MdRule)
i++
}
trimmed.startsWith(">") -> {
val quote = mutableListOf<String>()
while (i < lines.size && lines[i].trim().startsWith(">")) {
quote.add(lines[i].trim().removePrefix(">").removePrefix(" ").trimEnd())
i++
}
blocks.add(MdQuote(quote))
}
isTableStart(lines, i) -> {
val header = splitRow(lines[i])
i += 2 // header + delimiter row
val rows = mutableListOf<List<String>>()
while (i < lines.size && lines[i].contains('|') && lines[i].isNotBlank()) {
rows.add(fitRow(splitRow(lines[i]), header.size))
i++
}
blocks.add(MdTableBlock(header, rows))
}
listMarker(line) != null -> {
val ordered = listMarker(line)!!.first
val items = mutableListOf<String>()
while (i < lines.size && listMarker(lines[i])?.first == ordered) {
items.add(listMarker(lines[i])!!.second)
i++
}
blocks.add(MdListBlock(ordered, items))
}
else -> {
val paragraph = mutableListOf(line.trim())
i++
while (i < lines.size && lines[i].isNotBlank() && !startsBlock(lines, i)) {
paragraph.add(lines[i].trim())
i++
}
blocks.add(MdParagraph(paragraph.joinToString(" ")))
}
}
}
return blocks
}
/** The fence run (` ``` ` / `~~~`) a line opens or closes with, or null. */
private fun fenceRun(trimmed: String): String? {
val first = trimmed.firstOrNull() ?: return null
if (first != '`' && first != '~') return null
val run = trimmed.takeWhile { it == first }
return if (run.length >= 3) run else null
}
private fun headingLevel(trimmed: String): Int {
val hashes = trimmed.takeWhile { it == '#' }.length
if (hashes == 0 || hashes > 6) return 0
return if (trimmed.length == hashes || trimmed[hashes] == ' ') hashes else 0
}
private fun isRule(trimmed: String): Boolean =
trimmed.length >= 3 && trimmed.all { it == trimmed[0] } && trimmed[0] in "-*_"
/** True when [lines] at [index] is a table header followed by a `---` delimiter row. */
private fun isTableStart(lines: List<String>, index: Int): Boolean {
if (index + 1 >= lines.size || !lines[index].contains('|')) return false
val delimiter = splitRow(lines[index + 1])
if (delimiter.isEmpty() || splitRow(lines[index]).size < 2) return false
return delimiter.all { cell -> cell.isNotEmpty() && cell.all { it == '-' || it == ':' } && cell.contains('-') }
}
/** Splits a table row on unescaped `|`, dropping the leading/trailing empty cell. */
private fun splitRow(line: String): List<String> =
line.trim().removePrefix("|").removeSuffix("|").split('|').map { it.replace("\\|", "|").trim() }
private fun fitRow(row: List<String>, size: Int): List<String> =
List(size) { row.getOrElse(it) { "" } }
/** The ordered flag and item text of a list line, or null for a non-item line. */
private fun listMarker(line: String): Pair<Boolean, String>? {
val trimmed = line.trimStart()
val orderedMatch = ORDERED_ITEM.matchEntire(trimmed)
if (orderedMatch != null) return true to orderedMatch.groupValues[2]
val bulletMatch = BULLET_ITEM.matchEntire(trimmed)
if (bulletMatch != null) return false to bulletMatch.groupValues[2]
return null
}
/** True when [lines] at [index] begins a block that must interrupt a paragraph. */
private fun startsBlock(lines: List<String>, index: Int): Boolean {
val trimmed = lines[index].trim()
return fenceRun(trimmed) != null ||
headingLevel(trimmed) > 0 ||
isRule(trimmed) ||
trimmed.startsWith(">") ||
listMarker(lines[index]) != null ||
isTableStart(lines, index)
}
// ---- Inline parser -----------------------------------------------------------
/**
* Parses inline markup in [text] into a flat span tree. Handles `` `code` ``,
* `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
* `http(s)://` autolinks; everything else stays plain text. Underscore emphasis
* requires word boundaries so `snake_case` is never italicised.
*/
internal fun parseInline(text: String): List<MdSpan> {
val spans = mutableListOf<MdSpan>()
val buffer = StringBuilder()
var i = 0
fun flush() {
if (buffer.isNotEmpty()) {
spans.add(MdPlain(buffer.toString()))
buffer.clear()
}
}
while (i < text.length) {
val c = text[i]
when {
c == '`' -> {
val end = text.indexOf('`', i + 1)
if (end > i) {
flush()
spans.add(MdCodeSpan(text.substring(i + 1, end)))
i = end + 1
} else {
buffer.append(c); i++
}
}
c == '*' || c == '_' -> {
val doubled = i + 1 < text.length && text[i + 1] == c
val marker = if (doubled) "$c$c" else c.toString()
val boundOk = c != '_' || i == 0 || !text[i - 1].isLetterOrDigit()
val end = if (boundOk) text.indexOf(marker, i + marker.length) else -1
val closes = end > i + marker.length &&
(c != '_' || end + 1 >= text.length || !text[end + 1].isLetterOrDigit())
if (closes) {
flush()
val inner = parseInline(text.substring(i + marker.length, end))
spans.add(if (doubled) MdStrong(inner) else MdEmphasis(inner))
i = end + marker.length
} else {
buffer.append(c); i++
}
}
c == '[' -> {
val close = text.indexOf(']', i + 1)
if (close > i && close + 1 < text.length && text[close + 1] == '(') {
val urlEnd = text.indexOf(')', close + 2)
val url = if (urlEnd > close) text.substring(close + 2, urlEnd).trim() else ""
if (url.isNotEmpty()) {
flush()
spans.add(MdLinkSpan(parseInline(text.substring(i + 1, close)), url))
i = urlEnd + 1
} else {
buffer.append(c); i++
}
} else {
buffer.append(c); i++
}
}
else -> {
val url = autolinkAt(text, i)
if (url != null) {
flush()
spans.add(MdLinkSpan(listOf(MdPlain(url)), url))
i += url.length
} else {
buffer.append(c); i++
}
}
}
}
flush()
return spans
}
/** A bare `http(s)://` URL starting exactly at [index], trailing punctuation trimmed. */
private fun autolinkAt(text: String, index: Int): String? {
if (!text.startsWith("http://", index) && !text.startsWith("https://", index)) return null
var end = index
while (end < text.length && !text[end].isWhitespace() && text[end] !in "<>\"'") end++
var url = text.substring(index, end)
while (url.isNotEmpty() && url.last() in ".,;:!?)]}") url = url.dropLast(1)
return url.takeIf { it.length > "https://".length }
}
private val ORDERED_ITEM = Regex("""^(\d{1,9})[.)]\s+(.*)$""")
private val BULLET_ITEM = Regex("""^([-*+])\s+(.*)$""")
// ---- Renderers ---------------------------------------------------------------
private val MD_QUOTE_BAR = 3.dp
private val MD_TABLE_BORDER = HAIRLINE_DP
/**
* Renders [text] as markdown at the app's shared body style. The caller owns the
* selection container (a chat message is one selectable region), so this only
* lays out the blocks.
*/
@Composable
internal fun MarkdownText(text: String, modifier: Modifier = Modifier) {
val blocks = remember(text) { parseMarkdown(text) }
Column(modifier, verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
blocks.forEach { MarkdownBlock(it) }
}
}
/**
* Renders already-parsed [blocks] as markdown in a lazy list, one block per item,
* so a large document (an exported session of several hundred kilobytes) composes
* only the blocks on screen instead of every block up front. The caller parses
* once and passes the result here ([MarkdownText] is the eager variant for short
* prose), so the same [MarkdownBlock] renderer draws both and there is no second
* markdown implementation.
*/
@Composable
internal fun MarkdownBlocks(
blocks: List<MdBlock>,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(vertical = CHAT_ITEM_GAP),
) {
LazyColumn(
modifier = modifier,
contentPadding = contentPadding,
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
itemsIndexed(blocks) { _, block -> MarkdownBlock(block) }
}
}
@Composable
internal fun MarkdownBlock(block: MdBlock) {
val texts = pipelinesText()
when (block) {
is MdHeading -> Text(
text = inline(block.text),
style = when (block.level) {
1 -> MaterialTheme.typography.titleLarge
2 -> MaterialTheme.typography.titleMedium
else -> texts.cardTitle
},
color = MaterialTheme.colorScheme.onSurface,
)
is MdParagraph -> Text(text = inline(block.text), style = texts.body)
is MdCodeBlock -> CodeBlock(label = block.language.ifBlank { "code" }, text = block.code)
MdRule -> HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
is MdQuote -> Row(Modifier.height(IntrinsicSize.Min)) {
Box(
Modifier
.width(MD_QUOTE_BAR)
.fillMaxHeight()
.background(MaterialTheme.colorScheme.outlineVariant),
)
Column(
modifier = Modifier.padding(start = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2),
) {
block.lines.forEach { line ->
if (line.isNotBlank()) {
Text(
text = inline(line),
style = texts.body,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
is MdListBlock -> Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2)) {
block.items.forEachIndexed { index, item ->
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Text(
text = if (block.ordered) "${index + 1}." else "•",
style = texts.body,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(text = inline(item), style = texts.body)
}
}
}
is MdTableBlock -> MarkdownTable(block)
}
}
@Composable
private fun MarkdownTable(table: MdTableBlock) {
val border = MaterialTheme.colorScheme.outlineVariant
val shape = RoundedCornerShape(CHAT_ITEM_GAP)
Column(
Modifier
.fillMaxWidth()
.clip(shape)
.border(MD_TABLE_BORDER, border, shape),
) {
TableRow(table.header, header = true, border = border)
table.rows.forEach { row ->
HorizontalDivider(color = border)
TableRow(row, header = false, border = border)
}
}
}
@Composable
private fun TableRow(cells: List<String>, header: Boolean, border: Color) {
val texts = pipelinesText()
Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
cells.forEachIndexed { index, cell ->
if (index > 0) {
Box(Modifier.width(MD_TABLE_BORDER).fillMaxHeight().background(border))
}
Text(
text = inline(cell),
style = if (header) texts.body.copy(fontWeight = FontWeight.Bold) else texts.body,
modifier = Modifier.weight(1f).padding(CHAT_ITEM_GAP),
maxLines = if (header) 1 else Int.MAX_VALUE,
overflow = TextOverflow.Ellipsis,
)
}
}
}
/** Inline text as one [AnnotatedString]; links are tappable and code is monospace. */
@Composable
private fun inline(text: String): AnnotatedString {
val linkColor = MaterialTheme.colorScheme.primary
val codeBackground = MaterialTheme.colorScheme.surfaceContainerHigh
val codeColor = MaterialTheme.colorScheme.onSurface
return remember(text, linkColor, codeBackground, codeColor) {
buildInline(parseInline(text), linkColor, codeBackground, codeColor)
}
}
private fun buildInline(
spans: List<MdSpan>,
linkColor: Color,
codeBackground: Color,
codeColor: Color,
): AnnotatedString = buildAnnotatedString { appendSpans(spans, linkColor, codeBackground, codeColor) }
private fun androidx.compose.ui.text.AnnotatedString.Builder.appendSpans(
spans: List<MdSpan>,
linkColor: Color,
codeBackground: Color,
codeColor: Color,
) {
for (span in spans) {
when (span) {
is MdPlain -> append(span.text)
is MdCodeSpan -> withStyle(
SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground, color = codeColor),
) { append(span.text) }
is MdStrong -> withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
appendSpans(span.spans, linkColor, codeBackground, codeColor)
}
is MdEmphasis -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
appendSpans(span.spans, linkColor, codeBackground, codeColor)
}
is MdLinkSpan -> withLink(
LinkAnnotation.Url(
span.url,
TextLinkStyles(style = SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)),
),
) { appendSpans(span.spans, linkColor, codeBackground, codeColor) }
}
}
}
@@ -1,170 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.NotificationsActive
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.AttentionKind
import net.awan.pipelines.ui.attentionDismissalSnapshot
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
/**
* The one attention surface: an indicator that is visible from wherever the
* operator is (it floats in the same bottom container as the destination pill,
* so it survives every destination and every pane) and opens into an ordered
* list. It is not a navigation destination, so it never competes with the pill.
*
* The indicator only appears while something genuinely needs the operator, and
* both its headline and the list order come from the pure `ui/Attention.kt`
* model, so what is shown matches what the fold decided.
*/
/** The importance glyph and tint a kind borrows from the run-status vocabulary. */
internal fun attentionRunState(kind: AttentionKind): RunState = when (kind) {
AttentionKind.Decision -> RunState.Waiting
AttentionKind.Failed -> RunState.Failed
}
/** The notifications action shared by the main and detail app bars. */
@Composable
fun AttentionAction(
entries: List<AttentionEntry>,
onClick: () -> Unit,
) {
IconButton(onClick = onClick) {
BadgedBox(badge = {
if (entries.isNotEmpty()) Badge { Text(entries.size.toString()) }
}) {
Icon(
imageVector = Icons.Default.NotificationsActive,
contentDescription = if (entries.isEmpty()) "Notifications" else
"Notifications, ${entries.size} needing attention",
modifier = Modifier.size(ICON_INLINE_DP),
)
}
}
}
/**
* The ordered attention list, in a bottom sheet so it opens over whatever the
* operator is looking at and closes back to it. Rows are already ordered by the
* pure model (decision, then failure, then finished). Tapping a row opens the run;
* the trailing action deliberately dismisses just that entry.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AttentionSheet(
entries: List<AttentionEntry>,
onOpen: (AttentionEntry) -> Unit,
onDismissEntry: (AttentionEntry) -> Unit,
onDismiss: () -> Unit,
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val dismissalSnapshot = remember { attentionDismissalSnapshot(entries) }
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
Column(
modifier = Modifier.fillMaxWidth().padding(bottom = SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(
text = "Needs you",
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(horizontal = SPACING_L),
)
if (entries.isEmpty()) {
Text(
text = "Nothing needs you right now.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = SPACING_L),
)
return@Column
}
TextButton(
onClick = { dismissalSnapshot.forEach(onDismissEntry) },
enabled = dismissalSnapshot.isNotEmpty(),
modifier = Modifier.padding(horizontal = SPACING_L),
) {
Text("Clear all")
}
entries.forEach { entry ->
AttentionRow(
entry = entry,
onOpen = { onOpen(entry) },
onDismiss = { onDismissEntry(entry) },
)
}
}
}
}
/** One attention row: what the run is, its pipeline, what it needs and a dismiss. */
@Composable
private fun AttentionRow(
entry: AttentionEntry,
onOpen: () -> Unit,
onDismiss: () -> Unit,
) {
val scheme = MaterialTheme.colorScheme
Surface(onClick = onOpen, color = Color.Transparent) {
Row(
modifier = Modifier.fillMaxWidth().padding(start = SPACING_L, top = SPACING_S, bottom = SPACING_S),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
RunStatusIcon(state = attentionRunState(entry.kind), contentDescription = null)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(
text = entry.label,
style = MaterialTheme.typography.bodyLarge,
color = scheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "${entry.pipeline} · ${entry.detail}",
style = MaterialTheme.typography.bodySmall,
color = scheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(onClick = onDismiss) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Dismiss",
tint = scheme.onSurfaceVariant,
)
}
}
}
}
@@ -1,15 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.platform.ClipboardManager
import androidx.compose.ui.text.AnnotatedString
/**
* The app's single copy-to-clipboard path: copies [text] to the platform
* clipboard through the Compose [ClipboardManager]. Every copy affordance (the
* code blocks, the pipeline source, the artifact link and the bulk artifact
* links) goes through here, so the behaviour and the clipboard payload can never
* drift between screens.
*/
internal fun ClipboardManager.copyText(text: String) {
setText(AnnotatedString(text))
}
@@ -1,141 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXL
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The one themed card for code-like content (Input, Output, Source, transcripts,
* per-field/evidence data, diagnostics). It matches the rest of the app's cards
* (surfaceContainerHigh role, default rounded shape, no elevation) rather than
* reading as a foreign bordered monospace box — one tonal step above both the
* app background and a pane's surfaceContainer container, so a card stays a card
* wherever it is placed. It adds:
*
* - a small label header naming the block plus a whole-block copy action;
* - monospace body at the shared [pipelinesText] `mono` size/line height;
* - a bounded height so long content scrolls *inside* the card instead of
* pushing the page down. The internal scroll is finite-height, so it is safe
* inside the tab's single LazyColumn (never an unbounded same-direction nest);
* a fade at the cut edge marks that more content remains below.
*
* Pass `maxHeight = null` to render the whole block unbounded and let the
* surrounding page scroll as a whole (used by the Source tab, whose single
* LazyColumn owns all scrolling). The default bounded behaviour is unchanged for
* every other caller.
*
* Blank content renders nothing, so callers never leave an empty block.
*/
@Composable
fun CodeBlock(
label: String,
text: String,
modifier: Modifier = Modifier,
maxHeight: Dp? = CODE_BLOCK_MAX_HEIGHT,
) {
if (text.isBlank()) return
val styles = pipelinesText()
val clipboard = LocalClipboardManager.current
// One scroll state for the bounded body, so the fade below tracks exactly the
// scroll the body performs.
val scrollState = rememberScrollState()
Card(
modifier = modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
) {
Column {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = SPACING_L, end = SPACING_XS, top = SPACING_XS, bottom = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(
text = label,
style = styles.label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
IconButton(onClick = { clipboard.copyText(text) }) {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = "Copy $label",
modifier = Modifier.size(ICON_INLINE_DP),
)
}
}
val bodyPadding = Modifier.padding(start = SPACING_L, end = SPACING_L, bottom = SPACING_L)
if (maxHeight != null) {
Box(Modifier.fillMaxWidth()) {
Text(
text = text,
style = styles.mono,
modifier = Modifier
.fillMaxWidth()
.heightIn(max = maxHeight)
.verticalScroll(scrollState)
.then(bodyPadding),
)
// A fade at the cut edge while more content remains below, so a
// value clipped at the cap reads as continuing rather than ended.
if (scrollState.canScrollForward) {
Box(
Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth()
.height(SPACING_XXL)
.background(
Brush.verticalGradient(
listOf(Color.Transparent, MaterialTheme.colorScheme.surfaceContainerHigh),
),
),
)
}
}
} else {
Text(
text = text,
style = styles.mono,
modifier = Modifier.fillMaxWidth().then(bodyPadding),
)
}
}
}
}
/** Bounded code-block height: beyond this the block scrolls internally. */
val CODE_BLOCK_MAX_HEIGHT = 320.dp
@@ -1,100 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.windowInsetsPadding
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 net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
/**
* 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(
// The banner sits directly under the status bar (the outer Scaffold
// zeroes its content insets), so it owns the top safe-area inset: the
// padding is inside the Surface so the banner colour covers the bar
// and any cutout, and the pane stack below consumes it so it is not
// applied a second time.
modifier = Modifier
.windowInsetsPadding(paneSafeArea().only(WindowInsetsSides.Top))
.padding(horizontal = SPACING_L, vertical = SPACING_S),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
Text(
text = text,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f),
)
if (actionLabel != null && onAction != null) {
TextButton(onClick = onAction, enabled = actionEnabled) { Text(actionLabel) }
}
}
}
}
@@ -1,266 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FrontHand
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.ui.DecisionDraft
import net.awan.pipelines.ui.DecisionOption
import net.awan.pipelines.ui.PendingDecision
import net.awan.pipelines.ui.decisionRefusalMessage
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The one place a run's pending human decision is surfaced: a prominent card
* ("Waiting for your decision") with a deliberate Decide action, plus the
* decision sheet it opens. It is rendered by the run detail and by the stage
* pane of the waiting stage, so the decision is reachable exactly where the
* operator already is rather than buried in a submenu; an attention surface can
* render the same component.
*
* [decision] is nullable because the host outlives it: when a decision is
* refused and the run has moved on, the refreshed run no longer carries a
* decision, but the already-open sheet is kept — with the server's own reason —
* until the operator dismisses it, instead of vanishing mid-report.
*
* [onSend] performs the request; it reports the outcome through its callback so
* this component owns no networking and is unit-testable through the pure
* [DecisionDraft]/[decisionRefusalMessage] model.
*/
@Composable
fun DecisionPrompt(
decision: PendingDecision?,
onSend: (decision: PendingDecision, option: String, feedback: String, onResult: (Result<RunDetail>) -> Unit) -> Unit,
modifier: Modifier = Modifier,
openRequest: Boolean = false,
onOpenRequestHandled: () -> Unit = {},
) {
val shown = rememberPaneContent(decision)
var open by remember { mutableStateOf(false) }
var draft by remember(shown?.runId, shown?.stageKey) { mutableStateOf(DecisionDraft()) }
var sending by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
// A notification's tap asks for the decision itself, not just the run:
// open the sheet once the waiting run's detail has loaded. The request is
// consumed here so a recomposition or a dismissal does not reopen it.
LaunchedEffect(decision?.runId, openRequest) {
if (openRequest && decision != null && !open) {
open = true
onOpenRequestHandled()
}
}
if (decision != null) {
DecisionCard(
decision = decision,
onOpen = {
error = null
open = true
},
modifier = modifier,
)
}
if (open && shown != null) {
DecisionSheet(
decision = shown,
draft = draft,
sending = sending,
error = error,
onDraftChange = { draft = it },
onDismiss = {
if (!sending) {
open = false
error = null
}
},
onConfirm = { option ->
sending = true
error = null
onSend(shown, option.key, draft.feedback) { result ->
sending = false
result.onSuccess { open = false }
result.onFailure { error = decisionRefusalMessage(it) }
}
},
)
}
}
/** The waiting-for-decision banner: the run, the stage and the deliberate action. */
@Composable
private fun DecisionCard(
decision: PendingDecision,
onOpen: () -> Unit,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
val scheme = MaterialTheme.colorScheme
Surface(modifier = modifier.fillMaxWidth(), color = scheme.secondaryContainer) {
Row(
modifier = Modifier.fillMaxWidth().padding(SPACING_L),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
Icon(
imageVector = Icons.Default.FrontHand,
contentDescription = null,
tint = scheme.onSecondaryContainer,
)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
Text(
"Waiting for your decision",
style = text.cardTitle,
color = scheme.onSecondaryContainer,
)
Text(
"${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}",
style = text.meta,
color = scheme.onSecondaryContainer,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
Button(onClick = onOpen) { Text("Decide") }
}
}
}
/**
* The decision sheet: the run and the waiting stage, the author's recorded
* instructions, their options exactly as written (each with what it routes to),
* an optional feedback field and a deliberate confirm. Selecting an option only
* selects it; nothing is sent until Confirm decision is pressed, so a stray tap
* can never answer for the operator. A refusal keeps the sheet open and shows
* the server's exact reason.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DecisionSheet(
decision: PendingDecision,
draft: DecisionDraft,
sending: Boolean,
error: String?,
onDraftChange: (DecisionDraft) -> Unit,
onDismiss: () -> Unit,
onConfirm: (DecisionOption) -> Unit,
) {
val text = pipelinesText()
val scheme = MaterialTheme.colorScheme
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = SPACING_L)
.padding(bottom = SPACING_XL),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text("Decide ${decision.stageKey}", style = text.screenTitle)
Text("run ${decision.runId} · ${decision.runLabel}", style = text.meta)
if (decision.instructions.isNotBlank()) {
Text(decision.instructions, style = text.body)
}
decision.options.forEach { option ->
DecisionOptionRow(
option = option,
selected = draft.selected == option.key,
onSelect = { onDraftChange(draft.select(option.key)) },
)
}
OutlinedTextField(
value = draft.feedback,
onValueChange = { onDraftChange(draft.withFeedback(it)) },
label = { Text("Feedback (optional)") },
modifier = Modifier.fillMaxWidth(),
)
if (error != null) {
Text(error, color = scheme.error, style = text.body)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(SPACING_S, Alignment.End),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onDismiss, enabled = !sending) { Text("Cancel") }
Button(
onClick = { decision.options.firstOrNull { it.key == draft.selected }?.let(onConfirm) },
enabled = draft.canSubmit && !sending,
) {
Text(if (sending) "Sending…" else "Confirm decision")
}
}
}
}
}
/**
* One selectable option row: a radio target carrying the author's option key and,
* when the graph declares it, the label it routes to. Tapping selects; it never
* answers.
*/
@Composable
private fun DecisionOptionRow(
option: DecisionOption,
selected: Boolean,
onSelect: () -> Unit,
) {
val text = pipelinesText()
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(selected = selected, role = Role.RadioButton, onClick = onSelect)
.padding(vertical = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
RadioButton(selected = selected, onClick = null)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
Text(option.key, style = text.cardTitle)
if (option.target.isNotBlank()) {
Text("→ ${option.target}", style = text.meta)
}
}
}
}
@@ -1,271 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Input
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.Hub
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.ICON_RAIL_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.WIDE_RAIL_WIDTH_DP
import net.awan.pipelines.ui.theme.pipelinesText
/**
* A named detail page tab: [key] is stable for `when` dispatch, [title] is shown,
* and [icon] is the tab's glyph on the wide rail.
*/
data class DetailTab(val key: String, val title: String, val icon: ImageVector)
/** Run-detail tabs, Summary first so it is the default selection. */
val runDetailTabs: List<DetailTab> = listOf(
DetailTab("summary", "Summary", Icons.Default.Info),
DetailTab("graph", "Graph", Icons.Default.Hub),
DetailTab("input", "Input", Icons.AutoMirrored.Filled.Input),
DetailTab("output", "Output", Icons.AutoMirrored.Filled.Send),
DetailTab("steps", "Timeline", Icons.AutoMirrored.Filled.List),
)
/**
* Resolves a run-detail selection from its stable [key], falling back to its
* index when it was produced by this version of the app. Saved selections from
* before Evidence was removed use the old index order: Evidence (4) deliberately
* returns to Summary and Timeline (5) moves to its new last index.
*/
fun runDetailTabIndex(key: String?, index: Int): Int {
val keyedIndex = key?.let { selectedKey -> runDetailTabs.indexOfFirst { it.key == selectedKey } }
if (keyedIndex != null && keyedIndex >= 0) return keyedIndex
return when (index) {
4 -> 0
5 -> runDetailTabs.lastIndex
else -> clampTabIndex(index, runDetailTabs.size)
}
}
/** Pipeline-detail tabs, Summary first (the version list lives inside it). */
val pipelineDetailTabs: List<DetailTab> = listOf(
DetailTab("summary", "Summary", Icons.Default.Info),
DetailTab("graph", "Graph", Icons.Default.Hub),
DetailTab("source", "Source", Icons.Default.Code),
)
/**
* Clamps a restored/persisted selected index into `[0, tabCount)`. A stale saved
* index (or a tab list that shrank) can therefore never index out of bounds.
*/
fun clampTabIndex(index: Int, tabCount: Int): Int =
if (tabCount <= 0) 0 else index.coerceIn(0, tabCount - 1)
/**
* The section index + its panel. On narrow windows the index is the shared
* [SelectorStrip] pinned to the bottom of the surface, in the thumb zone, with the
* panel filling the area above it; on wide windows it is an always-visible
* selectable rail on the left. Both stay fixed and visible while the selected
* section's panel swaps in place behind a short [Crossfade]: selecting a section
* is an ordinary tab change with no lateral motion and no swipe, because the
* sections are not a left-to-right pager. Only navigation between levels
* (list → detail → stage pane) slides, via
* [net.awan.pipelines.ui.components.SlidingPaneStack].
*
* [selectedIndex] is the single source of truth; a tap reports the new index
* through [onSelect]. Each section's own saved state (e.g. its list scroll
* position) is keyed by its stable tab key, so returning to a section restores
* where the operator left off instead of resetting it.
*/
@Composable
fun DetailTabs(
tabs: List<DetailTab>,
selectedIndex: Int,
onSelect: (Int) -> Unit,
wide: Boolean,
modifier: Modifier = Modifier,
content: @Composable (DetailTab, Modifier) -> Unit,
) {
if (tabs.isEmpty()) return
val selected = clampTabIndex(selectedIndex, tabs.size)
// One entry per stable tab key holds a section's state while that section is
// off-screen, so swapping sections never resets a section's scroll position
// (or any other saved state).
val stateHolder = rememberSaveableStateHolder()
// A short cross-fade replaces the section in place: the incoming panel fades
// in as the outgoing one fades out, with no horizontal travel.
val swap: @Composable (Modifier) -> Unit = { contentModifier ->
Crossfade(
targetState = selected,
animationSpec = MotionStandard.spec(),
modifier = contentModifier,
label = "section-swap",
) { index ->
val tab = tabs[clampTabIndex(index, tabs.size)]
stateHolder.SaveableStateProvider(tab.key) {
content(tab, Modifier.fillMaxSize())
}
}
}
if (wide) {
Row(modifier.fillMaxSize()) {
Column(
modifier = Modifier
.width(WIDE_RAIL_WIDTH_DP.dp)
.fillMaxHeight()
.padding(vertical = SPACING_S),
) {
Column(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.selectableGroup()
.padding(top = SPACING_S, bottom = SPACING_S),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
tabs.forEachIndexed { index, tab ->
RailTab(
tab = tab,
selected = index == selected,
onClick = { onSelect(index) },
)
}
}
}
VerticalDivider()
Box(Modifier.weight(1f).fillMaxHeight()) {
swap(Modifier.fillMaxSize())
}
}
} else {
Column(modifier.fillMaxSize()) {
// The content fills the area above the strip; the selector sits after it,
// pinned to the bottom where a thumb reaches, instead of scrolling away
// at the top of a tall screen.
swap(Modifier.weight(1f).fillMaxWidth())
SelectorStrip(
entries = detailSelectorEntries(tabs),
selectedIndex = selected,
onSelect = onSelect,
)
}
}
}
/**
* One wide-rail tab: an icon+label row. Selection is conveyed by the tab
* semantics (Role.Tab + selected) and the container colour, not colour alone.
*/
@Composable
private fun RailTab(tab: DetailTab, selected: Boolean, onClick: () -> Unit) {
val text = pipelinesText()
val contentColor = if (selected) {
MaterialTheme.colorScheme.onSecondaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(selected = selected, role = Role.Tab, onClick = onClick)
.background(
if (selected) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent,
)
.padding(horizontal = SPACING_L, vertical = SPACING_M),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
Icon(
imageVector = tab.icon,
// The label names the tab, so the glyph is decorative.
contentDescription = null,
tint = contentColor,
modifier = Modifier.size(ICON_RAIL_DP),
)
Text(
text = tab.title,
style = text.cardTitle,
color = contentColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
/**
* Gives a tab body the complete safe-area width supplied by its page container.
* Internal content remains responsible for any narrower, purpose-specific layout
* such as chat bubbles.
*/
@Composable
fun DetailTabBody(
wide: Boolean,
modifier: Modifier = Modifier,
content: @Composable (Modifier) -> Unit,
) {
content(modifier.fillMaxSize())
}
/**
* Remembers which inner sections are expanded, keyed by their stable section
* key and saved across configuration changes. Sections start collapsed; the
* operator's own expand/collapse choices are then persisted (as an [ArrayList]
* a Bundle can hold).
*/
@Stable
class SectionExpansionState internal constructor(
private val expanded: androidx.compose.runtime.MutableState<Set<String>>,
) {
fun isExpanded(key: String): Boolean = key in expanded.value
fun toggle(key: String) {
expanded.value = if (key in expanded.value) expanded.value - key else expanded.value + key
}
}
private val expandedKeysSaver: Saver<Set<String>, ArrayList<String>> = Saver(
save = { ArrayList(it) },
restore = { it.toSet() },
)
@Composable
fun rememberSectionExpansion(vararg inputs: Any?): SectionExpansionState {
val expanded = rememberSaveable(*inputs, stateSaver = expandedKeysSaver) {
mutableStateOf(emptySet())
}
return remember(expanded) { SectionExpansionState(expanded) }
}
@@ -1,191 +0,0 @@
package net.awan.pipelines.ui.components
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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
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.filled.Check
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.toggleableState
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The tallest a list-filter menu may grow, as a fraction of the window height.
* Deliberately well under the window so the bottom sheet that presents the
* filters always leaves the app bar (and the list behind it) visible; beyond this
* the sheet's body scrolls rather than growing to cover the whole screen.
*/
internal fun filterMenuMaxHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.7f).dp
/**
* The filter icon's content description. With active filters the count is spoken
* ("Filter runs, 2 filters active") so the badge is not a purely visual signal;
* with none the plain [base] stands.
*/
internal fun filterMenuDescription(base: String, activeCount: Int): String = when {
activeCount <= 0 -> base
activeCount == 1 -> "$base, 1 filter active"
else -> "$base, $activeCount filters active"
}
/**
* The shared list-filter control: a top-bar icon carrying an active-filter count
* badge, opening the caller's [optionContent] plus one [resetLabel] action. It is
* its own action with a distinct glyph and content description, so it cannot
* collide with the adjacent sort or refresh actions, and the same control serves
* both list widths.
*
* The options are presented as a Material modal bottom sheet, not an anchored
* menu: the sheet is bottom-anchored and scrolls, so a filter popup can never grow
* up over the app-bar title, and its body is capped at a window-derived
* [filterMenuMaxHeight] (leaving the app bar visible) with a familiar scroll
* affordance. [activeCount] is drawn as a numeric badge (0 hides it) and folded
* into the icon's description, so "filters are active" is never colour alone and
* the count is announced. [optionContent] receives a `dismiss` callback: a
* single-select entry calls it to close the sheet, while a multi-select toggle
* simply omits it to keep the sheet open.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FilterMenu(
activeCount: Int,
contentDescription: String,
resetLabel: String,
onReset: () -> Unit,
modifier: Modifier = Modifier,
optionContent: @Composable (dismiss: () -> Unit) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val maxMenuHeight = filterMenuMaxHeight(LocalConfiguration.current.screenHeightDp)
Box(modifier) {
BadgedBox(
badge = {
if (activeCount > 0) {
Badge { Text(activeCount.toString()) }
}
},
) {
IconButton(onClick = { expanded = true }) {
Icon(
Icons.Default.FilterList,
contentDescription = filterMenuDescription(contentDescription, activeCount),
)
}
}
}
if (expanded) {
ModalBottomSheet(
onDismissRequest = { expanded = false },
sheetState = sheetState,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = maxMenuHeight)
.verticalScroll(rememberScrollState())
.padding(bottom = SPACING_L),
) {
Row(
modifier = Modifier.fillMaxWidth().padding(start = SPACING_L, end = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = "Filters",
style = pipelinesText().label,
color = MaterialTheme.colorScheme.primary,
)
TextButton(
onClick = {
onReset()
expanded = false
},
enabled = activeCount > 0,
) {
Text(resetLabel)
}
}
HorizontalDivider()
optionContent { expanded = false }
}
}
}
}
/**
* One checkable filter entry, sharing the sort menu's leading-check idiom so the
* active value is conveyed by a glyph as well as by text, and exposing the
* checked state to accessibility ([toggleableState] plus [Role.Checkbox]) so
* TalkBack announces which facet is selected rather than only the label. The
* caller decides whether to dismiss: a single-select option closes the menu, a
* multi-select toggle leaves it open so several values can be gathered.
*/
@Composable
fun FilterCheckItem(
label: String,
checked: Boolean,
onClick: () -> Unit,
) {
DropdownMenuItem(
text = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = onClick,
modifier = Modifier.semantics {
role = Role.Checkbox
toggleableState = if (checked) ToggleableState.On else ToggleableState.Off
},
leadingIcon = {
if (checked) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
)
}
/** A small section caption inside a menu (a filter facet or a sort's reach). */
@Composable
fun FilterSectionHeader(label: String) {
Text(
text = label,
style = pipelinesText().label,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(horizontal = SPACING_M, vertical = SPACING_S),
)
}
@@ -1,26 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* One row's gallery geometry: the number of [columns] that fit and the width each
* [cell] is stretched to. Shared by every measured gallery in the app (the
* artifacts gallery and the templates gallery), so the fitting rule lives in
* exactly one place and neither screen picks its own column count.
*/
internal data class GalleryGrid(val columns: Int, val cell: Dp)
/**
* The gallery geometry for [availableWidth]: the most [preferred]-shaped cells
* that fit with their [spacing] gaps, and each cell widened to fill the row
* exactly. A window narrower than one preferred cell falls back to a single,
* narrower cell; a non-positive preferred token never divides by zero. Pure, so
* the fitting is unit-tested without a device.
*/
internal fun galleryGrid(availableWidth: Dp, preferred: Dp, spacing: Dp): GalleryGrid {
if (preferred <= 0.dp) return GalleryGrid(columns = 1, cell = availableWidth.coerceAtLeast(0.dp))
val columns = ((availableWidth + spacing) / (preferred + spacing)).toInt().coerceAtLeast(1)
val cell = ((availableWidth - spacing * (columns - 1)) / columns).coerceAtLeast(0.dp)
return GalleryGrid(columns = columns, cell = cell)
}
@@ -1,31 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
/**
* A small rounded tonal chip whose label carries its meaning, so it never relies
* on colour alone. One shape, colour and type across the app; a caller passes
* only the padding its context needs (the search row's type badge is tighter than
* the stage-type chip), so a second copy of the chip never appears.
*/
@Composable
internal fun LabelChip(label: String, horizontalPadding: Dp, verticalPadding: Dp) {
Surface(
shape = RoundedCornerShape(50),
color = MaterialTheme.colorScheme.secondaryContainer,
) {
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(horizontal = horizontalPadding, vertical = verticalPadding),
)
}
}
@@ -1,111 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.selection.selectable
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_XXS
/**
* One row of the shared real list used by the wide pipelines/runs panes (and the
* narrow list, so both stay identical).
*
* It is a single flat [Surface] — no per-row card or elevation — with a leading
* element, a title/secondary content column and a thin divider closing the row,
* so a stack of rows reads as one continuous list rather than a grid of tiles.
*
* The selected row uses the same tonal selected container as the wide rail and
* the bottom destinations ([MaterialTheme.colorScheme.secondaryContainer] with
* `onSecondaryContainer` content) and exposes its selection through
* `selectable`'s accessibility selected state, so selection is never conveyed by
* colour alone. The highlight fades in and out under [MotionQuick] rather than
* appearing at once; the settled row is exactly the selected/unselected row, so
* the resting appearance is unchanged.
*/
@Composable
fun ListRow(
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
leading: (@Composable () -> Unit)? = null,
role: Role = Role.Button,
content: @Composable ColumnScope.() -> Unit,
) {
val scheme = MaterialTheme.colorScheme
val container by animateColorAsState(
targetValue = if (selected) scheme.secondaryContainer else Color.Transparent,
animationSpec = MotionQuick.spec(),
label = "row-selection-container",
)
val contentColor by animateColorAsState(
targetValue = if (selected) scheme.onSecondaryContainer else LocalContentColor.current,
animationSpec = MotionQuick.spec(),
label = "row-selection-content",
)
Surface(
color = container,
contentColor = contentColor,
tonalElevation = 0.dp,
modifier = modifier
.fillMaxWidth()
.selectable(selected = selected, role = role, onClick = onClick),
) {
Column {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
leading?.invoke()
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
content()
}
}
HorizontalDivider(color = scheme.outlineVariant)
}
}
}
/**
* The one per-item animation for the app's lazy lists (pipelines, runs, version
* and evidence rows). It is Compose's supported lazy-list item animation
* (`Modifier.animateItem`, not the deprecated placement-only one), so the list
* keeps its own scroll/measure state and is never re-measured or janked:
*
* - an item fades in as it appears and out as it leaves ([MotionQuick], a small
* in-place state change);
* - while it is on screen and the list is refreshed, filtered or re-sorted, it
* slides to its new position ([MotionStandard]) instead of jumping;
* - the item's resting appearance is untouched — the modifier only drives the
* transition, so the settled list is exactly the list without it.
*
* The specs are built here at composition time, not per frame, and every token
* maps the system animator duration scale, so with animations disabled Compose
* runs each spec for zero time and the item is at its final state at once.
*/
internal fun LazyItemScope.animateListItem(modifier: Modifier = Modifier): Modifier = modifier.animateItem(
fadeInSpec = MotionQuick.spec(),
placementSpec = MotionStandard.spec(),
fadeOutSpec = MotionQuick.spec(),
)
@@ -1,55 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
/**
* A list's saved scroll position: the index of the first visible item and the
* pixel offset of that item from the viewport's top edge. Both are primitives, so
* the pair round-trips through a Bundle and survives a configuration change or
* process death; it is deliberately independent of any particular list, so the
* restore/clamp rule is pure and unit-testable without a device.
*/
internal data class ListScrollAnchor(val index: Int = 0, val offset: Int = 0)
/**
* The anchor to restore into a list of [itemCount] items: the saved index clamped
* to the nearest valid item, because the list can have shrunk since the anchor was
* written (a filter, a sort, a refresh, items removed). An empty list has no valid
* index, so it stays at the top. The saved pixel offset is kept only when the
* saved item itself survived; a clamped index points at a different item, so it
* starts at its own top rather than part-way down an unrelated row. Never throws,
* and never falls back to the top while the saved item still exists.
*/
internal fun restoredScrollAnchor(anchor: ListScrollAnchor, itemCount: Int): ListScrollAnchor {
if (itemCount <= 0) return ListScrollAnchor()
val index = anchor.index.coerceIn(0, itemCount - 1)
val offset = if (index == anchor.index) anchor.offset else 0
return ListScrollAnchor(index, offset)
}
/**
* Reconciles the live [state] with a list that now has [itemCount] items, so a
* list that changed underneath the operator clamps to the nearest sensible item
* instead of staying past the end (which would draw nothing) or jumping to the
* top. Keyed on [itemCount], so it runs once when the size settles and never on
* the operator's own scrolling — a scroll after coming back is therefore never
* overridden — and an unloaded list ([itemCount] 0) is left alone so a restored
* position is not reset to the top while the data is still on its way.
*/
@Composable
internal fun RestoreListScroll(state: LazyListState, itemCount: Int) {
if (itemCount <= 0) return
LaunchedEffect(itemCount) {
val target = restoredScrollAnchor(
ListScrollAnchor(state.firstVisibleItemIndex, state.firstVisibleItemScrollOffset),
itemCount,
)
if (target.index != state.firstVisibleItemIndex ||
target.offset != state.firstVisibleItemScrollOffset
) {
state.scrollToItem(target.index, target.offset)
}
}
}
@@ -1,57 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
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.draw.clip
import androidx.compose.ui.graphics.Color
import net.awan.pipelines.ui.RunStreamState
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* A small, honest statement of whether the live run stream is delivering pushes,
* shown in the runs list and the run detail so the operator can trust what is on
* screen instead of assuming it is current. Colour is never the only signal: the
* accompanying word ("live"/"reconnecting"/"not live") says it too.
*
* Geometry reuses the shared spacing tokens (the dot is one [SPACING_S] square)
* rather than new literals.
*/
@Composable
fun LiveBadge(state: RunStreamState, modifier: Modifier = Modifier) {
val text = pipelinesText()
val color: Color = when (state) {
RunStreamState.Live -> MaterialTheme.colorScheme.primary
RunStreamState.Connecting -> MaterialTheme.colorScheme.tertiary
RunStreamState.Offline -> MaterialTheme.colorScheme.onSurfaceVariant
}
// A live stream gets a solid dot; a paused one a dimmed dot, so the two read
// apart at a glance as well as by the label.
val dotColor = if (state == RunStreamState.Live) color else color.copy(alpha = PAUSED_DOT_ALPHA)
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Box(
modifier = Modifier
.size(SPACING_S)
.clip(CircleShape)
.background(dotColor),
)
Text(state.label, style = text.label, color = color)
}
}
/** How faint the dot is while reconnecting or offline. */
private const val PAUSED_DOT_ALPHA = 0.4f
@@ -1,53 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import kotlinx.coroutines.delay
/** A live value advances once a second, never per frame. */
private const val LIVE_TICK_MILLIS = 1_000L
/**
* Whether the host activity is resumed. The one background/focus gate every live
* ticking value shares, so a backgrounded app never keeps waking up once a second
* just to repaint a number nobody can see.
*/
@Composable
internal fun hostResumed(): Boolean {
val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
return lifecycleState.isAtLeast(Lifecycle.State.RESUMED)
}
/**
* The device clock in epoch millis, advanced once a second while [ticking] is
* true and the host is resumed, and frozen at its last reading otherwise. The
* single ticker behind every live elapsed readout: callers derive their value
* from the server's own start timestamp and this clock, so the numbers stay
* correct after a reconnect (never anchored to when the app happened to load),
* a screen full of running rows runs one coroutine rather than one per row, and
* nothing ticks for a finished run or while the app is backgrounded.
*
* The clock is re-read as the loop (re)starts, so a value frozen while
* backgrounded jumps straight to the correct elapsed on the first frame back.
*/
@Composable
internal fun rememberLiveNowMillis(ticking: Boolean): Long {
var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }
val live = ticking && hostResumed()
LaunchedEffect(live) {
if (!live) return@LaunchedEffect
nowMillis = System.currentTimeMillis()
while (true) {
delay(LIVE_TICK_MILLIS)
nowMillis = System.currentTimeMillis()
}
}
return nowMillis
}
@@ -1,61 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.Easing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.tween
/**
* The named motion tokens: the one place every animation duration and easing in
* the app is defined, alongside the pane's dimension tokens in
* [SlidingPaneStack]. No call site writes a duration of its own.
*
* There are two, matching the size of the change:
* - [MotionQuick] — a small state change that stays where it is: a chevron
* turning, a list row appearing or leaving. Deliberately short (100-150ms).
* - [MotionStandard] — content that moves or swaps: a pane sliding, a section
* cross-fading, a row taking its new place in a refreshed, filtered or
* re-sorted list (200-250ms).
*
* Nothing animates for longer than [MAX_MOTION_MILLIS] (~300ms). Both easings
* are monotonic ease-in-out curves and [MotionStandard] is symmetric, so an
* animation run backwards is the same curve travelled backwards (see
* [paneSlideSpec], whose exact reversal is a unit-tested property).
*
* A token carries only timing; a call site asks it for the concrete spec it
* needs through [spec]. The spec is built during composition (or when the state
* changes), never per frame: the frame loop only advances an animator Compose
* already owns, so an animation allocates nothing as it runs.
*/
internal data class MotionToken(val durationMillis: Int, val easing: Easing) {
init {
require(durationMillis in 1..MAX_MOTION_MILLIS) {
"motion duration out of range: $durationMillis (1..$MAX_MOTION_MILLIS)"
}
}
}
/** The longest any single animation may run, in milliseconds. */
internal const val MAX_MOTION_MILLIS = 300
/** The stagger between the levels of a multi-level pane pop, in milliseconds. */
internal const val MOTION_STAGGER_MILLIS = 60
/** Small, in-place state changes (~100-150ms). */
internal val MotionQuick = MotionToken(
durationMillis = 120,
easing = CubicBezierEasing(0.4f, 0f, 0.6f, 1f),
)
/** Content moving or swapping (~200-250ms); symmetric, so it reverses exactly. */
internal val MotionStandard = MotionToken(
durationMillis = 220,
easing = CubicBezierEasing(0.42f, 0f, 0.58f, 1f),
)
/** The one tween for this token, optionally staggered by [delayMillis]. */
internal fun <T> MotionToken.spec(delayMillis: Int = 0): TweenSpec<T> = tween(
durationMillis = durationMillis,
delayMillis = delayMillis,
easing = easing,
)
@@ -1,327 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.MIN_COVERED_PANE_WIDTH_DP
import net.awan.pipelines.ui.theme.PEEK_WIDTH_DP
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* One labelled statistic a covered pane shows: its [label] (e.g. `runs`) and its
* [value] (e.g. `11`). The label always travels with its value so a reader can
* tell what the number means, and a [detail] statistic is the kind dropped first
* when the strip is too thin.
*/
data class PaneStat(
val label: String,
val value: String,
val detail: Boolean = false,
)
/**
* How much of a covered pane's statistics block fits at a given width: the title
* only ([Title]), the run counts ([Counts]) or the full block including the last
* run and the average duration ([Full]).
*/
internal enum class PaneStatTier { Title, Counts, Full }
/**
* The statistics tier for a covered strip [widthDp]: a strip narrower than one
* tappable peek ([PEEK_WIDTH_DP]) is too thin even for a labelled number, so it
* keeps the title only; a strip at least one minimum covered pane wide plus one
* peek ([MIN_COVERED_PANE_WIDTH_DP] + [PEEK_WIDTH_DP]) has room for the longest
* line (the last run's status and age), so it shows the full block. The
* boundaries reuse the named identity-tier tokens rather than new literals, and
* the decision is pure so it is unit-testable without a device.
*/
internal fun paneStatTier(widthDp: Dp): PaneStatTier = when {
widthDp < PEEK_WIDTH_DP -> PaneStatTier.Title
widthDp < MIN_COVERED_PANE_WIDTH_DP + PEEK_WIDTH_DP -> PaneStatTier.Counts
else -> PaneStatTier.Full
}
/**
* The statistics of [stats] that fit [tier]: nothing at [PaneStatTier.Title]
* (never a bare figure without its label), only the run counts at
* [PaneStatTier.Counts], and every line at [PaneStatTier.Full]. Pure, so the
* degradation rule is asserted in a unit test without composing anything.
*/
internal fun visiblePaneStats(stats: List<PaneStat>, tier: PaneStatTier): List<PaneStat> = when (tier) {
PaneStatTier.Title -> emptyList()
PaneStatTier.Counts -> stats.filterNot { it.detail }
PaneStatTier.Full -> stats
}
/**
* The width a covered identity must reserve for its compact content: [contentWidth]
* (the wider of the title and the icon, already measured) plus the identity's own
* horizontal padding, floored at the platform touch target [minTouch]. When the
* identity carries statistics ([withStats]) it is also floored one touch target
* above the full statistics block's width ([MIN_COVERED_PANE_WIDTH_DP] +
* [PEEK_WIDTH_DP] + [minTouch]), because this width is spent on the covered region
* and when a second level is covered the nearest edge gives the thin older edge
* ([minTouch]; the leading gesture inset cancels against the region's own — see
* `coveredEdgesDp`) inside that region, so its visible edge is this width less
* [minTouch]. Flooring at the block alone left the nearest edge below the Full
* boundary of [paneStatTier], so a pipeline's last-run and average lines were
* filtered out at every depth it was covered; the floor is what makes them
* reachable. The invariant the unit test pins is therefore [paneStatTier] of the
* nearest *edge*, not of this width: pure, so the floor needs no device.
*/
internal fun coveredIdentityWidthDp(
contentWidth: Dp,
minTouch: Dp,
withStats: Boolean,
): Dp {
val statsWidth = if (withStats) MIN_COVERED_PANE_WIDTH_DP + PEEK_WIDTH_DP + minTouch else 0.dp
return maxOf(contentWidth + SPACING_S * 2, statsWidth, minTouch)
}
/**
* [title] laid out for a strip [maxWidthPx] wide and at most [maxLines] lines:
* words pack greedily onto whole-word lines and, once the lines are full, the
* remaining words are dropped and the last line is ellipsized at a word boundary,
* so a title is never broken mid-word. A word wider than the whole strip is the
* one exception — it is ellipsized to the width rather than wrapped, because it
* has no internal boundary to break at. [measure] returns a candidate line's width
* in pixels, injected so the packing rule is unit-testable without a device; blank
* input, no room or no lines yields an empty string.
*/
internal fun wholeWordTitle(
title: String,
maxWidthPx: Int,
maxLines: Int,
ellipsis: String,
measure: (String) -> Int,
): String {
if (maxWidthPx <= 0 || maxLines <= 0) return ""
val words = title.trim().split(WHITESPACE).filter { it.isNotEmpty() }
if (words.isEmpty()) return ""
val lines = mutableListOf<String>()
var line = ""
for (word in words) {
val candidate = if (line.isEmpty()) word else "$line $word"
if (line.isEmpty() || measure(candidate) <= maxWidthPx) {
line = candidate
} else {
lines += line
line = word
}
}
if (line.isNotEmpty()) lines += line
val truncated = lines.size > maxLines
val kept = if (truncated) lines.subList(0, maxLines) else lines
return kept.mapIndexed { index, keptLine ->
when {
measure(keptLine) > maxWidthPx -> ellipsizeToWidth(keptLine, maxWidthPx, ellipsis, measure)
truncated && index == kept.lastIndex -> appendEllipsis(keptLine, maxWidthPx, ellipsis, measure)
else -> keptLine
}
}.joinToString("\n")
}
/** The longest prefix of [text] that still leaves room for [ellipsis] in [maxWidthPx]. */
private fun ellipsizeToWidth(
text: String,
maxWidthPx: Int,
ellipsis: String,
measure: (String) -> Int,
): String {
if (measure(ellipsis) > maxWidthPx) return ""
var low = 0
var high = text.length
while (low < high) {
val mid = (low + high + 1) / 2
if (measure(text.substring(0, mid) + ellipsis) <= maxWidthPx) low = mid else high = mid - 1
}
return text.substring(0, low) + ellipsis
}
/** [line] with a trailing [ellipsis], dropping whole trailing words until it fits. */
private fun appendEllipsis(
line: String,
maxWidthPx: Int,
ellipsis: String,
measure: (String) -> Int,
): String {
var words = line.split(' ').filter { it.isNotEmpty() }
while (words.isNotEmpty() && measure(words.joinToString(" ") + " " + ellipsis) > maxWidthPx) {
words = words.dropLast(1)
}
return when {
words.isEmpty() -> ellipsizeToWidth(line, maxWidthPx, ellipsis, measure)
else -> words.joinToString(" ") + " " + ellipsis
}
}
private val WHITESPACE = Regex("\\s+")
/** At most three title lines in a covered strip; the statistics are secondary to it. */
private const val TITLE_MAX_LINES = 3
/**
* A covered pane's compact identity: its title and, when there are any, a
* compact vertical statistics block, both centred in the peek strip. A covered
* pane renders this instead of its full body, so its tab rail, list, gallery and
* scrollable body are never drawn squeezed into a sliver.
*
* The strip is narrow but the identity is the whole point of it, so the title
* wraps onto a few centered lines rather than becoming an unreadable ellipsis; it
* is the one place a title may legitimately run over more than one line. It wraps
* at whole-word boundaries and ellipsizes whole words rather than breaking one
* mid-word ([wholeWordTitle]), so a covered "Complete a Task" reads as whole words
* instead of "Complet"/"e a Task". The statistics are secondary to it and degrade
* with the width ([paneStatTier]): each is a label above its own value, only whole
* statistics are shown, and a strip too thin for a labelled number keeps the title
* alone — never a number clipped mid-digit or a figure without its label.
* [subtitle] remains for the panes whose covered identity is a single status/type
* word (the stage pane) rather than statistics, and [icon] is the pane-kind glyph
* drawn above the title.
*/
@Composable
fun PaneIdentity(
title: String,
subtitle: String? = null,
stats: List<PaneStat> = emptyList(),
icon: ImageVector? = null,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
val measurer = rememberTextMeasurer()
val density = LocalDensity.current
// The strip's width is measured here so the statistics block can degrade with
// the space actually available, never from a fixed depth assumption.
BoxWithConstraints(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
val shown = visiblePaneStats(stats, paneStatTier(maxWidth))
// Whole-word fit, measured against the strip's own text width (the
// identity's horizontal padding aside) so no word is split mid-word.
val titleLines = remember(title, maxWidth, text, measurer, density) {
wholeWordTitle(
title = title,
maxWidthPx = with(density) { (maxWidth - SPACING_S * 2).toPx() }.toInt(),
maxLines = TITLE_MAX_LINES,
ellipsis = "…",
measure = { candidate ->
measurer.measure(AnnotatedString(candidate), style = text.cardTitle).size.width
},
)
}
Column(
modifier = Modifier.padding(horizontal = SPACING_S, vertical = SPACING_M),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
if (icon != null) {
// Drawn at the vector's own default size, which is exactly what
// [rememberCompactIdentityWidth] measures, so the measured width
// and the drawn identity agree without a new size token.
Icon(imageVector = icon, contentDescription = null)
}
Text(
text = titleLines,
style = text.cardTitle,
textAlign = TextAlign.Center,
maxLines = TITLE_MAX_LINES,
overflow = TextOverflow.Ellipsis,
)
if (!subtitle.isNullOrBlank()) {
Text(
text = subtitle,
style = text.meta,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
if (shown.isNotEmpty()) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
shown.forEach { stat ->
// Each statistic is its own label above its value, so the
// number is on a line wide enough for it and never shares a
// line with a label that could push it into an ellipsis.
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = stat.label,
style = text.meta,
textAlign = TextAlign.Center,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = stat.value,
style = text.label,
textAlign = TextAlign.Center,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
}
}
/**
* The width one covered edge must have to show its compact identity: the wider of
* the identity [icon]'s own size and the measured width of [label] (the shortest
* label that identifies the pane, measured at runtime with the app's own type
* role and the platform's font metrics), plus the identity's own horizontal
* padding. When the identity carries statistics ([withStats]) it is also floored
* one touch target above the full statistics block's width, so a covered pane is
* not sized for its bare title while the statistics it must carry are always
* filtered out — the reserve covers the thin older edge the nearest identity
* gives up when a second level is covered ([coveredIdentityWidthDp] holds the
* pure rule). The platform minimum touch target is the floor for the whole edge,
* so an edge is never derived below what can be tapped. The caller passes this to
* `SlidingPaneStack`, which uses it as the whole covered region's width at every
* depth, so the nearest edge still clears the statistics block.
*/
@Composable
internal fun rememberCompactIdentityWidth(
label: String,
icon: ImageVector? = null,
withStats: Boolean = false,
): Dp {
val measurer = rememberTextMeasurer()
val text = pipelinesText()
val density = LocalDensity.current
val minTouch = LocalMinimumInteractiveComponentSize.current
return remember(measurer, label, icon, text, density, minTouch, withStats) {
val labelWidth = with(density) {
measurer.measure(
text = AnnotatedString(label),
style = text.cardTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
).size.width.toDp()
}
coveredIdentityWidthDp(maxOf(labelWidth, icon?.defaultWidth ?: 0.dp), minTouch, withStats)
}
}
@@ -1,53 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* The floating destination pill's clearance at the bottom of the content, as the
* app shell computes it for the current window and route (see
* `pillScrollInset`). It is published around the content so a scrollable screen
* can add it to its own scroll content's bottom padding and let its last row
* scroll clear of the pill, without the pill ever taking or positioning layout
* space. Defaults to zero, so a screen composed outside the app shell (a preview,
* a test) keeps exactly its own padding.
*/
internal val LocalPillBottomInset = compositionLocalOf { 0.dp }
/**
* [base] with the floating pill's clearance added at the bottom, for a scroll
* container's `contentPadding`. It adds the clearance **inside** the scroll
* content, so the container keeps its full height and its last row can still be
* scrolled into view above the pill; it is deliberately not a layout padding on
* the container, which would shrink the viewport and hide the row behind the pill
* instead. Returns [base] unchanged when no pill is drawn.
*/
@Composable
internal fun pillContentPadding(base: PaddingValues): PaddingValues {
val inset = LocalPillBottomInset.current
if (inset == 0.dp) return base
val direction = LocalLayoutDirection.current
return PaddingValues(
start = base.calculateLeftPadding(direction),
top = base.calculateTopPadding(),
end = base.calculateRightPadding(direction),
bottom = base.calculateBottomPadding() + inset,
)
}
/**
* Adds the floating pill's clearance as bottom padding on a scrollable's **own
* content** (a `Column` inside `verticalScroll`, or any content whose end must
* clear the pill), for the cases a `LazyColumn`'s `contentPadding` cannot reach.
* Like [pillContentPadding] it is content padding, not a layout inset, so the
* container keeps its full height and only its last content scrolls clear of the
* pill. A no-op when no pill is drawn.
*/
@Composable
internal fun Modifier.pillBottomPadding(): Modifier = padding(bottom = LocalPillBottomInset.current)
@@ -1,192 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.DirectionsRun
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.FrontHand
import androidx.compose.material.icons.filled.PauseCircle
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The run states the server can report, mirroring the vocabulary in
* internal/tui/run_progress.go and internal/protocol/stats.go
* (`running`/`queued`/`succeeded`/`failed`/`canceled`/`interrupted`, plus the
* `active` usage bucket). [Unknown] is the safe fallback for a blank or
* unrecognised status so a bad value never crashes the UI.
*/
enum class RunState(val label: String) {
Running("running"),
Queued("queued"),
Waiting("waiting"),
Succeeded("succeeded"),
Failed("failed"),
Canceled("canceled"),
Interrupted("interrupted"),
Blocked("blocked"),
Skipped("skipped"),
Active("active"),
Unknown("unknown"),
}
/**
* Maps a server status or outcome word to a [RunState], accepting the server's
* own vocabulary only. The step/outcome words (`success`/`completed`/`error`)
* map onto the same states so the list, detail summary and steps timeline all
* render one shared chip and icon set.
*/
fun runStateOf(status: String): RunState = when (status.trim().lowercase()) {
"running" -> RunState.Running
"queued" -> RunState.Queued
"waiting" -> RunState.Waiting
"active" -> RunState.Active
"succeeded", "success", "completed", "done" -> RunState.Succeeded
"failed", "error" -> RunState.Failed
"canceled", "cancelled" -> RunState.Canceled
"interrupted" -> RunState.Interrupted
"blocked" -> RunState.Blocked
"skipped" -> RunState.Skipped
else -> RunState.Unknown
}
/**
* Colour family for a state, from the app-owned [RunStatusPalette] (never
* colour-only: every chip also carries its glyph and label). Pure, so it can be
* asserted in a plain JVM unit test.
*/
fun runStateColor(state: RunState): Color = RunStatusPalette.of(state).color
/** A distinct glyph per state, all from the standard filled material icon set. */
fun runStateIcon(state: RunState): ImageVector = when (state) {
RunState.Running -> Icons.AutoMirrored.Filled.DirectionsRun
RunState.Queued -> Icons.Default.Schedule
RunState.Waiting -> Icons.Default.FrontHand
RunState.Succeeded -> Icons.Default.CheckCircle
RunState.Failed -> Icons.Default.Error
RunState.Canceled -> Icons.Default.Cancel
RunState.Interrupted -> Icons.Default.PauseCircle
RunState.Blocked -> Icons.Default.Block
RunState.Skipped -> Icons.Default.SkipNext
RunState.Active -> Icons.Default.Bolt
RunState.Unknown -> Icons.AutoMirrored.Filled.HelpOutline
}
/**
* A state glyph with an accurate [contentDescription]. Every glyph comes from the
* standard filled material icon set (the extended pack is declared as a
* dependency), all the same weight/family, so state is never conveyed by colour
* alone. The tint eases under [MotionQuick], so a live run's status change fades
* the accent colour rather than swapping it.
*/
@Composable
fun RunStatusIcon(
state: RunState,
contentDescription: String? = state.label,
modifier: Modifier = Modifier,
tint: Color = runStateColor(state),
) {
val animatedTint by animateColorAsState(
targetValue = tint,
animationSpec = MotionQuick.spec(),
label = "run-status-tint",
)
Icon(
imageVector = runStateIcon(state),
contentDescription = contentDescription,
tint = animatedTint,
modifier = modifier,
)
}
/**
* A pill pairing a glyph with its text label, coloured by the caller. Shared by
* the run-status chip and the timeline's step-outcome chip so both render one
* shape and neither repeats the layout. The glyph always carries a
* [contentDescription], so state/outcome is never colour alone. Its container,
* label and glyph all ease to the new colour under [MotionQuick], so a status or
* outcome change while the screen is open visibly transitions instead of
* silently swapping a colour; the chip is identical once settled.
*/
@Composable
internal fun ColoredChip(
label: String,
color: Color,
icon: ImageVector,
contentDescription: String? = label,
modifier: Modifier = Modifier,
) {
val animatedColor by animateColorAsState(
targetValue = color,
animationSpec = MotionQuick.spec(),
label = "status-chip-color",
)
Row(
modifier = modifier
.clip(RoundedCornerShape(50))
.background(animatedColor.copy(alpha = 0.16f))
.padding(horizontal = SPACING_S, vertical = SPACING_XXS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Icon(
imageVector = icon,
contentDescription = contentDescription,
tint = animatedColor,
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = label,
color = animatedColor,
fontWeight = FontWeight.Medium,
style = pipelinesText().label,
)
}
}
/** A colour-coded chip pairing a state glyph with its text label. */
@Composable
fun StatusChip(
label: String,
state: RunState,
modifier: Modifier = Modifier,
) {
ColoredChip(
label = label,
color = runStateColor(state),
icon = runStateIcon(state),
modifier = modifier,
)
}
/** Convenience: the run's own status word plus its colour-coded chip. */
@Composable
fun RunStatusChip(state: RunState, modifier: Modifier = Modifier) {
StatusChip(label = state.label, state = state, modifier = modifier)
}
@@ -1,97 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.graphics.Color
import net.awan.pipelines.ui.theme.DarkError
/**
* The app-owned status palette, the single source of truth for the colour of a
* status or stage-outcome word.
*
* Borrowing Material roles put the wrong hue on the two states that matter most —
* `primary` (mint) made a *running* run read green and `tertiary` (amber) made a
* *succeeded* run read yellow — so every entry below is a deliberate, fixed
* colour with an explicit meaning. The stage outcomes that share a word with a
* run state (`success`/`done`→[Succeeded], `error`→[Failed], `blocked`,
* `skipped`, `waiting`) resolve here too, through [runStateOf], so the timeline,
* the graph, the runs list, the stage sheet and the peek all draw one word in one
* colour. Only genuinely graph-only flow outcomes (`approved`, `retry`, …) keep
* their own curated colour in [net.awan.pipelines.ui.graph.GraphPalette].
*
* Every entry is tuned for the dark Pipelines surface (`DarkSurface 0xFF0E1513`,
* over which the chip label is drawn). The contrast of each colour against that
* surface is *measured* by `RunStatusPaletteTest`, never judged by eye. Status is
* never colour-only: every entry keeps its own material glyph ([runStateIcon])
* and its text label ([RunState.label]).
*/
internal object RunStatusPalette {
/** One status colour plus the one-line reason it is that hue. */
data class Entry(val color: Color, val rationale: String)
/** In progress: the conventional blue. Green would read as already finished. */
private val Running =
Entry(Color(0xFF7FB2F0), "blue: in progress; green would read as already finished")
/**
* Waiting for a person (a human decision): a distinct cyan, matching the TUI's
* accent for a paused run, so it is neither the running blue nor a failure.
*/
private val Waiting =
Entry(Color(0xFF8EDFF5), "cyan: paused for a person; distinct from running and from failure")
/** Finished well: the conventional green. Amber/tertiary would read as a warning. */
private val Succeeded =
Entry(Color(0xFF7FE0A8), "green: completed successfully; amber would read as a warning")
/** Failure: the app's error red, the one alarm colour the scheme already owns. */
private val Failed =
Entry(DarkError, "the app error red: an explicit failure, never a soft warning hue")
/** Stopped by the operator mid-flight: amber, a warning that is not a failure. */
private val Interrupted =
Entry(Color(0xFFE8C06A), "amber: stopped by the operator, a warning distinct from failure red")
/** Operator-cancelled: muted grey so a deliberate stop is quiet, not alarming. */
private val Canceled =
Entry(Color(0xFF889391), "muted grey: an operator cancel is quiet, not the failure red")
/** Waiting to start: neutral grey, deliberately not a hue that reads as running. */
private val Queued =
Entry(Color(0xFF9AA6A2), "neutral grey: waiting, clearly not the in-progress blue")
/**
* Parked on a person (a human decision): distinct from the in-progress blue, the
* queued grey and the amber operator-stop, so a run needing a decision is
* unmistakable. Blocked and skipped are stage outcomes rather than run states:
* a stage that could not proceed is orange, and one deliberately not run is a
* quiet grey-blue - neither is a failure.
*/
private val Blocked =
Entry(Color(0xFFF0A35E), "orange: a blocked stage could not proceed; not the failure red")
/** Skipped: a stage deliberately not run — a cool muted grey-blue, quiet and distinct. */
private val Skipped =
Entry(Color(0xFFA8B8C8), "muted grey-blue: a stage deliberately not run; quiet, not a status")
/** Unknown/blank status: the safe, low-key fallback. */
private val Unknown =
Entry(Color(0xFFBEC9C5), "neutral surface grey: an unrecognised status stays low-key")
/**
* The entry for [state]. [RunState.Active] shares [Running] (it is the server's
* `active` usage bucket, i.e. work in progress). Pure, so the palette is
* unit-testable without the Compose runtime.
*/
fun of(state: RunState): Entry = when (state) {
RunState.Running, RunState.Active -> Running
RunState.Waiting -> Waiting
RunState.Succeeded -> Succeeded
RunState.Failed -> Failed
RunState.Interrupted -> Interrupted
RunState.Canceled -> Canceled
RunState.Queued -> Queued
RunState.Blocked -> Blocked
RunState.Skipped -> Skipped
RunState.Unknown -> Unknown
}
}
@@ -1,194 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The one section header shared by both detail screens and the stage screen's
* compact section list: the section title in the theme's section-header style, a
* trailing chevron, an opaque background so content passing underneath a stuck
* header stays readable, and a subtle divider.
*
* [navigation] distinguishes the two behaviours the same row shape carries. A
* disclosure row (the default) toggles [expanded], its chevron rotates with the
* state (animated, no jump cut) and it reads as e.g. "Steps, expanded" with an
* "Expand Steps"/"Collapse Steps" action. A navigation row ([navigation] true)
* opens the section as its own pane instead: [expanded] is ignored, the chevron
* is the static forward arrow (mirrored for RTL) and it reads as "Steps" with an
* "Open Steps" action, so assistive tech is never told the row expands in place
* when it actually opens a surface of its own.
*
* [containerColor] is the opaque colour the header covers with. It defaults to
* the screen background so a stuck header on an ordinary page hides the content
* scrolling under it; a caller whose surface is a different container (the stage
* pane) passes that same colour so the header never reads as a differently toned
* band across its pane.
*/
@Composable
fun SectionHeader(
title: String,
expanded: Boolean,
onToggle: () -> Unit,
modifier: Modifier = Modifier,
containerColor: Color = MaterialTheme.colorScheme.background,
navigation: Boolean = false,
) {
// Only a disclosure row animates its chevron; a navigation row shows the
// static forward arrow, so no animator is composed for it.
val rotation = if (navigation) {
null
} else {
animateFloatAsState(
targetValue = if (expanded) 0f else -90f,
animationSpec = MotionQuick.spec(),
label = "section-chevron",
)
}
Column(
modifier = modifier
.fillMaxWidth()
// Opaque: the header is sticky, so content scrolls under it.
.background(containerColor)
.clickable(role = Role.Button, onClick = onToggle)
.clearAndSetSemantics {
if (navigation) {
contentDescription = title
role = Role.Button
onClick(label = "Open $title") {
onToggle()
true
}
} else {
contentDescription = "$title, ${if (expanded) "expanded" else "collapsed"}"
role = Role.Button
onClick(label = if (expanded) "Collapse $title" else "Expand $title") {
onToggle()
true
}
}
},
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(
text = title,
style = pipelinesText().sectionHeader,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
Icon(
imageVector = if (navigation) {
Icons.AutoMirrored.Filled.KeyboardArrowRight
} else {
Icons.Default.KeyboardArrowDown
},
contentDescription = null,
// Read the animating angle inside the layer so the chevron turns
// without recomposing the header on every frame.
modifier = if (rotation != null) {
Modifier.graphicsLayer { rotationZ = rotation.value }
} else {
Modifier
},
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
}
}
/**
* The one animated collapsible body: [content] expands and shrinks with a fade
* under [MotionQuick], the same token the section chevron turns with, so the
* body and the chevron move together instead of the content popping in after the
* chevron has already turned. Collapsed, [content] is not composed, so a closed
* section does no work and the resting layout is the collapsed header alone.
* With animations disabled Compose maps the platform animator duration scale
* onto the specs, so the body is at its final state at once.
*
* [content] is laid out in a single full-width [Column]: [AnimatedVisibility]
* measures *one* child, so several composables emitted straight into the body
* would be stacked on top of each other at the section's top instead of under
* their header (the "renders oddly at the top of the section" defect). The
* wrapper gives the transition exactly one child and lets a section hold any
* number of rows.
*/
@Composable
fun CollapsibleSectionBody(
expanded: Boolean,
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
AnimatedVisibility(
visible = expanded,
enter = expandVertically(animationSpec = MotionQuick.spec()) +
fadeIn(animationSpec = MotionQuick.spec()),
exit = shrinkVertically(animationSpec = MotionQuick.spec()) +
fadeOut(animationSpec = MotionQuick.spec()),
modifier = modifier,
) {
Column(Modifier.fillMaxWidth()) { content() }
}
}
/**
* Emits a collapsible [section] into a [LazyListScope]: a sticky header for the
* title and one body item after it, wrapped in [CollapsibleSectionBody] so the
* whole section animates as a unit. Nothing ever nests a scrollable, so the
* outer list keeps its own scroll and laziness.
*/
@OptIn(ExperimentalFoundationApi::class)
fun LazyListScope.collapsibleSection(
title: String,
key: Any,
expanded: Boolean,
onToggle: () -> Unit,
content: @Composable () -> Unit,
) {
stickyHeader(key = "section-$key") {
SectionHeader(title = title, expanded = expanded, onToggle = onToggle)
}
item(key = "section-$key-body") {
CollapsibleSectionBody(expanded) { content() }
}
}
@@ -1,246 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.ui.theme.HAIRLINE_DP
import net.awan.pipelines.ui.theme.ICON_RAIL_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* One entry of a bottom selector strip: its stable [key] (a selector's per-entry
* saved state — a section's list scroll position, say — is kept under it), the
* [label] it shows, an optional leading [icon] and an optional per-entry state
* [marker]. A [marker] is only ever set from state the model actually carries (a
* visit's recorded status or outcome); an entry whose model has no such state
* shows no marker rather than a stand-in for data that is not there.
*/
data class SelectorEntry(
val key: String,
val label: String,
val icon: ImageVector? = null,
val marker: RunState? = null,
)
/** Where a surface's selector sits: the wide left rail, the wide pinned top row, or the narrow bottom strip. */
enum class SelectorPlacement { Rail, TopRow, BottomStrip }
/**
* Where the shared detail selector sits: the always-visible left rail on a wide
* window (unchanged), the bottom strip on a narrow one. Pure, so the one
* arrangement rule is unit-testable without a device.
*/
internal fun detailSelectorPlacement(wide: Boolean): SelectorPlacement =
if (wide) SelectorPlacement.Rail else SelectorPlacement.BottomStrip
/**
* Where the visit selector sits: the pinned top row on a wide window (unchanged),
* the bottom strip on a narrow one — the same thumb-reachable treatment the detail
* selector gets, so both selectors read the same on a phone.
*/
internal fun visitSelectorPlacement(wide: Boolean): SelectorPlacement =
if (wide) SelectorPlacement.TopRow else SelectorPlacement.BottomStrip
/**
* Whether a selector with [entryCount] entries needs a strip at all: one entry has
* nothing to select between, so a single-entry surface shows no pointless strip and
* its content fills the whole area.
*/
internal fun selectorStripShown(entryCount: Int): Boolean = entryCount > 1
/**
* The strip entries for a detail tab list: each tab's stable key and its own title,
* with the rail's glyph. No marker is invented — a detail tab's model carries no
* per-entry state. Keeping the tab [DetailTab.key] as the entry key is what keeps a
* section's saved state keyed the same whether the selector is the rail or the strip.
*/
internal fun detailSelectorEntries(tabs: List<DetailTab>): List<SelectorEntry> =
tabs.map { SelectorEntry(key = it.key, label = it.title, icon = it.icon) }
/** The stable per-visit key, so a visit's saved state is keyed the same everywhere. */
internal fun visitSelectorKey(index: Int): String = "visit-${index + 1}"
/** The one wording a visit's entry carries, shared by the strip and the wide top row. */
internal fun visitSelectorLabel(index: Int): String = "visit ${index + 1}"
/**
* The marker for one visit: the state of the status (or, absent that, the outcome)
* the visit actually recorded. A visit that recorded neither shows no marker, so the
* strip never invents a state for it.
*/
internal fun visitMarker(step: RunStep): RunState? {
val word = step.status.ifBlank { step.outcome }
return if (word.isBlank()) null else runStateOf(word)
}
/**
* The visit strip entries: `visit N` with the marker of that visit's own recorded
* state, in recorded order, so the selected visit and every other visit's state are
* both readable at a glance.
*/
internal fun visitSelectorEntries(runSteps: List<RunStep>): List<SelectorEntry> =
runSteps.mapIndexed { index, step ->
SelectorEntry(
key = visitSelectorKey(index),
label = visitSelectorLabel(index),
marker = visitMarker(step),
)
}
/**
* How tall the bottom selector strip currently is in the composition it is shown in.
* The strip publishes its own measured height here while it is shown and resets it
* to zero when it goes away; the app shell reads it to lift the floating destination
* pill clear of the strip, so the two never overlap. It is a small mutable cell
* rather than a plain value because the strip measures itself and the shell reacts
* to that measurement, and it defaults to a fresh zero cell, so a strip composed
* outside the shell (a preview, a test) lifts nothing.
*/
class BottomStripInset {
var height: Dp by mutableStateOf(0.dp)
}
/** The live bottom-strip height, published by the app shell and written by the strip. */
internal val LocalBottomStripInset = compositionLocalOf { BottomStripInset() }
/**
* The one bottom selector strip: a full-width bar pinned to the bottom of the
* surface, in the thumb zone the caller already placed it above the system gesture
* inset, with its entries in a single horizontally scrolling row and the content
* filling the area above it. Each entry keeps at least the platform's minimum touch
* target and shows its whole label (never squeezed); the selected entry is
* unmistakable through the tab semantics and the container colour, not colour alone.
* A single entry (or none) draws no strip at all.
*/
@Composable
internal fun SelectorStrip(
entries: List<SelectorEntry>,
selectedIndex: Int,
onSelect: (Int) -> Unit,
modifier: Modifier = Modifier,
) {
if (!selectorStripShown(entries.size)) return
val selected = selectedIndex.coerceIn(0, entries.size - 1)
val inset = LocalBottomStripInset.current
val density = LocalDensity.current
Surface(
modifier = modifier
.fillMaxWidth()
.onSizeChanged { inset.height = with(density) { it.height.toDp() } },
color = MaterialTheme.colorScheme.surfaceContainer,
) {
Column {
HorizontalDivider(
thickness = HAIRLINE_DP,
color = MaterialTheme.colorScheme.outlineVariant,
)
Row(
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.selectableGroup()
.padding(horizontal = SPACING_S, vertical = SPACING_S),
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
) {
entries.forEachIndexed { index, entry ->
StripTab(
entry = entry,
selected = index == selected,
onClick = { onSelect(index) },
)
}
}
}
}
// Leaving the strip (a section with a single entry, or the pane going away)
// withdraws the clearance, so the pill drops back to its resting place.
DisposableEffect(inset) {
onDispose { inset.height = 0.dp }
}
}
/**
* One strip entry: its glyph (when it has one), its full label and its state marker
* (when the model carries one). It keeps at least the platform minimum touch target,
* and selection is conveyed by its tab semantics and container colour — the glyph
* and label are the same in both states, so nothing is conveyed by colour alone.
*/
@Composable
private fun StripTab(entry: SelectorEntry, selected: Boolean, onClick: () -> Unit) {
val text = pipelinesText()
val minTouch = LocalMinimumInteractiveComponentSize.current
val contentColor = if (selected) {
MaterialTheme.colorScheme.onSecondaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
Row(
modifier = Modifier
.heightIn(min = minTouch)
.selectable(selected = selected, role = Role.Tab, onClick = onClick)
.background(
color = if (selected) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent,
shape = MaterialTheme.shapes.small,
)
.padding(horizontal = SPACING_L, vertical = SPACING_S),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
entry.icon?.let { icon ->
Icon(
imageVector = icon,
// The label names the entry, so the glyph is decorative here.
contentDescription = null,
tint = contentColor,
modifier = Modifier.size(ICON_RAIL_DP),
)
}
Text(
text = entry.label,
style = text.cardTitle,
color = contentColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
entry.marker?.let { state ->
RunStatusIcon(state = state, modifier = Modifier.size(ICON_STATUS_DP))
}
}
}
@@ -1,397 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.systemGestures
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.width
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.MAX_PANE_DEPTH
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
// The covered region's width is not a token: it is measured from the compact
// identity a covered pane actually has to show (an icon plus the shortest label
// that identifies it) plus the leading gesture inset, so no screen or constant
// decides how much of a folded window the stack spends. The only fixed values
// left are platform ones: the minimum touch target that keeps an edge tappable
// and the leading system gesture inset this file already reads from the window.
/**
* The one slide timing every pane shares: the [MotionStandard] token, whose
* easing is symmetric (its control points mirror about the centre). The same
* curve run from the open offset back to the closed one is therefore exactly the
* open curve travelled backwards — closing a pane is the time-reverse of opening
* it, at the same [MotionStandard.durationMillis]. When several levels close in
* one tap the levels below the topmost wait [MOTION_STAGGER_MILLIS] each, so they
* reverse in order.
*/
/**
* The extra delay, in milliseconds, before the pane at [level] starts reversing
* for a stack whose visible depth just moved from [previousDepth] to [depth]. A
* single closing level is the exact reverse of opening it and starts at once;
* when more than one level was open and several are leaving, the topmost leaves
* first and each lower level waits one more [MOTION_STAGGER_MILLIS] so the
* cascade reads in order. A level that is open or opening never waits. Pure, so
* the mirror/stagger rule needs no device.
*/
internal fun paneSlideDelayMillis(level: Int, depth: Int, previousDepth: Int): Int {
if (level <= depth) return 0
val closing = previousDepth - depth
return if (closing > 1) (previousDepth - level) * MOTION_STAGGER_MILLIS else 0
}
/**
* The slide spec for the pane at [level]: the shared [MotionStandard] duration
* and easing in both directions, plus [paneSlideDelayMillis] when several levels
* pop together.
*/
internal fun paneSlideSpec(level: Int, depth: Int, previousDepth: Int): TweenSpec<Dp> =
MotionStandard.spec(delayMillis = paneSlideDelayMillis(level, depth, previousDepth))
/**
* The width of the pane whose open left edge is [offset] on a wide window: from
* that offset to the host's right edge. The active pane therefore measures the
* host less the covered region; a narrow host can never yield a negative width.
*/
internal fun paneWidthDp(hostWidth: Dp, offset: Dp): Dp =
maxOf(0.dp, hostWidth - offset)
/**
* One covered pane's visible edge in a wide stack's covered region, in
* left-to-right order. [level] is the pane whose compact identity the edge shows
* (for a folded edge, the newest of the levels it stands in for). [folded] is the
* number of *additional* older levels that edge represents, so those levels
* collapse into its count instead of spending width on each of them.
*/
internal data class PaneEdge(
val level: Int,
val start: Dp,
val width: Dp,
val folded: Int = 0,
)
/**
* The covered edges of a wide stack for [covered] covered levels, laid out inside
* the one covered region [region]. The region is derived from the measured
* compact-identity width (see [rememberCompactIdentityWidth]) plus the leading
* gesture inset [startInset], and is **the same at every depth**: the nearest
* covered level keeps the whole region less, at most, one thinner edge. The active
* pane's left edge — and therefore its width — is the region, so it never changes
* as levels are added. That is the invariant: opening another level only ever adds
* its own thin edge inside the region, never widens the region.
*
* The nearest covered level always shows its identity. One older level is shown
* as a thinner edge — the platform minimum touch target [minTouch], the thinnest
* an edge may be and stay tappable after [startInset] — and every level older than
* that collapses into that edge's [PaneEdge.folded] count rather than
* accumulating width. When the region cannot fit that thinner edge as well as a
* full [minTouch] identity, nothing is squeezed below the touch target: the older
* levels fold into the nearest edge's count instead. Pure, so the invariant, the
* thin edge and the fold rule need no device; an empty list means nothing is
* covered.
*/
internal fun coveredEdgesDp(
covered: Int,
region: Dp,
minTouch: Dp,
startInset: Dp,
): List<PaneEdge> {
if (covered <= 0 || region <= 0.dp) return emptyList()
val nearest = covered - 1
if (covered == 1) return listOf(PaneEdge(nearest, 0.dp, region))
// The thinner older edge keeps one touch target after the leading inset; the
// nearest identity needs one too, or the older levels fold into its count.
val older = startInset + minTouch
return if (region >= older + minTouch) {
listOf(
PaneEdge(
level = (covered - 2).coerceAtLeast(0),
start = 0.dp,
width = older,
folded = (covered - 2).coerceAtLeast(0),
),
PaneEdge(nearest, older, region - older),
)
} else {
listOf(PaneEdge(nearest, 0.dp, region, folded = covered - 1))
}
}
/**
* The one set of system insets every pane — and every overlay laid over a pane,
* such as the search field and its results panel — must clear: the status bar
* and any display cutout, the navigation bar and the IME
* ([WindowInsets.safeDrawing], read live from the window, never a fixed
* padding). A pane's [androidx.compose.material3.Scaffold] applies it to its
* content and its app bar applies its top/horizontal part, so a pane can never
* sit under the status bar, a cutout, the navigation bar or the keyboard.
*
* It is reserved exactly once: a parent that has already owned an inset (the
* connection banner owns the status bar while it is shown) consumes it, so the
* pane below it applies it once, never twice.
*/
@Composable
internal fun paneSafeArea(): WindowInsets = WindowInsets.safeDrawing
/**
* The one shared sliding pane stack, adaptive to the window width. Both the
* Pipelines and Runs destinations use it, so the motion and geometry live in
* exactly one place and the stage pane is the same third level as the detail.
*
* On a **narrow** window ([wide] false) it is not a stack at all: there is no
* peek and no leftover strip, and each opened pane is a full-window screen that
* slides in over the last. On a **wide** window ([wide] true) the panes stack:
* the covered panes sit under the active one, each showing its left edge, and the
* covered region's width is not a constant but is measured from the compact
* identity a covered edge has to show ([compactLabel], see
* [rememberCompactIdentityWidth]) plus the leading gesture inset. The active
* pane's left edge is always exactly that region, so its width is the same at
* every depth: opening another level only adds its own thin edge inside the
* region and never resizes the panes already there.
*
* A covered pane shows a compact identity only (its pane composable is told
* [covered] and is expected to render just a title/status), constrained to the
* visible edge, so its full body is never drawn into a sliver. The nearest
* covered level shows its identity; one older level is a thinner edge and every
* older level than that folds into that edge's count ([coveredEdgesDp]), so no
* level is ever squeezed below the platform minimum touch target.
*
* [depth] is the number of visible panes minus one (0..[MAX_PANE_DEPTH]);
* [pane] composes the level's content. The stack mounts a level while it is open
* or still sliding out, and calls [pane] only then, so the caller can name the
* level's content with [rememberPaneContent]: the level keeps rendering the
* content that opened it until it is fully closed, and a fully closed level is
* not composed at all (no work, no stale content). On a wide window, tapping a
* covered pane's peek calls [onPopTo] with that pane's level, closing every pane
* to its right; [backContentDescription] names each strip. On a narrow window
* there is no strip and Back/gesture/the pane's own back control pop the level.
*
* Each level has its own long-lived [animateDpAsState], so opening slides in and
* closing slides back out with no first-frame hack, and a rapid run of taps only
* retargets an existing animator (never half-slid). Opening and closing are exact
* mirrors: the same offsets and the one shared [paneSlideSpec] (a fixed duration
* and a symmetric easing, so running it backwards is the same curve reversed)
* are retargeted in reverse, and several levels closing in one tap reverse in
* order. A covered pane is hidden from accessibility and made non-interactive so
* TalkBack focus follows the top pane and a tap can never leak through to a
* covered one; on a wide window only its edge stays tappable.
*/
@Composable
fun SlidingPaneStack(
depth: Int,
wide: Boolean,
onPopTo: (Int) -> Unit,
compactLabel: String,
compactIcon: ImageVector? = null,
modifier: Modifier = Modifier,
backContentDescription: (Int) -> String = { "Back" },
compactStats: Boolean = false,
pane: @Composable (level: Int, covered: Boolean, modifier: Modifier) -> Unit,
) {
BoxWithConstraints(modifier.fillMaxSize()) {
// Measured once per layout. The insets are read once here and applied to
// the strip node's geometry (not via a padding modifier, which would
// shrink the pointer node to nothing once the gesture insets are wide).
val hostWidth = maxWidth
val insetPadding = paneSafeArea().union(WindowInsets.systemGestures)
.asPaddingValues()
val direction = LocalLayoutDirection.current
val startInset = insetPadding.calculateLeftPadding(direction)
val topInset = insetPadding.calculateTopPadding()
val bottomInset = insetPadding.calculateBottomPadding()
// The strip/compact identity area: the host clear of the top/bottom insets.
val stripHeight = maxOf(0.dp, maxHeight - topInset - bottomInset)
// Narrow: no peek at all, so every pane fills the host and the covered
// region is empty. Wide: the region is one measured compact identity plus
// the leading gesture inset; it is the same at every depth, so the active
// pane's width never depends on how deep the stack is. The platform's
// minimum interactive size is the floor for each tappable edge, never a
// literal.
val minTouch = LocalMinimumInteractiveComponentSize.current
val identityWidth = rememberCompactIdentityWidth(compactLabel, compactIcon, compactStats)
val region = if (wide) identityWidth + startInset else 0.dp
val edges = coveredEdgesDp(depth, region, minTouch, startInset)
val edgeByLevel = edges.associateBy { it.level }
val shownCovered = edges.map { it.level }.toSet()
// The active pane always opens at exactly the covered region's width (0
// when nothing is covered or the window is narrow, so it fills the host).
val activeStart = edges.fold(0.dp) { acc, edge -> acc + edge.width }
// The depth just before the current one, so a pop knows how many levels
// were open (to stagger their reversal). Held stable for a given depth so
// the slide spec never changes part-way through a slide.
val depthTrack = remember { PaneDepthTrack(depth) }
val closingFrom = remember(depth) { depthTrack.previous.also { depthTrack.previous = depth } }
// Panes 0..MAX are always given their own long-lived animator, in order,
// even while closed, so a retarget slides rather than jumps and the
// animator stays warm; a level beyond the depth waits exactly off the
// right edge. The one shared spec (see [paneSlideSpec]) makes closing the
// exact time-reverse of opening.
for (level in 0..MAX_PANE_DEPTH) {
val covered = level < depth
// A level folded into an older edge's count is not drawn on its own.
// A narrow window has no edges at all, so every covered level keeps
// composing its full body under the active one, as before.
if (covered && edges.isNotEmpty() && level !in shownCovered) continue
val edge = if (covered) edgeByLevel[level] else null
// An open pane sits at its edge's offset; a closed one waits exactly
// off the right edge. Its width is already the width it will have when
// open, so it slides rather than grows.
val openOffset = when {
level > depth -> hostWidth
level == depth -> activeStart
edge != null -> edge.start
else -> 0.dp
}
val openWidth = paneWidthDp(hostWidth, if (level <= depth) openOffset else region)
val offset by animateDpAsState(
targetValue = openOffset,
animationSpec = paneSlideSpec(level, depth, closingFrom),
label = "pane-slide-$level",
)
// A level is mounted while it is open or has not yet finished sliding
// out. An unmounted level keeps its animator warm but composes no
// content, so a fully closed pane does no work; a closing pane keeps
// rendering its content (retained by the caller) until it is off the
// screen, so it slides back out instead of vanishing.
val mounted = level <= depth || offset.value < hostWidth.value
if (mounted) {
Box(
Modifier
.offset(x = offset)
.width(openWidth)
.fillMaxHeight()
.then(if (level < depth) Modifier.blockPointerInput() else Modifier),
) {
if (edge != null) {
// Constrain the compact identity to the visible edge so it
// is centred in the space the covered pane actually has, and
// carry this level's share of the folded older levels as a
// count. It rides with the pane's own offset and slides in so
// it also slides back out with it.
val edgeInset = if (edge === edges.first()) startInset else 0.dp
Box(
Modifier
.align(Alignment.TopStart)
.offset(x = edgeInset, y = topInset)
.width(maxOf(0.dp, edge.width - edgeInset))
.height(stripHeight),
) {
pane(level, true, Modifier.fillMaxSize())
if (edge.folded > 0) {
Text(
text = "${edge.folded} more",
style = pipelinesText().meta,
modifier = Modifier
.align(Alignment.TopEnd)
.padding(SPACING_XS),
)
}
}
} else {
pane(level, false, Modifier.fillMaxSize())
}
}
}
// The covered pane's tappable edge (wide windows only): the edge
// between this pane's offset and the next pane's, clear of the
// status/nav bars and of the left gesture area. It sits above the
// pane's compact identity so tapping it closes every pane to its
// right; it never overlaps the next pane.
if (edge != null) {
val edgeInset = if (edge === edges.first()) startInset else 0.dp
Box(
Modifier
.align(Alignment.TopStart)
.offset(x = edge.start + edgeInset, y = topInset)
.width(maxOf(0.dp, edge.width - edgeInset))
.height(stripHeight)
.clickable(
role = Role.Button,
onClickLabel = backContentDescription(edge.level),
onClick = { onPopTo(edge.level) },
)
.semantics {
contentDescription = backContentDescription(edge.level)
role = Role.Button
},
)
}
}
}
}
/**
* Clears a pane's semantics and consumes every pointer event, so a covered pane
* is neither reachable by TalkBack nor tappable through the peek strip above it.
* Consuming in the Initial pass stops the pane's own rows (which would otherwise
* handle the event first, bottom-up); a peek strip is a separate, higher sibling
* and is the only node hit where it sits, so its tap is never affected.
*/
private fun Modifier.blockPointerInput(): Modifier = this
.clearAndSetSemantics { }
.pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
awaitPointerEvent(PointerEventPass.Initial).changes.forEach { it.consume() }
}
}
}
/** A tiny non-observable cell, so remembering a value never schedules recomposition. */
private class PaneMemory<T> {
var value: T? = null
}
/** The depth before the current one, tracked without scheduling recomposition. */
private class PaneDepthTrack(initial: Int) {
var previous: Int = initial
}
/**
* Keeps the last non-null [value] a pane was given, so a pane that is sliding
* out still renders the content that opened it after the selection naming it
* has been cleared. It is only called while the stack has the level mounted
* (open or still finishing its exit), so once the level is fully closed the
* remembered value is discarded and a closed pane does no work. A pane that
* opens later sets a fresh value, so nothing stale is ever shown.
*/
@Composable
internal fun <T : Any> rememberPaneContent(value: T?): T? {
val memory = remember { PaneMemory<T>() }
if (value != null) memory.value = value
return memory.value
}
@@ -1,74 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
/**
* The shared list-sort control: a top-bar icon that opens [options] plus a
* divider and a Reset entry. It is deliberately its own action with a distinct
* glyph and content description, so it cannot collide with the adjacent Refresh
* action or a future top-bar search entry point; a `DropdownMenu` anchors to the
* icon and works at both window widths (it is not width-dependent geometry).
*
* [selected] draws a leading check on its row, so the active choice is conveyed
* by a glyph as well as by text, never by colour alone. An optional [header]
* captions the menu, e.g. to say that an order applies to the results in hand
* rather than server-side.
*/
@Composable
fun <T> SortMenu(
options: List<T>,
selected: T,
label: (T) -> String,
contentDescription: String,
onSelect: (T) -> Unit,
onReset: () -> Unit,
modifier: Modifier = Modifier,
header: String? = null,
) {
var expanded by remember { mutableStateOf(false) }
Box(modifier) {
IconButton(onClick = { expanded = true }) {
Icon(Icons.AutoMirrored.Filled.Sort, contentDescription = contentDescription)
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
header?.let { FilterSectionHeader(it) }
options.forEach { option ->
DropdownMenuItem(
text = { Text(label(option)) },
onClick = {
onSelect(option)
expanded = false
},
leadingIcon = {
if (option == selected) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
)
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Reset") },
onClick = {
onReset()
expanded = false
},
)
}
}
}
@@ -1,201 +0,0 @@
package net.awan.pipelines.ui.components
import androidx.compose.animation.Crossfade
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.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
@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 = SPACING_M))
}
}
@Composable
fun ErrorState(message: String, onRetry: (() -> Unit)? = null, modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxSize().padding(SPACING_XL),
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 = SPACING_L)) { Text("Retry") }
}
}
}
/**
* An empty-list message. [actionLabel]/[onAction] add one recovery action (the
* "nothing matches the current filters" case offers Clear filters); both are
* omitted for the "nothing exists" case, where there is nothing to clear.
*/
@Composable
fun EmptyState(
message: String,
modifier: Modifier = Modifier,
actionLabel: String? = null,
onAction: (() -> Unit)? = null,
) {
Column(
modifier = modifier.fillMaxSize().padding(SPACING_XL),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = message,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (actionLabel != null && onAction != null) {
Button(onClick = onAction, modifier = Modifier.padding(top = SPACING_L)) {
Text(actionLabel)
}
}
}
}
/**
* The mutually exclusive presentation states of a data-backed pane: a load with
* no data yet ([Loading]), a failed load with no data ([Error]), loaded-but-
* nothing-to-show ([Empty]) and loaded content ([Content]).
*
* Both message-carrying states and [Empty] capture the text they are rendered
* with when the state is classified and never read a live value, so the branch
* that is fading out cannot be recomposed against a since-cleared error or a
* since-changed filter. [StateCrossfade] animates between these and a pane is in
* exactly one at a time.
*/
sealed interface LoadPhase {
/** A load is in flight and there is nothing to show yet. */
data object Loading : LoadPhase
/** The load failed and there is no data to fall back to. */
data class Error(val message: String) : LoadPhase
/**
* The load succeeded but there is nothing to show; [message] explains it and
* [actionLabel] optionally labels one recovery action (the "nothing matches
* the current filters" case offers Clear filters).
*/
data class Empty(val message: String, val actionLabel: String? = null) : LoadPhase
/** The loaded content. */
data object Content : LoadPhase
}
/**
* Classifies a list pane's [LoadPhase] from its load signals. A failed load with
* no data wins, then a list with no data yet ([loaded] false, or a load in
* flight), then an empty result; anything else is [LoadPhase.Content].
* [emptyMessage] is non-null exactly when the pane is empty and is the text to
* show, captured so a fading-out empty branch never reads a changed query;
* [emptyActionLabel] labels the one recovery action offered with that text (both
* are captured at classification).
*
* [loaded] is the pane's "data has arrived at least once" signal. Before the
* first load completes the initial state is both not-loading and data-less, and
* without this it would classify as content: a list that has never loaded must
* read as loading, not as an empty list, so a restored scroll position is never
* clamped against a list that is merely not there yet. It defaults to true so a
* pane that has no such signal keeps the previous behaviour.
*
* When stale data is present neither loading nor an error replaces it: the
* screen keeps showing the data and surfaces the error inline, so [hasData]
* suppresses both.
*/
fun listLoadPhase(
loading: Boolean,
error: String?,
hasData: Boolean,
emptyMessage: String?,
emptyActionLabel: String? = null,
loaded: Boolean = true,
): LoadPhase = when {
error != null && !hasData -> LoadPhase.Error(error)
!hasData && (loading || !loaded) -> LoadPhase.Loading
emptyMessage != null -> LoadPhase.Empty(emptyMessage, emptyActionLabel)
else -> LoadPhase.Content
}
/**
* Classifies a detail pane's [LoadPhase]. There is no empty state — a detail with
* no data is either an error or still loading — so data present means [Content],
* then a reported error, then [LoadPhase.Loading].
*/
fun detailLoadPhase(error: String?, hasData: Boolean): LoadPhase = when {
hasData -> LoadPhase.Content
error != null -> LoadPhase.Error(error)
else -> LoadPhase.Loading
}
/**
* Cross-fades a pane between its [LoadPhase] branches with the shared
* [MotionStandard] token. Both branches are laid out in the same box, so the
* resting layout is exactly the branch's own layout while the outgoing phase
* fades out under the incoming one: loading never flashes into content and an
* empty or error state fades in and out rather than popping. With system
* animations disabled Compose maps the platform animator duration scale onto the
* spec, so the swap is instant.
*/
@Composable
fun StateCrossfade(
phase: LoadPhase,
modifier: Modifier = Modifier,
content: @Composable (LoadPhase) -> Unit,
) {
Crossfade(
targetState = phase,
animationSpec = MotionStandard.spec(),
modifier = modifier,
label = "load-phase",
) { content(it) }
}
/** Renders a labelled key/value row used across detail screens. */
@Composable
fun KeyValueRow(
label: String,
value: String,
modifier: Modifier = Modifier,
monospace: Boolean = false,
) {
if (value.isBlank()) return
Column(modifier = modifier.fillMaxWidth().padding(vertical = SPACING_XS)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)
Text(
value,
style = MaterialTheme.typography.bodyMedium,
fontFamily = if (monospace) FontFamily.Monospace else null,
)
}
}
@@ -1,296 +0,0 @@
package net.awan.pipelines.ui.graph
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaDataSource
import android.media.MediaMetadataRetriever
import android.util.LruCache
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LinkOff
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.awan.pipelines.ui.theme.ARTIFACT_PROGRESS_DP
import net.awan.pipelines.ui.theme.ARTIFACT_PROGRESS_STROKE_DP
import net.awan.pipelines.ui.theme.ARTIFACT_THUMB_DP
import net.awan.pipelines.ui.theme.ARTIFACT_TYPE_ICON_DP
/**
* Encoded artifact bytes, fetched at most once per url and kept in memory so a
* recomposition or a second preview never re-hits the network. Bounded by total
* bytes so a long session never grows without limit; a single artifact larger
* than the budget is simply evicted rather than retained. The fetch itself runs
* on the repository's IO dispatcher.
*/
internal object ArtifactBytesCache {
private val cache = object : LruCache<String, ByteArray>(MAX_CACHED_BYTES) {
override fun sizeOf(key: String, value: ByteArray): Int = value.size
}
fun get(url: String): ByteArray? = cache.get(url)
fun put(url: String, bytes: ByteArray) {
cache.put(url, bytes)
}
}
/** Total encoded bytes held for artifact previews (16 MiB). */
private const val MAX_CACHED_BYTES = 16 * 1024 * 1024
/** Decoded previews, keyed by url + requested sample size, bounded by count. */
private val artifactBitmapCache = object : LruCache<String, Bitmap>(MAX_CACHED_BITMAPS) {
override fun sizeOf(key: String, value: Bitmap): Int = 1
}
private const val MAX_CACHED_BITMAPS = 24
/**
* One inline preview's state. [Unavailable] is deliberately separate from
* [Error]: it means no fetch was attempted because the artifact url could not be
* resolved against a configured server, so it must never be drawn with the
* failure mark (that would blame a load that never happened). [Error] is reserved
* for a fetch or decode that was actually attempted and failed.
*/
internal sealed interface ArtifactImageState {
data object Loading : ArtifactImageState
data object Unavailable : ArtifactImageState
data object Error : ArtifactImageState
data class Ready(val bitmap: Bitmap) : ArtifactImageState
}
/**
* An inline artifact preview. [url] is the resolved, absolute http(s) url, or
* null when the artifact could not be resolved (no configured server): a null url
* shows [ArtifactImageState.Unavailable] and issues no request at all. Fetching
* and decoding happen off the main thread and are cached; [maxDim] requests a
* thumbnail-sized decode (a full-resolution bitmap is only used for the explicit
* full-size view, [maxDim] <= 0).
*/
@Composable
internal fun ArtifactImage(
url: String?,
contentDescription: String?,
maxDim: Int,
fetchBytes: suspend (String) -> ByteArray?,
modifier: Modifier = Modifier,
size: Dp = ARTIFACT_THUMB_DP,
) {
val state = rememberArtifactBitmap(url, maxDim, fetchBytes)
Box(modifier.size(size), contentAlignment = Alignment.Center) {
when (val current = state) {
is ArtifactImageState.Ready -> Image(
bitmap = current.bitmap.asImageBitmap(),
contentDescription = contentDescription,
contentScale = ContentScale.Fit,
modifier = Modifier.size(size),
)
// A real, visible loading state: distinct from both the failure mark
// and the non-image file glyph.
ArtifactImageState.Loading -> CircularProgressIndicator(
modifier = Modifier.size(ARTIFACT_PROGRESS_DP),
strokeWidth = ARTIFACT_PROGRESS_STROKE_DP,
)
// No fetch was attempted (unresolved url): a link-off glyph, never
// the failure mark, and never the file-type icon of a non-image.
ArtifactImageState.Unavailable -> Icon(
imageVector = Icons.Filled.LinkOff,
contentDescription = contentDescription?.let { "$it unavailable" }
?: "Preview unavailable",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
ArtifactImageState.Error -> Text(
"!",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
}
}
@Composable
internal fun rememberArtifactBitmap(
url: String?,
maxDim: Int,
fetchBytes: suspend (String) -> ByteArray?,
): ArtifactImageState = rememberArtifactPreview(url, maxDim, "", fetchBytes, ::decodeSampled)
/**
* The shared memoized-preview scaffold behind [rememberArtifactBitmap] and
* [rememberArtifactVideoFrame]: a null [url] is [ArtifactImageState.Unavailable]
* with no request attempted, otherwise the bytes are fetched once through
* [ArtifactBytesCache] and [derive] runs off the main thread, its bitmap cached
* under a [keyTag]-tagged key (so an image and a video of one url never collide).
*/
@Composable
private fun rememberArtifactPreview(
url: String?,
maxDim: Int,
keyTag: String,
fetchBytes: suspend (String) -> ByteArray?,
derive: (ByteArray, Int) -> Bitmap?,
): ArtifactImageState {
if (url == null) return ArtifactImageState.Unavailable
val key = "$url@$keyTag$maxDim"
var state by remember(key) { mutableStateOf<ArtifactImageState>(ArtifactImageState.Loading) }
LaunchedEffect(key) {
artifactBitmapCache.get(key)?.let {
state = ArtifactImageState.Ready(it)
return@LaunchedEffect
}
val bytes = ArtifactBytesCache.get(url)
?: runCatching { withContext(Dispatchers.IO) { fetchBytes(url) } }.getOrNull()
if (bytes == null) {
state = ArtifactImageState.Error
return@LaunchedEffect
}
ArtifactBytesCache.put(url, bytes)
val bitmap = withContext(Dispatchers.IO) { derive(bytes, maxDim) }
if (bitmap == null) {
state = ArtifactImageState.Error
} else {
artifactBitmapCache.put(key, bitmap)
state = ArtifactImageState.Ready(bitmap)
}
}
return state
}
/**
* A video tile's still/poster frame: the artifact's bytes are fetched through the
* same bounded, off-main-thread path as an image ([rememberArtifactBitmap]'s
* cache), then the first sync frame is extracted with the platform
* [MediaMetadataRetriever] and cached. [url] null (no configured server) shows
* [ArtifactImageState.Unavailable] and issues no request; a fetch or extraction
* failure shows [ArtifactImageState.Error]. Unlike an image there is no honest
* "still" without a decodable frame, so both non-`Ready` states fall back to the
* video glyph the gallery would otherwise use.
*/
@Composable
internal fun ArtifactVideoFrame(
url: String?,
contentDescription: String?,
fetchBytes: suspend (String) -> ByteArray?,
modifier: Modifier = Modifier,
size: Dp = ARTIFACT_THUMB_DP,
) {
val state = rememberArtifactVideoFrame(url, VIDEO_FRAME_MAX_DIM, fetchBytes)
Box(modifier.size(size), contentAlignment = Alignment.Center) {
when (val current = state) {
is ArtifactImageState.Ready -> Image(
bitmap = current.bitmap.asImageBitmap(),
contentDescription = contentDescription,
contentScale = ContentScale.Crop,
modifier = Modifier.size(size),
)
ArtifactImageState.Loading -> CircularProgressIndicator(
modifier = Modifier.size(ARTIFACT_PROGRESS_DP),
strokeWidth = ARTIFACT_PROGRESS_STROKE_DP,
)
ArtifactImageState.Unavailable, ArtifactImageState.Error -> Icon(
imageVector = artifactIcon(ArtifactKind.Video),
contentDescription = contentDescription,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ARTIFACT_TYPE_ICON_DP),
)
}
}
}
/**
* The state of a video's poster frame at up to [maxDim] on its longest edge (0
* for the platform's native resolution). Same caching and off-main-thread
* behaviour as [rememberArtifactBitmap]; the full-size viewer shares it so a
* video's still is extracted once.
*/
@Composable
internal fun rememberArtifactVideoFrame(
url: String?,
maxDim: Int,
fetchBytes: suspend (String) -> ByteArray?,
): ArtifactImageState = rememberArtifactPreview(url, maxDim, "video", fetchBytes, ::extractVideoFrame)
/**
* The representative sync frame of [bytes] as a [maxDim]-bounded bitmap (native
* when [maxDim] <= 0), or null when the bytes are not a decodable video (or the
* platform retriever fails). Runs off the main thread; the bytes are handed over
* through an in-memory [MediaDataSource], so no temporary file is written.
*/
private fun extractVideoFrame(bytes: ByteArray, maxDim: Int): Bitmap? = runCatching {
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(ByteArrayMediaDataSource(bytes))
retriever.getFrameAtTime(-1L, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
} finally {
runCatching { retriever.release() }
}
}.getOrNull()?.let { scaleToMaxDim(it, maxDim) }
/** The in-memory [MediaDataSource] over fetched video [data] (no temp file). */
private class ByteArrayMediaDataSource(private val data: ByteArray) : MediaDataSource() {
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
if (position < 0 || position >= data.size) return -1
val count = minOf(size.toLong(), data.size - position).toInt()
System.arraycopy(data, position.toInt(), buffer, offset, count)
return count
}
override fun getSize(): Long = data.size.toLong()
override fun close() = Unit
}
/** [bitmap] scaled so its longest edge is at most [maxDim] (native when <= 0). */
private fun scaleToMaxDim(bitmap: Bitmap, maxDim: Int): Bitmap {
val longest = maxOf(bitmap.width, bitmap.height)
if (maxDim <= 0 || longest <= maxDim || longest == 0) return bitmap
val scale = maxDim.toFloat() / longest
return Bitmap.createScaledBitmap(
bitmap,
(bitmap.width * scale).toInt().coerceAtLeast(1),
(bitmap.height * scale).toInt().coerceAtLeast(1),
true,
)
}
/** Longest edge of a video poster-frame decode (the same shape as an image thumbnail). */
private const val VIDEO_FRAME_MAX_DIM = 320
/**
* Decodes [bytes], downsampling to roughly [maxDim] on the longest edge when
* [maxDim] > 0 (so the list never holds full-resolution bitmaps), or at full
* resolution when [maxDim] <= 0. Returns null on malformed data instead of
* throwing.
*/
private fun decodeSampled(bytes: ByteArray, maxDim: Int): Bitmap? = try {
if (maxDim <= 0) {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
} else {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
var sample = 1
while (bounds.outWidth / sample > maxDim || bounds.outHeight / sample > maxDim) {
sample *= 2
}
val options = BitmapFactory.Options().apply { inSampleSize = sample }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
}
} catch (_: Throwable) {
null
}
@@ -1,302 +0,0 @@
package net.awan.pipelines.ui.graph
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.only
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Share
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.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.paneSafeArea
/**
* Which artifacts an artifacts gallery currently has selected, identified by
* their recorded url (the app's artifact identity). It is a plain immutable
* value, so entering, toggling and clearing selection are unit-tested without a
* device.
*
* Selection mode is not a separate flag: it is exactly "at least one url is
* selected". That makes the mode impossible to restore half-applied — an empty
* set is never "selecting" — and toggling the last item off simply leaves the
* mode. [urls] keeps selection order, but the bulk copy resolves the surface's
* candidates in their own (gallery) order, so it writes one link per line in
* that order.
*/
internal data class ArtifactSelection(val urls: List<String> = emptyList()) {
/** The mode is active exactly while something is selected. */
val active: Boolean get() = urls.isNotEmpty()
/** The number of selected artifacts (what the action bar reports). */
val count: Int get() = urls.size
fun contains(url: String): Boolean = url in urls
/** Long-pressing an item starts selection on that one item. */
fun enter(url: String): ArtifactSelection = ArtifactSelection(listOf(url))
/** A tap while selecting adds/removes [url]; removing the last leaves the mode. */
fun toggle(url: String): ArtifactSelection =
if (contains(url)) ArtifactSelection(urls - url) else ArtifactSelection(urls + url)
/** Selects every one of [all] (de-duplicated); an empty input leaves the mode. */
fun selectAll(all: Collection<String>): ArtifactSelection = ArtifactSelection(all.distinct())
/** Leaves selection mode, discarding every selection. */
fun clear(): ArtifactSelection = ArtifactSelection()
}
/**
* The [candidates] that [selection] still selects, in candidate order. A
* restored or stale selection whose urls no longer map to the surface's own
* artifacts resolves to nothing, which is what keeps selection mode and the
* resolved set from drifting apart. Pure.
*/
internal fun resolvedSelection(
candidates: List<StageArtifact>,
selection: ArtifactSelection,
): List<StageArtifact> = if (selection.active) {
candidates.filter { selection.contains(it.url) }
} else {
emptyList()
}
/**
* Saves a selection as its selected urls (plain strings a Bundle can hold) and
* restores it through the data class, so a rotation/restore either brings back a
* fully applied selection or none at all.
*/
internal val ArtifactSelectionSaver = listSaver<ArtifactSelection, String>(
save = { it.urls },
restore = { ArtifactSelection(it) },
)
/**
* The artifact selection remembered/saved for the current [inputs] (so a pane
* switching runs or visits reseeds instead of inheriting the other context's
* selection) and restored across configuration changes.
*/
@Composable
internal fun rememberArtifactSelection(vararg inputs: Any?): MutableState<ArtifactSelection> =
rememberSaveable(*inputs, stateSaver = ArtifactSelectionSaver) {
mutableStateOf(ArtifactSelection())
}
/**
* The selected artifacts' resolved absolute links, one per line, dropping any
* that cannot be resolved against [configuredServerUrl]. The single line-joining
* path the bulk "Copy links" action uses; resolving goes through
* [resolvedArtifactUrl], so no host is ever hardcoded. The caller confirms the
* number of lines it actually produced, so the count can never drift from this
* payload. Pure.
*/
internal fun artifactSelectionLinks(
artifacts: List<StageArtifact>,
configuredServerUrl: String,
): String = artifacts.mapNotNull { resolvedArtifactUrl(it, configuredServerUrl) }.joinToString("\n")
/** The action bar's count label, e.g. `3 selected`. Pure. */
internal fun selectionCountLabel(count: Int): String = "$count selected"
/** The bulk-copy confirmation, e.g. `Copied 3 links`. Pure. */
internal fun selectionCopiedMessage(count: Int): String =
"Copied $count ${if (count == 1) "link" else "links"}"
/**
* The contextual action bar shown while artifacts are selected: the number
* selected, a copy-links action, a share action and a close that leaves
* selection mode. It is the pane's top app bar (not an overlay), so it stays
* inside the safe area [paneSafeArea] via the same top/horizontal insets as the
* bar it replaces, and it can never cover the items it acts on. Every action is a
* 48dp [IconButton] with an accurate content description; the count is the title.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ArtifactSelectionBar(
count: Int,
onCopyLinks: () -> Unit,
onShare: () -> Unit,
onClose: () -> Unit,
modifier: Modifier = Modifier,
containerColor: Color = MaterialTheme.colorScheme.surface,
) {
TopAppBar(
title = { Text(selectionCountLabel(count)) },
navigationIcon = {
IconButton(onClick = onClose) {
Icon(Icons.Default.Close, contentDescription = "Exit selection")
}
},
actions = {
IconButton(onClick = onCopyLinks) {
Icon(Icons.Default.ContentCopy, contentDescription = "Copy selected links")
}
IconButton(onClick = onShare) {
Icon(Icons.Default.Share, contentDescription = "Share selected artifacts")
}
},
modifier = modifier,
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
colors = TopAppBarDefaults.topAppBarColors(containerColor = containerColor),
)
}
/** Shown when no server url is configured and there is no absolute link to copy. */
internal const val ARTIFACT_LINKS_NEED_SERVER_HINT =
"Set the server URL in Settings to copy artifact links."
/**
* The bulk copy/share actions the artifacts action bar exposes, built by
* [artifactSelectionActions] so the run-summary grid and the stage pane's
* per-visit list share one implementation and can never drift.
*/
internal data class ArtifactSelectionActions(
val copyLinks: () -> Unit,
val shareSelected: () -> Unit,
)
/**
* The one implementation of the action bar's **Copy links** and **Share** for
* [selectedArtifacts] resolved against [configuredServerUrl]: copy writes one
* absolute link per line through the single clipboard path and confirms it on
* [snackbarHostState] (or shows [ARTIFACT_LINKS_NEED_SERVER_HINT] when nothing
* resolves), and share fetches every selected artifact through
* [fetchArtifactBytes] and sends them together. Both artifact surfaces call this,
* so the payload and the share fallback are identical everywhere.
*/
@Composable
internal fun artifactSelectionActions(
selectedArtifacts: List<StageArtifact>,
configuredServerUrl: String,
fetchArtifactBytes: suspend (String) -> ByteArray?,
snackbarHostState: SnackbarHostState,
): ArtifactSelectionActions {
val context = LocalContext.current
val clipboard = LocalClipboardManager.current
val scope = rememberCoroutineScope()
return ArtifactSelectionActions(
copyLinks = {
val text = artifactSelectionLinks(selectedArtifacts, configuredServerUrl)
scope.launch {
// No configured server means no absolute link to copy; show the
// hint rather than copying a relative url. The confirmation counts
// the lines actually written, never the raw selection size.
if (text.isBlank()) {
snackbarHostState.showSnackbar(ARTIFACT_LINKS_NEED_SERVER_HINT)
} else {
clipboard.copyText(text)
snackbarHostState.showSnackbar(selectionCopiedMessage(text.lines().size))
}
}
},
shareSelected = {
val targets = shareTargets(selectedArtifacts, configuredServerUrl)
scope.launch { shareArtifacts(context, targets, fetchArtifactBytes) }
},
)
}
/**
* The one artifact-selection host both artifact surfaces share (the run
* summary's grid and the stage pane's per-visit list): it owns [selectionState],
* resolves the selected artifacts from [candidates] with [resolvedSelection],
* builds the bulk copy/share actions, runs the Back-leaves-selection-first
* handler and renders the contextual [ArtifactSelectionBar] in place of [topBar]
* while [enabled] and the selection actually maps to artifacts. [content] gets
* the resolved [ArtifactSelection] plus the scaffold padding, so a surface's
* gallery and body stay inside the system bars and the two surfaces can never
* drift.
*
* A selection whose urls no longer map to [candidates] (a stale or restored set)
* is cleared, so selection mode is never active with nothing behind it and a tap
* can never toggle invisibly with no bar to exit.
*/
@Composable
internal fun ArtifactSelectionScaffold(
selectionState: MutableState<ArtifactSelection>,
candidates: List<StageArtifact>,
configuredServerUrl: String,
fetchArtifactBytes: suspend (String) -> ByteArray?,
modifier: Modifier = Modifier,
containerColor: Color = MaterialTheme.colorScheme.surface,
enabled: Boolean = true,
topBar: @Composable () -> Unit,
content: @Composable (
selection: ArtifactSelection,
onSelectionChange: (ArtifactSelection) -> Unit,
padding: PaddingValues,
) -> Unit,
) {
val selection = selectionState.value
// Derived once per data change, never per recomposition.
val selectedArtifacts = remember(selection, candidates) {
resolvedSelection(candidates, selection)
}
val selecting = enabled && selectedArtifacts.isNotEmpty()
val onSelectionChange: (ArtifactSelection) -> Unit = { selectionState.value = it }
// Keep the mode and the resolved set in sync: a selection that resolves to
// nothing (stale urls after a data change, or a restore on a surface that no
// longer shows them) is cleared, so `active` always means "taps toggle and a
// bar is showing".
LaunchedEffect(selection, selectedArtifacts, enabled) {
if (selection.active && (selectedArtifacts.isEmpty() || !enabled)) {
selectionState.value = ArtifactSelection()
}
}
// Back leaves selection mode first; only then does the surface's own Back run.
BackHandler(enabled = selecting) { selectionState.value = ArtifactSelection() }
val snackbarHostState = remember { SnackbarHostState() }
val actions = artifactSelectionActions(
selectedArtifacts = selectedArtifacts,
configuredServerUrl = configuredServerUrl,
fetchArtifactBytes = fetchArtifactBytes,
snackbarHostState = snackbarHostState,
)
Scaffold(
modifier = modifier,
containerColor = containerColor,
contentWindowInsets = paneSafeArea(),
snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = {
if (selecting) {
// The contextual bar replaces the app bar (inside the safe area,
// above the items) so it never covers what it acts on.
ArtifactSelectionBar(
count = selectedArtifacts.size,
onCopyLinks = actions.copyLinks,
onShare = actions.shareSelected,
onClose = { selectionState.value = ArtifactSelection() },
containerColor = containerColor,
)
} else {
topBar()
}
},
) { padding -> content(selection, onSelectionChange, padding) }
}
@@ -1,341 +0,0 @@
package net.awan.pipelines.ui.graph
import android.content.ClipData
import android.content.ClipDescription
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.awan.pipelines.data.protocol.StageArtifact
/**
* How a share action delivers an artifact. [File] streams the fetched bytes to a
* cache file and hands it to the platform's [Intent.ACTION_SEND]; [Link] is the
* fallback used when the fetch failed (or returned nothing), so a receiver still
* gets the artifact's resolved link as text instead of a failed share.
*/
internal enum class ShareDelivery { File, Link }
/**
* The delivery a share attempt uses for [bytes]: absent or empty bytes fall back
* to [ShareDelivery.Link]. Pure, so the fallback decision is unit-tested without
* a device or a network.
*/
internal fun shareDelivery(bytes: ByteArray?): ShareDelivery =
if (bytes == null || bytes.isEmpty()) ShareDelivery.Link else ShareDelivery.File
/**
* Canonical (mime, extension) pairs for the artifact formats the app can name;
* the single format table shared by [artifactExtension] and [shareMimeType] so
* the two never disagree.
*/
private val ARTIFACT_FORMATS: List<Pair<String, String>> = listOf(
"image/png" to "png",
"image/jpeg" to "jpg",
"image/webp" to "webp",
"image/gif" to "gif",
"image/bmp" to "bmp",
"image/svg+xml" to "svg",
"text/plain" to "txt",
"text/markdown" to "md",
"application/json" to "json",
"text/csv" to "csv",
"text/html" to "html",
"application/pdf" to "pdf",
"application/zip" to "zip",
)
private val EXTENSION_BY_MIME: Map<String, String> = ARTIFACT_FORMATS.toMap()
private val MIME_BY_EXTENSION: Map<String, String> = ARTIFACT_FORMATS.associate { (mime, ext) -> ext to mime }
/** Longest base name kept before the url-derived suffix (keeps paths well under limits). */
private const val MAX_BASE_CHARS = 48
/**
* The name a shared artifact is cached and sent under: a filesystem-safe form of
* its own [name] (or "artifact" when blank), a short stable suffix derived from
* its [url] so two artifacts with the same name never collide, and an extension
* from [contentType] or the url. Pure, so the naming is unit-tested without a
* device; deterministic, so re-sharing the same artifact overwrites its file
* instead of accumulating copies.
*/
internal fun artifactFileName(name: String, url: String, contentType: String?): String {
val extension = artifactExtension(contentType, url)
val sanitized = sanitizeArtifactName(name)
// Drop a trailing extension that matches the one we append, so a name that
// already carries its suffix is not doubled (`shot.png` -> `shot_<id>.png`).
val base = if (sanitized.endsWith(".$extension", ignoreCase = true)) {
sanitized.dropLast(extension.length + 1)
} else {
sanitized
}.ifBlank { "artifact" }
return "${base}_${Integer.toHexString(url.hashCode())}.$extension"
}
/**
* A filesystem-safe artifact name: path separators and any character outside the
* portable `[A-Za-z0-9._-]` set become `_`, leading/trailing punctuation is
* trimmed and the result is capped at [MAX_BASE_CHARS]. Pure.
*/
internal fun sanitizeArtifactName(name: String): String =
name.trim()
.map { if (it.isLetterOrDigit() || it == '.' || it == '-' || it == '_') it else '_' }
.joinToString("")
.trim('.', '_', '-')
.take(MAX_BASE_CHARS)
/**
* The extension (without the dot) an artifact is shared under: the canonical one
* for its normalised [contentType], else the url's own last-segment extension
* when it is a short alphanumeric token, else "bin". Pure.
*/
internal fun artifactExtension(contentType: String?, url: String): String {
val mime = contentType?.substringBefore(';')?.trim()?.lowercase().orEmpty()
EXTENSION_BY_MIME[mime]?.let { return it }
val fromUrl = url.substringAfterLast('/', "").substringAfterLast('.', "").lowercase()
if (fromUrl.isNotEmpty() && fromUrl.length <= 5 && fromUrl.all { it.isLetterOrDigit() }) return fromUrl
return "bin"
}
/**
* The MIME type a shared artifact is sent as: its normalised [contentType] when
* present, else one inferred from [fileName]'s extension, else the generic
* binary type. Pure, so the value the platform intent carries is unit-tested.
*/
internal fun shareMimeType(contentType: String, fileName: String): String {
val mime = contentType.substringBefore(';').trim().lowercase()
if (mime.isNotEmpty()) return mime
return MIME_BY_EXTENSION[fileName.substringAfterLast('.', "").lowercase()]
?: "application/octet-stream"
}
/**
* One selected artifact resolved for a bulk share: its absolute [url] plus the
* name and content type the intent needs. Built by [shareTargets], so the same
* resolution the single-item share uses is applied to every item.
*/
internal data class ShareTarget(val url: String, val name: String, val contentType: String)
/**
* The resolved share targets of [artifacts] against [configuredServerUrl];
* unresolvable urls are dropped. Pure.
*/
internal fun shareTargets(
artifacts: List<StageArtifact>,
configuredServerUrl: String,
): List<ShareTarget> = artifacts.mapNotNull { artifact ->
resolvedArtifactUrl(artifact, configuredServerUrl)?.let {
ShareTarget(it, artifact.name, artifact.contentType)
}
}
/**
* The MIME an intent carrying several [targets] declares: the one type they all
* share (each derived by the single-item [shareMimeType]), or the wildcard type
* for a mixed set. Pure, so the declared type is unit-tested without a device.
*/
internal fun bulkShareMimeType(targets: List<ShareTarget>): String {
val mimes = targets.map {
shareMimeType(it.contentType, artifactFileName(it.name, it.url, it.contentType))
}.distinct()
return if (mimes.size == 1) mimes.first() else "*/*"
}
/**
* Fetches [url]'s resolved artifact through the app's existing client and shares
* it: the bytes go to the app cache and out through [Intent.ACTION_SEND]-with-
* stream (via the declared [FileProvider]); when the fetch fails (offline server,
* non-2xx, empty body) the artifact's link is shared as text instead. Never
* throws: an unreachable server degrades to the link.
*/
internal suspend fun shareArtifact(
context: Context,
url: String,
name: String,
contentType: String?,
fetchBytes: suspend (String) -> ByteArray?,
) {
val bytes = runCatching { fetchBytes(url) }.getOrNull()
// A fetched file is preferred; a failed fetch, an unwritable cache or a
// provider that cannot hand the file out all degrade to the link.
val uri = writeSharedArtifact(context, bytes, url, name, contentType)
val sharedFile = uri != null && runCatching {
launchFileShare(context, uri, url, name, contentType)
}.isSuccess
if (!sharedFile) shareLink(context, url)
}
/**
* Fetches and shares every [targets] in one action. Each file goes through the
* same bounded cache and [FileProvider] path as the single share
* ([writeSharedArtifact]), and all the uris then leave together in one
* [Intent.ACTION_SEND_MULTIPLE] whose type is [bulkShareMimeType] and whose
* chooser title carries the item count. If fetching any item fails the whole set
* degrades, in the same action, to its resolved links shared as text. Never
* throws.
*/
internal suspend fun shareArtifacts(
context: Context,
targets: List<ShareTarget>,
fetchBytes: suspend (String) -> ByteArray?,
) {
if (targets.isEmpty()) return
// Prepare the bounded shared cache once for the whole set (created + pruned),
// not per item, so a bulk share does its filesystem bookkeeping a single time.
val dir = runCatching { sharedArtifactDir(context) }.getOrNull()
if (dir == null) {
shareLinks(context, targets.map { it.url })
return
}
val uris = ArrayList<Uri>(targets.size)
for (target in targets) {
val bytes = runCatching { fetchBytes(target.url) }.getOrNull()
val uri = writeSharedArtifact(context, bytes, target.url, target.name, target.contentType, dir)
if (uri == null) {
// Any failure is the set's failure: fall back to the links for all.
shareLinks(context, targets.map { it.url })
return
}
uris += uri
}
launchMultiFileShare(context, uris, targets)
}
/**
* The bounded shared-artifact cache directory, created if missing and pruned.
* Callers that write more than one file prepare it once and pass it to
* [writeSharedArtifact], so the filesystem work is not repeated per artifact.
*/
private suspend fun sharedArtifactDir(context: Context): File = withContext(Dispatchers.IO) {
File(context.applicationContext.cacheDir, SHARED_ARTIFACT_DIR).also {
it.mkdirs()
pruneSharedArtifacts(it)
}
}
/**
* Writes [bytes] into [dir] (the bounded shared-artifact cache, prepared by
* [sharedArtifactDir] when not supplied) and returns its shareable [Uri], or null
* when there is nothing to write or the cache/provider cannot produce one. Never
* throws, so both the single and the bulk share can degrade to a link instead.
*/
private suspend fun writeSharedArtifact(
context: Context,
bytes: ByteArray?,
url: String,
name: String,
contentType: String?,
dir: File? = null,
): Uri? {
// Capture the non-null bytes from the delivery check instead of asserting
// them later inside the coroutine, where a stray null would be a crash.
val fileBytes = bytes.takeIf { shareDelivery(it) == ShareDelivery.File } ?: return null
return runCatching {
val file = withContext(Dispatchers.IO) {
val targetDir = dir ?: sharedArtifactDir(context)
File(targetDir, artifactFileName(name, url, contentType)).also { it.writeBytes(fileBytes) }
}
FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
}.getOrNull()
}
/** Launches the single-file share of an already-written [uri]. */
private fun launchFileShare(
context: Context,
uri: Uri,
url: String,
name: String,
contentType: String?,
) {
val intent = Intent(Intent.ACTION_SEND).apply {
type = shareMimeType(contentType.orEmpty(), artifactFileName(name, url, contentType))
putExtra(Intent.EXTRA_STREAM, uri)
putExtra(Intent.EXTRA_TITLE, name)
// A ClipData carrying the same uri lets the sharesheet read the stream
// (for its preview and to look up the resolved type) without a separate
// grant; the flag still covers targets that only read EXTRA_STREAM.
clipData = ClipData.newUri(context.contentResolver, name, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
launchShare(context, intent)
}
/**
* Launches the multi-file share: one [Intent.ACTION_SEND_MULTIPLE] carrying every
* [uri], typed by [bulkShareMimeType] and labelled with the item count, with a
* ClipData that carries the same uris and their type so the sharesheet can read
* each stream. The chooser title also names the count.
*/
private fun launchMultiFileShare(context: Context, uris: List<Uri>, targets: List<ShareTarget>) {
val label = "${targets.size} artifacts"
val mime = bulkShareMimeType(targets)
val intent = Intent(Intent.ACTION_SEND_MULTIPLE).apply {
type = mime
putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))
putExtra(Intent.EXTRA_TITLE, label)
clipData = ClipData(ClipDescription(label, arrayOf(mime)), ClipData.Item(uris.first())).apply {
uris.drop(1).forEach { addItem(ClipData.Item(it)) }
}
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
launchShare(context, intent, label)
}
private fun shareLink(context: Context, url: String) = shareLinks(context, listOf(url))
/** Shares [urls] as one newline-joined plain-text payload. */
private fun shareLinks(context: Context, urls: List<String>) {
val text = urls.joinToString("\n")
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, text)
clipData = ClipData.newPlainText(null, text)
}
launchShare(context, intent)
}
/**
* Shows the platform chooser for [intent], tolerating a missing handler. An
* optional [chooserTitle] is the chooser headline (the bulk share puts the item
* count there).
*/
private fun launchShare(context: Context, intent: Intent, chooserTitle: CharSequence? = null) {
runCatching { context.startActivity(Intent.createChooser(intent, chooserTitle)) }
}
/**
* Bounds the shared-artifact cache directory: entries older than [ttlMillis] are
* dropped, and if the survivors still exceed [maxBytes] the oldest go first.
* Keeps a long session's shared files from growing without bound; missing or
* empty directories are a no-op.
*/
internal fun pruneSharedArtifacts(
dir: File,
now: Long = System.currentTimeMillis(),
ttlMillis: Long = SHARED_ARTIFACT_TTL_MILLIS,
maxBytes: Long = MAX_CACHED_SHARE_BYTES,
) {
val files = dir.listFiles()?.filter { it.isFile } ?: return
val fresh = files.filter { now - it.lastModified() < ttlMillis }
files.forEach { if (it !in fresh) it.delete() }
var total = fresh.sumOf { it.length() }
if (total <= maxBytes) return
fresh.sortedBy { it.lastModified() }.forEach { file ->
if (total <= maxBytes) return
val size = file.length()
if (file.delete()) total -= size
}
}
/** The app cache subdirectory shared artifact files are written to. */
private const val SHARED_ARTIFACT_DIR = "shared-artifacts"
/** Shared artifact files are pruned after a day and capped at 64 MiB on disk. */
private const val SHARED_ARTIFACT_TTL_MILLIS = 24L * 60 * 60 * 1000
private const val MAX_CACHED_SHARE_BYTES = 64L * 1024 * 1024
/** Opacity of the scrim that backs an action over a bright artifact image. */
internal const val ARTIFACT_ACTION_SCRIM_ALPHA = 0.5f
@@ -1,153 +0,0 @@
package net.awan.pipelines.ui.graph
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.filled.AudioFile
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.DataObject
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.FolderZip
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.Movie
import androidx.compose.material.icons.filled.PictureAsPdf
import androidx.compose.material.icons.automirrored.filled.ReceiptLong
import androidx.compose.material.icons.filled.TableChart
import androidx.compose.ui.graphics.vector.ImageVector
import net.awan.pipelines.ui.isImageContentType
import net.awan.pipelines.ui.isVideoContentType
/**
* What an artifact's file type is, from the app's point of view: the two media
* kinds the gallery previews (image, video) and the file kinds it labels with a
* type icon (everything else). It is the one classification the gallery branches
* on, so the grid, the tile and the icon can never disagree about a file.
*/
internal enum class ArtifactKind {
Image,
Video,
Audio,
Pdf,
Json,
Archive,
Spreadsheet,
Log,
Code,
Document,
Other,
}
/**
* The gallery kind of an artifact from its [contentType] (server-sniffed, may
* carry parameters) and its [name] (the extension is the fallback when the sniff
* is generic `text/plain`/`application/octet-stream`). Image and video are
* recognised straight from the content type; the rest are matched by the
* normalised mime first, then by the name's extension. Pure and total, so the
* type-to-icon mapping is unit-tested without a device.
*/
internal fun artifactKind(contentType: String, name: String): ArtifactKind {
if (isImageContentType(contentType)) return ArtifactKind.Image
if (isVideoContentType(contentType)) return ArtifactKind.Video
val mime = contentType.substringBefore(';').trim().lowercase()
val ext = name.substringAfterLast('.', "").lowercase()
return when {
mime.startsWith("audio/") -> ArtifactKind.Audio
mime == "application/pdf" || ext == "pdf" -> ArtifactKind.Pdf
mime.contains("json") || ext == "json" -> ArtifactKind.Json
mime in ARCHIVE_MIMES || ext in ARCHIVE_EXTENSIONS -> ArtifactKind.Archive
mime in SPREADSHEET_MIMES || ext in SPREADSHEET_EXTENSIONS -> ArtifactKind.Spreadsheet
ext == "log" -> ArtifactKind.Log
mime == "text/html" -> ArtifactKind.Document
mime in CODE_MIMES || ext in CODE_EXTENSIONS -> ArtifactKind.Code
mime.startsWith("text/") || mime in DOCUMENT_MIMES || ext in DOCUMENT_EXTENSIONS -> ArtifactKind.Document
else -> ArtifactKind.Other
}
}
/**
* The glyph that names [kind] in the gallery: a distinct [ImageVector] per kind
* (its own shape, not colour alone), so a document, archive, log, code file, JSON
* payload and PDF are told apart at a glance. Pure, so the mapping is unit-tested.
*/
internal fun artifactIcon(kind: ArtifactKind): ImageVector = when (kind) {
ArtifactKind.Image -> Icons.Filled.Image
ArtifactKind.Video -> Icons.Filled.Movie
ArtifactKind.Audio -> Icons.Filled.AudioFile
ArtifactKind.Pdf -> Icons.Filled.PictureAsPdf
ArtifactKind.Json -> Icons.Filled.DataObject
ArtifactKind.Archive -> Icons.Filled.FolderZip
ArtifactKind.Spreadsheet -> Icons.Filled.TableChart
ArtifactKind.Log -> Icons.AutoMirrored.Filled.ReceiptLong
ArtifactKind.Code -> Icons.Filled.Code
ArtifactKind.Document -> Icons.Filled.Description
ArtifactKind.Other -> Icons.AutoMirrored.Filled.InsertDriveFile
}
/**
* The word that names [kind] where a surface shows the type glyph but must also
* say the type in prose (a screen reader cannot read an icon). It is the same
* classification [artifactIcon] draws from, so the glyph and the word never
* disagree. Pure, so the mapping is unit-tested.
*/
internal fun artifactKindLabel(kind: ArtifactKind): String = when (kind) {
ArtifactKind.Image -> "Image"
ArtifactKind.Video -> "Video"
ArtifactKind.Audio -> "Audio"
ArtifactKind.Pdf -> "PDF"
ArtifactKind.Json -> "JSON"
ArtifactKind.Archive -> "Archive"
ArtifactKind.Spreadsheet -> "Spreadsheet"
ArtifactKind.Log -> "Log"
ArtifactKind.Code -> "Code"
ArtifactKind.Document -> "Document"
ArtifactKind.Other -> "File"
}
private val ARCHIVE_EXTENSIONS =
setOf("zip", "tar", "gz", "tgz", "bz2", "xz", "rar", "7z", "jar", "war")
private val ARCHIVE_MIMES = setOf(
"application/zip",
"application/gzip",
"application/x-tar",
"application/x-7z-compressed",
"application/x-rar-compressed",
"application/java-archive",
)
private val SPREADSHEET_EXTENSIONS = setOf("csv", "tsv", "xls", "xlsx", "ods")
private val SPREADSHEET_MIMES = setOf(
"text/csv",
"text/tab-separated-values",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
private val CODE_EXTENSIONS = setOf(
"kt", "kts", "java", "go", "py", "rb", "php", "rs", "c", "h", "cc", "cpp",
"hpp", "cs", "js", "jsx", "ts", "tsx", "mjs", "cjs", "swift", "scala", "sh",
"bash", "zsh", "fish", "ps1", "sql", "yaml", "yml", "toml", "ini", "xml",
"gradle", "properties", "proto",
)
private val CODE_MIMES = setOf(
"application/xml",
"application/x-yaml",
"application/javascript",
"text/javascript",
"text/x-python",
"text/x-java-source",
"text/x-kotlin",
"application/x-sh",
"application/x-httpd-php",
"application/sql",
)
private val DOCUMENT_EXTENSIONS =
setOf("txt", "md", "markdown", "rst", "doc", "docx", "odt", "rtf", "html", "htm")
private val DOCUMENT_MIMES = setOf(
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/rtf",
)
@@ -1,799 +0,0 @@
package net.awan.pipelines.ui.graph
import android.os.Build
import android.view.WindowManager
import androidx.compose.animation.core.animate
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import kotlin.math.abs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.ui.ArtifactGroup
import net.awan.pipelines.ui.components.MotionQuick
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.spec
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The full-screen media viewer opened by tapping a gallery tile (the run summary
* grid, the per-visit artifacts section and the stage pane all render through
* [ArtifactGallery], so they all open this): an image at full size, or a video's
* poster frame with the external-open action to actually play it. It replaces the
* former small centred dialog rather than stacking on top of it.
*
* A single-artifact shortcut ([url], [name], [video]) is kept for callers such as
* [net.awan.pipelines.ui.graph.StageVerdict] that already resolve one url.
*/
@Composable
internal fun ArtifactViewer(
url: String,
name: String,
fetchBytes: suspend (String) -> ByteArray?,
onDismiss: () -> Unit,
video: Boolean = false,
) {
val artifact = remember(url) {
StageArtifact(
name = name,
contentType = if (video) "video/*" else "image/*",
url = url,
sizeBytes = 0,
)
}
val artifacts = remember(url) { listOf(artifact) }
ArtifactViewer(
artifacts = artifacts,
index = 0,
configuredServerUrl = "",
fetchBytes = fetchBytes,
onIndexChange = {},
onDismiss = onDismiss,
)
}
/**
* The full-screen artifact viewer opened by tapping a gallery thumbnail (the run
* summary grid, the per-visit artifacts list and the stage pane all render
* through [ArtifactGallery], so they all open this). It replaces the former
* small centred dialog rather than stacking on top of it.
*
* It is a [Dialog] whose window is laid out edge to edge (`decorFitsSystemWindows
* = false`): the dark [MaterialTheme.colorScheme.scrim] backdrop fills the whole
* screen, while the interactive content clears the pane safe area
* ([paneSafeArea]) so nothing sits under the status bar, a cutout or the
* navigation bar. As a dialog it is drawn above every pane of the stack, and the
* platform routes Back to it ([DialogProperties.dismissOnBackPress]) so system
* Back closes the viewer and not the screen behind it.
*
* It shows one [artifacts] entry at a time and pages horizontally through the
* neighbours in gallery order ([artifacts] is that order): a swipe left/right at
* fit moves to the next/previous artifact, and the position ("2 of 5"), name and
* content type of the open artifact are always shown. A horizontal drag is only
* a page while the image is at fit — a zoomed image still pans — because the
* viewer is zoomable and pannable; at the first/last artifact the drag is damped
* and never wraps. A one-artifact gallery is inert (no page, no resistance). The
* previous/next [IconButton]s keep both neighbours reachable without a swipe.
*
* Images load at full resolution through [rememberArtifactBitmap]; videos load
* their first sync frame through [rememberArtifactVideoFrame]. While the content
* loads a spinner is shown and a failed fetch/decode shows a distinct error
* message, and paging keeps working so a broken artifact never strands the
* viewer. The open-in-new, copy-link and share actions are kept from the
* artifact rows, a tap on the image is deliberately not a dismissal (only the
* close button, a downward swipe at fit, or Back close it), and each artifact
* reloads its own content, name and actions rather than reusing the previous
* one's.
*/
@Composable
internal fun ArtifactViewer(
artifacts: List<StageArtifact>,
index: Int,
configuredServerUrl: String,
fetchBytes: suspend (String) -> ByteArray?,
onIndexChange: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val count = artifacts.size
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(
usePlatformDefaultWidth = false,
decorFitsSystemWindows = false,
// A tap on the backdrop/image is not a gesture, so it must never
// close the viewer.
dismissOnClickOutside = false,
),
) {
// Stretch the dialog window over the whole display (behind the status
// bar, cutout and navigation bar) so the dark backdrop is truly full
// screen; the content below then applies the safe-area insets itself.
val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window
SideEffect {
dialogWindow?.let { window ->
window.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
)
val attrs = window.attributes
// Fit no system insets and draw into the display cutout too, so
// the backdrop reaches every edge; the content re-applies the
// safe area itself with windowInsetsPadding. Each field/constant
// is guarded by its own API level (fitInsetsTypes and
// CUTOUT_MODE_ALWAYS are API 30, SHORT_EDGES is API 28).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
attrs.fitInsetsTypes = 0
attrs.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
attrs.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
window.attributes = attrs
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.scrim)
.windowInsetsPadding(paneSafeArea()),
) {
val artifact = artifacts.getOrNull(index) ?: return@Box
ArtifactViewerBody(
artifact = artifact,
resolvedUrl = resolvedArtifactUrl(artifact, configuredServerUrl),
index = index,
count = count,
fetchBytes = fetchBytes,
// Clamp through the one paging rule, so a page attempt at an end
// resolves to the same index and the viewer never leaves range.
onPage = { delta -> onIndexChange(pagedIndex(index, delta, count)) },
onDismiss = onDismiss,
)
}
}
}
/**
* One open artifact: the zoomable image or video poster frame (or its
* loading/error panel) plus the fixed position header and the action/page
* affordances. The paging/dismiss gesture and its animation live on the
* full-screen surface here, above the per-artifact content, so the swipe offset
* survives the artifact swap and the page slides rather than jumping — and so a
* drag that starts anywhere in the viewer, including the letterbox around a
* fitted image, reaches the page rule.
*
* This one full-screen surface owns both gestures: a horizontal drag at fit pages
* (a downward drag at fit dismisses), while a pinch or a drag at any zoomed scale
* is the pan/zoom transform instead — the pan clamp leaves a fitted image
* centred, so the same drag is free to page. The image itself is drawn at its
* fitted size and transformed inside this surface; it carries no gesture of its
* own, so the loading/error/unavailable panel and the image share exactly one
* paging implementation.
*/
@Composable
private fun ArtifactViewerBody(
artifact: StageArtifact,
resolvedUrl: String?,
index: Int,
count: Int,
fetchBytes: suspend (String) -> ByteArray?,
onPage: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val kind = remember(artifact.contentType, artifact.name) {
artifactKind(artifact.contentType, artifact.name)
}
val isVideo = kind == ArtifactKind.Video
val imageState = if (isVideo) {
rememberArtifactVideoFrame(resolvedUrl, FULL_RESOLUTION, fetchBytes)
} else {
rememberArtifactBitmap(resolvedUrl, FULL_RESOLUTION, fetchBytes)
}
// The two neighbours are derived through the same clamp the page commit
// uses, so an affordance and the gesture can never disagree about an end.
val hasPrevious = pagedIndex(index, -1, count) != index
val hasNext = pagedIndex(index, 1, count) != index
// Keying the zoom state on the open url means paging (a new url) starts the
// neighbour at fit/centred instead of inheriting the previous one's transform.
val url = resolvedUrl ?: artifact.url
BoxWithConstraints(Modifier.fillMaxSize().clipToBounds()) {
val density = LocalDensity.current
val viewport = Size(with(density) { maxWidth.toPx() }, with(density) { maxHeight.toPx() })
val paging = rememberArtifactPaging(
viewport = { viewport },
pagingEnabled = { count > 1 },
hasPrevious = { hasPrevious },
hasNext = { hasNext },
onPage = onPage,
onDismiss = onDismiss,
)
// The fitted image size (zero until a bitmap is ready), kept on the bitmap
// so a decode does not re-fit on every recomposition.
val ready = imageState as? ArtifactImageState.Ready
val base = remember(viewport, ready?.bitmap) {
ready?.let { fitImageSize(viewport, Size(it.bitmap.width.toFloat(), it.bitmap.height.toFloat())) }
?: Size.Zero
}
// The fitted image's centred offset, so a freshly-opened (or freshly
// paged-to) artifact is drawn already centred rather than flashing at the
// origin for a frame before the effect below re-centres it.
val centredOffset = remember(url, viewport, base) {
clampImageOffset(Offset.Zero, scaled(base, FIT_SCALE), viewport)
}
var scale by remember(url) { mutableFloatStateOf(FIT_SCALE) }
var offset by remember(url) { mutableStateOf(centredOffset) }
// Centre the fitted image on first layout and re-clamp it whenever the
// fitted geometry changes; scale changes are handled by the gestures.
LaunchedEffect(url, viewport, base) {
offset = clampImageOffset(offset, scaled(base, scale), viewport)
}
// The full-screen gesture surface. Its graphicsLayer carries the page
// offset, so the whole content (image and its letterbox) slides as one.
Box(
modifier = Modifier
.fillMaxSize()
.graphicsLayer { translationX = paging.offsetPx }
.pointerInput(url, viewport, base) {
detectTransformGestures { centroid, pan, zoom, _ ->
// Page/dismiss only at fit (a pinch has zoom != 1); while
// zoomed the pan below is the gesture instead.
if (canPageAtScale(scale) && zoom == 1f) {
paging.onPan(pan.x, pan.y, atFit = true)
} else {
val zoomed = zoomAbout(offset, scale, centroid, zoom, MIN_ZOOM, MAX_ZOOM)
scale = zoomed.scale
offset = clampImageOffset(zoomed.offset + pan, scaled(base, scale), viewport)
}
}
}
.settlePageDrag(paging)
.pointerInput(url) {
detectTapGestures(
// A plain tap is not a gesture: it never closes.
onTap = { },
onDoubleTap = { position ->
val zoomed = zoomAbout(
offset,
scale,
position,
toggleZoomScale(scale) / scale,
MIN_ZOOM,
MAX_ZOOM,
)
scale = zoomed.scale
offset = clampImageOffset(zoomed.offset, scaled(base, scale), viewport)
},
)
},
) {
when (imageState) {
is ArtifactImageState.Ready ->
if (base.width > 0f && base.height > 0f) {
Image(
bitmap = imageState.bitmap.asImageBitmap(),
contentDescription = artifact.name,
contentScale = ContentScale.Fit,
modifier = Modifier
.size(with(density) { base.width.toDp() }, with(density) { base.height.toDp() })
.graphicsLayer {
transformOrigin = TransformOrigin(0f, 0f)
scaleX = scale
scaleY = scale
translationX = offset.x
translationY = offset.y
},
)
}
ArtifactImageState.Loading -> ViewerMessage(
if (isVideo) "Loading video frame…" else "Loading image…",
spinner = true,
)
ArtifactImageState.Error -> ViewerMessage(
if (isVideo) "Couldn't load the video frame." else "Couldn't load image.",
)
ArtifactImageState.Unavailable -> ViewerMessage(
if (isVideo) "Video unavailable." else "Image unavailable.",
)
}
}
// Name/position on the left and the actions on the right, in one bounded
// row so a long artifact name ellipsizes instead of running under the
// actions.
Row(
modifier = Modifier.align(Alignment.TopStart).fillMaxWidth().padding(SPACING_S),
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
verticalAlignment = Alignment.Top,
) {
ArtifactViewerHeader(
artifact = artifact,
index = index,
count = count,
modifier = Modifier.weight(1f),
)
ArtifactViewerActions(
artifact = artifact,
resolvedUrl = resolvedUrl,
fetchBytes = fetchBytes,
onDismiss = onDismiss,
)
}
// A one-artifact gallery pages nowhere, so it shows no page affordances.
if (count > 1) {
ArtifactViewerPageButtons(
hasPrevious = hasPrevious,
hasNext = hasNext,
onPrevious = { paging.page(-1) },
onNext = { paging.page(1) },
modifier = Modifier.align(Alignment.BottomCenter).padding(SPACING_M),
)
}
}
}
/**
* The open artifact's name and position ("2 of 5") over the image, in the light
* [androidx.compose.material3.ColorScheme.inverseSurface] used by [ViewerMessage]
* (the backdrop is the always-dark scrim), on the same translucent capsule as the
* actions so it reads over a bright image.
*/
@Composable
private fun ArtifactViewerHeader(
artifact: StageArtifact,
index: Int,
count: Int,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
Column(
modifier = modifier.viewerCapsule().padding(horizontal = SPACING_M, vertical = SPACING_XS),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
Text(
artifact.name.ifBlank { "(unnamed artifact)" },
style = text.label,
color = MaterialTheme.colorScheme.inverseSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
artifactViewerPositionLabel(index, count, artifact.contentType),
style = text.meta,
color = MaterialTheme.colorScheme.inverseSurface,
)
}
}
/**
* The viewer's loading/error/unavailable message, centred on the backdrop. The
* backdrop is the always-black scrim, so the message uses the light
* [androidx.compose.material3.ColorScheme.inverseSurface] rather than
* `inverseOnSurface` (a dark colour on the scrim, previously illegible).
*/
@Composable
private fun ViewerMessage(text: String, spinner: Boolean = false) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(
modifier = Modifier.padding(SPACING_XL),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(SPACING_M),
) {
if (spinner) CircularProgressIndicator()
Text(
text = text,
style = pipelinesText().meta,
color = MaterialTheme.colorScheme.inverseSurface,
textAlign = TextAlign.Center,
)
}
}
}
/**
* The open artifact's open-in-new, copy-link and share actions plus the close
* affordance. Each acts on the *open* artifact ([resolvedUrl]), so paging
* reloads the actions with the artifact rather than reusing the previous one's.
* A translucent scrim capsule behind the row keeps the light action icons legible
* over a bright image; over the black backdrop it is invisible.
*/
@Composable
private fun ArtifactViewerActions(
artifact: StageArtifact,
resolvedUrl: String?,
fetchBytes: suspend (String) -> ByteArray?,
onDismiss: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val clipboard = LocalClipboardManager.current
val scope = rememberCoroutineScope()
val name = artifact.name
Row(
modifier = modifier.viewerCapsule(),
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
IconButton(onClick = { openArtifact(context, resolvedUrl) }, enabled = resolvedUrl != null) {
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open $name externally")
}
IconButton(
onClick = { resolvedUrl?.let { clipboard.copyText(it) } },
enabled = resolvedUrl != null,
) {
Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to $name")
}
IconButton(
onClick = {
resolvedUrl?.let { url ->
scope.launch { shareArtifact(context, url, name, artifact.contentType, fetchBytes) }
}
},
enabled = resolvedUrl != null,
) {
Icon(Icons.Default.Share, contentDescription = "Share ${name.ifBlank { "artifact" }}")
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Close viewer")
}
}
}
/**
* The focusable previous/next affordances, so a person who cannot swipe can still
* reach both neighbours. Each is a 48dp [IconButton] disabled exactly when that
* neighbour does not exist (the first/last artifact).
*/
@Composable
private fun ArtifactViewerPageButtons(
hasPrevious: Boolean,
hasNext: Boolean,
onPrevious: () -> Unit,
onNext: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier.viewerCapsule(),
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
IconButton(onClick = onPrevious, enabled = hasPrevious) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Previous artifact")
}
IconButton(onClick = onNext, enabled = hasNext) {
Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = "Next artifact")
}
}
}
/**
* The translucent scrim capsule behind the viewer's floating controls (the
* header, the action row and the page buttons): it keeps the light icons and
* text legible over a bright image and is invisible over the black backdrop.
*/
@Composable
private fun Modifier.viewerCapsule(): Modifier = background(
color = MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA),
shape = CircleShape,
)
/**
* The full-screen viewer's horizontal paging state, fed by the one full-screen
* gesture surface the viewer shows, so the page rule lives in exactly one place.
*
* A horizontal drag at fit follows the finger ([offsetPx]); at an end — or for a
* one-artifact gallery — it is damped ([PAGE_RESISTANCE]) and never wraps, and the
* drag springs back to rest when the pointers lift ([settle]). A predominantly
* downward drag at fit still dismisses, exactly as the single-artifact viewer
* did. Once the drag crosses [PAGE_SWIPE_FRACTION] of the viewport width it
* commits one page: the open content slides out, the index changes, and the
* neighbour slides in; while that runs further drags are ignored so an animation
* can never fight itself. All state is plain (only [offsetPx] is observable), so
* a drag schedules no recomposition beyond the translation it actually changes.
*/
private class ArtifactPaging(
private val viewport: () -> Size,
private val pagingEnabled: () -> Boolean,
private val hasPrevious: () -> Boolean,
private val hasNext: () -> Boolean,
private val onPage: (Int) -> Unit,
private val onDismiss: () -> Unit,
private val scope: CoroutineScope,
) {
/** The live page translation in pixels; positive drags the content right. */
var offsetPx by mutableFloatStateOf(0f)
private set
private var paging = false
private var swipeDown = 0f
private var settleJob: Job? = null
/** Feeds one pan event; [atFit] is false while zoomed or pinching. */
fun onPan(panX: Float, panY: Float, atFit: Boolean) {
if (!atFit || paging) {
swipeDown = 0f
return
}
if (abs(panX) > abs(panY)) {
swipeDown = 0f
if (!pagingEnabled()) return
// A leftward drag (negative x) advances to the next artifact.
val direction = if (panX < 0f) 1 else -1
val available = if (direction > 0) hasNext() else hasPrevious()
val proposed = offsetPx + panX
settleJob?.cancel()
offsetPx = if (available) proposed else proposed * PAGE_RESISTANCE
if (available && abs(offsetPx) >= viewport().width * PAGE_SWIPE_FRACTION) startPage(direction)
} else if (panY > 0f && panY >= abs(panX)) {
swipeDown += panY
if (swipeDown >= viewport().height * SWIPE_DISMISS_FRACTION) onDismiss()
} else {
swipeDown = 0f
}
}
/** Springs a resisted (uncommitted) drag back to rest when the fingers lift. */
fun settle() {
if (paging || offsetPx == 0f) return
settleJob?.cancel()
settleJob = scope.launch {
animate(offsetPx, 0f, animationSpec = MotionQuick.spec()) { value, _ -> offsetPx = value }
}
}
/** Commits one page in [direction] (+1 next, -1 previous) without a drag. */
fun page(direction: Int) {
if (!paging) startPage(direction)
}
private fun startPage(direction: Int) {
paging = true
swipeDown = 0f
settleJob?.cancel()
val width = viewport().width
scope.launch {
// Slide the open artifact out, swap in its neighbour, then slide that
// in from the opposite side — one page, in the drag's direction.
animate(offsetPx, -direction * width, animationSpec = MotionQuick.spec()) { value, _ ->
offsetPx = value
}
onPage(direction)
offsetPx = direction * width
animate(offsetPx, 0f, animationSpec = MotionQuick.spec()) { value, _ -> offsetPx = value }
paging = false
}
}
}
/**
* The one [ArtifactPaging] remembered across the artifact swaps of a viewer
* session, reading its latest viewport/availability/callbacks through
* [rememberUpdatedState] so the instance can outlive a composition that a page
* has already changed.
*/
@Composable
private fun rememberArtifactPaging(
viewport: () -> Size,
pagingEnabled: () -> Boolean,
hasPrevious: () -> Boolean,
hasNext: () -> Boolean,
onPage: (Int) -> Unit,
onDismiss: () -> Unit,
): ArtifactPaging {
val viewportState = rememberUpdatedState(viewport)
val enabledState = rememberUpdatedState(pagingEnabled)
val previousState = rememberUpdatedState(hasPrevious)
val nextState = rememberUpdatedState(hasNext)
val pageState = rememberUpdatedState(onPage)
val dismissState = rememberUpdatedState(onDismiss)
val scope = rememberCoroutineScope()
return remember {
ArtifactPaging(
viewport = { viewportState.value() },
pagingEnabled = { enabledState.value() },
hasPrevious = { previousState.value() },
hasNext = { nextState.value() },
onPage = { pageState.value(it) },
onDismiss = { dismissState.value() },
scope = scope,
)
}
}
/**
* Observes gesture ends without consuming the events (the zoom/pan detector
* above owns the drag), so a resisted page drag springs back to rest the moment
* the fingers lift. A committed page owns its own animation and is a no-op here.
*/
private fun Modifier.settlePageDrag(paging: ArtifactPaging): Modifier =
this.pointerInput(paging) {
awaitPointerEventScope {
while (true) {
awaitFirstDown(requireUnconsumed = false)
var pressed = true
while (pressed) {
pressed = awaitPointerEvent().changes.any { it.pressed }
}
paging.settle()
}
}
}
/** The fitted base size scaled by the current [scale], in pixels. */
private fun scaled(base: Size, scale: Float): Size = Size(base.width * scale, base.height * scale)
/** Full resolution for the explicit viewer (the inline previews downsample). */
private const val FULL_RESOLUTION = 0
/** Fit scale (the image fits the viewport) and the double-tap zoomed level. */
private const val FIT_SCALE = 1f
private const val DOUBLE_TAP_SCALE = 2.5f
/** Zoom limits for the viewer, as multiples of the fitted image. */
private const val MIN_ZOOM = 1f
private const val MAX_ZOOM = 5f
/** Tolerance for deciding the image is back at fit. */
private const val ZOOM_EPSILON = 0.01f
/** Fraction of the viewport height a downward swipe must cross to dismiss. */
private const val SWIPE_DISMISS_FRACTION = 0.22f
/** Fraction of the viewport width a horizontal drag must cross to page. */
private const val PAGE_SWIPE_FRACTION = 0.18f
/** How far a drag past the first/last artifact moves before it is stopped. */
private const val PAGE_RESISTANCE = 0.35f
/**
* The media artifacts [groups] hold, in the exact order the gallery draws them
* (group by group, each group's images and videos in recorded order): the
* neighbours the full-screen viewer pages through, so a swipe visits the same
* list the grid showed. Non-media artifacts open externally instead of in the
* viewer and are not part of it. Pure, so the ordering is unit tested.
*/
internal fun pagedArtifacts(groups: List<ArtifactGroup>): List<StageArtifact> =
groups.flatMap { group ->
group.artifacts.filter { artifact ->
artifactKind(artifact.contentType, artifact.name).let {
it == ArtifactKind.Image || it == ArtifactKind.Video
}
}
}
/**
* Each gallery media artifact's url mapped to its position in [pagedArtifacts]
* — the same ordered list the viewer pages through. The grid's tiles resolve
* their viewer index here, so the tile and the viewer derive from one source and
* cannot drift. The first occurrence of a url wins. Pure, so the mapping is unit
* tested against the grid's draw order.
*/
internal fun viewerIndexByUrl(groups: List<ArtifactGroup>): Map<String, Int> {
val indices = LinkedHashMap<String, Int>()
pagedArtifacts(groups).forEachIndexed { index, artifact -> indices.putIfAbsent(artifact.url, index) }
return indices
}
/**
* The index paging from [current] by [delta] within a list of [count], clamped at
* both ends so a page never wraps (and an empty list is index 0). The one paging
* rule the gesture, the buttons and the commit all share. Pure.
*/
internal fun pagedIndex(current: Int, delta: Int, count: Int): Int =
if (count <= 0) 0 else (current + delta).coerceIn(0, count - 1)
/**
* Whether a horizontal drag at [scale] may page: only at the default fit scale,
* so a zoomed viewer pans instead. Pure, so the rule is unit tested.
*/
internal fun canPageAtScale(scale: Float, fit: Float = FIT_SCALE): Boolean =
scale <= fit + ZOOM_EPSILON
/** The viewer's position label, e.g. `2 of 5 · image/png`. Pure. */
internal fun artifactViewerPositionLabel(index: Int, count: Int, contentType: String): String {
val type = contentType.substringBefore(';').trim().ifBlank { "artifact" }
return "${index + 1} of $count · $type"
}
/**
* The size [image] is drawn at to fit inside [viewport] with its aspect ratio
* preserved, never upscaling past 1:1 (a small image keeps its native size).
* Degenerate (zero/negative) sizes return [Size.Zero] rather than dividing by
* zero, so callers never see NaN. Pure, so the fitting is unit tested.
*/
internal fun fitImageSize(viewport: Size, image: Size): Size {
if (image.width <= 0f || image.height <= 0f || viewport.width <= 0f || viewport.height <= 0f) {
return Size.Zero
}
val scale = minOf(1f, viewport.width / image.width, viewport.height / image.height)
return Size(image.width * scale, image.height * scale)
}
/**
* Bounds a pan [offset] of the scaled [content] inside [viewport]: on an axis
* where the content is larger than the viewport the offset stays in
* `[viewport - content, 0]` (its edges never move inside the viewport, so the
* image cannot be dragged off screen); on an axis where it is smaller the offset
* is the centred value. Degenerate content is returned unchanged. Pure, so the
* clamping is unit tested without a device.
*/
internal fun clampImageOffset(offset: Offset, content: Size, viewport: Size): Offset {
if (content.width <= 0f || content.height <= 0f) return offset
return Offset(
x = clampImageAxis(offset.x, content.width, viewport.width),
y = clampImageAxis(offset.y, content.height, viewport.height),
)
}
private fun clampImageAxis(value: Float, content: Float, viewport: Float): Float =
if (content <= viewport) (viewport - content) / 2f else value.coerceIn(viewport - content, 0f)
/**
* The scale a double-tap toggles to: back to [fit] when already zoomed in,
* otherwise the [zoomed] level. Pure, so the toggle is unit tested.
*/
internal fun toggleZoomScale(current: Float, fit: Float = FIT_SCALE, zoomed: Float = DOUBLE_TAP_SCALE): Float =
if (current > fit + ZOOM_EPSILON) fit else zoomed
@@ -1,515 +0,0 @@
package net.awan.pipelines.ui.graph
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.data.transport.ServerUrl
import net.awan.pipelines.ui.ArtifactGroup
import net.awan.pipelines.ui.artifactCaptureNotes
import net.awan.pipelines.ui.artifactsSummary
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.galleryGrid
import net.awan.pipelines.ui.humanBytes
import net.awan.pipelines.ui.presentedArtifacts
import net.awan.pipelines.ui.theme.ARTIFACT_BADGE_DP
import net.awan.pipelines.ui.theme.ARTIFACT_PLAY_BADGE_DP
import net.awan.pipelines.ui.theme.ARTIFACT_TILE_ACTION_DP
import net.awan.pipelines.ui.theme.ARTIFACT_TILE_DP
import net.awan.pipelines.ui.theme.ARTIFACT_TYPE_ICON_DP
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The per-visit artifacts section for the stage pane: the summary line (matching
* the TUI's empty/partial wording), the capture notes, and the visit's own
* artifacts rendered through the shared [ArtifactGallery]. The single artifacts
* rendering path; it resolves each url against the configured server URL and
* never hardcodes a host.
*
* When no server URL is configured the tiles still show (name/size/type) but the
* open/copy actions are disabled and a hint is shown.
*/
@Composable
internal fun ArtifactsSection(
step: RunStep,
configuredServerUrl: String,
fetchArtifactBytes: suspend (String) -> ByteArray?,
modifier: Modifier = Modifier,
selection: ArtifactSelection = ArtifactSelection(),
onSelectionChange: (ArtifactSelection) -> Unit = {},
) {
val text = pipelinesText()
// Derived once per data change, never per recomposition (performance requirement).
val artifacts = remember(step) { presentedArtifacts(step) }
val summary = remember(step) { artifactsSummary(step) }
val notes = remember(step) { artifactCaptureNotes(step) }
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SPACING_XS)) {
Text(summary, style = text.label, color = MaterialTheme.colorScheme.primary)
if (configuredServerUrl.isBlank()) {
Text(
"Set the server URL in Settings to open or copy artifact links.",
style = text.meta,
)
}
notes.forEach { note -> Text(note, style = text.meta) }
if (artifacts.isNotEmpty()) {
// The section is already scoped to this visit, so no group header.
val visit = step.control?.visit?.takeIf { it > 0 } ?: 1
ArtifactGallery(
groups = listOf(ArtifactGroup(step.stage, visit, artifacts)),
configuredServerUrl = configuredServerUrl,
fetchArtifactBytes = fetchArtifactBytes,
showHeaders = false,
selection = selection,
onSelectionChange = onSelectionChange,
)
}
}
}
/**
* The artifacts gallery: one group per (stage, visit) with a header and every
* artifact as a tile in a grid. An image shows its thumbnail, a video its
* still/poster frame with a play marker on top, and anything else its file-type
* icon with the name and size beneath it. Every url is resolved with
* [ServerUrl.resolveArtifactUrl], so nothing here hardcodes a host. The grid is
* built from non-lazy chunked [Row]s, so it never nests a scrollable inside the
* Summary [LazyColumn] or the pane's scroll.
*
* The grid geometry is derived from the measured width (one [BoxWithConstraints],
* see [galleryGrid]): as many cells as fit at the preferred [ARTIFACT_TILE_DP]
* shape, stretched to fill the row, so a wide window shows several tiles per row
* and a narrow one shows fewer, larger ones — never a fixed column count.
*/
@Composable
internal fun ArtifactGallery(
groups: List<ArtifactGroup>,
configuredServerUrl: String,
fetchArtifactBytes: suspend (String) -> ByteArray?,
modifier: Modifier = Modifier,
showHeaders: Boolean = true,
selection: ArtifactSelection = ArtifactSelection(),
onSelectionChange: (ArtifactSelection) -> Unit = {},
) {
val text = pipelinesText()
// The media artifacts in the exact order the grid draws them: the neighbours
// the full-screen viewer pages through, so a swipe visits the same list the
// grid showed. Held once per data change, never per recomposition.
val viewable = remember(groups) { pagedArtifacts(groups) }
// Each media tile opens the viewer at the position it holds in [viewable],
// derived from that same ordered list rather than a second running counter,
// so the grid and the viewer can never disagree about which artifact is which.
val viewerIndexOf = remember(groups) { viewerIndexByUrl(groups) }
// The open viewer's index into [viewable], or [NO_VIEWER] when it is closed.
val viewerIndex = remember(groups) { mutableIntStateOf(NO_VIEWER) }
BoxWithConstraints(modifier.fillMaxWidth()) {
val grid = galleryGrid(
availableWidth = maxWidth,
preferred = ARTIFACT_TILE_DP,
spacing = ARTIFACT_TILE_SPACING_DP,
)
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SPACING_S)) {
groups.forEach { group ->
if (showHeaders) {
Text(
"${group.stageKey} · visit ${group.visit}",
style = text.sectionHeader,
)
}
group.artifacts.chunked(grid.columns).forEach { rowArtifacts ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(ARTIFACT_TILE_SPACING_DP),
) {
rowArtifacts.forEach { artifact ->
ArtifactTile(
artifact = artifact,
configuredServerUrl = configuredServerUrl,
fetchArtifactBytes = fetchArtifactBytes,
tile = grid.cell,
selection = selection,
onSelectionChange = onSelectionChange,
onOpen = { viewerIndexOf[artifact.url]?.let { viewerIndex.intValue = it } },
)
}
// Keep a partial last row's tiles aligned to the grid.
repeat(grid.columns - rowArtifacts.size) {
Box(Modifier.size(grid.cell))
}
}
}
}
}
}
// The one viewer instance the gallery owns, so a swipe pages through
// [viewable] rather than a per-tile viewer that has no neighbours.
if (viewerIndex.intValue in viewable.indices) {
ArtifactViewer(
artifacts = viewable,
index = viewerIndex.intValue,
configuredServerUrl = configuredServerUrl,
fetchBytes = fetchArtifactBytes,
onIndexChange = { viewerIndex.intValue = it },
onDismiss = { viewerIndex.intValue = NO_VIEWER },
)
}
}
/** No artifact is open in this gallery's viewer. */
private const val NO_VIEWER = -1
/**
* The absolute url a gallery artifact is previewed/opened at, or null when it
* cannot be resolved against the configured server (blank or invalid). The one
* place a gallery artifact url is resolved, shared by every tile so they can
* never disagree. A null must never reach a fetch: a server-relative url has no
* scheme and can never load, so the tile renders the distinct "unavailable"
* state instead of the failure mark.
*/
internal fun resolvedArtifactUrl(artifact: StageArtifact, configuredServerUrl: String): String? =
ServerUrl.resolveArtifactUrl(configuredServerUrl, artifact.url)
/**
* One gallery tile. An image or video fills the cell with its thumbnail (a video
* with a play marker on top) and opens the full-screen viewer on tap; any other
* type shows its file-type icon with the name and size beneath it and opens
* externally on tap. A long-press enters artifact selection on this item; while
* selection mode is active a tap toggles it instead of opening, and the selected
* cell gets the app's selected treatment (a tonal ring + check badge in the
* shared secondaryContainer/onSecondaryContainer roles, and the `selected`
* semantics state). The per-item actions are hidden while selecting so the whole
* cell is the toggle target.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ArtifactTile(
artifact: StageArtifact,
configuredServerUrl: String,
fetchArtifactBytes: suspend (String) -> ByteArray?,
tile: Dp,
selection: ArtifactSelection,
onSelectionChange: (ArtifactSelection) -> Unit,
onOpen: () -> Unit,
) {
val context = LocalContext.current
// Resolve and classify once per data change, not on every recomposition.
val resolved = remember(artifact.url, configuredServerUrl) {
resolvedArtifactUrl(artifact, configuredServerUrl)
}
val kind = remember(artifact.contentType, artifact.name) {
artifactKind(artifact.contentType, artifact.name)
}
val media = kind == ArtifactKind.Image || kind == ArtifactKind.Video
val selected = selection.contains(artifact.url)
Box(
Modifier
.size(tile)
.clip(MaterialTheme.shapes.medium)
.background(
if (selected) {
MaterialTheme.colorScheme.secondaryContainer
} else {
MaterialTheme.colorScheme.surfaceContainerHigh
},
)
.then(
if (selected) {
Modifier.border(3.dp, MaterialTheme.colorScheme.secondary, MaterialTheme.shapes.medium)
} else {
Modifier
},
)
.combinedClickable(
onClick = {
when {
selection.active -> onSelectionChange(selection.toggle(artifact.url))
// An image or video opens the full-screen viewer; any
// other type uses the existing open action.
media -> if (resolved != null) onOpen()
else -> openArtifact(context, resolved)
}
},
onLongClick = { onSelectionChange(selection.enter(artifact.url)) },
onLongClickLabel = "Select ${artifact.name}",
)
.semantics { this.selected = selected },
) {
if (media) {
ArtifactMediaPreview(
kind = kind,
name = artifact.name,
resolved = resolved,
fetchArtifactBytes = fetchArtifactBytes,
tile = tile,
)
} else {
ArtifactTypeLabel(kind = kind, artifact = artifact)
}
if (selection.active) {
// While the gallery is selecting, no item exposes its own actions:
// every tap toggles, so only the selected cells carry the check badge.
if (selected) {
Box(
Modifier
.align(Alignment.TopStart)
.padding(SPACING_XS)
.background(MaterialTheme.colorScheme.secondaryContainer, CircleShape),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(SPACING_XS).size(ARTIFACT_BADGE_DP),
)
}
}
} else {
// The per-item share (and, for a non-media tile, copy) controls are
// their own hit areas over the tile: they consume the tap, so an
// action never falls through to open the artifact.
ArtifactTileActions(
artifact = artifact,
resolved = resolved,
fetchArtifactBytes = fetchArtifactBytes,
media = media,
)
}
}
}
/**
* A media tile's content: the image thumbnail, or a video's still/poster frame
* with a centred play marker on top of it. Both load through the same bounded,
* off-main-thread cache, so a media tile never re-hits the network on a
* recomposition.
*/
@Composable
private fun BoxScope.ArtifactMediaPreview(
kind: ArtifactKind,
name: String,
resolved: String?,
fetchArtifactBytes: suspend (String) -> ByteArray?,
tile: Dp,
) {
if (kind == ArtifactKind.Video) {
ArtifactVideoFrame(
url = resolved,
contentDescription = "Poster frame of $name",
fetchBytes = fetchArtifactBytes,
size = tile,
)
Box(
Modifier
.align(Alignment.Center)
.size(ARTIFACT_PLAY_BADGE_DP)
.background(
MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA),
CircleShape,
),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = "Play $name",
tint = MaterialTheme.colorScheme.inverseSurface,
)
}
} else {
// Pass the resolved url (null when there is no configured server): a
// null never triggers a relative-url fetch, it shows the distinct
// "unavailable" state instead of the failure mark.
ArtifactImage(
url = resolved,
contentDescription = "Preview of $name",
maxDim = THUMBNAIL_MAX_DIM,
fetchBytes = fetchArtifactBytes,
size = tile,
)
}
}
/**
* A non-media tile's content: its file-type glyph ([artifactIcon]) with the
* artifact's name and human-readable size beneath it, centred in the cell. The
* action strip is pinned to the cell's top corners, away from this centred
* column, so a compact tile never draws its glyph or text under the actions.
*/
@Composable
private fun ArtifactTypeLabel(kind: ArtifactKind, artifact: StageArtifact) {
val text = pipelinesText()
val size = remember(artifact.sizeBytes) { humanBytes(artifact.sizeBytes) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = SPACING_XS, vertical = SPACING_XS),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Icon(
imageVector = artifactIcon(kind),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ARTIFACT_TYPE_ICON_DP),
)
Text(
artifact.name.ifBlank { "(unnamed artifact)" },
style = text.label,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
modifier = Modifier.padding(top = SPACING_XXS),
)
Text(
size,
style = text.meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
)
}
}
/**
* The compact per-item actions strip a tile shows while not selecting: the share
* control at the end, and — for a non-media tile — the copy-link control at the
* start, so both the existing open (the tile's own tap) and copy actions stay
* reachable from the gallery. A media tile taps through to the viewer, which
* carries its own copy action, so it shows only share.
*/
@Composable
private fun BoxScope.ArtifactTileActions(
artifact: StageArtifact,
resolved: String?,
fetchArtifactBytes: suspend (String) -> ByteArray?,
media: Boolean,
) {
Row(
modifier = Modifier.align(Alignment.TopStart).fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
if (media) {
Spacer(Modifier.size(ARTIFACT_TILE_ACTION_DP))
} else {
ArtifactCopyButton(artifact = artifact, resolved = resolved)
}
ArtifactShareButton(
artifact = artifact,
resolved = resolved,
fetchArtifactBytes = fetchArtifactBytes,
modifier = Modifier.size(ARTIFACT_TILE_ACTION_DP),
scrim = media,
)
}
}
/** The compact copy-link control a non-media tile carries. */
@Composable
private fun ArtifactCopyButton(artifact: StageArtifact, resolved: String?) {
val clipboard = LocalClipboardManager.current
IconButton(
onClick = { resolved?.let { clipboard.copyText(it) } },
enabled = resolved != null,
modifier = Modifier.size(ARTIFACT_TILE_ACTION_DP),
) {
Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}")
}
}
/**
* The share action every artifact tile carries: a compact [IconButton] target, an
* accurate content description, and a click that launches the platform share
* chooser. It is the item's own child action, so a tap on it never opens the
* image or the item. [scrim] adds the translucent backing the viewer uses so the
* icon stays legible over a bright image.
*/
@Composable
private fun ArtifactShareButton(
artifact: StageArtifact,
resolved: String?,
fetchArtifactBytes: suspend (String) -> ByteArray?,
modifier: Modifier = Modifier,
scrim: Boolean = false,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
IconButton(
onClick = {
resolved?.let { url ->
scope.launch {
shareArtifact(context, url, artifact.name, artifact.contentType, fetchArtifactBytes)
}
}
},
enabled = resolved != null,
modifier = if (scrim) {
modifier.background(
MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA),
CircleShape,
)
} else {
modifier
},
) {
Icon(Icons.Default.Share, contentDescription = "Share ${artifact.name.ifBlank { "artifact" }}")
}
}
/** Opens the resolved artifact url externally, tolerating a missing handler. */
internal fun openArtifact(context: Context, url: String?) {
if (url == null) return
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
}
/** Longest edge of a list thumbnail decode. */
private const val THUMBNAIL_MAX_DIM = 160
/** Gap between gallery tiles; shared by the row arrangement and the fitting. */
private val ARTIFACT_TILE_SPACING_DP = SPACING_S
@@ -1,99 +0,0 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.RunGraphState
import kotlin.math.PI
import kotlin.math.sin
/**
* How a stage node is drawn under a run:
*
* - [Active]: the stage the live run is executing right now; it carries a
* pulsing halo, and its live elapsed time is drawn under its label.
* - [Visited]: a stage the run already visited (or any stage in the
* definition-only view); it settles into its static fill/border.
* - [Unvisited]: a stage the run did not reach; drawn hollow, never animating.
*
* A finished run has no [Active] node, so nothing animates once it stops.
*/
internal enum class NodeMotion { Active, Visited, Unvisited }
/**
* How an edge is drawn under a run:
*
* - [Flowing]: an executed route while the run is live; its stroke carries a
* moving dot that reads the direction of travel.
* - [Settled]: an executed route under a finished run; a plain static stroke.
* - [Unvisited]: a route the run did not take; dashed and arrowless.
*/
internal enum class EdgeMotion { Flowing, Settled, Unvisited }
/**
* Whether the graph may animate at all, from the three independent gates:
* the run must still be executing (never animate a finished run), the system
* must have animations enabled (honour the OS/animation-scale setting), and the
* graph must be on screen (a backgrounded graph is paused). Pure, so the
* decision is asserted in a unit test rather than inferred from a frame clock.
*
* When this is false while the run is live, the graph still marks the active
* stage statically (see [ACTIVE_HALO_STATIC_ALPHA] and the drawn elapsed time),
* so "animations off" is a static but unmistakable running state, not a blank.
*/
internal fun graphShouldAnimate(
runState: RunGraphState?,
animationsEnabled: Boolean,
onScreen: Boolean,
): Boolean = runState?.executing == true && animationsEnabled && onScreen
/**
* The motion state of the stage [key] under [runState]. Pure and the single
* definition the drawing and the tests share: the definition-only view
* ([runState] == null) is entirely visited/static, an unvisited key is idle, and
* only the stage the live run is on is [NodeMotion.Active]. The live stage wins
* over the visited check, so it is unmistakably active even in the brief window
* before its step has been recorded in [RunGraphState.visitedStages].
*/
internal fun nodeMotion(key: String, runState: RunGraphState?): NodeMotion = when {
runState == null -> NodeMotion.Visited
runState.executing && key == runState.currentStage -> NodeMotion.Active
key !in runState.visitedStages -> NodeMotion.Unvisited
else -> NodeMotion.Visited
}
/**
* The motion state of [edge] under [runState]: an executed route flows while the
* run is live and settles once it finishes, and an untaken route is idle. The
* definition-only view ([runState] == null) is settled (static), as before.
*/
internal fun edgeMotion(edge: GraphEdge, runState: RunGraphState?): EdgeMotion = when {
!edgeIsExecuted(edge, runState) -> EdgeMotion.Unvisited
runState?.executing == true -> EdgeMotion.Flowing
else -> EdgeMotion.Settled
}
/**
* The active-node halo strength for a 0..1 animation [phase]: a smooth
* sinusoid that rises and falls once per cycle, never stepping between two
* values (a pulse, not a blink). Bounded to `[PULSE_MIN, PULSE_MAX]` so the
* halo is always visible and never fully transparent, and periodic in [phase]
* so it is seamless at the wrap. Pure, so the rhythm is asserted without any
* frame-timing.
*/
internal fun pulseAlpha(phase: Float): Float {
val t = ((phase % 1f) + 1f) % 1f
val wave = (sin(t * 2.0 * PI) + 1.0) / 2.0
return (PULSE_MIN + (PULSE_MAX - PULSE_MIN) * wave).toFloat()
}
/** Faintest the active halo ever gets; never invisible, never a blink-off. */
private const val PULSE_MIN = 0.35f
/** Strongest the active halo gets at the peak of a pulse. */
private const val PULSE_MAX = 0.9f
/**
* The fixed active-halo strength drawn when animation is off (the system
* setting, or a paused graph): clearly marked, just not moving. Within the
* [pulseAlpha] range so the static state looks like a frozen pulse.
*/
internal const val ACTIVE_HALO_STATIC_ALPHA = 0.85f
@@ -1,146 +0,0 @@
package net.awan.pipelines.ui.graph
import androidx.compose.ui.graphics.Color
import net.awan.pipelines.data.protocol.Protocol
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
/**
* The curated palette for the graph-only flow outcomes.
*
* A stage outcome that is also a run state (`success`/`done`/`error`/`blocked`/
* `skipped`/`waiting`) is coloured from the one owned status palette
* ([net.awan.pipelines.ui.components.RunStatusPalette], through [outcomeColor]),
* so the graph, the timeline and the runs list never disagree. This palette
* covers only the words with no status meaning — the loop/choice outcomes a
* pipeline defines (`rejected`, `exhausted`, `retry`, `approved`, `fast`,
* `missing`) — giving each its own deliberate entry (no `hashCode() % 4`
* collisions): the mapping is pure and deterministic, so a given outcome name is
* the same colour across runs and recompositions, and an unknown/new name gets a
* stable reserved fallback colour instead of silently borrowing a known one.
*
* The palette is tuned for the dark Pipelines surface (DarkSurface `0xFF0E1513`,
* over which the outcome label is drawn on a ~0.92-alpha chip). Every entry is
* bright enough to be legible both as a 3px edge stroke and as the small 11sp
* label text: contrast is *measured* by [GraphPaletteTest], not asserted by eye.
*/
internal object GraphPalette {
/**
* The fixed palette. Deliberately fixed (rather than scheme-derived) so an
* outcome is the same colour on every device.
*/
val colors: List<Color> = listOf(
Color(0xFFF5A3A3), // 0 rejected - red
Color(0xFFF5B37A), // 1 exhausted - orange
Color(0xFF7FD4E8), // 2 retry - cyan
Color(0xFFC0A3F5), // 3 approved - violet
Color(0xFFF0E07A), // 4 fast - yellow
Color(0xFFF5A3D0), // 5 missing - pink
// Reserved fallback region for names not in [KNOWN], kept distinct from
// the known entries so an unknown outcome never borrows a known colour.
Color(0xFFD8C98A), // 6 fallback - khaki
Color(0xFF9FD8C0), // 7 fallback - sea
Color(0xFFD8A8C0), // 8 fallback - dusty rose
)
/** The known graph-only outcome names and their fixed palette index, in display order. */
private val KNOWN: Map<String, Int> = linkedMapOf(
"rejected" to 0,
"exhausted" to 1,
"retry" to 2,
"approved" to 3,
"fast" to 4,
"missing" to 5,
)
/** First palette index reserved for names that are not in [KNOWN]. */
private val FALLBACK_START = KNOWN.size
/**
* The palette index for [outcome]. Pure and deterministic for every input
* (including blank): known names get their curated slot, everything else a
* stable slot inside the reserved fallback region. A word that resolves to a
* run state is coloured from the status palette by [outcomeColor] and does not
* reach this palette.
*/
fun outcomeColorIndex(outcome: String): Int {
KNOWN[outcome]?.let { return it }
val fallbackCount = colors.size - FALLBACK_START
if (fallbackCount <= 0) return 0
return FALLBACK_START + abs(outcome.hashCode()) % fallbackCount
}
}
/**
* Which kind of thing a graph node is, used to give the nodes genuinely distinct
* fills: terminals versus stages, and a stage's effective type (model / ntfy /
* other). Mirrors [effectiveStageType], so a blank type is the model stage.
*/
internal enum class GraphNodeKind { TerminalSuccess, TerminalFailure, Model, Ntfy, Custom }
/** The kind of [key], from whether it is a terminal and its declared type. */
internal fun graphNodeKind(terminal: Boolean, key: String, type: String?): GraphNodeKind = when {
terminal && key == Protocol.FAILURE_END -> GraphNodeKind.TerminalFailure
terminal -> GraphNodeKind.TerminalSuccess
effectiveStageType(type) == "ntfy" -> GraphNodeKind.Ntfy
effectiveStageType(type) == "model" -> GraphNodeKind.Model
else -> GraphNodeKind.Custom
}
/**
* A more vivid version of [color] with the same hue, value and alpha: the HSV
* saturation is scaled by [factor] and clamped to 1. Used to make an executed
* pass/fail edge stroke stronger without changing its outcome hue, so both
* terminal colours get more punch while staying recognisably success/failure.
*
* Pure sRGB maths. A non-finite/non-positive [factor], an achromatic colour or
* one already at full saturation returns [color] unchanged, so callers never get
* NaN and every input is safe.
*/
internal fun boostSaturation(color: Color, factor: Float): Color {
if (!factor.isFinite() || factor <= 0f) return color
val r = color.red
val g = color.green
val b = color.blue
val max = maxOf(r, g, b)
val min = minOf(r, g, b)
val delta = max - min
if (max <= 0f || delta <= 0f) return color
val current = delta / max
val saturation = (current * factor).coerceAtMost(1f)
if (saturation <= current) return color
val hue = (when (max) {
r -> ((g - b) / delta + 6f) % 6f
g -> (b - r) / delta + 2f
else -> (r - g) / delta + 4f
}) * 60f
return Color.hsv(hue, saturation, max, color.alpha)
}
/**
* WCAG relative luminance of [color] (sRGB), the building block of the WCAG
* contrast ratio. Pure so the palette's legibility is measured in a unit test
* rather than judged by eye.
*/
internal fun relativeLuminance(color: Color): Double {
fun channel(value: Float): Double {
val c = value.toDouble()
return if (c <= 0.03928) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4)
}
return 0.2126 * channel(color.red) + 0.7152 * channel(color.green) + 0.0722 * channel(color.blue)
}
/**
* WCAG 2.x contrast ratio between two opaque colours, in `[1.0, 21.0]`. The
* formula is symmetric, so argument order does not matter.
*/
internal fun contrastRatio(a: Color, b: Color): Double {
val la = relativeLuminance(a)
val lb = relativeLuminance(b)
val hi = max(la, lb)
val lo = min(la, lb)
return (hi + 0.05) / (lo + 0.05)
}
@@ -1,230 +0,0 @@
package net.awan.pipelines.ui.graph
import android.webkit.WebView
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The html session export [step] recorded, resolved against the visit's recorded
* artifacts, or null when the visit has no export to open. The server writes one
* html file per session; a visit that recorded no export (a Pi harness, a failed
* export or a pre-export server) or whose file is missing from a truncated
* artifact listing yields null, so the stage pane lists no Session section for a
* visit that has nothing to show. The retired `session.md` export is never named
* by the server record and is never presented.
*/
internal fun sessionExportFile(step: RunStep): StageArtifact? {
val export = step.sessionExport ?: return null
val name = export.html.takeIf { it.isNotBlank() } ?: return null
return step.artifacts.orEmpty().firstOrNull { it.name == name }
}
/**
* One exported session file, loaded: its html kept as the document text, its
* absence a distinct error. A null url means no server was configured to fetch
* it from.
*/
internal sealed interface SessionLoad {
data object Loading : SessionLoad
data object Unavailable : SessionLoad
data object Error : SessionLoad
data class Html(val document: String) : SessionLoad
}
/**
* Classifies one fetched session file: a failed fetch ([bytes] null) is a distinct
* error state, never rendered as an empty session, and a fetched file decodes to
* its document text. Pure (the UTF-8 decode replaces malformed sequences rather
* than throwing), so the viewer passes it off the main thread and it is unit
* tested.
*/
internal fun sessionLoad(bytes: ByteArray?): SessionLoad =
if (bytes == null) SessionLoad.Error else SessionLoad.Html(bytes.toString(Charsets.UTF_8))
/**
* The Session section pane: the exported session of the selected visit, read like
* the artifacts beside it. The one session export is html, shown in a WebView for
* fidelity — there is no markdown view and no view toggle. The context line stays
* pinned above the scroll, exactly as the other section panes keep their chrome.
* On a wide window [visitTabs] renders the pinned visit row in that header; on a
* narrow one the caller owns the visit strip below instead, so the header must not
* double it.
*
* The file is fetched once per url through the app's shared artifact byte cache and
* the fetch runs off the main thread, so reopening the pane never re-hits the
* network and never blocks the pane. A missing server URL shows that state, and a
* failed fetch shows its own error in this pane only: the stage screen and every
* other section are unaffected.
*/
@Composable
internal fun SessionExportSection(
stageKey: String,
step: RunStep,
runSteps: List<RunStep>,
visitIndex: Int,
onVisitIndexChange: (Int) -> Unit,
configuredServerUrl: String,
fetchArtifactBytes: suspend (String) -> ByteArray?,
visitTabs: Boolean = true,
modifier: Modifier = Modifier,
) {
val file = remember(step) { sessionExportFile(step) }
Column(modifier.fillMaxSize()) {
if (file == null) {
SessionHeader(stageKey, runSteps, visitIndex, onVisitIndexChange, visitTabs) {
Text("No session was exported for this visit.", style = pipelinesText().meta)
}
return@Column
}
SessionHeader(stageKey, runSteps, visitIndex, onVisitIndexChange, visitTabs) {}
SessionBody(
load = rememberSessionLoad(resolvedArtifactUrl(file, configuredServerUrl), fetchArtifactBytes),
modifier = Modifier.weight(1f),
)
}
}
/**
* The session pane's pinned header: the context line naming the stage and — on a
* wide window — the visit row, followed by the caller's [content] (the
* missing-export notice, or nothing when a session is shown). It stays above the
* session's own scroll, exactly as the other section panes keep their chrome. On a
* narrow window [visitTabs] is false and the visit selector is the caller's bottom
* strip instead, so the header does not show it twice.
*/
@Composable
private fun SessionHeader(
stageKey: String,
runSteps: List<RunStep>,
visitIndex: Int,
onVisitIndexChange: (Int) -> Unit,
visitTabs: Boolean,
content: @Composable () -> Unit,
) {
val text = pipelinesText()
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L, vertical = SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(GraphSemantics.nodeLabel(stageKey), style = text.meta)
if (visitTabs) StageVisitTabs(runSteps.size, visitIndex, onVisitIndexChange)
content()
}
}
/**
* The loaded session's body: the html document in a WebView, or the
* loading/unavailable/error notice. The one branch that draws a session.
*/
@Composable
private fun SessionBody(load: SessionLoad, modifier: Modifier = Modifier) {
when (load) {
SessionLoad.Loading -> SessionNotice(
message = "Loading session…",
modifier = modifier,
spinner = true,
)
SessionLoad.Unavailable -> SessionNotice(
message = "Set the server URL in Settings to open the session.",
modifier = modifier,
)
SessionLoad.Error -> SessionNotice(
message = "Couldn't load the exported session.",
modifier = modifier,
)
is SessionLoad.Html -> SessionHtml(document = load.document, modifier = modifier)
}
}
/** A centred loading/unavailable/error notice, in the section's own pane only. */
@Composable
private fun SessionNotice(message: String, modifier: Modifier = Modifier, spinner: Boolean = false) {
Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(
modifier = Modifier.padding(SPACING_L),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
if (spinner) CircularProgressIndicator()
Text(message, style = pipelinesText().meta)
}
}
}
/**
* The html export in a WebView, the fidelity view of the one session export. The
* document is self-contained, so it is loaded with a null base URL (no file or
* network origin), scripting is off, and the view is destroyed with the
* composition.
*/
@Composable
private fun SessionHtml(document: String, modifier: Modifier = Modifier) {
val context = LocalContext.current
val webView = remember {
WebView(context).apply {
settings.javaScriptEnabled = false
settings.builtInZoomControls = true
settings.displayZoomControls = false
}
}
LaunchedEffect(document) {
webView.loadDataWithBaseURL(null, document, "text/html", "utf-8", null)
}
DisposableEffect(webView) {
onDispose { webView.destroy() }
}
AndroidView(factory = { webView }, modifier = modifier.fillMaxWidth())
}
/**
* Loads the resolved session [url] once and classifies it. A null url is
* [SessionLoad.Unavailable] with no request attempted. The bytes are fetched
* through the app's shared [ArtifactBytesCache], so re-opening the section reuses
* them instead of loading the file a second time; the decode runs off the main
* thread so a large session never blocks the UI. A canceled effect (the url
* changed) never publishes its stale result.
*/
@Composable
private fun rememberSessionLoad(
url: String?,
fetchBytes: suspend (String) -> ByteArray?,
): SessionLoad {
if (url == null) return SessionLoad.Unavailable
var load by remember(url) { mutableStateOf<SessionLoad>(SessionLoad.Loading) }
LaunchedEffect(url) {
val cached = ArtifactBytesCache.get(url)
val bytes = cached ?: runCatching {
withContext(Dispatchers.IO) { fetchBytes(url) }
}.getOrNull()
if (cached == null && bytes != null) ArtifactBytesCache.put(url, bytes)
load = withContext(Dispatchers.Default) { sessionLoad(bytes) }
}
return load
}

Some files were not shown because too many files have changed in this diff Show More