run attention: publish to ntfy and surface what needs the operator
Nothing told the operator that a run was waiting for a person or had failed; they found out by going looking. A run that needs attention now reaches the ntfy they already run, and the app answers "what needs me now" in one live, ordered surface. Server (smallest change, reusing the existing publisher): - internal/server/notify.go adds notifyRun, called from finishRunState (failed) and when a run parks on a human (runner.go runLoop). It publishes to the same already-configured `system` destination through the unchanged stage.PublishNtfy, so there is no second publisher, topic or service and the token handling is the stage's own. runAttentionEvent maps only waiting and failed; queued, running, succeeded, canceled and interrupted publish nothing. - No storms: runner.attentionSent records sequence:event per run before publishing, so a run that stays waiting is never republished on a re-request or restart, and a stage notify policy that already covers the same event marks it first so the run-level default is suppressed. The set is dropped when the run is terminal. A delivery failure is logged, never fails the run, and is not retried. - The payload names the run and pipeline and carries a click action pipelines://run/<id> (validated: absolute URL, no userinfo, no fragment, no credentials). PublishNtfy gained the optional click parameter; existing callers pass "". App: - AndroidManifest/MainActivity declare the pipelines://run/<id> deep link (singleTop); runIdFromDeepLink parses it and PipelinesApp opens that run once, clearing the link. It opens a run; it starts nothing. - ui/Attention.kt is the pure model (status -> Decision/Failed/Finished or nothing, ordered by kind then newest-first) and ui/components/AttentionSurface.kt is the floating indicator plus bottom sheet. It is derived from the same run events the server already pushes, so an entry appears with no refresh and clears when resolved; a finished run clears once looked at, and any entry can be dismissed, persisted in SettingsRepository. The existing destinations, pill and bottom strip are untouched and no competing navigation surface is added. Checked before committing: - Packaged authoring skill references: internal/author/skill/references/ notifications.md documents the automatic run-attention notifications and the app surface. The only packaged "template" carrying notify is that reference; no pipeline definition template exists to update and install.go's managed file list is unchanged (notifications.md already existed). - Repository guidelines: docs/ntfy.md gains an "Automatic run-attention notifications" section and no longer claims "No block means no notifications"; the top-level README phone-notifications note now says a waiting/failed run notifies automatically; android/README.md gains the dated feature section and supersedes the previous section's note that the attention surface was absent. - docker.md, install docs and the CLI/TUI docs describe mechanisms this change does not alter; left as they are. Tests: go test ./internal/server/... ./internal/stage/... ./internal/author/... all ok; notify_test.go covers the event mapping and the real HTTP delivery (destination, topic, click, no duplicate). Android :app:testDebugUnitTest -> BUILD SUCCESSFUL, 58 suites / 531 tests / 0 failures (new AttentionTest, 13 cases, covering ordering, appearing from a push, clearing on resolution, dismissal, the empty case, persistence and the deep link). Device screenshots and the phone's own notification are visual review's per the brief's device policy. Scope: android/ plus the smallest server change; no new dependency, no run started from the app, no installer or Docker change.
This commit is contained in:
@@ -226,9 +226,10 @@ pipelines run "your pipeline name" "Describe the task"
|
||||
|
||||
Open **:status** for the server and ntfy connection details. In the ntfy phone
|
||||
app, add the displayed ntfy server, sign in as **phone-reader** with the password
|
||||
you set during installation, and subscribe to the displayed topic. Stages must
|
||||
include a `notify` block to send notifications; see [ntfy setup](docs/ntfy.md).
|
||||
Installation checks publishing, not reception on your phone.
|
||||
you set during installation, and subscribe to the displayed topic. A run that
|
||||
waits for a decision or fails notifies automatically; to notify on a stage's own
|
||||
result, add a `notify` block. See [ntfy setup](docs/ntfy.md). Installation checks
|
||||
publishing, not reception on your phone.
|
||||
|
||||
For Tailscale, both devices must be connected; use
|
||||
`http://<server-Tailscale-IP>:8090`. Binding to `0.0.0.0` does not bypass firewalls:
|
||||
|
||||
@@ -5944,3 +5944,69 @@ surface" named in the brief is not present in this tree, so the decision is
|
||||
reachable from the run detail and its stage and the shared component is ready for
|
||||
it. No packaged skill reference was touched: the decide protocol is unchanged and
|
||||
already documented, and this is an app-UI change.
|
||||
|
||||
## Run attention surface and phone notifications (17 Oct 2026)
|
||||
|
||||
> Supersedes the note at the end of the previous section: the run-attention
|
||||
> surface the brief named is now present in this tree. The server publishes the
|
||||
> notification; the app shows the same information in one live surface.
|
||||
|
||||
A run that needs a person — waiting for a human decision, or failed — now reaches
|
||||
the operator through the ntfy they already run, and the app answers "what needs me
|
||||
now" in one ordered list. The server change is the smallest that reuses the
|
||||
existing delivery machinery; there is no second publisher, topic or service.
|
||||
|
||||
- **One run-level notification, reusing the stage's publisher.** `internal/server/
|
||||
notify.go` adds `notifyRun`, called from `finishRunState` (failed) and when a run
|
||||
parks on a human (`runner.go` `runLoop`). It publishes to the same `system`
|
||||
destination through the unchanged `stage.PublishNtfy`, with the operator's
|
||||
configured token handling, so nothing is duplicated. `runAttentionEvent` maps
|
||||
only `waiting` and `failed`; queued/running/succeeded/canceled/interrupted
|
||||
produce `""` and publish nothing.
|
||||
- **No storms.** `runner.attentionSent` (guarded by `attentionMu`) records
|
||||
`sequence:event` per run before publishing, so a run that stays waiting is never
|
||||
republished on a re-request or restart, and a stage `notify` policy that already
|
||||
covers the same event (`on=waiting`, or a failure hook) marks it first so the
|
||||
run-level default is suppressed. The set is dropped when the run is terminal
|
||||
(`forgetAttention`). A delivery failure is logged, never fails the run, and is
|
||||
not retried.
|
||||
- **The payload opens the run.** It names the run id and pipeline, and carries a
|
||||
`click` action `pipelines://run/<id>` (validated in `validNtfyClick` — absolute
|
||||
URL, no userinfo, no fragment, no credentials). `AndroidManifest.xml` declares
|
||||
the `pipelines`/`run` deep link on `MainActivity` (`launchMode=singleTop`);
|
||||
`runIdFromDeepLink` parses it and `PipelinesApp` opens that run once, clearing
|
||||
the link so a rotation re-opens nothing. It opens a run; it starts nothing.
|
||||
- **One attention surface.** `ui/Attention.kt` is the pure model: a run status maps
|
||||
to `Decision`/`Failed`/`Finished` (or nothing), and `attentionEntries` orders by
|
||||
kind then newest-first. `ui/components/AttentionSurface.kt` renders a floating
|
||||
indicator in the same bottom container as the destination pill — visible from
|
||||
every destination and window width — that opens a bottom sheet listing the run,
|
||||
its pipeline and what it needs, with a per-row dismiss. The indicator draws
|
||||
nothing when the list is empty. No competing navigation surface is added.
|
||||
- **Live and self-clearing.** The list is derived from the same `RuntimeState`
|
||||
pushes the runs list folds, so an entry appears with no refresh and clears when
|
||||
the run is resolved (the decision answered, the failure retried). A finished run
|
||||
clears once the list is opened; any entry can be deliberately dismissed;
|
||||
dismissals and looked-at finishes persist in `SettingsRepository` as one
|
||||
serializable preference. Opening a non-decision entry deals with it.
|
||||
|
||||
Tests: `internal/server/notify_test.go` covers the event mapping (waiting, failed,
|
||||
nothing else) and the real HTTP delivery (destination, topic, click, no
|
||||
duplicate); `AttentionTest` (13 cases) covers the app's mapping, ordering,
|
||||
appearing from a pushed event, clearing on resolution, dismissal, the empty case,
|
||||
persistence and the deep-link parser.
|
||||
|
||||
Evidence (this pass, macOS, JDK 17 `/opt/homebrew/opt/openjdk@17`, cached Gradle
|
||||
8.11.1, `ANDROID_HOME=$HOME/Library/Android/sdk`):
|
||||
|
||||
- `go build ./...` → success; `go test ./internal/server/... ./internal/stage/...
|
||||
./internal/author/...` → `ok` for all three packages.
|
||||
- `gradle :app:testDebugUnitTest --offline --no-daemon --console=plain` →
|
||||
`BUILD SUCCESSFUL`; the JUnit XMLs total **58 suites / 531 tests / 0 failures /
|
||||
0 errors / 0 skipped** (up from 57 suites / 518 tests: the new `AttentionTest`).
|
||||
|
||||
Not verified in this pass: the on-device indicator/list/finished/empty screenshots
|
||||
and the phone's own notification — the brief keeps ordinary code review to the
|
||||
build and the unit tests, and visual review owns the operator's Pixel 9 Pro XL.
|
||||
The concrete payload delivered to the local ntfy service was reproduced by the
|
||||
code review with a live curl subscriber; the device captures are visual review's.
|
||||
|
||||
@@ -30,12 +30,26 @@
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:launchMode="singleTop"
|
||||
android:theme="@style/Theme.Pipelines"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!--
|
||||
The notification click action opens the run it names. The server
|
||||
publishes `pipelines://run/<id>` as the ntfy Click URL, so a tap on
|
||||
the phone's own notification resolves here rather than to a browser.
|
||||
This is the app's one deep link and it only opens a run; it starts
|
||||
nothing.
|
||||
-->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="pipelines" android:host="run" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!--
|
||||
|
||||
@@ -1,24 +1,46 @@
|
||||
package net.awan.pipelines
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import net.awan.pipelines.ui.AppViewModel
|
||||
import net.awan.pipelines.ui.PipelinesApp
|
||||
import net.awan.pipelines.ui.runIdFromDeepLink
|
||||
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.
|
||||
private var deepLinkedRunId by mutableStateOf<Long?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
deepLinkedRunId = runIdFromDeepLink(intent?.data?.toString())
|
||||
enableEdgeToEdge()
|
||||
val app = application as PipelinesApplication
|
||||
setContent {
|
||||
PipelinesTheme {
|
||||
val vm: AppViewModel = viewModel(factory = AppViewModel.factory(app))
|
||||
PipelinesApp(vm)
|
||||
PipelinesApp(
|
||||
vm = vm,
|
||||
initialRunId = deepLinkedRunId,
|
||||
onInitialRunHandled = { deepLinkedRunId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A notification tap while the app is already open opens its run in place. */
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
deepLinkedRunId = runIdFromDeepLink(intent.data?.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,12 @@ class SettingsRepository(context: Context) {
|
||||
private val _chatSeen = MutableStateFlow(prefs.getString(KEY_CHAT_SEEN, "").orEmpty())
|
||||
val chatSeen: StateFlow<String> = _chatSeen.asStateFlow()
|
||||
|
||||
// What the operator has dealt with on the attention surface (dismissals and
|
||||
// finished runs already looked at), stored as one opaque JSON string the same
|
||||
// way the chat state above is: the attention layer owns the shape.
|
||||
private val _attention = MutableStateFlow(prefs.getString(KEY_ATTENTION, "").orEmpty())
|
||||
val attention: StateFlow<String> = _attention.asStateFlow()
|
||||
|
||||
fun setServerUrl(value: String) {
|
||||
val trimmed = value.trim()
|
||||
_serverUrl.value = trimmed
|
||||
@@ -129,6 +135,12 @@ class SettingsRepository(context: Context) {
|
||||
prefs.edit().putString(KEY_CHAT_SEEN, value).apply()
|
||||
}
|
||||
|
||||
fun setAttention(value: String) {
|
||||
if (value == _attention.value) return
|
||||
_attention.value = value
|
||||
prefs.edit().putString(KEY_ATTENTION, value).apply()
|
||||
}
|
||||
|
||||
/** True only when the user has explicitly supplied both required values. */
|
||||
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
|
||||
|
||||
@@ -145,5 +157,6 @@ class SettingsRepository(context: Context) {
|
||||
const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name"
|
||||
const val KEY_CHAT_OVERRIDES = "chat_overrides"
|
||||
const val KEY_CHAT_SEEN = "chat_seen"
|
||||
const val KEY_ATTENTION = "attention"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
@@ -16,6 +17,7 @@ import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.filterIsInstance
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import net.awan.pipelines.PipelinesApplication
|
||||
@@ -123,6 +125,16 @@ class AppViewModel(
|
||||
/** The omni-search panel state: query, last results, loading and any error. */
|
||||
val search: StateFlow<SearchUiState> = _search.asStateFlow()
|
||||
|
||||
// What the operator has already dealt with on the attention surface. The
|
||||
// visible list is derived from it and the run state below, so an entry
|
||||
// appears and clears from the same pushes that update the runs list.
|
||||
private val _attentionState = MutableStateFlow(AttentionState.decode(settings.attention.value))
|
||||
|
||||
/** The ordered attention list: what needs the operator now, most important first. */
|
||||
val attention: StateFlow<List<AttentionEntry>> = combine(_runs, _attentionState) { runs, state ->
|
||||
attentionEntries(runs.data?.runs.orEmpty(), state)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
|
||||
// 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()
|
||||
@@ -182,6 +194,7 @@ class AppViewModel(
|
||||
observeConnection()
|
||||
observeChatOverrides()
|
||||
observeChatSeen()
|
||||
observeAttention()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -495,6 +508,37 @@ class AppViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists what the operator has dealt with on the attention surface as it
|
||||
* changes, so a dismissal or a finished run already seen survives a restart.
|
||||
* Only a real change is written; the settings repository ignores a repeat, so
|
||||
* the initial emission is a no-op.
|
||||
*/
|
||||
private fun observeAttention() {
|
||||
viewModelScope.launch {
|
||||
_attentionState.collect {
|
||||
settings.setAttention(it.encode())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deliberately dismisses one attention entry for good, so a still-waiting or
|
||||
* still-failed run the operator has chosen to ignore stops asking.
|
||||
*/
|
||||
fun dismissAttention(runId: Long, kind: AttentionKind) {
|
||||
_attentionState.value = _attentionState.value.dismissed(attentionKey(runId, kind))
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
fun sawFinishedAttention(ids: Collection<Long>) {
|
||||
_attentionState.value = _attentionState.value.lookedAtFinished(ids.toSet())
|
||||
}
|
||||
|
||||
fun updateServerUrlDraft(value: String) {
|
||||
_serverUrlDraft.value = value
|
||||
_urlError.value = null
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package net.awan.pipelines.ui
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import net.awan.pipelines.data.protocol.PipelinesJson
|
||||
import net.awan.pipelines.data.protocol.RunSummary
|
||||
|
||||
/**
|
||||
* The one place the app decides what needs the operator and how much it matters.
|
||||
*
|
||||
* A run's server status maps to at most one [AttentionKind]: a run parked on a
|
||||
* person ([AttentionKind.Decision]) is the most important, 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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
data class AttentionEntry(
|
||||
val runId: Long,
|
||||
val pipeline: String,
|
||||
val label: String,
|
||||
val kind: AttentionKind,
|
||||
val detail: String,
|
||||
/**
|
||||
* The run's own recency (its finish time, else its creation time), used only
|
||||
* to order equal kinds newest-first so the list never reshuffles on a read.
|
||||
*/
|
||||
val recency: String = "",
|
||||
) {
|
||||
/** The stable identity a dismissal is keyed by, so it survives the fold. */
|
||||
val key: String get() = attentionKey(runId, kind)
|
||||
}
|
||||
|
||||
/** The identity of one run+kind entry; the unit an explicit dismissal removes. */
|
||||
internal fun attentionKey(runId: Long, kind: AttentionKind): String = "$runId:${kind.name}"
|
||||
|
||||
/**
|
||||
* The attention kind a run status maps to, or null when the run needs nobody. It
|
||||
* reads the server's own words only, so an unknown status can never invent an
|
||||
* entry.
|
||||
*/
|
||||
internal fun attentionKindOf(status: String): AttentionKind? =
|
||||
when (status.trim().lowercase()) {
|
||||
"waiting" -> AttentionKind.Decision
|
||||
"failed" -> AttentionKind.Failed
|
||||
"succeeded" -> AttentionKind.Finished
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* What one entry asks of the operator, in the operator's words. A failed run
|
||||
* shows the server's own diagnostic when it recorded one so the line is
|
||||
* actionable rather than a bare "failed".
|
||||
*/
|
||||
internal fun attentionDetail(kind: AttentionKind, run: RunSummary): String = when (kind) {
|
||||
AttentionKind.Decision -> "Waiting for your decision"
|
||||
AttentionKind.Failed -> run.diagnostic.trim().ifBlank { "Run failed" }
|
||||
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.
|
||||
*/
|
||||
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,
|
||||
label = run.title?.trim()?.takeIf { it.isNotEmpty() } ?: run.name,
|
||||
kind = kind,
|
||||
detail = attentionDetail(kind, run),
|
||||
recency = run.finishedAt.ifBlank { run.createdAt },
|
||||
)
|
||||
}.sortedWith(
|
||||
compareBy<AttentionEntry> { it.kind.rank }
|
||||
.thenByDescending { it.recency }
|
||||
.thenByDescending { it.runId },
|
||||
)
|
||||
|
||||
/**
|
||||
* What the operator has already dealt with on the attention surface, kept as one
|
||||
* serializable preference so it survives a restart exactly like the app's other
|
||||
* stored state:
|
||||
*
|
||||
* - [dismissed] is the run+kind keys the operator deliberately dismissed, so a
|
||||
* still-waiting 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.
|
||||
*/
|
||||
@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)
|
||||
|
||||
companion object {
|
||||
/** Decodes a stored value; anything unreadable falls back to nothing dealt with. */
|
||||
fun decode(stored: String): AttentionState =
|
||||
if (stored.isBlank()) {
|
||||
AttentionState()
|
||||
} else {
|
||||
runCatching { PipelinesJson.decodeFromString(serializer(), stored) }
|
||||
.getOrDefault(AttentionState())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The deep-link scheme the run notification's click action opens. */
|
||||
internal const val RUN_DEEP_LINK_PREFIX = "pipelines://run/"/**
|
||||
* The one-line headline the indicator shows: the single most important thing when
|
||||
* there is one entry, else the count. Pure, so it can be asserted without a device.
|
||||
*/
|
||||
internal fun attentionHeadline(entries: List<AttentionEntry>): String = when {
|
||||
entries.isEmpty() -> ""
|
||||
entries.size == 1 -> when (entries[0].kind) {
|
||||
AttentionKind.Decision -> "A run is waiting for you"
|
||||
AttentionKind.Failed -> "A run failed"
|
||||
AttentionKind.Finished -> "A run finished"
|
||||
}
|
||||
else -> "${entries.size} runs need you"
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the run id from a `pipelines://run/<id>` deep link, or null for
|
||||
* anything else. Pure and total, so a malformed link simply opens nothing rather
|
||||
* than a guessed run.
|
||||
*/
|
||||
internal fun runIdFromDeepLink(link: String?): Long? {
|
||||
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 }
|
||||
}
|
||||
@@ -77,6 +77,8 @@ import androidx.navigation.compose.rememberNavController
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import net.awan.pipelines.data.protocol.SearchResult
|
||||
import net.awan.pipelines.data.transport.ConnectionState
|
||||
import net.awan.pipelines.ui.components.AttentionIndicator
|
||||
import net.awan.pipelines.ui.components.AttentionSheet
|
||||
import net.awan.pipelines.ui.components.ConnectionBanner
|
||||
import net.awan.pipelines.ui.components.MotionStandard
|
||||
import net.awan.pipelines.ui.components.SlidingPaneStack
|
||||
@@ -131,12 +133,19 @@ private fun backFrom(selection: PaneSelection): PaneSelection =
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun PipelinesApp(vm: AppViewModel) {
|
||||
fun PipelinesApp(
|
||||
vm: AppViewModel,
|
||||
initialRunId: Long? = null,
|
||||
onInitialRunHandled: () -> Unit = {},
|
||||
) {
|
||||
val navController = rememberNavController()
|
||||
val backStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = backStackEntry?.destination?.route
|
||||
val connectionState by vm.connectionState.collectAsStateWithLifecycle()
|
||||
val configuredUrl by vm.configuredServerUrl.collectAsStateWithLifecycle()
|
||||
// The ordered list of runs that need the operator, derived from the same
|
||||
// pushed run state the rest of the app folds, so it is live with no refresh.
|
||||
val attention by vm.attention.collectAsStateWithLifecycle()
|
||||
// Window-size driven (never a hardcoded device): the same sliding pane works at
|
||||
// every width; only the section index presentation (tab row vs rail) changes.
|
||||
val wide = isWideLayout(LocalConfiguration.current.screenWidthDp)
|
||||
@@ -154,6 +163,10 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
// run's steps are loaded; the Runs destination applies it then (see below).
|
||||
var runSearchNav by remember { mutableStateOf<SearchTarget.Run?>(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 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
|
||||
@@ -190,6 +203,41 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
dismissSearch()
|
||||
}
|
||||
|
||||
// Opening the run a notification or an attention entry names: the Runs
|
||||
// destination's saved selection points at it, then that destination is shown.
|
||||
val openRunFromAttention: (Long) -> Unit = { 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) {
|
||||
if (initialRunId != null) {
|
||||
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.
|
||||
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.
|
||||
val openAttentionEntry: (AttentionEntry) -> Unit = { entry ->
|
||||
if (entry.kind != AttentionKind.Decision) {
|
||||
vm.dismissAttention(entry.runId, entry.kind)
|
||||
}
|
||||
closeAttentionList()
|
||||
openRunFromAttention(entry.runId)
|
||||
}
|
||||
|
||||
// One list scroll position each, owned here above the NavHost so it survives
|
||||
// the destination (and list screen) being recreated when a pane is covered or
|
||||
// the runs selection changes, as well as a configuration change and process
|
||||
@@ -326,6 +374,11 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
.padding(bottom = 16.dp),
|
||||
)
|
||||
}
|
||||
AttentionIndicator(
|
||||
entries = attention,
|
||||
onClick = { attentionOpen = true },
|
||||
modifier = Modifier.padding(bottom = SPACING_S),
|
||||
)
|
||||
DestinationBar(
|
||||
destinations = destinations,
|
||||
currentRoute = currentRoute,
|
||||
@@ -341,6 +394,14 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
onSubmitSearch = { vm.searchNow() },
|
||||
)
|
||||
}
|
||||
if (attentionOpen) {
|
||||
AttentionSheet(
|
||||
entries = attention,
|
||||
onOpen = openAttentionEntry,
|
||||
onDismissEntry = { entry -> vm.dismissAttention(entry.runId, entry.kind) },
|
||||
onDismiss = closeAttentionList,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package net.awan.pipelines.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.NotificationsActive
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.ui.AttentionEntry
|
||||
import net.awan.pipelines.ui.AttentionKind
|
||||
import net.awan.pipelines.ui.attentionHeadline
|
||||
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
|
||||
import net.awan.pipelines.ui.theme.SPACING_L
|
||||
import net.awan.pipelines.ui.theme.SPACING_M
|
||||
import net.awan.pipelines.ui.theme.SPACING_S
|
||||
|
||||
/**
|
||||
* The one attention surface: an indicator that is visible from wherever the
|
||||
* operator is (it floats in the same bottom container as the destination pill,
|
||||
* so it survives every destination and every pane) and opens into an ordered
|
||||
* list. It is not a navigation destination, so it never competes with the pill.
|
||||
*
|
||||
* The indicator only appears while something genuinely needs the operator, and
|
||||
* both its headline and the list order come from the pure `ui/Attention.kt`
|
||||
* model, so what is shown matches what the fold decided.
|
||||
*/
|
||||
|
||||
/** The importance glyph and tint a kind borrows from the run-status vocabulary. */
|
||||
internal fun attentionRunState(kind: AttentionKind): RunState = when (kind) {
|
||||
AttentionKind.Decision -> RunState.Waiting
|
||||
AttentionKind.Failed -> RunState.Failed
|
||||
AttentionKind.Finished -> RunState.Succeeded
|
||||
}
|
||||
|
||||
/**
|
||||
* The floating indicator: the count and the most important item, tappable to open
|
||||
* the list. Hidden (draws nothing) when [entries] is empty, so it never becomes a
|
||||
* permanent chrome element.
|
||||
*/
|
||||
@Composable
|
||||
fun AttentionIndicator(
|
||||
entries: List<AttentionEntry>,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (entries.isEmpty()) return
|
||||
val scheme = MaterialTheme.colorScheme
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = modifier,
|
||||
shape = RoundedCornerShape(50),
|
||||
color = scheme.errorContainer,
|
||||
contentColor = scheme.onErrorContainer,
|
||||
shadowElevation = 6.dp,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = SPACING_M, vertical = SPACING_S),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.NotificationsActive,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(ICON_INLINE_DP),
|
||||
)
|
||||
Text(
|
||||
text = attentionHeadline(entries),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ordered attention list, in a bottom sheet so it opens over whatever the
|
||||
* operator is looking at and closes back to it. Rows are already ordered by the
|
||||
* pure model (decision, then failure, then finished). Tapping a row opens the run;
|
||||
* the trailing action deliberately dismisses just that entry.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AttentionSheet(
|
||||
entries: List<AttentionEntry>,
|
||||
onOpen: (AttentionEntry) -> Unit,
|
||||
onDismissEntry: (AttentionEntry) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = SPACING_L),
|
||||
verticalArrangement = Arrangement.spacedBy(SPACING_S),
|
||||
) {
|
||||
Text(
|
||||
text = "Needs you",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.padding(horizontal = SPACING_L),
|
||||
)
|
||||
if (entries.isEmpty()) {
|
||||
Text(
|
||||
text = "Nothing needs you right now.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = SPACING_L),
|
||||
)
|
||||
return@Column
|
||||
}
|
||||
entries.forEach { entry ->
|
||||
AttentionRow(
|
||||
entry = entry,
|
||||
onOpen = { onOpen(entry) },
|
||||
onDismiss = { onDismissEntry(entry) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One attention row: what the run is, its pipeline, what it needs and a dismiss. */
|
||||
@Composable
|
||||
private fun AttentionRow(
|
||||
entry: AttentionEntry,
|
||||
onOpen: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val scheme = MaterialTheme.colorScheme
|
||||
Surface(onClick = onOpen, color = Color.Transparent) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = SPACING_L, top = SPACING_S, bottom = SPACING_S),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
|
||||
) {
|
||||
RunStatusIcon(state = attentionRunState(entry.kind), contentDescription = null)
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(SPACING_S),
|
||||
) {
|
||||
Text(
|
||||
text = entry.label,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = scheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = "${entry.pipeline} · ${entry.detail}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = scheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Close,
|
||||
contentDescription = "Dismiss",
|
||||
tint = scheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package net.awan.pipelines.ui
|
||||
|
||||
import net.awan.pipelines.data.protocol.RunEventFrame
|
||||
import net.awan.pipelines.data.protocol.RunSummary
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
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.
|
||||
*/
|
||||
class AttentionTest {
|
||||
|
||||
private fun run(
|
||||
id: Long,
|
||||
status: String,
|
||||
name: String = "pipeline",
|
||||
title: String? = null,
|
||||
diagnostic: String = "",
|
||||
createdAt: String = "2026-10-17T09:00:00Z",
|
||||
finishedAt: String = "",
|
||||
) = RunSummary(
|
||||
id = id,
|
||||
pipelineId = 4,
|
||||
name = name,
|
||||
title = title,
|
||||
status = status,
|
||||
executing = status == "running",
|
||||
diagnostic = diagnostic,
|
||||
createdAt = createdAt,
|
||||
finishedAt = finishedAt,
|
||||
)
|
||||
|
||||
private fun frame(runId: Long, status: String, finishedAt: String = "") = RunEventFrame(
|
||||
runId = runId,
|
||||
workspace = "/work",
|
||||
status = status,
|
||||
finishedAt = finishedAt,
|
||||
)
|
||||
|
||||
// --- mapping ---------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun onlyWaitingFailedAndFinishedAskForAttention() {
|
||||
assertEquals(AttentionKind.Decision, attentionKindOf("waiting"))
|
||||
assertEquals(AttentionKind.Failed, attentionKindOf("failed"))
|
||||
assertEquals(AttentionKind.Finished, attentionKindOf("succeeded"))
|
||||
assertNull(attentionKindOf("queued"))
|
||||
assertNull(attentionKindOf("running"))
|
||||
assertNull(attentionKindOf("canceled"))
|
||||
assertNull(attentionKindOf("interrupted"))
|
||||
assertNull(attentionKindOf(""))
|
||||
assertNull(attentionKindOf("Warning"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun eachEntryNamesTheRunItsPipelineAndWhatItNeeds() {
|
||||
val entries = attentionEntries(
|
||||
listOf(
|
||||
run(1, "waiting", name = "release", title = "Ship 1.4"),
|
||||
run(2, "failed", name = "release", diagnostic = "provider returned 500"),
|
||||
run(3, "succeeded", name = "nightly"),
|
||||
run(4, "running"),
|
||||
),
|
||||
AttentionState(),
|
||||
)
|
||||
assertEquals(3, entries.size)
|
||||
val decision = entries[0]
|
||||
assertEquals(AttentionKind.Decision, decision.kind)
|
||||
assertEquals("Ship 1.4", decision.label)
|
||||
assertEquals("release", decision.pipeline)
|
||||
assertEquals("Waiting for your decision", decision.detail)
|
||||
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() {
|
||||
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 })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun equalKindsAreOrderedNewestFirst() {
|
||||
val entries = attentionEntries(
|
||||
listOf(
|
||||
run(1, "failed", finishedAt = "2026-10-17T09:01:00Z"),
|
||||
run(2, "failed", finishedAt = "2026-10-17T09:05:00Z"),
|
||||
run(3, "failed", finishedAt = "2026-10-17T09:03:00Z"),
|
||||
),
|
||||
AttentionState(),
|
||||
)
|
||||
assertEquals(listOf(2L, 3L, 1L), entries.map { it.runId })
|
||||
}
|
||||
|
||||
// --- live from pushed events ----------------------------------------------
|
||||
|
||||
@Test
|
||||
fun anEntryAppearsFromAPushedRunEvent() {
|
||||
val runs = listOf(run(1, "running"))
|
||||
assertTrue(attentionEntries(runs, AttentionState()).isEmpty())
|
||||
val folded = foldRunEvent(runs, frame(runId = 1, status = "waiting"))
|
||||
val entries = attentionEntries(folded.runs, AttentionState())
|
||||
assertEquals(1, entries.size)
|
||||
assertEquals(AttentionKind.Decision, entries[0].kind)
|
||||
assertEquals(1L, entries[0].runId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWaitingEntryClearsWhenTheDecisionIsAnswered() {
|
||||
val waiting = foldRunEvent(listOf(run(1, "running")), frame(runId = 1, status = "waiting")).runs
|
||||
assertEquals(1, attentionEntries(waiting, AttentionState()).size)
|
||||
// The decision resumes the run: the pushed running frame clears the entry,
|
||||
// with no dismissal and no refresh.
|
||||
val resumed = foldRunEvent(waiting, frame(runId = 1, status = "running")).runs
|
||||
assertTrue(attentionEntries(resumed, AttentionState()).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedEntryClearsWhenItSucceedsOnRetry() {
|
||||
val failed = listOf(run(1, "failed"))
|
||||
assertEquals(1, attentionEntries(failed, AttentionState()).size)
|
||||
val retried = listOf(run(1, "running"))
|
||||
assertTrue(attentionEntries(retried, AttentionState()).isEmpty())
|
||||
}
|
||||
|
||||
// --- dismissal and look ----------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aDeliberateDismissalRemovesAnEntryForGood() {
|
||||
val runs = listOf(run(1, "waiting"), run(2, "failed"))
|
||||
val state = AttentionState().dismissed(attentionKey(1, AttentionKind.Decision))
|
||||
val entries = attentionEntries(runs, state)
|
||||
assertEquals(listOf(2L), entries.map { it.runId })
|
||||
// The run is still waiting, but the operator chose to ignore it.
|
||||
assertEquals(listOf(2L), attentionEntries(runs, state).map { it.runId })
|
||||
}
|
||||
|
||||
@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())
|
||||
}
|
||||
|
||||
// --- empty case ------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun nothingThatNeedsNobodyIsListed() {
|
||||
assertTrue(attentionEntries(emptyList(), AttentionState()).isEmpty())
|
||||
assertTrue(
|
||||
attentionEntries(
|
||||
listOf(run(1, "running"), run(2, "queued"), run(3, "canceled"), run(4, "interrupted")),
|
||||
AttentionState(),
|
||||
).isEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptyListHasNoHeadlineAndASingleEntryNamesItsKind() {
|
||||
assertEquals("", attentionHeadline(emptyList()))
|
||||
val decision = attentionEntries(listOf(run(1, "waiting")), AttentionState())
|
||||
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))
|
||||
}
|
||||
|
||||
// --- persistence -----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun attentionStateSurvivesAnEncodeDecodeRoundTrip() {
|
||||
val state = AttentionState()
|
||||
.dismissed(attentionKey(7, AttentionKind.Failed))
|
||||
.lookedAtFinished(setOf(9L, 11L))
|
||||
assertEquals(state, AttentionState.decode(state.encode()))
|
||||
assertEquals(AttentionState(), AttentionState.decode(""))
|
||||
assertEquals(AttentionState(), AttentionState.decode("not json"))
|
||||
}
|
||||
|
||||
// --- notification deep link ------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun theRunDeepLinkParsesOnlyARealRunId() {
|
||||
assertEquals(42L, runIdFromDeepLink("pipelines://run/42"))
|
||||
assertEquals(7L, runIdFromDeepLink(" pipelines://run/7 "))
|
||||
assertNull(runIdFromDeepLink(null))
|
||||
assertNull(runIdFromDeepLink(""))
|
||||
assertNull(runIdFromDeepLink("pipelines://run/"))
|
||||
assertNull(runIdFromDeepLink("pipelines://run/abc"))
|
||||
assertNull(runIdFromDeepLink("pipelines://run/0"))
|
||||
assertNull(runIdFromDeepLink("pipelines://runs/1"))
|
||||
assertNull(runIdFromDeepLink("https://example.com/run/1"))
|
||||
}
|
||||
}
|
||||
+21
-2
@@ -45,8 +45,9 @@ artifacts=markdown,files
|
||||
do not choose topics or addresses. Configure `PIPELINES_NTFY_URL` (publishing
|
||||
topic URL), `PIPELINES_NTFY_PUBLIC_URL` (phone-facing server base URL), and
|
||||
`PIPELINES_NTFY_TOKEN` or `PIPELINES_NTFY_TOKEN_FILE` once on the server.
|
||||
The topic is `pipelines` in the provided setup. No block means no notifications.
|
||||
Legacy `destination` lines remain parseable for immutable-history compatibility
|
||||
The topic is `pipelines` in the provided setup. No block means no per-stage
|
||||
notifications; a run that needs a person is still announced automatically (see
|
||||
below). Legacy `destination` lines remain parseable for immutable-history compatibility
|
||||
but no longer select a connection for notification hooks. Explicit native
|
||||
`type=ntfy` stages retain their separate destination configuration.
|
||||
- `artifacts=markdown` sends the string in `output.markdown` as `digest.md`.
|
||||
@@ -68,6 +69,24 @@ artifacts=markdown,files
|
||||
notifications are not replayed during recovery. Tool access follows the stage's
|
||||
declared tools; notification settings do not grant additional tools.
|
||||
|
||||
## Automatic run-attention notifications
|
||||
|
||||
Independently of any `notify` block, the server publishes one run-level
|
||||
notification to the `system` destination when a run needs a person: when it enters
|
||||
`waiting` (a human stage asked for a decision) and when it fails. Nothing else
|
||||
notifies — queued, running, succeeded, canceled and interrupted runs are silent.
|
||||
The payload names the run and its pipeline and carries a `click` action
|
||||
`pipelines://run/<id>` that opens that run in the Android app.
|
||||
|
||||
A genuine event notifies once: a run that stays `waiting` is not republished on a
|
||||
read or restart, and a stage `notify` policy that already covers the same event
|
||||
(`on=waiting`, or a failure hook) suppresses the run-level default, so one event
|
||||
means one notification. A failed delivery is logged, never fails the run, and is
|
||||
not retried. The Android app shows the same information in one attention surface
|
||||
ordered by importance — a run waiting for a decision, then a failed run, then a
|
||||
run that finished since the operator last looked — derived from the run events the
|
||||
server already pushes, so it needs no refresh and starts nothing.
|
||||
|
||||
## Explicit delivery stage (optional)
|
||||
|
||||
The preceding stage must output three nonempty UTF-8 strings: `title`, `summary`,
|
||||
|
||||
@@ -88,3 +88,26 @@ adds retained delivery metadata on success and follows its error edge on failure
|
||||
Neither hooks nor native delivery automatically retry ambiguous publishes; a new
|
||||
run or repeated visit can send again. An upstream execution error does not reliably
|
||||
produce the required three strings, so adding this stage alone cannot cover it.
|
||||
|
||||
## Automatic run-attention notifications
|
||||
|
||||
Independently of any `notify` block, the server publishes one run-level attention
|
||||
notification to the same already-configured `system` destination when a run needs a
|
||||
person: when it enters `waiting` (a human stage asked for a decision) and when it
|
||||
fails. Nothing else notifies — a queued, running, succeeded, canceled or interrupted
|
||||
run sends nothing. You do not author these; they are the operator default, so a run
|
||||
you never wired still reaches the operator.
|
||||
|
||||
The payload names the run and its pipeline and carries a `click` action
|
||||
`pipelines://run/<id>` that opens that run in the Android app (the app declares the
|
||||
scheme). A run that stays waiting is not republished on a read or restart, and a
|
||||
stage `notify` policy that already covers the same event (`on=waiting`, or a failure
|
||||
hook) suppresses the run-level default, so one genuine event means one notification.
|
||||
A delivery failure is logged, never fails the run, and is not retried.
|
||||
|
||||
The app shows the same information in one attention surface ordered by importance:
|
||||
a run waiting for a decision, then a failed run, then a run that finished since the
|
||||
operator last looked. It is derived from the run events the server already pushes
|
||||
(no extra request), an entry clears when the run is resolved or the operator opens
|
||||
it, and it can be deliberately dismissed. It is not a new place to start a run.
|
||||
|
||||
|
||||
+125
-7
@@ -34,15 +34,14 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
// The stage's own policy already covers this attention event, so the
|
||||
// run-level default must not repeat it. Recorded before delivery so a failed
|
||||
// stage notification is reported by its own receipt, not silently duplicated.
|
||||
r.markAttentionSent(id, step.Sequence, stageAttentionEvent(event))
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
summary := fmt.Sprintf("%s · run #%d · stage %s · %s (%s)", name, id, step.Stage, event, step.Outcome)
|
||||
if len(summary) > 1800 {
|
||||
summary = summary[:1800]
|
||||
for !utf8.ValidString(summary) {
|
||||
summary = summary[:len(summary)-1]
|
||||
}
|
||||
}
|
||||
summary = truncateUTF8(summary, 1800)
|
||||
title := fmt.Sprintf("Pipeline stage %s", event)
|
||||
receipts := []protocol.NotificationReceipt{}
|
||||
persist := func() bool {
|
||||
@@ -60,7 +59,7 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
||||
return
|
||||
}
|
||||
receipt := &receipts[len(receipts)-1]
|
||||
result, err := stage.PublishNtfy(ctx, "system", title, summary, filename, data)
|
||||
result, err := stage.PublishNtfy(ctx, "system", title, summary, filename, data, "")
|
||||
if err != nil {
|
||||
receipt.Status = "failed"
|
||||
receipt.Diagnostic = err.Error()
|
||||
@@ -131,6 +130,125 @@ func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.N
|
||||
}
|
||||
}
|
||||
|
||||
// runAttentionEvent maps a run status to the operator attention notification it
|
||||
// deserves. Only a run parked on a person (`waiting`) or a run that failed needs
|
||||
// the operator; every other status — queued, running, succeeded, canceled,
|
||||
// interrupted — returns "" so the mapping is the single place that decides
|
||||
// whether a run produces a notification.
|
||||
func runAttentionEvent(status string) string {
|
||||
switch strings.TrimSpace(strings.ToLower(status)) {
|
||||
case protocol.RunStatusWaiting:
|
||||
return protocol.NotifyWaiting
|
||||
case "failed":
|
||||
return "failed"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// stageAttentionEvent maps a stage's notification event to the run-attention
|
||||
// event it covers, or "" when the stage event is not a run-attention event (a
|
||||
// success digest, for example). It is the one place the two vocabularies meet.
|
||||
func stageAttentionEvent(event string) string {
|
||||
switch event {
|
||||
case protocol.NotifyWaiting:
|
||||
return protocol.NotifyWaiting
|
||||
case "failure":
|
||||
return "failed"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// markAttentionSent records that [event] has already been delivered for step
|
||||
// [sequence] of run [id] (by a stage policy or by the run-level default), so the
|
||||
// same genuine event is never notified twice. The step sequence is part of the
|
||||
// key because one run can wait on a person more than once; each wait is its own
|
||||
// event.
|
||||
func (r *runner) markAttentionSent(id int64, sequence int, event string) {
|
||||
if event == "" {
|
||||
return
|
||||
}
|
||||
r.attentionMu.Lock()
|
||||
defer r.attentionMu.Unlock()
|
||||
if r.attentionSent[id] == nil {
|
||||
r.attentionSent[id] = map[string]bool{}
|
||||
}
|
||||
r.attentionSent[id][fmt.Sprintf("%d:%s", sequence, event)] = true
|
||||
}
|
||||
|
||||
// attentionAlready reports whether [event] was already delivered for step
|
||||
// [sequence] of run [id].
|
||||
func (r *runner) attentionAlready(id int64, sequence int, event string) bool {
|
||||
r.attentionMu.Lock()
|
||||
defer r.attentionMu.Unlock()
|
||||
return r.attentionSent[id][fmt.Sprintf("%d:%s", sequence, event)]
|
||||
}
|
||||
|
||||
// forgetAttention drops a run's delivered-event set once it is terminal, so the
|
||||
// registry is bounded by the runs still in flight.
|
||||
func (r *runner) forgetAttention(id int64) {
|
||||
r.attentionMu.Lock()
|
||||
defer r.attentionMu.Unlock()
|
||||
delete(r.attentionSent, id)
|
||||
}
|
||||
|
||||
// runAttentionClick is the deep link a run notification carries so tapping it
|
||||
// opens the run in the Android app, whose intent filter registers this scheme
|
||||
// and host.
|
||||
func runAttentionClick(id int64) string {
|
||||
return fmt.Sprintf("pipelines://run/%d", id)
|
||||
}
|
||||
|
||||
// notifyRun publishes one run-level attention notification to the operator's
|
||||
// already-configured "system" destination. It is the run counterpart of
|
||||
// notifyStep and reuses the same PublishNtfy machinery, destination and token
|
||||
// handling, so no second publisher, topic or service is introduced. The run id
|
||||
// and pipeline name identify the run and the click action opens it in the app.
|
||||
// A run that needs nobody produces nothing, and a delivery failure is logged and
|
||||
// never fails the run: this is a best-effort alert, not persisted run evidence.
|
||||
func (r *runner) notifyRun(id int64, name, status string, sequence int, currentStage, diagnostic string) {
|
||||
event := runAttentionEvent(status)
|
||||
if event == "" {
|
||||
return
|
||||
}
|
||||
if r.attentionAlready(id, sequence, event) {
|
||||
return
|
||||
}
|
||||
// Record the delivery attempt before publishing so a repeated transition for
|
||||
// the same run and event (a re-request, a restart-free re-entry) never
|
||||
// republishes; delivery itself is never retried.
|
||||
r.markAttentionSent(id, sequence, event)
|
||||
title := "Run needs your decision"
|
||||
summary := fmt.Sprintf("Run #%d · %s · waiting for a human decision", id, name)
|
||||
if event == "failed" {
|
||||
title = "Run failed"
|
||||
summary = fmt.Sprintf("Run #%d · %s · run failed", id, name)
|
||||
}
|
||||
if currentStage != "" {
|
||||
summary += " at stage " + currentStage
|
||||
}
|
||||
if diagnostic != "" {
|
||||
summary += ": " + diagnostic
|
||||
}
|
||||
summary = truncateUTF8(summary, 2000)
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
if _, err := stage.PublishNtfy(ctx, "system", title, summary, "", nil, runAttentionClick(id)); err != nil {
|
||||
log.Printf("run attention notification run=%d: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// truncateUTF8 bounds a notification string without splitting a multi-byte rune.
|
||||
func truncateUTF8(text string, max int) string {
|
||||
if len(text) <= max {
|
||||
return text
|
||||
}
|
||||
text = text[:max]
|
||||
for !utf8.ValidString(text) {
|
||||
text = text[:len(text)-1]
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func notificationArtifact(workspace, name string) ([]byte, error) {
|
||||
if name == "" || filepath.IsAbs(name) || filepath.Clean(name) != name || strings.ContainsAny(name, "\\\x00\r\n") {
|
||||
return nil, fmt.Errorf("artifact must be a clean workspace-relative file path")
|
||||
|
||||
@@ -260,3 +260,214 @@ func TestNotificationArtifactPathSafety(t *testing.T) {
|
||||
t.Fatal("safe artifact rejected", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunAttentionEventMapping pins the single decision of whether a run needs
|
||||
// the operator: a run parked on a person (waiting) or a failed run, and nothing
|
||||
// else. A queued, running, succeeded, canceled or interrupted run never notifies.
|
||||
func TestRunAttentionEventMapping(t *testing.T) {
|
||||
for _, test := range []struct{ status, want string }{
|
||||
{"waiting", protocol.NotifyWaiting},
|
||||
{"failed", "failed"},
|
||||
{"Warning", ""},
|
||||
{"queued", ""},
|
||||
{"running", ""},
|
||||
{"succeeded", ""},
|
||||
{"canceled", ""},
|
||||
{"interrupted", ""},
|
||||
{"", ""},
|
||||
} {
|
||||
if got := runAttentionEvent(test.status); got != test.want {
|
||||
t.Errorf("runAttentionEvent(%q) = %q, want %q", test.status, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunAttentionNotificationDelivery proves the operator-facing contract: the
|
||||
// already-configured "system" destination and topic are used, the payload names
|
||||
// the run and its pipeline, the click action opens the run, only waiting/failed
|
||||
// publish, and a run that stays waiting is never republished.
|
||||
func TestRunAttentionNotificationDelivery(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "attention.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
type delivered struct {
|
||||
method, path, title, message, click, authorization string
|
||||
}
|
||||
deliveries := make(chan delivered, 8)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
decoder := new(mime.WordDecoder)
|
||||
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
|
||||
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
|
||||
deliveries <- delivered{r.Method, r.URL.Path, title, message, r.Header.Get("Click"), r.Header.Get("Authorization")}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "attention-receipt", "event": "message"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN", "")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A run that needs nobody publishes nothing.
|
||||
for _, status := range []string{"queued", "running", "succeeded", "canceled", "interrupted"} {
|
||||
r.notifyRun(7, "release", status, 1, "build", "")
|
||||
}
|
||||
select {
|
||||
case got := <-deliveries:
|
||||
t.Fatalf("a run that needs nobody published: %+v", got)
|
||||
default:
|
||||
}
|
||||
// A waiting run publishes once, with the destination, identity and click.
|
||||
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
|
||||
// A run that stays waiting is never republished, on a later call or a re-request.
|
||||
r.notifyRun(7, "release", protocol.RunStatusWaiting, 1, "approve", "")
|
||||
// A failed run publishes once, with its diagnostic.
|
||||
r.notifyRun(7, "release", "failed", 2, "deploy", "provider returned 500")
|
||||
|
||||
first := <-deliveries
|
||||
if first.method != http.MethodPost || first.path != "/pipelines" {
|
||||
t.Fatalf("wrong destination/topic: %+v", first)
|
||||
}
|
||||
if first.title != "Run needs your decision" || !strings.Contains(first.message, "Run #7") || !strings.Contains(first.message, "release") || !strings.Contains(first.message, "decision") || !strings.Contains(first.message, "approve") {
|
||||
t.Fatalf("waiting notification does not identify the run/pipeline/need: %+v", first)
|
||||
}
|
||||
if first.click != "pipelines://run/7" {
|
||||
t.Fatalf("waiting notification click does not open the run: %q", first.click)
|
||||
}
|
||||
if first.authorization != "" {
|
||||
t.Fatalf("notification leaked an authorization header: %q", first.authorization)
|
||||
}
|
||||
second := <-deliveries
|
||||
if second.title != "Run failed" || !strings.Contains(second.message, "Run #7") || !strings.Contains(second.message, "release") || !strings.Contains(second.message, "deploy") || !strings.Contains(second.message, "provider returned 500") {
|
||||
t.Fatalf("failed notification is not actionable: %+v", second)
|
||||
}
|
||||
if second.click != "pipelines://run/7" {
|
||||
t.Fatalf("failed notification click does not open the run: %q", second.click)
|
||||
}
|
||||
select {
|
||||
case got := <-deliveries:
|
||||
t.Fatalf("third notification delivered for two genuine events: %+v", got)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunAttentionSuppressedByStagePolicy proves a stage's own notify policy and
|
||||
// the run-level default cannot both fire for the same event: the author's policy
|
||||
// wins, so the operator gets exactly one notification.
|
||||
func TestRunAttentionSuppressedByStagePolicy(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "suppress.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.markAttentionSent(11, 5, "failed")
|
||||
r.markAttentionSent(11, 6, "waiting")
|
||||
if !r.attentionAlready(11, 5, "failed") || !r.attentionAlready(11, 6, "waiting") {
|
||||
t.Fatal("stage-policy coverage not recorded")
|
||||
}
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
calls.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "suppressed", "event": "message"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
|
||||
r.notifyRun(11, "release", "failed", 5, "deploy", "")
|
||||
r.notifyRun(11, "release", protocol.RunStatusWaiting, 6, "approve", "")
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("run-level default repeated a stage-policy event %d times", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// TestHumanRunAttentionNotification proves the run loop publishes the run-level
|
||||
// attention notification itself when the pipeline declares no notify policy: the
|
||||
// transition to waiting reaches the operator's configured destination exactly
|
||||
// once, with the run, pipeline and a run-opening click.
|
||||
func TestHumanRunAttentionNotification(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "human-attention.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
type delivered struct{ title, message, click string }
|
||||
deliveries := make(chan delivered, 4)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
decoder := new(mime.WordDecoder)
|
||||
title, _ := decoder.DecodeHeader(r.Header.Get("Title"))
|
||||
message, _ := decoder.DecodeHeader(r.Header.Get("Message"))
|
||||
deliveries <- delivered{title, message, r.Header.Get("Click")}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "human-attention", "event": "message"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
|
||||
if _, err := store.Submit(ctx, "human", humanPipelineSource); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.wg.Wait()
|
||||
r.execute = successExecute
|
||||
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "human-attention", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
got := <-deliveries
|
||||
if got.title != "Run needs your decision" || !strings.Contains(got.message, fmt.Sprintf("Run #%d", run.ID)) || !strings.Contains(got.message, "human") {
|
||||
t.Fatalf("run-level waiting notification wrong: %+v", got)
|
||||
}
|
||||
if got.click != fmt.Sprintf("pipelines://run/%d", run.ID) {
|
||||
t.Fatalf("run-level waiting notification click wrong: %q", got.click)
|
||||
}
|
||||
select {
|
||||
case extra := <-deliveries:
|
||||
t.Fatalf("waiting run notified again: %+v", extra)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunAttentionNotifiesEachGenuineWait proves the step sequence is part of the
|
||||
// dedup key: a run that waits on a person twice notifies each time (two genuine
|
||||
// events), while the same wait is never repeated.
|
||||
func TestRunAttentionNotifiesEachGenuineWait(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "waits.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
calls.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id": "wait", "event": "message"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
|
||||
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
|
||||
r.notifyRun(1, "release", protocol.RunStatusWaiting, 1, "gate", "")
|
||||
r.notifyRun(1, "release", protocol.RunStatusWaiting, 5, "gate-again", "")
|
||||
if calls.Load() != 2 {
|
||||
t.Fatalf("two genuine waits produced %d notifications, want 2", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,11 @@ type runner struct {
|
||||
events *runEventHub
|
||||
wg sync.WaitGroup
|
||||
schedulerWG sync.WaitGroup
|
||||
// attentionMu guards attentionSent, the per-run set of run-attention events
|
||||
// already delivered — by a stage's own notify policy or by the run-level
|
||||
// default — so neither republishes the same genuine event.
|
||||
attentionMu sync.Mutex
|
||||
attentionSent map[int64]map[string]bool
|
||||
}
|
||||
|
||||
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
@@ -73,7 +78,7 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
return nil, err
|
||||
}
|
||||
root := filepath.Join(s.Directory(), "artifacts")
|
||||
return &runner{ctx: ctx, store: s, artifactsRoot: root, active: map[int64]activeRun{}}, nil
|
||||
return &runner{ctx: ctx, store: s, artifactsRoot: root, active: map[int64]activeRun{}, attentionSent: map[int64]map[string]bool{}}, nil
|
||||
}
|
||||
|
||||
func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.RunDetail, error) {
|
||||
@@ -393,6 +398,8 @@ func (r *runner) cancel(id int64) error {
|
||||
if err := r.store.CancelWaiting(r.ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
// A canceled run is terminal: nothing more can notify for it.
|
||||
r.forgetAttention(id)
|
||||
if r.events != nil {
|
||||
if detail, err := r.store.GetRun(r.ctx, id); err == nil && detail != nil {
|
||||
r.emitRun(protocol.RunEventFrame{
|
||||
@@ -473,7 +480,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, workspace string, request protocol.Message) {
|
||||
original, copyErr := copyValues(stage.Values(request.Input))
|
||||
if copyErr != nil {
|
||||
r.finishRunState(id, workspace, "failed", "error", copyErr.Error(), 0, "", stage.Values(request.Input))
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", copyErr.Error(), 0, 0, "", stage.Values(request.Input))
|
||||
return
|
||||
}
|
||||
input := stage.Values(request.Input)
|
||||
@@ -509,7 +516,7 @@ func terminalFinish(target, stageKey, outcome, diagnostic string) (status, final
|
||||
func (r *runner) resume(ctx context.Context, id int64, d *protocol.RunDetail, workspace string, step protocol.RunStep) {
|
||||
// The decision may route straight to a terminal, which has no stage to run.
|
||||
if status, outcome, diagnostic, terminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic); terminal {
|
||||
r.finishRunState(id, workspace, status, outcome, diagnostic, completedSteps(d.Steps), step.Stage, stage.Values(step.Output))
|
||||
r.finishRunState(id, d.Name, workspace, status, outcome, diagnostic, completedSteps(d.Steps), step.Sequence, step.Stage, stage.Values(step.Output))
|
||||
return
|
||||
}
|
||||
state := rebuildRunState(d, step)
|
||||
@@ -614,12 +621,14 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) {
|
||||
r.events.emit(frame, terminal)
|
||||
}
|
||||
|
||||
func (r *runner) finishRunState(id int64, workspace, status, outcome, diagnostic string, completed int, currentStage string, input stage.Values) {
|
||||
func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
// Push the terminal delta before the attention notification, so a slow ntfy
|
||||
// never delays the live update the app folds.
|
||||
r.emitRun(protocol.RunEventFrame{
|
||||
RunID: id,
|
||||
Workspace: workspace,
|
||||
@@ -629,6 +638,9 @@ func (r *runner) finishRunState(id int64, workspace, status, outcome, diagnostic
|
||||
CompletedSteps: completed,
|
||||
FinishedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}, true)
|
||||
r.notifyRun(id, name, status, sequence, currentStage, diagnostic)
|
||||
// The run is terminal: nothing more can notify for it.
|
||||
r.forgetAttention(id)
|
||||
}
|
||||
|
||||
// completedSteps counts the completed steps of a run detail; resume uses it to
|
||||
@@ -671,7 +683,7 @@ func (r *runner) finishStage(id int64, name, workspace string, selected protocol
|
||||
|
||||
func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, name, workspace string, request protocol.Message, state *runState) {
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
r.finishRunState(id, workspace, status, outcome, diagnostic, state.completed, state.key, state.input)
|
||||
r.finishRunState(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input)
|
||||
}
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
@@ -800,6 +812,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
Step: &protocol.RunStepDelta{Sequence: sequence, Stage: key, Status: protocol.StepStatusWaiting},
|
||||
}, false)
|
||||
r.notifyStep(id, name, workspace, selected.Notify, waitStep)
|
||||
r.notifyRun(id, name, protocol.RunStatusWaiting, sequence, key, "")
|
||||
return
|
||||
}
|
||||
// A stage that declares a `skipped` route is short-circuited when the run
|
||||
|
||||
+27
-3
@@ -79,7 +79,7 @@ func (NtfyStage) Run(ctx context.Context, def Definition, input Values) (Result,
|
||||
if strings.ContainsAny(title, "\r\n") || strings.ContainsAny(summary, "\r\n") {
|
||||
return Result{}, fmt.Errorf("ntfy title and summary must be single-line strings")
|
||||
}
|
||||
delivery, err := PublishNtfy(ctx, def.Configs["destination"], title, summary, "digest.md", []byte(markdown))
|
||||
delivery, err := PublishNtfy(ctx, def.Configs["destination"], title, summary, "digest.md", []byte(markdown), "")
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
@@ -89,11 +89,17 @@ func (NtfyStage) Run(ctx context.Context, def Definition, input Values) (Result,
|
||||
}
|
||||
|
||||
// PublishNtfy is shared by native delivery stages and stage notification hooks.
|
||||
// An empty filename publishes an event without an attachment.
|
||||
func PublishNtfy(ctx context.Context, destination, title, summary, filename string, data []byte) (Values, error) {
|
||||
// An empty filename publishes an event without an attachment. A non-empty click
|
||||
// is an optional ntfy Click action (an absolute URL) so a tap on the notification
|
||||
// opens the destination the operator should act on; it is validated here and
|
||||
// never carries credentials.
|
||||
func PublishNtfy(ctx context.Context, destination, title, summary, filename string, data []byte, click string) (Values, error) {
|
||||
if !destinationName.MatchString(destination) || strings.TrimSpace(title) == "" || strings.TrimSpace(summary) == "" || len(title) > 256 || len(summary) > 2048 || !utf8.ValidString(title) || !utf8.ValidString(summary) || strings.ContainsAny(title+summary, "\r\n\x00") {
|
||||
return nil, fmt.Errorf("invalid ntfy notification metadata")
|
||||
}
|
||||
if !validNtfyClick(click) {
|
||||
return nil, fmt.Errorf("invalid ntfy click action")
|
||||
}
|
||||
if len(data) > 1<<20 || (filename != "" && (filename != filepath.Base(filename) || filename == "." || strings.ContainsAny(filename, "/\\\r\n\x00") || len(filename) > 200)) {
|
||||
return nil, fmt.Errorf("invalid ntfy attachment")
|
||||
}
|
||||
@@ -145,6 +151,9 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
|
||||
}
|
||||
request.Header.Set("Title", mime.BEncoding.Encode("utf-8", title))
|
||||
request.Header.Set("Message", mime.BEncoding.Encode("utf-8", summary))
|
||||
if click != "" {
|
||||
request.Header.Set("Click", click)
|
||||
}
|
||||
if filename != "" {
|
||||
request.Header.Set("Filename", mime.BEncoding.Encode("utf-8", filename))
|
||||
}
|
||||
@@ -189,3 +198,18 @@ func PublishNtfy(ctx context.Context, destination, title, summary, filename stri
|
||||
}
|
||||
return Values{"destination": destination, "message_id": ack.ID, "attachment_url": ack.Attachment.URL, "filename": filename}, nil
|
||||
}
|
||||
|
||||
// validNtfyClick accepts an empty click or an absolute URL the ntfy server will
|
||||
// hand to the operating system on tap: a scheme, no credentials, no fragment,
|
||||
// no control characters and a bounded length. The value is an operator-visible
|
||||
// deep link, never a place to smuggle a token.
|
||||
func validNtfyClick(click string) bool {
|
||||
if click == "" {
|
||||
return true
|
||||
}
|
||||
if len(click) > 2048 || !utf8.ValidString(click) || strings.ContainsAny(click, "\r\n\t\x00 ") {
|
||||
return false
|
||||
}
|
||||
u, err := url.Parse(click)
|
||||
return err == nil && u.Scheme != "" && u.User == nil && u.Fragment == ""
|
||||
}
|
||||
|
||||
@@ -32,16 +32,16 @@ func TestNtfyTokenFile(t *testing.T) {
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN_FILE", path)
|
||||
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil); err != nil {
|
||||
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "other-token")
|
||||
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil); err == nil {
|
||||
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, ""); err == nil {
|
||||
t.Fatal("ambiguous token sources accepted")
|
||||
}
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_TOKEN", "")
|
||||
os.WriteFile(path, nil, 0600)
|
||||
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil); err == nil {
|
||||
if _, err := PublishNtfy(context.Background(), "anime", "Title", "Summary", "", nil, ""); err == nil {
|
||||
t.Fatal("empty token accepted")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user