feat(app): add the pure native attention model
Port the browser's Needs-you list, dismissal bookkeeping and attention
transition ledger as widget-free Dart under lib/features/attention/domain/.
Includes the local-day window, export-wait exclusion, {runId}:{kind}
identities, sorted dismissal storage and focused regressions.
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/// The local storage key shared with the browser client: one JSON array of
|
||||
/// `{runId}:{kind}` strings. A stored dismissal itself never expires; the
|
||||
/// surface's local-day window is applied when entries are read, not here.
|
||||
const attentionStorageKey = 'pipelines.web.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.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 diagnostic = '${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);
|
||||
|
||||
/// 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);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'attention_models.dart';
|
||||
|
||||
/// One newly-entered attention state: a run that has just become failed or has
|
||||
/// just become a human decision. The entry carries the whole current summary, so
|
||||
/// its wording and unknown fields match what the surface would show.
|
||||
class AttentionTransition {
|
||||
const AttentionTransition(this.entry);
|
||||
|
||||
final AttentionEntry entry;
|
||||
|
||||
int get runId => entry.runId;
|
||||
AttentionKind get kind => entry.kind;
|
||||
String get key => entry.key;
|
||||
JsonMap get run => entry.run;
|
||||
}
|
||||
|
||||
/// Tracks the last status seen for each run and emits only a genuine transition
|
||||
/// *into* a qualifying state.
|
||||
///
|
||||
/// - [seed] records the authoritative list (the initial `list_runs` read or a
|
||||
/// `subscribe` snapshot) without emitting anything, so a run that was already
|
||||
/// failed/waiting before this client looked never announces itself.
|
||||
/// - [beginSeed]/[endSeed] bracket a reconnect's pushed snapshot: frames seen
|
||||
/// while seeding update the baseline but raise nothing, so a gap can never
|
||||
/// manufacture a transition.
|
||||
/// - [observe] emits only when a known run's status changes into `failed` or a
|
||||
/// human `waiting`. A duplicate frame, an unchanged qualifying state, an
|
||||
/// unknown/nonqualifying status and a first-seen run all return null.
|
||||
/// - A run+kind key is forgotten when the run leaves that qualifying state (or
|
||||
/// enters the other kind), so a genuinely new transition can fire once more;
|
||||
/// the same transition can never repeat.
|
||||
/// - [resetForReconnect] drops the status baseline but keeps the emitted keys.
|
||||
/// The following [reseed] establishes the new baseline without emitting, so a
|
||||
/// disconnect cannot produce a delayed notification for a state the operator
|
||||
/// already saw.
|
||||
class AttentionTransitionDetector {
|
||||
final Map<int, String> _lastStatus = {};
|
||||
final Set<String> _emitted = {};
|
||||
bool _seeding = false;
|
||||
|
||||
/// Records [runs] as the baseline without emitting. Keys that still qualify
|
||||
/// are kept so a reconnect cannot repeat them; keys whose run disappeared from
|
||||
/// the read are kept too, because an absent run tells us nothing.
|
||||
void seed(Iterable<JsonMap>? runs) {
|
||||
final statuses = <int, String>{};
|
||||
final kinds = <int, AttentionKind?>{};
|
||||
for (final run in runs ?? const <JsonMap>[]) {
|
||||
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
|
||||
if (runId == null) continue;
|
||||
statuses[runId] = _word(run['status']);
|
||||
kinds[runId] = attentionKindForRun(run);
|
||||
}
|
||||
_lastStatus
|
||||
..clear()
|
||||
..addAll(statuses);
|
||||
for (final key in [..._emitted]) {
|
||||
final split = key.lastIndexOf(':');
|
||||
if (split <= 0) continue;
|
||||
final runId = attentionRunId(key.substring(0, split));
|
||||
if (runId == null || !statuses.containsKey(runId)) continue;
|
||||
final kind = kinds[runId];
|
||||
if (kind == null || key != attentionKey(runId, kind)) {
|
||||
_emitted.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the baseline for a reconnect. Emitted keys survive: a transition
|
||||
/// swallowed by the gap is not replayed after the socket returns.
|
||||
void reseed(Iterable<JsonMap>? runs) {
|
||||
_lastStatus.clear();
|
||||
_seeding = false;
|
||||
seed(runs);
|
||||
}
|
||||
|
||||
/// Drops the status baseline but keeps this session's emitted keys. Call
|
||||
/// before the next [seed] when the connection is lost.
|
||||
void resetForReconnect() {
|
||||
_lastStatus.clear();
|
||||
_seeding = false;
|
||||
}
|
||||
|
||||
void beginSeed() => _seeding = true;
|
||||
|
||||
void endSeed() => _seeding = false;
|
||||
|
||||
/// Observes one pushed `run_event` summary/frame. Returns the transition only
|
||||
/// when this run enters a qualifying state; [dismissed] identities are marked
|
||||
/// seen but do not emit.
|
||||
AttentionTransition? observe(
|
||||
JsonMap frame, {
|
||||
Set<String> dismissed = const {},
|
||||
}) {
|
||||
final runId =
|
||||
attentionRunId(frame['run_id']) ?? attentionRunId(frame['id']);
|
||||
final status = _word(frame['status']);
|
||||
if (runId == null || status.isEmpty) return null;
|
||||
|
||||
final previous = _lastStatus[runId];
|
||||
_lastStatus[runId] = status;
|
||||
|
||||
final kind = attentionKindForRun(frame);
|
||||
if (kind == null) {
|
||||
_forget(runId);
|
||||
return null;
|
||||
}
|
||||
for (final other in AttentionKind.values) {
|
||||
if (other != kind) _emitted.remove(attentionKey(runId, other));
|
||||
}
|
||||
if (_seeding) return null;
|
||||
|
||||
final key = attentionKey(runId, kind);
|
||||
if (previous == null || previous == status) return null;
|
||||
|
||||
final entry = attentionEntryFor(frame);
|
||||
if (entry == null) return null;
|
||||
_emitted.add(key);
|
||||
if (dismissed.contains(key)) return null;
|
||||
return AttentionTransition(entry);
|
||||
}
|
||||
|
||||
/// A copy of the run+kind identities raised in this session.
|
||||
Set<String> get emittedKeys => {..._emitted};
|
||||
|
||||
/// The last status recorded for [runId], or null for a run never seen.
|
||||
String? statusOf(int runId) => _lastStatus[runId];
|
||||
|
||||
void _forget(int runId) {
|
||||
for (final kind in AttentionKind.values) {
|
||||
_emitted.remove(attentionKey(runId, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
|
||||
Reference in New Issue
Block a user