Merge main into multiclient: combine the multi-client chat fan-out with main's chat tool-work, notifications, status palette and docs-fold changes

No conflicts: main's chat-surface work (the in-flight tool work in ChatFormat,
ChatStore and ChatTranscript, run notifications, the status palette) sits in
different hunks from this branch's fan-out edits, and main did not touch
docs/cli.md. Checks re-run on the merged tree: gofmt -l . (clean), go build ./...,
go vet ./..., go test -count=1 ./... (all packages pass; the focused multi-client
tests fan-out, per-session serialisation, first-answer-wins, pending replay and
resync pass), and the Android unit tests
(gradle --offline --no-daemon :app:testDebugUnitTest, BUILD SUCCESSFUL, 598 tests,
0 failures).
This commit is contained in:
2026-10-18 00:09:17 +01:00
44 changed files with 2073 additions and 229 deletions
+19 -4
View File
@@ -1,8 +1,21 @@
# Pipelines maintenance
When changing user-facing behavior or learning a confirmed runtime limitation,
update the relevant packaged OpenCode skill reference in
`internal/author/skill/references/` in the same change. Keep `SKILL.md` a concise,
## Consent (hard rule)
The operator owns this system. No change to it happens without their explicit consent in the
current conversation: new pipelines or versions, definition and stage-prompt edits,
orchestration scripts, briefs and the conventions they carry, the packaged skill and templates,
deploys, installs and deletions. Read-only investigation and reporting need no consent. Ask
first and name exactly what would change; a request for a fix is not consent for a particular
mechanism.
When a change alters user-facing behavior, or you learn a confirmed runtime
limitation, record the stale documentation instead of editing the shared document in
the same change: leave a per-item note at `docs/notes/<slug>.md` naming what changed and
which packaged OpenCode skill reference in `internal/author/skill/references/`, README
or topic doc is now stale and what should change there. The manual-only `docs-fold`
pipeline folds `docs/notes/` into the shared docs and references; an item never edits a
shared document itself. Keep `SKILL.md` a concise,
task-directed index: preserve ask-first authoring and never preload every reference.
Separate current capabilities, dated verification evidence, deployment state and
unimplemented ideas. Do not turn mocked or structural checks into live claims.
@@ -12,7 +25,9 @@ Run the author package tests: they check embedding, reference links, installatio
upgrades and protection of user modifications. Never hand-edit an installed copy
as the source of truth; refresh it with the current-source `pipelines skill install`
only when installation is requested. Do not deploy runtime changes merely because
the skill is updated. Keep README/topic docs and the packaged reference consistent.
the skill is updated. Keep the shared docs and packaged references consistent through
the single `docs-fold` writer rather than editing them per item: leave a
`docs/notes/<slug>.md` note.
## Maintenance workflow
+56 -2
View File
@@ -253,7 +253,12 @@ stops it.
Nothing is removed, and the visit tabs still switch the selected visit.
- Steps render as a timeline in run detail: a leading status glyph connected to
the next step by an outcome-coloured line (kept aligned with the step title),
the stage with its sequence and an outcome chip. A step's metadata is a set of
the stage with its sequence and an outcome chip. A step's colour comes from the
one status source, so a word that is a run state (`success`/`error`/`blocked`/
`skipped`/`waiting`/…) is the same colour the runs list draws; only a graph-only
flow outcome (`approved`, `retry`, …) keeps its curated graph colour. A visit's
*outcome* is still distinguished from the run's *status* by the chip's own label
and the row's state glyph, never by a second colour. A step's metadata is a set of
aligned label/value rows (`KeyValueRow`) — paired side by side in two columns on
a wide window and stacked in one column on a narrow one — with a single
consistent vertical rhythm (one bottom gap per step, no doubled gap when a step
@@ -267,7 +272,8 @@ stops it.
via `formatDuration`, and colour-coded succeeded/failed/canceled/interrupted/
active counts). Each card shows the pipeline name with a version chip, a
colour-coded status chip with a distinct icon per state
(running/queued/succeeded/failed/canceled/interrupted/active/unknown), a meta
(running/waiting/queued/succeeded/failed/canceled/interrupted/active/unknown),
a meta
row (run id, start time, duration) and the diagnostic only when non-blank,
clamped to two lines. The raw `resultPreview` is no longer printed, and
progress is shown honestly (completed visits + current stage, with an
@@ -2703,6 +2709,10 @@ command targeted `emulator-5556`; lane A's `emulator-5554` was not used).
call the shared `graphColors(scheme)` factory (extracted from `WorkflowGraph`,
which uses it too) and `outcomeColor`, so a step chip agrees with the graph.
The run header and runs-list cards keep the run-status palette.
*(Superseded 17 Oct 2026: the graph's terminal roles and the Timeline chip now
also take the one run-status colour, so "the graph outcome palette is unchanged"
no longer holds — see "One status colour everywhere" below. `RunStatusPalette`
stays the single status source.)*
- **Shared helper.** `ui/components/RunStatus.kt` gained `ColoredChip(label,
colour, icon, …)` — the single pill layout now used by both `StatusChip` (run
status) and the Timeline's outcome chip, instead of a second copy.
@@ -2785,6 +2795,50 @@ tree (JDK 17 from Homebrew `openjdk@17`, Gradle 8.11.1, `--offline`):
`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 18009527`, and a streamed `GET | shasum -a 256` matched.
## One status colour everywhere (17 Oct 2026)
A successful stage in the Timeline read amber, because a visit's chip was coloured
from the graph's outcome palette while every other surface used the run-status
palette, so the same word meant two colours. `android/` only; nothing in the
Pipelines server, its Go source, the Docker/compose files or the installer was
touched, no dependency was added beyond the already-declared
`material-icons-extended`, and no run was started from the app.
- **One source of truth.** `ui/components/RunStatusPalette.kt`, with `RunState` /
`runStateOf` / `runStateColor` / `runStateIcon` in `ui/components/RunStatus.kt`,
owns a status colour. `RunState` gained the server's own `Waiting`/`Blocked`/
`Skipped` words (`waiting` corroborated by `internal/tui/run_progress.go`), each
with a deliberate palette entry, a distinct material glyph
(`HourglassEmpty`/`Block`/`SkipNext`) and a label, so status is never colour
alone.
- **The graph and timeline route through it.** `graphColors(scheme)` sets
`success`/`error` from `runStateColor(Succeeded/Failed)`, and `outcomeColor`
returns the shared status colour for any word that resolves to a `RunState`,
falling back to `GraphPalette` only for the graph-only flow outcomes
(`rejected`, `exhausted`, `retry`, `approved`, `fast`, `missing`; `blocked`/
`skipped`/`done` were removed from the graph palette). The Timeline's
`TimelineRow` uses the same factory, so a successful visit is green and a failure
red. A visit's *outcome* stays distinct from the run's *status* by the chip's own
label and the row's state glyph, never a second colour. The runs list's failure
diagnostic uses `runStateColor(Failed)` rather than a scheme role that could
drift from the chip above it, and the list's status filter gained `waiting`.
- **Tests.** `GraphPaletteTest` asserts every status word's graph colour equals the
runs-list colour and that the graph-only outcomes stay distinct and borrow no
status colour; `ui/graph/StatusColorConsistencyTest` asserts the timeline maps
through the same source and that every state maps to exactly one colour, the one
deliberate alias being Running/Active.
Evidence obtained on this tree (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle
8.11.1, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`,
`--no-daemon`):
- `gradle :app:testDebugUnitTest --rerun-tasks` → **516 tests, 0 failures, 0
errors, 0 skipped** (including the new `StatusColorConsistencyTest`, 2 cases, and
the extended `GraphPaletteTest`, 12 cases, and `RunStatusTest`, 3 cases).
- **APK publish.** The run's debug APK is
`…/artifacts/282/1/pipelines-debug-wip-d13f359.apk` (18,486,624 bytes, sha256
`b11481889b2894efb5fb6b17bcb62af819fe4b6ffb0196f5e27834b4736a5e1c`).
## Last-run facts on every pipeline row (16 Oct 2026)
`android/` only. No server field was added: the whole run history already arrives
+8
View File
@@ -3,6 +3,14 @@
<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"
@@ -11,18 +11,21 @@ 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.runIdFromDeepLink
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. It is read from the launch or update intent and cleared once
// PipelinesApp has opened it, so a recomposition never re-navigates.
// 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)
deepLinkedRunId = runIdFromDeepLink(intent?.data?.toString())
applyDeepLink(intent)
enableEdgeToEdge()
val app = application as PipelinesApplication
setContent {
@@ -31,7 +34,11 @@ class MainActivity : ComponentActivity() {
PipelinesApp(
vm = vm,
initialRunId = deepLinkedRunId,
onInitialRunHandled = { deepLinkedRunId = null },
initialRunAction = deepLinkedAction,
onInitialRunHandled = {
deepLinkedRunId = null
deepLinkedAction = null
},
)
}
}
@@ -41,6 +48,12 @@ class MainActivity : ComponentActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
deepLinkedRunId = runIdFromDeepLink(intent.data?.toString())
applyDeepLink(intent)
}
private fun applyDeepLink(intent: Intent?) {
val link = runLinkFromDeepLink(intent?.data?.toString())
deepLinkedRunId = link?.runId
deepLinkedAction = link?.action
}
}
@@ -7,6 +7,7 @@ import kotlinx.coroutines.SupervisorJob
import net.awan.pipelines.data.PipelinesRepository
import net.awan.pipelines.data.SettingsRepository
import net.awan.pipelines.data.transport.PipelinesClient
import net.awan.pipelines.notify.RunNotifier
/**
* Holds the single long-lived repository, WebSocket client and application
@@ -21,4 +22,16 @@ class PipelinesApplication : Application() {
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) }
override fun onCreate() {
super.onCreate()
runNotifier.ensureChannel()
}
}
@@ -71,6 +71,13 @@ class SettingsRepository(context: Context) {
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()
fun setServerUrl(value: String) {
val trimmed = value.trim()
_serverUrl.value = trimmed
@@ -141,6 +148,13 @@ class SettingsRepository(context: Context) {
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()
}
/** True only when the user has explicitly supplied both required values. */
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
@@ -158,5 +172,6 @@ class SettingsRepository(context: Context) {
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"
}
}
@@ -0,0 +1,249 @@
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()
@@ -0,0 +1,187 @@
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"
}
}
@@ -38,6 +38,9 @@ import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.data.protocol.Template
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.data.transport.ServerUrl
import net.awan.pipelines.notify.NoRunAlerts
import net.awan.pipelines.notify.RunAlertSink
import net.awan.pipelines.notify.runAlerts
import net.awan.pipelines.ui.chat.ChatAttachment
import net.awan.pipelines.ui.chat.ChatSessionOverrides
import net.awan.pipelines.ui.chat.ChatSeenState
@@ -61,6 +64,7 @@ data class LoadState<T>(
class AppViewModel(
private val repository: PipelinesRepository,
private val settings: SettingsRepository,
private val alertSink: RunAlertSink = NoRunAlerts,
) : ViewModel() {
val connectionState: StateFlow<ConnectionState> = repository.connectionState
@@ -135,6 +139,20 @@ class AppViewModel(
attentionEntries(runs.data?.runs.orEmpty(), state)
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/**
* Whether the app's notifications can actually be shown right now (the
* POST_NOTIFICATIONS permission on Android 13+, the app's switch before that).
* The permission layer reads this to decide whether to ask; the app degrades to
* its in-app attention surface when it is false rather than pretending a
* notification was posted. Refreshed whenever the app returns to the front, so
* a change made in system settings is reflected.
*/
private val _notificationsAllowed = MutableStateFlow(false)
val notificationsAllowed: StateFlow<Boolean> = _notificationsAllowed.asStateFlow()
/** Whether the runtime notification permission has already been asked for (or refused). */
val notificationPermissionAsked: StateFlow<Boolean> = settings.notificationPermissionAsked
// Debounces keystrokes and gates replies so an older query can never land on
// top of a newer one; the pure ordering lives in SearchSequencer.
private val searchSequencer = SearchSequencer()
@@ -209,6 +227,7 @@ class AppViewModel(
observeChatOverrides()
observeChatSeen()
observeAttention()
observeRunAlerts()
}
/**
@@ -543,20 +562,54 @@ class AppViewModel(
}
/**
* Deliberately dismisses one attention entry for good, so a still-waiting or
* still-failed run the operator has chosen to ignore stops asking.
* Feeds the app's Android notifications from the same attention list the
* in-app surface shows: a run waiting for a decision and a failed run each
* become one notification (or, when several need the operator, one grouped
* summary), and a run that leaves the list — resolved, answered or dismissed —
* has its notification cleared. Nothing here decides what matters; it is the
* pure alert model applied.
*/
fun dismissAttention(runId: Long, kind: AttentionKind) {
_attentionState.value = _attentionState.value.dismissed(attentionKey(runId, kind))
private fun observeRunAlerts() {
_notificationsAllowed.value = alertSink.notificationsAllowed()
viewModelScope.launch {
attention.collect { entries -> alertSink.sync(runAlerts(entries)) }
}
}
/** Re-reads whether notifications can be shown; called when the app comes to the front. */
fun refreshNotificationsAllowed() {
val allowed = alertSink.notificationsAllowed()
_notificationsAllowed.value = allowed
// A grant may have happened after the alert was already needed (the
// operator answered the system dialog or changed the setting): re-sync so
// the still-pending run is shown now rather than waiting for the next push.
// The ledger still prevents re-posting anything already shown.
if (allowed) alertSink.sync(runAlerts(attention.value))
}
/** Records that the runtime notification permission has been asked for, so it never nags. */
fun markNotificationPermissionAsked() {
settings.setNotificationPermissionAsked(true)
}
/**
* Records that the operator has looked at the finished runs now on the
* surface, so a run that merely finished since the last look clears on this
* look rather than reappearing. Called when the list is opened.
* The operator has reached [runId]: its notification is cleared, and — because
* the run is still waiting or failed — it is not posted again. Called through
* the one path that opens a run, so a tap, an attention tap and a deep link all
* clear the same way.
*/
fun sawFinishedAttention(ids: Collection<Long>) {
_attentionState.value = _attentionState.value.lookedAtFinished(ids.toSet())
fun arrivedAtRun(runId: Long) {
alertSink.arrived(runId)
}
/**
* Deliberately dismisses one attention entry for good, so a still-waiting or
* still-failed run the operator has chosen to ignore stops asking. The
* notification for it is cleared by the same attention change the app's
* notifications are fed from.
*/
fun dismissAttention(runId: Long, kind: AttentionKind) {
_attentionState.value = _attentionState.value.dismissed(attentionKey(runId, kind))
}
fun updateServerUrlDraft(value: String) {
@@ -1142,7 +1195,7 @@ class AppViewModel(
private const val CHAT_HISTORY_LIMIT = 200
fun factory(app: PipelinesApplication) = viewModelFactory {
initializer { AppViewModel(app.repository, app.settings) }
initializer { AppViewModel(app.repository, app.settings, app.runNotifier) }
}
}
}
@@ -8,22 +8,21 @@ 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, a failed run
* ([AttentionKind.Failed]) next, and a run that finished since the operator last
* looked ([AttentionKind.Finished]) last. Everything else — queued, running,
* canceled, interrupted — asks nothing and is not listed, so the surface can only
* ever show something that is genuinely actionable.
* 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 three things the attention surface ranks, most important first. */
/** The two things the attention surface ranks, most important first. */
enum class AttentionKind(val rank: Int) {
Decision(0),
Failed(1),
Finished(2),
}
/** One entry on the attention surface: what run needs the operator, and why. */
@@ -55,7 +54,6 @@ internal fun attentionKindOf(status: String): AttentionKind? =
when (status.trim().lowercase()) {
"waiting" -> AttentionKind.Decision
"failed" -> AttentionKind.Failed
"succeeded" -> AttentionKind.Finished
else -> null
}
@@ -67,22 +65,19 @@ internal fun attentionKindOf(status: String): AttentionKind? =
internal fun attentionDetail(kind: AttentionKind, run: RunSummary): String = when (kind) {
AttentionKind.Decision -> "Waiting for your decision"
AttentionKind.Failed -> run.diagnostic.trim().ifBlank { "Run failed" }
AttentionKind.Finished -> "Finished"
}
/**
* The ordered attention list. Every run that needs the operator becomes one
* entry, ranked by kind (decision, failed, finished) 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 finished run the operator
* has already looked at stays gone; a waiting or failed run returns until it is
* resolved or dismissed, because it is still asking.
* 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
if (kind == AttentionKind.Finished && run.id in state.finishedSeen) return@mapNotNull null
AttentionEntry(
runId = run.id,
pipeline = run.name,
@@ -103,25 +98,20 @@ internal fun attentionEntries(runs: List<RunSummary>, state: AttentionState): Li
* stored state:
*
* - [dismissed] is the run+kind keys the operator deliberately dismissed, so a
* still-waiting run stays out of the list after an explicit dismissal.
* - [finishedSeen] is the finished runs the operator has looked at, so the list
* shows a completed run once and clears it on the next look.
* 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(),
val finishedSeen: Set<Long> = 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)
/** Records the finished runs the operator has now looked at. */
fun lookedAtFinished(ids: Set<Long>): AttentionState {
val added = ids.filter { it > 0 && it !in finishedSeen }.toSet()
return if (added.isEmpty()) this else copy(finishedSeen = finishedSeen + added)
}
/** The one-line JSON this value is stored as; never fails on our own value. */
fun encode(): String = PipelinesJson.encodeToString(serializer(), this)
@@ -138,7 +128,45 @@ data class AttentionState(
}
/** The deep-link scheme the run notification's click action opens. */
internal const val RUN_DEEP_LINK_PREFIX = "pipelines://run/"/**
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.
*/
@@ -147,7 +175,6 @@ internal fun attentionHeadline(entries: List<AttentionEntry>): String = when {
entries.size == 1 -> when (entries[0].kind) {
AttentionKind.Decision -> "A run is waiting for you"
AttentionKind.Failed -> "A run failed"
AttentionKind.Finished -> "A run finished"
}
else -> "${entries.size} runs need you"
}
@@ -157,10 +184,4 @@ internal fun attentionHeadline(entries: List<AttentionEntry>): String = when {
* anything else. Pure and total, so a malformed link simply opens nothing rather
* than a guessed run.
*/
internal fun runIdFromDeepLink(link: String?): Long? {
val value = link?.trim().orEmpty()
if (!value.startsWith(RUN_DEEP_LINK_PREFIX)) return null
val rest = value.removePrefix(RUN_DEEP_LINK_PREFIX)
if (rest.isEmpty() || !rest.all { it.isDigit() }) return null
return rest.toLongOrNull()?.takeIf { it > 0 }
}
internal fun runIdFromDeepLink(link: String?): Long? = runLinkFromDeepLink(link)?.runId
@@ -1,6 +1,9 @@
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
@@ -23,8 +26,11 @@ 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.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -39,6 +45,8 @@ 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
@@ -46,6 +54,8 @@ 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.AttentionIndicator
import net.awan.pipelines.ui.components.AttentionSheet
@@ -91,6 +101,7 @@ internal fun backFrom(selection: PaneSelection): PaneSelection =
fun PipelinesApp(
vm: AppViewModel,
initialRunId: Long? = null,
initialRunAction: String? = null,
onInitialRunHandled: () -> Unit = {},
) {
val navController = rememberNavController()
@@ -118,10 +129,42 @@ fun PipelinesApp(
// 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
@@ -166,31 +209,35 @@ fun PipelinesApp(
// 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("runs") { 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.
LaunchedEffect(initialRunId) {
// 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: a run that merely finished since the
// last look clears on this look, while a waiting or failed run stays until it
// is resolved or deliberately dismissed.
// 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 = {
vm.sawFinishedAttention(attention.filter { it.kind == AttentionKind.Finished }.map { it.runId })
attentionOpen = false
}
// Opening an entry deals with it: a failure (like a finished run) is cleared
// by opening it, a waiting run is not, because only its decision clears it.
// 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)
@@ -279,6 +326,8 @@ fun PipelinesApp(
pendingNav = runSearchNav,
onPendingNavResolved = { runSearchNav = null },
listState = runListState,
decisionRequest = decisionRequest,
onDecisionRequestHandled = { decisionRequest = null },
)
}
composable("chat") {
@@ -370,6 +419,27 @@ fun PipelinesApp(
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") }
},
)
}
}
}
}
@@ -32,6 +32,8 @@ internal fun RunsDestination(
pendingNav: SearchTarget.Run?,
onPendingNavResolved: () -> Unit,
listState: LazyListState,
decisionRequest: Long? = null,
onDecisionRequestHandled: () -> Unit = {},
) {
val depth = selection.depth
val onBack: () -> Unit = { onSelectionChange(backFrom(selection)) }
@@ -99,6 +101,8 @@ internal fun RunsDestination(
)
},
covered = covered,
requestDecision = decisionRequest == itemId,
onDecisionRequestHandled = onDecisionRequestHandled,
)
}
2 -> rememberPaneContent(
@@ -7,6 +7,7 @@ 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.ChatToolState
@@ -79,6 +80,126 @@ internal fun formatToolDuration(millis: Long): String = when {
/** The chip label for a tool call: its name, or a placeholder when unnamed. */
internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" }
/**
* 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
}
/**
* 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
/**
* 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 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.
@@ -255,8 +255,8 @@ private fun SessionListItem(
val thread = state.thread(session.id)
SessionRow(
session = session,
thread = thread,
open = thread != null,
running = thread?.running == true,
unseen = state.isUnseen(session),
active = state.activeId == session.id,
onClick = { vm.openChatSession(session) },
@@ -289,8 +289,8 @@ private const val NO_DIRECTORY_LABEL = "No directory"
@Composable
private fun SessionRow(
session: ChatSession,
thread: ChatThread?,
open: Boolean,
running: Boolean,
unseen: Boolean,
active: Boolean,
onClick: () -> Unit,
@@ -298,6 +298,7 @@ private fun SessionRow(
onRemove: () -> Unit,
) {
val texts = pipelinesText()
val running = thread?.running == true
val activity = sessionActivity(running, unseen)
ListRow(selected = active, onClick = onClick) {
Row(
@@ -321,7 +322,7 @@ private fun SessionRow(
SessionMenu(onRename = onRename, onRemove = onRemove)
}
val meta = buildList {
add(sessionStatusLabel(session, running))
add(sessionWorkLabel(session.busy, thread))
if (session.directory.isNotBlank()) add(session.directory)
if (session.model.isNotBlank()) add(session.model)
}.joinToString(" · ")
@@ -70,6 +70,15 @@ data class ChatThread(
* the turn settles.
*/
val runningSince: Long = 0,
/**
* Wall-clock epoch millis each currently-running tool call was first seen
* running, keyed by the tool part's id. The brokered stream pushes a tool part
* with no timing envelope, so a running call's elapsed time is measured from
* here; a call that settles loses its stamp. Kept on the thread (not in the
* composable) so the elapsed time survives a chat switch, exactly like
* [runningSince] does for the turn.
*/
val toolStartedAt: Map<String, Long> = emptyMap(),
/** The unsent composer text for this chat. */
val draft: String = "",
/**
@@ -122,6 +131,22 @@ data class ChatThread(
*/
fun elapsedMillis(nowMillis: Long): Long =
if (running && runningSince in 1 until nowMillis) nowMillis - runningSince else 0
/**
* The tool calls still in flight for this session, in transcript order, so the
* conversation's in-flight indicator and the session row both read the same
* set. Empty once every call has completed or errored, which is what clears
* the indicator.
*/
val runningTools: List<ChatPart> get() = runningToolCalls(messages)
/**
* How long [part] has been running at [nowMillis]: the protocol's own timing
* when the part carries it, else the local start recorded in [toolStartedAt]
* (see [runningToolElapsedMillis]). Zero when neither is usable.
*/
fun toolElapsedMillis(part: ChatPart, nowMillis: Long): Long =
runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, nowMillis)
}
/**
@@ -582,7 +607,16 @@ class ChatStore(
*/
fun history(sessionId: String, messages: List<ChatMessage>) {
update(sessionId) {
it.copy(messages = messages, loading = false, loaded = true, error = null)
it.copy(
messages = messages,
loading = false,
loaded = true,
error = null,
// A running call the history reports (a turn that started before
// this fetch) is stamped now, the best local measurement there is;
// a call that already settled drops its stamp.
toolStartedAt = runningToolStamps(it.toolStartedAt, messages, now()),
)
}
// A conversation on screen is read as its history arrives: its recency
// watermark advances to the newest message the server reports (its own
@@ -614,7 +648,9 @@ class ChatStore(
val ids = _state.value.open.map { it.sessionId }
if (ids.isEmpty()) return ids
_state.value = _state.value.copy(
open = _state.value.open.map { if (it.running) it.copy(running = false, runningSince = 0) else it },
open = _state.value.open.map {
if (it.running) it.copy(running = false, runningSince = 0, toolStartedAt = emptyMap()) else it
},
)
return ids
}
@@ -812,7 +848,8 @@ class ChatStore(
val updated = upsert(if (partIndex >= 0) parts[partIndex] else null)
if (partIndex >= 0) parts[partIndex] = updated else parts.add(updated)
messages[resolvedIndex] = message.copy(parts = parts)
setRunning(thread.copy(messages = messages), true)
val stamped = runningToolStamps(thread.toolStartedAt, messages, now())
setRunning(thread.copy(messages = messages, toolStartedAt = stamped), true)
}
}
@@ -825,7 +862,7 @@ class ChatStore(
private fun setRunning(thread: ChatThread, running: Boolean): ChatThread = when {
running && !thread.running -> thread.copy(running = true, runningSince = now())
running -> thread
else -> thread.copy(running = false, runningSince = 0)
else -> thread.copy(running = false, runningSince = 0, toolStartedAt = emptyMap())
}
private fun update(sessionId: String, block: (ChatThread) -> ChatThread) {
@@ -20,6 +20,7 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
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.Psychology
@@ -34,6 +35,7 @@ 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
@@ -46,6 +48,7 @@ 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 kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
@@ -57,6 +60,7 @@ 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. */
@@ -274,24 +278,90 @@ private fun LazyListState.bottomDistancePx(itemCount: Int): Int? {
/**
* The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed
* time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]),
* so it keeps counting across a chat switch, and the tick loop stops the moment
* the turn settles.
* 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 elapsed values are derived 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. This is what makes the
* otherwise-silent part of a turn legible: the operator can tell `working on X`
* from `waiting on something` instead of watching a bare `Running`.
*/
@Composable
private fun RunningIndicator(thread: ChatThread) {
val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince))
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("Working…", 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(vertical = 4.dp),
modifier = Modifier.fillMaxWidth().padding(start = CHAT_GUTTER),
) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Icon(
Icons.Default.Build,
contentDescription = null,
tint = tint,
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = "· ${formatDuration(elapsedMillis / 1_000)}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
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,
)
}
}
@@ -47,7 +47,6 @@ import net.awan.pipelines.ui.theme.SPACING_S
internal fun attentionRunState(kind: AttentionKind): RunState = when (kind) {
AttentionKind.Decision -> RunState.Waiting
AttentionKind.Failed -> RunState.Failed
AttentionKind.Finished -> RunState.Succeeded
}
/**
@@ -22,6 +22,7 @@ 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
@@ -65,6 +66,8 @@ 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) }
@@ -72,6 +75,16 @@ fun DecisionPrompt(
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,
@@ -10,6 +10,7 @@ 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
@@ -17,6 +18,7 @@ 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
@@ -48,6 +50,8 @@ enum class RunState(val label: String) {
Failed("failed"),
Canceled("canceled"),
Interrupted("interrupted"),
Blocked("blocked"),
Skipped("skipped"),
Active("active"),
Unknown("unknown"),
}
@@ -67,6 +71,8 @@ fun runStateOf(status: String): RunState = when (status.trim().lowercase()) {
"failed", "error" -> RunState.Failed
"canceled", "cancelled" -> RunState.Canceled
"interrupted" -> RunState.Interrupted
"blocked" -> RunState.Blocked
"skipped" -> RunState.Skipped
else -> RunState.Unknown
}
@@ -86,6 +92,8 @@ fun runStateIcon(state: RunState): ImageVector = when (state) {
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
}
@@ -4,17 +4,20 @@ import androidx.compose.ui.graphics.Color
import net.awan.pipelines.ui.theme.DarkError
/**
* The app-owned run-status palette.
* The app-owned status palette, the single source of truth for the colour of a
* status or stage-outcome word.
*
* Run status is a *different vocabulary* from the graph's stage outcomes
* ([net.awan.pipelines.ui.graph.GraphPalette]): a run that is `running` is not a
* `skipped` stage, and a `succeeded` run is not the amber the theme uses for a
* positive *stage* outcome. Borrowing Material roles therefore 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.
* 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 below is instead a deliberate, fixed colour with an explicit
* meaning, tuned for the dark Pipelines surface (`DarkSurface 0xFF0E1513`,
* 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])
@@ -29,6 +32,13 @@ internal object RunStatusPalette {
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")
@@ -50,11 +60,18 @@ internal object RunStatusPalette {
Entry(Color(0xFF9AA6A2), "neutral grey: waiting, clearly not the in-progress blue")
/**
* Parked on a person: violet, distinct from the in-progress blue, the queued
* grey and the amber operator-stop, so a run needing a decision is unmistakable.
* 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 Waiting =
Entry(Color(0xFFC0A3F5), "violet: parked for the operator's decision; not running, not a stop")
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 =
@@ -67,12 +84,14 @@ internal object RunStatusPalette {
*/
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.Waiting -> Waiting
RunState.Blocked -> Blocked
RunState.Skipped -> Skipped
RunState.Unknown -> Unknown
}
}
@@ -8,9 +8,15 @@ import kotlin.math.min
import kotlin.math.pow
/**
* The curated graph colour palette.
* The curated palette for the graph-only flow outcomes.
*
* Every distinct outcome gets its own deliberate entry (no `hashCode() % 4`
* 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.
@@ -19,46 +25,35 @@ import kotlin.math.pow
* 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.
*
* The two terminal outcomes stay theme roles in [GraphColors] (`error`→error,
* `success`→tertiary) so their meaning is preserved; everything else uses
* [colors].
*/
internal object GraphPalette {
/**
* The fixed palette. Deliberately fixed (rather than scheme-derived) so an
* outcome is the same colour on every device; the two terminal roles above
* remain scheme roles.
* outcome is the same colour on every device.
*/
val colors: List<Color> = listOf(
Color(0xFF8FE0A0), // 0 blocked - green
Color(0xFFF5A3A3), // 1 rejected - red
Color(0xFF8FB4F5), // 2 skipped - blue
Color(0xFFF5B37A), // 3 exhausted - orange
Color(0xFF7FD4E8), // 4 retry - cyan
Color(0xFFC0A3F5), // 5 approved - violet
Color(0xFFF0E07A), // 6 fast - yellow
Color(0xFFF5A3D0), // 7 missing - pink
Color(0xFFD6B08C), // 8 done - sand
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), // 9 fallback - khaki
Color(0xFF9FD8C0), // 10 fallback - sea
Color(0xFFD8A8C0), // 11 fallback - dusty rose
Color(0xFFD8C98A), // 6 fallback - khaki
Color(0xFF9FD8C0), // 7 fallback - sea
Color(0xFFD8A8C0), // 8 fallback - dusty rose
)
/** The known outcome names and their fixed palette index, in display order. */
/** The known graph-only outcome names and their fixed palette index, in display order. */
private val KNOWN: Map<String, Int> = linkedMapOf(
"blocked" to 0,
"rejected" to 1,
"skipped" to 2,
"exhausted" to 3,
"retry" to 4,
"approved" to 5,
"fast" to 6,
"missing" to 7,
"done" to 8,
"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]. */
@@ -67,8 +62,9 @@ internal object GraphPalette {
/**
* 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. `success`/`error` resolve
* to the theme roles in [outcomeColor] but still return a stable index here.
* 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 }
@@ -85,8 +85,11 @@ import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.edges
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.hostResumed
import net.awan.pipelines.ui.components.rememberLiveNowMillis
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.secondsSince
import net.awan.pipelines.ui.theme.GRAPH_ACTIVE_HALO_GAP
@@ -534,44 +537,51 @@ internal class GraphColors(
/**
* The graph's colours for [scheme], built in one place so every surface that must
* agree with the graph (the graph itself and the timeline's step-outcome chips)
* uses the same palette. The two terminal roles stay scheme roles so their
* meaning is kept; every other outcome uses the one curated, legible
* [GraphPalette] for both a stroke and its label text.
* uses the same palette. The two terminal roles take the one owned run-status
* colour (success green, failure red) so they can never disagree with the runs
* list; every other status word is coloured by the status palette in
* [outcomeColor], and the remaining graph-only flow outcomes use the one curated,
* legible [GraphPalette] for both a stroke and its label text.
*
* Node and label surfaces are *tonal*: a raised surface tone ([scheme]'s
* `surfaceContainerHigh`/`surfaceContainerHighest`) blended with a subtle tint of
* the node's semantic colour (see [tonalFill]) rather than a flat fill, so a node
* reads as raised card, not a terminal cell.
*/
internal fun graphColors(scheme: ColorScheme): GraphColors = GraphColors(
// The two terminal roles stay scheme roles so their meaning is kept.
success = scheme.tertiary,
error = scheme.error,
// Every other outcome uses the one curated, legible palette for both its
// stroke and its label text, so a curve and its label always agree.
palette = GraphPalette.colors,
// Node fills differ by kind (see [GraphNodeKind]): model (neutral), ntfy
// (amber), other/custom (green), and the two terminals (success/error). Each
// is a tonal surface carrying a subtle tint of that kind's semantic hue.
nodeFill = tonalFill(scheme.surfaceContainerHigh, scheme.onSurfaceVariant, NEUTRAL_TINT),
nodeNtfyFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, KIND_TINT),
nodeCustomFill = tonalFill(scheme.surfaceContainerHigh, scheme.primary, KIND_TINT),
// A selected node inverts (light fill / dark text) plus a stronger border, so
// selection reads in either appearance and never relies on colour.
nodeFillActive = scheme.inverseSurface,
nodeTextActive = scheme.inverseOnSurface,
// The stage border is deliberately soft (a low-contrast outline variant), not
// the hard original outline; terminals carry their outcome hue instead.
nodeBorder = scheme.outlineVariant,
nodeBorderActive = scheme.primary,
nodeText = scheme.onSurface,
terminalFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, TERMINAL_TINT),
terminalErrorFill = tonalFill(scheme.surfaceContainerHigh, scheme.error, TERMINAL_TINT),
// Edge outcome labels sit on a tonal chip (drawn as a rounded rect) rather than
// raw text over the canvas.
labelBackground = scheme.surfaceContainerHighest,
labelText = scheme.onSurfaceVariant,
)
internal fun graphColors(scheme: ColorScheme): GraphColors {
// The two terminal outcomes take the shared run-status colours so the graph
// and the runs list can never disagree about success/failure.
val success = runStateColor(RunState.Succeeded)
val error = runStateColor(RunState.Failed)
return GraphColors(
success = success,
error = error,
// Every other graph-only outcome uses the one curated, legible palette for
// both its stroke and its label text, so a curve and its label always agree.
palette = GraphPalette.colors,
// Node fills differ by kind (see [GraphNodeKind]): model (neutral), ntfy
// (amber), other/custom (green), and the two terminals (success/error). Each
// is a tonal surface carrying a subtle tint of that kind's semantic hue.
nodeFill = tonalFill(scheme.surfaceContainerHigh, scheme.onSurfaceVariant, NEUTRAL_TINT),
nodeNtfyFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, KIND_TINT),
nodeCustomFill = tonalFill(scheme.surfaceContainerHigh, scheme.primary, KIND_TINT),
// A selected node inverts (light fill / dark text) plus a stronger border, so
// selection reads in either appearance and never relies on colour.
nodeFillActive = scheme.inverseSurface,
nodeTextActive = scheme.inverseOnSurface,
// The stage border is deliberately soft (a low-contrast outline variant), not
// the hard original outline; terminals carry their outcome hue instead.
nodeBorder = scheme.outlineVariant,
nodeBorderActive = scheme.primary,
nodeText = scheme.onSurface,
terminalFill = tonalFill(scheme.surfaceContainerHigh, success, TERMINAL_TINT),
terminalErrorFill = tonalFill(scheme.surfaceContainerHigh, error, TERMINAL_TINT),
// Edge outcome labels sit on a tonal chip (drawn as a rounded rect) rather than
// raw text over the canvas.
labelBackground = scheme.surfaceContainerHighest,
labelText = scheme.onSurfaceVariant,
)
}
/**
* [surface] blended with a [fraction] (0..1) of [accent], so a node/label fill
@@ -1602,17 +1612,19 @@ private fun DrawScope.drawActiveHalo(
}
/**
* The colour for an outcome: the theme error role for `error`, a clearly
* positive theme colour for `success`, and the curated [GraphPalette] entry for
* everything else. One colour is used for both the edge stroke and its label
* text (the palette is legible on the surface), so a curve and its label always
* agree. `success`/`error` are the terminal roles and are never colour-only
* signals (their labels name them). Pure and deterministic.
* The colour for an outcome or stage status, from the one owned source: a word
* that is a run state (`success`/`done`/`error`/`blocked`/`skipped`/`waiting`/
* `running`/…) takes the shared status colour the operator already learned from
* the runs list, so the same word is the same colour in the timeline, the graph,
* the stage sheet and the peek; a graph-only flow outcome (`approved`, `retry`, …)
* takes its curated [GraphPalette] entry. One colour serves both the edge stroke
* and its label text (the palette is legible on the surface), so a curve and its
* label always agree. Pure and deterministic.
*/
internal fun outcomeColor(outcome: String, colors: GraphColors): Color = when (outcome) {
"error" -> colors.error
"success" -> colors.success
else -> colors.palette[GraphPalette.outcomeColorIndex(outcome)]
internal fun outcomeColor(outcome: String, colors: GraphColors): Color {
val state = runStateOf(outcome)
if (state != RunState.Unknown) return runStateColor(state)
return colors.palette[GraphPalette.outcomeColorIndex(outcome)]
}
/**
@@ -46,13 +46,15 @@ enum class RunPresence(val label: String, val storageKey: String) {
/**
* The statuses a run filter can select. The server's own run vocabulary
* (internal/pipeline/runs.go: queued/running/succeeded/failed/canceled/
* interrupted); the app-only `active` usage bucket and the `unknown` fallback
* are deliberately not offered, so a status filter always names a real state.
* (internal/pipeline/runs.go: queued/running/waiting/succeeded/failed/canceled/
* interrupted); the app-only `active` usage bucket, the stage-outcome words
* (`blocked`/`skipped`) and the `unknown` fallback are deliberately not offered,
* so a status filter always names a real run state.
*/
internal val RUN_STATUS_FILTERS: List<RunState> = listOf(
RunState.Queued,
RunState.Running,
RunState.Waiting,
RunState.Succeeded,
RunState.Failed,
RunState.Canceled,
@@ -67,6 +67,8 @@ fun RunDetailScreen(
modifier: Modifier = Modifier,
wide: Boolean = false,
covered: Boolean = false,
requestDecision: Boolean = false,
onDecisionRequestHandled: () -> Unit = {},
) {
val state by vm.runDetail.collectAsStateWithLifecycle()
val runsState by vm.runs.collectAsStateWithLifecycle()
@@ -83,6 +85,9 @@ fun RunDetailScreen(
val selectionState = rememberArtifactSelection(runId)
LaunchedEffect(runId) {
// Reaching a run clears its notification, whichever path opened it (the
// notification's own tap, the attention list, the runs list or a search).
vm.arrivedAtRun(runId)
// Scope evidence to this run: drop the previous run's records, then fetch
// this run's evidence once (on demand; live pushes carry no evidence).
vm.resetEvidence()
@@ -210,6 +215,8 @@ fun RunDetailScreen(
vm.decideRun(pending.runId, pending.stageKey, option, feedback, onResult)
},
modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S),
openRequest = requestDecision,
onOpenRequestHandled = onDecisionRequestHandled,
)
StateCrossfade(
phase = detailLoadPhase(state.error, hasData = run != null),
@@ -585,8 +585,10 @@ private fun RunRow(
Text(
run.diagnostic,
style = text.meta,
// The one status colour for a failure, never a scheme role that
// could drift from the chip above it.
color = if (state == RunState.Failed) {
MaterialTheme.colorScheme.error
runStateColor(RunState.Failed)
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The monochrome status-bar glyph for "a run needs you": three attention bars
with a raised exclamation-free silhouette, so the small icon reads at 24dp
instead of shrinking the full-colour launcher art.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4,18h3v-6h-3z M10.5,18h3v-10h-3z M17,18h3v-14h-3z" />
</vector>
@@ -0,0 +1,249 @@
package net.awan.pipelines.notify
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.ui.AttentionEntry
import net.awan.pipelines.ui.AttentionKind
import net.awan.pipelines.ui.AttentionState
import net.awan.pipelines.ui.RUN_DEEP_LINK_ACTION_DECIDE
import net.awan.pipelines.ui.attentionEntries
import net.awan.pipelines.ui.runLinkFromDeepLink
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The notification model's pure rules: the event-to-notification mapping
* (waiting and failed only), the permission paths (granted, refused,
* not-yet-asked), coalescing into one summary, the dedupe/clear ledger, and the
* tap destination. No Android types are involved, so every path is asserted
* without a device.
*/
class RunAlertsTest {
private fun entry(
runId: Long,
kind: AttentionKind,
label: String = "Ship 1.4",
pipeline: String = "release",
detail: String = "",
) = AttentionEntry(
runId = runId,
pipeline = pipeline,
label = label,
kind = kind,
detail = detail,
)
private fun run(id: Long, status: String, title: String? = null, diagnostic: String = "") = RunSummary(
id = id,
pipelineId = 4,
name = "release",
title = title,
status = status,
executing = status == "running",
diagnostic = diagnostic,
)
// --- event-to-notification mapping ----------------------------------------
@Test
fun onlyWaitingAndFailedRaiseANotification() {
assertEquals(RunAlertKind.Decision, alertKindOf(AttentionKind.Decision))
assertEquals(RunAlertKind.Failed, alertKindOf(AttentionKind.Failed))
}
@Test
fun aSuccessfulRunningOrCancelledRunRaisesNothing() {
val runs = listOf(
run(1, "succeeded"),
run(2, "running"),
run(3, "canceled"),
run(4, "interrupted"),
run(5, "queued"),
)
assertTrue(runAlerts(attentionEntries(runs, AttentionState())).isEmpty())
}
@Test
fun waitingAndFailedBecomeOneAlertEachAndFinishedDoesNot() {
val runs = listOf(
run(1, "waiting", title = "Ship 1.4"),
run(2, "failed", diagnostic = "provider returned 500"),
run(3, "succeeded", title = "Nightly"),
)
val alerts = runAlerts(attentionEntries(runs, AttentionState()))
assertEquals(listOf(1L, 2L), alerts.map { it.runId })
assertEquals(listOf(RunAlertKind.Decision, RunAlertKind.Failed), alerts.map { it.kind })
assertEquals("A run needs your decision", alerts[0].title)
assertEquals("Ship 1.4 · release", alerts[0].text)
assertEquals("A run failed", alerts[1].title)
assertEquals("release", alerts[1].text)
}
@Test
fun oneRunAndEventKindHasOneStableIdentity() {
assertEquals(alertKey(7, RunAlertKind.Decision), alertKey(7, RunAlertKind.Decision))
assertTrue(alertKey(7, RunAlertKind.Decision) != alertKey(7, RunAlertKind.Failed))
assertTrue(alertKey(7, RunAlertKind.Decision) != alertKey(8, RunAlertKind.Decision))
// The notification id is stable per run+kind, so a repost updates in place.
assertEquals(alertNotificationId(7, RunAlertKind.Decision), alertNotificationId(7, RunAlertKind.Decision))
assertTrue(alertNotificationId(7, RunAlertKind.Decision) != alertNotificationId(7, RunAlertKind.Failed))
}
// --- coalescing -------------------------------------------------------------
@Test
fun aSingleAlertHasNoSummaryButSeveralCoalesceIntoOne() {
val one = runAlerts(listOf(entry(1, AttentionKind.Decision)))
assertNull(alertSummary(one))
val several = runAlerts(
listOf(
entry(1, AttentionKind.Decision),
entry(2, AttentionKind.Failed),
entry(3, AttentionKind.Failed),
),
)
val summary = alertSummary(several)
assertNotNull(summary)
assertEquals(3, summary!!.count)
assertEquals("3 runs need you", summary.title)
assertEquals("1 waiting for you · 2 failed", summary.text)
assertEquals(3, summary.lines.size)
}
// --- dedupe and clearing ----------------------------------------------------
@Test
fun theSameRunAndKindIsPostedOnlyOnce() {
val ledger = AlertLedger()
val alerts = runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed)))
val first = ledger.reconcile(alerts)
assertEquals(listOf(1L, 2L), first.post.map { it.runId })
assertTrue(first.cancel.isEmpty())
// A later reconciliation (the run stays waiting/failed) posts nothing.
val second = ledger.reconcile(alerts)
assertTrue(second.post.isEmpty())
assertTrue(second.isEmpty)
assertEquals(2, ledger.shown.size)
}
@Test
fun aResolvedRunIsCancelledAndOnlyTheNewOneIsPosted() {
val ledger = AlertLedger()
ledger.reconcile(runAlerts(listOf(entry(1, AttentionKind.Decision))))
val delta = ledger.reconcile(runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed))))
assertEquals(listOf(2L), delta.post.map { it.runId })
assertTrue(delta.cancel.isEmpty())
// Run 1 resolves/leaves the surface: its notification is cleared, run 2 stays.
val cleared = ledger.reconcile(runAlerts(listOf(entry(2, AttentionKind.Failed))))
assertTrue(cleared.post.isEmpty())
assertEquals(listOf(1L), cleared.cancel.map { it.runId })
assertEquals(setOf(alertKey(2, RunAlertKind.Failed)), ledger.shown.keys)
}
@Test
fun everythingIsClearedWhenNothingNeedsTheOperator() {
val ledger = AlertLedger()
ledger.reconcile(runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed))))
val cleared = ledger.reconcile(emptyList())
assertEquals(setOf(1L, 2L), cleared.cancel.map { it.runId }.toSet())
assertTrue(ledger.shown.isEmpty())
}
@Test
fun arrivingAtAStillWaitingRunClearsItWithoutReNotifying() {
val ledger = AlertLedger()
val alerts = runAlerts(listOf(entry(1, AttentionKind.Decision), entry(2, AttentionKind.Failed)))
ledger.reconcile(alerts)
assertEquals(2, ledger.visible().size)
// The operator opens run 1; its notification is cleared and the grouped
// summary stops counting it.
assertEquals(listOf(1L), ledger.arrived(1).map { it.runId })
assertEquals(listOf(2L), ledger.visible().map { it.runId })
// The run is still waiting, so the next reconciliation must not re-post it.
val again = ledger.reconcile(alerts)
assertTrue(again.post.isEmpty())
// Run 2 is untouched and still tracked.
assertTrue(ledger.shown.containsKey(alertKey(2, RunAlertKind.Failed)))
}
@Test
fun aRunThatFailsAgainAfterResolvingNotifiesAgain() {
val ledger = AlertLedger()
val failed = runAlerts(listOf(entry(1, AttentionKind.Failed)))
assertEquals(1, ledger.reconcile(failed).post.size)
// Resolved (left the surface): the key is forgotten.
assertTrue(ledger.reconcile(emptyList()).cancel.isNotEmpty())
// A new failure for the same run is a new event and notifies once more.
assertEquals(1, ledger.reconcile(failed).post.size)
}
// --- permission paths -------------------------------------------------------
@Test
fun aGrantedPermissionIsNeverAsked() {
val prompt = alertPermissionPrompt(granted = true, asked = false, trigger = true)
assertFalse(prompt.request)
assertNull(prompt.rationale)
}
@Test
fun theFirstTimeSomethingNeedsTheOperatorAsksWithARationale() {
val prompt = alertPermissionPrompt(granted = false, asked = false, trigger = true)
assertTrue(prompt.request)
assertEquals(NOTIFICATION_RATIONALE, prompt.rationale)
}
@Test
fun nothingIsAskedBeforeSomethingNeedsTheOperator() {
val prompt = alertPermissionPrompt(granted = false, asked = false, trigger = false)
assertFalse(prompt.request)
assertNull(prompt.rationale)
}
@Test
fun aRefusalIsRememberedAndNeverAskedAgain() {
// "asked" covers both a refusal and a dismissal of the rationale.
val prompt = alertPermissionPrompt(granted = false, asked = true, trigger = true)
assertFalse(prompt.request)
assertNull(prompt.rationale)
}
// --- tap destination --------------------------------------------------------
@Test
fun aWaitingRunOpensTheDecisionSheetAndAFailedRunOpensTheRun() {
assertEquals(AlertTapTarget.DecisionSheet, alertTapTarget(RunAlertKind.Decision))
assertEquals(AlertTapTarget.Run, alertTapTarget(RunAlertKind.Failed))
assertEquals("pipelines://run/42", alertDeepLink(42, RunAlertKind.Failed))
assertEquals(
"pipelines://run/42?action=$RUN_DEEP_LINK_ACTION_DECIDE",
alertDeepLink(42, RunAlertKind.Decision),
)
}
@Test
fun theRunDeepLinkCarriesItsOptionalAction() {
val decision = runLinkFromDeepLink("pipelines://run/42?action=$RUN_DEEP_LINK_ACTION_DECIDE")
assertEquals(42L, decision?.runId)
assertEquals(RUN_DEEP_LINK_ACTION_DECIDE, decision?.action)
val plain = runLinkFromDeepLink("pipelines://run/42")
assertEquals(42L, plain?.runId)
assertNull(plain?.action)
assertNull(runLinkFromDeepLink("pipelines://run/abc?action=$RUN_DEEP_LINK_ACTION_DECIDE"))
assertNull(runLinkFromDeepLink("pipelines://run/0"))
}
}
@@ -8,10 +8,11 @@ import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The attention surface's pure model: the event-to-entry mapping (waiting,
* failed and nothing else), the ranking of the three kinds, an entry appearing
* from a pushed run event and clearing when it is resolved, deliberate
* dismissal, the empty case, persistence, and the notification's deep link.
* The attention surface's pure model: the event-to-entry mapping (a waiting run
* and a failed run, and nothing else — a successful run is never announced), the
* ranking of the two kinds, an entry appearing from a pushed run event and
* clearing when it is resolved, deliberate dismissal, the empty case, persistence,
* and the notification's deep link.
*/
class AttentionTest {
@@ -45,10 +46,10 @@ class AttentionTest {
// --- mapping ---------------------------------------------------------------
@Test
fun onlyWaitingFailedAndFinishedAskForAttention() {
fun onlyAWaitingOrFailedRunAsksForAttention() {
assertEquals(AttentionKind.Decision, attentionKindOf("waiting"))
assertEquals(AttentionKind.Failed, attentionKindOf("failed"))
assertEquals(AttentionKind.Finished, attentionKindOf("succeeded"))
assertNull(attentionKindOf("succeeded"))
assertNull(attentionKindOf("queued"))
assertNull(attentionKindOf("running"))
assertNull(attentionKindOf("canceled"))
@@ -68,7 +69,7 @@ class AttentionTest {
),
AttentionState(),
)
assertEquals(3, entries.size)
assertEquals(2, entries.size)
val decision = entries[0]
assertEquals(AttentionKind.Decision, decision.kind)
assertEquals("Ship 1.4", decision.label)
@@ -77,25 +78,21 @@ class AttentionTest {
val failed = entries[1]
assertEquals(AttentionKind.Failed, failed.kind)
assertEquals("provider returned 500", failed.detail)
val finished = entries[2]
assertEquals(AttentionKind.Finished, finished.kind)
assertEquals("nightly", finished.label)
}
// --- ordering --------------------------------------------------------------
@Test
fun decisionRanksBeforeFailedBeforeFinished() {
fun decisionRanksBeforeFailed() {
val entries = attentionEntries(
listOf(
run(3, "succeeded", finishedAt = "2026-10-17T09:09:00Z"),
run(2, "failed", finishedAt = "2026-10-17T09:08:00Z"),
run(1, "waiting"),
),
AttentionState(),
)
assertEquals(listOf(AttentionKind.Decision, AttentionKind.Failed, AttentionKind.Finished), entries.map { it.kind })
assertEquals(listOf(1L, 2L, 3L), entries.map { it.runId })
assertEquals(listOf(AttentionKind.Decision, AttentionKind.Failed), entries.map { it.kind })
assertEquals(listOf(1L, 2L), entries.map { it.runId })
}
@Test
@@ -142,7 +139,7 @@ class AttentionTest {
assertTrue(attentionEntries(retried, AttentionState()).isEmpty())
}
// --- dismissal and look ----------------------------------------------------
// --- dismissal -------------------------------------------------------------
@Test
fun aDeliberateDismissalRemovesAnEntryForGood() {
@@ -155,11 +152,16 @@ class AttentionTest {
}
@Test
fun aFinishedRunClearsOnceTheOperatorHasLooked() {
val runs = listOf(run(1, "succeeded"))
assertEquals(1, attentionEntries(runs, AttentionState()).size)
val looked = AttentionState().lookedAtFinished(setOf(1L))
assertTrue(attentionEntries(runs, looked).isEmpty())
fun aSuccessfulRunIsNeverListed() {
assertTrue(attentionEntries(listOf(run(1, "succeeded")), AttentionState()).isEmpty())
// Even a finished run that was never looked at does not appear: a
// successful run raises nothing on any surface.
assertTrue(
attentionEntries(
listOf(run(2, "succeeded"), run(3, "running"), run(4, "canceled")),
AttentionState(),
).isEmpty(),
)
}
// --- empty case ------------------------------------------------------------
@@ -169,7 +171,13 @@ class AttentionTest {
assertTrue(attentionEntries(emptyList(), AttentionState()).isEmpty())
assertTrue(
attentionEntries(
listOf(run(1, "running"), run(2, "queued"), run(3, "canceled"), run(4, "interrupted")),
listOf(
run(1, "running"),
run(2, "queued"),
run(3, "canceled"),
run(4, "interrupted"),
run(5, "succeeded"),
),
AttentionState(),
).isEmpty(),
)
@@ -182,18 +190,21 @@ class AttentionTest {
assertEquals("A run is waiting for you", attentionHeadline(decision))
val failed = attentionEntries(listOf(run(2, "failed"), run(3, "failed")), AttentionState())
assertEquals("2 runs need you", attentionHeadline(failed))
val singleFailed = attentionEntries(listOf(run(4, "failed")), AttentionState())
assertEquals("A run failed", attentionHeadline(singleFailed))
}
// --- persistence -----------------------------------------------------------
@Test
fun attentionStateSurvivesAnEncodeDecodeRoundTrip() {
val state = AttentionState()
.dismissed(attentionKey(7, AttentionKind.Failed))
.lookedAtFinished(setOf(9L, 11L))
val state = AttentionState().dismissed(attentionKey(7, AttentionKind.Failed))
assertEquals(state, AttentionState.decode(state.encode()))
assertEquals(AttentionState(), AttentionState.decode(""))
assertEquals(AttentionState(), AttentionState.decode("not json"))
// A state stored by an older build that also recorded looked-at finished
// runs still decodes, keeping the dismissals.
assertEquals(AttentionState(), AttentionState.decode("""{"finishedSeen":[9,11]}"""))
}
// --- notification deep link ------------------------------------------------
@@ -0,0 +1,235 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import net.awan.pipelines.data.protocol.ChatEventFrame
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.ChatSession
import net.awan.pipelines.data.protocol.ChatTime
import net.awan.pipelines.data.protocol.ChatToolState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The in-flight work a conversation and its session row show: a running tool with
* its name, the command or description the part carries, and a live elapsed time
* that grows from when the call turned running, uses the protocol's own timing
* when the part has it, and clears the moment the call completes or errors. All
* pure or driven against [ChatStore] with an injected clock, so no device, server
* or Compose runtime is needed.
*/
class ChatRunningWorkTest {
private fun tool(
id: String,
name: String,
status: String,
input: JsonObject? = null,
time: ChatTime? = null,
) = ChatPart(
type = ChatProtocol.PART_TOOL,
id = id,
name = name,
state = ChatToolState(status = status, input = input),
time = time,
)
private fun toolFrame(sessionId: String, messageId: String, part: ChatPart) =
ChatEventFrame(sessionId = sessionId, messageId = messageId, kind = ChatProtocol.PART_TOOL, part = part)
private fun input(vararg pairs: Pair<String, String>): JsonObject =
JsonObject(pairs.associate { (key, value) -> key to JsonPrimitive(value) })
private fun threadWith(vararg parts: ChatPart) = ChatThread(
sessionId = "s",
running = true,
messages = listOf(
ChatMessage(
id = "m1",
sessionId = "s",
role = ChatProtocol.ROLE_ASSISTANT,
parts = parts.toList(),
),
),
)
@Test
fun aRunningToolShowsItsNameDetailAndGrowingTime() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.history("s", emptyList())
store.event(
toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls -la"))),
)
val thread = store.value.thread("s")!!
assertTrue(thread.running)
val call = thread.runningTools.single()
assertEquals("shell", call.name)
assertEquals("ls -la", toolDetail(call))
// Elapsed is measured locally from when the call turned running, so it
// starts at zero and grows with the clock.
assertEquals(0L, thread.toolElapsedMillis(call, clock))
clock = 6_000L
val later = thread.toolElapsedMillis(call, clock)
assertEquals(5_000L, later)
assertTrue(later > 0L)
}
@Test
fun aToolWithProtocolTimingUsesItsOwnStart() {
val timed = tool("c1", "bash", ChatProtocol.TOOL_RUNNING, time = ChatTime(created = 900, ran = 1_000))
// The protocol's own `ran` wins over the local stamp, so the elapsed is
// its start to now.
assertEquals(4_000L, runningToolElapsedMillis(timed, startedAt = 0L, nowMillis = 5_000L))
// Neither a protocol start nor a local one: nothing to show, never a guess.
assertEquals(0L, runningToolElapsedMillis(tool("c2", "bash", ChatProtocol.TOOL_RUNNING), 0L, 5_000L))
}
@Test
fun aCompletedOrFailedCallLeavesTheRunningSetAndTheFailureIsVisible() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls"))))
assertEquals(1, store.value.thread("s")!!.runningTools.size)
// Completion clears the call from the in-flight set and drops its stamp.
clock = 2_000L
store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_COMPLETED, input("command" to "ls"))))
val done = store.value.thread("s")!!
assertTrue(done.runningTools.isEmpty())
assertTrue(done.toolStartedAt.isEmpty())
assertFalse(toolFailed(done.messages.last().parts.single().state))
// A failure is out of the running set too, and reads as failed on its chip.
store.event(toolFrame("s", "m1", tool("c2", "shell", ChatProtocol.TOOL_ERROR)))
val failed = store.value.thread("s")!!
assertTrue(failed.runningTools.isEmpty())
assertTrue(toolFailed(failed.messages.last().parts.first { it.id == "c2" }.state))
}
@Test
fun severalCallsRunTogetherInOrderWithStableStartStamps() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "build"))))
clock = 2_000L
store.event(toolFrame("s", "m1", tool("c2", "grep", ChatProtocol.TOOL_RUNNING, input("pattern" to "TODO"))))
val thread = store.value.thread("s")!!
// Both render, in transcript order, so the list does not flicker between them.
assertEquals(listOf("c1", "c2"), thread.runningTools.map { it.id })
// Each keeps the clock it first turned running on...
assertEquals(mapOf("c1" to 1_000L, "c2" to 2_000L), thread.toolStartedAt)
// ...so a later frame for the first call does not restart its timer.
clock = 3_000L
store.event(
toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "build && test"))),
)
val updated = store.value.thread("s")!!
assertEquals(1_000L, updated.toolStartedAt["c1"])
clock = 11_000L
assertEquals(10_000L, updated.toolElapsedMillis(updated.runningTools.single { it.id == "c1" }, clock))
}
@Test
fun aCallWithoutADescriptionStillRendersNameStatusAndTime() {
var clock = 5_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
// No input at all: the part carries no description to show.
store.event(toolFrame("s", "m1", tool("c1", "task", ChatProtocol.TOOL_RUNNING)))
val call = store.value.thread("s")!!.runningTools.single()
assertNull(toolDetail(call))
assertEquals("task", toolLabel(call))
assertTrue(ChatProtocol.toolRunning(call.state))
clock = 9_000L
assertEquals(4_000L, store.value.thread("s")!!.toolElapsedMillis(call, clock))
}
@Test
fun toolDetailPrefersDescriptionThenCommandAndIgnoresWhatItCannotRead() {
// A description wins over a command when both are present.
assertEquals(
"Summarise the diff",
toolDetail(
tool(
"c1", "task", ChatProtocol.TOOL_RUNNING,
input("description" to "Summarise the diff", "command" to "git diff"),
),
),
)
// A shell's command is next.
assertEquals(
"ls -la",
toolDetail(tool("c2", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls -la"))),
)
// A file tool's path is shown when nothing more descriptive exists.
assertEquals(
"/tmp/a.txt",
toolDetail(tool("c3", "read", ChatProtocol.TOOL_RUNNING, input("filePath" to "/tmp/a.txt"))),
)
// A multi-line command collapses to a single line.
assertEquals(
"run this",
toolDetail(tool("c4", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "run\n this"))),
)
// A partial (not-yet-object) input, a missing state, and an input with no
// known key all show nothing rather than something invented.
assertNull(
toolDetail(
ChatPart(
type = ChatProtocol.PART_TOOL,
id = "c5",
name = "shell",
state = ChatToolState(status = ChatProtocol.TOOL_STREAMING, input = JsonPrimitive("{\"command\"")),
),
),
)
assertNull(toolDetail(ChatPart(type = ChatProtocol.PART_TOOL, id = "c6", name = "shell")))
assertNull(toolDetail(tool("c7", "shell", ChatProtocol.TOOL_RUNNING, input("foo" to "bar"))))
}
@Test
fun aCallRunningTooLongIsMarked() {
assertFalse(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1))
assertTrue(toolLongRunning(TOOL_LONG_RUNNING_MILLIS))
}
@Test
fun theSessionRowReportsWhatIsRunning() {
assertEquals("Running shell", sessionWorkLabel(busy = false, threadWith(tool("c1", "shell", ChatProtocol.TOOL_RUNNING))))
assertEquals(
"Running 2 tools",
sessionWorkLabel(
busy = false,
threadWith(
tool("c1", "shell", ChatProtocol.TOOL_RUNNING),
tool("c2", "grep", ChatProtocol.TOOL_RUNNING),
),
),
)
// A turn running with no tool yet reads as plain Running, never idle, so a
// text stream and a parked tool call stay distinguishable.
assertEquals("Running", sessionWorkLabel(busy = false, ChatThread(sessionId = "s", running = true)))
assertEquals("Running", sessionWorkLabel(busy = true, ChatThread(sessionId = "s", running = true)))
// Nothing running falls back to the ordinary busy/idle label.
assertEquals("Busy · read-only", sessionWorkLabel(busy = true, thread = null))
assertEquals("Idle", sessionWorkLabel(busy = false, thread = null))
assertEquals("Idle", sessionWorkLabel(busy = false, ChatThread(sessionId = "s")))
}
}
@@ -11,14 +11,18 @@ class RunStatusTest {
assertEquals(RunState.Queued, runStateOf("queued"))
assertEquals(RunState.Waiting, runStateOf("waiting"))
assertEquals(RunState.Active, runStateOf("active"))
assertEquals(RunState.Waiting, runStateOf("waiting"))
assertEquals(RunState.Succeeded, runStateOf("succeeded"))
// Step/outcome words map onto the same states.
// Step/outcome words map onto the same states, so one word is one colour.
assertEquals(RunState.Succeeded, runStateOf("completed"))
assertEquals(RunState.Succeeded, runStateOf("success"))
assertEquals(RunState.Succeeded, runStateOf("done"))
assertEquals(RunState.Failed, runStateOf("failed"))
assertEquals(RunState.Failed, runStateOf("error"))
assertEquals(RunState.Canceled, runStateOf("canceled"))
assertEquals(RunState.Interrupted, runStateOf("interrupted"))
assertEquals(RunState.Blocked, runStateOf("blocked"))
assertEquals(RunState.Skipped, runStateOf("skipped"))
}
@Test
@@ -5,6 +5,9 @@ import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -15,9 +18,9 @@ class GraphPaletteTest {
/** The dark Pipelines surface the outcome label chip is drawn on. */
private val darkSurface = Color(0xFF0E1513)
/** The two terminal roles as the dark scheme supplies them. */
private val successRole = Color(0xFFF2C879)
private val errorRole = Color(0xFFFFB4AB)
/** The two terminal roles are the shared run-status colours. */
private val successRole = runStateColor(RunState.Succeeded)
private val errorRole = runStateColor(RunState.Failed)
private fun colors() = GraphColors(
success = successRole,
@@ -43,11 +46,39 @@ class GraphPaletteTest {
"exhausted", "retry", "approved", "fast", "missing", "done",
)
/** The outcomes with no run-status meaning that the graph palette owns. */
private val graphOnlyOutcomes = listOf(
"rejected", "exhausted", "retry", "approved", "fast", "missing",
)
/**
* A word that is a run state resolves to exactly the colour the runs list
* draws for it: the graph factory and [outcomeColor] share one source.
*/
@Test
fun everyRealisticOutcomeGetsADistinctColour() {
fun statusOutcomesTakeTheSharedRunStatusColour() {
val colors = colors()
val mapped = realisticOutcomes.map { outcomeColor(it, colors) }
assertEquals(realisticOutcomes.size, mapped.toSet().size)
listOf(
"success", "completed", "done", "error", "failed",
"blocked", "skipped", "waiting", "running", "queued",
"canceled", "interrupted",
).forEach { word ->
assertEquals(
"outcomeColor($word) must equal the runs-list colour",
runStateColor(runStateOf(word)),
outcomeColor(word, colors),
)
}
}
/** The graph-only outcomes keep distinct curated colours, none a status colour. */
@Test
fun graphOnlyOutcomesGetDistinctColours() {
val colors = colors()
val mapped = graphOnlyOutcomes.map { outcomeColor(it, colors) }
assertEquals(graphOnlyOutcomes.size, mapped.toSet().size)
val statusColours = RunState.entries.map { runStateColor(it) }.toSet()
mapped.forEach { assertFalse("$it borrowed a run-status colour", it in statusColours) }
}
@Test
@@ -74,10 +105,8 @@ class GraphPaletteTest {
assertEquals(unknown, outcomeColor("something-brand-new", colors))
// A blank name is just another unknown: stable and non-throwing.
assertEquals(outcomeColor("", colors), outcomeColor("", colors))
// The fallback comes from the reserved region, not a known outcome slot.
val knownIndices = realisticOutcomes
.filter { it != "success" && it != "error" }
.map { GraphPalette.outcomeColorIndex(it) }
// The fallback comes from the reserved region, not a known graph-only slot.
val knownIndices = graphOnlyOutcomes.map { GraphPalette.outcomeColorIndex(it) }
assertFalse(GraphPalette.outcomeColorIndex("something-brand-new") in knownIndices)
}
@@ -0,0 +1,57 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.theme.PipelinesDarkColors
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* The one-colour contract behind the status brief: whatever draws a status or a
* stage outcome — the runs list, the timeline's step chips, the graph, the stage
* sheet — resolves a word through one owned source, so a word means one colour
* everywhere and never a second colour for the same meaning.
*/
class StatusColorConsistencyTest {
private val colors = graphColors(PipelinesDarkColors)
/**
* Every word the timeline can show that is a run state resolves, through the
* graph factory the timeline uses, to exactly the runs-list colour.
*/
@Test
fun theTimelineColourComesFromTheRunsListSource() {
listOf(
"success", "completed", "done", "error", "failed",
"blocked", "skipped", "waiting", "running", "queued",
"canceled", "cancelled", "interrupted", "active",
).forEach { word ->
assertEquals(
"timeline colour for '$word' must be the runs-list colour",
runStateColor(runStateOf(word)),
outcomeColor(word, colors),
)
}
}
/**
* Every state maps to exactly one colour: the lookup is deterministic, and no
* two states collide except the one deliberate alias (a live run and the
* server's `active` usage bucket are the same in-progress state).
*/
@Test
fun everyStateMapsToExactlyOneColour() {
RunState.entries.forEach { state ->
assertEquals(runStateColor(state), runStateColor(state))
}
val shared = RunState.entries
.groupBy { runStateColor(it) }
.filterValues { it.size > 1 }
.values
.map { it.toSet() }
.toSet()
assertEquals(setOf(setOf(RunState.Running, RunState.Active)), shared)
}
}
+65
View File
@@ -0,0 +1,65 @@
# Chat in-flight tool work
## What this item changed
`android/` only, the chat's two "working" surfaces.
- `ui/chat/ChatFormat.kt` adds `runningToolCalls` (the tool parts still
`running`, in transcript order), `toolDetail` (the command/description the
part's own input carries, from description/command/filePath/file_path/path/
pattern/query/url, one line, elided at 72 chars, `null` when absent),
`runningToolElapsedMillis` (the protocol's `time.ran`/`created` when present,
else the local per-part stamp), `runningToolStamps` (a stable start per part
across frames), `TOOL_LONG_RUNNING_MILLIS` = 60s with `toolLongRunning`, and
`sessionWorkLabel`.
- `ui/chat/ChatStore.kt`: `ChatThread.toolStartedAt` plus `runningTools` and
`toolElapsedMillis`; `history()`, the frame fold and `setRunning` maintain it.
- `ui/chat/ChatTranscript.kt`: `RunningIndicator` now also lists one line per
running call (name, detail where present, live elapsed), keyed by part id so
concurrent calls render together; a call past 60s is tinted and marked
`· long`.
- `ui/chat/ChatListPane.kt`: the session row renders
`sessionWorkLabel(session.busy, thread)`.
- `ui/chat/ChatRunningWorkTest.kt` covers it (name/detail/elapsed, clear on
completion, error state, concurrent calls, no-detail stream).
No percentage, ETA or progress bar is invented; only the reported fields (tool
name, `state.status`, `state.input`) are used.
## Shared documents this change makes stale
`android/README.md` documents the two surfaces this item changed, in the
`## Streaming replies (16 Oct 2026)` record. The note is written here rather
than edited in place; the `docs-fold` writer should update it.
- `android/README.md:4633` — the **Running indicator** bullet reads "The
transcript's indicator shows the spinner, `Working…` and the live elapsed
time (ticked once a second, never per frame, through the shared
`formatDuration`)." It should add that the indicator also lists, one line per
tool call still in flight, the call's name, the command/description the part
carries when it carries one, and that call's own live elapsed time; that a
call running 60 seconds or more is tinted and marked `· long`; that a call's
line drops out the moment it completes or errors, which is what clears the
indicator; and that no percentage, ETA or progress bar is shown. The rest of
the bullet (one-second tick, the tick loop keyed on the turn's start, the
elapsed count surviving a chat switch) is still true.
- `android/README.md:4454` — the session-list sentence "the list shows each
session's running/busy/read-only status" is now incomplete: a working session
row names what it is doing (`Running <tool>`, or `Running <n> tools` when
several run at once) instead of only `Running`, while a turn that is only
generating text still reads plain `Running`, so the two stay distinguishable;
a busy session with nothing running still reads `Busy · read-only`, and an
idle one `Idle`.
Dates, counts and capture names in those dated records are past evidence and
stay as they are; only the two behaviour statements above are now stale.
## Not stale
- No packaged OpenCode skill reference documents this app surface. The chat
references in `internal/author/skill/references/operations.md` document the
server's brokered `chat_*` protocol, which this change does not touch, and no
packaged template or `internal/author/` managed file names the app's chat
indicator or session label.
- `android/AGENTS.md` already lists `ui/chat/` and its files, so it needs no
change.
+40
View File
@@ -0,0 +1,40 @@
# docs-fold single documentation writer
## What this item changed
Per-item workflows no longer edit shared documentation themselves. The convention now
lives in `internal/author/skill/references/orchestration.md` (brief item 5, the
hard-constraint bullet, "Single documentation writer", and the "Pipeline choice"
committer bullet), the canonical committer checklist in
`internal/author/skill/references/format.md` (step 6), the bundled committer prompts in
`examples/task.md` and `examples/three-stage.md`, and the repository guideline
`AGENTS.md`.
The chosen mechanism is a **per-item note file** at `docs/notes/<slug>.md`: when a
change makes a shared document stale, the item records what changed and what should
change there, commits that note with its own change, and never edits a shared document.
The chosen **single writer** is the manual-only `docs-fold` pipeline, added as a fifth
bundled starter at `examples/docs-fold.md` and listed in `examples/catalog.go` and
`examples/README.md`. Its `fold` stage reads every note under `docs/notes/`, folds each
into the shared document it names, and deletes the consumed notes in its own commit.
## Shared documents this change makes stale
Adding the fifth starter (`docs-fold`) makes the following documents' starter counts
wrong. They were deliberately **not** edited by this item; the `docs-fold` writer should
correct them when it next folds notes.
- `README.md:191` — "To skip authoring, use **:templates**, choose one of the four
generic starters," should read "five generic starters".
- `docs/cli.md:170` — "Use `:templates` for four simple, manual-only starters: task,
review, research, and plan/implement/review." should say five starters and name
`docs-fold` (fold accumulated documentation notes, then commit locally).
- `internal/author/skill/references/operations.md:13` — "Four optional generic starters
are task, review, research and three-stage;" should read "Five optional generic
starters are task, review, research, three-stage and docs-fold;".
## Do not change
- `docs/first-version-testing.md:148` and the dated records in
`docs/installation-verification.md` describe a past fixture run at the time it ran;
they are dated evidence, not current counts, and stay as they are.
+8 -1
View File
@@ -1,6 +1,6 @@
# Simple workflow templates
Four optional, technology-neutral starters. Nothing is installed as a published
Five optional, technology-neutral starters. Nothing is installed as a published
pipeline automatically; all templates are manual-only and have at most four stages.
| Template key | Workflow | Tools |
@@ -9,6 +9,7 @@ pipeline automatically; all templates are manual-only and have at most four stag
| `review` | Read repository content and report findings | Read/glob/grep and conditional web search/fetch; no edit/shell |
| `research` | Research a topic, then write a sourced report | Web search/fetch, then none |
| `three-stage` | Plan → implement → review → commit | Planner read/glob/grep + conditional web; implementer read/glob/grep/edit/shell with no web (follows the planner's research); reviewer independent shell + conditional web; committer read/shell |
| `docs-fold` | Fold accumulated item documentation notes into the shared docs, then commit locally | Fold: read/glob/grep/edit/shell; committer: read/shell |
Every workflow that changes the repository ends in a **committer** stage that
commits locally and never pushes. The committer stages the union of the runner's
@@ -17,6 +18,12 @@ declared `changed_files` — a declared list can be incomplete — then runs the
repository's required checks before committing. `task` and `three-stage` follow this;
`review` and `research` change nothing and so do not commit.
`docs-fold` is the deliberate **single documentation writer**. A per-item workflow never
edits a shared README or topic doc: when its change makes one stale it records a note at
`docs/notes/<slug>.md`, unique per item, and commits that note with the change. Running
the manual-only `docs-fold` pipeline later folds the accumulated notes into the shared
documentation and removes them.
Model and agent stages return the line-oriented result: the first non-empty line is
the declared outcome, a `# output` section holds the JSON output map for the next
stage, and any further `# <heading>` section is retained verbatim as evidence. The
+1
View File
@@ -16,6 +16,7 @@ var starters = []protocol.Template{
{Key: "three-stage", Name: "Plan, implement, review", Description: "Plan a change, implement it, review and verify it, then commit it locally. Any language or file type."},
{Key: "review", Name: "Review a repository", Description: "One read-only stage to review repository content and report findings."},
{Key: "research", Name: "Research a topic", Description: "Research a topic on the web, then write a sourced report. Requires web search support."},
{Key: "docs-fold", Name: "Fold documentation notes", Description: "Fold the accumulated per-item documentation notes into the shared docs, then commit locally. The repository's single documentation writer; manual-only."},
}
func Catalog() []protocol.Template {
+7 -2
View File
@@ -27,11 +27,11 @@ func TestReadmeThreeStageExampleIsValid(t *testing.T) {
func TestCatalogContainsValidUnpublishedTemplates(t *testing.T) {
items := examples.Catalog()
if len(items) != 4 {
if len(items) != 5 {
t.Fatal("unexpected catalog size", len(items))
}
seen := map[string]bool{}
wantStages := map[string]int{"task": 2, "review": 1, "research": 2, "three-stage": 4}
wantStages := map[string]int{"task": 2, "review": 1, "research": 2, "three-stage": 4, "docs-fold": 2}
for _, item := range items {
if seen[item.Key] || item.Description == "" || item.Name == "" {
t.Fatal("invalid template metadata", item.Key)
@@ -104,6 +104,10 @@ var starterTools = map[string]map[string][]string{
"reviewer": {"read", "glob", "grep", "shell", "websearch", "webfetch"},
"committer": {"read", "glob", "grep", "shell"},
},
"docs-fold": {
"fold": {"read", "glob", "grep", "edit", "shell"},
"committer": {"read", "glob", "grep", "shell"},
},
}
func TestStarterRoleToolRestrictions(t *testing.T) {
@@ -182,6 +186,7 @@ func TestWorkProducingStartersEndInACommitter(t *testing.T) {
for _, tc := range []struct{ key, producer string }{
{"task", "worker"},
{"three-stage", "implementer"},
{"docs-fold", "fold"},
} {
graph := parsedCatalog(t)[tc.key]
last := graph.Stages[len(graph.Stages)-1]
+90
View File
@@ -0,0 +1,90 @@
# stage fold
```output
{ summary, changed_files, folded_notes }
```
```prompt
Fold the accumulated per-item documentation notes into the repository's shared
documentation. Read every file under `docs/notes/`; for each note, apply the change it
records to the shared document the note names - the repository's READMEs and topic docs
and the packaged skill references - then delete the consumed note. Do not edit any other
file, change behaviour, or rewrite documentation that is still true. Keep values from
their single existing sources. An empty or missing `docs/notes/` directory is a success
no-op: make no change, commit nothing, and say so. Limit inspection to the notes
directory and the documents they name; never scan filesystem or mount roots, and use
commands supported by the actual execution environment. Save any artifacts you produce
into the artifacts directory named in the runtime context. Report the notes read, the
documents changed and the notes deleted in an `# evidence` section, with the exact
commands and observed results. Return the line-oriented result: the first non-empty line
is the declared outcome, a `# output` section holds one JSON object with the output
fields named above, and any further `# <heading>` section is retained verbatim as
evidence. Return blocked if the notes directory cannot be read.
```
```tools
read
glob
grep
edit
shell
```
```configs
provider=opencode-go
model=deepseek-v4.1-flash
retries=2
timeout=1h
```
```edges
success -> committer
blocked -> #failure
error -> #failure
```
# stage committer
```output
{ committed, commit, changed_files, pre_commit_checks }
```
```prompt
Commit this run's change locally. Never push, tag, deploy or rewrite history. Select
the run's changed paths from input.server_changed_files (the runner's captured
evidence) and the fold stage's declared changed_files, and stage their union, including
the notes the fold stage deleted (stage the removal, not only surviving paths). Inspect
the staged diff before committing; never commit unrelated work, secrets or generated
artifacts. When nothing is staged - for example an empty notes directory - do not create
an empty commit; return success with a clear note. Otherwise commit with a concise
message naming this run's change and report the commit hash. If a required check fails,
do not commit; return blocked with the failing output. Return the line-oriented result:
the first non-empty line is the declared outcome, a `# output` section holds one JSON
object with the output fields named above, and any further `# <heading>` section is
retained verbatim as evidence. Never claim an unexecuted check passed or fabricate a
commit.
```
```memory
{"changed_files":"fold.changed_files","server_changed_files":"input.server_changed_files"}
```
```tools
read
glob
grep
shell
```
```configs
provider=opencode-go
model=deepseek-v4.1-flash
retries=2
timeout=1h
```
```edges
success -> #success
blocked -> #failure
error -> #failure
```
+6 -1
View File
@@ -71,7 +71,12 @@ Commit this run's change locally. Never push, tag, deploy or rewrite history.
Select the run's changed paths from input.server_changed_files (the runner's
captured evidence) and the worker's declared changed_files, and stage their union
of paths that still exist, keeping any exclusions. Inspect the staged diff before
committing; never commit unrelated work, secrets or generated artifacts. Pre-commit
committing; never commit unrelated work, secrets or generated artifacts. Follow the
documentation-note step of the committer checklist in `references/format.md`: when the
change makes a shared document stale, stage the item's own documentation note
(`docs/notes/<slug>.md`) with the change, and never edit a shared document (a README,
topic docs or the packaged skill references) here; a single documentation writer folds
notes later. Pre-commit
checklist: confirm the staged paths are this run's change; run the repository's
required checks and record the exact commands and observed results in an
`# evidence` section; do not commit if a required check fails, return blocked
+5 -1
View File
@@ -179,7 +179,11 @@ Select the run's changed paths from input.server_changed_files (the runner's
captured evidence) and the implementer's declared changed_files, and stage their
union of paths that still exist, keeping any exclusions. Inspect the staged diff
before committing; never commit unrelated work, secrets or generated artifacts.
Pre-commit checklist: confirm the staged paths are this run's change; run the
Follow the documentation-note step of the committer checklist in
`references/format.md`: when the change makes a shared document stale, stage the item's
own documentation note (`docs/notes/<slug>.md`) with the change, and never edit a shared
document (a README, topic docs or the packaged skill references) here; a single
documentation writer folds notes later. Pre-commit checklist: confirm the staged paths are this run's change; run the
repository's required checks and record the exact commands and observed results in
a `# evidence` section; do not commit if a required check fails, return
blocked with the failing output instead. If nothing is staged, do not create an
@@ -228,6 +228,15 @@ State this pre-commit checklist in the prompt:
note.
5. Commit with a concise message naming the run's change and report the commit hash;
never push, tag, rebase or amend.
6. Ensure the item's per-item documentation note (`docs/notes/<slug>.md`, written when
the change makes a shared document stale) is staged with the change. Never edit a
shared document (a README or topic doc, or a packaged skill reference) here: a single
documentation writer folds notes later (`references/orchestration.md`). An item that
staled no shared document has no note and needs no step 6.
This list is the canonical checklist. The bundled starters `task`, `three-stage` and
`docs-fold` each repeat it in their committer prompt because a template is embedded and
published on its own; keep those copies in sync with this list.
Merging is the operator's or a lane's job, not the committer's: it commits locally
and stops (`references/orchestration.md`, `references/lanes.md`). The server does
@@ -55,9 +55,11 @@ Every brief has:
output it must report, plus the screenshots the reviewer must read. Say plainly:
"report the exact commands and their observed results. Do not claim a check you
did not run."
5. **Where it belongs** — the packaged templates, the repository's guidelines (README
and topic docs) and the packaged skill references the change is expected to touch,
so the committer can check and update them before it commits.
5. **Documentation note** — where the change makes shared documentation stale, the item
records that in its own per-item note `docs/notes/<slug>.md`: what it changed and
which shared document (a README or topic doc, or a packaged skill reference) is now
stale and what should change there. The item writes only its note; it must not edit a
shared document. See "Single documentation writer" below.
6. **The hard constraints block** (below).
7. **Publishing rules** (`references/delivery.md`).
@@ -81,7 +83,8 @@ dependencies; do not restart, rebuild or reconfigure the Pipelines or OpenCode
server, the installer, the ntfy service or any other service - runs and lanes are
active; never install on the operator's physical device; keep geometry and values
from their single existing sources rather than new literals; commit locally only,
never push; <the item's publishing rules>.
never push; record a documentation note in `docs/notes/<slug>.md` rather than editing
a shared document; <the item's publishing rules>.
```
Requirements must be concrete and checkable. Name files, functions, commands, and
@@ -106,12 +109,36 @@ Adapt the scope and publishing lines per item; keep the rest.
- **Keep values from single sources** — geometry, tokens, sizes and constants come
from the source that already owns them, not from new literals.
- **Commit locally only, never push** — the committer stage commits, no other stage.
- **Reflect the change where it belongs** — before committing, the committer checks
that the change is reflected in the packaged templates, the repository's guidelines
(README and topic docs) and the packaged skill references, updates anything stale,
and states in the commit body what it checked or that nothing needed updating.
- **Record stale documentation; do not rewrite it** — before committing, the committer
ensures the item's `docs/notes/<slug>.md` note, when the change makes a shared document
stale, is staged with the change, and states in the commit body what it checked. The
committer never edits a shared document (a README or topic doc, or a packaged skill
reference) itself; the single documentation writer folds notes later.
- **Publish rules** — WIP artefact naming and LAN URLs per `references/delivery.md`.
## Single documentation writer
Shared documentation — the repository's READMEs and topic docs (for this repository
`android/README.md` and `docs/cli.md`) and the packaged skill references in
`internal/author/skill/references/` — has exactly one writer, never an item. Each item
that makes one of these stale leaves a note at `docs/notes/<slug>.md` (item 5 above).
The note's filename is unique per item, so two items never write the same file and
never conflict on prose.
The writer is the manual-only `docs-fold` pipeline, bundled as the starter
`examples/docs-fold.md`. Its `fold` stage reads every note under `docs/notes/`, folds
each into the shared document it names, and deletes the consumed notes in its own
commit; an empty `docs/notes/` is a success no-op with no empty commit. It is never
scheduled and is never part of a per-item workflow.
The operator triggers it deliberately:
```sh
pipelines new "Docs fold" --template docs-fold --no-open
pipelines submit <draft.md>
pipelines run "Docs fold"
```
## Pipeline choice
- Use a pipeline that keeps **implementer + reviewer + ui_reviewer + committer** for
@@ -123,10 +150,11 @@ Adapt the scope and publishing lines per item; keep the rest.
`skipped` with a reason when the change has no rendered surface. Never accept a UI
change approved without the images.
- The committer is the only stage that commits, and it stages only the run's changed
files. Before committing it checks that the change is reflected in the packaged
templates, the repository's guidelines (README and topic docs) and the packaged
skill references, updates anything stale, and states in the commit body what it
checked or that nothing needed updating. It must also select `input.server_changed_files`
files. Before committing it ensures the item's `docs/notes/<slug>.md` note, when the
change makes a shared document stale, is staged with the change, and states in the
commit body what it checked; it never edits a shared document (a README or topic doc,
or a packaged skill reference) itself, because a single documentation writer folds
notes later. It must also select `input.server_changed_files`
(the runner's captured evidence, `references/control.md`) alongside the implementer's
declared `changed_files` and stage their union: an implementer's declared list can be
incomplete, and a captured path it omitted is still this run's change. Its prompt carries
+2 -1
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"git.a-wan.net/alan/pipelines/examples"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/coder/websocket"
@@ -44,7 +45,7 @@ func TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting(t *testing.T)
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Templates || len(response.Templates) != 4 {
if response.Type != protocol.Templates || len(response.Templates) != len(examples.Catalog()) {
t.Fatal("missing catalog", response.Type, len(response.Templates))
}
items, err := store.List(ctx)
+2 -2
View File
@@ -78,7 +78,7 @@ def main():
assert pong["build"] == version, "Client/server build mismatch"
assert not rpc("list").get("pipelines"), "Fresh database must be empty"
assert not rpc("runs").get("runs"), "Fresh database must have no runs"
assert len(rpc("templates")["templates"]) == 4
assert len(rpc("templates")["templates"]) == 5
draft = rpc("new", "First test", "Review the repository", "--template", "review", "--no-open", "--yes")
assert not rpc("list").get("pipelines"), "Draft creation must not publish"
rpc("validate", draft["path"])
@@ -100,7 +100,7 @@ def main():
assert not rpc("runs").get("runs"), "Smoke check must not execute a workflow"
finally:
stop(process)
print("PASS developer lifecycle fixture: isolated source binaries/skill, offline version, empty DB, four templates, draft/validate/publish, ZIP identical import, restart persistence. Not an installation option; no inference or notifications.")
print("PASS developer lifecycle fixture: isolated source binaries/skill, offline version, empty DB, five templates, draft/validate/publish, ZIP identical import, restart persistence. Not an installation option; no inference or notifications.")
if __name__ == "__main__":