diff --git a/app/.gitignore b/app/.gitignore index 9f91cbac..ffe0bc2c 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,6 +45,10 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# is code, not runtime data, and must be included in fresh checkouts. +# and its mirroring tests are code, not runtime data, and must be included in +# fresh checkouts. The test negation is required too: without it every +# `test/**/data/` directory is silently dropped from the candidate. !/lib/**/data/ !/lib/**/data/** +!/test/**/data/ +!/test/**/data/** diff --git a/app/AGENTS.md b/app/AGENTS.md index 7752342a..bee8f407 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -7,6 +7,7 @@ - Develop and test ONLY web now. No ADB, emulators, device changes, Android/iOS builds or installs. Keep source portable to all three targets. Explicitly report mobile as unverified. - Small cohesive files (aim below 250 lines; split by responsibility, not arbitrary fragments). Each task owns a directory and its tests. Do not edit another lane or root pubspec/main unless assigned. - Code quality is a delivery requirement. No minified implementations, silent capability fallbacks, fake data masking missing features, or workarounds that bypass the real defect. A pipeline success does not waive missing behavior, native controls, regression coverage or rendered evidence. Label incomplete work honestly and complete it before claiming parity. +- The manager drives authorized routine integration and recovery without repeatedly stopping for permission. Feature implementation stays in pipelines where appropriate; infrastructure blockers can be resolved directly within the user's authorized scope. Verify quiescence, preserve data and rollback, act, and report actual results. Ask only for genuinely new scope or unresolved destructive choices. ## Shared contract - `lib/core/api_gateway.dart`: `JsonMap` alias; `ApiGateway.call(type, [fields])` yields the entire decoded reply envelope; `frames` yields unsolicited server envelopes. Gateway owns request IDs. Do not put domain interpretation in transport. diff --git a/app/WORK.md b/app/WORK.md index 6074319d..2b5cc144 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -12,12 +12,25 @@ All work under app/. Existing applications remain running and unchanged. | F3 | Run models, live event fold, actions | run 32 + 1515ebe | 11 regressions/analyze pass; 5 source files 105–226 lines | main 37d0823, ancestry verified | — | | F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | | F5 | Isolated authenticated web preview tooling | run 30 + ae352bb | 6 proxy fixtures incl auth/bytes/origin/idle sockets pass | main 160ab45, ancestry verified | http://127.0.0.1:8096/ | -| P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | -| C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | -| N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | controller 43 accepted; list 45 → resume 48; detail 46 | manager reran 15 controller tests, all pass; reproduced 3 list-test invariant failures and sent focused fix to resume48; detail lane independent | controller accepted, whole UI held | browser integration pending | -| D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | -| R2a | Human-decision native confirm | run 47 / flutter/r2-decision | running (Flash), exact confirmation/refusal tests | pending | pending | +| P1 | Pipeline list/detail/source/version browser | run34 / flutter/p1-pipelines | original export repaired; Review resumed | pending review/landing | pending | +| C1 | Chat session browser and management | 35 →36 →42 / flutter/f4-chat | original export42 repaired; Review resumed | pending review/landing | pending | +| N1 | Connection settings/preferences | run37 / flutter/n1-settings | original export repaired; Review resumed | pending review/landing | pending | +| R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | +| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | original export repaired; Review resumed | pending review/landing | pending | +| R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | +| R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | +| X1 | Native search and result targets | run49 / flutter/x1-search | original export repaired; Review resumed | pending review/landing | pending | +| I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | original export repaired; Review resumed | pending review/landing | not deployed | +| E1 | Narrow authorized server export-bound fix | run53 / source22801a9 / deployb4627e2 | bounded regressions + full isolated Go suite pass; exact installed revision verified | source merged; deployed minimal patch on original server revision | installed; seven exact exports complete, Review resumed | +| R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | +| R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | +| S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | +| T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | +| S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | +| P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | +| P2b | Content-sized graph node layout | run60 / commitc1f140b | manager checked caller-supplied extents + reran21 tests/analyze, pass | mainec9e889, ancestry verified | geometry only, no renderer | +| A1a | Artifact records/grouping/safe URL navigation | run61 / flutter/a1-data | Task v6, Flash; pure data/security fixtures | running | — | +| P2c | Edge routes and measured label geometry | run62 / flutter/p2-routes | Task v6, Flash; separate from painter/widgets | running | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -50,6 +63,81 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +At804e531 manager ran the integrated main Flutter suite: 98tests passed and +flutter analyze was clean. These cover landed source/components only, not the +six unreviewed export-blocked feature branches or visible screen delivery. + +### Export blocker RESOLVED — direct manager recovery +User explicitly directed manager to perform routine unblock/install without +waiting for further decisions. Confirmed ZERO active runs and quiescent original +Code sessions, backed up SQLite via backup API plus installed binary/plist under +~/.local/share/pipelines/backups/exportfix-b4627e2 (private directory), atomically +replaced only the server binary and restarted exact launchd job +gui/501/net.awan.pipelines.server. No web/ntfy/OpenCode service was restarted. +Installed ping commit is b4627e29755c3496f5caee5a9c316d8bf24f0713; SHA256 +f70b4e17324262cf5275927c40f617838fefc0d9217946eeaf6d3a320c786fac. +Rollback binary remains saved, DB/session/workspaces untouched. + +Export-only repair of34/37/39/42/49/50/58 visit1 ALL returned complete, +untruncated, 2.25–4.28MiB. Original Code session IDs and output hashes match the +pre-install checkpoint, with one Code visit each; all seven moved to Review, +export_pending_sequence0. Evidence in approved OpenCode temp: +export-recovery-before.json, export-recovery-repair-results.json and +export-recovery-after.json. EOF/reset errors on old background waits were the +expected restart disconnect, NOT run failures. Reattached seven waits using a +private CLI built from the sameb4627e2 source; installed global CLI left alone. +No coding-stage replay, evidence overwrite or gate bypass. Network preview still +responds302 to protected login at http://10.0.0.249:8096/. Implementation/reviews +now proceed in parallel; the prior install-approval notes below are historical. + +The fix is now merged: rendered file cap8MiB, source cap8MiB unchanged, within +ordinary artifact allowance. Pipeline read-only scratch exports of all six exact +sessions were complete at2.25–4.28MiB, establishing the fix is sufficient. +Run53 automatic delivery failed in pre-existing TestHumanRunAttentionNotification +because the test inherited the running service's PIPELINES_WEB_PUBLIC_URL. Manager +reproduced that same failure on unchanged main with a harmless example URL; no +notification source/test was edited. All packages pass on candidate with only that +test-process env var unset; build/vet/diff pass. Manager landed checked source +directly (no coding-stage replay), and refreshed installed managed Pipelines skill +from current source via go run ./cmd/pipelines skill install. +Installed server is unchanged. Deployment safety inspection found57/58/59 active; +no restart or binary replacement performed. Need explicit operator approval for +installation/restart after active work settles before exact export-only repairs. +Old CLI service status cannot resolve its expected launchd label; do not guess a +service or restart unrelated processes. Inspect authoritative supervisor first. +Preparation completed after user asked what manager was doing: authoritative +launchd label is net.awan.pipelines.server (not old CLI's net.a-wan.pipelines), +running installed binary under ~/.local/share/pipelines/bin with original DB +and OpenCode endpoint retained. Built a deployment candidate from the exact +running9ee2e00 revision plus ONLY export fix22801a9: branch +deploy/export-limit-only, commitb4627e2. All six new export regressions pass on +that exact candidate. Staged binary in approved OpenCode temp directory is +pipelines-server-exportfix-b4627e2; rollback copy is +pipelines-server-before-exportfix-66779. Installed binary/launchd registration +remain untouched. This avoids deploying unrelated newer main changes. +The temporary launch pause ended after the direct, safe server installation. +Graph/model/layout lanes have progressed, and independent small tasks continue +alongside the seven restored feature reviews. No repeat approval gate remains +for routine authorized recovery/integration. + +User asked about failed runs; explicit status inspection found runs34/37/39/42/ +49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, +but export is partial/truncated at exactly2097152 bytes. Exact recorded native +session identities remain retained. `pipelines repair-session-export 34 1` was +attempted once; it returned `session export repair incomplete: partial` at the +same cap. No full stage reruns, evidence replacement, cancellation or gate bypass +was performed. Remaining waits stay active for eventual export-only recovery. +User subsequently approved the narrow server export-limit exception and asked +for continued small parallel tasks. Run53 owns ONLY bounded export-limit code, +necessary verification/repair regressions and a focused note. Existing web and +mobile source remain off-limits. Deployment remains a separate operator gate +under internal/server/AGENTS.md; no shared service restart is delegated. After +authorized installation, recover the original exact visits EXPORT-ONLY. Do not +burn repeated repair attempts against the unchanged deterministic size limit. + +Parallel work while E1 runs: R2c/R2d/S1a are separate worktrees, each with its own +focused existing Task v6 run and background wait. No new workflow definitions. + At 160ab45: 29 Flutter tests and 6 Node proxy fixtures pass; flutter analyze, flutter build web and git diff --check pass. Real Chrome phone/desktop captures are in the approved OpenCode temporary directory, named f2-shell-*.png. The @@ -65,6 +153,15 @@ HTML login redirect 302 and unauthenticated JS 401 via the LAN address. Existing proxy/API services remain unchanged. Bind command uses --host 0.0.0.0 explicitly; the source default remains loopback for safety. +HTTPS access fixed for the user's Tailscale URL: +https://alans-macbook-pro.tail6bf4dc.ts.net:8096/. Port8096 originally spoke only +plain HTTP; added tailnet-only Tailscale Serve HTTPS8096 → http://127.0.0.1:8096. +Existing Serve443→8787 and8443→8095 routes preserved. Verified trusted certificate +(curl ssl_verify_result0), protected root302 to login, login200, unauthenticated +JS401; LAN HTTP still302. No Funnel/public-Internet exposure or auth disabling. +Prior Serve config saved in approved temp tailscale-serve-before-preview8096.json; +remove ONLY this route with tailscale serve --https=8096 off if rollback needed. + ### Manager integration findings - F3 candidate omitted `lib/features/runs/data/runs_repository.dart`: root runtime-data ignore matched source. Main 718442d adds an app-only exception; diff --git a/app/lib/features/graph/domain/graph_definition.dart b/app/lib/features/graph/domain/graph_definition.dart new file mode 100644 index 00000000..60735fa9 --- /dev/null +++ b/app/lib/features/graph/domain/graph_definition.dart @@ -0,0 +1,152 @@ +import 'graph_protocol.dart'; + +/// The graph definition: nodes and edges declared by a pipeline, never the +/// evidence that a run executed them. Run evidence lives in +/// `run_graph_state.dart`; keeping the two shapes separate means a definition +/// can be drawn without claiming a visit happened. +/// +/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel` +/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only. + +/// Ordering priority: success first, error last, every other outcome +/// alphabetical in between (the web client's `outcomePriority`). +int _outcomePriority(String outcome) { + if (outcome == 'success') return 0; + if (outcome == 'error') return 2; + return 1; +} + +/// A stage's edge outcomes in the app's one stable order. +List stageOutcomes(dynamic stage) { + final edges = stage is Map ? stage['edges'] : null; + if (edges is! Map) return const []; + final outcomes = edges.keys.map((key) => '$key').toList(); + outcomes.sort((a, b) { + final priority = _outcomePriority(a) - _outcomePriority(b); + return priority != 0 ? priority : a.compareTo(b); + }); + return outcomes; +} + +/// The outcome label on an edge: `error*` for an implicit fallback error route. +String edgeLabel(dynamic stage, String outcome) { + final implicitFallback = stage is Map && stage['fallback_error'] == true; + return outcome == 'error' && implicitFallback ? 'error*' : outcome; +} + +/// One declared edge, in stable definition order. +class GraphEdge { + const GraphEdge({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.label, + required this.fallback, + required this.knownTarget, + }); + + /// The 1-based id assigned in stable definition order (`Graph.edges()`). + final int id; + final String source; + final String outcome; + + /// The resolved target: `#` has already become `#success`/`#failure`. + final String target; + final String label; + + /// True only for the parser's implicit `error -> #failure` route. + final bool fallback; + + /// True when [target] is a terminal or a stage declared in this graph. + /// + /// An empty or unknown target is kept exactly as recorded, with this flag + /// false, so callers can show it honestly instead of inventing a node. + final bool knownTarget; + + bool get isTerminal => isTerminalTarget(target); +} + +/// One graph definition node: a declared stage, or a terminal the definition +/// routes to. +class GraphNode { + const GraphNode({required this.key, required this.terminal, this.stageIndex}); + + final String key; + final bool terminal; + + /// The node's stage declaration index, or null for a terminal. + final int? stageIndex; + + String get label => nodeDisplayLabel(key); + String get shortLabel => nodeLabel(key); +} + +List> _stages(dynamic graph) { + if (graph is! Map) return const >[]; + final stages = graph['stages']; + if (stages is! List) return const >[]; + return stages.whereType().map(Map.from).toList(); +} + +String _stageKey(Map stage) => '${stage['key'] ?? ''}'; + +/// Every definition edge in stable id order. +/// +/// Stages keep declaration order and each stage's outcomes use +/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge +/// value declares no edge and is skipped, while an empty or unknown target is +/// preserved with [GraphEdge.knownTarget] false. +List graphEdges(dynamic graph) { + final stages = _stages(graph); + final stageKeys = { + for (final stage in stages) + if (_stageKey(stage).isNotEmpty) _stageKey(stage), + }; + final result = []; + for (final stage in stages) { + final edges = stage['edges']; + if (edges is! Map) continue; + final source = _stageKey(stage); + for (final outcome in stageOutcomes(stage)) { + final raw = edges[outcome]; + if (raw == null) continue; + final target = resolveTarget(outcome, '$raw') ?? ''; + result.add( + GraphEdge( + id: result.length + 1, + source: source, + outcome: outcome, + target: target, + label: edgeLabel(stage, outcome), + fallback: outcome == 'error' && stage['fallback_error'] == true, + knownTarget: isTerminalTarget(target) || stageKeys.contains(target), + ), + ); + } + } + return result; +} + +/// The definition's nodes in declaration order. +/// +/// A stage key identifies one node even when it is declared twice; self edges +/// and loops therefore never duplicate identity. Terminal nodes are appended +/// failure first, then success, once any declared edge resolves to a terminal +/// (the same `hasTerminal` rule the web layout uses). They are still +/// definition nodes, not evidence that a run reached them. +List graphNodes(dynamic graph) { + final stages = _stages(graph); + final seen = {}; + final nodes = []; + for (var index = 0; index < stages.length; index += 1) { + final key = _stageKey(stages[index]); + if (key.isEmpty || !seen.add(key)) continue; + nodes.add(GraphNode(key: key, terminal: false, stageIndex: index)); + } + if (graphEdges(graph).any((edge) => edge.isTerminal)) { + nodes.add(const GraphNode(key: failureEnd, terminal: true)); + nodes.add(const GraphNode(key: successEnd, terminal: true)); + } + return nodes; +} diff --git a/app/lib/features/graph/domain/graph_protocol.dart b/app/lib/features/graph/domain/graph_protocol.dart new file mode 100644 index 00000000..a033884c --- /dev/null +++ b/app/lib/features/graph/domain/graph_protocol.dart @@ -0,0 +1,43 @@ +/// Protocol terminal targets and the labels the graph uses for them. +/// +/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`, +/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`. +/// Pure Dart: no Flutter imports and no layout or rendering decisions. +library; + +/// The explicit success terminal (`Protocol.SUCCESS_END`). +const String successEnd = '#success'; + +/// The explicit failure terminal (`Protocol.FAILURE_END`). +const String failureEnd = '#failure'; + +/// True only for the two explicit terminal targets. +/// +/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using +/// the outcome, exactly as the server and the web client do. +bool isTerminalTarget(String? target) => + target == successEnd || target == failureEnd; + +/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal. +/// +/// Every other value is preserved verbatim, including an empty or unknown +/// stage key. A missing target stays null rather than becoming a terminal, so +/// a blank edge cannot fabricate a visit or a terminal node. +String? resolveTarget(String? outcome, String? target) { + if (target != '#') return target; + return outcome == 'error' ? failureEnd : successEnd; +} + +/// A graph node title: a stage keeps its key, a terminal reads Success/Failure. +String nodeDisplayLabel(String? key) { + if (key == successEnd) return 'Success'; + if (key == failureEnd) return 'Failure'; + return key ?? ''; +} + +/// The TUI-mirroring label: terminal targets are all caps. +String nodeLabel(String? key) { + if (key == successEnd) return 'SUCCESS'; + if (key == failureEnd) return 'FAILURE'; + return key ?? ''; +} diff --git a/app/lib/features/graph/domain/run_graph_state.dart b/app/lib/features/graph/domain/run_graph_state.dart new file mode 100644 index 00000000..ef3fb8be --- /dev/null +++ b/app/lib/features/graph/domain/run_graph_state.dart @@ -0,0 +1,124 @@ +import 'graph_protocol.dart'; + +/// Which stages and routes a run actually recorded. +/// +/// This is executed-route evidence, deliberately distinct from the graph +/// definition's nodes and edges. It mirrors `runGraphState` from +/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's +/// stage is visited once in first-appearance order, a step with a non-blank +/// outcome and target contributes one deduplicated `source\0outcome\0target` +/// route, and only a resolved terminal is added by its target. A non-terminal +/// target is not visited until a step lands on it. +/// +/// The run map is the same detail produced by the runs feature; this helper +/// reads recorded steps and never folds live events a second time. +class RunGraphState { + RunGraphState({ + required List visitedStages, + required List takenRoutes, + required this.currentStage, + required this.executing, + required this.currentStageStartedAt, + }) : visitedStages = List.unmodifiable(visitedStages), + takenRoutes = List.unmodifiable(takenRoutes); + + /// Visited stage keys in first-appearance order, without duplicates. + final List visitedStages; + + /// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order. + final List takenRoutes; + + /// The run's current stage, else the last recorded visit's stage, else null. + final String? currentStage; + final bool executing; + + /// The running visit's start for [currentStage], only while executing. + final String? currentStageStartedAt; + + bool isStageVisited(String key) => visitedStages.contains(key); + + /// True when a recorded visit took this definition route. The target is + /// resolved with the same `#` rule the definition edges use. + bool isRouteTaken(String source, String outcome, String target) { + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) return false; + return takenRoutes.contains('$source\u0000$outcome\u0000$resolved'); + } + + /// The active stage for a live run, else null. A finished run has none. + String? get activeStage { + if (!executing || currentStage == null || currentStage!.isEmpty) { + return null; + } + return currentStage; + } +} + +List> _steps(dynamic run) { + if (run is! Map) return const >[]; + final steps = run['steps']; + if (steps is! List) return const >[]; + return steps.whereType().map(Map.from).toList(); +} + +String _text(dynamic value) => '${value ?? ''}'; + +/// Derives [RunGraphState] from one run detail map. +/// +/// Missing or malformed steps yield no visits and no routes; nothing is +/// fabricated from a missing capture. Repeated visits stay one identity per +/// stage, and self edges or loops never recurse. +RunGraphState runGraphState(dynamic run) { + final steps = _steps(run); + final visitedStages = []; + final seenStages = {}; + final takenRoutes = []; + final seenRoutes = {}; + + void visit(String? key) { + if (key == null || key.isEmpty || !seenStages.add(key)) return; + visitedStages.add(key); + } + + for (final step in steps) { + final stage = _text(step['stage']); + if (stage.isNotEmpty) visit(stage); + + final outcome = _text(step['outcome']); + final target = _text(step['target']); + if (outcome.trim().isEmpty || target.trim().isEmpty) continue; + + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) continue; + final route = '$stage\u0000$outcome\u0000$resolved'; + if (seenRoutes.add(route)) takenRoutes.add(route); + if (isTerminalTarget(resolved)) visit(resolved); + } + + final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']); + final rawCurrent = _text(run is Map ? run['current_stage'] : null); + final currentStage = rawCurrent.trim().isNotEmpty + ? rawCurrent + : (lastStage.trim().isNotEmpty ? lastStage : null); + final executing = run is Map && run['executing'] == true; + + String? currentStageStartedAt; + if (executing && currentStage != null) { + for (var index = steps.length - 1; index >= 0; index -= 1) { + final step = steps[index]; + if (_text(step['stage']) != currentStage) continue; + if (_text(step['status']) != 'running') continue; + final started = _text(step['started_at']); + if (started.trim().isNotEmpty) currentStageStartedAt = started; + break; + } + } + + return RunGraphState( + visitedStages: visitedStages, + takenRoutes: takenRoutes, + currentStage: currentStage, + executing: executing, + currentStageStartedAt: currentStageStartedAt, + ); +} diff --git a/app/lib/features/graph/domain/stage_visits.dart b/app/lib/features/graph/domain/stage_visits.dart new file mode 100644 index 00000000..4a546cfa --- /dev/null +++ b/app/lib/features/graph/domain/stage_visits.dart @@ -0,0 +1,107 @@ +import '../../../core/api_gateway.dart'; + +/// Recorded stage-visit selection, matching the web client's timeline and +/// stage pane. Visits are ordered by their recorded sequence, never by the +/// order a caller happens to pass them in; repeated visits to one stage stay +/// separate entries. Pure data: no widgets, layout or coordinates. + +int _sequenceOf(JsonMap step) { + final sequence = step['sequence']; + return sequence is num ? sequence.toInt() : 0; +} + +int _positiveVisit(dynamic control) { + if (control is! Map) return 0; + final visit = control['visit']; + if (visit is num) return visit > 0 ? visit.toInt() : 0; + return int.tryParse('${visit ?? ''}') ?? 0; +} + +/// The visit number a timeline row shows: the recorded `control.visit` when it +/// is positive, else the position within the stage's ordered visits. +int displayVisit(JsonMap step, int index) { + final recorded = _positiveVisit(step['control']); + return recorded > 0 ? recorded : index + 1; +} + +/// Clamps a visit index into `[0, count)`; an empty list yields 0. +int clampVisitIndex(int index, int count) { + if (count <= 0) return 0; + if (index < 0) return 0; + return index >= count ? count - 1 : index; +} + +List _ordered(List visits) { + final indexed = <({int position, JsonMap step})>[ + for (var index = 0; index < visits.length; index += 1) + (position: index, step: visits[index]), + ]; + indexed.sort((a, b) { + final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step)); + return bySequence != 0 ? bySequence : a.position.compareTo(b.position); + }); + return [for (final entry in indexed) entry.step]; +} + +/// Every stage's recorded visits, ordered by sequence. +/// +/// The map keeps stage first-appearance order. Equal sequences keep their +/// recorded order (the web client's stable sort), and a stage with no recorded +/// visit is simply absent rather than present with a synthetic visit. +Map> visitsByStage(List steps) { + final grouped = >{}; + for (final step in steps) { + final stage = '${step['stage'] ?? ''}'; + grouped.putIfAbsent(stage, () => []).add(step); + } + return >{ + for (final entry in grouped.entries) entry.key: _ordered(entry.value), + }; +} + +/// One selected stage visit. [step] is null when the stage has no recorded +/// visit, so callers cannot mistake an absent capture for an execution. +class StageVisitSelection { + const StageVisitSelection({ + required this.stageKey, + required this.visits, + required this.index, + }); + + final String stageKey; + + /// The stage's visits ordered by sequence. + final List visits; + + /// The clamped index into [visits]; 0 when there are none. + final int index; + + bool get hasVisit => visits.isNotEmpty; + JsonMap? get step => hasVisit ? visits[index] : null; + int get visitNumber => step == null ? 0 : displayVisit(step!, index); + + /// True when an explicit requested index was clamped, so a caller can + /// correct its route exactly as the web stage route does. + bool correctedRequest(int? requested) => + requested != null && requested != index; +} + +/// Selects a stage's visit exactly as the web stage pane does. +/// +/// A null [visitIndex] means the stage's most recent recorded visit; an +/// out-of-range index is clamped to the last visit (negative values to the +/// first). A stage with no recorded visits returns [StageVisitSelection.step] +/// null instead of a fabricated visit. +StageVisitSelection selectStageVisit( + List steps, + String stageKey, { + int? visitIndex, +}) { + final visits = visitsByStage(steps)[stageKey] ?? const []; + final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1); + return StageVisitSelection( + stageKey: stageKey, + visits: visits, + index: clampVisitIndex(wanted, visits.length), + ); +} diff --git a/app/lib/features/graph/layout/graph_node_layout.dart b/app/lib/features/graph/layout/graph_node_layout.dart new file mode 100644 index 00000000..767426ea --- /dev/null +++ b/app/lib/features/graph/layout/graph_node_layout.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import 'graph_ranks.dart'; +import 'layout_models.dart'; + +/// Places definition nodes in topological columns. +/// +/// Nodes keep definition order inside a rank, each column is as wide as its +/// widest measured node, and columns are top-aligned. A node is centred in its +/// column, so heterogeneous widths and text-expanded heights stay separated by +/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap] +/// between ranks. Nothing is clipped to a fixed box: the supplied measured +/// width and height are used verbatim and the returned bounds include them. +/// +/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose +/// source or target is not one of [nodes] are ignored, so an unknown target can +/// never invent a node. A measurement is required for every node; a missing one +/// is an error rather than a made-up size. Extra measurement entries are +/// ignored because they cannot become nodes. +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}) { + _validateNodeKeys(nodes); + final ranks = assignGraphRanks(nodes, edges); + final measured = {}; + final missing = []; + for (final node in nodes) { + final extent = extents[node.key]; + if (extent == null) { + missing.add(node.key); + } else { + measured[node.key] = extent; + } + } + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'extents', + 'missing measured extents for graph nodes', + ); + } + + final columns = List>.generate( + ranks.rankCount, + (_) => [], + ); + for (final node in nodes) { + columns[ranks.rankOf[node.key]!].add(node); + } + + final columnWidths = [ + for (final column in columns) + column.fold( + 0, + (width, node) => math.max(width, measured[node.key]!.width), + ), + ]; + final columnHeights = [ + for (final column in columns) + _columnHeight(column, measured, config.rowGap), + ]; + final columnX = []; + var nextX = config.padding; + for (var rank = 0; rank < columns.length; rank += 1) { + columnX.add(nextX); + nextX += columnWidths[rank]; + if (rank + 1 < columns.length) nextX += config.columnGap; + } + + final boxes = []; + for (var rank = 0; rank < columns.length; rank += 1) { + var nextY = config.padding; + for (final node in columns[rank]) { + final extent = measured[node.key]!; + boxes.add( + GraphNodeBox( + key: node.key, + terminal: node.terminal, + stageIndex: node.stageIndex, + rank: rank, + x: columnX[rank] + (columnWidths[rank] - extent.width) / 2, + y: nextY, + width: extent.width, + height: extent.height, + ), + ); + nextY += extent.height + config.rowGap; + } + } + + final width = + config.padding * 2 + + columnWidths.fold(0, (sum, column) => sum + column) + + config.columnGap * math.max(0, columns.length - 1); + final height = + config.padding * 2 + + columnHeights.fold( + 0, + (tallest, column) => math.max(tallest, column), + ); + + return GraphLayout( + nodes: boxes, + width: width, + height: height, + rankCount: ranks.rankCount, + ranks: ranks.rankOf, + ); +} + +void _validateNodeKeys(List nodes) { + final seen = {}; + for (final node in nodes) { + if (node.key.isEmpty) { + throw ArgumentError.value( + node.key, + 'nodes', + 'node key must not be empty', + ); + } + if (!seen.add(node.key)) { + throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key'); + } + } +} + +double _columnHeight( + List column, + Map measured, + double rowGap, +) { + if (column.isEmpty) return 0; + var height = 0.0; + for (final node in column) { + height += measured[node.key]!.height; + } + return height + rowGap * (column.length - 1); +} diff --git a/app/lib/features/graph/layout/graph_ranks.dart b/app/lib/features/graph/layout/graph_ranks.dart new file mode 100644 index 00000000..f7558db2 --- /dev/null +++ b/app/lib/features/graph/layout/graph_ranks.dart @@ -0,0 +1,191 @@ +import 'dart:collection'; +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; + +/// Deterministic 0-based ranks for a graph definition's nodes. +/// +/// Ranks come from the condensation DAG: every strongly connected component +/// shares one rank, and a component sits one past its deepest predecessor +/// (longest path). Self loops and cycles therefore stay finite, a cycle's +/// members do not drift apart, and disconnected nodes stay at rank 0. Edges +/// whose endpoints are not definition nodes are ignored: an unknown target +/// never invents a node. +class GraphRanks { + GraphRanks({ + required Map rankOf, + required this.rankCount, + required List> components, + }) : rankOf = Map.unmodifiable(rankOf), + components = List.unmodifiable(>[ + for (final component in components) List.unmodifiable(component), + ]); + + /// Every definition key's rank, in definition order. + final Map rankOf; + + /// Number of distinct ranks, 0 for an empty node set. + final int rankCount; + + /// Strongly connected components as keys, each sorted by definition order and + /// the list sorted by its first member. + final List> components; +} + +/// One DFS frame for the iterative Tarjan walk. +class _Frame { + _Frame(this.node); + + final int node; + int nextChild = 0; +} + +/// Assigns ranks to exactly the supplied [nodes]. +/// +/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are +/// harmless. The walk is iterative, so a deep chain cannot overflow the call +/// stack, and the work is linear in nodes plus edges. +GraphRanks assignGraphRanks(List nodes, List edges) { + final indexOf = {}; + for (var index = 0; index < nodes.length; index += 1) { + indexOf[nodes[index].key] = index; + } + + final adjacency = List>.generate(nodes.length, (_) => []); + final seenPairs = {}; + for (final edge in edges) { + final source = indexOf[edge.source]; + final target = indexOf[edge.target]; + if (source == null || target == null) continue; + if (!seenPairs.add(source * nodes.length + target)) continue; + adjacency[source].add(target); + } + + final components = _components(adjacency); + final componentOf = List.filled(nodes.length, -1); + for (var component = 0; component < components.length; component += 1) { + for (final node in components[component]) { + componentOf[node] = component; + } + } + + // Condensation edges and their indegrees. + final successors = List>.generate(components.length, (_) => {}); + final indegree = List.filled(components.length, 0); + for (var source = 0; source < adjacency.length; source += 1) { + final from = componentOf[source]; + for (final target in adjacency[source]) { + final to = componentOf[target]; + if (from == to) continue; + if (successors[from].add(to)) indegree[to] += 1; + } + } + + // Longest-path ranks over the condensation. Queue order only has to be a + // topological order; the resulting rank per component is unique. + final ranks = List.filled(components.length, 0); + final ready = ListQueue(); + for (var component = 0; component < components.length; component += 1) { + if (indegree[component] == 0) ready.add(component); + } + var settled = 0; + while (ready.isNotEmpty) { + final component = ready.removeFirst(); + settled += 1; + for (final next in successors[component]) { + ranks[next] = math.max(ranks[next], ranks[component] + 1); + indegree[next] -= 1; + if (indegree[next] == 0) ready.add(next); + } + } + if (settled != components.length) { + // The condensation cannot contain a cycle by construction; stop rather than + // return a silently truncated layout. + throw StateError('graph condensation was not acyclic'); + } + + final componentKeys = >[ + for (final component in components) + [for (final node in component) nodes[node].key], + ]; + final componentOrder = [ + for (var component = 0; component < components.length; component += 1) + component, + ]..sort((a, b) => components[a].first.compareTo(components[b].first)); + + final rankOf = {}; + var rankCount = 0; + for (var index = 0; index < nodes.length; index += 1) { + final rank = ranks[componentOf[index]]; + rankOf[nodes[index].key] = rank; + if (rank + 1 > rankCount) rankCount = rank + 1; + } + + return GraphRanks( + rankOf: rankOf, + rankCount: rankCount, + components: >[ + for (final component in componentOrder) componentKeys[component], + ], + ); +} + +/// Tarjan's strongly connected components, emitted sinks first. +/// +/// Iterative rather than recursive so a long chain cannot exhaust the stack. +/// Members are sorted by definition index, which keeps every output stable. +List> _components(List> adjacency) { + final discovery = List.filled(adjacency.length, -1); + final low = List.filled(adjacency.length, 0); + final onStack = List.filled(adjacency.length, false); + final stack = []; + final components = >[]; + var nextDiscovery = 0; + + for (var root = 0; root < adjacency.length; root += 1) { + if (discovery[root] != -1) continue; + discovery[root] = low[root] = nextDiscovery; + nextDiscovery += 1; + stack.add(root); + onStack[root] = true; + final callStack = <_Frame>[_Frame(root)]; + + while (callStack.isNotEmpty) { + final frame = callStack.last; + final node = frame.node; + if (frame.nextChild < adjacency[node].length) { + final child = adjacency[node][frame.nextChild]; + frame.nextChild += 1; + if (discovery[child] == -1) { + discovery[child] = low[child] = nextDiscovery; + nextDiscovery += 1; + stack.add(child); + onStack[child] = true; + callStack.add(_Frame(child)); + } else if (onStack[child]) { + low[node] = math.min(low[node], discovery[child]); + } + continue; + } + + callStack.removeLast(); + if (callStack.isNotEmpty) { + final parent = callStack.last.node; + low[parent] = math.min(low[parent], low[node]); + } + if (low[node] == discovery[node]) { + final component = []; + while (stack.isNotEmpty) { + final member = stack.removeLast(); + onStack[member] = false; + component.add(member); + if (member == node) break; + } + component.sort(); + components.add(component); + } + } + } + + return components; +} diff --git a/app/lib/features/graph/layout/layout_models.dart b/app/lib/features/graph/layout/layout_models.dart new file mode 100644 index 00000000..4a8dac4e --- /dev/null +++ b/app/lib/features/graph/layout/layout_models.dart @@ -0,0 +1,129 @@ +/// Pure geometry for a workflow graph's node layout. +/// +/// Every size and gap is supplied by the caller. The native renderer measures +/// each node after text layout (including the platform's text scaling), so this +/// library never assumes a node width, font, palette or device class. +/// +/// No Flutter imports: rectangles are plain numbers so the same result can be +/// built into widgets, a canvas or a test fixture. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +/// One caller-measured node extent, in logical pixels. +/// +/// A width or height may be zero for an empty label; the layout still keeps the +/// node separate from its neighbours through the configured gaps. +class NodeExtent { + NodeExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// The gaps a caller reserves around measured nodes. +/// +/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a +/// rank, and [padding] is the outer margin included in [GraphLayout] bounds. +class GraphLayoutConfig { + GraphLayoutConfig({ + required this.columnGap, + required this.rowGap, + this.padding = 0, + }) { + _requireFiniteNonNegative('columnGap', columnGap); + _requireFiniteNonNegative('rowGap', rowGap); + _requireFiniteNonNegative('padding', padding); + } + + final double columnGap; + final double rowGap; + final double padding; +} + +/// One placed node. +/// +/// [key], [terminal] and [stageIndex] are the definition node's own identity, +/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in +/// graph space and [rank] is its 0-based topological column. +class GraphNodeBox { + const GraphNodeBox({ + required this.key, + required this.terminal, + required this.stageIndex, + required this.rank, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final String key; + final bool terminal; + final int? stageIndex; + final int rank; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is GraphNodeBox && + other.key == key && + other.terminal == terminal && + other.stageIndex == stageIndex && + other.rank == rank && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => + Object.hash(key, terminal, stageIndex, rank, x, y, width, height); +} + +/// An immutable node layout: every placed box plus the total graph bounds. +/// +/// [nodes] is ordered by rank first and definition order inside a rank; use +/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the +/// caller's padding; every box's [right] and [bottom] stay inside them. +/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the +/// number of columns (0 for an empty node set). +class GraphLayout { + GraphLayout({ + required List nodes, + required this.width, + required this.height, + required this.rankCount, + required Map ranks, + }) : nodes = List.unmodifiable(nodes), + ranks = Map.unmodifiable(ranks); + + final List nodes; + final Map ranks; + final double width; + final double height; + final int rankCount; + + bool get isEmpty => nodes.isEmpty; + + /// The placed box for [key], or null when the definition has no such node. + GraphNodeBox? nodeFor(String key) { + for (final node in nodes) { + if (node.key == key) return node; + } + return null; + } +} diff --git a/app/lib/features/runs/actions/action_refusal.dart b/app/lib/features/runs/actions/action_refusal.dart new file mode 100644 index 00000000..87e03995 --- /dev/null +++ b/app/lib/features/runs/actions/action_refusal.dart @@ -0,0 +1,18 @@ +/// A refused operator action and, when one was started, the bounded re-read of +/// server truth that follows it. +/// +/// The prompt shows [message] and allows dismissal immediately; it must never +/// wait for [stillPossible]. That future is only observed so a retry can be +/// ruled out once server truth arrives: `true` means the re-read found the run +/// still allows the action, `false` means it plainly does not, and `null` means +/// the re-read failed or was overtaken, leaving a deliberate retry possible. +class ActionRefusal { + const ActionRefusal(this.message, {this.stillPossible}); + + final String message; + final Future? stillPossible; +} + +/// Local guards, distinct from a server refusal; they never claim success. +const actionOptionRequired = 'Choose an option before continuing.'; +const actionAlreadySending = 'That action is still being sent.'; diff --git a/app/lib/features/runs/actions/cancel_dialog.dart b/app/lib/features/runs/actions/cancel_dialog.dart new file mode 100644 index 00000000..1654f442 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_dialog.dart @@ -0,0 +1,165 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'cancel_wording.dart'; + +/// Sends the confirmed cancellation. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef CancelSubmit = Future Function(); + +/// Opens the native cancel confirmation for [runId]. +/// +/// Nothing is sent until the operator presses the confirm action, and the +/// dismiss action (`Keep`) only closes the prompt. +Future showCancelRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required CancelSubmit onSubmit, +}) { + final prompt = _CancelPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _CancelPrompt extends StatefulWidget { + const _CancelPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final CancelSubmit onSubmit; + + @override + State<_CancelPrompt> createState() => _CancelPromptState(); +} + +class _CancelPromptState extends State<_CancelPrompt> { + bool _sending = false; + bool _checking = false; + bool _blocked = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(cancelDialogTitle(widget.runId)), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + TextButton( + key: cancelKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(cancelKeepLabel), + ), + FilledButton( + key: cancelConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: const Text(cancelConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(cancelDialogTitle(widget.runId)), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: cancelKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(cancelKeepLabel), + ), + CupertinoDialogAction( + key: cancelConfirmKey, + isDestructiveAction: true, + onPressed: _confirmDisabled ? null : _confirm, + child: const Text(cancelConfirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(cancelDialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: cancelErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/cancel_eligibility.dart b/app/lib/features/runs/actions/cancel_eligibility.dart new file mode 100644 index 00000000..a8cbb620 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_eligibility.dart @@ -0,0 +1,31 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may cancel [run], matching `canCancel` in +/// `web/src/actions.js` exactly: +/// +/// `(executing || (status == "waiting" && export_pending_sequence > 0)) && +/// !cancel_requested && !cleanup_unconfirmed` +/// +/// The status word alone is not enough: a stale `running` status without +/// `executing` is not cancellable, while a run waiting on a pending session +/// export is. +bool canCancelRun(JsonMap? run) { + if (run == null) return false; + final exportPending = _number(run['export_pending_sequence']); + return (run['executing'] == true || + (run['status'] == 'waiting' && exportPending > 0)) && + run['cancel_requested'] != true && + run['cleanup_unconfirmed'] != true; +} + +/// The run id used by the cancel request, or null for a malformed run. +num? cancelRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// `Number(value) > 0`, tolerating numeric strings as the browser does. +double _number(dynamic value) { + if (value is num) return value.toDouble(); + return double.tryParse('${value ?? ''}'.trim()) ?? 0; +} diff --git a/app/lib/features/runs/actions/cancel_run_action.dart b/app/lib/features/runs/actions/cancel_run_action.dart new file mode 100644 index 00000000..19bdf181 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_run_action.dart @@ -0,0 +1,119 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'cancel_dialog.dart'; +import 'cancel_eligibility.dart'; +import 'cancel_wording.dart'; + +/// The run detail's deliberate cancel entry point. +/// +/// Renders one native button only while [run] is cancellable under the browser +/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends +/// nothing; only the confirm action asks the server to stop the run. A refusal +/// is returned to the kept-open prompt immediately and the run is re-read +/// separately, so [onRunChanged] still receives server truth without locking +/// the prompt while that read is pending. +class CancelRunAction extends StatefulWidget { + const CancelRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _CancelRunActionState(); +} + +class _CancelRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = cancelRunId(widget.run); + if (id == null || !canCancelRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showCancelRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: () => _submit(id), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.cancelRun(id); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeCancelError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && cancelRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canCancelRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: cancelActionKey, + onPressed: _open, + child: const Text(cancelActionLabel), + ); + } + return FilledButton( + key: cancelActionKey, + onPressed: _open, + child: const Text(cancelActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/cancel_wording.dart b/app/lib/features/runs/actions/cancel_wording.dart new file mode 100644 index 00000000..b4812921 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_wording.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's cancel wording, kept verbatim. +const cancelActionLabel = 'Cancel run'; +const cancelDialogMessage = 'This asks the server to stop the active run.'; +const cancelConfirmLabel = 'Cancel run'; +const cancelKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const cancelActionKey = ValueKey('cancel-run-action'); +const cancelKeepKey = ValueKey('cancel-run-keep'); +const cancelConfirmKey = ValueKey('cancel-run-confirm'); +const cancelErrorKey = ValueKey('cancel-run-error'); + +/// The cancel dialog's title: `Cancel run {id}?`. +String cancelDialogTitle(num runId) => 'Cancel run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a cancellation that did not happen. +String describeCancelError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not cancel the run.' : message; +} diff --git a/app/lib/features/runs/actions/decision_action.dart b/app/lib/features/runs/actions/decision_action.dart new file mode 100644 index 00000000..246c66fb --- /dev/null +++ b/app/lib/features/runs/actions/decision_action.dart @@ -0,0 +1,176 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'action_refusal.dart'; +import 'decision_dialog.dart'; +import 'decision_wording.dart'; + +/// The run detail's deliberate human-decision entry point. +/// +/// Renders one native button only while [run] is genuinely waiting on a person. +/// Nothing is sent until the operator opens the prompt, chooses an option and +/// presses Confirm; cancel, selection and optional feedback stay local. A +/// server refusal is shown verbatim in the prompt immediately, the draft is +/// preserved and the run is re-read separately so [onRunChanged] still receives +/// server truth without locking the prompt while that read is pending. +class HumanDecisionAction extends StatefulWidget { + const HumanDecisionAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + this.cupertino, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + /// Overrides the platform style; by default it follows the enclosing app. + final bool? cupertino; + + @override + State createState() => _HumanDecisionActionState(); +} + +class _HumanDecisionActionState extends State { + PendingDecision? _pending; + bool _dialogOpen = false; + bool _sending = false; + Future? _resync; + + @override + void initState() { + super.initState(); + _pending = pendingDecision(widget.run); + } + + @override + void didUpdateWidget(covariant HumanDecisionAction oldWidget) { + super.didUpdateWidget(oldWidget); + _pending = pendingDecision(widget.run); + } + + bool _usesCupertino(BuildContext context) { + if (widget.cupertino != null) return widget.cupertino!; + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final decision = _pending; + if (decision == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showHumanDecisionPrompt( + context: context, + decision: decision, + cupertino: _usesCupertino(context), + onSubmit: (draft) => _submit(decision, draft), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit( + PendingDecision decision, + DecisionDraft draft, + ) async { + final option = draft.selected?.trim() ?? ''; + if (option.isEmpty) return const ActionRefusal(actionOptionRequired); + if (_sending) return const ActionRefusal(actionAlreadySending); + _sending = true; + final repository = RunsRepository(widget.gateway); + try { + final JsonMap run; + try { + run = await repository.decideRun( + decision.runId, + stage: decision.stageKey, + option: option, + feedback: draft.feedback, + ); + } catch (error) { + return ActionRefusal( + _describe(error), + stillPossible: _resyncRun(decision), + ); + } + if (!mounted) return null; + if (_owns(decision.runId)) { + setState(() => _pending = pendingDecision(run)); + widget.onRunChanged(run); + } + return null; + } finally { + _sending = false; + } + } + + bool _owns(num id) => mounted && widget.run['id'] == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(PendingDecision decision) { + return _resync ??= _readRun(decision); + } + + Future _readRun(PendingDecision expected) async { + try { + final run = await RunsRepository(widget.gateway).getRun(expected.runId); + if (!_owns(expected.runId)) return null; + final next = pendingDecision(run); + setState(() => _pending = next); + widget.onRunChanged(run); + return _stillDecidable(next, expected); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + /// Whether the refreshed run offers the same decision the prompt is showing. + bool _stillDecidable(PendingDecision? next, PendingDecision expected) { + if (next == null || + next.runId != expected.runId || + next.stageKey != expected.stageKey) { + return false; + } + final keys = next.options.map((option) => option.key).toSet(); + return expected.options.every((option) => keys.contains(option.key)); + } + + @override + Widget build(BuildContext context) { + final decision = _pending; + if (decision == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: decisionActionKey, + onPressed: _open, + child: const Text(decisionActionLabel), + ); + } + return FilledButton( + key: decisionActionKey, + onPressed: _open, + child: const Text(decisionActionLabel), + ); + } +} + +String _describe(Object error) { + final message = '$error'; + return message.trim().isEmpty ? 'The server refused the decision.' : message; +} diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart new file mode 100644 index 00000000..81aa717c --- /dev/null +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -0,0 +1,268 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'action_refusal.dart'; +import 'decision_wording.dart'; + +/// Sends the draft to the server. Returns null on success, or an +/// [ActionRefusal] with the server's words verbatim; the prompt stays open +/// with the draft intact and dismissal available immediately. +typedef DecisionSubmit = Future Function(DecisionDraft draft); + +/// Opens the native decision prompt for [decision]. +Future showHumanDecisionPrompt({ + required BuildContext context, + required PendingDecision decision, + required bool cupertino, + required DecisionSubmit onSubmit, +}) { + final prompt = _DecisionPrompt( + decision: decision, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _DecisionPrompt extends StatefulWidget { + const _DecisionPrompt({ + required this.decision, + required this.cupertino, + required this.onSubmit, + }); + + final PendingDecision decision; + final bool cupertino; + final DecisionSubmit onSubmit; + + @override + State<_DecisionPrompt> createState() => _DecisionPromptState(); +} + +class _DecisionPromptState extends State<_DecisionPrompt> { + DecisionDraft _draft = const DecisionDraft(); + late final TextEditingController _feedback = TextEditingController(); + bool _sending = false; + bool _checking = false; + bool _blocked = false; + String? _error; + + @override + void dispose() { + _feedback.dispose(); + super.dispose(); + } + + void _select(String option) { + if (_sending) return; + setState(() => _draft = _draft.select(option)); + } + + void _feedbackChanged(String value) => _draft = _draft.withFeedback(value); + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending || _checking || _blocked || !_draft.canSubmit) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_draft); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle(color: theme.colorScheme.error), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + RadioListTile( + value: option.key, + enabled: !_sending, + title: Text(option.key), + subtitle: _target(option), + ), + ], + ), + ), + feedback: TextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + decoration: const InputDecoration(labelText: decisionFeedbackLabel), + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + TextButton( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + FilledButton( + onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + CupertinoButton( + onPressed: _sending ? null : () => _select(option.key), + child: Row( + children: [ + CupertinoRadio( + value: option.key, + useCheckmarkStyle: true, + enabled: !_sending, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(option.key), + if (_targetText(option) case final target?) + Text(target), + ], + ), + ), + ], + ), + ), + ], + ), + ), + feedback: CupertinoTextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + placeholder: decisionFeedbackLabel, + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + CupertinoDialogAction( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _body({ + required TextStyle errorStyle, + required Widget options, + required Widget feedback, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(decisionMeta(widget.decision)), + if (widget.decision.instructions.trim().isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(widget.decision.instructions), + ), + Padding(padding: const EdgeInsets.only(top: 8), child: options), + Padding(padding: const EdgeInsets.only(top: 8), child: feedback), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: decisionErrorKey, style: errorStyle), + ), + ], + ); + } + + Widget? _target(DecisionOption option) { + final text = _targetText(option); + return text == null ? null : Text(text); + } + + String? _targetText(DecisionOption option) { + final text = decisionTargetText(option.target); + return text.isEmpty ? null : text; + } +} diff --git a/app/lib/features/runs/actions/decision_wording.dart b/app/lib/features/runs/actions/decision_wording.dart new file mode 100644 index 00000000..a9904946 --- /dev/null +++ b/app/lib/features/runs/actions/decision_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/run_decisions.dart'; + +/// The browser client's decision wording, kept verbatim. +const decisionWaitingTitle = 'Waiting for your decision'; +const decisionActionLabel = 'Decide'; +const decisionFeedbackLabel = 'Feedback (optional)'; +const decisionCancelLabel = 'Cancel'; +const decisionConfirmLabel = 'Confirm decision'; +const decisionSendingLabel = 'Sending…'; + +/// Stable test/semantics keys shared by the action and its prompt. +const decisionActionKey = ValueKey('human-decision-action'); +const decisionFeedbackKey = ValueKey('human-decision-feedback'); +const decisionErrorKey = ValueKey('human-decision-error'); + +/// `{stage} · run {id} · {label}`, as the web decision card shows it. +String decisionMeta(PendingDecision decision) => + '${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}'; + +/// The option's target line, `→ {target}`, or "" when no target was declared. +String decisionTargetText(String target) => + target.trim().isEmpty ? '' : '→ $target'; diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart new file mode 100644 index 00000000..28cda388 --- /dev/null +++ b/app/lib/features/runs/actions/retry_action.dart @@ -0,0 +1,123 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'retry_dialog.dart'; +import 'retry_eligibility.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// The run detail's deliberate retry entry point. +/// +/// Renders one native button only while [run] is a stopped `failed` run. Opening +/// the resume or restart confirmation sends nothing; only the confirm action +/// asks the server to retry. A refusal is returned to the kept-open prompt +/// immediately and the run is re-read separately, so [onRunChanged] still +/// receives server truth without locking the prompt while that read is pending. +class RetryRunAction extends StatefulWidget { + const RetryRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RetryRunActionState(); +} + +class _RetryRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = retryRunId(widget.run); + if (id == null || !canRetryRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showRetryRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: (intent) => _submit(id, intent), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, RetryIntent intent) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.retryRun( + id, + requestKey: intent.requestKey, + mode: intent.mode.wireMode, + ); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeRetryError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && retryRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canRetryRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } + return FilledButton( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart new file mode 100644 index 00000000..846133a1 --- /dev/null +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -0,0 +1,207 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// Sends the confirmed retry intent. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef RetrySubmit = Future Function(RetryIntent intent); + +/// Opens the native retry confirmation for [runId]. +/// +/// The first confirmation offers resume (the default) and a secondary +/// `Restart from start` confirmation, exactly like the browser's retry dialog. +/// Nothing is sent until the operator presses a confirm action; `Keep` only +/// closes the prompt. +Future showRetryRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required RetrySubmit onSubmit, +}) { + final prompt = _RetryPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _RetryPrompt extends StatefulWidget { + const _RetryPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final RetrySubmit onSubmit; + + @override + State<_RetryPrompt> createState() => _RetryPromptState(); +} + +class _RetryPromptState extends State<_RetryPrompt> { + RetryMode _mode = RetryMode.resume; + String? _requestKey; + bool _sending = false; + bool _checking = false; + bool _blocked = false; + bool _attempted = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + void _restart() { + if (_sending || _checking || _attempted) return; + setState(() { + _mode = RetryMode.restart; + _error = null; + }); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _attempted = true; + _error = null; + }); + final intent = RetryIntent( + mode: _mode, + requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + ); + final refusal = await widget.onSubmit(intent); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + bool get _showRestart => _mode == RetryMode.resume && !_attempted; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(_dialogTitle), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + if (_showRestart) + TextButton( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + TextButton( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + FilledButton( + key: retryConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(_dialogTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + if (_showRestart) + CupertinoDialogAction( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + CupertinoDialogAction( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + CupertinoDialogAction( + key: retryConfirmKey, + isDestructiveAction: _mode == RetryMode.restart, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(_dialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: retryErrorKey, style: errorStyle), + ), + ], + ); + } + + String get _dialogTitle => _mode == RetryMode.restart + ? restartDialogTitle(widget.runId) + : retryDialogTitle(widget.runId); + + String get _dialogMessage => + _mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage; + + String get _confirmLabel => + _mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel; +} diff --git a/app/lib/features/runs/actions/retry_eligibility.dart b/app/lib/features/runs/actions/retry_eligibility.dart new file mode 100644 index 00000000..13026230 --- /dev/null +++ b/app/lib/features/runs/actions/retry_eligibility.dart @@ -0,0 +1,16 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may retry [run], matching `canRetry` in +/// `web/src/actions.js` exactly: a loaded run that is not executing and whose +/// status is `failed`. A stale `failed` status while the run still executes is +/// not retryable. +bool canRetryRun(JsonMap? run) { + if (run == null) return false; + return run['executing'] != true && run['status'] == 'failed'; +} + +/// The run id used by the retry request, or null for a malformed run. +num? retryRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart new file mode 100644 index 00000000..17140a70 --- /dev/null +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -0,0 +1,29 @@ +import 'dart:math'; + +/// The two deliberate retry choices. `resume` is the server's default, so its +/// wire field is omitted; `restart` replays the whole pipeline. +enum RetryMode { + resume, + restart; + + /// The `retry_mode` value to send, or null to let the server resume. + String? get wireMode => this == RetryMode.restart ? 'restart' : null; +} + +/// One confirmed retry intent: the chosen mode plus the idempotency key that +/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the +/// server can dedupe it; a fresh deliberate intent uses a new key. +class RetryIntent { + const RetryIntent({required this.mode, required this.requestKey}); + + final RetryMode mode; + final String requestKey; +} + +/// A fresh `request_key` for one retry intent. The server requires one and caps +/// it at 128 characters; this stays well inside that bound and unique per call. +String newRetryRequestKey(num runId, {DateTime? now, int? random}) { + final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; + final entropy = random ?? Random().nextInt(1 << 32); + return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; +} diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart new file mode 100644 index 00000000..efec7d86 --- /dev/null +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -0,0 +1,33 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's retry wording, kept verbatim. +const retryActionLabel = 'Retry'; +const retryDialogMessage = + 'Only failed runs can be retried. The server starts a new run from the ' + 'same input.'; +const retryConfirmLabel = 'Retry'; +const restartDialogMessage = + 'This replays the whole pipeline from the start instead of resuming the ' + 'failed stage.'; +const restartConfirmLabel = 'Restart from start'; +const retryKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const retryActionKey = ValueKey('retry-run-action'); +const retryKeepKey = ValueKey('retry-run-keep'); +const retryConfirmKey = ValueKey('retry-run-confirm'); +const retryRestartKey = ValueKey('retry-run-restart'); +const retryErrorKey = ValueKey('retry-run-error'); + +/// The retry dialog's title: `Retry run {id}?`. +String retryDialogTitle(num runId) => 'Retry run $runId?'; + +/// The restart dialog's title: `Restart run {id}?`. +String restartDialogTitle(num runId) => 'Restart run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a retry that did not happen. +String describeRetryError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not retry the run.' : message; +} diff --git a/app/lib/features/runs/actions/title_action.dart b/app/lib/features/runs/actions/title_action.dart new file mode 100644 index 00000000..7a5b9b97 --- /dev/null +++ b/app/lib/features/runs/actions/title_action.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'title_dialog.dart'; +import 'title_wording.dart'; + +/// The run detail's rename entry point, mirroring the browser's rename row. +/// +/// The prompt starts with [run]'s stored title exactly as the server sent it +/// (never a prompt or output fallback). Typing and Cancel send nothing; only +/// Save sends `set_run_title` with the exact run id and title text. A refusal is +/// returned verbatim to the kept-open prompt, and only the server's returned +/// `run_detail` is delivered through [onRunChanged], once. +class RunTitleAction extends StatefulWidget { + const RunTitleAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RunTitleActionState(); +} + +class _RunTitleActionState extends State { + bool _dialogOpen = false; + bool _saving = false; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = runTitleId(widget.run); + if (id == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showRunTitlePrompt( + context: context, + runId: id, + initialTitle: storedRunTitle(widget.run), + cupertino: _usesCupertino(context), + onSubmit: (title) => _submit(id, title), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, String title) async { + if (_saving) return const ActionRefusal(actionAlreadySending); + _saving = true; + try { + final run = await RunsRepository(widget.gateway).setRunTitle(id, title); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal(describeTitleError(error)); + } finally { + _saving = false; + } + } + + bool _owns(num id) => mounted && runTitleId(widget.run) == id; + + @override + Widget build(BuildContext context) { + if (runTitleId(widget.run) == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } + return OutlinedButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } +} + +/// The run id used by the rename request, or null for a malformed run. +num? runTitleId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// The run's stored title exactly as the browser reads it +/// (`String(d.title ?? "")`); never inferred from the prompt or output. +String storedRunTitle(JsonMap run) { + final title = run['title']; + return title == null ? '' : '$title'; +} diff --git a/app/lib/features/runs/actions/title_dialog.dart b/app/lib/features/runs/actions/title_dialog.dart new file mode 100644 index 00000000..9ae03a11 --- /dev/null +++ b/app/lib/features/runs/actions/title_dialog.dart @@ -0,0 +1,183 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'title_wording.dart'; + +/// Sends the typed title. Returns null once the server has accepted it, or an +/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays +/// open with the typed title intact. +typedef TitleSubmit = Future Function(String title); + +/// Opens the native rename prompt for [runId], seeded with the run's stored +/// [initialTitle]. +/// +/// Typing and the dismiss action send nothing; only Save sends the title. The +/// title is passed through exactly as typed, including surrounding whitespace, +/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether +/// a blank title is acceptable. +Future showRunTitlePrompt({ + required BuildContext context, + required num runId, + required String initialTitle, + required bool cupertino, + required TitleSubmit onSubmit, +}) { + final prompt = _TitlePrompt( + runId: runId, + initialTitle: initialTitle, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _TitlePrompt extends StatefulWidget { + const _TitlePrompt({ + required this.runId, + required this.initialTitle, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final String initialTitle; + final bool cupertino; + final TitleSubmit onSubmit; + + @override + State<_TitlePrompt> createState() => _TitlePromptState(); +} + +class _TitlePromptState extends State<_TitlePrompt> { + late final TextEditingController _title = TextEditingController( + text: widget.initialTitle, + ); + bool _sending = false; + String? _error; + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _save() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_title.text); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal.message; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(runTitleDialogTitle), + content: _body( + field: TextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + decoration: const InputDecoration(labelText: runTitleFieldLabel), + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle(color: theme.colorScheme.error), + ), + actions: [ + TextButton( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + FilledButton( + key: runTitleSaveKey, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(runTitleDialogTitle), + content: _body( + field: CupertinoTextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + placeholder: runTitleFieldLabel, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + CupertinoDialogAction( + key: runTitleSaveKey, + isDefaultAction: true, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _body({required Widget field, required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field, + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: runTitleErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/title_wording.dart b/app/lib/features/runs/actions/title_wording.dart new file mode 100644 index 00000000..8fa85891 --- /dev/null +++ b/app/lib/features/runs/actions/title_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's rename wording, kept verbatim. +const runTitleActionLabel = 'Rename'; +const runTitleDialogTitle = 'Rename'; +const runTitleFieldLabel = 'Run title'; +const runTitleSaveLabel = 'Save'; +const runTitleCancelLabel = 'Cancel'; + +/// Stable test/semantics keys shared by the action and its prompt. +const runTitleActionKey = ValueKey('rename-run-action'); +const runTitleFieldKey = ValueKey('rename-run-field'); +const runTitleSaveKey = ValueKey('rename-run-save'); +const runTitleCancelKey = ValueKey('rename-run-cancel'); +const runTitleErrorKey = ValueKey('rename-run-error'); + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a rename that did not happen. +String describeTitleError(Object error) { + final message = '$error'; + return message.trim().isEmpty + ? 'The server did not rename the run.' + : message; +} diff --git a/app/lib/features/schedules/data/schedules_repository.dart b/app/lib/features/schedules/data/schedules_repository.dart new file mode 100644 index 00000000..432bf841 --- /dev/null +++ b/app/lib/features/schedules/data/schedules_repository.dart @@ -0,0 +1,116 @@ +import '../../../core/api_gateway.dart'; +import '../domain/saved_schedule.dart'; +import '../domain/schedule_json.dart'; + +/// Client-side protocol failure. Server refusals and transport errors are not +/// wrapped: [ApiGateway] already surfaces their exact text. +class SchedulesRepositoryException implements Exception { + const SchedulesRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// The saved-schedule commands of the current web client. +/// +/// These are run configurations, not pipeline definitions: this repository +/// never submits, validates or publishes a workflow, and it never starts or +/// polls a run. Timer execution belongs to the server. +class SchedulesRepository { + SchedulesRepository(this._gateway); + + final ApiGateway _gateway; + + /// Lists saved schedules, optionally for one pipeline. + /// + /// An explicit empty reply is a valid empty list. A reply without the + /// `schedules` type is not: that is an older/unsupported server and must be + /// reported rather than shown as "no schedules". + Future> listSchedules({int? pipelineId}) async { + final fields = {}; + if (pipelineId != null) { + if (!_isPositiveId(pipelineId)) { + throw const SchedulesRepositoryException( + 'A positive pipeline ID is required.', + ); + } + fields['pipeline_id'] = pipelineId; + } + final reply = await _gateway.call('list_schedules', fields); + final schedules = reply['schedules']; + if (reply['type'] != 'schedules' || + (schedules != null && schedules is! List)) { + throw const SchedulesRepositoryException( + 'The server returned no schedules response.', + ); + } + if (schedules == null) return const []; + return [ + for (final item in schedules as List) + if (item is Map) + SavedSchedule(Map.from(item)) + else + throw const SchedulesRepositoryException( + 'The server returned an invalid schedule record.', + ), + ]; + } + + /// Creates or updates one saved schedule. + /// + /// Creation sends the web client's sentinel record (`id` 0, no revision) and + /// may carry a stable request key so a lost reply is retried instead of + /// creating a duplicate. Updating sends the record read from the server, + /// whose `revision` is the compare-and-swap token; the key is omitted, as in + /// the web client. A stale revision is refused by the server and propagated + /// unchanged, never overwritten locally. + Future saveSchedule( + JsonMap schedule, { + String? requestKey, + }) async { + if (requestKey != null && requestKey.length > 128) { + throw const SchedulesRepositoryException( + 'Schedule request keys must be strings of at most 128 characters.', + ); + } + final fields = {'schedule': cloneJsonMap(schedule)}; + if (requestKey != null && requestKey.isNotEmpty) { + fields['request_key'] = requestKey; + } + final reply = await _gateway.call('save_schedule', fields); + final saved = reply['schedule']; + if (saved is! Map) { + throw const SchedulesRepositoryException( + 'The server returned no saved schedule.', + ); + } + return SavedSchedule(Map.from(saved)); + } + + /// Deletes exactly the revision the caller read. + /// + /// Both identity and revision are required before any request is sent; a + /// confirmation for a different schedule is treated as a failed delete. + Future deleteSchedule(int id, int revision) async { + if (!_isPositiveId(id) || !_isPositiveId(revision)) { + throw const SchedulesRepositoryException( + 'An exact schedule ID and revision are required.', + ); + } + final reply = await _gateway.call('delete_schedule', { + 'schedule_id': id, + 'expected_revision': revision, + }); + if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) { + throw const SchedulesRepositoryException( + 'The server did not confirm deletion of this schedule.', + ); + } + } +} + +/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks +/// `Number.isSafeInteger` before sending an identity. +const _maxSafeInteger = 9007199254740991; + +bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger; diff --git a/app/lib/features/schedules/domain/saved_schedule.dart b/app/lib/features/schedules/domain/saved_schedule.dart new file mode 100644 index 00000000..32570b72 --- /dev/null +++ b/app/lib/features/schedules/domain/saved_schedule.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; +import 'schedule_rule.dart'; + +/// One saved run configuration from `list_schedules` or `save_schedule`. +/// +/// A saved schedule is a complete run request pinned to one pipeline version. +/// It is deliberately not a pipeline definition: nothing here is published, +/// validated as a graph or treated as the pipeline's current version. +/// +/// [raw] keeps the exact server record, including fields this client does not +/// know yet. Typed getters are views; they never rewrite [raw]. +class SavedSchedule { + SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw); + + final JsonMap raw; + + /// Server identity; null when an older reply omits it. Never defaulted to 0, + /// because 0 is the create sentinel rather than a saved identity. + int? get id => _integer(raw['id']); + + /// Compare-and-swap token. Updates reuse it and deletes send it as + /// `expected_revision`; this client never invents or increments it. + int? get revision => _integer(raw['revision']); + + int? get pipelineId => _integer(raw['pipeline_id']); + int? get version => _integer(raw['version']); + String get name => _text(raw['name']); + bool get enabled => raw['enabled'] == true; + + JsonMap get input => _map(raw['input']); + String get prompt => _text(input['prompt']); + String get workspace => _text(raw['workspace']); + ScheduleRule get rule => ScheduleRule(_map(raw['rule'])); + + List get writePaths => _texts(raw['write_paths']); + bool get allowTools => raw['allow_tools'] == true; + String get model => _text(raw['model']); + Map get stageModels => { + for (final entry in _map(raw['stage_models']).entries) + if (entry.value is String) entry.key: entry.value as String, + }; + String get notifyMode => _text(raw['notify_mode']); + String get title => _text(raw['title']); + String get outputFormat => _text(raw['output_format']); + + String get nextDue => _text(raw['next_due']); + String get createdAt => _text(raw['created_at']); + String get updatedAt => _text(raw['updated_at']); + + /// The record to pass to `save_schedule`, deep-copied so callers cannot + /// mutate this snapshot by aliasing. + JsonMap toJson() => cloneJsonMap(raw); + + /// Pause/enable copy. Identity, revision and every unknown field are kept so + /// the update still targets the revision this record was read at. + SavedSchedule withEnabled(bool value) { + final copy = toJson(); + copy['enabled'] = value; + return SavedSchedule(copy); + } +} + +int? _integer(dynamic value) { + if (value is int) return value; + if (value is num && value.isFinite && value == value.truncateToDouble()) { + return value.toInt(); + } + return null; +} + +String _text(dynamic value) => value is String ? value : ''; + +JsonMap _map(dynamic value) { + if (value is! Map) return {}; + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; +} + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/lib/features/schedules/domain/schedule_json.dart b/app/lib/features/schedules/domain/schedule_json.dart new file mode 100644 index 00000000..a0e541bf --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_json.dart @@ -0,0 +1,22 @@ +import '../../../core/api_gateway.dart'; + +/// Deep copy of a decoded JSON value. +/// +/// Saved schedules travel back to the server unchanged, so unknown fields (and +/// unknown nested values) must survive every round trip without sharing state +/// with the reply map that produced them. +dynamic cloneJsonValue(dynamic value) { + if (value is Map) { + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; + } + if (value is List) { + return [for (final item in value) cloneJsonValue(item)]; + } + return value; +} + +JsonMap cloneJsonMap(JsonMap value) => + Map.from(cloneJsonValue(value) as Map); diff --git a/app/lib/features/schedules/domain/schedule_rule.dart b/app/lib/features/schedules/domain/schedule_rule.dart new file mode 100644 index 00000000..7eb4bed5 --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_rule.dart @@ -0,0 +1,41 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; + +/// Weekday keys the server accepts for an interval rule. +const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; + +/// The timer part of a saved schedule (`rule` on the wire). +/// +/// This is a view over the decoded server record, not a timer implementation: +/// it never calculates due times, converts timezones or starts runs. Unknown +/// rule fields stay in [raw] and are returned by [toJson]. +class ScheduleRule { + ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {}); + + final JsonMap raw; + + /// Go-style duration such as `24h` or `1h30m`; empty for a clock rule. + String get every => _text(raw['every']); + + /// Distinct 24-hour times such as `09:00`; empty for an interval rule. + List get times => _texts(raw['times']); + + /// Empty means every day (written as absent on the wire). + List get days => _texts(raw['days']); + + /// Empty or `Local` means the server's timezone. + String get timezone => _text(raw['timezone']); + + bool get isClock => times.isNotEmpty; + + JsonMap toJson() => cloneJsonMap(raw); +} + +String _text(dynamic value) => value is String ? value : ''; + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/lib/features/templates/data/template_repository.dart b/app/lib/features/templates/data/template_repository.dart new file mode 100644 index 00000000..da56f5ea --- /dev/null +++ b/app/lib/features/templates/data/template_repository.dart @@ -0,0 +1,84 @@ +import '../../../core/api_gateway.dart'; +import '../domain/template_entry.dart'; + +/// A templates protocol refusal kept separate from transport errors; server +/// error envelopes are propagated unchanged by [ApiGateway]. +class TemplateRepositoryException implements Exception { + const TemplateRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// Template catalogue, definition validation and create-only submission over +/// the application's shared gateway. +/// +/// These are reads plus one explicit submit. No method publishes, runs, +/// overwrites or schedules a pipeline, so merely loading or validating a +/// template can never start work. +class TemplateRepository { + TemplateRepository(this._gateway); + final ApiGateway _gateway; + + /// The server's template catalogue, exactly as `list_templates` returns it. + /// A reply without a `templates` field is the older server answering with no + /// catalogue, which is an empty list rather than an error. + Future> listTemplates() async { + final reply = await _gateway.call('list_templates'); + final templates = reply['templates']; + if (templates == null) return const []; + if (templates is! List) { + throw const TemplateRepositoryException( + 'The server returned no template catalogue.', + ); + } + return List.unmodifiable( + templates.map((entry) { + if (entry is! Map) { + throw const TemplateRepositoryException( + 'The server returned a template that is not an object.', + ); + } + return TemplateEntry.fromJson(Map.from(entry)); + }), + ); + } + + /// Parses one definition source on the server (`validate`) and returns the + /// graph it produced. The source is sent byte-for-byte: no trimming, casing or + /// whitespace changes. A malformed definition rejects with the server's own + /// error; a reply without a graph is refused rather than reported as valid. + Future validate(String source) async { + final reply = await _gateway.call('validate', {'source': source}); + final graph = reply['graph']; + if (graph is! Map) { + throw const TemplateRepositoryException('The server returned no graph.'); + } + return Map.from(graph); + } + + /// Creates a new draft pipeline from [source] (`submit`), create-only. + /// + /// A blank name is refused locally before anything is sent, matching the + /// browser and Android clients; the name that is sent is trimmed. The source + /// is not changed. `create_only` is always true, so an existing pipeline can + /// never be overwritten, and no run is started. + Future submit(String name, String source) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) { + throw const TemplateRepositoryException('Enter a pipeline name.'); + } + final reply = await _gateway.call('submit', { + 'name': trimmed, + 'source': source, + 'create_only': true, + }); + final detail = reply['detail']; + if (detail is! Map) { + throw const TemplateRepositoryException( + 'The server returned no pipeline detail.', + ); + } + return Map.from(detail); + } +} diff --git a/app/lib/features/templates/domain/template_entry.dart b/app/lib/features/templates/domain/template_entry.dart new file mode 100644 index 00000000..6c86bcbf --- /dev/null +++ b/app/lib/features/templates/domain/template_entry.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; + +/// One template from the server catalogue. +/// +/// The server owns this record: [key], [name], [description], [source] and +/// [scheduled] are read from it verbatim and every other field is kept in +/// [raw], so a later view or round-trip never loses fields this client does not +/// understand yet. Loading a template is a read; it never publishes or runs it. +class TemplateEntry { + const TemplateEntry({ + required this.key, + required this.name, + required this.description, + required this.source, + required this.scheduled, + required this.raw, + }); + + factory TemplateEntry.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return TemplateEntry( + key: _text(raw['key']), + name: _text(raw['name']), + description: _text(raw['description']), + source: _text(raw['source']), + scheduled: raw['scheduled'] == true, + raw: raw, + ); + } + + /// The stable catalogue key the gallery selects on. + final String key; + final String name; + final String description; + + /// The template's complete, untrimmed definition source. + final String source; + + /// Whether the source declares a schedule (the summary's "Includes a schedule"). + final bool scheduled; + + /// Every field the server sent, including fields this client does not model. + /// Deeply unmodifiable: nested maps and lists are copied into read-only + /// collections too, so a view cannot mutate the server reply through it. + final JsonMap raw; + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static JsonMap _frozenMap(Map json) => + Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) { + return _frozenMap(Map.from(value)); + } + if (value is List) { + return List.unmodifiable(value.map(_frozen)); + } + return value; + } +} diff --git a/app/notes/P2a.md b/app/notes/P2a.md new file mode 100644 index 00000000..a77dc77d --- /dev/null +++ b/app/notes/P2a.md @@ -0,0 +1,114 @@ +# P2a — graph domain: nodes, edges, terminals, run evidence and stage visits + +## What changed + +New, app-only, pure-Dart files. No server, web client, legacy client, shell, +`main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/domain/graph_protocol.dart` | 43 | terminal constants, `resolveTarget`, terminal labels | +| `lib/features/graph/domain/graph_definition.dart` | 152 | outcome/edge order, definition edges, definition nodes | +| `lib/features/graph/domain/run_graph_state.dart` | 124 | recorded visited stages/routes, current-stage fallback, live start | +| `lib/features/graph/domain/stage_visits.dart` | 107 | sequence-ordered visits, display visit, clamped visit selection | +| `test/features/graph/domain/graph_fixtures.dart` | 96 | linear/diamond/self-loop/incomplete definitions and step fixtures | +| `test/features/graph/domain/graph_protocol_test.dart` | 56 | shorthand and terminal-label regressions | +| `test/features/graph/domain/graph_definition_test.dart` | 229 | edge order/ids, loops, duplicate keys, missing/unknown targets | +| `test/features/graph/domain/run_graph_state_test.dart` | 170 | linear/diamond/self-loop/repeated visits/outcomes/terminals/no evidence | +| `test/features/graph/domain/run_graph_state_live_test.dart` | 91 | current/last-stage fallback, live start, finished run | +| `test/features/graph/domain/stage_visits_test.dart` | 150 | repeated visits by sequence, latest default, clamping, absent visit | + +No layout, coordinates, widgets, styles or rendering were added. + +## Behavior copied from the current web client + +- **Terminals and `#`** (`web/src/protocol.js`): `#success`, `#failure`, + `isTerminal` only for the explicit keys, and `resolveTarget`: a bare `#` + becomes `#failure` for the `error` outcome and `#success` for every other + outcome. All other values are preserved verbatim, including `""` and unknown + stage keys. A missing target stays `null`, never a fabricated terminal. +- **Labels** (`web/src/graph.js`): `nodeDisplayLabel` gives `Success` / + `Failure` for graph nodes; `nodeLabel` gives the TUI-mirroring `SUCCESS` / + `FAILURE`. Stage keys are unchanged. +- **Definition edges** (`web/src/graph.js`): outcomes are success first, other + outcomes alphabetical, `error` last; stages keep declaration order; ids are + contiguous in that order; the label carries `error*` only when + `fallback_error` is true. A `null` edge value declares no edge and is + skipped. Empty/unknown targets are kept, with `knownTarget == false`. +- **Definition nodes** (`web/src/graph.js` `layoutGraph`): stage nodes keep + declaration order and one identity per key; terminal nodes are appended + failure then success once any declared edge resolves to a terminal. These + are definition nodes only, never run evidence. +- **Run evidence** (`web/src/runDetail.js` `runGraphState`): visited stages in + first-appearance order without duplicates; routes keyed + `source\0outcome\0resolvedTarget` without duplicates; only a resolved + terminal is visited by its target; a non-terminal target is not visited until + a step lands there. Current stage is `current_stage` when non-blank, else the + last recorded step's stage, else `null`. A start timestamp is read only while + executing, for a `running` visit of the current stage. +- **Visits** (`web/src/runDetail.js` `runTimeline`, `clampVisitIndex`, + `displayVisit`, and `web/src/app.js` stage routing): visits are grouped by + stage and ordered by recorded sequence with stable ties; the display visit + is a positive `control.visit`, else position + 1; no requested visit selects + the stage's most recent visit; an explicit index clamps to `[0, count)`; a + stage with no recorded visit yields `step == null`. + +The run map is the same detail the runs feature already holds; this slice only +reads `steps`, so it adds no second event fold. Live-event merging remains in +`lib/features/runs/domain/run_step_evidence.dart` and `run_events.dart`. + +## Honest edge handling + +- A missing/`null` definition edge produces no edge and no node. +- An empty or unknown target is returned as recorded, flagged `knownTarget: + false`; it never becomes a stage node or terminal and never produces a + visited stage. +- A blank recorded stage key is not turned into an empty visited identity. A + step with a blank outcome or target records no route and no terminal visit. +- Self edges and loops record one route and one node identity; nothing recurses. +- A stage with no recorded visits cannot be presented as visited: selection + exposes a null step rather than synthesizing one. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph test/features/graph # 10 files, 0 changed after formatting +flutter test test/features/graph/domain # 41 passed +flutter analyze # No issues found! (0.8s) +flutter test # 139 passed +``` + +Focused coverage is the requested matrix: + +- **Linear**: plan -> build -> ship, contiguous ids, implicit `error*` + fallback, terminals. +- **Diamond**: fan-out/fan-in edges stay distinct and ordered; converging + routes do not merge. +- **Self loop**: `a/retry -> a` is one edge and one node identity; one run + self-loop is one route and one visited stage. +- **Repeated stage**: repeated visits remain separate ordered entries; visited + stage identity is not duplicated; repeated identical routes collapse. +- **Different outcomes**: success/approved/rejected routes to the same target + remain distinct. +- **Terminals**: bare `#` resolves by outcome, explicit terminals normalize, + labels are `SUCCESS`/`FAILURE`, mid-run targets do not fabricate visits. +- **Missing evidence**: null/absent/malformed steps and graphs yield empty + evidence, no terminals and no fabricated visits. + +## Honest limits + +- **No UI, layout or wiring.** This is deliberately the nonvisual foundation + slice; the native graph screen, layout, highlighting and interaction are + later work and are not claimed here. +- **No browser evidence.** A nonvisual pure-Dart change has no rendered + behavior to capture; no browser or screenshot check applies. +- **No live server or device used.** All tests use local fixtures. No run, + pipeline, schedule, workflow or service was created, changed or restarted. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no + Android/iOS build, emulator, ADB or device. +- **Committed, not deployed.** The reviewed slice is commit `2c10507` on + `flutter/p2-model`; current `main` was merged in after review (final merge + `f07ada0`, which includes `main` `e8bde4f`). No push, install, preview server + or canonical-URL change was made by this landing stage; server-side checks and + the actual land follow. diff --git a/app/notes/P2b.md b/app/notes/P2b.md new file mode 100644 index 00000000..91d5e07a --- /dev/null +++ b/app/notes/P2b.md @@ -0,0 +1,100 @@ +# P2b — deterministic pure node layout + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/layout/layout_models.dart` | 127 | measured extents, gap config, immutable node box, layout + ranks | +| `lib/features/graph/layout/graph_ranks.dart` | 191 | deterministic SCC ranks over the landed definition nodes/edges | +| `lib/features/graph/layout/graph_node_layout.dart` | 142 | column/row placement, bounds, validation | +| `test/features/graph/layout/layout_fixtures.dart` | 102 | shared definitions and measured extents | +| `test/features/graph/layout/graph_ranks_test.dart` | 116 | linear/diamond/cycle/self-loop/disconnected/unknown/long-chain ranks | +| `test/features/graph/layout/graph_node_layout_test.dart` | 224 | ordering, terminals, heterogeneous and expanded extents, bounds, determinism | +| `test/features/graph/layout/graph_layout_validation_test.dart` | 96 | empty input, missing/extra measurements, duplicate keys, invalid sizes | + +No layout widgets, painters, edge routing, styling or shell wiring were added. + +## Public API + +```dart +GraphRanks assignGraphRanks(List nodes, List edges); + +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}); +``` + +`NodeExtent` is the caller's measured width/height after text layout. +`GraphLayoutConfig` takes `columnGap`, `rowGap` and an optional outer `padding`. +No node size, font, colour or device value is assumed in the library. + +`GraphLayout` returns an unmodifiable `nodes` list of `GraphNodeBox` +(`key`, `terminal`, `stageIndex`, `rank`, `x`, `y`, `width`, `height`), an +unmodifiable `ranks` map, `rankCount`, and total `width`/`height` including +padding. Node keys, terminal flags and stage indices are copied from the +landed `graphNodes` identities unchanged. + +## Ranking behavior + +Ranks are read from the definition supplied by the caller; the existing +`graphNodes`/`graphEdges` helpers remain the source of identities. + +- Iterative Tarjan strongly connected components (no recursion; a 2000-stage + chain is covered), then longest-path ranks over the condensation DAG. +- Every member of a cycle shares one rank, so cyclic routes cannot recurse or + push members apart. Self loops are internal supervision and add no rank. +- Disconnected stages and disconnected terminals stay at rank 0. +- Edges whose source or target is not a node are ignored. An unknown or empty + target never creates a node or a rank. +- Ranking is linear in nodes plus edges and stable for repeated input. + +## Placement behavior + +- One column per rank; nodes keep definition order inside a rank. +- A column is as wide as its widest measured node; columns are separated by + `columnGap` and top-aligned. +- Nodes are centred in their column and stacked with exactly `rowGap` between + measured boxes (centres are compared in the heterogeneous test). +- Supplied widths/heights are placed verbatim, so expanded text is never + clipped to a fixed box; growing the extents grows the total bounds. +- Bounds include every box: tests assert `right <= width` and + `bottom <= height` for every fixture. +- The result is immutable and identical for identical input. + +Measurements are required for every node; a missing key throws +`ArgumentError` rather than inventing a default size. Extra measurements are +ignored because they cannot become nodes. Duplicate/empty node keys, negative +or non-finite gaps and extents are rejected. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/layout test/features/graph/layout +flutter test test/features/graph/layout # 21 passed +flutter analyze # No issues found! +flutter test # 173 passed +git diff --check # clean +``` + +Tests cover linear, diamond, cycle, self-loop, disconnected, terminals, +unknown/empty targets, heterogeneous extents, 2.6x expanded text, determinism, +bounds and invalid input. + +## Honest limits + +- **Nodes only.** Edge routing, ports, labels, lanes, hit testing, selection + highlighting, painting and native controls are separate later items. +- **Not rendered.** A pure nonvisual slice has no browser behavior to capture; + no screenshot or browser check applies. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/notes/R2a.md b/app/notes/R2a.md new file mode 100644 index 00000000..30ec1ace --- /dev/null +++ b/app/notes/R2a.md @@ -0,0 +1,84 @@ +# R2a — native human-decision action + +## What changed + +New `lib/features/runs/actions/` slice (no existing source file edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `decision_action.dart` | 141 | `HumanDecisionAction`, gating, submit/refusal/resync orchestration | +| `decision_dialog.dart` | 248 | Material `AlertDialog` / Cupertino `CupertinoAlertDialog` prompt | +| `decision_wording.dart` | 24 | Web-verbatim words, meta/target formatting and test keys | +| `test/.../decision_action_test.dart` | 237 | Material/Cupertino deliberate send and gating | +| `test/.../decision_resilience_test.dart` | 240 | refusal resync, double submit, disposal, 2x/narrow | + +`HumanDecisionAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one `FilledButton` (`Decide`) on Material +and one `CupertinoButton.filled` on Cupertino, and nothing at all when +`pendingDecision(run)` is null. Recorded waiting-step options therefore win over +the pinned graph, and a pending session export suppresses the action through the +existing domain rule without duplicating it here. + +Opening the prompt sends nothing. The prompt uses the web wording +(`Waiting for your decision`, `Feedback (optional)`, `Cancel`, +`Confirm decision`, `Sending…`), shows the stage/run meta line and each option's +`→ target` when declared. Confirm is disabled until an option is selected; +selecting itself only updates the draft. Confirm calls `RunsRepository.decideRun` +with the exact stage, trimmed option and trimmed optional feedback (blank +feedback is omitted by the repository). + +A refusal is shown verbatim inside the kept-open prompt; the option selection +and feedback controller are untouched. The action then calls +`RunsRepository.getRun` and passes the refreshed run to `onRunChanged`. A +successful decision passes the server's `run_detail` to `onRunChanged` and +closes the prompt. Both sends are guarded in the prompt and in the owner state; +buttons are disabled while `Sending…`. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +Platform style follows the enclosing app: `MaterialApp` gets the Material +dialog and controls, `CupertinoApp` gets the Cupertino dialog with native +buttons/radios/field. No custom palette, font family, fixed button/row size, +dependency or CSS token was added; the theme's error color and default control +spacing are used. The one optional `cupertino` override exists for +callers/tests that do not wrap in either app. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions test/features/runs/actions +flutter analyze # No issues found! +flutter test test/features/runs # 18 passed +flutter test # 36 passed +flutter test test/features/runs/actions # 7 passed +flutter build web # Built build/web (14.2s) +``` + +Focused coverage maps to the requested acceptance: + +- material: action visible, dialog open, selection does not send, Confirm is + disabled before selection, exact `decide_run` stage/option/`looks good` + feedback, callback gets the decided run and the action disappears; +- cupertino: native `CupertinoAlertDialog`, disabled Confirm first, blank + feedback omitted, exact request fields; +- gating: running, export-pending and non-human runs render no action; +- refusal: `decide_run` then `get_run`, verbatim error still visible, selected + option and typed feedback retained, refreshed failed run delivered to owner; +- double submit: two Confirm taps produce one `decide_run`, Cancel is disabled + while sending; +- stale disposal: completing the decision after the tree is replaced produces + no exception and no owner callback; +- 320×480 at 2x text on both apps: prompt opens with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** `lib/features/runs/` has no screen or + controller on this branch; the manager owns that integration. There is + therefore no real browser interaction or capture for this widget. The + `flutter build web` result proves compilation only, not rendered behavior. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway. +- No repository/domain/controller/screen/main, `web/`, Go server, installer or + deployment file was changed. Nothing was committed, pushed or deployed. diff --git a/app/notes/R2b-refusal.md b/app/notes/R2b-refusal.md new file mode 100644 index 00000000..65851110 --- /dev/null +++ b/app/notes/R2b-refusal.md @@ -0,0 +1,92 @@ +# R2b-refusal — immediate refusals, separate resync + +Focused correction on the retained `faa5866` cancellation candidate. The action +source is now shared by both deliberate run actions (cancel and human decision); +no wiring, screen, controller, repository, socket, pubspec, web, server or +device file was touched. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/action_refusal.dart` | 18 | Refusal message plus optional bounded re-read outcome; local guard words | +| `lib/features/runs/actions/cancel_run_action.dart` | 119 | Immediate refusal return, single-flight resync, ownership checks | +| `lib/features/runs/actions/cancel_dialog.dart` | 165 | Shows the refusal and re-enables Keep before the resync settles | +| `lib/features/runs/actions/decision_action.dart` | 176 | Same async flow for `decide_run`, draft preserved | +| `lib/features/runs/actions/decision_dialog.dart` | 268 | Shows refusal, keeps draft, disables retry only on server truth | +| `test/features/runs/actions/cancel_resilience_test.dart` | 271 | Three new fake-gateway regressions | +| `test/features/runs/actions/decision_resilience_test.dart` | 351 | Three new fake-gateway regressions | +| `test/features/runs/actions/decision_action_test.dart` | 265 | Cancel/no-request coverage | + +## Async flow + +A refused mutation no longer awaits `get_run` before returning: + +1. `_submit` catches the mutation error and computes the refusal text. +2. It returns `ActionRefusal(message, stillPossible: _resyncRun(id))` at once. + `_resyncRun` starts one `get_run` for that refusal; a concurrent refusal + observes the same future instead of issuing another request. +3. The prompt clears its sending state, shows the server's words and makes + Keep/Cancel available in the same frame. Back is enabled too (`PopScope` + only gates the in-flight mutation). Confirm stays disabled while the check + is pending and after it proves the action impossible, so a doomed mutation + cannot be resubmitted from the open prompt. +4. The resync runs detached but bounded: exactly one `get_run`, no retries or + polling. Every exception becomes `null` (unknown truth), which leaves the + refusal visible and a deliberate retry available. +5. Before delivering a refreshed run, the action checks `mounted` and that the + run id it owns is still the request's id. A late read after disposal or + navigation touches nothing and raises nothing. + +On success the mutation reply is still used directly, the prompt closes, and no +duplicate `get_run` is issued. The dialog and action keep the existing +in-flight double-submit guard. The human-decision prompt keeps the selected +option and feedback controller untouched while a refusal or resync is pending; +its retry is disabled only when the refreshed run no longer offers the same +decision (same stage and option keys). + +No repository, protocol or socket code changed. The web's `cancel_run` plus +silent refresh remains the reference; this version keeps the diagnostic in the +open prompt rather than moving it to the web's separate Action-failed dialog. + +## Regression coverage added + +Fake gateway, no socket or real server: + +- immediate `cancel_run` refusal plus a deliberately unresolved `get_run`: the + exact message is visible, Keep is enabled, confirm is disabled and no run + callback has fired **before** the resync completes; Keep closes the prompt; + a late resync still delivers server truth safely; +- late cancel resync after the whole action is disposed: no exception, no + callback; +- resync proving the run is no longer cancellable: refusal stays visible, + confirm cannot submit again (an attempted tap adds no request), Keep + dismisses and the ineligible run is delivered; +- immediate `decide_run` refusal plus an unresolved `get_run`: exact message, + selection and feedback retained, Cancel enabled, no callback yet; after the + resync proves the decision gone, the message remains and confirm is disabled; +- decision resync that fails: message and draft remain, Confirm is re-enabled + because server truth is unknown; +- late decision resync after disposal: no exception, no callback; +- Cancel on an untouched decision draft sends nothing and keeps the action + available. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 23 passed +flutter test # 52 passed +flutter build web # Built build/web +``` + +## Honest limits + +- Still **not wired into a run-detail screen** on this branch; there is no + browser interaction or rendered capture for this widget. `flutter build web` + proves compilation only. +- Mobile remains unverified: no Android/iOS build, emulator, ADB or device. +- No real server or run was mutated; all evidence uses local fakes. +- No commit, push, deployment or canonical-URL change is claimed here beyond + the candidate commit checked by the manager. diff --git a/app/notes/R2b.md b/app/notes/R2b.md new file mode 100644 index 00000000..0fda73b5 --- /dev/null +++ b/app/notes/R2b.md @@ -0,0 +1,96 @@ +# R2b — native run cancellation + +## What changed + +New `lib/features/runs/actions/cancel*` slice plus its tests. No existing source +file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/cancel_eligibility.dart` | 31 | Web-exact `canCancelRun`, run-id extraction, numeric export counter | +| `lib/features/runs/actions/cancel_wording.dart` | 23 | Web-verbatim words, dialog title, error text, test keys | +| `lib/features/runs/actions/cancel_dialog.dart` | 145 | Native Material/Cupertino confirmation and inline refusal | +| `lib/features/runs/actions/cancel_run_action.dart` | 101 | `CancelRunAction`, gating, send/refusal/resync orchestration | +| `test/features/runs/actions/cancel_test_support.dart` | 101 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/cancel_action_test.dart` | 192 | Eligibility and both-platform deliberate-confirm flows | +| `test/features/runs/actions/cancel_resilience_test.dart` | 176 | Refusal/resync, resync failure, double submit, disposal, 2x/narrow | + +`CancelRunAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one native `FilledButton` (`Cancel run`) on +Material and one `CupertinoButton.filled` on Cupertino, and nothing at all when +the browser rule says the run is not cancellable. Platform style follows the +enclosing app (`MaterialLocalizations` presence); no extra style parameter or +dependency was added. + +## Behaviour + +Eligibility is a direct port of `canCancel` in `../web/src/actions.js`: + +``` +(executing || (status == "waiting" && export_pending_sequence > 0)) + && !cancel_requested && !cleanup_unconfirmed +``` + +A run with a stale `running` status but `executing == false` is therefore not +cancellable, while a `waiting` run with a pending session export is. A run +without a numeric `id` is not offered because the request cannot be addressed +(the pure eligibility function still matches the web rule exactly). + +Opening the prompt sends nothing and `Keep` only closes it. The prompt uses the +web wording (`Cancel run {id}?`, `This asks the server to stop the active run.`, +`Cancel run`, `Keep`). Only the confirm action calls +`RunsRepository.cancelRun(id)`, which sends the exact envelope +`cancel_run {"run_id": id}`. + +Both the dialog and the action guard the in-flight state: a second confirm tap +or a `Keep` tap while sending is ignored, and the dialog's actions are disabled +until the reply arrives. A successful reply closes the prompt and passes the +server's returned `run_detail` to `onRunChanged`; no local status is invented. + +A refusal keeps the prompt open and shows the server's message verbatim. The +action then calls `RunsRepository.getRun(id)` and passes the refreshed run to +`onRunChanged`, so the owner sees server truth (for example the run finished +before cancellation). If the re-read also fails, the original refusal stays +visible and no synthetic run is delivered. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions/cancel*.dart \ + test/features/runs/actions/cancel*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 16 passed +flutter test # 45 passed +flutter build web # Built build/web (15.5s) +``` + +Focused coverage maps to the requested acceptance: + +- eligibility: executing, export-wait, waiting without export, stale `running` + without `executing`, already stopping, cleanup unconfirmed, finished/failed; + plus widget visibility for the same states; +- both platforms: native prompt opens, nothing is sent on open or `Keep`, exact + `cancel_run` envelope, callback receives the returned run, action disappears; +- refusal: cancellation error shown verbatim, `get_run` resync delivered to the + owner, and a failed resync leaves the refusal visible with no callback; +- double submit: two confirm taps produce one `cancel_run`, both actions disable; +- stale disposal: a reply after the tree is replaced causes no exception and no + callback; +- 320x480 at 2x text: both prompts open with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen + or controller; the manager owns integration. There is therefore no real + browser interaction or capture for this widget. `flutter build web` proves + compilation only, not rendered behavior, and no visible feature is claimed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway with no + socket. +- No controller/screen/main/domain/repository/pubspec, `web/`, Go server, + installer or deployment file was changed. Nothing was committed, pushed or + deployed. diff --git a/app/notes/R2c.md b/app/notes/R2c.md new file mode 100644 index 00000000..f2240602 --- /dev/null +++ b/app/notes/R2c.md @@ -0,0 +1,114 @@ +# R2c — native retry / restart action + +Small app-only addition, new files only. `RetryRunAction(run, gateway, +onRunChanged)` is the deliberate retry entry point for a stopped failed run; it +does not add a screen or controller and is not wired into the shell. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/retry_action.dart` | 123 | `RetryRunAction`, gating, send/refusal/resync orchestration | +| `lib/features/runs/actions/retry_dialog.dart` | 207 | Native resume/restart confirmation, refusal display, key lifetime | +| `lib/features/runs/actions/retry_eligibility.dart` | 16 | `canRetryRun` mirroring the web `canRetry` | +| `lib/features/runs/actions/retry_intent.dart` | 29 | Mode, confirmed intent and idempotency-key generation | +| `lib/features/runs/actions/retry_wording.dart` | 33 | Web-verbatim words, titles, error wording and test keys | +| `test/.../retry_test_support.dart` | 112 | Fake gateway and Material/Cupertino hosts | +| `test/.../retry_action_test.dart` | 245 | Eligibility, both platforms, modes and key fields | +| `test/.../retry_resilience_test.dart` | 223 | Immediate refusals, recheck outcomes, key retention | +| `test/.../retry_safety_test.dart` | 133 | Double submit, late replies, narrow 2x layout | + +No repository, gateway, socket, controller, shell, main, pubspec, web, server or +device file was edited. + +## Behavior + +Eligibility is exactly the browser's rule: a loaded run that is not executing and +whose status is `failed` (`run != null && !run.executing && status == "failed"`). +A stale `failed` status while execution is still in flight, a running/waiting/ +succeeded/canceled run, and a malformed run render nothing. + +The button is a Material `FilledButton` or a Cupertino `CupertinoButton.filled`, +labelled `Retry`. Opening the prompt sends nothing, and `Keep` only closes it. + +The first confirmation is the browser's retry copy: title `Retry run {id}?`, +message `Only failed runs can be retried. The server starts a new run from the +same input.`, confirm `Retry`, dismiss `Keep`, plus the browser-only secondary +`Restart from start` that leads to a distinct confirmation. That second prompt +uses title `Restart run {id}?`, message `This replays the whole pipeline from the +start instead of resuming the failed stage.` and confirm `Restart from start`; +the resume actions are gone, so the more destructive choice cannot be mistaken +for resume. + +Resume calls `RunsRepository.retryRun` with only `run_id` and `request_key`, so +`retry_mode` is omitted and the server's `resume` default applies. Restart sends +`retry_mode: "restart"` with the same two required fields. + +A `request_key` is created on the first confirm of an open prompt, not on opening +or `Keep`. It survives a refusal, so pressing confirm again for the same +uncertain request reuses the key and the server can dedupe it. Closing the prompt +and opening it again is a fresh deliberate intent and gets a new key, so a resume +attempt followed by a restart attempt never shares a key. Switching to the +restart confirmation before any send simply confirms restart with that prompt's +first key. Keys are bounded and run-scoped (`app-retry-{runId}-…`, well under the +server's 128-character cap). + +A server refusal returns to the prompt immediately: the exact server words are +visible and `Keep`/back are available while the detached `get_run` recheck is +still pending. One bounded re-read is issued per refusal, single-flight through a +retained future, with no retry loop or polling. If server truth says the run is no +longer retryable, confirm is disabled and an attempted tap sends nothing; the +refusal stays visible until dismissal. If the recheck itself fails, truth is +unknown, so confirm is re-enabled and a deliberate retry uses the retained key. +Late retry replies and late rechecks after disposal or navigation are ignored. + +Construction, controls and error colour are standard Material/Cupertino defaults; +there is no custom palette, fixed control size or dependency. The narrow layout +relies on the native dialog's own scrolling/wrapping. + +## Acceptance checks + +Fake-gateway widget tests, both platforms, no socket or real server: + +- eligibility table for stopped failed vs executing failed, running, waiting, + succeeded and canceled runs, plus the same visibility table under both apps; +- `Retry` opens the native `AlertDialog`/`CupertinoAlertDialog`, `Keep` closes it + and the recorded gateway calls are still empty; +- resume sends exactly `{run_id, request_key}` and no `retry_mode`; restart sends + exactly `{run_id, request_key, retry_mode: "restart"}`; +- key format is deterministic under an injected clock/entropy, bounded, fresh per + call, retained across an uncertain retry (resume and restart), and different + after a deliberate reopen or mode change; +- refusal message appears while `get_run` is deliberately unresolved, with Keep + enabled, confirm disabled and no callback yet; Keep then closes and the late + recheck still delivers server truth safely; +- ineligible recheck (`succeeded`) blocks a repeat action; failed recheck leaves + the same key and a working deliberate retry; +- two confirm taps while in flight produce one `retry_run`; both the retry reply + and the recheck are safe after disposal; +- 320×480 at 2× text: both resume and restart confirmations render on both apps + with no exception, and Keep sends nothing. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 40 passed +flutter test # 69 passed +flutter build web # Built build/web (14.5s) +``` + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no runs screen or + controller; the manager owns that integration. There is no browser interaction + or rendered capture for this widget, and `flutter build web` proves compilation + only, not rendered behavior. +- Browser parity is by source/word/request-shape comparison with + `web/src/actions.js` and `web/src/repository.js`; the web client itself was not + changed and no live web retry was performed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. +- No real server or run was retried, canceled or otherwise mutated; all evidence + uses local fakes. +- The candidate is committed, not pushed or deployed. diff --git a/app/notes/R2d.md b/app/notes/R2d.md new file mode 100644 index 00000000..c262351f --- /dev/null +++ b/app/notes/R2d.md @@ -0,0 +1,93 @@ +# R2d — native run title rename + +## What changed + +New `lib/features/runs/actions/title*` slice plus its tests and this note. No +existing source file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/title_wording.dart` | 24 | Web-verbatim words, test keys, refusal wording | +| `lib/features/runs/actions/title_dialog.dart` | 183 | Native Material/Cupertino text-field prompt and inline refusal | +| `lib/features/runs/actions/title_action.dart` | 109 | `RunTitleAction`, stored-title seeding, send/deliver orchestration | +| `test/features/runs/actions/title_test_support.dart` | 110 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/title_action_test.dart` | 244 | Both-platform open/cancel/exact-save and stored-title seeding | +| `test/features/runs/actions/title_resilience_test.dart` | 243 | Refusal retention, double save, disposal, stale owner, 2x/narrow | + +`RunTitleAction(run: …, gateway: …, onRunChanged: …)` renders one native +`OutlinedButton` (`Rename`) on Material and one plain `CupertinoButton` on +Cupertino, and nothing for a run without a numeric id. Platform style follows the +enclosing app (`MaterialLocalizations` presence). No style overrides, fixed +component sizes or new dependencies. + +## Behaviour and web parity + +The prompt is seeded with the run's actual stored title exactly as the browser +reads it, `String(d.title ?? "")` in `web/src/views/runDetail.js`. It is never +derived from `input.prompt`, stage output or a placeholder. A missing title seeds +an empty field. + +Typing, opening and the dismiss action send nothing. Only `Save` calls the +existing `RunsRepository.setRunTitle(id, title)`, which sends the exact envelope: + +``` +set_run_title {"run_id": , "title": } +``` + +The field text is passed through untrimmed, matching `repo.setRunTitle(id, +String(state.renameValue ?? ""))` in `web/src/repository.js`. Leading/trailing +spaces and Unicode are preserved, and a blank title is sent as `""` so the server, +not the client, decides whether it is acceptable. There is no local +`canSubmit` gate on blank text. + +A refusal (including a blank-title refusal) is shown verbatim below the field and +the prompt stays open with the typed draft intact. Nothing is updated locally. +Only an accepted reply closes the prompt and passes the server's returned +`run_detail` once through `onRunChanged`; the action never fabricates a run or a +title. A second Save tap while sending is ignored, both dialog actions disable +until the reply, and every asynchronous resume checks `mounted`. A reply for a run +the widget no longer owns is dropped. + +## Checks actually run + +``` +dart format lib/features/runs/actions/title*.dart \ + test/features/runs/actions/title*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions/title_action_test.dart \ + test/features/runs/actions/title_resilience_test.dart # 11 passed +flutter test test/features/runs # 45 passed +flutter test # 63 passed +flutter build web # Built build/web (16.2s) +``` + +Focused acceptance coverage: + +- both platforms: native button and dialog, stored title in the field, typing and + Cancel produce zero gateway calls, Save sends exact `set_run_title` fields; +- exact field values: Unicode plus leading/trailing whitespace preserved; blank + title sent as `""` and the server refusal shown with the blank draft retained; +- failed save: server words verbatim, draft retained, dialog open, no callback and + no local title change; transport failure likewise; +- double Save: one request, action buttons disabled while in flight; +- disposal: a late reply after the tree is replaced throws nothing and delivers + nothing; a reply after the widget's run id changes is not delivered; +- 320x480 at 2x text: both prompts open, show a long title and a refusal, and close + with no rendering exception; +- malformed run: no rename button, and the stored-title helper ignores prompts. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen or + controller; the manager owns integration. No real browser interaction or + capture was performed, so rendered feature parity is not claimed. `flutter build + web` proves compilation of the existing entrypoint, not that this widget is + reachable or visible. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses portable Flutter/Cupertino/Material widgets only. +- No real server, operator run or chat was touched. Tests use a local fake gateway + with no socket. +- No repository/domain/controller/shell/main/pubspec, `web/`, Go server, + installer or deployment file was changed. +- Nothing was committed, pushed or deployed; the files above are the candidate in + the working tree, per the stage instruction not to commit. diff --git a/app/notes/S1a.md b/app/notes/S1a.md new file mode 100644 index 00000000..58426e32 --- /dev/null +++ b/app/notes/S1a.md @@ -0,0 +1,94 @@ +# S1a — saved-schedule repository and record + +## What changed + +New, app-only files (no existing feature, shell, transport, `main` or pubspec +source edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/data/schedules_repository.dart` | 116 | `list_schedules`, `save_schedule`, `delete_schedule` envelopes and reply checks | +| `lib/features/schedules/domain/saved_schedule.dart` | 87 | typed view over one saved run configuration; exact raw record retained | +| `lib/features/schedules/domain/schedule_rule.dart` | 41 | interval/clock/timezone/weekday fields of `rule` | +| `lib/features/schedules/domain/schedule_json.dart` | 22 | deep JSON copy used by every round trip | +| `test/features/schedules/data/schedules_repository_test.dart` | 132 | list/create/update envelopes, unchanged input, CAS revision | +| `test/features/schedules/data/schedules_delete_test.dart` | 131 | delete envelope, confirmations, refusals, missing/empty replies | +| `test/features/schedules/data/schedules_protocol_bounds_test.dart` | 81 | web-mirrored ID/revision/request-key bounds | +| `test/features/schedules/data/saved_schedule_record_test.dart` | 101 | provenance, unknown fields, deep-copy and absent-field behavior | +| `test/features/schedules/data/schedule_test_support.dart` | 83 | recording fake gateway and server-shaped fixtures | + +`app/.gitignore` also gained the missing `!/test/**/data/` exception. The root +`.gitignore` ignores every `data/` directory, so without it these assigned tests +would silently disappear from a fresh checkout. The existing `!/lib/**/data/` +exception is for the same reason. + +## Behavior copied from the current web client + +Requests are exactly the ones in `web/src/repository.js`: + +- `list_schedules` with no field, or `pipeline_id` for one pipeline. A positive + safe integer is required before sending; `{type:"schedules"}` or + `schedules:null` is an empty list, while a reply without `type:"schedules"` is + an error, not "no schedules". +- `save_schedule` with `schedule` unchanged. A non-empty `request_key` (at most + 128 characters) is added only for a create retry; updates omit it, as the web + editor does. Creation keeps the web sentinel `id: 0` and no revision. Updates + send the record read from the server, whose `revision` is the server's + compare-and-swap token. The reply is only accepted when it contains + `schedule`. +- `delete_schedule` with exactly `schedule_id` and `expected_revision`; only + `{type:"schedule_deleted", schedule_id:}` counts as success. + +Server refusals are not wrapped or translated. `ApiGateway` already turns an +`error` envelope into `ProtocolError` with the server's text, and the repository +lets that object through unchanged (conflict and unknown-command coverage in +`server refusals and conflicts propagate verbatim`). The repository has no +capability flags, no "not supported" substitution and no local fallback. + +Saved schedules are run configurations, never pipeline definitions. `SavedSchedule` +keeps the complete server map, including unknown future nested fields, and +exposes pipeline, version, prompt/input, workspace, rule (every/times/days/ +timezone), enabled, model/stage models, notify mode, write paths/tools, title, +output format, due time and timestamps. `toJson()` is a deep copy; `withEnabled` +preserves identity, revision and unknowns. Missing identity/revision stays +`null` rather than becoming a fabricated `0`. There is no timer execution, +polling, rule parsing into due dates or timezone conversion in this slice. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/schedules test/features/schedules # 9 files, 5 changed, then clean +flutter test test/features/schedules/data # 18 passed +flutter analyze # No issues found! (1.4s) +flutter test # 70 passed +``` + +Focused coverage maps to the requested acceptance: + +- exact `list_schedules`/`save_schedule`/`delete_schedule` bodies recorded by a + fake gateway, including `expected_revision` only on delete and no invented + create revision/key; +- untouched caller record on save; deep equality of returned records with the + server reply including unknown top-level/rule/input fields; +- update reuses revision 3, accepts server revision 4 and leaves the stale draft + at 3; a mismatch is the server's refusal, propagated verbatim; +- empty list vs missing/unsupported schedules reply, missing/invalid saved + schedule, and delete confirmation for the wrong id/type; +- preflight bounds match the web client: pipeline id, schedule id, revision and + 129-character request keys send nothing; 128 characters is accepted; +- no fabricated identity when a reply contains an empty schedule object. + +## Honest limits + +- **No UI or wiring.** There is no schedules screen, editor, pause/delete control + or shell registration in this slice; the manager owns later UI integration. + No browser interaction or screenshot applies to this nonvisual item. +- **No live server used.** All checks use local recording fakes; no production + schedule, run or workflow was created, changed or deleted. No polling or + scheduler was touched. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran. No + Android/iOS build, emulator, ADB or device was used; the code is pure Dart. +- **Not committed.** The stage instruction for this visit forbids commit, push + and deploy, so the candidate remains in the `flutter/s1-data` worktree for the + manager to inspect and commit. No deployment or preview was performed. diff --git a/app/notes/T1a.md b/app/notes/T1a.md new file mode 100644 index 00000000..e8a39fc4 --- /dev/null +++ b/app/notes/T1a.md @@ -0,0 +1,140 @@ +# T1a — template catalogue, validate and create-only submit + +## What changed + +New nonvisual `templates` data/domain slice. One shared file was edited: +`app/.gitignore` re-includes `test/**/data/`, because the repository's runtime +`data/` rule was silently excluding this slice's tests from the candidate. No +other lane's work, `lib/main.dart`, shell, pubspec, `web/`, server or Android +file was touched. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/templates/domain/template_entry.dart` | 63 | Immutable server template; models key/name/description/source/scheduled and keeps every unknown field in deeply read-only `raw` | +| `lib/features/templates/data/template_repository.dart` | 84 | `TemplateRepository(ApiGateway)`: list, validate, create-only submit | +| `test/features/templates/data/template_test_support.dart` | 47 | Recording/refusing fake gateways, server-refusal error, Unicode source fixture | +| `test/features/templates/data/template_list_test.dart` | 165 | Catalogue request shape, field preservation, deep immutability, missing/malformed catalogue | +| `test/features/templates/data/template_create_test.dart` | 147 | Validate/submit envelopes, blank-name gate, missing payloads, verbatim refusals | +| `app/.gitignore` | +4 | Re-includes `test/**/data/` so test files enter the candidate | + +Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was changed. No dependency was added. + +## Review findings addressed + +- **Tests could never land (blocking).** `test/features/templates/data/` was + excluded by the repository root rule `data/`; `app/.gitignore` only re-included + `lib/**/data/`. The same negation now covers `test/**/data/`, so these three + test files are untracked-but-visible to git and `git add -n` succeeds. Fixing + the rule (rather than `git add -f`) also protects later `test/**/data/` lanes + such as S1a. No test was moved, so `test/` still mirrors `lib/`. +- **`raw` was only shallowly immutable (advisory).** `TemplateEntry.fromJson` + now deep-copies nested maps/lists into read-only collections, and the listed + test proves nested mutation throws and that the copy does not alias the reply. +- **Malformed-catalogue branches were untested (advisory).** Added tests for a + non-list `templates` value and a non-object catalogue entry, both rejecting + with explicit messages. +- `_text` still stringifies a non-string protocol value with `'$value'`; the + protocol only sends strings, and this matches how the browser would render + such a value, so the behaviour was left unchanged and is documented here + rather than claimed as strict parity. + +## Wire behaviour (mirrors `web/src/repository.js`) + +- `listTemplates()` sends exactly `{"type":"list_templates"}` with no fields and + returns the `templates` catalogue. A reply with no `templates` field is the + older server's empty catalogue (`?? []` in the browser), not a fake template. + Each entry keeps `key`, `name`, `description`, `source`, `scheduled` and all + unknown fields in `TemplateEntry.raw`; the reply list/maps are never mutated. + `raw` is a deep unmodifiable copy: nested unknown maps and lists are copied + into read-only collections, so neither the view nor a later caller can mutate + the server reply through it. +- `listTemplates()` rejects a malformed envelope instead of fabricating + entries: a non-list `templates` throws + `"The server returned no template catalogue."` and a non-object entry throws + `"The server returned a template that is not an object."`. The real server + cannot produce either, but a protocol mistake must not look like an empty or + half-populated catalogue. +- `validate(source)` sends exactly `{"type":"validate","source":}` and + returns the reply's `graph`. A reply without a graph throws + `TemplateRepositoryException("The server returned no graph.")` — the browser's + exact words — rather than reporting a valid definition. +- `submit(name, source)` sends exactly + `{"type":"submit","name":,"source":,"create_only":true}`. + A blank/whitespace-only name is refused locally with + `TemplateRepositoryException("Enter a pipeline name.")` and no gateway call is + made; the accepted name is trimmed. A reply without `detail` throws + `TemplateRepositoryException("The server returned no pipeline detail.")`. +- The source string is never trimmed, normalised or re-encoded: Unicode, tabs, + newlines and significant leading/trailing whitespace arrive unchanged. +- A server refusal is never caught or reworded by the repository. It reaches the + caller as the same gateway error object, so the server's own text is shown. +- The repository exposes only these three operations. It has no publish, run, + schedule or overwrite path, so loading or validating a template cannot start + work or mutate a retained pipeline. + +## Checks actually run + +``` +flutter pub get # Got dependencies +dart format lib/features/templates test/features/templates # clean +flutter analyze # No issues found! (0.9s) +flutter test test/features/templates # 13 passed +flutter test # 76 passed +flutter build web # ✓ Built build/web (15.5s) +git diff --check # clean +git check-ignore / git add -n # tests are no longer ignored +``` + +Tests are part of the candidate, not merely present on disk: + +``` +$ git add -n app/test/features/templates/data/template_list_test.dart \ + app/test/features/templates/data/template_create_test.dart \ + app/test/features/templates/data/template_test_support.dart +add 'app/test/features/templates/data/template_create_test.dart' +add 'app/test/features/templates/data/template_list_test.dart' +add 'app/test/features/templates/data/template_test_support.dart' +exit=0 + +$ git status --porcelain=v1 -uall + M app/.gitignore +?? app/lib/features/templates/data/template_repository.dart +?? app/lib/features/templates/domain/template_entry.dart +?? app/notes/T1a.md +?? app/test/features/templates/data/template_create_test.dart +?? app/test/features/templates/data/template_list_test.dart +?? app/test/features/templates/data/template_test_support.dart +``` + +Focused acceptance coverage: + +- exact `list_templates` request (no fields, one call) and preservation of + modelled plus unknown fields, including nested unknown data; +- listing does not mutate the reply's template list or entry maps; `raw` and + every nested map/list are read-only, and the copy does not alias the reply; +- missing catalogue -> empty list; malformed catalogue -> explicit refusal; +- blank/whitespace name -> refusal with zero gateway calls; +- Unicode/emoji, tab/newline and leading/trailing source whitespace preserved in + both `validate` and `submit`; submit sends only name, source and + `create_only: true`, with the name trimmed; +- missing `graph` and missing `detail` rejected with the browser's exact + messages, with no fabricated graph/detail; +- validate and submit server refusals surface as the identical error object, + not a wrapper. + +## Honest limits + +- **Not wired into a screen.** This branch has no templates screen and the task + owns data/domain only; the manager owns integration. No browser capture was + made because there is no rendered change in this slice. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + The code is plain Dart with no platform-specific code. +- No live server, template catalogue, validate call or submit/creation was + performed. All tests use local fake gateways with no socket, so no real + pipeline was created or run. +- No export-gate workaround, server change or service operation was made; the + pending export-cap fix remains another lane's scope. +- **Not committed.** The stage instruction says not to commit, push or deploy, + so the candidate above is uncommitted in the working tree even though the run + prompt asks to commit a reviewed candidate. Nothing was pushed or deployed. diff --git a/app/test/features/graph/domain/graph_definition_test.dart b/app/test/features/graph/domain/graph_definition_test.dart new file mode 100644 index 00000000..deb13d62 --- /dev/null +++ b/app/test/features/graph/domain/graph_definition_test.dart @@ -0,0 +1,229 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('outcome and edge order', () { + test('success first, other outcomes alphabetical, error last', () { + expect( + stageOutcomes( + stage( + 'a', + edges: { + 'error': '#', + 'rejected': 'a', + 'success': 'b', + 'approved': 'b', + 'retry': 'a', + }, + ), + ), + ['success', 'approved', 'rejected', 'retry', 'error'], + ); + expect(stageOutcomes({}), isEmpty); + expect(stageOutcomes(null), isEmpty); + }); + + test('edgeLabel marks only an implicit fallback error route', () { + expect( + edgeLabel({'fallback_error': true}, 'error'), + 'error*', + ); + expect( + edgeLabel({'fallback_error': false}, 'error'), + 'error', + ); + expect( + edgeLabel({'fallback_error': true}, 'success'), + 'success', + ); + expect(edgeLabel({}, 'rejected'), 'rejected'); + }); + }); + + group('linear definition', () { + test('edges keep stage and outcome order with contiguous ids', () { + final edges = graphEdges(linearGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4, 5]); + expect(edges.map((edge) => edge.source), [ + 'plan', + 'plan', + 'build', + 'ship', + 'ship', + ]); + expect(edges.map((edge) => edge.outcome), [ + 'success', + 'error', + 'success', + 'success', + 'error', + ]); + expect(edges.map((edge) => edge.target), [ + 'build', + '#failure', + 'ship', + '#success', + '#failure', + ]); + expect(edges.map((edge) => edge.label), [ + 'success', + 'error*', + 'success', + 'success', + 'error', + ]); + expect(edges.where((edge) => edge.fallback).map((edge) => edge.id), [ + 2, + ]); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + + test('nodes are declaration order plus failure then success terminals', () { + final nodes = graphNodes(linearGraph()); + expect(nodes.map((node) => node.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(nodes.map((node) => node.stageIndex), [0, 1, 2, null, null]); + expect(nodes.map((node) => node.terminal), [ + false, + false, + false, + true, + true, + ]); + expect(nodes[3].label, 'Failure'); + expect(nodes[3].shortLabel, 'FAILURE'); + expect(nodes[4].label, 'Success'); + expect(nodes[4].shortLabel, 'SUCCESS'); + }); + }); + + group('diamond definition', () { + test('keeps every converging edge distinct in stable order', () { + final edges = graphEdges(diamondGraph()); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/approved->c', + 'a/error->#failure', + 'b/success->d', + 'c/success->d', + 'd/success->#success', + ], + ); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + }); + + group('self loops', () { + test('a self edge is one edge and never duplicates node identity', () { + final graph = selfLoopGraph(); + final edges = graphEdges(graph); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/retry->a', + 'b/success->#success', + 'b/error->#failure', + ], + ); + expect(edges[1].source, edges[1].target); + expect(edges[1].knownTarget, isTrue); + + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), [ + 'a', + 'b', + failureEnd, + successEnd, + ]); + expect(nodes.where((node) => node.key == 'a'), hasLength(1)); + }); + + test( + 'a stage declared twice keeps one node and one set of edges per key', + () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'a'}), + stage('a', edges: {'success': '#success'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), [ + 'a', + failureEnd, + successEnd, + ]); + // Both declarations are still definition data, with unique edge ids. + expect(graphEdges(graph).map((edge) => edge.id), [1, 2]); + }, + ); + }); + + group('missing and unknown targets', () { + test( + 'an absent edge declares nothing; empty and unknown targets stay honest', + () { + final edges = graphEdges(incompleteGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4]); + expect(edges.map((edge) => edge.outcome), [ + 'blocked', + 'retry', + 'error', + 'success', + ]); + expect(edges[0].target, ''); + expect(edges[0].knownTarget, isFalse); + expect(edges[1].target, 'ghost'); + expect(edges[1].knownTarget, isFalse); + expect(edges[2].target, failureEnd); + expect(edges[2].fallback, isTrue); + expect(edges[3].target, successEnd); + }, + ); + + test('an unknown target does not become a node or a terminal', () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'ghost'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), ['a']); + expect(graphEdges(graph).single.knownTarget, isFalse); + }); + + test('a graph with no stages has no nodes or edges', () { + expect(graphNodes({}), isEmpty); + expect(graphEdges({'stages': null}), isEmpty); + expect(graphNodes(null), isEmpty); + }); + }); + + test( + 'definition nodes ignore run evidence even when the graph map carries it', + () { + final graph = { + 'stages': [ + stage('a', edges: {'success': 'b'}), + stage('b'), + ], + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ], + 'visited_stages': ['a', 'b'], + }; + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), ['a', 'b']); + expect(nodes.every((node) => !node.terminal), isTrue); + }, + ); +} diff --git a/app/test/features/graph/domain/graph_fixtures.dart b/app/test/features/graph/domain/graph_fixtures.dart new file mode 100644 index 00000000..3a074221 --- /dev/null +++ b/app/test/features/graph/domain/graph_fixtures.dart @@ -0,0 +1,96 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Small, server-shaped fixtures shared by the graph domain tests. + +JsonMap step({ + int sequence = 0, + String stage = '', + String status = 'completed', + String outcome = '', + String target = '', + String startedAt = '', + Map? control, +}) { + return { + 'sequence': sequence, + 'stage': stage, + 'status': status, + 'outcome': outcome, + 'target': target, + if (startedAt.isNotEmpty) 'started_at': startedAt, + 'control': ?control, + }; +} + +JsonMap stage( + String key, { + Map edges = const {}, + bool fallbackError = false, + String type = 'model', +}) { + return { + 'key': key, + 'type': type, + 'edges': edges, + if (fallbackError) 'fallback_error': true, + }; +} + +/// plan -> build -> ship, with an implicit failure fallback on plan and an +/// explicit terminal pair on ship. +JsonMap linearGraph() => { + 'stages': [ + stage( + 'plan', + edges: {'success': 'build', 'error': '#'}, + fallbackError: true, + ), + stage('build', edges: {'success': 'ship'}), + stage( + 'ship', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// a fans out to b/c and both converge on d. +JsonMap diamondGraph() => { + 'stages': [ + stage( + 'a', + edges: {'success': 'b', 'approved': 'c', 'error': '#'}, + fallbackError: true, + ), + stage('b', edges: {'success': 'd'}), + stage('c', edges: {'success': 'd'}), + stage('d', edges: {'success': '#success'}), + ], +}; + +/// a retries itself and can still succeed into b; terminal pair on b. +JsonMap selfLoopGraph() => { + 'stages': [ + stage('a', edges: {'success': 'b', 'retry': 'a'}), + stage( + 'b', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// A definition with an absent edge, an empty target and an unknown target. +JsonMap incompleteGraph() => { + 'stages': [ + stage( + 'a', + edges: { + 'success': null, + 'blocked': '', + 'retry': 'ghost', + 'error': '#', + }, + fallbackError: true, + ), + stage('b', edges: {'success': '#success'}), + ], +}; diff --git a/app/test/features/graph/domain/graph_protocol_test.dart b/app/test/features/graph/domain/graph_protocol_test.dart new file mode 100644 index 00000000..972fc77e --- /dev/null +++ b/app/test/features/graph/domain/graph_protocol_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +void main() { + group('terminal target normalization', () { + test('a bare # resolves by outcome exactly like the web protocol', () { + expect(resolveTarget('error', '#'), failureEnd); + expect(resolveTarget('success', '#'), successEnd); + expect(resolveTarget('approved', '#'), successEnd); + expect(resolveTarget('', '#'), successEnd); + }); + + test('explicit, empty and unknown targets are preserved verbatim', () { + expect(resolveTarget('success', successEnd), successEnd); + expect(resolveTarget('error', failureEnd), failureEnd); + expect(resolveTarget('success', 'review'), 'review'); + expect(resolveTarget('blocked', ''), ''); + expect(resolveTarget('retry', 'ghost'), 'ghost'); + expect(resolveTarget('success', ' #success'), ' #success'); + }); + + test( + 'a missing target stays missing instead of fabricating a terminal', + () { + expect(resolveTarget('success', null), isNull); + expect(resolveTarget(null, null), isNull); + }, + ); + + test('only the explicit terminal keys are terminals', () { + expect(isTerminalTarget(successEnd), isTrue); + expect(isTerminalTarget(failureEnd), isTrue); + expect(isTerminalTarget('#'), isFalse); + expect(isTerminalTarget('review'), isFalse); + expect(isTerminalTarget(''), isFalse); + expect(isTerminalTarget(null), isFalse); + }); + }); + + group('terminal labels', () { + test('TUI labels are SUCCESS and FAILURE', () { + expect(nodeLabel(successEnd), 'SUCCESS'); + expect(nodeLabel(failureEnd), 'FAILURE'); + expect(nodeLabel('implementer'), 'implementer'); + expect(nodeLabel(''), ''); + expect(nodeLabel(null), ''); + }); + + test('display labels title-case the terminals and keep stage keys', () { + expect(nodeDisplayLabel(successEnd), 'Success'); + expect(nodeDisplayLabel(failureEnd), 'Failure'); + expect(nodeDisplayLabel('implementer'), 'implementer'); + expect(nodeDisplayLabel(null), ''); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_live_test.dart b/app/test/features/graph/domain/run_graph_state_live_test.dart new file mode 100644 index 00000000..18244107 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_live_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('current stage fallback', () { + test('the run current stage wins over the last recorded visit', () { + final state = runGraphState({ + 'current_stage': 'committer', + 'steps': [step(sequence: 1, stage: 'review')], + }); + expect(state.currentStage, 'committer'); + }); + + test('a blank current stage falls back to the last visit, else null', () { + final fallback = runGraphState({ + 'current_stage': ' ', + 'steps': [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'b'), + ], + }); + expect(fallback.currentStage, 'b'); + + final blankLast = runGraphState({ + 'steps': [step(sequence: 1)], + }); + expect(blankLast.currentStage, isNull); + }); + }); + + group('active stage and start', () { + test('a live run exposes its running visit start', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.executing, isTrue); + expect(state.activeStage, 'review'); + expect(state.currentStageStartedAt, '2026-01-01T00:00:00Z'); + }); + + test('a finished run has no active stage or start', () { + final state = runGraphState({ + 'executing': false, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.activeStage, isNull); + expect(state.currentStageStartedAt, isNull); + }); + + test('only an exact running status with a non-blank start is used', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'Running', + startedAt: '2026-01-01T00:00:00Z', + ), + step( + sequence: 2, + stage: 'review', + status: 'running', + startedAt: ' ', + ), + ], + }); + expect(state.currentStageStartedAt, isNull); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_test.dart b/app/test/features/graph/domain/run_graph_state_test.dart new file mode 100644 index 00000000..3af43777 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_test.dart @@ -0,0 +1,170 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('linear run evidence', () { + test('visits and routes follow the recorded visits', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'), + step(sequence: 2, stage: 'build', outcome: 'success', target: 'ship'), + step( + sequence: 3, + stage: 'ship', + outcome: 'success', + target: '#success', + ), + ], + }); + expect(state.visitedStages, [ + 'plan', + 'build', + 'ship', + successEnd, + ]); + expect(state.takenRoutes, [ + 'plan\u0000success\u0000build', + 'build\u0000success\u0000ship', + 'ship\u0000success\u0000#success', + ]); + expect(state.currentStage, 'ship'); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + expect(state.activeStage, isNull); + }); + }); + + group('diamond run evidence', () { + test('repeated visits keep one identity and loop routes stay distinct', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 3, stage: 'd', outcome: 'rejected', target: 'b'), + step(sequence: 4, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 5, stage: 'd', outcome: 'success', target: '#success'), + ], + }); + expect(state.visitedStages, ['a', 'b', 'd', successEnd]); + expect(state.visitedStages.where((key) => key == 'b'), hasLength(1)); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'b\u0000success\u0000d', + 'd\u0000rejected\u0000b', + 'd\u0000success\u0000#success', + ]); + }); + + test('different outcomes to the same target stay separate routes', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'a', outcome: 'approved', target: 'b'), + step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'a\u0000approved\u0000b', + ]); + }); + }); + + group('self edges', () { + test('a self edge is evidence, not a second visit or recursion', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'), + step(sequence: 2, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000retry\u0000a', + 'a\u0000success\u0000b', + ]); + }); + }); + + group('terminals', () { + test('a bare # resolves to failure on error and success otherwise', () { + final failed = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'error', target: '#'), + ], + }); + expect(failed.visitedStages, ['impl', failureEnd]); + expect(failed.visitedStages, isNot(contains(successEnd))); + expect(failed.isRouteTaken('impl', 'error', '#'), isTrue); + + final succeeded = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'done', target: '#'), + ], + }); + expect(succeeded.visitedStages, ['impl', successEnd]); + expect(succeeded.visitedStages, isNot(contains(failureEnd))); + }); + + test('a non-terminal target is not visited until a step lands on it', () { + final state = runGraphState({ + 'steps': [ + step( + sequence: 1, + stage: 'impl', + outcome: 'success', + target: 'review', + ), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.isStageVisited('review'), isFalse); + expect(state.isRouteTaken('impl', 'success', 'review'), isTrue); + }); + + test('blank outcome or target records no route and no terminal visit', () { + final state = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'success', target: ''), + step(sequence: 2, stage: 'impl', outcome: '', target: '#success'), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.takenRoutes, isEmpty); + }); + }); + + group('missing evidence', () { + test('absent run or steps fabricates no visits', () { + for (final run in [ + null, + {}, + {'steps': null}, + {'steps': []}, + ]) { + final state = runGraphState(run); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + expect(state.currentStage, isNull); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + } + }); + + test('malformed step entries are ignored, not invented', () { + final state = runGraphState({ + 'steps': ['nope', 42, null], + }); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + }); + }); +} diff --git a/app/test/features/graph/domain/stage_visits_test.dart b/app/test/features/graph/domain/stage_visits_test.dart new file mode 100644 index 00000000..dcf77840 --- /dev/null +++ b/app/test/features/graph/domain/stage_visits_test.dart @@ -0,0 +1,150 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/stage_visits.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('ordered stage visits', () { + test('repeated visits are ordered by sequence, not input order', () { + final steps = [ + step( + sequence: 5, + stage: 'review', + outcome: 'rejected', + target: 'implementer', + control: {'visit': 2}, + ), + step(sequence: 3, stage: 'implementer'), + step( + sequence: 2, + stage: 'review', + outcome: 'success', + target: 'done', + control: {'visit': 1}, + ), + ].cast>(); + + final byStage = visitsByStage(steps); + expect(byStage.keys, ['review', 'implementer']); + expect(byStage['review']!.map((visit) => visit['sequence']), [2, 5]); + expect(byStage['review']!.map((visit) => visit['outcome']), [ + 'success', + 'rejected', + ]); + expect(displayVisit(byStage['review']![0], 0), 1); + expect(displayVisit(byStage['review']![1], 1), 2); + }); + + test('equal sequences keep their recorded order', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'first'), + step(sequence: 1, stage: 'a', outcome: 'second'), + ].cast>(); + expect( + visitsByStage(steps)['a']!.map((visit) => visit['outcome']), + ['first', 'second'], + ); + }); + + test('a missing control visit falls back to the position', () { + final steps = [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'a'), + ].cast>(); + final visits = visitsByStage(steps)['a']!; + expect(displayVisit(visits[0], 0), 1); + expect(displayVisit(visits[1], 1), 2); + }); + + test( + 'a non-positive or malformed control visit falls back to position', + () { + expect( + displayVisit(step(control: {'visit': 0}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': -1}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': '3'}), 0), + 3, + ); + expect(displayVisit(step(), 4), 5); + }, + ); + }); + + group('clamping', () { + test('keeps a valid index and handles an empty list', () { + expect(clampVisitIndex(0, 3), 0); + expect(clampVisitIndex(2, 3), 2); + expect(clampVisitIndex(99, 3), 2); + expect(clampVisitIndex(-4, 3), 0); + expect(clampVisitIndex(5, 0), 0); + }); + }); + + group('selection', () { + List> repeatedVisits() => [ + step(sequence: 5, stage: 'review', outcome: 'rejected'), + step(sequence: 2, stage: 'review', outcome: 'success'), + ].cast>(); + + test('no requested visit selects the stage most recent recorded visit', () { + final selection = selectStageVisit(repeatedVisits(), 'review'); + expect(selection.hasVisit, isTrue); + expect(selection.index, 1); + expect(selection.step!['sequence'], 5); + expect(selection.visitNumber, 2); + }); + + test('an explicit visit selects that recorded visit', () { + final selection = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: 0, + ); + expect(selection.step!['sequence'], 2); + expect(selection.visitNumber, 1); + }); + + test('out-of-range indexes clamp to the nearest recorded visit', () { + final late = selectStageVisit(repeatedVisits(), 'review', visitIndex: 99); + expect(late.index, 1); + expect(late.step!['sequence'], 5); + expect(late.correctedRequest(99), isTrue); + + final early = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: -4, + ); + expect(early.index, 0); + expect(early.step!['sequence'], 2); + expect(early.correctedRequest(-4), isTrue); + expect(early.correctedRequest(null), isFalse); + }); + + test('a stage with no recorded visit returns no fabricated step', () { + final selection = selectStageVisit(repeatedVisits(), 'never-ran'); + expect(selection.hasVisit, isFalse); + expect(selection.step, isNull); + expect(selection.index, 0); + expect(selection.visitNumber, 0); + + final empty = selectStageVisit(const >[], 'review'); + expect(empty.hasVisit, isFalse); + expect(empty.step, isNull); + }); + + test('an absent capture for one stage does not hide another stage', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ].cast>(); + expect(selectStageVisit(steps, 'a').hasVisit, isTrue); + expect(selectStageVisit(steps, 'b').hasVisit, isFalse); + }); + }); +} diff --git a/app/test/features/graph/layout/graph_layout_validation_test.dart b/app/test/features/graph/layout/graph_layout_validation_test.dart new file mode 100644 index 00000000..dd70f7ee --- /dev/null +++ b/app/test/features/graph/layout/graph_layout_validation_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +/// Invalid and boundary input for the pure layout engine. +void main() { + test('an empty definition yields empty padded bounds', () { + final layout = layoutGraphNodes( + nodes: const [], + edges: const [], + extents: const {}, + config: layoutConfig(columnGap: 30, rowGap: 10, padding: 6), + ); + + expect(layout.isEmpty, isTrue); + expect(layout.rankCount, 0); + expect(layout.width, 12); + expect(layout.height, 12); + expect(layout.ranks, isEmpty); + }); + + test('missing measurements are reported rather than invented', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes)..remove('build'); + + expect( + () => layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra measurements are ignored because they cannot become nodes', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes) + ..['ghost'] = NodeExtent(width: 20, height: 20); + + final layout = layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ); + + expect(layout.nodeFor('ghost'), isNull); + expect(layout.nodes.length, nodes.length); + }); + + test('duplicate or empty node keys are rejected', () { + const stageNode = GraphNode(key: 'a', terminal: false, stageIndex: 0); + expect( + () => layoutGraphNodes( + nodes: const [stageNode, stageNode], + edges: const [], + extents: {'a': NodeExtent(width: 10, height: 10)}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + expect( + () => layoutGraphNodes( + nodes: const [ + GraphNode(key: '', terminal: false, stageIndex: 0), + ], + edges: const [], + extents: const {}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid gaps and extents are rejected', () { + expect( + () => GraphLayoutConfig(columnGap: -1, rowGap: 8), + throwsArgumentError, + ); + expect( + () => GraphLayoutConfig(columnGap: 8, rowGap: double.nan), + throwsArgumentError, + ); + expect( + () => NodeExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + }); +} diff --git a/app/test/features/graph/layout/graph_node_layout_test.dart b/app/test/features/graph/layout/graph_node_layout_test.dart new file mode 100644 index 00000000..bbaf2408 --- /dev/null +++ b/app/test/features/graph/layout/graph_node_layout_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +GraphLayout _layout( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? uniformExtents(nodes), + config: config ?? layoutConfig(), + ); +} + +void _expectWithinBounds(GraphLayout layout) { + for (final box in layout.nodes) { + expect(box.x, greaterThanOrEqualTo(0), reason: '${box.key} left'); + expect(box.y, greaterThanOrEqualTo(0), reason: '${box.key} top'); + expect( + box.right, + lessThanOrEqualTo(layout.width), + reason: '${box.key} right inside width', + ); + expect( + box.bottom, + lessThanOrEqualTo(layout.height), + reason: '${box.key} bottom inside height', + ); + } +} + +void _expectSeparated(GraphLayout layout) { + for (var first = 0; first < layout.nodes.length; first += 1) { + for (var second = first + 1; second < layout.nodes.length; second += 1) { + final a = layout.nodes[first]; + final b = layout.nodes[second]; + final separated = + a.right <= b.x || + b.right <= a.x || + a.bottom <= b.y || + b.bottom <= a.y; + expect(separated, isTrue, reason: '${a.key} overlaps ${b.key}'); + } + } +} + +void main() { + test('linear nodes keep declaration order and terminal identity', () { + final layout = _layout(linearGraphFixture()); + + expect(layout.rankCount, 4); + expect(layout.nodes.map((box) => box.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(layout.ranks, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(layout.nodeFor('plan')!.stageIndex, 0); + expect(layout.nodeFor('build')!.stageIndex, 1); + expect(layout.nodeFor('ship')!.stageIndex, 2); + expect(layout.nodeFor(failureEnd)!.terminal, isTrue); + expect(layout.nodeFor(failureEnd)!.stageIndex, isNull); + expect(layout.nodeFor(successEnd)!.terminal, isTrue); + expect( + layout.nodeFor(successEnd)!.y - layout.nodeFor(failureEnd)!.bottom, + layoutConfig().rowGap, + ); + expect(layout.nodeFor(failureEnd)!.x, layout.nodeFor(successEnd)!.x); + expect(layout.nodeFor('plan')!.x, layoutConfig().padding); + expect(layout.nodeFor('plan')!.y, layoutConfig().padding); + expect( + layout.nodeFor('build')!.x - layout.nodeFor('plan')!.right, + layoutConfig().columnGap, + ); + expect(layout.width, 560); + expect(layout.height, 140); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('diamond ranks place siblings in one column', () { + final layout = _layout(diamondGraphFixture()); + + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, 1); + expect(c.rank, 1); + expect(b.x, c.x); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.nodeFor('d')!.rank, 2); + expect(layout.nodeFor('d')!.x, greaterThan(b.right)); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('cycles share a column and terminals still follow them', () { + final layout = _layout(cycleGraph()); + + final a = layout.nodeFor('a')!; + final b = layout.nodeFor('b')!; + expect(a.rank, 0); + expect(b.rank, 0); + expect(b.y - a.bottom, layoutConfig().rowGap); + expect(layout.nodeFor(failureEnd)!.rank, 1); + expect(layout.nodeFor(successEnd)!.rank, 1); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('self loops and disconnected stages stay finite and separate', () { + final selfLoop = _layout(selfLoopGraphFixture()); + expect(selfLoop.nodeFor('a')!.rank, 0); + expect(selfLoop.nodeFor('b')!.rank, 1); + + final disconnected = _layout(disconnectedGraph()); + expect(disconnected.nodeFor('a')!.rank, 0); + expect(disconnected.nodeFor('b')!.rank, 0); + expect(disconnected.nodeFor('c')!.rank, 0); + expect( + disconnected.nodeFor('b')!.y, + greaterThan(disconnected.nodeFor('a')!.bottom), + ); + _expectWithinBounds(selfLoop); + _expectSeparated(selfLoop); + _expectWithinBounds(disconnected); + _expectSeparated(disconnected); + }); + + test('unknown edge targets add no node and no column', () { + final graph = incompleteGraphFixture(); + final layout = _layout(graph); + + expect( + layout.nodes.map((box) => box.key), + graphNodes(graph).map((node) => node.key), + ); + expect(layout.nodeFor('ghost'), isNull); + expect(layout.ranks.containsKey('ghost'), isFalse); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('heterogeneous measured widths stay inside their columns', () { + final layout = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + + for (final entry in heterogeneousExtents().entries) { + final box = layout.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, c.rank); + expect(b.x + b.width / 2, c.x + c.width / 2); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.width, greaterThan(0)); + expect(layout.width, 770); + expect(layout.height, 236); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('expanded text extents grow the canvas without overlap or clipping', () { + final base = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + final expandedExtents = scaledExtents(heterogeneousExtents(), 2.6); + final expanded = _layout(diamondGraphFixture(), extents: expandedExtents); + + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + for (final entry in expandedExtents.entries) { + final box = expanded.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + _expectWithinBounds(expanded); + _expectSeparated(expanded); + }); + + test('the same input produces the same immutable layout', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + final extents = uniformExtents(nodes, width: 133, height: 77); + + final first = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + final second = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + + expect(second.nodes, first.nodes); + expect(second.ranks, first.ranks); + expect(second.width, first.width); + expect(second.height, first.height); + expect(second.rankCount, first.rankCount); + expect(() => second.nodes.add(first.nodes.first), throwsUnsupportedError); + expect(() => second.ranks['a'] = 99, throwsUnsupportedError); + }); +} diff --git a/app/test/features/graph/layout/graph_ranks_test.dart b/app/test/features/graph/layout/graph_ranks_test.dart new file mode 100644 index 00000000..320ba287 --- /dev/null +++ b/app/test/features/graph/layout/graph_ranks_test.dart @@ -0,0 +1,116 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_ranks.dart'; + +import 'layout_fixtures.dart'; + +GraphRanks _ranksFor(Map graph) { + return assignGraphRanks(graphNodes(graph), graphEdges(graph)); +} + +void main() { + test('linear definitions rank one stage per column', () { + final ranks = _ranksFor(linearGraphFixture()); + + expect(ranks.rankOf, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(ranks.rankCount, 4); + expect(ranks.components, >[ + ['plan'], + ['build'], + ['ship'], + [failureEnd], + [successEnd], + ]); + }); + + test('diamond fan-out shares a rank and converges after it', () { + final ranks = _ranksFor(diamondGraphFixture()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], ranks.rankOf['c']); + expect(ranks.rankOf['b'], 1); + expect(ranks.rankOf['d'], 2); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 3); + expect(ranks.rankCount, 4); + }); + + test('a cycle collapses to one shared rank instead of recursing', () { + final ranks = _ranksFor(cycleGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + expect(ranks.components, contains(equals(['a', 'b']))); + }); + + test('a self edge stays inside its own component and adds no rank', () { + final ranks = _ranksFor(selfLoopGraphFixture()); + + expect(ranks.rankOf, { + 'a': 0, + 'b': 1, + failureEnd: 2, + successEnd: 2, + }); + expect(ranks.components, contains(equals(['a']))); + expect(ranks.components, contains(equals(['b']))); + }); + + test('disconnected stages stay at rank zero', () { + final ranks = _ranksFor(disconnectedGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf['c'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + }); + + test('unknown and empty edge targets never become ranks or nodes', () { + final graph = incompleteGraphFixture(); + final nodes = graphNodes(graph); + final ranks = assignGraphRanks(nodes, graphEdges(graph)); + + expect(nodes.map((node) => node.key), isNot(contains('ghost'))); + expect(ranks.rankOf.containsKey('ghost'), isFalse); + expect(ranks.rankOf.containsKey(''), isFalse); + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + }); + + test('ranks are stable across repeated assignments', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + + final first = assignGraphRanks(nodes, edges); + final second = assignGraphRanks(nodes, edges); + + expect(second.rankOf, first.rankOf); + expect(second.rankCount, first.rankCount); + expect(second.components, first.components); + }); + + test('a long chain is walked iteratively without overflow', () { + const length = 2000; + final ranks = _ranksFor(chainGraph(length)); + + expect(ranks.rankCount, length + 1); + expect(ranks.rankOf['s0'], 0); + expect(ranks.rankOf['s${length - 1}'], length - 1); + expect(ranks.rankOf[successEnd], length); + }); +} diff --git a/app/test/features/graph/layout/layout_fixtures.dart b/app/test/features/graph/layout/layout_fixtures.dart new file mode 100644 index 00000000..e67a6051 --- /dev/null +++ b/app/test/features/graph/layout/layout_fixtures.dart @@ -0,0 +1,102 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import '../domain/graph_fixtures.dart' as domain; + +/// Small definitions and measured extents shared by the layout tests. + +GraphLayoutConfig layoutConfig({ + double columnGap = 24, + double rowGap = 12, + double padding = 4, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +/// One measured size for every node, optionally scaled to simulate text growth. +Map uniformExtents( + Iterable nodes, { + double width = 120, + double height = 60, + double scale = 1, +}) { + return { + for (final node in nodes) + node.key: NodeExtent(width: width * scale, height: height * scale), + }; +} + +Map scaledExtents( + Map base, + double scale, +) { + return { + for (final entry in base.entries) + entry.key: NodeExtent( + width: entry.value.width * scale, + height: entry.value.height * scale, + ), + }; +} + +/// Deliberately uneven measured boxes for the diamond definition. +Map heterogeneousExtents() { + return { + 'a': NodeExtent(width: 210, height: 84), + 'b': NodeExtent(width: 92, height: 44), + 'c': NodeExtent(width: 148, height: 126), + 'd': NodeExtent(width: 104, height: 58), + failureEnd: NodeExtent(width: 72, height: 34), + successEnd: NodeExtent(width: 228, height: 96), + }; +} + +/// Two stages in a cycle; both terminals are reached from inside the cycle. +Map cycleGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: {'success': 'b', 'error': '#'}, + fallbackError: true, + ), + domain.stage( + 'b', + edges: {'success': 'a', 'error': '#success'}, + ), + ], +}; + +/// Two independent routes and a stage with no edges at all. +Map disconnectedGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': '#success'}), + domain.stage('b', edges: {'success': '#failure'}), + domain.stage('c'), + ], +}; + +Map linearGraphFixture() => domain.linearGraph(); + +Map diamondGraphFixture() => domain.diamondGraph(); + +Map selfLoopGraphFixture() => domain.selfLoopGraph(); + +Map incompleteGraphFixture() => domain.incompleteGraph(); + +/// A long chain, used to prove the iterative rank walk cannot overflow. +Map chainGraph(int length) => { + 'stages': [ + for (var index = 0; index < length; index += 1) + domain.stage( + 's$index', + edges: { + 'success': index + 1 < length ? 's${index + 1}' : '#success', + }, + ), + ], +}; diff --git a/app/test/features/runs/actions/cancel_action_test.dart b/app/test/features/runs/actions/cancel_action_test.dart new file mode 100644 index 00000000..e50a6eea --- /dev/null +++ b/app/test/features/runs/actions/cancel_action_test.dart @@ -0,0 +1,192 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; + +import 'cancel_test_support.dart'; + +void main() { + test('cancel eligibility matches the web canCancel exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('executing run', executingRun(), true), + ( + 'waiting while a session export is pending', + executingRun(executing: false, status: 'waiting', exportPending: 2), + true, + ), + ( + 'waiting with no pending export', + executingRun(executing: false, status: 'waiting'), + false, + ), + ( + 'status says running but the run is not executing', + executingRun(executing: false), + false, + ), + ( + 'cancellation already requested', + executingRun(cancelRequested: true), + false, + ), + ('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false), + ( + 'completed run', + executingRun(executing: false, status: 'succeeded'), + false, + ), + ('failed run', executingRun(executing: false, status: 'failed'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canCancelRun(run), expected, reason: label); + } + expect(canCancelRun(null), isFalse); + }); + + testWidgets( + 'material cancel asks first, Keep sends nothing, then sends the envelope', + (tester) async { + final accepted = acceptedCancelRun(); + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: executingRun(), + changed: changed, + ), + cupertino: false, + ), + ); + + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect(find.text(cancelKeepLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run']); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino cancel uses a native prompt and sends only on confirm', + (tester) async { + final accepted = acceptedCancelRun(); + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: executingRun(), + changed: changed, + ), + cupertino: true, + ), + ); + + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run']); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + }, + ); + + testWidgets('the action is absent for runs the web does not cancel', ( + tester, + ) async { + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': executingRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('executing', executingRun(), true), + ( + 'export wait', + executingRun(executing: false, status: 'waiting', exportPending: 1), + true, + ), + ( + 'no export wait', + executingRun(executing: false, status: 'waiting'), + false, + ), + ('stale running status', executingRun(executing: false), false), + ('already stopping', executingRun(cancelRequested: true), false), + ('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false), + ('finished', executingRun(executing: false, status: 'succeeded'), false), + ]; + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + cancelApp( + CancelHost( + key: ValueKey(label), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: false, + ), + ); + expect( + find.byKey(cancelActionKey), + visible ? findsOneWidget : findsNothing, + reason: label, + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/cancel_resilience_test.dart b/app/test/features/runs/actions/cancel_resilience_test.dart new file mode 100644 index 00000000..675c58b2 --- /dev/null +++ b/app/test/features/runs/actions/cancel_resilience_test.dart @@ -0,0 +1,271 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; + +import 'cancel_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeCancelGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: run ?? executingRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); +} + +void main() { + testWidgets('a refusal stays visible and delivers the resynced run', ( + tester, + ) async { + const refusal = 'run 7 already completed; nothing to cancel'; + final refreshed = executingRun(executing: false, status: 'succeeded'); + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return {'run_detail': refreshed}; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(gateway.calls.first.fields, {'run_id': 7}); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(cancelErrorKey), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed.single, equals(refreshed)); + expect(find.byKey(cancelActionKey), findsNothing); + }); + + testWidgets('a failed resync never hides the refusal or invents a run', ( + tester, + ) async { + const refusal = 'server refused to stop the run'; + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + throw const NotConnectedError(); + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect(find.byKey(cancelActionKey), findsOneWidget); + }); + + testWidgets('a refusal and Keep do not wait for the resync', (tester) async { + const refusal = 'run 7 is already stopping'; + final resync = Completer(); + final gateway = FakeCancelGateway((type, fields) { + if (type == 'cancel_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({ + 'run_detail': executingRun(executing: false, status: 'succeeded'), + }); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeCancelGateway((type, fields) { + if (type == 'cancel_run') throw const ProtocolError('already stopped'); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': acceptedCancelRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('an ineligible resync disables confirm but keeps the refusal', ( + tester, + ) async { + const refusal = 'run 7 already completed; nothing to cancel'; + final finished = executingRun(executing: false, status: 'succeeded'); + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + expect(changed.single, equals(finished)); + }); + + testWidgets( + 'confirm cannot submit twice while the cancellation is in flight', + (tester) async { + final reply = Completer(); + final gateway = FakeCancelGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(cancelConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'cancel_run'), + hasLength(1), + ); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': acceptedCancelRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }, + ); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeCancelGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': acceptedCancelRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': acceptedCancelRun()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + } + }); +} diff --git a/app/test/features/runs/actions/cancel_test_support.dart b/app/test/features/runs/actions/cancel_test_support.dart new file mode 100644 index 00000000..7acee8d9 --- /dev/null +++ b/app/test/features/runs/actions/cancel_test_support.dart @@ -0,0 +1,101 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_run_action.dart'; + +typedef CancelHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeCancelGateway implements ApiGateway { + FakeCancelGateway(this.handler); + + final CancelHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap executingRun({ + num id = 7, + bool executing = true, + String status = 'running', + int exportPending = 0, + bool cancelRequested = false, + bool cleanupUnconfirmed = false, +}) => { + 'id': id, + 'title': 'Nightly build', + 'status': status, + 'executing': executing, + 'export_pending_sequence': exportPending, + 'cancel_requested': cancelRequested, + 'cleanup_unconfirmed': cleanupUnconfirmed, +}; + +JsonMap acceptedCancelRun() => + executingRun(executing: false, status: 'canceled', cancelRequested: true); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class CancelHost extends StatefulWidget { + const CancelHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeCancelGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _CancelHostState(); +} + +class _CancelHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return CancelRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget cancelApp( + Widget child, { + required bool cupertino, + double textScale = 1, +}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} diff --git a/app/test/features/runs/actions/decision_action_test.dart b/app/test/features/runs/actions/decision_action_test.dart new file mode 100644 index 00000000..b756db79 --- /dev/null +++ b/app/test/features/runs/actions/decision_action_test.dart @@ -0,0 +1,265 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun({ + String status = 'waiting', + int exportPending = 0, + String type = 'human', + List options = const ['go', 'skip'], +}) => { + 'id': 7, + 'title': 'Report', + 'name': 'Build', + 'status': status, + 'current_stage': 'human', + 'export_pending_sequence': exportPending, + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': type, + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': {'prompt': 'Ship it?', 'options': options}, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + if (cupertino) { + return CupertinoApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + JsonMap run, { + required bool cupertino, + required List changed, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: run, + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'material decision waits for option and confirm, then sends exact fields', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await _open(tester); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect(find.text('→ SUCCESS'), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText(FilledButton, decisionConfirmLabel); + expect(tester.widget(confirm).onPressed, isNull); + + await tester.tap(find.text('go')); + await tester.pump(); + expect(gateway.calls, isEmpty); + expect(tester.widget(confirm).onPressed, isNotNull); + + await tester.enterText(find.byKey(decisionFeedbackKey), ' looks good '); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'go', + 'feedback': 'looks good', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(decisionActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino decision uses a native dialog and omits empty feedback', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: true, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + await _open(tester); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText( + CupertinoDialogAction, + decisionConfirmLabel, + ); + expect(tester.widget(confirm).onPressed, isNull); + await tester.tap(find.text('skip')); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'skip', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('Cancel dismisses the draft without sending anything', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + await _open(tester); + await tester.tap(find.text('go')); + await tester.pump(); + await tester.enterText(find.byKey(decisionFeedbackKey), 'not sent'); + await tester.tap(find.widgetWithText(TextButton, decisionCancelLabel)); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect(find.byKey(decisionActionKey), findsOneWidget); + }); + + testWidgets('the action is absent unless a run is genuinely waiting', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _waitingRun()}, + ); + final changed = []; + for (final (label, run) in [ + ('not waiting', _waitingRun(status: 'running')), + ('export pending', _waitingRun(exportPending: 2)), + ('model stage', _waitingRun(type: 'model')), + ]) { + await _pump(tester, gateway, run, cupertino: false, changed: changed); + expect( + find.byKey(decisionActionKey), + findsNothing, + reason: '$label must not offer a decision', + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/decision_resilience_test.dart b/app/test/features/runs/actions/decision_resilience_test.dart new file mode 100644 index 00000000..e755ddc5 --- /dev/null +++ b/app/test/features/runs/actions/decision_resilience_test.dart @@ -0,0 +1,351 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun() => { + 'id': 7, + 'title': 'Report', + 'status': 'waiting', + 'current_stage': 'human', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Ship it?', + 'options': ['go', 'skip'], + }, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: _waitingRun(), + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _chooseGo(WidgetTester tester, {String feedback = ''}) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('go')); + await tester.pump(); + if (feedback.isNotEmpty) { + await tester.enterText(find.byKey(decisionFeedbackKey), feedback); + } +} + +void main() { + testWidgets('a refusal stays visible and keeps the selected draft', ( + tester, + ) async { + const refusal = 'option "go" is not a valid outcome; choose one of: skip'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return { + 'run_detail': { + ..._waitingRun(), + 'status': 'failed', + 'steps': const [], + }, + }; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect(changed.single['status'], 'failed'); + expect(find.byKey(decisionActionKey), findsNothing); + }); + + testWidgets('a refusal is shown before the resync keeps the draft', ( + tester, + ) async { + const refusal = 'option "go" is no longer valid'; + final resync = Completer(); + final gateway = _FakeGateway((type, fields) { + if (type == 'decide_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNotNull, + ); + expect(changed, isEmpty); + + resync.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(FilledButton, decisionConfirmLabel), + ) + .onPressed, + isNull, + ); + expect(changed.single['status'], 'succeeded'); + }); + + testWidgets('a failed resync keeps the draft and allows a retry', ( + tester, + ) async { + const refusal = 'server refused the decision'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + throw const NotConnectedError(); + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget( + find.widgetWithText(FilledButton, decisionConfirmLabel), + ) + .onPressed, + isNotNull, + ); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = _FakeGateway((type, fields) { + if (type == 'decide_run') throw const ProtocolError('no longer waiting'); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('confirm cannot submit twice while the decision is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + + final confirm = find.text(decisionConfirmLabel); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'decide_run'), + hasLength(1), + ); + expect(find.text(decisionSendingLabel), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNull, + ); + + reply.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + } + }); +} diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart new file mode 100644 index 00000000..ca11fa8b --- /dev/null +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -0,0 +1,245 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + test('retry eligibility matches the web canRetry exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('failed and stopped', failedRun(), true), + ('failed but still executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canRetryRun(run), expected, reason: label); + } + expect(canRetryRun(null), isFalse); + expect(retryRunId(failedRun()), 7); + expect(retryRunId({'id': '7'}), isNull); + }); + + test('a generated retry key is bounded, run-scoped and fresh', () { + final first = newRetryRequestKey(7); + final second = newRetryRequestKey(7); + + expect(first, startsWith('app-retry-7-')); + expect(first.length, lessThanOrEqualTo(128)); + expect(second.length, lessThanOrEqualTo(128)); + expect(first, isNot(second)); + expect( + newRetryRequestKey(7, now: DateTime.utc(2026, 1, 1), random: 36), + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-10', + ); + }); + + testWidgets( + 'material retry asks first, Keep sends nothing, then omits retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text(retryConfirmLabel), + ), + findsOneWidget, + ); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields.keys, containsAll(['run_id', 'request_key'])); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(fields['request_key'].length, lessThanOrEqualTo(128)); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + }, + ); + + testWidgets( + 'material restart has its own confirmation and sends retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsNothing); + expect(find.text(retryDialogMessage), findsNothing); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(find.byKey(retryRestartKey), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + }, + ); + + testWidgets( + 'cupertino retry uses a native prompt and sends only on confirm', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry( + tester, + gateway: gateway, + changed: changed, + cupertino: true, + ); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('cupertino restart switches to the restart confirmation', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: true, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.retries.single.fields['retry_mode'], 'restart'); + }); + + testWidgets('the action is absent for runs the web does not retry', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('failed', failedRun(), true), + ('executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final cupertino in [false, true]) { + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + retryApp( + RetryHost( + key: ValueKey('$label-$cupertino'), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: cupertino, + ), + ); + expect( + find.byKey(retryActionKey), + visible ? findsOneWidget : findsNothing, + reason: '$label cupertino=$cupertino', + ); + } + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_resilience_test.dart b/app/test/features/runs/actions/retry_resilience_test.dart new file mode 100644 index 00000000..26053426 --- /dev/null +++ b/app/test/features/runs/actions/retry_resilience_test.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); +} + +void main() { + testWidgets('a refusal is shown at once and Keep does not wait for resync', ( + tester, + ) async { + const refusal = 'run 7 is still executing; wait for it to stop completely'; + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(retryErrorKey), findsOneWidget); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({'run_detail': failedRun(status: 'succeeded')}); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + expect(find.byKey(retryActionKey), findsNothing); + }); + + testWidgets('server truth that is ineligible blocks a repeat action', ( + tester, + ) async { + const refusal = 'only failed runs can be retried'; + final finished = failedRun(status: 'succeeded'); + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'retry_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect(changed.single, equals(finished)); + expect(canRetryRun(changed.single), isFalse); + }); + + testWidgets('a failed recheck keeps the same key for the uncertain request', ( + tester, + ) async { + const refusal = 'connection dropped while retrying'; + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError(refusal); + return {'run_detail': retriedRun()}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNotNull, + ); + expect(gateway.retries, hasLength(1)); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + expect( + gateway.retries.every((call) => !call.fields.containsKey('retry_mode')), + isTrue, + ); + expect(changed.single, equals(retriedRun())); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('a restart retry keeps the mode and key across uncertainty', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('network lost'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields['retry_mode'], 'restart'); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + }); + + testWidgets('a deliberate reopen sends a fresh request key', (tester) async { + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + throw const ProtocolError('server did not answer'); + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); + + testWidgets('a restart after a dismissed resume uses a fresh key', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('resume refused'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + // A refusal leaves the prompt open; keep the mode frozen and dismiss. + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields.containsKey('retry_mode'), isFalse); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); +} diff --git a/app/test/features/runs/actions/retry_safety_test.dart b/app/test/features/runs/actions/retry_safety_test.dart new file mode 100644 index 00000000..df9e7e88 --- /dev/null +++ b/app/test/features/runs/actions/retry_safety_test.dart @@ -0,0 +1,133 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + testWidgets('confirm cannot submit twice while the retry is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(retryConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect(gateway.retries, hasLength(1)); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': retriedRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late retry reply after disposal is ignored safely', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.retries, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError('refused'); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both confirmations fit 2x text at a narrow width', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: cupertino, + textScale: 2, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'restart=$cupertino'); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + } + }); +} diff --git a/app/test/features/runs/actions/retry_test_support.dart b/app/test/features/runs/actions/retry_test_support.dart new file mode 100644 index 00000000..67556d05 --- /dev/null +++ b/app/test/features/runs/actions/retry_test_support.dart @@ -0,0 +1,112 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_action.dart'; + +typedef RetryHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeRetryGateway implements ApiGateway { + FakeRetryGateway(this.handler); + + final RetryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + Iterable<({String type, JsonMap fields})> get retries => + calls.where((call) => call.type == 'retry_run'); +} + +JsonMap failedRun({ + num id = 7, + bool executing = false, + String status = 'failed', + String title = 'Nightly build', +}) => {'id': id, 'title': title, 'status': status, 'executing': executing}; + +JsonMap retriedRun({num id = 8}) => + failedRun(id: id, status: 'running', executing: true, title: 'Retry of 7'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class RetryHost extends StatefulWidget { + const RetryHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeRetryGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _RetryHostState(); +} + +class _RetryHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return RetryRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget retryApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future pumpRetry( + WidgetTester tester, { + required FakeRetryGateway gateway, + required List changed, + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + retryApp( + RetryHost( + gateway: gateway, + initial: run ?? failedRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} diff --git a/app/test/features/runs/actions/title_action_test.dart b/app/test/features/runs/actions/title_action_test.dart new file mode 100644 index 00000000..110fda20 --- /dev/null +++ b/app/test/features/runs/actions/title_action_test.dart @@ -0,0 +1,244 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +String _materialFieldText(WidgetTester tester) => + tester.widget(find.byKey(runTitleFieldKey)).controller!.text; + +String _cupertinoFieldText(WidgetTester tester) => tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + +void main() { + testWidgets( + 'material rename starts from the stored title, typing sends nothing, ' + 'Cancel sends nothing and Save sends the exact text', + (tester) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(OutlinedButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(runTitleDialogTitle), findsWidgets); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(_materialFieldText(tester), 'Nightly build'); + + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Nightly build'); + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' 发布 🚀 — nightly ', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Release build', + ); + }, + ); + + testWidgets('cupertino rename is native and sends only on Save', ( + tester, + ) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: true, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(OutlinedButton), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(_cupertinoFieldText(tester), 'Nightly build'); + + await tester.enterText(find.byKey(runTitleFieldKey), 'Typed only'); + await tester.pump(); + expect(gateway.calls, isEmpty); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), 'Release build'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Release build', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }); + + testWidgets('a blank title is sent exactly and the server refusal is shown', ( + tester, + ) async { + const refusal = 'title must not be blank'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), ''); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.single.fields, {'run_id': 7, 'title': ''}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_materialFieldText(tester), ''); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + expect( + tester.widget(find.byKey(runTitleSaveKey)).onPressed, + isNotNull, + ); + }); + + testWidgets('the prompt is seeded from the stored title, never the prompt', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + final changed = []; + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun( + title: 'Stored title', + prompt: 'prompt fallback must not appear', + ), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Stored title'); + expect(find.text('prompt fallback must not appear'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(title: null, prompt: 'prompt is not a title'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), ''); + expect(find.text('prompt is not a title'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); + + testWidgets('a malformed run has no rename entry point', (tester) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: {'title': 'No id'}, + changed: [], + ), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsNothing); + expect(gateway.calls, isEmpty); + expect(runTitleId({'title': 'No id'}), isNull); + expect(storedRunTitle({'title': 'Kept'}), 'Kept'); + expect(storedRunTitle({}), ''); + }); +} diff --git a/app/test/features/runs/actions/title_resilience_test.dart b/app/test/features/runs/actions/title_resilience_test.dart new file mode 100644 index 00000000..32a566c3 --- /dev/null +++ b/app/test/features/runs/actions/title_resilience_test.dart @@ -0,0 +1,243 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeTitleGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: run ?? titledRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); +} + +String _fieldText(WidgetTester tester, {required bool cupertino}) { + if (cupertino) { + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + } + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; +} + +void main() { + testWidgets('a failed save keeps the prompt open with the draft intact', ( + tester, + ) async { + const refusal = 'rename refused: the run is locked'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), ' Renamed draft '); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' Renamed draft ', + }); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: false), ' Renamed draft '); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + }); + + testWidgets('a transport failure keeps the server words and the draft', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => throw const NotConnectedError(), + ); + final changed = []; + await _pump(tester, gateway, changed, cupertino: true); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Unsent title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: true), 'Unsent title'); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(changed, isEmpty); + }); + + testWidgets('Save cannot send twice while the rename is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'One title'); + final save = find.byKey(runTitleSaveKey); + await tester.tap(save); + await tester.tap(save); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'set_run_title'), + hasLength(1), + ); + expect(tester.widget(save).onPressed, isNull); + expect( + tester.widget(find.byKey(runTitleCancelKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': renamedRun(title: 'One title')}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + expect(changed.single['title'], 'One title'); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': renamedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a reply for a run the widget no longer owns is not delivered', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Run seven title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(id: 8, title: 'Another run'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.pump(); + reply.complete({'run_detail': renamedRun(title: 'Run seven title')}); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Run seven title', + }); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Another run', + ); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + const refusal = 'the title is too long for this run; shorten it'; + for (final cupertino in [false, true]) { + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await _open(tester); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.enterText( + find.byKey(runTitleFieldKey), + 'A deliberately long title that must scroll rather than overflow', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(refusal), findsOneWidget); + expect( + _fieldText(tester, cupertino: cupertino), + 'A deliberately long title that must scroll rather than overflow', + ); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoAlertDialog), findsNothing); + } + }); +} diff --git a/app/test/features/runs/actions/title_test_support.dart b/app/test/features/runs/actions/title_test_support.dart new file mode 100644 index 00000000..b566a2d8 --- /dev/null +++ b/app/test/features/runs/actions/title_test_support.dart @@ -0,0 +1,110 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; + +typedef TitleHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeTitleGateway implements ApiGateway { + FakeTitleGateway(this.handler); + + final TitleHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap titledRun({ + num id = 7, + String? title = 'Nightly build', + String status = 'succeeded', + String prompt = 'the submitted prompt', +}) => { + 'id': id, + 'title': title, + 'status': status, + 'input': {'prompt': prompt}, +}; + +JsonMap renamedRun({num id = 7, String title = 'Release build'}) => + titledRun(id: id, title: title, status: 'succeeded'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. Re-pumping with a different +/// initial run updates the action in place, as a refreshed detail does. +class TitleHost extends StatefulWidget { + const TitleHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeTitleGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _TitleHostState(); +} + +class _TitleHostState extends State { + late JsonMap _run = widget.initial; + + @override + void didUpdateWidget(covariant TitleHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.initial, widget.initial)) { + _run = widget.initial; + } + } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${_run['title'] ?? ''}', key: titleHostTitleKey), + RunTitleAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ), + ], + ); + } +} + +const titleHostTitleKey = ValueKey('rename-host-title'); + +Widget titleApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final body = Center(child: child); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: body), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: body), + ); +} diff --git a/app/test/features/schedules/data/saved_schedule_record_test.dart b/app/test/features/schedules/data/saved_schedule_record_test.dart new file mode 100644 index 00000000..aef17fe6 --- /dev/null +++ b/app/test/features/schedules/data/saved_schedule_record_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('saved schedule exposes run-configuration provenance', () { + final schedule = SavedSchedule(savedRecord()); + + expect(schedule.id, 8); + expect(schedule.revision, 3); + expect(schedule.pipelineId, 4); + expect(schedule.version, 2); + expect(schedule.name, 'Research batteries'); + expect(schedule.enabled, isTrue); + expect(schedule.prompt, 'Research batteries'); + expect(schedule.input['custom'], {'nested': 'kept'}); + expect(schedule.workspace, '/srv/research'); + expect(schedule.writePaths, ['reports/research.md']); + expect(schedule.allowTools, isTrue); + expect(schedule.model, 'openai/gpt-5'); + expect(schedule.stageModels, {'one': 'openai/gpt-5'}); + expect(schedule.notifyMode, 'off'); + expect(schedule.title, 'Battery research'); + expect(schedule.outputFormat, 'markdown'); + expect(schedule.rule.every, '24h'); + expect(schedule.rule.days, ['mon', 'wed']); + expect(schedule.rule.timezone, 'Europe/London'); + expect(schedule.rule.isClock, isFalse); + expect(schedule.nextDue, '2026-10-22T09:00:00Z'); + expect(schedule.createdAt, '2026-10-20T09:00:00Z'); + expect(schedule.updatedAt, '2026-10-21T09:00:00Z'); + }); + + test('unknown fields survive the typed view and pause copy', () { + final schedule = SavedSchedule(savedRecord()); + final paused = schedule.withEnabled(false); + + expect(paused.enabled, isFalse); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + expect(paused.toJson()['input'], { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }); + expect(paused.toJson()['rule'], savedRecord()['rule']); + + // The original snapshot is untouched and still enabled. + expect(schedule.enabled, isTrue); + expect(schedule.revision, 3); + }); + + test('toJson is a deep copy, not an alias of the server reply', () { + final source = savedRecord(); + final schedule = SavedSchedule(source); + + final first = schedule.toJson(); + ((first['future_server_field'] as Map)['nested'] as List).add('changed'); + final second = schedule.toJson(); + expect((second['future_server_field'] as Map)['nested'], [ + 1, + 2, + {'deep': true}, + ]); + + final promptInput = schedule.input; + promptInput['custom'] = 'changed'; + expect(schedule.input['custom'], {'nested': 'kept'}); + }); + + test('missing fields stay absent instead of being fabricated', () { + final schedule = SavedSchedule(const {}); + + expect(schedule.id, isNull); + expect(schedule.revision, isNull); + expect(schedule.pipelineId, isNull); + expect(schedule.version, isNull); + expect(schedule.enabled, isFalse); + expect(schedule.prompt, ''); + expect(schedule.workspace, ''); + expect(schedule.rule.every, ''); + expect(schedule.rule.times, isEmpty); + expect(schedule.writePaths, isEmpty); + expect(schedule.stageModels, isEmpty); + expect(schedule.toJson(), isEmpty); + }); + + test('a fractional revision is not truncated into a false token', () { + final schedule = SavedSchedule(const {'id': 8, 'revision': 3.5}); + + expect(schedule.id, 8); + expect(schedule.revision, isNull); + }); +} diff --git a/app/test/features/schedules/data/schedule_test_support.dart b/app/test/features/schedules/data/schedule_test_support.dart new file mode 100644 index 00000000..f80b852f --- /dev/null +++ b/app/test/features/schedules/data/schedule_test_support.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +class RecordedCall { + const RecordedCall(this.type, this.fields); + final String type; + final JsonMap fields; +} + +/// Records the exact request built by the repository and replays queued +/// replies. Both are deep-copied, so a test can prove the repository neither +/// mutated its input nor depended on alias mutation of a reply. +class RecordingGateway implements ApiGateway { + final calls = []; + final replies = []; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(RecordedCall(type, deepCopy(fields))); + if (failure case final error?) throw error; + if (replies.isEmpty) throw StateError('No recorded reply for $type'); + return deepCopy(replies.removeAt(0)); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap; + +/// A complete server record including fields this client does not interpret +/// yet, an unknown nested rule field and unknown input. +JsonMap savedRecord() => { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }, + 'workspace': '/srv/research', + 'write_paths': ['reports/research.md'], + 'allow_tools': true, + 'model': 'openai/gpt-5', + 'stage_models': {'one': 'openai/gpt-5'}, + 'notify_mode': 'off', + 'title': 'Battery research', + 'output_format': 'markdown', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + 'future_rule_field': 'kept', + }, + 'next_due': '2026-10-22T09:00:00Z', + 'created_at': '2026-10-20T09:00:00Z', + 'updated_at': '2026-10-21T09:00:00Z', + 'future_server_field': { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }, +}; + +/// The create form of the record: id 0 is the server's create sentinel and no +/// revision has been issued yet. +JsonMap createRecord() => { + 'id': 0, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Research batteries'}, + 'workspace': '/srv/research', + 'rule': {'every': '24h', 'timezone': 'Europe/London'}, +}; diff --git a/app/test/features/schedules/data/schedules_delete_test.dart b/app/test/features/schedules/data/schedules_delete_test.dart new file mode 100644 index 00000000..fc4f8d32 --- /dev/null +++ b/app/test/features/schedules/data/schedules_delete_test.dart @@ -0,0 +1,131 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('delete sends the exact ID and expected revision', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule_deleted', 'schedule_id': 8}); + final repository = SchedulesRepository(gateway); + + await repository.deleteSchedule(8, 3); + + expect(gateway.calls.single.type, 'delete_schedule'); + expect(gateway.calls.single.fields, { + 'schedule_id': 8, + 'expected_revision': 3, + }); + }); + + test('delete refuses a confirmation for anything else', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedule_deleted'}, + {'type': 'schedule_deleted', 'schedule_id': 9}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.deleteSchedule(8, 3), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server did not confirm deletion of this schedule.', + ), + ), + ); + } + }); + + test('server refusals and conflicts propagate verbatim', () async { + final conflict = const ProtocolError( + 'schedule revision conflict; reload before editing', + ); + final recording = RecordingGateway()..failure = conflict; + final conflicting = SchedulesRepository(recording); + await expectLater( + conflicting.saveSchedule(createRecord()), + throwsA(same(conflict)), + ); + await expectLater( + conflicting.deleteSchedule(8, 3), + throwsA(same(conflict)), + ); + + final unsupported = const ProtocolError( + 'unknown message type: list_schedules', + ); + recording.failure = unsupported; + await expectLater( + conflicting.listSchedules(pipelineId: 4), + throwsA(same(unsupported)), + ); + }); + + test('missing and empty list replies are different facts', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedules'}); + expect(await repository.listSchedules(), isEmpty); + + gateway.replies.add({'type': 'schedules', 'schedules': null}); + expect(await repository.listSchedules(), isEmpty); + + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedules', 'schedules': {}}, + { + 'type': 'schedules', + 'schedules': ['not a record'], + }, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.listSchedules(), + throwsA(isA()), + ); + } + }); + + test('save requires a saved schedule in the reply', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'schedule'}, + {'type': 'schedule', 'schedule': null}, + {'type': 'schedule', 'schedule': 'record'}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.saveSchedule(createRecord()), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no saved schedule.', + ), + ), + ); + } + }); + + test('an empty schedule object is not turned into a fake identity', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': {}}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(createRecord()); + + expect(saved.id, isNull); + expect(saved.revision, isNull); + expect(saved.toJson(), isEmpty); + }); +} diff --git a/app/test/features/schedules/data/schedules_protocol_bounds_test.dart b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart new file mode 100644 index 00000000..db39b164 --- /dev/null +++ b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart @@ -0,0 +1,81 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'list rejects non-positive and unsafe pipeline IDs before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final id in [0, -1, 9007199254740992]) { + await expectLater( + repository.listSchedules(pipelineId: id), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'A positive pipeline ID is required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'delete rejects an inexact identity or revision before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final pair in [ + (0, 1), + (-1, 1), + (8, 0), + (8, -1), + (8, 9007199254740992), + ]) { + await expectLater( + repository.deleteSchedule(pair.$1, pair.$2), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'An exact schedule ID and revision are required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'request keys are bounded at 128 characters like the web client', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + await expectLater( + repository.saveSchedule(createRecord(), requestKey: 'x' * 129), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Schedule request keys must be strings of at most 128 characters.', + ), + ), + ); + expect(gateway.calls, isEmpty); + + final key = 'x' * 128; + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(createRecord(), requestKey: key); + expect(gateway.calls.single.fields['request_key'], key); + }, + ); +} diff --git a/app/test/features/schedules/data/schedules_repository_test.dart b/app/test/features/schedules/data/schedules_repository_test.dart new file mode 100644 index 00000000..8ac1ef4c --- /dev/null +++ b/app/test/features/schedules/data/schedules_repository_test.dart @@ -0,0 +1,132 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'lists with the exact web envelope and retains every record field', + () async { + final record = savedRecord(); + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedules', + 'schedules': [record], + }); + final repository = SchedulesRepository(gateway); + + final listed = await repository.listSchedules(pipelineId: 4); + + expect(gateway.calls.single.type, 'list_schedules'); + expect(gateway.calls.single.fields, {'pipeline_id': 4}); + expect(listed.single.toJson(), record); + expect(listed.single.pipelineId, 4); + expect(listed.single.version, 2); + expect(listed.single.prompt, 'Research batteries'); + expect(listed.single.workspace, '/srv/research'); + expect(listed.single.enabled, isTrue); + expect(listed.single.rule.every, '24h'); + expect(listed.single.rule.days, ['mon', 'wed']); + expect(listed.single.rule.timezone, 'Europe/London'); + expect(listed.single.model, 'openai/gpt-5'); + expect(listed.single.notifyMode, 'off'); + expect(listed.single.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + + gateway.replies.add({'type': 'schedules'}); + await repository.listSchedules(); + expect(gateway.calls.last.type, 'list_schedules'); + expect(gateway.calls.last.fields, isEmpty); + }, + ); + + test( + 'create sends the web sentinel record without inventing a revision', + () async { + final create = createRecord(); + final original = deepCopy(create); + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': savedRecord()}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(create); + + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields, {'schedule': create}); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(create, original, reason: 'the caller record must be unchanged'); + expect(saved.id, 8); + expect(saved.revision, 3); + expect(saved.toJson(), savedRecord()); + }, + ); + + test( + 'a stable create key is forwarded exactly and blanks are omitted', + () async { + final create = createRecord(); + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule( + create, + requestKey: 'schedule:stable-editor-key', + ); + expect(gateway.calls.last.fields, { + 'schedule': create, + 'request_key': 'schedule:stable-editor-key', + }); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(create, requestKey: ''); + expect(gateway.calls.last.fields, {'schedule': create}); + }, + ); + + test('update reuses the read revision as the CAS token', () async { + final current = SavedSchedule(savedRecord()); + final paused = current.withEnabled(false); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], isNotNull); + + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedule', + 'schedule': {...savedRecord(), 'enabled': false, 'revision': 4}, + }); + final repository = SchedulesRepository(gateway); + + final updated = await repository.saveSchedule(paused.toJson()); + + final body = gateway.calls.single.fields['schedule'] as Map; + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(body['id'], 8); + expect(body['revision'], 3); + expect(body['enabled'], isFalse); + expect(body['future_server_field'], isNotNull); + expect(updated.revision, 4); + expect(updated.enabled, isFalse); + + // The stale draft keeps its token: a conflict must not be papered over by + // silently adopting the reply revision. + expect(current.revision, 3); + expect(current.enabled, isTrue); + }); +} diff --git a/app/test/features/templates/data/template_create_test.dart b/app/test/features/templates/data/template_create_test.dart new file mode 100644 index 00000000..68b82c4b --- /dev/null +++ b/app/test/features/templates/data/template_create_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'validate sends the exact source and returns the server graph', + () async { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'model'}, + ], + 'unknown_graph_field': true, + }; + final gateway = RecordingGateway([ + {'type': 'validated', 'graph': graph}, + ]); + + final result = await TemplateRepository(gateway).validate(source); + + expect(gateway.calls.single.type, 'validate'); + expect(gateway.calls.single.fields, {'source': source}); + expect(gateway.calls.single.fields['source'], source); + expect(result, graph); + }, + ); + + test( + 'validate rejects a reply without a graph instead of faking success', + () async { + for (final reply in [ + {'type': 'validated'}, + {'type': 'validated', 'graph': null}, + ]) { + final gateway = RecordingGateway([reply]); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no graph.', + ), + ), + ); + } + }, + ); + + test('validate propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('invalid stage "añadir": unknown key'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['validate']); + }); + + test('submit refuses a blank name without sending anything', () async { + for (final name in ['', ' ', '\t\n']) { + final gateway = RecordingGateway([ + { + 'detail': {'id': 1}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).submit(name, source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Enter a pipeline name.', + ), + ), + ); + expect(gateway.calls, isEmpty); + } + }); + + test( + 'submit trims the name, preserves the source and is always create-only', + () async { + final detail = { + 'id': 9, + 'name': 'Release 2', + 'version': 1, + }; + final gateway = RecordingGateway([ + {'type': 'submitted', 'detail': detail}, + ]); + + final result = await TemplateRepository( + gateway, + ).submit(' Release 2 ', source); + + expect(gateway.calls.single.type, 'submit'); + expect(gateway.calls.single.fields, { + 'name': 'Release 2', + 'source': source, + 'create_only': true, + }); + expect(gateway.calls.single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(result, detail); + }, + ); + + test( + 'submit rejects a reply without a detail instead of faking success', + () async { + final gateway = RecordingGateway([ + {'type': 'submitted'}, + ]); + + await expectLater( + TemplateRepository(gateway).submit('Release', source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no pipeline detail.', + ), + ), + ); + }, + ); + + test('submit propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('a pipeline named "Release" already exists'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).submit(' Release ', source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['submit']); + }); +} diff --git a/app/test/features/templates/data/template_list_test.dart b/app/test/features/templates/data/template_list_test.dart new file mode 100644 index 00000000..63cd2e93 --- /dev/null +++ b/app/test/features/templates/data/template_list_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'list_templates sends only the type and preserves every field', + () async { + final catalogue = [ + { + 'key': 'release', + 'name': 'Release', + 'description': 'Ship a version', + 'source': source, + 'scheduled': true, + 'future_field': { + 'nested': [1, 2, 3], + }, + }, + { + 'key': 'blank', + 'name': '', + 'description': '', + 'source': 'name: empty', + 'scheduled': false, + }, + ]; + final gateway = RecordingGateway([ + {'templates': catalogue}, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + expect(entries, hasLength(2)); + expect(entries.first.key, 'release'); + expect(entries.first.name, 'Release'); + expect(entries.first.description, 'Ship a version'); + expect(entries.first.source, source); + expect(entries.first.scheduled, isTrue); + expect(entries.first.raw['future_field'], { + 'nested': [1, 2, 3], + }); + expect(entries.last.key, 'blank'); + expect(entries.last.scheduled, isFalse); + expect(entries.last.raw, isNot(contains('missing'))); + }, + ); + + test('list_templates leaves the server reply untouched', () async { + final first = { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }; + final reply = { + 'templates': [first], + 'usage': {'templates': 1}, + }; + final gateway = RecordingGateway([reply]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(reply['templates'], hasLength(1)); + expect(first, { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }); + expect(entries.single.raw['unknown'], ['keep', 'me']); + expect( + () => entries.single.raw['name'] = 'changed', + throwsUnsupportedError, + ); + expect(first['name'], 'One'); + }); + + test('list_templates freezes nested unknown data in raw', () async { + final nested = { + 'nested': [1, 2, 3], + }; + final gateway = RecordingGateway([ + { + 'templates': [ + { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'future_field': nested, + }, + ], + }, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + final raw = entries.single.raw; + final future = raw['future_field'] as Map; + + expect(() => future['added'] = true, throwsUnsupportedError); + expect(() => (future['nested'] as List).add(4), throwsUnsupportedError); + expect(future['nested'], [1, 2, 3]); + // The unmodifiable copies do not alias the server reply either. + nested['added'] = true; + expect(raw['future_field'], isNot(contains('added'))); + }); + + test('list_templates rejects a catalogue that is not a list', () async { + final gateway = RecordingGateway([ + { + 'templates': {'key': 'not-a-list'}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no template catalogue.', + ), + ), + ); + }); + + test( + 'list_templates rejects a catalogue entry that is not an object', + () async { + final gateway = RecordingGateway([ + { + 'templates': ['not-an-entry'], + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned a template that is not an object.', + ), + ), + ); + }, + ); + + test('list_templates treats a reply with no catalogue as empty', () async { + final gateway = RecordingGateway([{}]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(entries, isEmpty); + expect(gateway.calls.single.type, 'list_templates'); + }); +} diff --git a/app/test/features/templates/data/template_test_support.dart b/app/test/features/templates/data/template_test_support.dart new file mode 100644 index 00000000..f4f36500 --- /dev/null +++ b/app/test/features/templates/data/template_test_support.dart @@ -0,0 +1,47 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A recording gateway: it captures every request and answers from [replies]. +class RecordingGateway implements ApiGateway { + RecordingGateway([List replies = const []]) + : _replies = [...replies]; + + final List _replies; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: Map.from(fields))); + return _replies.removeAt(0); + } + + @override + Stream get frames => const Stream.empty(); +} + +/// A gateway that refuses every request with the same server error object. +class RefusingGateway implements ApiGateway { + RefusingGateway(this.refusal); + + final Object refusal; + final List calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + throw refusal; + } + + @override + Stream get frames => const Stream.empty(); +} + +class ServerRefusal implements Exception { + const ServerRefusal(this.message); + final String message; + @override + String toString() => message; +} + +/// A source with Unicode, tabs, newlines and significant leading/trailing +/// whitespace: every request must carry it unchanged. +const source = ' name: "café"\n\tstages:\n - key: "añadir" 😀 \n'; diff --git a/docs/notes/session-export-handoff-gate.md b/docs/notes/session-export-handoff-gate.md index 6f09e72c..086d550a 100644 --- a/docs/notes/session-export-handoff-gate.md +++ b/docs/notes/session-export-handoff-gate.md @@ -73,7 +73,7 @@ retry and refresh of an already-open Session tab. Large (>256 KiB) API fixtures, wrong identity, partial/empty exports, restart, cancellation, workspace reservation, and exactly-once successor admission have focused regressions. A full ordinary artifact inventory no longer blocks versioned audit repair. -Repairs have a separate bounded allowance (twenty attempts, each at most 2 MiB), +Repairs have a separate bounded allowance (twenty attempts, each at most 8 MiB), so neither the ordinary inventory's file count nor its byte budget consumes the mandatory audit-recovery capacity. The ordinary scan limits remain unchanged. diff --git a/docs/notes/session-export-render-cap.md b/docs/notes/session-export-render-cap.md new file mode 100644 index 00000000..3ffd0b34 --- /dev/null +++ b/docs/notes/session-export-render-cap.md @@ -0,0 +1,44 @@ +# Session export: rendered-file cap aligned with the artifact bound + +## Problem + +Six computed Flutter runs (34, 37, 39, 42, 49, 50) reached Code visit 1 with a +successful, quiescent agent session but stopped at the export handoff gate. Each +recorded `session_export.status: partial`, `html_bytes: 2097152`, +`truncated: true`; the manual versioned repair of run 34 hit the same exact size. +The sessions had completed their computation, so a stage rerun was not the right +recovery. + +A read-only inspection of the recorded session rows showed the original native +data for those six sessions was between 1,083,391 and 2,111,470 bytes (the +complete HTTP export envelope for one of them was 2,126,449 bytes). All were +well inside the existing 8 MiB source read cap. The binding limit was the 2 MiB +rendered-file cap: html escaping and the readable projection keep native text +more than once, so an ordinary session can render larger than its source. +Re-exporting the six exact sessions read-only into scratch directories with the +new cap produced complete, untruncated files of 2,252,874 to 4,276,358 bytes. + +## Change + +`internal/stage/session_export.go` raises `SessionExportFileLimit` from 2 MiB to +8 MiB. That value is the same as the server's ordinary per-artifact file bound +(`maxArtifactFileBytes` in `internal/server/artifacts.go`), so a complete export +remains listed and served instead of being cut below the bound that the artifact +inventory already enforces. + +The source read remains capped by `SessionExportSourceLimit` (the single +`opencode.MaxSessionExport` value, 8 MiB). Normal export verification, versioned +export repair and the handoff gate all use `SessionExportFileLimit`, so they now +share one larger bound. The export still refuses to overwrite an existing file, +still marks any cut with a visible leading and trailing banner, and still reports +`truncated: true` and `status: partial`; nothing treats a partial export as +complete. + +## Checks + +Focused stage and server regressions cover a complete export above the old 2 MiB +cap but inside the new cap, a file above the new cap rejected as partial with the +verification diagnostic, repair accepting the larger complete file while the +original evidence stays unchanged, and the constant staying within the ordinary +artifact file bound. Focused stage/server suites and `go build ./...` plus +`go vet ./...` are run before landing; see the delivery report for exact results. diff --git a/docs/stage-artifacts.md b/docs/stage-artifacts.md index b29260d0..b2da6462 100644 --- a/docs/stage-artifacts.md +++ b/docs/stage-artifacts.md @@ -97,10 +97,13 @@ no special casing. `opencode session export `. Both reuse the same invocation helper and session-ID/messages validation as the transcript readback. The file is the harness's real session, never a reconstruction. -- Bounds: the source read is capped at 8 MiB and the rendered file at 2 MiB. When - either is cut, the file carries a visible truncation banner near the start and - the end and the step records `truncated: true`; a truncated export is never - described as whole. +- Bounds: the source read is capped at 8 MiB and the rendered file at 8 MiB, + matching the ordinary per-artifact file bound. The rendered file can exceed + its source because html escaping and the readable projection keep native text + more than once, so the previous 2 MiB render cap cut complete sessions that + were well inside the source bound. When either bound is exceeded, the file + carries a visible truncation banner near the start and the end and the step + records `truncated: true`; a truncated export is never described as whole. - Evidence: the step records `session_export` (`session_id`, `backend`, `source`, `html`, `html_bytes`, `messages`, `truncated`, `diagnostic`), so `pipelines inspect RUN_ID --json` shows what was written without reading the diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index 06a6013a..c67de23b 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -249,9 +249,10 @@ landed. presented. A run recorded before the HTML-only change still lists `session.md` among its stored artifacts (dated evidence kept on disk, not deleted); every listing — app, TUI, web spike — hides it rather than showing it beside the html. -- The source read is capped at 8 MiB and the rendered file at 2 MiB; a cut source or - a cut rendered file carries a visible truncation banner at both ends and - `session_export.truncated: true`, and a truncated export is never called whole. +- The source read is capped at 8 MiB and the rendered file at 8 MiB, matching the + ordinary per-artifact file bound; a cut source or a cut rendered file carries a + visible truncation banner at both ends and `session_export.truncated: true`, and + a truncated export is never called whole. - The step records `session_export` (`session_id`, `backend`, `source`, the html file name, `html_bytes`, `messages`, `truncated`, `diagnostic`) in `inspect RUN_ID --json`. A record written before the change still carried diff --git a/internal/server/session_export_gate_test.go b/internal/server/session_export_gate_test.go index a32a0943..3c9519c4 100644 --- a/internal/server/session_export_gate_test.go +++ b/internal/server/session_export_gate_test.go @@ -136,6 +136,56 @@ func TestSessionExportGateRetryOnlyAndExactlyOnce(t *testing.T) { } } +// TestSessionExportGateAcceptsRepairAboveOldRenderCap keeps the handoff gate's +// versioned-repair verification on the same larger bound as normal export. +func TestSessionExportGateAcceptsRepairAboveOldRenderCap(t *testing.T) { + h, s, id, first, second := gateRunner(t, func(context.Context, stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("export offline") + }, false) + h.runner.wg.Wait() + ctx := context.Background() + if err := s.ConfirmRecoveredSession(ctx, pipeline.SessionOwner{RunID: id, ID: "ses_exact"}); err != nil { + t.Fatal(err) + } + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + if _, err := h.runner.repairSessionExport(ctx, id, 1); err != nil { + t.Fatal(err) + } + // The worker promotes a persisted complete repair before claiming a lease. + job, err := s.ClaimSessionExportJob(ctx, time.Now().Add(time.Second), time.Minute) + if err != nil { + t.Fatal(err) + } + if job != nil { + t.Fatalf("complete repair still claimed as a recovery job: %+v", job) + } + if err := h.runner.resumeExportGates(ctx); err != nil { + t.Fatal(err) + } + h.runner.wg.Wait() + d, _ := s.GetRun(ctx, id) + if first.Load() != 1 || second.Load() != 1 || d.Status != "succeeded" || len(d.Steps) != 2 { + t.Fatalf("large repair did not advance the gate: %+v (%d/%d)", d, first.Load(), second.Load()) + } +} + func TestSessionExportGateCleanupUnconfirmedDoesNotExportOrAdvance(t *testing.T) { var exports atomic.Int32 h, s, id, _, second := gateRunner(t, func(ctx context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { diff --git a/internal/server/session_export_repair_test.go b/internal/server/session_export_repair_test.go index 4c0d8252..c2aabf3a 100644 --- a/internal/server/session_export_repair_test.go +++ b/internal/server/session_export_repair_test.go @@ -111,6 +111,57 @@ func TestRuntimeSessionExportRepairPreservesOriginalAndUsesRecordedOwner(t *test } } +// TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap proves a versioned +// repair uses the same larger bound as a normal export while leaving the +// original recorded evidence untouched. +func TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap(t *testing.T) { + h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("initial export unavailable") + }) + if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil { + t.Fatal(err) + } + original, err := s.GetRun(context.Background(), id) + if err != nil { + t.Fatal(err) + } + before, _ := json.Marshal(original.Steps[0].SessionExport) + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + repaired, err := h.runner.repairSessionExport(context.Background(), id, 1) + if err != nil { + t.Fatal(err) + } + latest := repaired.Steps[0].SessionExportRepairs[0] + if latest.Status != "complete" || latest.HTMLBytes != size || latest.HTML == "" { + t.Fatalf("repair above the old cap was not complete: %+v", latest) + } + after, _ := json.Marshal(repaired.Steps[0].SessionExport) + if string(before) != string(after) { + t.Fatal("repair above the old cap overwrote original evidence") + } + info, err := os.Stat(filepath.Join(h.runner.artifactsRoot, "1", "stages", "01-"+repaired.Steps[0].Stage, latest.HTML)) + if err != nil || info.Size() != size { + t.Fatalf("repair file missing or resized: %v %+v", err, info) + } +} + func TestRuntimeRepairRejectsUnrecordedAndActiveVisits(t *testing.T) { h, _, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { return stage.SessionExportResult{}, errors.New("unavailable") diff --git a/internal/server/session_export_status_test.go b/internal/server/session_export_status_test.go index a1bae02a..10daae33 100644 --- a/internal/server/session_export_status_test.go +++ b/internal/server/session_export_status_test.go @@ -1,10 +1,13 @@ package server import ( - "git.a-wan.net/alan/pipelines/internal/protocol" "os" "path/filepath" + "strings" "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" ) func TestSessionExportCompleteness(t *testing.T) { @@ -56,3 +59,61 @@ func TestRuntimeSessionExportFileVerificationDoesNotClaimMissingEvidence(t *test }) } } + +func sizedSessionFile(t *testing.T, size int64) string { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "session.html") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + if err := f.Truncate(size); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + return dir +} + +// TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap pins the +// ordinary-session case the previous 2 MiB rendered bound cut. The file is +// larger than that old cap and inside the artifact-aligned bound, so normal +// export verification must keep it and classify the evidence complete. +func TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap(t *testing.T) { + size := int64(2<<20) + 4096 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "complete" || evidence.HTML != "session.html" || evidence.HTMLBytes != size || evidence.Diagnostic != "" { + t.Fatalf("complete export above the old cap was rejected: %+v", evidence) + } +} + +// TestRuntimeSessionExportVerificationRejectsAboveTheNewCap confirms the larger +// bound is still a hard bound: an oversized file is not presented as evidence. +func TestRuntimeSessionExportVerificationRejectsAboveTheNewCap(t *testing.T) { + size := int64(stage.SessionExportFileLimit) + 1 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "partial" || evidence.HTML != "" || evidence.HTMLBytes != 0 || !strings.Contains(evidence.Diagnostic, "bounded verification") { + t.Fatalf("oversized export was not rejected as partial: %+v", evidence) + } +} + +// TestSessionExportFileLimitStaysInsideArtifactBounds keeps the render cap +// principled: larger than the cap that cut ordinary sessions, and no larger +// than the ordinary per-artifact file bound that serves the file. +func TestSessionExportFileLimitStaysInsideArtifactBounds(t *testing.T) { + if stage.SessionExportFileLimit <= 2<<20 { + t.Fatalf("render cap %d did not grow beyond the old 2 MiB cutoff", stage.SessionExportFileLimit) + } + if stage.SessionExportFileLimit > maxArtifactFileBytes { + t.Fatalf("render cap %d exceeds the artifact file bound %d", stage.SessionExportFileLimit, maxArtifactFileBytes) + } +} diff --git a/internal/stage/session_export.go b/internal/stage/session_export.go index 583602dd..2c752c5c 100644 --- a/internal/stage/session_export.go +++ b/internal/stage/session_export.go @@ -20,7 +20,7 @@ import ( // artifacts directory as one html file so the existing artifact listing and // serving paths find it with no special casing. The source read is capped at // SessionExportSourceLimit and the rendered file at SessionExportFileLimit, so -// the export adds at most ~2 MiB per step, inside the artifact scan limits. +// the export stays inside the server's per-artifact file bound. const ( // SessionHTMLFile is the one session export a stage writes. SessionHTMLFile = "session.html" @@ -32,8 +32,15 @@ const ( // SessionExportSourceLimit is the native session read cap; it is the one // opencode.MaxSessionExport value, not a second copy. SessionExportSourceLimit = opencode.MaxSessionExport - SessionExportFileLimit = 2 << 20 - SessionExportTimeout = 10 * time.Second + // SessionExportFileLimit is the rendered file cap. Ordinary native sessions + // commonly render a little larger than their raw source because html escaping + // and the readable projection duplicate native text; the previous 2 MiB cap + // cut complete sessions that were well inside the source bound. This cap + // matches the server's per-artifact file bound (maxArtifactFileBytes in + // internal/server/artifacts.go), so a complete export remains listed and + // served while a genuinely oversized one is still visibly truncated. + SessionExportFileLimit = 8 << 20 + SessionExportTimeout = 10 * time.Second ) // SessionExportRequest names the stage session to export and the evidence the diff --git a/internal/stage/session_export_test.go b/internal/stage/session_export_test.go index 5db417fd..8cf2efe2 100644 --- a/internal/stage/session_export_test.go +++ b/internal/stage/session_export_test.go @@ -222,6 +222,38 @@ func TestExportSessionLargeHTTPExportWritesBoundedRealHTML(t *testing.T) { } } +// TestExportSessionCompletesAboveTheOldRenderedCap covers the ordinary case the +// previous 2 MiB render cap cut: a complete native session inside the 8 MiB +// source bound whose escaped html is larger than 2 MiB. +func TestExportSessionCompletesAboveTheOldRenderedCap(t *testing.T) { + const oldRenderCap = 2 << 20 + dir := t.TempDir() + line := "complete ordinary session line " + text := strings.Repeat(line, oldRenderCap/len(line)+1000) + body := `{"info":{"id":"ses_ok"},"messages":[{"info":{"id":"m1","role":"user"},"text":"` + text + `"}]}` + sessionCLI(t, "ses_ok", body) + result, err := ExportSession(context.Background(), sessionRequest(dir)) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, result.HTML)) + if err != nil { + t.Fatal(err) + } + if result.Truncated || result.Messages != 1 || result.HTMLBytes != int64(len(data)) { + t.Fatalf("complete export above the old cap was not recorded: %+v", result) + } + if len(data) <= oldRenderCap || len(data) > SessionExportFileLimit { + t.Fatalf("rendered size %d is not above the old cap and inside the new one", len(data)) + } + if strings.Contains(string(data), "TRUNCATED") { + t.Fatal("a complete export carried a truncation banner") + } + if !strings.Contains(string(data), "complete ordinary session line") { + t.Fatal("complete export lost its session text") + } +} + func TestExportSessionSourceTruncationIsLabelledNotWhole(t *testing.T) { session := opencode.ExportedSession{ ID: "ses_ok",