Merge main into lane-srv3: combine the review-loop control change with main's notification and chat work
Keeps this branch's advisory review edge, bounded blocked_retryable implementer edge and their tests alongside main's run-attention/ntfy notification work, the split of the Android chat conversation screen, and the retention/history changes. No conflicts: the two sides touch disjoint files.
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:
|
||||
|
||||
@@ -6010,6 +6010,131 @@ reachable from the run detail and its stage and the shared component is ready fo
|
||||
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.
|
||||
|
||||
## Destination pill stands down in an open conversation (17 Oct 2026)
|
||||
|
||||
The floating destinations pill was drawn over the bottom of every screen,
|
||||
including an open chat, where it sat on the composer and the newest message and
|
||||
competed with the send/stop controls. It now stands down while the Chat
|
||||
destination is showing an open conversation and stays everywhere else,
|
||||
unchanged. `android/` only; no new dependency, no run started from the app, no
|
||||
server/installer/Docker file touched, and the operator's Pixel was never used.
|
||||
|
||||
- **One rule.** `destinationPillVisible(currentRoute, conversationOpen)` is false
|
||||
only for `chat` with an open conversation — a session's transcript and composer
|
||||
— and true for the chat list and every other destination. `conversationOpen` is
|
||||
the new `AppViewModel.conversationOpen` (`chatStore.state.map { it.active != null }`,
|
||||
`distinctUntilChanged`), read from the same store the chat surface renders, so a
|
||||
background open chat never hides the pill elsewhere and a streamed chat delta
|
||||
never recomposes the app shell.
|
||||
- **The space, not just the pill.** `destinationPillReserve(pillVisible)` returns
|
||||
the named `DESTINATION_PILL_RESERVE` while the pill is drawn and `0.dp` while it
|
||||
is hidden: the content Column keeps clearing a drawn pill, and a hidden pill
|
||||
leaves no empty band at the end of scrollable content, so the composer sits at
|
||||
the true bottom. The pill and its reservation are driven by the one predicate,
|
||||
so no frame has a drawn pill over content it does not clear or a reserved gap
|
||||
behind a hidden pill; the viewport height is constant for as long as a
|
||||
conversation is open, so the composer and the newest message do not move while
|
||||
it is shown. Works with the keyboard open: the composer's own `imePadding` and
|
||||
the pill's `paneSafeArea()` are unchanged, with no pill left to sit over them.
|
||||
- **Still escapable.** Nothing about leaving a conversation changed: its top-bar
|
||||
back arrow (`Back to chats`), the system Back button/gesture (`ChatScreen`'s
|
||||
`PredictiveBackHandler`), and on a wide window the covered chat-list strip
|
||||
(`SlidingPaneStack.onPopTo`) all return to the list. The pill was never the way
|
||||
out; Back is.
|
||||
- **Nothing else touched.** The pill's destinations, travelling indicator,
|
||||
morph-into-search and behaviour on every other screen are untouched; the
|
||||
attention indicator is unchanged.
|
||||
|
||||
Evidence (this pass, macOS, JDK 17 `/opt/homebrew/opt/openjdk@17`, cached Gradle
|
||||
8.11.1, `ANDROID_HOME=$HOME/Library/Android/sdk`, `--offline --no-daemon`):
|
||||
|
||||
- `gradle :app:testDebugUnitTest --offline --no-daemon --console=plain` →
|
||||
`BUILD SUCCESSFUL in 11s`; the JUnit XMLs total **58 suites / 533 tests / 0
|
||||
failures / 0 errors / 0 skipped** (up from 531: `PipelinesNavTest` gains
|
||||
`thePillStandsDownOnlyWhileAConversationIsOpen` and
|
||||
`theReserveTracksTheDrawnPillSoContentNeitherJumpsNorLeavesAGap`).
|
||||
- `gradle :app:assembleDebug --offline --no-daemon --console=plain` →
|
||||
`BUILD SUCCESSFUL`; `app/build/outputs/apk/debug/app-debug.apk` is **18,535,932
|
||||
bytes**, sha256 `fc872b5398c231f053cd6e5f6794b2b6c2a8f947314ba0de02851dab2a95c3e`.
|
||||
- **APK publish.** Copied to
|
||||
`~/.local/share/pipelines/data/artifacts/287/1/pipelines-debug-wip-890d267.apk`
|
||||
(`890d267` = `git rev-parse --short HEAD`; the tree is uncommitted WIP on top of
|
||||
it), sha256 matched. The LAN URL
|
||||
`http://10.0.0.75:8080/artifacts/287/1/pipelines-debug-wip-890d267.apk` returned
|
||||
`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18535932`.
|
||||
|
||||
Not verified in this pass: the conversation/list screenshots — the brief keeps
|
||||
implementation and ordinary code review to the build and the unit tests, and
|
||||
visual review owns the operator's Pixel 9 Pro XL (its captures are the ones the
|
||||
brief names: a conversation with no pill, and the chat list with it).
|
||||
|
||||
## Run title readability: whole in the run view, two lines in the list (17 Oct 2026)
|
||||
|
||||
A run's title is derived from its prompt, so it is often long. The run view now
|
||||
|
||||
@@ -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()
|
||||
@@ -141,6 +153,19 @@ class AppViewModel(
|
||||
)
|
||||
val chat: StateFlow<ChatState> = chatStore.state
|
||||
|
||||
/**
|
||||
* Whether the Chat destination is showing an open conversation — a session's
|
||||
* transcript and composer — rather than the session list or the create flow.
|
||||
* The app hides the floating destination pill in exactly this state. A derived
|
||||
* boolean, distinct until changed, so the whole chat state (streamed deltas,
|
||||
* drafts, scroll) never recomposes the app shell; it is read from the same
|
||||
* store the chat surface renders, so the pill and the pane can never disagree.
|
||||
*/
|
||||
val conversationOpen: StateFlow<Boolean> = chatStore.state
|
||||
.map { it.active != null }
|
||||
.distinctUntilChanged()
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, chatStore.value.active != null)
|
||||
|
||||
// The live run subscription: the workspace currently watched, the job that
|
||||
// established it, and the coalescing jobs that re-sync on a push. One
|
||||
// subscription per connection; a reconnect (which clears this watch, not the
|
||||
@@ -182,6 +207,7 @@ class AppViewModel(
|
||||
observeConnection()
|
||||
observeChatOverrides()
|
||||
observeChatSeen()
|
||||
observeAttention()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -495,6 +521,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
|
||||
@@ -162,6 +175,12 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
mutableStateOf(OmniSearchState())
|
||||
}
|
||||
val search by vm.search.collectAsStateWithLifecycle()
|
||||
// Whether the Chat destination currently shows an open conversation. The
|
||||
// floating pill stands down only there (see [destinationPillVisible]); it is
|
||||
// read from the chat store, so it flips in the same recomposition that swaps
|
||||
// the chat list for the conversation.
|
||||
val conversationOpen by vm.conversationOpen.collectAsStateWithLifecycle()
|
||||
val pillVisible = destinationPillVisible(currentRoute, conversationOpen)
|
||||
|
||||
/** Back/scrim/close and a selection all dismiss the morph and clear the panel. */
|
||||
val dismissSearch: () -> Unit = {
|
||||
@@ -190,6 +209,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
|
||||
@@ -216,11 +270,13 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
// Scaffold, and the floating pill explicitly clears the safe area (system
|
||||
// bars, cutout, gesture area and IME) via windowInsetsPadding. The Column
|
||||
// reserves DESTINATION_PILL_RESERVE at the bottom so no scrollable content is
|
||||
// permanently hidden behind the pill.
|
||||
// permanently hidden behind the pill; while the pill is hidden (an open
|
||||
// conversation, see [destinationPillVisible]) that reservation is dropped too,
|
||||
// so the composer sits at the true bottom instead of over an empty band.
|
||||
val bannerVisible = connectionState !is ConnectionState.Connected
|
||||
Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0)) { padding ->
|
||||
Box(Modifier.fillMaxSize().padding(padding)) {
|
||||
Column(Modifier.fillMaxSize().padding(bottom = DESTINATION_PILL_RESERVE)) {
|
||||
Column(Modifier.fillMaxSize().padding(bottom = destinationPillReserve(pillVisible))) {
|
||||
ConnectionBanner(
|
||||
state = connectionState,
|
||||
configuredUrl = configuredUrl,
|
||||
@@ -326,19 +382,37 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
.padding(bottom = 16.dp),
|
||||
)
|
||||
}
|
||||
DestinationBar(
|
||||
destinations = destinations,
|
||||
currentRoute = currentRoute,
|
||||
state = searchState,
|
||||
onSelect = onNavigate,
|
||||
onOpenSearch = { searchState = openOmniSearch(searchState) },
|
||||
onDismissSearch = dismissSearch,
|
||||
onQueryChange = {
|
||||
searchState = setOmniSearchQuery(searchState, it)
|
||||
vm.onSearchQueryChanged(it)
|
||||
},
|
||||
onFocusChange = { searchState = setOmniSearchFocus(searchState, it) },
|
||||
onSubmitSearch = { vm.searchNow() },
|
||||
AttentionIndicator(
|
||||
entries = attention,
|
||||
onClick = { attentionOpen = true },
|
||||
modifier = Modifier.padding(bottom = SPACING_S),
|
||||
)
|
||||
// The pill stands down while a conversation is open; the search
|
||||
// field it morphs into is unreachable there anyway (the field opens
|
||||
// from the pill), so nothing is stranded by not drawing it.
|
||||
if (pillVisible) {
|
||||
DestinationBar(
|
||||
destinations = destinations,
|
||||
currentRoute = currentRoute,
|
||||
state = searchState,
|
||||
onSelect = onNavigate,
|
||||
onOpenSearch = { searchState = openOmniSearch(searchState) },
|
||||
onDismissSearch = dismissSearch,
|
||||
onQueryChange = {
|
||||
searchState = setOmniSearchQuery(searchState, it)
|
||||
vm.onSearchQueryChanged(it)
|
||||
},
|
||||
onFocusChange = { searchState = setOmniSearchFocus(searchState, it) },
|
||||
onSubmitSearch = { vm.searchNow() },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (attentionOpen) {
|
||||
AttentionSheet(
|
||||
entries = attention,
|
||||
onOpen = openAttentionEntry,
|
||||
onDismissEntry = { entry -> vm.dismissAttention(entry.runId, entry.kind) },
|
||||
onDismiss = closeAttentionList,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -669,6 +743,34 @@ private fun TemplatesDestination(
|
||||
internal fun destinationIndicatorOffsetDp(index: Int, itemSize: Dp, gap: Dp): Dp =
|
||||
gap + (itemSize + gap) * index.coerceAtLeast(0)
|
||||
|
||||
/** The Chat destination's navigation route. */
|
||||
private const val CHAT_ROUTE = "chat"
|
||||
|
||||
/**
|
||||
* Whether the floating destination pill is drawn for [currentRoute]. The pill
|
||||
* stands down only while the Chat destination is showing an open conversation —
|
||||
* a session's transcript and composer — where it would sit over the composer and
|
||||
* the newest message and compete with send/stop. The chat list and every other
|
||||
* destination keep it exactly as before; the covered peek strip and Back still
|
||||
* leave a conversation, so hiding the pill strands nothing. Pure, so the one
|
||||
* rule is unit-testable without a device.
|
||||
*/
|
||||
internal fun destinationPillVisible(currentRoute: String?, conversationOpen: Boolean): Boolean =
|
||||
!(currentRoute == CHAT_ROUTE && conversationOpen)
|
||||
|
||||
/**
|
||||
* The bottom space the content reserves for the pill: the named
|
||||
* [DESTINATION_PILL_RESERVE] while the pill is drawn, and none while it is
|
||||
* hidden, so a hidden pill leaves no empty band at the end of scrollable content
|
||||
* and the composer sits at the true bottom. Derived from [pillVisible] alone, so
|
||||
* the reservation and the drawn pill can never disagree into a frame with a
|
||||
* drawn pill over content it does not clear, or a reserved gap behind a hidden
|
||||
* one — which is what keeps the content from jumping as the pill appears and
|
||||
* disappears.
|
||||
*/
|
||||
internal fun destinationPillReserve(pillVisible: Boolean): Dp =
|
||||
if (pillVisible) DESTINATION_PILL_RESERVE else 0.dp
|
||||
|
||||
/**
|
||||
* The bottom container: the destination pill that morphs into the omni-search
|
||||
* field. It is one [Surface] so the morph reads as the same container changing
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Shield
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.ui.theme.HAIRLINE_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_LIST_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
|
||||
import net.awan.pipelines.ui.theme.pipelinesText
|
||||
|
||||
/**
|
||||
* The approval card's amber review panel and pending-card border strengths,
|
||||
* echoing the reference app's 10%-alpha amber `RISK REVIEW` box.
|
||||
*/
|
||||
private const val RISK_REVIEW_ALPHA = 0.12f
|
||||
private const val APPROVAL_PENDING_BORDER_ALPHA = 0.5f
|
||||
|
||||
/**
|
||||
* One approval request as a card in the conversation (research §1.3 `_CodeRun` /
|
||||
* risk review): the action being requested, the affected resources, the amber
|
||||
* `RISK REVIEW` panel repeating the server's risk summary, and once/always/reject
|
||||
* actions answered with `chat_reply`, so the server-held credentials and the tool
|
||||
* never leave it. A card that is already answered or resolved keeps its place but
|
||||
* drops the actions and states the outcome, so it can never offer a stale choice.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ApprovalCardItem(card: ApprovalCard, onDecision: (String) -> Unit) {
|
||||
val amber = MaterialTheme.colorScheme.tertiary
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
border = if (card.actionable) BorderStroke(HAIRLINE_DP, amber.copy(alpha = APPROVAL_PENDING_BORDER_ALPHA)) else null,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER),
|
||||
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_LIST_DP))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(card.headline, style = pipelinesText().cardTitle)
|
||||
Text(
|
||||
text = card.statusLine,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (card.resources.isNotEmpty()) {
|
||||
Text(
|
||||
text = card.resources.joinToString("\n"),
|
||||
style = pipelinesText().mono,
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (card.showRisk && card.risk.isNotBlank()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(CHAT_ITEM_GAP))
|
||||
.background(amber.copy(alpha = RISK_REVIEW_ALPHA))
|
||||
.padding(CHAT_ITEM_GAP),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_STATUS_DP))
|
||||
Text("RISK REVIEW", style = MaterialTheme.typography.labelSmall, color = amber)
|
||||
}
|
||||
Text(card.risk, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
if (card.actionable) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
Button(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") }
|
||||
TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always allow") }
|
||||
TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Reject") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun ChatComposer(
|
||||
thread: ChatThread,
|
||||
onDraft: (String) -> Unit,
|
||||
onAttach: (List<ChatAttachment>) -> Unit,
|
||||
onRemoveAttachment: (String) -> Unit,
|
||||
onSend: () -> Unit,
|
||||
onStop: () -> Unit,
|
||||
) {
|
||||
val action = composerAction(thread)
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
// The platform picker: the operator chooses files and they are only resolved
|
||||
// into attachments here — nothing is sent until the message is.
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||
if (uris.isNotEmpty()) {
|
||||
scope.launch {
|
||||
val resolved = withContext(Dispatchers.IO) { uris.map { resolveChatAttachment(context, it) } }
|
||||
onAttach(resolved)
|
||||
}
|
||||
}
|
||||
}
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) {
|
||||
if (thread.readOnly) {
|
||||
Text(
|
||||
text = "Another client holds this session; it is read-only here.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
if (thread.attachments.isNotEmpty()) {
|
||||
ChatAttachmentStrip(attachments = thread.attachments, onRemove = onRemoveAttachment)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) {
|
||||
IconButton(
|
||||
onClick = { picker.launch(arrayOf("*/*")) },
|
||||
enabled = !thread.readOnly,
|
||||
) {
|
||||
Icon(Icons.Default.AttachFile, contentDescription = "Attach file")
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = thread.draft,
|
||||
onValueChange = onDraft,
|
||||
enabled = !thread.readOnly,
|
||||
placeholder = { Text("Message the agent…") },
|
||||
minLines = 1,
|
||||
maxLines = 6,
|
||||
keyboardActions = KeyboardActions(
|
||||
onSend = { if (action == ComposerAction.Send && thread.canSend) onSend() },
|
||||
),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
when (action) {
|
||||
// While a turn is in flight the send control becomes the stop
|
||||
// control, so it must interrupt rather than send the draft.
|
||||
ComposerAction.Stop -> IconButton(onClick = onStop) {
|
||||
Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
ComposerAction.Send -> IconButton(onClick = onSend, enabled = thread.canSend) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.PanTool
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.launch
|
||||
import net.awan.pipelines.ui.AppViewModel
|
||||
import net.awan.pipelines.ui.components.EmptyState
|
||||
import net.awan.pipelines.ui.components.ErrorState
|
||||
import net.awan.pipelines.ui.components.LabelChip
|
||||
import net.awan.pipelines.ui.components.LoadingState
|
||||
import net.awan.pipelines.ui.theme.SPACING_S
|
||||
import net.awan.pipelines.ui.theme.SPACING_XS
|
||||
import net.awan.pipelines.ui.theme.SPACING_XXS
|
||||
import net.awan.pipelines.ui.theme.pipelinesText
|
||||
|
||||
// ---- Pane 1: the active conversation -----------------------------------------
|
||||
|
||||
/**
|
||||
* The conversation's identity context, directly below the app bar that carries
|
||||
* its title: the session kind (labelled, never a bare name), its activity and,
|
||||
* when the server knows them, the directory and model. The title is not repeated
|
||||
* here — this block adds only what the title cannot say.
|
||||
*/
|
||||
@Composable
|
||||
private fun ConversationHeader(header: ConversationHeader) {
|
||||
val texts = pipelinesText()
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
) {
|
||||
header.kind?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
|
||||
Text(
|
||||
text = header.activity,
|
||||
style = texts.label,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (header.context.isNotEmpty()) {
|
||||
Text(
|
||||
text = header.context.joinToString(" · "),
|
||||
style = texts.meta,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
internal fun ChatConversationPane(
|
||||
vm: AppViewModel,
|
||||
state: ChatState,
|
||||
thread: ChatThread,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
val approval = approvalCard(thread.permission, thread.permissionAnswer)
|
||||
val awaiting = approval?.actionable == true
|
||||
// The header's one identity: the title, with the kind, activity, directory and
|
||||
// model as context below it. It is built once so the app bar and the context
|
||||
// line cannot disagree about the session's name.
|
||||
val header = conversationHeader(thread)
|
||||
// Reasoning expansion is hoisted here, not into the lazy transcript: a
|
||||
// reasoning part keeps its open/closed state while the operator scrolls (and
|
||||
// the item is disposed), and the state is per conversation, so a newly opened
|
||||
// chat starts with every reasoning part collapsed.
|
||||
var reasoning by remember(thread.sessionId) { mutableStateOf(ReasoningExpansion()) }
|
||||
// A turn blocked on an approval is not generating, so the running indicator
|
||||
// (and its ticking clock) stands down while the card is unanswered.
|
||||
val showRunning = thread.running && !awaiting
|
||||
// The count of the transcript's items: the messages, the running indicator
|
||||
// while a turn is in flight and a pending approval card, which is the last item
|
||||
// the top bar's approval action jumps to.
|
||||
val itemCount = thread.messages.size + (if (showRunning) 1 else 0) + (if (approval != null) 1 else 0)
|
||||
// The position the operator left this conversation at, read once: a
|
||||
// conversation with none of its own opens at its newest message instead (see
|
||||
// chatOpensAtNewest), so the current turn is never hunted for.
|
||||
val savedScroll = remember(thread.sessionId) { thread.scroll }
|
||||
// The list state is created the moment the conversation first has content, so
|
||||
// its very first measure is already at the newest item rather than at the top:
|
||||
// opening a chat must not show anything else first. It is still saveable, so a
|
||||
// rotation or process death keeps the operator's position.
|
||||
val listState = rememberSaveable(thread.sessionId, itemCount > 0, saver = LazyListState.Saver) {
|
||||
val first = chatFirstScroll(savedScroll, itemCount)
|
||||
LazyListState(
|
||||
firstVisibleItemIndex = first.index,
|
||||
firstVisibleItemScrollOffset = first.offset,
|
||||
)
|
||||
}
|
||||
// Persist the scroll position when the operator leaves this chat, so switching
|
||||
// away and back returns them exactly where they were. Keyed on the list state,
|
||||
// so the position saved is the one that was actually shown; a state that never
|
||||
// held content (replaced when the conversation first loaded) saves nothing,
|
||||
// leaving the conversation with no position of its own to open at its newest.
|
||||
DisposableEffect(listState) {
|
||||
onDispose {
|
||||
if (listState.layoutInfo.totalItemsCount > 0) {
|
||||
vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
// The one identity: the app bar carries the title (the value
|
||||
// the context line below is built beside), and under it the
|
||||
// model meta the server reports — its model, kind tag and
|
||||
// directory — so what is answering is visible without leaving
|
||||
// the conversation. Every part is server-reported; a blank one
|
||||
// is simply omitted.
|
||||
Column {
|
||||
Text(
|
||||
text = header.title,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val meta = chatHeaderMeta(thread)
|
||||
if (meta.isNotBlank()) {
|
||||
Text(
|
||||
text = meta,
|
||||
style = pipelinesText().meta,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
IconButton(onClick = vm::showChatList) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to chats")
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (awaiting) {
|
||||
IconButton(
|
||||
onClick = {
|
||||
// The transcript's one scroll path, so a pending
|
||||
// request is brought into view the same way new
|
||||
// content is.
|
||||
scope.launch { listState.scrollToEnd(itemCount, animated = true) }
|
||||
},
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.PanTool,
|
||||
contentDescription = "Waiting for your approval",
|
||||
tint = MaterialTheme.colorScheme.tertiary,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (thread.running) {
|
||||
IconButton(onClick = { vm.stopChat(thread.sessionId) }) {
|
||||
Icon(Icons.Default.Stop, contentDescription = "Stop")
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.fillMaxSize().padding(padding).imePadding()) {
|
||||
ConversationHeader(header)
|
||||
// Every *other* open chat is still one tap away; the active one is
|
||||
// already named by the app bar, so it is not repeated here.
|
||||
OpenChatStrip(
|
||||
state = state,
|
||||
onSelect = vm::activateChat,
|
||||
onClose = vm::closeChat,
|
||||
excludeSessionId = thread.sessionId,
|
||||
)
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
when {
|
||||
thread.loading && !thread.loaded -> LoadingState("Loading conversation…")
|
||||
thread.error != null && !thread.loaded -> ErrorState(
|
||||
message = thread.error,
|
||||
onRetry = { vm.loadChatHistory(thread.sessionId) },
|
||||
)
|
||||
thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState(
|
||||
message = if (thread.readOnly) {
|
||||
"This chat is read-only while another client holds the session."
|
||||
} else {
|
||||
"This chat has no messages yet. Ask something below."
|
||||
},
|
||||
)
|
||||
else -> ChatTranscript(
|
||||
thread = thread,
|
||||
listState = listState,
|
||||
savedScroll = savedScroll,
|
||||
itemCount = itemCount,
|
||||
approval = approval,
|
||||
showRunning = showRunning,
|
||||
reasoning = reasoning,
|
||||
onToggleReasoning = { reasoning = reasoning.toggled(it) },
|
||||
onDecision = { decision ->
|
||||
approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (thread.error != null && thread.loaded) {
|
||||
Text(
|
||||
text = thread.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
ChatComposer(
|
||||
thread = thread,
|
||||
onDraft = { vm.updateChatDraft(thread.sessionId, it) },
|
||||
onAttach = { vm.attachChatFiles(thread.sessionId, it) },
|
||||
onRemoveAttachment = { vm.removeChatAttachment(thread.sessionId, it) },
|
||||
onSend = { vm.sendChatPrompt(thread.sessionId) },
|
||||
onStop = { vm.stopChat(thread.sessionId) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.ui.AppViewModel
|
||||
import net.awan.pipelines.ui.components.ErrorState
|
||||
import net.awan.pipelines.ui.components.ListRow
|
||||
import net.awan.pipelines.ui.components.LoadingState
|
||||
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
|
||||
import net.awan.pipelines.ui.theme.pipelinesText
|
||||
|
||||
// ---- The create flow: choose the directory, then create ----------------------
|
||||
|
||||
/**
|
||||
* Where the operator starts a new chat: the server's directories, the home first
|
||||
* and the recents after it, each with its full path. It is a normal pane of the
|
||||
* chat stack — Back or its Cancel control leaves without creating anything — so
|
||||
* starting a chat is a step in the flow rather than a modal dead end, and a
|
||||
* session is never created wherever the server happens to run.
|
||||
*
|
||||
* The operator's home is the default; a recent is chosen with one tap, and the
|
||||
* chat is created only when the operator confirms.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
internal fun NewChatPane(
|
||||
vm: AppViewModel,
|
||||
state: ChatState,
|
||||
create: ChatCreateState,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
val choices = remember(state.directories) { directoryChoices(state.directories) }
|
||||
val selected = remember(create.directory, choices) {
|
||||
choices.firstOrNull { it.createDirectory == create.directory } ?: defaultDirectoryChoice(choices)
|
||||
}
|
||||
Scaffold(
|
||||
modifier = modifier,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Start a chat") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = vm::cancelNewChat) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel new chat")
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.fillMaxSize().padding(padding)) {
|
||||
when {
|
||||
state.directoriesError != null && !state.directoriesLoaded ->
|
||||
ErrorState(state.directoriesError, onRetry = vm::refreshChatDirectories)
|
||||
!state.directoriesLoaded -> LoadingState("Loading directories…")
|
||||
else -> {
|
||||
Text(
|
||||
text = "Where should this chat live?",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
)
|
||||
LazyColumn(Modifier.weight(1f).fillMaxWidth()) {
|
||||
items(choices, key = { it.createDirectory }) { choice ->
|
||||
DirectoryRow(
|
||||
choice = choice,
|
||||
selected = choice.createDirectory == selected?.createDirectory,
|
||||
onClick = { vm.selectChatDirectory(choice.createDirectory) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.directoriesError != null) {
|
||||
Text(
|
||||
text = state.directoriesError,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
create.error?.let { error ->
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
// The brokered server exposes no request for choosing a
|
||||
// session's model: chat_prompt carries model/agent fields but
|
||||
// the server does not forward them, and there is no catalogue
|
||||
// request to offer a choice from. So the flow says so plainly
|
||||
// rather than shipping a picker that would do nothing. The
|
||||
// conversation header then shows whatever model the server
|
||||
// reports for the created session.
|
||||
Text(
|
||||
text = "This server has no request for choosing a chat's model, so a new chat uses the server's default.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
)
|
||||
NewChatActions(
|
||||
directory = selected?.createDirectory ?: create.directory,
|
||||
creating = create.creating,
|
||||
onCreate = vm::createNewChat,
|
||||
onCancel = vm::cancelNewChat,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One directory the new chat can live in: the home first, then the recents. */
|
||||
@Composable
|
||||
private fun DirectoryRow(choice: ChatDirectoryChoice, selected: Boolean, onClick: () -> Unit) {
|
||||
ListRow(selected = selected, onClick = onClick) {
|
||||
Text(
|
||||
text = choice.label,
|
||||
style = pipelinesText().cardTitle,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
// The home row's label is `~`, so its full path is shown beneath it; a
|
||||
// recent's own label already is its full path.
|
||||
choice.secondary?.let { path ->
|
||||
Text(text = path, style = pipelinesText().meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The create flow's footer: the chosen directory, its confirm and its cancel. */
|
||||
@Composable
|
||||
private fun NewChatActions(directory: String, creating: Boolean, onCreate: () -> Unit, onCancel: () -> Unit) {
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP),
|
||||
modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER),
|
||||
) {
|
||||
Text(
|
||||
text = "Start in $directory",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onCancel, enabled = !creating) { Text("Cancel") }
|
||||
Button(onClick = onCreate, enabled = !creating) {
|
||||
if (creating) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator(Modifier.size(ICON_INLINE_DP), strokeWidth = 2.dp)
|
||||
}
|
||||
} else {
|
||||
Text("New chat")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT
|
||||
import net.awan.pipelines.ui.components.RunState
|
||||
import net.awan.pipelines.ui.components.RunStatusPalette
|
||||
import net.awan.pipelines.ui.theme.pipelinesText
|
||||
|
||||
/** The `+N -M` counts, green/red monospace, exactly as the reference diff stat. */
|
||||
@Composable
|
||||
internal fun DiffStat(diff: ToolDiff) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
Text(
|
||||
text = "+${diff.added}",
|
||||
style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace),
|
||||
color = RunStatusPalette.of(RunState.Succeeded).color,
|
||||
)
|
||||
Text(
|
||||
text = "-${diff.removed}",
|
||||
style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace),
|
||||
color = RunStatusPalette.of(RunState.Failed).color,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The unified diff body of an edit card: line-by-line monospace with `+`/`-`
|
||||
* gutter symbols and the app's success/failure hues, bounded so a long diff
|
||||
* scrolls inside the card instead of pushing the transcript down.
|
||||
*/
|
||||
@Composable
|
||||
internal fun DiffView(diff: ToolDiff) {
|
||||
val added = RunStatusPalette.of(RunState.Succeeded).color
|
||||
val removed = RunStatusPalette.of(RunState.Failed).color
|
||||
val context = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = CODE_BLOCK_MAX_HEIGHT)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
) {
|
||||
if (diff.omitted > 0) {
|
||||
// A very large edit is summarised rather than rendered in full, so
|
||||
// the card stays short and readable on a phone. The note sits first
|
||||
// so the truncation is visible without scrolling to the end.
|
||||
Text(
|
||||
text = "… ${diff.omitted} more changed " +
|
||||
(if (diff.omitted == 1) "line" else "lines") + " not shown",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
diff.lines.forEach { line ->
|
||||
val (symbol, color) = when (line.kind) {
|
||||
DiffKind.ADD -> "+" to added
|
||||
DiffKind.REMOVE -> "-" to removed
|
||||
DiffKind.CONTEXT -> " " to context
|
||||
}
|
||||
Text(
|
||||
text = "$symbol ${line.text}",
|
||||
style = pipelinesText().mono,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarDuration
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.SnackbarResult
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.ui.AppViewModel
|
||||
import net.awan.pipelines.ui.components.EmptyState
|
||||
import net.awan.pipelines.ui.components.ErrorState
|
||||
import net.awan.pipelines.ui.components.FilterMenu
|
||||
import net.awan.pipelines.ui.components.FilterSectionHeader
|
||||
import net.awan.pipelines.ui.components.LabelChip
|
||||
import net.awan.pipelines.ui.components.ListRow
|
||||
import net.awan.pipelines.ui.components.LoadingState
|
||||
import net.awan.pipelines.ui.components.PaneIdentity
|
||||
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
|
||||
import net.awan.pipelines.ui.theme.SPACING_M
|
||||
import net.awan.pipelines.ui.theme.SPACING_S
|
||||
import net.awan.pipelines.ui.theme.SPACING_XXS
|
||||
import net.awan.pipelines.ui.theme.pipelinesText
|
||||
|
||||
// ---- Pane 0: the server's session list ---------------------------------------
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
internal fun ChatListPane(
|
||||
vm: AppViewModel,
|
||||
state: ChatState,
|
||||
connected: Boolean,
|
||||
covered: Boolean,
|
||||
modifier: Modifier,
|
||||
) {
|
||||
// A covered pane shows its compact identity only; the server list and the
|
||||
// operator's own local changes are folded into the visible projection only
|
||||
// for the pane actually drawn, never for the sliver behind a conversation.
|
||||
if (covered) {
|
||||
val count = state.visibleSessionCount
|
||||
PaneIdentity(
|
||||
title = "Chat",
|
||||
subtitle = when {
|
||||
state.open.isNotEmpty() -> "${state.open.size} open"
|
||||
count > 0 -> "$count sessions"
|
||||
else -> null
|
||||
},
|
||||
modifier = modifier.fillMaxSize(),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// The server returns operator sessions only, with the operator's own local
|
||||
// renames and removals applied on top; the app never guesses which session
|
||||
// belongs to a run. The operator's search narrows that list without touching
|
||||
// its order, and the survivors are grouped by directory when there is more
|
||||
// than one so sessions in the same repository sit together.
|
||||
val sessions = state.filteredSessions
|
||||
val groups = groupChatSessionsByDirectory(sessions)
|
||||
val query = state.sessionQuery
|
||||
|
||||
// A removal is reported for what it is: a local, undoable change, never a
|
||||
// pretend delete — the server is not asked to remove anything.
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
LaunchedEffect(state.lastRemoved) {
|
||||
if (state.lastRemoved != null &&
|
||||
snackbarHostState.showSnackbar(
|
||||
message = CHAT_REMOVED_MESSAGE,
|
||||
actionLabel = "Undo",
|
||||
duration = SnackbarDuration.Long,
|
||||
) == SnackbarResult.ActionPerformed
|
||||
) {
|
||||
vm.undoRemoveChat()
|
||||
}
|
||||
}
|
||||
var renaming by remember { mutableStateOf<ChatSession?>(null) }
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier,
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Chat") },
|
||||
actions = {
|
||||
ChatListSearchControl(query = query, onQuery = vm::setChatSessionQuery)
|
||||
IconButton(onClick = vm::refreshChatSessions) {
|
||||
Icon(Icons.Default.Refresh, contentDescription = "Refresh chats")
|
||||
}
|
||||
// The create path stays one tap away while the list is
|
||||
// narrowed: it is the same trailing action, never hidden.
|
||||
IconButton(onClick = vm::startNewChat) {
|
||||
Icon(Icons.Default.Add, contentDescription = "New chat")
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.fillMaxSize().padding(padding)) {
|
||||
if (state.open.isNotEmpty()) {
|
||||
OpenChatStrip(
|
||||
state = state,
|
||||
onSelect = vm::activateChat,
|
||||
onClose = vm::closeChat,
|
||||
)
|
||||
}
|
||||
if (!connected) {
|
||||
NotConnectedNotice()
|
||||
}
|
||||
when {
|
||||
state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…")
|
||||
state.sessionsError != null && state.sessions.isEmpty() -> {
|
||||
ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions)
|
||||
}
|
||||
sessions.isEmpty() && query.isNotBlank() -> EmptyState(
|
||||
// A narrowing that matches nothing says so plainly and offers
|
||||
// to clear it, the same empty-state pattern the other lists use.
|
||||
message = "No chats match \"${query.trim()}\".",
|
||||
actionLabel = "Clear search",
|
||||
onAction = { vm.setChatSessionQuery("") },
|
||||
)
|
||||
sessions.isEmpty() -> EmptyState(
|
||||
message = "No chat sessions on this server yet.",
|
||||
actionLabel = "New chat",
|
||||
onAction = vm::startNewChat,
|
||||
)
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
if (groups.size > 1) {
|
||||
// More than one directory: one section per repository so
|
||||
// same-directory chats sit together, each keeping the
|
||||
// recency order inside it.
|
||||
groups.forEach { group ->
|
||||
item(key = "dir-" + group.directory) { DirectoryHeader(group.directory) }
|
||||
items(group.sessions, key = { it.id }) { session ->
|
||||
SessionListItem(state, session, vm, onRename = { renaming = it })
|
||||
}
|
||||
}
|
||||
} else {
|
||||
items(sessions, key = { it.id }) { session ->
|
||||
SessionListItem(state, session, vm, onRename = { renaming = it })
|
||||
}
|
||||
}
|
||||
if (state.sessionsError != null) {
|
||||
item("error") {
|
||||
Text(
|
||||
text = state.sessionsError,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(CHAT_GUTTER),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
renaming?.let { session ->
|
||||
RenameChatDialog(
|
||||
session = session,
|
||||
onDismiss = { renaming = null },
|
||||
onConfirm = { title ->
|
||||
vm.renameChat(session.id, title)
|
||||
renaming = null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The session-list search control: the same top-bar filter-menu pattern the other
|
||||
* lists use, with one free-text field that narrows the list by title and directory
|
||||
* as the operator types. The active-count badge and the reset action report and
|
||||
* clear the narrowing, and the create action beside it is never hidden.
|
||||
*/
|
||||
@Composable
|
||||
private fun ChatListSearchControl(query: String, onQuery: (String) -> Unit) {
|
||||
FilterMenu(
|
||||
activeCount = if (query.isBlank()) 0 else 1,
|
||||
contentDescription = "Search chats",
|
||||
resetLabel = "Clear search",
|
||||
onReset = { onQuery("") },
|
||||
) {
|
||||
FilterSectionHeader("Search")
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = onQuery,
|
||||
label = { Text("Title or directory contains") },
|
||||
singleLine = true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = SPACING_M, vertical = SPACING_S),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One session of the list, whether it is rendered flat or inside a directory
|
||||
* section: [SessionRow] fed from the live [state], so the activity marks, the open
|
||||
* flag and the rename/remove actions are identical in both layouts.
|
||||
*/
|
||||
@Composable
|
||||
private fun SessionListItem(
|
||||
state: ChatState,
|
||||
session: ChatSession,
|
||||
vm: AppViewModel,
|
||||
onRename: (ChatSession) -> Unit,
|
||||
) {
|
||||
val thread = state.thread(session.id)
|
||||
SessionRow(
|
||||
session = session,
|
||||
open = thread != null,
|
||||
running = thread?.running == true,
|
||||
unseen = state.isUnseen(session),
|
||||
active = state.activeId == session.id,
|
||||
onClick = { vm.openChatSession(session) },
|
||||
onRename = { onRename(session) },
|
||||
onRemove = { vm.removeChat(session.id) },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The heading of one directory section. The directory is shown here as well as on
|
||||
* every row, so the grouping is legible even after a row scrolls out of view.
|
||||
*/
|
||||
@Composable
|
||||
private fun DirectoryHeader(directory: String) {
|
||||
Text(
|
||||
text = directory.ifBlank { NO_DIRECTORY_LABEL },
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
|
||||
/** The section heading for sessions the server reported without a directory. */
|
||||
private const val NO_DIRECTORY_LABEL = "No directory"
|
||||
|
||||
@Composable
|
||||
private fun SessionRow(
|
||||
session: ChatSession,
|
||||
open: Boolean,
|
||||
running: Boolean,
|
||||
unseen: Boolean,
|
||||
active: Boolean,
|
||||
onClick: () -> Unit,
|
||||
onRename: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
) {
|
||||
val texts = pipelinesText()
|
||||
val activity = sessionActivity(running, unseen)
|
||||
ListRow(selected = active, onClick = onClick) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = sessionTitle(session),
|
||||
style = texts.cardTitle,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// The kind chip names the session kind the server reported, so an
|
||||
// operator chat is tellable from anything run-related at a glance.
|
||||
sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
|
||||
// The activity badge is the new-activity signal; the tag and the
|
||||
// directory below are unchanged beside it.
|
||||
SessionActivityBadge(activity, open)
|
||||
SessionMenu(onRename = onRename, onRemove = onRemove)
|
||||
}
|
||||
val meta = buildList {
|
||||
add(sessionStatusLabel(session, running))
|
||||
if (session.directory.isNotBlank()) add(session.directory)
|
||||
if (session.model.isNotBlank()) add(session.model)
|
||||
}.joinToString(" · ")
|
||||
Text(text = meta, style = texts.meta, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/** A session row's management actions: rename and remove from this device's list. */
|
||||
@Composable
|
||||
private fun SessionMenu(onRename: () -> Unit, onRemove: () -> Unit) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
IconButton(onClick = { expanded = true }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
|
||||
Icon(
|
||||
Icons.Default.MoreVert,
|
||||
contentDescription = "Chat actions",
|
||||
modifier = Modifier.size(ICON_INLINE_DP),
|
||||
)
|
||||
}
|
||||
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Rename…") },
|
||||
onClick = {
|
||||
expanded = false
|
||||
onRename()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("Remove from list") },
|
||||
onClick = {
|
||||
expanded = false
|
||||
onRemove()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The rename dialog. The brokered protocol has no rename for a chat session, so
|
||||
* the dialog says plainly that the name is kept on this device rather than
|
||||
* implying the server was told.
|
||||
*/
|
||||
@Composable
|
||||
private fun RenameChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: (String) -> Unit) {
|
||||
var title by remember(session.id) { mutableStateOf(sessionTitle(session)) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Rename chat") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
OutlinedTextField(
|
||||
value = title,
|
||||
onValueChange = { title = it },
|
||||
singleLine = true,
|
||||
label = { Text("Name") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text(
|
||||
text = "The server has no rename for a chat, so this name is kept on this device.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onConfirm(title) }, enabled = title.isNotBlank()) { Text("Save") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
/** The removal report: what happened and how to undo it. */
|
||||
private const val CHAT_REMOVED_MESSAGE = "Removed from this list; the chat stays on the server."
|
||||
|
||||
/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */
|
||||
@Composable
|
||||
private fun SessionActivityBadge(activity: SessionActivity, open: Boolean) {
|
||||
val label = when (activity) {
|
||||
SessionActivity.STREAMING -> "Streaming"
|
||||
SessionActivity.UNSEEN -> "New"
|
||||
SessionActivity.IDLE -> if (open) "Open" else return
|
||||
}
|
||||
val color = when (activity) {
|
||||
SessionActivity.STREAMING -> MaterialTheme.colorScheme.tertiary
|
||||
SessionActivity.UNSEEN -> MaterialTheme.colorScheme.primary
|
||||
SessionActivity.IDLE -> MaterialTheme.colorScheme.outline
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color))
|
||||
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NotConnectedNotice() {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = "Not connected. Chats are served by the Pipelines server; connect in Settings.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PanTool
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.ui.theme.CHAT_TITLE_MAX_WIDTH_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
|
||||
|
||||
/**
|
||||
* The open-conversation switcher: one chip per open conversation, so several
|
||||
* chats can be kept at once and switched between in one tap. A running chat
|
||||
* carries its live dot, a chat waiting on an approval carries its hand, and the
|
||||
* X closes that chat (optional close is provided). [excludeSessionId] omits one
|
||||
* chat — the conversation pane omits its own active one, whose title already
|
||||
* stands in the app bar, while the session list shows every open chat.
|
||||
*/
|
||||
@Composable
|
||||
internal fun OpenChatStrip(
|
||||
state: ChatState,
|
||||
onSelect: (String) -> Unit,
|
||||
onClose: (String) -> Unit,
|
||||
excludeSessionId: String? = null,
|
||||
) {
|
||||
val threads = if (excludeSessionId == null) {
|
||||
state.open
|
||||
} else {
|
||||
openChatsBeside(state.open, excludeSessionId)
|
||||
}
|
||||
if (threads.isEmpty()) return
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
) {
|
||||
threads.forEach { thread ->
|
||||
val selected = state.activeId == thread.sessionId
|
||||
Surface(
|
||||
shape = RoundedCornerShape(50),
|
||||
color = if (selected) {
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceContainerHigh
|
||||
},
|
||||
modifier = Modifier
|
||||
.selectable(selected = selected, role = Role.Tab, onClick = { onSelect(thread.sessionId) }),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.padding(start = CHAT_ITEM_GAP + 4.dp, end = 2.dp, top = 4.dp, bottom = 4.dp),
|
||||
) {
|
||||
if (thread.running) {
|
||||
Box(
|
||||
Modifier.size(CHAT_STATUS_DOT).clip(CircleShape)
|
||||
.background(MaterialTheme.colorScheme.tertiary),
|
||||
)
|
||||
}
|
||||
if (approvalCard(thread.permission, thread.permissionAnswer)?.actionable == true) {
|
||||
// A request waiting on the operator is surfaced on the
|
||||
// chat's own chip, so it is findable without opening it.
|
||||
Icon(
|
||||
Icons.Default.PanTool,
|
||||
contentDescription = "Waiting for your approval",
|
||||
tint = MaterialTheme.colorScheme.tertiary,
|
||||
modifier = Modifier.size(ICON_STATUS_DP),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = thread.title.ifBlank { thread.sessionId.take(12) },
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.widthIn(max = CHAT_TITLE_MAX_WIDTH_DP),
|
||||
)
|
||||
IconButton(onClick = { onClose(thread.sessionId) }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Close chat ${thread.title}",
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,256 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Build
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntRect
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.ui.components.CodeBlock
|
||||
import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
|
||||
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
|
||||
import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP
|
||||
|
||||
/** The tool panel floats over the transcript; these bound its width and offsets. */
|
||||
|
||||
private val TOOL_PANEL_GAP = 4.dp
|
||||
private val TOOL_PANEL_MARGIN = 8.dp
|
||||
private val TOOL_PANEL_ELEVATION = 12.dp
|
||||
|
||||
/**
|
||||
* One turn's tool calls as a single group of compact chips, mirroring the
|
||||
* reference transcript's `_ToolCalls`/`_ToolChip` (research §1.3): each call
|
||||
* shows its name (or the edited file), its duration and a spinner while it runs,
|
||||
* and the chips of the turn wrap together on as few lines as they fit instead of
|
||||
* each taking a row.
|
||||
*
|
||||
* Tapping a chip opens its INPUT (pretty JSON) / OUTPUT (monospace) panel as an
|
||||
* overlay anchored to that chip (research §1.3 `_buildPanel`), dismissed by its
|
||||
* own X or by tapping outside. Because the panel is a popup and not part of the
|
||||
* transcript layout, opening or closing it never re-flows the conversation nor
|
||||
* moves its scroll position — the transcript stays exactly where the operator
|
||||
* left it.
|
||||
*
|
||||
* An `edit`-family call expands to a diff card (research §1.3 `_CodeRun` /
|
||||
* `_DiffView`): the `+N -M` stat on the chip and a green/red unified diff derived
|
||||
* from the arguments, since the brokered protocol carries no diff field. An
|
||||
* `error` call is visibly failed — an error-tinted chip and error icon — and its
|
||||
* panel shows the error text.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun ToolCalls(parts: List<ChatPart>) {
|
||||
// One id at a time: the reference shows a single panel, and a focusable popup
|
||||
// dismisses the previous one on open. No key is needed: an id that is no
|
||||
// longer among the calls simply matches nothing, so a streaming rebuild keeps
|
||||
// the panel the operator just opened without allocating a key list per frame.
|
||||
var openId by remember { mutableStateOf<String?>(null) }
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
) {
|
||||
parts.forEach { part ->
|
||||
ToolChip(
|
||||
part = part,
|
||||
expanded = openId == part.id,
|
||||
onToggle = { openId = if (openId == part.id) null else part.id },
|
||||
onDismiss = { openId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A compact tool-call chip: kind icon, label, diff stat, duration and chevron. */
|
||||
@Composable
|
||||
private fun ToolChip(part: ChatPart, expanded: Boolean, onToggle: () -> Unit, onDismiss: () -> Unit) {
|
||||
val running = ChatProtocol.toolRunning(part.state)
|
||||
val failed = toolFailed(part.state)
|
||||
val diff = toolEditDiff(part.state?.input)
|
||||
Box {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp),
|
||||
color = if (failed) {
|
||||
MaterialTheme.colorScheme.errorContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceContainerHigh
|
||||
},
|
||||
modifier = Modifier.clickable(onClick = onToggle),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP),
|
||||
) {
|
||||
if (running) {
|
||||
CircularProgressIndicator(Modifier.size(ICON_STATUS_DP), strokeWidth = 2.dp)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = when {
|
||||
failed -> Icons.Default.ErrorOutline
|
||||
diff != null -> Icons.Default.Edit
|
||||
else -> Icons.Default.Build
|
||||
},
|
||||
contentDescription = if (failed) "Failed tool call" else null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
diff?.let { DiffStat(it) }
|
||||
toolDurationMillis(part)?.let {
|
||||
Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Icon(
|
||||
imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
|
||||
contentDescription = if (expanded) "Collapse tool call" else "Expand tool call",
|
||||
modifier = Modifier.size(ICON_INLINE_DP),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (expanded) {
|
||||
Popup(
|
||||
popupPositionProvider = rememberToolPanelPositionProvider(),
|
||||
onDismissRequest = onDismiss,
|
||||
properties = PopupProperties(focusable = true),
|
||||
) {
|
||||
ToolPanel(part = part, onDismiss = onDismiss)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchors the tool panel just below its chip, or above it when there is no room
|
||||
* below, keeping it inside the window margins — the same flip the reference
|
||||
* panel does. Resolved in px, so it is independent of the current density.
|
||||
*/
|
||||
internal class ToolPanelPositionProvider(private val gapPx: Int, private val marginPx: Int) : PopupPositionProvider {
|
||||
override fun calculatePosition(
|
||||
anchorBounds: IntRect,
|
||||
windowSize: IntSize,
|
||||
layoutDirection: LayoutDirection,
|
||||
popupContentSize: IntSize,
|
||||
): IntOffset {
|
||||
val maxX = (windowSize.width - popupContentSize.width - marginPx).coerceAtLeast(marginPx)
|
||||
val x = anchorBounds.left.coerceIn(marginPx, maxX)
|
||||
val below = anchorBounds.bottom + gapPx
|
||||
val above = anchorBounds.top - popupContentSize.height - gapPx
|
||||
val maxY = (windowSize.height - popupContentSize.height - marginPx).coerceAtLeast(marginPx)
|
||||
val y = if (below <= maxY) below else above.coerceAtLeast(marginPx)
|
||||
return IntOffset(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun rememberToolPanelPositionProvider(): PopupPositionProvider {
|
||||
val density = LocalDensity.current
|
||||
return remember(density) {
|
||||
ToolPanelPositionProvider(
|
||||
gapPx = with(density) { TOOL_PANEL_GAP.roundToPx() },
|
||||
marginPx = with(density) { TOOL_PANEL_MARGIN.roundToPx() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The expanded panel of one tool call, mirroring the reference panel
|
||||
* (`_buildPanel`, research §1.3): a header naming the call and its duration with
|
||||
* a close X, then the pretty-printed INPUT and the monospace OUTPUT (or the
|
||||
* synthesised edit diff). Both content blocks carry the shared whole-block copy
|
||||
* action from [CodeBlock]. A failed call always renders its error text in an
|
||||
* ERROR block — even an edit-family call, whose diff is still shown alongside it.
|
||||
*/
|
||||
@Composable
|
||||
private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val diff = toolEditDiff(part.state?.input)
|
||||
val failed = toolFailed(part.state)
|
||||
Surface(
|
||||
shape = RoundedCornerShape(CHAT_ITEM_GAP),
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
shadowElevation = TOOL_PANEL_ELEVATION,
|
||||
modifier = modifier.widthIn(max = TOOL_PANEL_MAX_WIDTH_DP).fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
modifier = Modifier.fillMaxWidth().padding(CHAT_ITEM_GAP + 2.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
Icon(
|
||||
imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Text(
|
||||
text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
diff?.let { DiffStat(it) }
|
||||
toolDurationMillis(part)?.let {
|
||||
Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Close tool call", modifier = Modifier.size(16.dp))
|
||||
}
|
||||
}
|
||||
if (diff != null) {
|
||||
DiffView(diff)
|
||||
} else {
|
||||
CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input))
|
||||
}
|
||||
if (failed) {
|
||||
CodeBlock(label = "ERROR", text = toolErrorText(part.state))
|
||||
} else if (diff == null) {
|
||||
CodeBlock(label = "OUTPUT", text = toolOutputText(part.state))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.animateScrollBy
|
||||
import androidx.compose.foundation.gestures.scrollBy
|
||||
import androidx.compose.foundation.interaction.DragInteraction
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SmallFloatingActionButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.minimumInteractiveComponentSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.launch
|
||||
import net.awan.pipelines.data.protocol.ChatMessage
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.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.SPACING_XS
|
||||
|
||||
/** The running indicator's elapsed time ticks once a second, never per frame. */
|
||||
private const val CHAT_ELAPSED_TICK_MILLIS = 1_000L
|
||||
|
||||
/**
|
||||
* The bottom-anchored transcript: content is packed to the bottom (so a short or
|
||||
* freshly opened chat sits against the composer) and the running indicator sits
|
||||
* at the newest end while a turn is in flight.
|
||||
*
|
||||
* The transcript has one scroll path ([scrollToEnd] / [closeBottomGap]) and one
|
||||
* decision for whether it follows new content. It opens at the newest message
|
||||
* (placed by the pane's initial position, with any part of a last message taller
|
||||
* than the viewport closed instantly here), and then — while the operator intends
|
||||
* to read the newest part — every arrival (a message, a streamed delta, a tool
|
||||
* chip, a grown composer or the appearing keyboard) is followed smoothly, so the
|
||||
* newest content stays in view. An item that arrives entirely below the fold is
|
||||
* brought in rather than left there. A freshly arrived approval card is followed
|
||||
* the same way. Once the operator has scrolled up to read history nothing moves
|
||||
* under them, and the jump-to-latest affordance is offered instead.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ChatTranscript(
|
||||
thread: ChatThread,
|
||||
listState: LazyListState,
|
||||
savedScroll: ChatScrollPosition?,
|
||||
itemCount: Int,
|
||||
approval: ApprovalCard?,
|
||||
showRunning: Boolean,
|
||||
reasoning: ReasoningExpansion,
|
||||
onToggleReasoning: (String) -> Unit,
|
||||
onDecision: (String) -> Unit,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val density = LocalDensity.current
|
||||
val thresholdPx = remember(density) { with(density) { CHAT_FOLLOW_THRESHOLD_DP.roundToPx() } }
|
||||
// The transcript's item count, read at use time: the drag collector and the
|
||||
// derived state below outlive any single recomposition, so a count captured
|
||||
// when they were created would go stale as messages arrive and the follow
|
||||
// would measure against how many items there used to be.
|
||||
val currentItemCount by rememberUpdatedState(itemCount)
|
||||
// Whether the operator wants the newest content kept in view. Only their own
|
||||
// drag changes it — a programmatic scroll never touches the list's
|
||||
// interactionSource, so it cannot un-stick the view — and a drag that settles
|
||||
// at (or within the threshold of) the bottom resumes the follow. Its real
|
||||
// value is settled once the transcript is placed, when the live distance to
|
||||
// the bottom is known.
|
||||
// Saved, so a rotation or process death while the operator is reading history
|
||||
// restores "not following" too, rather than the restored transcript being
|
||||
// yanked to the bottom by the placement the new composition would otherwise run.
|
||||
var following by rememberSaveable(thread.sessionId) { mutableStateOf(true) }
|
||||
LaunchedEffect(listState, thresholdPx) {
|
||||
listState.interactionSource.interactions.collect { interaction ->
|
||||
when (interaction) {
|
||||
is DragInteraction.Start -> following = false
|
||||
is DragInteraction.Stop, is DragInteraction.Cancel ->
|
||||
following = chatFollowsAt(
|
||||
distanceFromBottomPx = listState.bottomDistancePx(currentItemCount),
|
||||
thresholdPx = thresholdPx,
|
||||
itemCount = currentItemCount,
|
||||
)
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
// The distance to the transcript's end, read through a derived state so the
|
||||
// affordance's visibility is recomputed only when it actually changes rather
|
||||
// than on every scrolled pixel. The item count is read through
|
||||
// [currentItemCount] so the derived value also recomputes as content arrives.
|
||||
val showJumpToLatest by remember(listState, thresholdPx) {
|
||||
derivedStateOf {
|
||||
chatShowJumpToLatest(
|
||||
following = following,
|
||||
distanceFromBottomPx = listState.bottomDistancePx(currentItemCount),
|
||||
thresholdPx = thresholdPx,
|
||||
itemCount = currentItemCount,
|
||||
)
|
||||
}
|
||||
}
|
||||
// The transcript is placed once, when it first has content, and only after it
|
||||
// has been measured; the viewport height is an input too, so a grown composer
|
||||
// or the appearing keyboard re-follows rather than leaving the newest message
|
||||
// hidden behind it. Placement itself is saved, so restoring a rotation does not
|
||||
// re-place (and re-follow) a transcript the operator had scrolled up.
|
||||
var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) }
|
||||
val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } }
|
||||
LaunchedEffect(thread.messages, thread.running, approval?.requestId, viewportHeight) {
|
||||
if (itemCount <= 0) return@LaunchedEffect
|
||||
if (!placed) {
|
||||
// Wait for the first measure: placement run before it would no-op and
|
||||
// leave the first display to the measured re-run, which animates, and
|
||||
// the first display must not animate.
|
||||
if (viewportHeight <= 0) return@LaunchedEffect
|
||||
placed = true
|
||||
if (chatOpensAtNewest(savedScroll)) {
|
||||
// No position of the operator's own: bring the newest item fully
|
||||
// into view, instantly — the first display must not animate — and
|
||||
// through the same path the follow uses, so placement and follow
|
||||
// cannot disagree about what the newest item is (a last message
|
||||
// taller than the viewport has its below-the-fold part closed by
|
||||
// the same call), then follow.
|
||||
listState.scrollToEnd(itemCount, animated = false)
|
||||
following = true
|
||||
} else {
|
||||
// A position the operator left: follow only if it was the bottom, so
|
||||
// returning to a chat never yanks the view.
|
||||
following = chatFollowsAt(listState.bottomDistancePx(itemCount), thresholdPx, itemCount)
|
||||
}
|
||||
return@LaunchedEffect
|
||||
}
|
||||
if (following) listState.scrollToEnd(itemCount, animated = true)
|
||||
}
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
// Only the newest turn can be streaming, so its reasoning wears the live
|
||||
// label; a settled turn's reasoning is labelled as settled.
|
||||
val streamingMessageId = thread.messages.lastOrNull()?.id?.takeIf { thread.running }
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom),
|
||||
) {
|
||||
items(thread.messages, key = { it.id }) { message ->
|
||||
MessageItem(
|
||||
message = message,
|
||||
reasoning = reasoning,
|
||||
streaming = message.id == streamingMessageId,
|
||||
onToggleReasoning = onToggleReasoning,
|
||||
)
|
||||
}
|
||||
if (showRunning) {
|
||||
item(key = "pending") { RunningIndicator(thread) }
|
||||
}
|
||||
if (approval != null) {
|
||||
// Keyed by request id so switching between requests swaps the card
|
||||
// instead of reusing the previous one's state.
|
||||
item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) }
|
||||
}
|
||||
}
|
||||
// Offered only once the transcript is placed and the operator has left the
|
||||
// bottom, so it never covers the newest content it would return to.
|
||||
if (placed && showJumpToLatest) {
|
||||
SmallFloatingActionButton(
|
||||
onClick = {
|
||||
following = true
|
||||
scope.launch { listState.scrollToEnd(itemCount, animated = true) }
|
||||
},
|
||||
modifier = Modifier.align(Alignment.BottomEnd).padding(CHAT_GUTTER),
|
||||
) {
|
||||
Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Jump to latest")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript's one scroll path, shared by the first placement, the follow,
|
||||
* the app-bar approval jump and the jump-to-latest affordance. The newest item is
|
||||
* brought into view when it sits entirely below the fold — an item appended past
|
||||
* the viewport's edge, so no pixel of it is on screen and the remaining distance
|
||||
* cannot be measured — and any part of it still below the fold (a message taller
|
||||
* than the viewport) is then closed by exactly that distance. An item that is
|
||||
* already partly visible is only gap-closed, never moved up first. [animated] is
|
||||
* false only for the first placement, which must not animate.
|
||||
*
|
||||
* [itemCount] is the transcript's *content* count, which can be ahead of the
|
||||
* layout's: an appended item exists in the content before the recomposition that
|
||||
* measures it, and the effect that follows it is dispatched ahead of that measure,
|
||||
* so the layout still describes the previous items and its own last visible item
|
||||
* reads as the end. Measuring against [itemCount] — see [bottomDistancePx] — is
|
||||
* what stops an appended item from being mistaken for the already-visible end and
|
||||
* left below the fold: it has no pixel on screen, so it is unknown-distance and is
|
||||
* brought into view rather than gap-closed at zero.
|
||||
*/
|
||||
internal suspend fun LazyListState.scrollToEnd(itemCount: Int, animated: Boolean) {
|
||||
if (itemCount <= 0) return
|
||||
if (bottomDistancePx(itemCount) == null) {
|
||||
if (animated) animateScrollToItem(itemCount - 1) else scrollToItem(itemCount - 1)
|
||||
}
|
||||
closeBottomGap(itemCount, animated)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolls the transcript's end into view by exactly the distance it sits below
|
||||
* the viewport, measured against the same [itemCount] the decisions above use.
|
||||
*/
|
||||
private suspend fun LazyListState.closeBottomGap(itemCount: Int, animated: Boolean) {
|
||||
val remaining = bottomDistancePx(itemCount) ?: return
|
||||
if (remaining <= 0) return
|
||||
if (animated) animateScrollBy(remaining.toFloat()) else scrollBy(remaining.toFloat())
|
||||
}
|
||||
|
||||
/**
|
||||
* The distance from the transcript's end to the viewport's bottom, measured
|
||||
* against [itemCount] — the transcript's *content* count, not the layout's. The
|
||||
* two differ on the frame content arrives: the layout still describes the
|
||||
* previous items, so its own last visible item reads as the end and the appended
|
||||
* item's absence is invisible. Measuring against the content count makes the
|
||||
* appended item read exactly as [chatBottomDistancePx] defines it — no pixel on
|
||||
* screen — so the scroll path above brings it into view rather than trusting a
|
||||
* stale layout's "already at the end". [itemCount] is what the transcript
|
||||
* renders, so the two counts agree as soon as the layout catches up.
|
||||
*/
|
||||
private fun LazyListState.bottomDistancePx(itemCount: Int): Int? {
|
||||
val info = layoutInfo
|
||||
val last = info.visibleItemsInfo.lastOrNull()
|
||||
return chatBottomDistancePx(
|
||||
lastVisibleIndex = last?.index ?: -1,
|
||||
lastVisibleEndPx = last?.let { it.offset + it.size } ?: 0,
|
||||
itemCount = itemCount,
|
||||
viewportEndPx = info.viewportEndOffset,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-flight turn indicator: a spinner, `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.
|
||||
*/
|
||||
@Composable
|
||||
private fun RunningIndicator(thread: ChatThread) {
|
||||
val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
|
||||
) {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wall clock, re-read once a second while a turn is in flight, so the
|
||||
* indicator derives the elapsed time with [ChatThread.elapsedMillis] — the one
|
||||
* derivation its unit test also shares — instead of subtracting the turn's start
|
||||
* itself. Keyed on [runningSince] and only entered for a live turn, so a settled
|
||||
* chat schedules nothing.
|
||||
*/
|
||||
@Composable
|
||||
private fun rememberElapsedNow(runningSince: Long): Long {
|
||||
var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(runningSince) {
|
||||
if (runningSince <= 0) return@LaunchedEffect
|
||||
while (true) {
|
||||
nowMillis = System.currentTimeMillis()
|
||||
delay(CHAT_ELAPSED_TICK_MILLIS)
|
||||
}
|
||||
}
|
||||
return nowMillis
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MessageItem(
|
||||
message: ChatMessage,
|
||||
reasoning: ReasoningExpansion,
|
||||
streaming: Boolean,
|
||||
onToggleReasoning: (String) -> Unit,
|
||||
) {
|
||||
val isUser = message.role == ChatProtocol.ROLE_USER
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(CHAT_GUTTER),
|
||||
color = if (isUser) {
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceContainer
|
||||
},
|
||||
modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP),
|
||||
) {
|
||||
SelectionContainer {
|
||||
Column(Modifier.padding(CHAT_GUTTER)) {
|
||||
if (isUser) {
|
||||
UserParts(message.parts)
|
||||
} else {
|
||||
AssistantParts(
|
||||
messageId = message.id,
|
||||
parts = message.parts,
|
||||
reasoning = reasoning,
|
||||
streaming = streaming,
|
||||
onToggleReasoning = onToggleReasoning,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A user turn: its text, then the files that rode with it. The attachments are
|
||||
* the same [ChatProtocol.PART_FILE] parts [MessageItem] already renders, so the
|
||||
* sent message shows its file in the transcript through the one display path
|
||||
* rather than a second attachment list under the bubble.
|
||||
*/
|
||||
@Composable
|
||||
private fun UserParts(parts: List<ChatPart>) {
|
||||
val text = parts.filter { it.type == ChatProtocol.PART_TEXT || it.type.isBlank() }
|
||||
.joinToString("\n") { it.text }
|
||||
.trim()
|
||||
val files = parts.filter { it.type == ChatProtocol.PART_FILE }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
if (text.isNotBlank()) Text(text, style = MaterialTheme.typography.bodyMedium)
|
||||
files.forEach { FilePart(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An assistant turn's parts in order, with each run of consecutive tool calls
|
||||
* rendered as one wrapping chip group (mirroring the reference transcript's
|
||||
* `_ToolCalls`, research §1.3): the calls of a turn sit together on as few lines
|
||||
* as they fit, instead of each taking a row, so the transcript stays scannable.
|
||||
*/
|
||||
@Composable
|
||||
private fun AssistantParts(
|
||||
messageId: String,
|
||||
parts: List<ChatPart>,
|
||||
reasoning: ReasoningExpansion,
|
||||
streaming: Boolean,
|
||||
onToggleReasoning: (String) -> Unit,
|
||||
) {
|
||||
var index = 0
|
||||
while (index < parts.size) {
|
||||
if (parts[index].type == ChatProtocol.PART_TOOL) {
|
||||
var end = index
|
||||
while (end < parts.size && parts[end].type == ChatProtocol.PART_TOOL) end++
|
||||
ToolCalls(parts.subList(index, end))
|
||||
index = end
|
||||
} else {
|
||||
val part = parts[index]
|
||||
MessagePart(
|
||||
part = part,
|
||||
reasoningKey = reasoningKey(messageId, part, index),
|
||||
reasoning = reasoning,
|
||||
streaming = streaming,
|
||||
onToggleReasoning = onToggleReasoning,
|
||||
)
|
||||
index++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MessagePart(
|
||||
part: ChatPart,
|
||||
reasoningKey: String,
|
||||
reasoning: ReasoningExpansion,
|
||||
streaming: Boolean,
|
||||
onToggleReasoning: (String) -> Unit,
|
||||
) {
|
||||
when (partRendering(part)) {
|
||||
PartRendering.MARKDOWN -> MarkdownText(part.text)
|
||||
PartRendering.REASONING -> ReasoningBlock(
|
||||
text = part.text,
|
||||
expanded = reasoning.isExpanded(reasoningKey),
|
||||
streaming = streaming,
|
||||
onToggle = { onToggleReasoning(reasoningKey) },
|
||||
)
|
||||
PartRendering.PLAIN -> Text(part.text, style = MaterialTheme.typography.bodyMedium)
|
||||
PartRendering.HIDDEN -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reasoning is visually secondary and collapsed by default: one compact, muted
|
||||
* line per part (its spinner-free label names the state; the live label is
|
||||
* `Thinking…`) that expands on tap to the full, still-muted text. The expansion
|
||||
* state lives on the conversation, so it survives the transcript disposing the
|
||||
* item while the operator scrolls and a streaming part keeps its state as
|
||||
* deltas arrive.
|
||||
*/
|
||||
@Composable
|
||||
private fun ReasoningBlock(
|
||||
text: String,
|
||||
expanded: Boolean,
|
||||
streaming: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
) {
|
||||
if (text.isBlank()) return
|
||||
val label = if (streaming) REASONING_STREAMING_LABEL else REASONING_SETTLED_LABEL
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.minimumInteractiveComponentSize()
|
||||
.clickable(role = Role.Button, onClick = onToggle)
|
||||
.padding(vertical = SPACING_XS),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Psychology,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(ICON_INLINE_DP),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Icon(
|
||||
imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
|
||||
contentDescription = if (expanded) "Hide reasoning" else "Show reasoning",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(ICON_INLINE_DP),
|
||||
)
|
||||
}
|
||||
if (expanded) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Default),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = ICON_INLINE_DP + CHAT_ITEM_GAP, bottom = CHAT_ITEM_GAP),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The live and settled labels of a reasoning part's one collapsed line. */
|
||||
private const val REASONING_STREAMING_LABEL = "Thinking…"
|
||||
private const val REASONING_SETTLED_LABEL = "Reasoning"
|
||||
@@ -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"))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package net.awan.pipelines.ui
|
||||
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -52,6 +53,44 @@ class PipelinesNavTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePillStandsDownOnlyWhileAConversationIsOpen() {
|
||||
// An open conversation (the chat transcript and composer) hides the pill;
|
||||
// the chat list keeps it, and so does every other destination.
|
||||
assertFalse(destinationPillVisible("chat", conversationOpen = true))
|
||||
assertTrue(destinationPillVisible("chat", conversationOpen = false))
|
||||
for (route in listOf("pipelines", "templates", "runs", "settings", null)) {
|
||||
assertTrue(destinationPillVisible(route, conversationOpen = false))
|
||||
}
|
||||
// A conversation only exists on the chat route; even if the flag were set
|
||||
// elsewhere the pill stays, so a background chat never hides it.
|
||||
assertTrue(destinationPillVisible("runs", conversationOpen = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theReserveTracksTheDrawnPillSoContentNeitherJumpsNorLeavesAGap() {
|
||||
// Drawn: content reserves the named pill space and clears it. Hidden: no
|
||||
// reservation, so there is no empty band where the pill used to be.
|
||||
assertDp(DESTINATION_PILL_RESERVE.value, destinationPillReserve(pillVisible = true))
|
||||
assertDp(0f, destinationPillReserve(pillVisible = false))
|
||||
// One predicate drives both, so the space can never disagree with the
|
||||
// pill: reserved exactly when drawn, gone exactly when hidden.
|
||||
for (route in listOf("pipelines", "chat", "runs", "settings", null)) {
|
||||
for (open in listOf(false, true)) {
|
||||
val drawn = destinationPillVisible(route, open)
|
||||
val reserve = destinationPillReserve(drawn)
|
||||
assertTrue(
|
||||
"reserve held behind a hidden pill on $route (open=$open)",
|
||||
drawn || reserve.value == 0f,
|
||||
)
|
||||
assertTrue(
|
||||
"content not cleared of a drawn pill on $route (open=$open)",
|
||||
!drawn || reserve.value == DESTINATION_PILL_RESERVE.value,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertDp(expected: Float, actual: Dp) =
|
||||
assertEquals(expected, actual.value, 0.01f)
|
||||
}
|
||||
|
||||
+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