Files
pipelines/app/lib/features/attention/domain/attention_models.dart
T
alan 767643d991 Open the run's artifact from notifications
Phone and browser notifications that carry an artifact open it full
screen in the artifact viewer, with an Open run action and the preview as
expanded text; pipelines://artifact deep links route to the viewer.
2026-11-12 18:56:26 +00:00

263 lines
9.9 KiB
Dart

import 'dart:convert';
import '../../../core/api_gateway.dart';
/// The two things the attention surface ranks, most important first. The rank
/// orders the list; the wire name is what a dismissal identity is keyed by.
///
/// This mirrors the browser's pure `web/src/attention.js` model: only a run
/// parked on a person ([AttentionKind.decision]) and a failed run
/// ([AttentionKind.failed]) need the operator. A waiting run that is really an
/// audit/export handoff asks nobody, so it is excluded by [attentionKindForRun].
enum AttentionKind {
decision(0, 'Decision'),
failed(1, 'Failed');
const AttentionKind(this.rank, this.wireName);
final int rank;
/// The spelling used in a persisted `{runId}:{kind}` identity.
final String wireName;
}
/// This client's own storage key, namespaced like the rest of the app
/// (`pipelines.next.*`). The identity format matches the browser's, but a
/// dismissal set is deliberately not shared with the legacy web app: the two
/// clients must never rewrite each other's local state on a shared origin.
const attentionStorageKey = 'pipelines.next.attention.v1';
/// The run id a summary or pushed frame carries, or null when it is malformed.
/// The server ids are positive integers; anything else cannot identify an entry.
int? attentionRunId(dynamic value) {
final id = value is num
? (value.isFinite ? value.toInt() : null)
: int.tryParse('${value ?? ''}'.trim());
return id != null && id > 0 ? id : null;
}
/// The attention kind a server status word maps to. Only the server's own
/// `waiting` and `failed` words qualify; queued, running, succeeded, canceled,
/// interrupted and unknown words ask nobody. A waiting run's *reason* is
/// checked by [attentionKindForRun], because the status word alone cannot tell a
/// human decision from an export handoff.
AttentionKind? attentionKindOf(dynamic status) {
switch (_word(status)) {
case 'waiting':
return AttentionKind.decision;
case 'failed':
return AttentionKind.failed;
default:
return null;
}
}
/// The attention kind a complete run summary maps to, or null when it asks
/// nobody.
///
/// A `waiting` run is listed only when it is actually waiting on a person. It is
/// not a Decision when the server recorded a session audit/export handoff
/// (`export_pending_sequence > 0`), so a machine export wait never reaches the
/// operator's "Needs you" list.
///
/// `resource_wait` is deliberately not consulted, matching `web/src/attention.js`
/// and the Android client: it was retired server-side, and a stale value carried
/// onto a waiting run must not hide a genuine human decision.
AttentionKind? attentionKindForRun(JsonMap run) {
final kind = attentionKindOf(run['status']);
if (kind == AttentionKind.failed &&
_word(run['failure_kind']) == 'expected') {
return null;
}
if (kind != AttentionKind.decision) return kind;
if (_positive(run['export_pending_sequence'])) return null;
return kind;
}
/// The identity of one run+kind entry; the unit an explicit dismissal removes.
String attentionKey(int runId, AttentionKind kind) => '$runId:${kind.wireName}';
/// 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.
String attentionDetail(AttentionKind kind, JsonMap run) {
if (kind == AttentionKind.decision) return 'Waiting for your decision';
final failureReason = '${run['failure_reason'] ?? ''}'.trim();
final diagnostic = failureReason.isNotEmpty
? failureReason
: '${run['diagnostic'] ?? ''}'.trim();
return diagnostic.isNotEmpty ? diagnostic : 'Run failed';
}
/// The one-line secondary text for a row: `{pipeline} · {detail}`.
String attentionRowDescription(AttentionEntry entry) =>
'${entry.pipeline} · ${entry.detail}';
/// The bell action's accessible name: the bare `Notifications` when nothing
/// needs the operator, else the count.
String attentionBadgeLabel(int count) =>
count > 0 ? 'Notifications, $count needing attention' : 'Notifications';
/// One run that needs the operator.
///
/// The original summary map is kept whole, so fields this model does not read —
/// or fields a newer server adds — remain available to the caller unchanged.
/// Only [attentionEntryFor] constructs an entry, so [runId] is always a validated
/// positive server id rather than a getter that could throw.
class AttentionEntry {
const AttentionEntry._({
required this.run,
required this.kind,
required this.runId,
});
final JsonMap run;
final AttentionKind kind;
final int runId;
String get pipeline => '${run['name'] ?? ''}';
String get detail => attentionDetail(kind, run);
String get key => attentionKey(runId, kind);
/// Notification metadata attached by newer servers, when present on the
/// run-event summary. Kept optional so older frames retain today's behavior.
dynamic get notificationArtifact => run['artifact'];
String? get notificationPreview {
final value = run['preview'];
return value is String && value.isNotEmpty ? value : null;
}
/// The trimmed title else the pipeline label.
String get label {
final title = '${run['title'] ?? ''}'.trim();
return title.isNotEmpty ? title : pipeline;
}
/// The run's own recency, used only for ordering equal kinds newest-first.
/// A finished run is ordered by `finished_at`; a still-waiting one by its
/// creation time.
String get recency {
final finished = '${run['finished_at'] ?? ''}';
return finished.trim().isNotEmpty ? finished : '${run['created_at'] ?? ''}';
}
}
/// The entry for one qualifying run, or null when it asks nobody.
AttentionEntry? attentionEntryFor(JsonMap run) {
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
final kind = attentionKindForRun(run);
if (runId == null || kind == null) return null;
return AttentionEntry._(run: run, kind: kind, runId: runId);
}
/// The start of the operator's local day. "Needs you" is a to-do list for what
/// changed now, so callers pass this as [attentionEntries]' `since`; yesterday's
/// failures are history, not a badge that follows every device for ever. Inject
/// [now] for a deterministic test; production callers pass nothing.
DateTime startOfLocalDay({DateTime? now}) {
final local = (now ?? DateTime.now()).toLocal();
return DateTime(local.year, local.month, local.day);
}
/// The ordered attention list: one entry per qualifying run, minus any identity
/// the operator explicitly dismissed and minus work older than [since].
///
/// Order matches the browser: kind rank (Decision before Failed), then recency
/// descending (the server's timestamp text, `finished_at` else `created_at`),
/// then run id descending so equal rows never reshuffle between reads.
///
/// [since] is the local-day cutoff ([startOfLocalDay]) the bell, the sheet and
/// Clear all pass. As in `web/src/attention.js`, the cutoff applies only when the
/// entry's recency parses as a timestamp; a blank or unreadable recency is kept.
/// A null or epoch-zero cutoff shows everything.
List<AttentionEntry> attentionEntries(
Iterable<JsonMap>? runs, {
Set<String> dismissed = const {},
DateTime? since,
}) {
final entries = <AttentionEntry>[];
for (final run in runs ?? const <JsonMap>[]) {
final entry = attentionEntryFor(run);
if (entry == null || dismissed.contains(entry.key)) continue;
if (since != null &&
since.millisecondsSinceEpoch > 0 &&
_before(entry.recency, since)) {
continue;
}
entries.add(entry);
}
entries.sort((a, b) {
final rank = a.kind.rank.compareTo(b.kind.rank);
if (rank != 0) return rank;
final recency = b.recency.compareTo(a.recency);
return recency != 0 ? recency : b.runId.compareTo(a.runId);
});
return entries;
}
/// Captures what the surface showed when it opened. Clear all acts on this
/// snapshot, so an entry that arrives later is not silently removed.
List<AttentionEntry> attentionDismissalSnapshot(
Iterable<AttentionEntry> entries,
) => List<AttentionEntry>.unmodifiable(entries);
/// Adds one identity, ignoring a blank or already-present key.
Set<String> attentionDismiss(Set<String> dismissed, String key) {
final next = {...dismissed};
if (key.trim().isNotEmpty) next.add(key);
return next;
}
/// Unions exactly the snapshot's identities. Entries that arrived after the
/// snapshot was taken are left alone.
Set<String> attentionDismissAll(
Set<String> dismissed,
Iterable<AttentionEntry> snapshot,
) {
final next = {...dismissed};
for (final entry in snapshot) {
next.add(entry.key);
}
return next;
}
/// The one-line JSON a dismissed set is stored as: a sorted array of strings, so
/// an unchanged set always encodes to the same bytes.
String encodeAttentionDismissals(Set<String> dismissed) {
final keys = dismissed.where((key) => key.isNotEmpty).toList()..sort();
return jsonEncode(keys);
}
/// Decodes a stored value into a dismissed set. Total: blank text, unreadable
/// JSON, a non-array value and non-string members all decode to the members we
/// can read, and a malformed value never throws.
Set<String> decodeAttentionDismissals(String? stored) {
final text = (stored ?? '').trim();
if (text.isEmpty) return <String>{};
dynamic parsed;
try {
parsed = jsonDecode(text);
} catch (_) {
return <String>{};
}
if (parsed is! List) return <String>{};
return {
for (final value in parsed)
if (value is String && value.isNotEmpty) value,
};
}
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
bool _positive(dynamic value) {
final number = value is num ? value : num.tryParse('${value ?? ''}'.trim());
return (number ?? 0) > 0;
}
/// True only when [recency] is a readable timestamp before [cutoff]. An
/// unparseable or blank timestamp is not filtered out, matching the browser.
bool _before(String recency, DateTime cutoff) {
final at = DateTime.tryParse(recency.trim());
return at != null && at.isBefore(cutoff);
}