merge(app): land pure Needs you attention model

This commit is contained in:
2026-10-21 22:17:23 +01:00
6 changed files with 1116 additions and 0 deletions
@@ -0,0 +1,246 @@
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.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();
+62
View File
@@ -0,0 +1,62 @@
# Attention model (pure domain)
The `Needs you` model exists as reusable, widget-free Dart under
`lib/features/attention/domain/`. The list, identity, wording and local-day
window mirror the browser's `src/attention.js`; no UI, storage plugin,
notification permission or API request is added here.
`attention_transitions.dart` is an attention transition ledger, not a port of
`src/notify.js`: notification permission, tray alerts, `notify_mode` suppression
and success alerts are deliberately outside this slice.
- `attention_models.dart` owns the two kinds (`Decision` rank 0, `Failed` rank 1),
qualification, ordered entries, labels/detail wording, `{runId}:{kind}`
identities, dismissal/snapshot bookkeeping and the JSON string-array
serialisation under this app's own `pipelines.next.attention.v1` (deliberately
not the legacy web key, so neither client rewrites the other's local state).
- Only `waiting` and `failed` statuses qualify, after trimming/lowercasing. A
waiting run with a session audit/export handoff (`export_pending_sequence > 0`)
asks no person and is excluded; a failed run stays failed. `resource_wait` is
deliberately not consulted, matching `web/src/attention.js` and `Attention.kt`
(the server retired the field, and a stale value must not hide a decision).
- The surface is today's work: `attentionEntries` accepts an optional `since`
cutoff and drops an entry when its recency parses and is before it, keeping a
blank or unreadable recency, exactly as the browser does. No cutoff (or an
epoch-zero one) shows everything. Callers pass `startOfLocalDay()` to the bell,
the sheet and the Clear-all snapshot, so yesterday's failures become history.
Stored dismissals themselves still never expire.
- `startOfLocalDay({now})` returns local midnight and takes an injectable `now`
so the UI does not re-derive it and tests stay deterministic.
- Ordering is kind rank, then `finished_at` else `created_at` descending using the
server's timestamp text, then run id descending. The label is the trimmed title
else pipeline name; the detail is `Waiting for your decision`, or the trimmed
diagnostic else `Run failed`.
- Entries retain the whole source summary map, so fields this model does not read
(and unknown future fields) are preserved. `AttentionEntry` is constructed only
by `attentionEntryFor`, so its `runId` is always a validated positive id.
- `attention_transitions.dart` is a pure detector: a seed/first-seen run,
duplicate frame, nonqualifying status, export wait, reconnect reseed or a
snapshot bracketed with `beginSeed`/`endSeed` never emits. It emits once when a
known run enters `failed` or a human `waiting`, forgets the key when the run
leaves that state, and keeps the emitted set across `resetForReconnect`/`reseed`
so a gap cannot replay a transition. A reseed keeps the key of a run that still
qualifies (or that is absent from the read) and prunes one whose run no longer
asks. Dismissed identities are marked seen but suppressed.
Focused tests in `test/features/attention/` cover qualification and exclusions,
ordering and tie-breaks, the local-day cutoff (older/newer, unparseable/blank
recency, no cutoff, decisions, dismissal composition), wording/labels, identity,
dismissal filtering, the clear-all snapshot, defensive copying, malformed/blank
storage, unknown-field preservation, and transition dedupe/first-seen/
nonqualifying/reconnect reseed/emitted-key retention.
Verification: `flutter test test/features/attention` passed all 44 tests;
`flutter analyze` reported no issues. No browser capture applies to this
nonvisual domain slice.
Not done here: no `Needs you` screen/sheet, badge, storage write, store/controller
wiring or notification permission was added, and `PARITY.md` remains `Missing`
until those land. The older `orderAttention` helper in
`lib/features/runs/domain/run_models.dart` was left untouched for lane ownership;
the runs UI must delegate to this model when it is wired, so the two authorities
cannot diverge. Mobile is unverified.
@@ -0,0 +1,114 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
group('dismissal and clear-all snapshot', () {
test('a dismissed identity is filtered out and never returns', () {
final rows = [
run({'id': 7, 'status': 'waiting', 'title': 'Wait'}),
];
final dismissed = attentionDismiss(const {}, '7:Decision');
expect(attentionEntries(rows, dismissed: dismissed), isEmpty);
expect(attentionEntries(rows, dismissed: dismissed), isEmpty);
});
test('a different kind for the same run is a different identity', () {
final dismissed = attentionDismiss(const {}, '7:Decision');
final failed = run({'id': 7, 'status': 'failed', 'diagnostic': 'later'});
final entries = attentionEntries([failed], dismissed: dismissed);
expect(entries.single.key, '7:Failed');
expect(entries.single.detail, 'later');
});
test('dismiss ignores a blank key and adds once', () {
final one = attentionDismiss(const {}, '1:Failed');
expect(one, {'1:Failed'});
expect(attentionDismiss(one, '1:Failed'), {'1:Failed'});
expect(attentionDismiss(one, ' '), {'1:Failed'});
expect(one, {'1:Failed'}, reason: 'input set is not mutated');
});
test('clear all applies only the identities in the open snapshot', () {
final a = attentionEntryFor(run({'id': 1}))!;
final snapshot = attentionDismissalSnapshot([a]);
final b = attentionEntryFor(run({'id': 2}))!;
final after = attentionDismissAll(const {}, snapshot);
expect(after, {'1:Failed'});
expect(after.contains(b.key), isFalse);
expect(
attentionEntries([
run({'id': 1}),
run({'id': 2}),
], dismissed: after).map((entry) => entry.runId),
[2],
);
});
test('the snapshot is a defensive copy', () {
final a = attentionEntryFor(run({'id': 1}))!;
final b = attentionEntryFor(run({'id': 2}))!;
final live = [a, b];
final snapshot = attentionDismissalSnapshot(live);
live.add(attentionEntryFor(run({'id': 3}))!);
expect(snapshot.map((entry) => entry.runId), [1, 2]);
expect(snapshot, isNot(same(live)));
});
});
group('persistence', () {
test('the key is the documented one', () {
expect(attentionStorageKey, 'pipelines.next.attention.v1');
expect(attentionStorageKey, isNot('pipelines.web.attention.v1'));
});
test('encoding is one sorted JSON array and round-trips', () {
final encoded = encodeAttentionDismissals({
'9:Failed',
'1:Decision',
'4:Failed',
});
expect(encoded, '["1:Decision","4:Failed","9:Failed"]');
expect(decodeAttentionDismissals(encoded), {
'1:Decision',
'4:Failed',
'9:Failed',
});
expect(encodeAttentionDismissals(const {}), '[]');
});
test('blank or unreadable storage decodes to empty and never throws', () {
for (final stored in [
null,
'',
' ',
'not json',
'{',
'"a string"',
'{}',
'42',
]) {
expect(decodeAttentionDismissals(stored), isEmpty);
}
});
test('a JSON array keeps only non-empty strings', () {
expect(
decodeAttentionDismissals(
'["1:Failed", 2, null, {"a":1}, "3:Decision", ""]',
),
{'1:Failed', '3:Decision'},
);
});
});
}
@@ -0,0 +1,334 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
group('qualification', () {
test('only waiting and failed qualify; every other status asks nobody', () {
expect(attentionKindOf('waiting'), AttentionKind.decision);
expect(attentionKindOf('failed'), AttentionKind.failed);
for (final status in [
'queued',
'running',
'succeeded',
'canceled',
'cancelled',
'interrupted',
'active',
'blocked',
'skipped',
'unknown',
'',
' ',
null,
'FAILED?',
]) {
expect(
attentionKindOf(status),
isNull,
reason: 'status ${status ?? 'null'} must not qualify',
);
}
});
test('trims and lowercases the server words', () {
expect(attentionKindOf(' Waiting '), AttentionKind.decision);
expect(attentionKindOf('Failed\n'), AttentionKind.failed);
expect(attentionKindOf('WAITING'), AttentionKind.decision);
});
test('ranks are Decision 0 then Failed 1', () {
expect(AttentionKind.decision.rank, 0);
expect(AttentionKind.failed.rank, 1);
});
test('waiting excludes audit/export handoffs, not resource waits', () {
expect(
attentionKindForRun(run({'status': 'waiting'})),
AttentionKind.decision,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': 4}),
),
isNull,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': ' 2 '}),
),
isNull,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': 0}),
),
AttentionKind.decision,
);
// web/src/attention.js and Attention.kt never consult resource_wait; the
// server retired it, so a stale value must not hide a real decision.
for (final stale in [
{'resource': 'device-1'},
'device-1',
true,
1,
]) {
expect(
attentionKindForRun(
run({'status': 'waiting', 'resource_wait': stale}),
),
AttentionKind.decision,
reason: 'resource_wait $stale must not suppress a decision',
);
}
// A failed run stays failed even if a stale export field survived.
expect(
attentionKindForRun(
run({'status': 'failed', 'export_pending_sequence': 4}),
),
AttentionKind.failed,
);
});
test(
'nonqualifying runs are dropped entirely, including malformed ids',
() {
final entries = attentionEntries([
run({'id': 1, 'status': 'succeeded'}),
run({'id': 2, 'status': 'running'}),
run({'id': 3, 'status': 'failed'}),
run({'id': 4, 'status': 'queued'}),
run({'id': 'not-a-number', 'status': 'failed'}),
run({'id': 0, 'status': 'failed'}),
]);
expect(entries.map((entry) => entry.runId), [3]);
expect(attentionEntries(null), isEmpty);
},
);
});
group('identity and wording', () {
test('identity is exactly {runId}:{kind}', () {
expect(attentionKey(440, AttentionKind.failed), '440:Failed');
expect(attentionKey(12, AttentionKind.decision), '12:Decision');
});
test('label is the trimmed title else the pipeline name', () {
expect(attentionEntryFor(run({'title': ' My run '}))!.label, 'My run');
expect(attentionEntryFor(run({'title': ' '}))!.label, 'Plan and land');
expect(attentionEntryFor(run({'title': null}))!.label, 'Plan and land');
});
test(
'detail is the decision line or the trimmed diagnostic else Run failed',
() {
expect(
attentionDetail(AttentionKind.decision, run({'status': 'waiting'})),
'Waiting for your decision',
);
expect(
attentionDetail(
AttentionKind.failed,
run({'diagnostic': ' boom '}),
),
'boom',
);
expect(
attentionDetail(AttentionKind.failed, run({'diagnostic': ' '})),
'Run failed',
);
expect(
attentionDetail(AttentionKind.failed, run({'diagnostic': null})),
'Run failed',
);
},
);
test('row description is exactly {pipeline} · {detail}', () {
final entry = attentionEntryFor(
run({'title': 'T', 'diagnostic': 'failed hard'}),
)!;
expect(attentionRowDescription(entry), 'Plan and land · failed hard');
});
test('badge label is bare Notifications when empty, else the count', () {
expect(attentionBadgeLabel(0), 'Notifications');
expect(attentionBadgeLabel(-3), 'Notifications');
expect(attentionBadgeLabel(1), 'Notifications, 1 needing attention');
expect(attentionBadgeLabel(171), 'Notifications, 171 needing attention');
});
test('the entry keeps the whole summary, including unknown fields', () {
final source = run({
'unknown_future_field': {'keep': true},
'id': 7,
});
final entry = attentionEntryFor(source)!;
expect(entry.run['unknown_future_field'], {'keep': true});
expect(entry.run, same(source));
});
});
group('ordering', () {
test('kind rank, then recency descending, then run id descending', () {
final entries = attentionEntries([
run({
'id': 10,
'status': 'failed',
'finished_at': '2026-10-19T10:00:00Z',
}),
run({
'id': 11,
'status': 'waiting',
'finished_at': '2026-10-19T09:00:00Z',
}),
run({
'id': 12,
'status': 'failed',
'finished_at': '2026-10-19T11:00:00Z',
}),
run({
'id': 13,
'status': 'waiting',
'finished_at': '2026-10-19T08:00:00Z',
}),
]);
expect(entries.map((entry) => entry.runId), [11, 13, 12, 10]);
});
test('recency falls back to created_at when finished_at is blank', () {
final entries = attentionEntries([
run({
'id': 1,
'status': 'failed',
'finished_at': '',
'created_at': '2026-10-19T12:00:00Z',
}),
run({
'id': 2,
'status': 'failed',
'finished_at': '2026-10-19T11:00:00Z',
}),
]);
expect(entries.map((entry) => entry.runId), [1, 2]);
});
test('equal kind and recency tie by run id descending and stay stable', () {
final rows = [
run({'id': 3, 'finished_at': '2026-10-19T10:00:00Z'}),
run({'id': 9, 'finished_at': '2026-10-19T10:00:00Z'}),
run({'id': 5, 'finished_at': '2026-10-19T10:00:00Z'}),
];
expect(attentionEntries(rows).map((entry) => entry.runId), [9, 5, 3]);
expect(attentionEntries(rows.reversed).map((entry) => entry.runId), [
9,
5,
3,
]);
});
});
group('local-day window', () {
final since = DateTime.utc(2026, 10, 20);
final rows = [
run({'id': 1, 'finished_at': '2026-10-19T21:33:27Z'}),
run({'id': 2, 'finished_at': '2026-10-20T10:00:00Z'}),
];
test('startOfLocalDay is local midnight, injectable for tests', () {
final now = DateTime(2026, 10, 20, 15, 4, 5, 6);
final start = startOfLocalDay(now: now);
expect(start, DateTime(2026, 10, 20));
expect(start.hour, 0);
expect(start.minute, 0);
expect(start.second, 0);
expect(start.millisecond, 0);
expect(start.isBefore(now), isTrue);
expect(start.toLocal(), start);
});
test('a cutoff drops older work and keeps newer work', () {
expect(attentionEntries(rows, since: since).map((entry) => entry.runId), [
2,
]);
});
test('no cutoff, and an epoch-zero cutoff, show everything', () {
expect(attentionEntries(rows).map((entry) => entry.runId), [2, 1]);
expect(
attentionEntries(
rows,
since: DateTime.fromMillisecondsSinceEpoch(0),
).map((entry) => entry.runId),
[2, 1],
);
});
test('the cutoff applies to waiting decisions as well as failures', () {
expect(
attentionEntries([
run({
'id': 3,
'status': 'waiting',
'finished_at': '2026-10-19T09:00:00Z',
}),
], since: since),
isEmpty,
);
});
test('unparseable or blank recency is kept, as in the browser', () {
for (final recency in ['', ' ', 'not a timestamp']) {
final kept = attentionEntries([
run({'id': 4, 'finished_at': recency, 'created_at': recency}),
], since: since);
expect(
kept.map((entry) => entry.runId),
[4],
reason: 'recency ${recency.isEmpty ? '<blank>' : recency} is kept',
);
}
});
test('finished_at is the recency the cutoff reads, else created_at', () {
expect(
attentionEntries([
run({
'id': 5,
'created_at': '2026-10-18T09:00:00Z',
'finished_at': '2026-10-20T09:00:00Z',
}),
], since: since).map((entry) => entry.runId),
[5],
);
expect(
attentionEntries([
run({
'id': 6,
'created_at': '2026-10-18T09:00:00Z',
'finished_at': '',
}),
], since: since),
isEmpty,
);
});
test('dismissal and the cutoff compose', () {
final dismissed = attentionDismiss(const {}, '2:Failed');
expect(
attentionEntries(rows, dismissed: dismissed, since: since),
isEmpty,
);
});
});
}
@@ -0,0 +1,224 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
import 'package:pipelines_app/features/attention/domain/attention_transitions.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
test('a seeded failed/waiting run raises nothing', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 1, 'status': 'failed'}),
run({'id': 2, 'status': 'waiting'}),
]);
expect(detector.observe(run({'id': 1, 'status': 'failed'})), isNull);
expect(detector.observe(run({'id': 2, 'status': 'waiting'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('a first-seen run raises nothing and becomes the baseline', () {
final detector = AttentionTransitionDetector();
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.statusOf(5), 'failed');
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('entering failed from a known running run emits exactly once', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 5, 'status': 'running'}),
]);
final first = detector.observe(run({'id': 5, 'status': 'failed'}));
expect(first, isNotNull);
expect(first!.runId, 5);
expect(first.kind, AttentionKind.failed);
expect(first.key, '5:Failed');
expect(first.entry.label, 'Plan and land');
expect(first.entry.detail, 'Run failed');
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, {'5:Failed'});
});
test('entering a human waiting state emits a Decision', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 6, 'status': 'running'}),
]);
final transition = detector.observe(
run({'id': 6, 'status': 'waiting', 'title': ' Decide '}),
);
expect(transition, isNotNull);
expect(transition!.kind, AttentionKind.decision);
expect(transition.key, '6:Decision');
expect(transition.entry.label, 'Decide');
expect(transition.entry.detail, 'Waiting for your decision');
});
test('waiting to failed is a new kind and emits once', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 7, 'status': 'waiting'}),
]);
final transition = detector.observe(run({'id': 7, 'status': 'failed'}));
expect(transition!.key, '7:Failed');
expect(detector.emittedKeys, {'7:Failed'});
});
test('a run that leaves the state and returns may emit again', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 8, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNotNull);
expect(detector.observe(run({'id': 8, 'status': 'running'})), isNull);
expect(detector.emittedKeys, isEmpty);
final again = detector.observe(run({'id': 8, 'status': 'failed'}));
expect(again, isNotNull);
expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNull);
});
test('nonqualifying statuses never emit', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 9, 'status': 'queued'}),
]);
for (final status in [
'running',
'succeeded',
'canceled',
'interrupted',
'unknown',
]) {
expect(
detector.observe(run({'id': 9, 'status': status})),
isNull,
reason: 'status $status must not emit',
);
}
expect(detector.emittedKeys, isEmpty);
});
test(
'an export wait never emits a Decision even though status is waiting',
() {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 10, 'status': 'running'}),
]);
expect(
detector.observe(
run({'id': 10, 'status': 'waiting', 'export_pending_sequence': 2}),
),
isNull,
);
expect(detector.emittedKeys, isEmpty);
},
);
test('dismissed identities are marked seen but do not emit', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 11, 'status': 'running'}),
]);
expect(
detector.observe(
run({'id': 11, 'status': 'failed'}),
dismissed: {'11:Failed'},
),
isNull,
);
expect(detector.emittedKeys, {'11:Failed'});
expect(detector.observe(run({'id': 11, 'status': 'failed'})), isNull);
});
test('a reconnect reseed produces no transition and no replay', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 12, 'status': 'failed'}),
]);
detector.resetForReconnect();
detector.reseed([
run({'id': 12, 'status': 'failed'}),
]);
expect(detector.observe(run({'id': 12, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('a reseed keeps still-qualifying keys and prunes the rest', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 20, 'status': 'running'}),
run({'id': 21, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNotNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull);
expect(detector.emittedKeys, {'20:Failed', '21:Decision'});
detector.reseed([
run({'id': 20, 'status': 'failed'}),
run({'id': 21, 'status': 'succeeded'}),
]);
// 20 still qualifies, so its key survives; 21 no longer asks, so its key is
// pruned and a genuine later transition can be raised once more.
expect(detector.emittedKeys, {'20:Failed'});
expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNull);
});
test('a reseed keeps the key of a run absent from the read', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 22, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNotNull);
detector.reseed([
run({'id': 23, 'status': 'running'}),
]);
expect(detector.emittedKeys, {'22:Failed'});
// Absence says nothing, so seeing the same state again is not a transition.
expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNull);
});
test('a snapshot bracketed as a seed does not emit or replay', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 13, 'status': 'running'}),
])
..beginSeed();
expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull);
detector.endSeed();
expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('the transition keeps the whole frame, including unknown fields', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 14, 'status': 'running'}),
]);
final frame = run({
'id': 14,
'run_id': 14,
'status': 'failed',
'diagnostic': ' boom ',
'unknown_future_field': ['keep'],
});
final transition = detector.observe(frame);
expect(transition!.entry.detail, 'boom');
expect(transition.run, same(frame));
expect(transition.run['unknown_future_field'], ['keep']);
});
}